diff --git a/shared/backend/carriernodeclient/carriernodeclient.go b/shared/backend/carriernodeclient/carriernodeclient.go index 149ab26..3306a01 100644 --- a/shared/backend/carriernodeclient/carriernodeclient.go +++ b/shared/backend/carriernodeclient/carriernodeclient.go @@ -49,17 +49,77 @@ type Client struct { // with no restart needed. Callers typically wire this as a closure over // their own settings lookup, falling back to a static CARRIERNODE_URL // env var default when no setting has been saved yet. + // + // Set exactly one of BaseURL or BaseURLs (New/NewMulti do this for you). + // When BaseURLs is set it takes priority. BaseURL func(ctx context.Context) string + + // BaseURLs resolves every configured CarrierNode instance's base URL, in + // priority order, for a request - see NewMulti's doc comment for how the + // multiple candidates are actually used (union for discovery, first-match + // for reads, primary-only for writes). + BaseURLs func(ctx context.Context) []string } -// New returns a Client. baseURL is called fresh on every request (see -// Client.BaseURL's doc comment for why). +// New returns a Client backed by a single CarrierNode instance. baseURL is +// called fresh on every request (see Client.BaseURL's doc comment for why). func New(internalServiceSecret string, baseURL func(ctx context.Context) string) *Client { return &Client{InternalServiceSecret: internalServiceSecret, BaseURL: baseURL} } -func (c *Client) newRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { - request, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(c.BaseURL(ctx), "/")+path, body) +// NewMulti returns a Client backed by every CarrierNode instance configured +// in ProjectConfigurator (its Projects workspace supports registering more +// than one CarrierNode instance - separate storage backends, HA/failover +// replicas of the same storage, or a mix of both). baseURLs is called fresh +// on every request and should return them in priority order (the first +// non-empty entry is treated as the primary instance). +// +// The candidates are used differently depending on the operation: +// - ListFiles (discovery) queries every instance and merges the results, +// so files living on distinct storage backends are all found. +// - Read operations tied to one file (Probe, FetchToScratch, ProbeMedia) +// try each instance in order and use the first one that actually has the +// file, so a replica standing in for a downed primary (or a file that +// simply lives on a non-primary storage backend) is still found. +// - Writes/streaming that don't originate from a discovered file +// (Proxy, PushThumbnail, DeleteThumbnail, PushOutput, PushInput, +// PushCopy, UploadDownload, StoreDownload) always target the primary +// instance (the first candidate), matching single-instance behavior. +func NewMulti(internalServiceSecret string, baseURLs func(ctx context.Context) []string) *Client { + return &Client{InternalServiceSecret: internalServiceSecret, BaseURLs: baseURLs} +} + +// candidateBaseURLs returns every configured CarrierNode base URL in +// priority order, trimmed and with blanks dropped. A single-instance Client +// (BaseURLs unset) always returns exactly one (possibly empty) entry. +func (c *Client) candidateBaseURLs(ctx context.Context) []string { + if c.BaseURLs != nil { + var cleaned []string + for _, candidate := range c.BaseURLs(ctx) { + if candidate = strings.TrimSpace(candidate); candidate != "" { + cleaned = append(cleaned, candidate) + } + } + return cleaned + } + base := "" + if c.BaseURL != nil { + base = c.BaseURL(ctx) + } + return []string{base} +} + +// primaryBaseURL is the instance every write/streaming operation targets - +// see NewMulti's doc comment. +func (c *Client) primaryBaseURL(ctx context.Context) string { + if candidates := c.candidateBaseURLs(ctx); len(candidates) > 0 { + return candidates[0] + } + return "" +} + +func (c *Client) newRequest(ctx context.Context, baseURL, method, path string, body io.Reader) (*http.Request, error) { + request, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(baseURL, "/")+path, body) if err != nil { return nil, err } @@ -72,8 +132,9 @@ func (c *Client) newRequest(ctx context.Context, method, path string, body io.Re // Proxy streams a CarrierNode response straight through to the original // client, preserving range/conditional-request semantics so video scrubbing // keeps working without reimplementing http.ServeContent on this side. +// Always targets the primary instance - see NewMulti's doc comment. func (c *Client) Proxy(w http.ResponseWriter, r *http.Request, carrierNodePath string) { - request, err := c.newRequest(r.Context(), r.Method, carrierNodePath, nil) + request, err := c.newRequest(r.Context(), c.primaryBaseURL(r.Context()), r.Method, carrierNodePath, nil) if err != nil { writeError(w, http.StatusBadGateway, "media service unavailable") return @@ -100,11 +161,9 @@ func (c *Client) Proxy(w http.ResponseWriter, r *http.Request, carrierNodePath s } } -// Probe checks whether a CarrierNode-served path exists without fetching its -// bytes. A 404 is reported as exists=false with a nil error, not a failure - -// only transport/5xx problems are surfaced as errors. -func (c *Client) Probe(ctx context.Context, carrierNodePath string) (exists bool, size int64, modTime time.Time, err error) { - request, err := c.newRequest(ctx, http.MethodHead, carrierNodePath, nil) +// probeOne runs Probe's HEAD request against a single base URL. +func (c *Client) probeOne(ctx context.Context, baseURL, carrierNodePath string) (exists bool, size int64, modTime time.Time, err error) { + request, err := c.newRequest(ctx, baseURL, http.MethodHead, carrierNodePath, nil) if err != nil { return false, 0, time.Time{}, err } @@ -124,12 +183,30 @@ func (c *Client) Probe(ctx context.Context, carrierNodePath string) (exists bool return true, size, modTime, nil } -// FetchToScratch downloads a CarrierNode-served path into an ephemeral temp -// file for local processing (ffmpeg/ffprobe/yt-dlp all need a real file -// handle). Callers must invoke the returned cleanup once done; it removes -// the scratch file unconditionally. -func (c *Client) FetchToScratch(ctx context.Context, carrierNodePath, suffix string) (path string, cleanup func(), err error) { - request, err := c.newRequest(ctx, http.MethodGet, carrierNodePath, nil) +// Probe checks whether a CarrierNode-served path exists without fetching its +// bytes. Every configured instance is tried in order; the first one +// reporting the file exists wins. A path missing from every instance is +// reported as exists=false with a nil error, not a failure - only a +// transport/5xx problem on every instance is surfaced as an error. +func (c *Client) Probe(ctx context.Context, carrierNodePath string) (exists bool, size int64, modTime time.Time, err error) { + var lastErr error + for _, baseURL := range c.candidateBaseURLs(ctx) { + found, foundSize, foundModTime, probeErr := c.probeOne(ctx, baseURL, carrierNodePath) + if probeErr != nil { + lastErr = probeErr + continue + } + if found { + return true, foundSize, foundModTime, nil + } + lastErr = nil // a clean 404 from a reachable instance is a real answer, not a failure + } + return false, 0, time.Time{}, lastErr +} + +// fetchOne runs FetchToScratch's GET request against a single base URL. +func (c *Client) fetchOne(ctx context.Context, baseURL, carrierNodePath, suffix string) (path string, cleanup func(), err error) { + request, err := c.newRequest(ctx, baseURL, http.MethodGet, carrierNodePath, nil) if err != nil { return "", nil, err } @@ -158,15 +235,33 @@ func (c *Client) FetchToScratch(ctx context.Context, carrierNodePath, suffix str return scratch.Name(), cleanup, nil } +// FetchToScratch downloads a CarrierNode-served path into an ephemeral temp +// file for local processing (ffmpeg/ffprobe/yt-dlp all need a real file +// handle). Callers must invoke the returned cleanup once done; it removes +// the scratch file unconditionally. Every configured instance is tried in +// order; the first one that actually serves the file wins. +func (c *Client) FetchToScratch(ctx context.Context, carrierNodePath, suffix string) (path string, cleanup func(), err error) { + var lastErr error + for _, baseURL := range c.candidateBaseURLs(ctx) { + scratchPath, scratchCleanup, fetchErr := c.fetchOne(ctx, baseURL, carrierNodePath, suffix) + if fetchErr != nil { + lastErr = fetchErr + continue + } + return scratchPath, scratchCleanup, nil + } + return "", nil, lastErr +} + // push streams a local file as the request body without buffering it in -// memory. +// memory. Always targets the primary instance - see NewMulti's doc comment. func (c *Client) push(ctx context.Context, method, carrierNodePath, localPath string) (*http.Response, error) { file, err := os.Open(localPath) if err != nil { return nil, err } defer file.Close() - request, err := c.newRequest(ctx, method, carrierNodePath, file) + request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), method, carrierNodePath, file) if err != nil { return nil, err } @@ -204,9 +299,9 @@ func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64 } // DeleteThumbnail removes a thumbnail from CarrierNode. A 404 is treated as -// already-deleted, not an error. +// already-deleted, not an error. Always targets the primary instance. func (c *Client) DeleteThumbnail(ctx context.Context, id string) error { - request, err := c.newRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil) + request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil) if err != nil { return err } @@ -264,13 +359,14 @@ func (c *Client) UploadDownload(ctx context.Context, localPath, filename string) } // StoreDownload catalogs an already-uploaded file into CarrierNode's -// media/downloaded_media tables via its /api/store endpoint. +// media/downloaded_media tables via its /api/store endpoint. Always targets +// the primary instance. func (c *Client) StoreDownload(ctx context.Context, filePath, sourceURL, tool, status string) (map[string]any, error) { body, err := json.Marshal(map[string]any{"filePath": filePath, "sourceUrl": sourceURL, "tool": tool, "status": status}) if err != nil { return nil, err } - request, err := c.newRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body)) + request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodPost, "/api/store", bytes.NewReader(body)) if err != nil { return nil, err } @@ -298,10 +394,7 @@ type FileEntry struct { Mtime int64 `json:"mtime"` } -// ListFiles lists files under CarrierNode's MediaRoots via its /api/files -// (recent=false) or /api/files/recent (recent=true) endpoints - the -// replacement for a local filepath.WalkDir over MediaRoots. -func (c *Client) ListFiles(ctx context.Context, relative string, recent bool, limit int) ([]FileEntry, error) { +func (c *Client) listFilesOne(ctx context.Context, baseURL, relative string, recent bool, limit int) ([]FileEntry, error) { endpoint := "/api/files" if recent { endpoint = "/api/files/recent" @@ -316,7 +409,7 @@ func (c *Client) ListFiles(ctx context.Context, relative string, recent bool, li if encoded := query.Encode(); encoded != "" { endpoint += "?" + encoded } - request, err := c.newRequest(ctx, http.MethodGet, endpoint, nil) + request, err := c.newRequest(ctx, baseURL, http.MethodGet, endpoint, nil) if err != nil { return nil, err } @@ -337,6 +430,34 @@ func (c *Client) ListFiles(ctx context.Context, relative string, recent bool, li return payload.Files, nil } +// ListFiles lists files under every configured CarrierNode instance's +// MediaRoots via its /api/files (recent=false) or /api/files/recent +// (recent=true) endpoints - the replacement for a local filepath.WalkDir +// over MediaRoots. With more than one instance configured, every reachable +// one is queried and the results are merged (each instance is a distinct +// storage backend, or a failover replica reporting the same files as its +// peers - either way, merging is correct); an unreachable instance is +// skipped rather than failing the whole listing, unless none of them +// answered at all. +func (c *Client) ListFiles(ctx context.Context, relative string, recent bool, limit int) ([]FileEntry, error) { + var files []FileEntry + var lastErr error + reachable := false + for _, baseURL := range c.candidateBaseURLs(ctx) { + found, err := c.listFilesOne(ctx, baseURL, relative, recent, limit) + if err != nil { + lastErr = err + continue + } + reachable = true + files = append(files, found...) + } + if !reachable && lastErr != nil { + return nil, lastErr + } + return files, nil +} + // ProbeResult is the ffprobe-derived metadata CarrierNode's /api/probe // endpoint reports for a media file. type ProbeResult struct { @@ -345,13 +466,10 @@ type ProbeResult struct { Height int `json:"height"` } -// ProbeMedia runs ffprobe on CarrierNode against a MediaRoots-relative path -// and returns just the metadata fields - bytes never leave CarrierNode, -// unlike every other method on Client. -func (c *Client) ProbeMedia(ctx context.Context, relative string) (ProbeResult, error) { +func (c *Client) probeMediaOne(ctx context.Context, baseURL, relative string) (ProbeResult, error) { query := url.Values{} query.Set("path", relative) - request, err := c.newRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil) + request, err := c.newRequest(ctx, baseURL, http.MethodGet, "/api/probe?"+query.Encode(), nil) if err != nil { return ProbeResult{}, err } @@ -370,6 +488,23 @@ func (c *Client) ProbeMedia(ctx context.Context, relative string) (ProbeResult, return result, nil } +// ProbeMedia runs ffprobe on CarrierNode against a MediaRoots-relative path +// and returns just the metadata fields - bytes never leave CarrierNode, +// unlike every other method on Client. Every configured instance is tried in +// order; the first one that actually has the file wins. +func (c *Client) ProbeMedia(ctx context.Context, relative string) (ProbeResult, error) { + var lastErr error + for _, baseURL := range c.candidateBaseURLs(ctx) { + result, err := c.probeMediaOne(ctx, baseURL, relative) + if err != nil { + lastErr = err + continue + } + return result, nil + } + return ProbeResult{}, lastErr +} + func writeJSON(w http.ResponseWriter, status int, value any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(status) diff --git a/shared/backend/carriernodeclient/carriernodeclient_test.go b/shared/backend/carriernodeclient/carriernodeclient_test.go new file mode 100644 index 0000000..0d3150b --- /dev/null +++ b/shared/backend/carriernodeclient/carriernodeclient_test.go @@ -0,0 +1,133 @@ +package carriernodeclient + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +func TestListFilesMergesAcrossInstances(t *testing.T) { + first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`)) + })) + defer first.Close() + second := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"files":[{"rel":"b.mp4"}]}`)) + })) + defer second.Close() + + client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} }) + + files, err := client.ListFiles(context.Background(), "", false, 0) + if err != nil { + t.Fatalf("ListFiles error: %v", err) + } + if len(files) != 2 { + t.Fatalf("ListFiles returned %d files, want 2: %+v", len(files), files) + } +} + +func TestListFilesSkipsUnreachableInstance(t *testing.T) { + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`)) + })) + defer up.Close() + down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + down.Close() // closed immediately so requests to it fail outright + + client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL, up.URL} }) + + files, err := client.ListFiles(context.Background(), "", false, 0) + if err != nil { + t.Fatalf("ListFiles error: %v", err) + } + if len(files) != 1 || files[0].Rel != "a.mp4" { + t.Fatalf("ListFiles = %+v, want just the reachable instance's file", files) + } +} + +func TestListFilesErrorsWhenNoInstanceReachable(t *testing.T) { + down := httptest.NewServer(nil) + down.Close() + + client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL} }) + + if _, err := client.ListFiles(context.Background(), "", false, 0); err == nil { + t.Fatal("ListFiles error = nil, want an error when every instance is unreachable") + } +} + +func TestProbeFallsBackToNextInstance(t *testing.T) { + notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + })) + defer notFound.Close() + found := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "42") + w.WriteHeader(http.StatusOK) + })) + defer found.Close() + + client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, found.URL} }) + + exists, size, _, err := client.Probe(context.Background(), "/media/a.mp4") + if err != nil { + t.Fatalf("Probe error: %v", err) + } + if !exists { + t.Fatal("Probe exists = false, want true (second instance has it)") + } + if size != 42 { + t.Fatalf("Probe size = %d, want 42", size) + } +} + +func TestProbeExistsFalseWhenNoInstanceHasFile(t *testing.T) { + notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + })) + defer notFound.Close() + + client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} }) + + exists, _, _, err := client.Probe(context.Background(), "/media/missing.mp4") + if err != nil { + t.Fatalf("Probe error: %v", err) + } + if exists { + t.Fatal("Probe exists = true, want false") + } +} + +func TestProxyAlwaysTargetsPrimaryInstance(t *testing.T) { + var primaryHit, secondaryHit bool + primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + primaryHit = true + w.WriteHeader(http.StatusOK) + })) + defer primary.Close() + secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + secondaryHit = true + w.WriteHeader(http.StatusOK) + })) + defer secondary.Close() + + client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} }) + + req := httptest.NewRequest(http.MethodGet, "/thumbnails/x.jpg", nil) + rec := httptest.NewRecorder() + client.Proxy(rec, req, "/thumbnails/x.jpg") + + if !primaryHit { + t.Fatal("Proxy did not hit the primary instance") + } + if secondaryHit { + t.Fatal("Proxy hit the secondary instance, want primary-only") + } +} diff --git a/shared/backend/coreconfig/coreconfig.go b/shared/backend/coreconfig/coreconfig.go index 8fc9c84..e85e8d5 100644 --- a/shared/backend/coreconfig/coreconfig.go +++ b/shared/backend/coreconfig/coreconfig.go @@ -1,7 +1,7 @@ // Package coreconfig lets any service in this workspace receive AuthGuard's and CarrierNode's -// current base URLs pushed from ProjectConfigurator, instead of each service hardcoding them in +// current base URL(s) pushed from ProjectConfigurator, instead of each service hardcoding them in // its own env vars. ProjectConfigurator's Projects workspace is the operator-facing source of -// truth for both (its authguard_url/carriernode_url settings); it pushes a fresh copy to every +// truth for both (its authguard_url/carriernode_url(_N) settings); it pushes a fresh copy to every // project it has registered whenever either changes, and again on a periodic tick, so a service // that restarted (and lost its in-memory copy) converges again within a couple of minutes with no // manual step. See ProjectConfigurator/README.md's "Pushing core service info to other projects" @@ -16,10 +16,20 @@ import ( "sync" ) -// Info is AuthGuard's and CarrierNode's current base URL, as pushed by ProjectConfigurator. +// Info is AuthGuard's and CarrierNode's current base URL(s), as pushed by ProjectConfigurator. type Info struct { - AuthGuardURL string `json:"authGuardUrl"` + AuthGuardURL string `json:"authGuardUrl"` + + // CarrierNodeURL is the primary CarrierNode instance's URL (CarrierNodeURLs[0], if any) - kept + // for the services that only ever talk to one CarrierNode instance via + // carriernodeclient.New(secret, store.CarrierNodeURL). CarrierNodeURL string `json:"carrierNodeUrl"` + + // CarrierNodeURLs is every CarrierNode instance ProjectConfigurator has registered, in + // priority order (the first entry is the same as CarrierNodeURL) - services that want to + // discover files across every configured storage backend / fail over between replicas wire + // this through carriernodeclient.NewMulti(secret, store.CarrierNodeURLs) instead. + CarrierNodeURLs []string `json:"carrierNodeUrls"` } // Store holds the most recently pushed Info, defaulting to whatever fallback NewStore was given @@ -34,7 +44,7 @@ type Store struct { // NewStore returns a Store seeded with fallback. func NewStore(fallback Info) *Store { - return &Store{info: fallback} + return &Store{info: normalizeInfo(fallback)} } // Get returns the current Info. @@ -49,10 +59,16 @@ func (s *Store) Get() Info { func (s *Store) AuthGuardURL() string { return s.Get().AuthGuardURL } // CarrierNodeURL is a convenience accessor for Get().CarrierNodeURL - the natural closure to wire -// as a carriernodeclient.Client's BaseURL: carriernodeclient.New(secret, func(ctx +// as a single-instance carriernodeclient.Client's BaseURL: carriernodeclient.New(secret, func(ctx // context.Context) string { return store.CarrierNodeURL() }). func (s *Store) CarrierNodeURL() string { return s.Get().CarrierNodeURL } +// CarrierNodeURLs is a convenience accessor for Get().CarrierNodeURLs - the natural closure to +// wire as a multi-instance carriernodeclient.Client's BaseURLs: +// carriernodeclient.NewMulti(secret, func(ctx context.Context) []string { return +// store.CarrierNodeURLs() }). +func (s *Store) CarrierNodeURLs() []string { return s.Get().CarrierNodeURLs } + // OnUpdate registers fn to be called (synchronously, so keep it fast) with the new Info after // every Set - e.g. client.SetBaseURL for an authclient.Client that isn't already reading through // Store on every call. Only one callback is kept; a second registration replaces the first, which @@ -63,15 +79,17 @@ func (s *Store) OnUpdate(fn func(Info)) { s.mu.Unlock() } -// Set replaces the current Info, field by field, ignoring a blank field so a partial push (e.g. -// only carrierNodeUrl changed) never clobbers the other value with an empty string. +// Set replaces the current Info, field by field, ignoring a blank/empty field so a partial push +// (e.g. only carrierNodeUrl(s) changed) never clobbers the other value. func (s *Store) Set(next Info) { + next = normalizeInfo(next) s.mu.Lock() if url := strings.TrimSpace(next.AuthGuardURL); url != "" { s.info.AuthGuardURL = url } - if url := strings.TrimSpace(next.CarrierNodeURL); url != "" { - s.info.CarrierNodeURL = url + if len(next.CarrierNodeURLs) > 0 { + s.info.CarrierNodeURLs = next.CarrierNodeURLs + s.info.CarrierNodeURL = next.CarrierNodeURLs[0] } current := s.info callback := s.onUpdate @@ -81,6 +99,30 @@ func (s *Store) Set(next Info) { } } +// normalizeInfo trims/drops blank CarrierNodeURLs entries and fills in CarrierNodeURLs from a +// lone legacy CarrierNodeURL (or vice versa), so every caller - old pushes that only ever set +// CarrierNodeURL, and new ones that set CarrierNodeURLs - sees both fields populated consistently. +func normalizeInfo(info Info) Info { + var cleaned []string + for _, url := range info.CarrierNodeURLs { + if url = strings.TrimSpace(url); url != "" { + cleaned = append(cleaned, url) + } + } + if len(cleaned) == 0 { + if url := strings.TrimSpace(info.CarrierNodeURL); url != "" { + cleaned = []string{url} + } + } + info.CarrierNodeURLs = cleaned + if len(cleaned) > 0 { + info.CarrierNodeURL = cleaned[0] + } else { + info.CarrierNodeURL = "" + } + return info +} + // Handler is the X-Internal-Auth-gated PUT /api/core-services/internal endpoint // ProjectConfigurator calls to push a fresh Info: mount it at that path (see // ProjectConfigurator/README.md) behind a secret check for this service's own diff --git a/shared/backend/coreconfig/coreconfig_test.go b/shared/backend/coreconfig/coreconfig_test.go index fcc0f00..4744294 100644 --- a/shared/backend/coreconfig/coreconfig_test.go +++ b/shared/backend/coreconfig/coreconfig_test.go @@ -63,6 +63,44 @@ func TestHandlerRejectsMissingOrWrongSecret(t *testing.T) { } } +func TestStoreSetPopulatesCarrierNodeURLsFromLegacyField(t *testing.T) { + store := NewStore(Info{}) + + store.Set(Info{CarrierNodeURL: "http://carrier.example.com"}) + + got := store.Get() + if want := []string{"http://carrier.example.com"}; !equalStrings(got.CarrierNodeURLs, want) { + t.Fatalf("CarrierNodeURLs = %v, want %v", got.CarrierNodeURLs, want) + } +} + +func TestStoreSetCarrierNodeURLsAlsoUpdatesPrimary(t *testing.T) { + store := NewStore(Info{}) + + store.Set(Info{CarrierNodeURLs: []string{"http://primary.example.com", "http://replica.example.com"}}) + + got := store.Get() + if got.CarrierNodeURL != "http://primary.example.com" { + t.Fatalf("CarrierNodeURL = %q, want first CarrierNodeURLs entry", got.CarrierNodeURL) + } + want := []string{"http://primary.example.com", "http://replica.example.com"} + if !equalStrings(got.CarrierNodeURLs, want) { + t.Fatalf("CarrierNodeURLs = %v, want %v", got.CarrierNodeURLs, want) + } +} + +func equalStrings(got, want []string) bool { + if len(got) != len(want) { + return false + } + for i := range got { + if got[i] != want[i] { + return false + } + } + return true +} + func TestHandlerAppliesPushedInfo(t *testing.T) { store := NewStore(Info{}) handler := Handler("s3cret", store) diff --git a/shared/backend/mediacore/mediacore.go b/shared/backend/mediacore/mediacore.go index e235bb9..2bbb8f7 100644 --- a/shared/backend/mediacore/mediacore.go +++ b/shared/backend/mediacore/mediacore.go @@ -37,6 +37,7 @@ import ( "net/url" "os" "path/filepath" + "regexp" "strconv" "strings" "time" @@ -796,6 +797,49 @@ func SaveSetting(ctx context.Context, db *pgxpool.Pool, key, value string) error return err } +// carrierNodeInstancePattern matches a registered project key naming a CarrierNode instance: the +// base "carriernode" itself, or a numbered peer like "carriernode_2" - see +// ProjectConfigurator/backend/cmd/projectconfigurator/settings.go's identical pattern (kept in +// sync manually since one is the sender's copy and this is the direct-DB-read receiver's copy of +// the same convention, not literally shared code). +var carrierNodeInstancePattern = regexp.MustCompile(`^carriernode(_\d+)?$`) + +// CarrierNodeURLs returns every CarrierNode instance registered in ProjectConfigurator's Projects +// workspace ("carriernode_url", "carriernode_2_url", ...), read directly from the shared +// `settings` table in registration order, dropping any instance with no URL set. This is for the +// 7 MEDIA_SERVICE instances that share this database directly instead of going through +// ProjectConfigurator's coreconfig push (see ProjectConfigurator/README.md's "Pushing core service +// info to other projects" section) - wire it as a carriernodeclient.Client's BaseURLs: +// +// carriernodeclient.NewMulti(secret, func(ctx context.Context) []string { +// return mediacore.CarrierNodeURLs(ctx, db, fallback) +// }) +// +// Returns fallback if no carriernode* instance is registered (or none has a URL) yet. +func CarrierNodeURLs(ctx context.Context, db *pgxpool.Pool, fallback []string) []string { + var registered []string + _ = json.Unmarshal([]byte(SettingValue(ctx, db, "configured_central", "")), ®istered) + var urls []string + for _, project := range registered { + key := strings.ToLower(strings.TrimSpace(project)) + if !carrierNodeInstancePattern.MatchString(key) { + continue + } + if url := strings.TrimSpace(SettingValue(ctx, db, key+"_url", "")); url != "" { + urls = append(urls, url) + } + } + if len(urls) == 0 { + if url := strings.TrimSpace(SettingValue(ctx, db, "carriernode_url", "")); url != "" { + urls = []string{url} + } + } + if len(urls) == 0 { + return fallback + } + return urls +} + // --- path-safety helpers (generic, no Core dependency) --- // SafeRelative reports whether value is a relative path with no `..`