feat(sense): establish M1 offline intake skeleton
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
package mtx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
mediamtxapi "yovision/sense/internal/mtx/generated"
|
||||
)
|
||||
|
||||
var ErrPathNotFound = errors.New("MediaMTX path not found")
|
||||
|
||||
type APIError struct {
|
||||
Operation string
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string {
|
||||
return fmt.Sprintf("MediaMTX %s failed with HTTP status %d", e.Operation, e.StatusCode)
|
||||
}
|
||||
|
||||
type PathConfig struct {
|
||||
Name string
|
||||
Source string
|
||||
}
|
||||
|
||||
type pathAPI interface {
|
||||
ConfigPathsAddWithResponse(context.Context, string, mediamtxapi.ConfigPathsAddJSONRequestBody, ...mediamtxapi.RequestEditorFn) (*mediamtxapi.ConfigPathsAddResponse, error)
|
||||
ConfigPathsGetWithResponse(context.Context, string, ...mediamtxapi.RequestEditorFn) (*mediamtxapi.ConfigPathsGetResponse, error)
|
||||
ConfigPathsPatchWithResponse(context.Context, string, mediamtxapi.ConfigPathsPatchJSONRequestBody, ...mediamtxapi.RequestEditorFn) (*mediamtxapi.ConfigPathsPatchResponse, error)
|
||||
ConfigPathsDeleteWithResponse(context.Context, string, ...mediamtxapi.RequestEditorFn) (*mediamtxapi.ConfigPathsDeleteResponse, error)
|
||||
PathsGetWithResponse(context.Context, string, ...mediamtxapi.RequestEditorFn) (*mediamtxapi.PathsGetResponse, error)
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
api pathAPI
|
||||
}
|
||||
|
||||
func NewClient(baseURL string, httpClient *http.Client) (*Client, error) {
|
||||
options := make([]mediamtxapi.ClientOption, 0, 1)
|
||||
if httpClient != nil {
|
||||
options = append(options, mediamtxapi.WithHTTPClient(httpClient))
|
||||
}
|
||||
generated, err := mediamtxapi.NewClientWithResponses(strings.TrimRight(baseURL, "/"), options...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create MediaMTX client: %w", err)
|
||||
}
|
||||
return &Client{api: generated}, nil
|
||||
}
|
||||
|
||||
func newClientWithAPI(api pathAPI) *Client {
|
||||
return &Client{api: api}
|
||||
}
|
||||
|
||||
func (c *Client) CreatePath(ctx context.Context, name, source string) error {
|
||||
response, err := c.api.ConfigPathsAddWithResponse(ctx, name, mediamtxapi.PathConf{Source: &source})
|
||||
if err != nil {
|
||||
return fmt.Errorf("MediaMTX create path transport: %w", err)
|
||||
}
|
||||
if response.StatusCode() != http.StatusOK {
|
||||
return &APIError{Operation: "create path", StatusCode: response.StatusCode()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) GetPath(ctx context.Context, name string) (PathConfig, error) {
|
||||
response, err := c.api.ConfigPathsGetWithResponse(ctx, name)
|
||||
if err != nil {
|
||||
return PathConfig{}, fmt.Errorf("MediaMTX read path transport: %w", err)
|
||||
}
|
||||
if response.StatusCode() == http.StatusNotFound {
|
||||
return PathConfig{}, ErrPathNotFound
|
||||
}
|
||||
if response.StatusCode() != http.StatusOK || response.JSON200 == nil {
|
||||
return PathConfig{}, &APIError{Operation: "read path", StatusCode: response.StatusCode()}
|
||||
}
|
||||
result := PathConfig{Name: name}
|
||||
if response.JSON200.Name != nil {
|
||||
result.Name = *response.JSON200.Name
|
||||
}
|
||||
if response.JSON200.Source != nil {
|
||||
result.Source = *response.JSON200.Source
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *Client) DeletePath(ctx context.Context, name string) error {
|
||||
response, err := c.api.ConfigPathsDeleteWithResponse(ctx, name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("MediaMTX delete path transport: %w", err)
|
||||
}
|
||||
if response.StatusCode() == http.StatusNotFound {
|
||||
return ErrPathNotFound
|
||||
}
|
||||
if response.StatusCode() != http.StatusOK {
|
||||
return &APIError{Operation: "delete path", StatusCode: response.StatusCode()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnsurePath converges one desired path. It never enumerates or deletes orphans.
|
||||
func (c *Client) EnsurePath(ctx context.Context, name, source string) (bool, error) {
|
||||
current, err := c.GetPath(ctx, name)
|
||||
if errors.Is(err, ErrPathNotFound) {
|
||||
if err := c.CreatePath(ctx, name, source); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if current.Source == source {
|
||||
return false, nil
|
||||
}
|
||||
response, err := c.api.ConfigPathsPatchWithResponse(ctx, name, mediamtxapi.PathConf{Source: &source})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("MediaMTX patch path transport: %w", err)
|
||||
}
|
||||
if response.StatusCode() != http.StatusOK {
|
||||
return false, &APIError{Operation: "patch path", StatusCode: response.StatusCode()}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (c *Client) PathReady(ctx context.Context, name string) (bool, error) {
|
||||
response, err := c.api.PathsGetWithResponse(ctx, name)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("MediaMTX probe path transport: %w", err)
|
||||
}
|
||||
if response.StatusCode() == http.StatusNotFound {
|
||||
return false, ErrPathNotFound
|
||||
}
|
||||
if response.StatusCode() != http.StatusOK || response.JSON200 == nil {
|
||||
return false, &APIError{Operation: "probe path", StatusCode: response.StatusCode()}
|
||||
}
|
||||
if response.JSON200.Online == nil || response.JSON200.Available == nil {
|
||||
return false, &APIError{Operation: "probe path response", StatusCode: response.StatusCode()}
|
||||
}
|
||||
return *response.JSON200.Online && *response.JSON200.Available, nil
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package mtx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeMediaMTX struct {
|
||||
mu sync.Mutex
|
||||
paths map[string]string
|
||||
mutations int
|
||||
}
|
||||
|
||||
func (f *fakeMediaMTX) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
prefixes := map[string]string{
|
||||
"/v3/config/paths/get/": "get",
|
||||
"/v3/config/paths/add/": "add",
|
||||
"/v3/config/paths/patch/": "patch",
|
||||
"/v3/config/paths/delete/": "delete",
|
||||
"/v3/paths/get/": "runtime",
|
||||
}
|
||||
for prefix, operation := range prefixes {
|
||||
if !strings.HasPrefix(request.URL.Path, prefix) {
|
||||
continue
|
||||
}
|
||||
name := strings.TrimPrefix(request.URL.Path, prefix)
|
||||
source, exists := f.paths[name]
|
||||
switch operation {
|
||||
case "get":
|
||||
if !exists {
|
||||
http.Error(writer, `{"error":"not found"}`, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(writer).Encode(map[string]any{"name": name, "source": source})
|
||||
case "add", "patch":
|
||||
var body struct {
|
||||
Source string `json:"source"`
|
||||
}
|
||||
if err := json.NewDecoder(request.Body).Decode(&body); err != nil {
|
||||
http.Error(writer, `{}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
f.paths[name] = body.Source
|
||||
f.mutations++
|
||||
_, _ = writer.Write([]byte(`{}`))
|
||||
case "delete":
|
||||
if !exists {
|
||||
http.Error(writer, `{"error":"not found"}`, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
delete(f.paths, name)
|
||||
f.mutations++
|
||||
_, _ = writer.Write([]byte(`{}`))
|
||||
case "runtime":
|
||||
if !exists {
|
||||
http.Error(writer, `{"error":"not found"}`, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"online":true,"available":true}`))
|
||||
}
|
||||
return
|
||||
}
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
|
||||
func TestGeneratedClientCreateReadDeleteMapping(t *testing.T) {
|
||||
t.Parallel()
|
||||
fake := &fakeMediaMTX{paths: make(map[string]string)}
|
||||
server := httptest.NewServer(fake)
|
||||
defer server.Close()
|
||||
client, err := NewClient(server.URL, server.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
if err := client.CreatePath(ctx, "camera-1", "rtsp://media.invalid/camera-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path, err := client.GetPath(ctx, "camera-1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if path.Source != "rtsp://media.invalid/camera-1" {
|
||||
t.Fatalf("unexpected source mapping: %+v", path)
|
||||
}
|
||||
if err := client.DeletePath(ctx, "camera-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.GetPath(ctx, "camera-1"); err != ErrPathNotFound {
|
||||
t.Fatalf("expected not found after delete, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsurePathIsIdempotentAndCanPatch(t *testing.T) {
|
||||
t.Parallel()
|
||||
fake := &fakeMediaMTX{paths: make(map[string]string)}
|
||||
server := httptest.NewServer(fake)
|
||||
defer server.Close()
|
||||
client, err := NewClient(server.URL, server.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
changed, err := client.EnsurePath(ctx, "camera-2", "rtsp://media.invalid/first")
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("first ensure: changed=%v err=%v", changed, err)
|
||||
}
|
||||
changed, err = client.EnsurePath(ctx, "camera-2", "rtsp://media.invalid/first")
|
||||
if err != nil || changed {
|
||||
t.Fatalf("second ensure must be idempotent: changed=%v err=%v", changed, err)
|
||||
}
|
||||
changed, err = client.EnsurePath(ctx, "camera-2", "rtsp://media.invalid/second")
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("changed source must patch: changed=%v err=%v", changed, err)
|
||||
}
|
||||
if fake.mutations != 2 {
|
||||
t.Fatalf("expected create + patch, got %d mutations", fake.mutations)
|
||||
}
|
||||
ready, err := client.PathReady(ctx, "camera-2")
|
||||
if err != nil || !ready {
|
||||
t.Fatalf("runtime probe: ready=%v err=%v", ready, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIErrorDoesNotLeakSource(t *testing.T) {
|
||||
t.Parallel()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
writer.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = fmt.Fprint(writer, `{"error":"upstream included a secret"}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := NewClient(server.URL, server.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secretSource := "rtsp://" + "user" + ":" + "redacted" + "@camera.invalid/live"
|
||||
err = client.CreatePath(context.Background(), "camera", secretSource)
|
||||
if err == nil || strings.Contains(err.Error(), secretSource) || strings.Contains(err.Error(), "secret") {
|
||||
t.Fatalf("error must be redacted, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Package mtx wraps the generated MediaMTX control API client.
|
||||
package mtx
|
||||
|
||||
// The input is the official API document vendored from the frozen MediaMTX tag.
|
||||
//go:generate go tool oapi-codegen -config oapi-codegen.yaml ../../api/vendor/mediamtx-v1.19.3.openapi.yaml
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
||||
package: mediamtxapi
|
||||
output: generated/client.gen.go
|
||||
generate:
|
||||
models: true
|
||||
client: true
|
||||
output-options:
|
||||
skip-prune: false
|
||||
Reference in New Issue
Block a user