Sync shared snapshot from 9f78995
Docker / Docker Build & Push (push) Successful in 3m45s

This commit is contained in:
Gabriel20xx committed 2026-09-11 11:38:44 +02:00
1 parent df94fc6d8b
commit a2a96f6a46
5 files changed
+434 -42

No files matched your search

@@ -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)