2026-09-29 22:23:11 +02:00
|
|
|
// Package carriernodeclient is the HTTP client non-CarrierNode services use
|
|
|
|
|
// to access CarrierNode's media and project-specific mount APIs. Existing
|
|
|
|
|
// media services use it for central file storage; other projects use its
|
|
|
|
|
// generic project/type methods after preferring their local volumes.
|
|
|
|
|
// CarrierNode's own backend keeps resolving and serving configured roots -
|
|
|
|
|
// this client is never used from CarrierNode's own code path.
|
2026-09-07 16:00:08 +02:00
|
|
|
//
|
|
|
|
|
// Promoted unchanged (aside from being detached from a shared *Server type)
|
|
|
|
|
// from each service's own internal carriernode_client.go into this shared
|
|
|
|
|
// library, so all 6 callers use one copy instead of duplicating it.
|
|
|
|
|
package carriernodeclient
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"context"
|
|
|
|
|
"encoding/json"
|
2026-10-15 13:56:24 +00:00
|
|
|
"errors"
|
2026-09-07 16:00:08 +02:00
|
|
|
"fmt"
|
|
|
|
|
"io"
|
|
|
|
|
"net/http"
|
|
|
|
|
"net/url"
|
|
|
|
|
"os"
|
|
|
|
|
"strconv"
|
|
|
|
|
"strings"
|
2026-10-20 15:27:53 +00:00
|
|
|
"sync"
|
2026-09-07 16:00:08 +02:00
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
2026-10-20 15:27:53 +00:00
|
|
|
// httpClient has no total timeout since it streams large media files. The
|
|
|
|
|
// transport still bounds how long a request may wait for response headers;
|
|
|
|
|
// callers that need a shorter bound add a context deadline as well.
|
|
|
|
|
var httpClient = newHTTPClient()
|
|
|
|
|
|
|
|
|
|
func newHTTPClient() *http.Client {
|
|
|
|
|
var transport *http.Transport
|
|
|
|
|
if defaultTransport, ok := http.DefaultTransport.(*http.Transport); ok {
|
|
|
|
|
transport = defaultTransport.Clone()
|
|
|
|
|
} else {
|
|
|
|
|
transport = &http.Transport{Proxy: http.ProxyFromEnvironment}
|
|
|
|
|
}
|
|
|
|
|
transport.ResponseHeaderTimeout = 10 * time.Second
|
|
|
|
|
return &http.Client{Transport: transport}
|
|
|
|
|
}
|
2026-09-07 16:00:08 +02:00
|
|
|
|
|
|
|
|
var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
|
|
|
|
|
var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
|
|
|
|
|
|
2026-09-29 22:23:11 +02:00
|
|
|
// Client calls CarrierNode's HTTP API on behalf of another workspace service.
|
2026-09-07 16:00:08 +02:00
|
|
|
type Client struct {
|
2026-09-18 11:21:06 +02:00
|
|
|
// ProjectKey identifies the service making a request to CarrierNode. It is
|
|
|
|
|
// optional for backwards compatibility, but when set it lets CarrierNode
|
|
|
|
|
// attribute internal transfers to the originating project on its traffic
|
|
|
|
|
// dashboard instead of combining every service under one bucket.
|
|
|
|
|
ProjectKey string
|
|
|
|
|
|
2026-09-07 16:00:08 +02:00
|
|
|
// InternalServiceSecret is sent as the X-Internal-Auth header on every
|
|
|
|
|
// request, so CarrierNode can distinguish trusted service-to-service
|
|
|
|
|
// calls from public traffic. Empty means no header is sent.
|
|
|
|
|
InternalServiceSecret string
|
|
|
|
|
|
2026-09-16 19:52:57 +02:00
|
|
|
// InternalServiceSecretFunc, when set, resolves the current secret for
|
|
|
|
|
// each request. This lets callers use ProjectConfigurator's live
|
|
|
|
|
// per-service secret while retaining InternalServiceSecret as the
|
|
|
|
|
// bootstrap/fallback value.
|
|
|
|
|
InternalServiceSecretFunc func(ctx context.Context) string
|
|
|
|
|
|
2026-09-07 16:00:08 +02:00
|
|
|
// BaseURL resolves CarrierNode's current base URL for a request. It is a
|
|
|
|
|
// function rather than a fixed string because CarrierNode's URL is
|
|
|
|
|
// configured live through ProjectConfigurator's Projects workspace
|
|
|
|
|
// (stored in the shared `settings` table under the "carriernode_url"
|
|
|
|
|
// key) - a change there takes effect on this client's very next call
|
|
|
|
|
// 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.
|
2026-09-11 11:37:56 +02:00
|
|
|
//
|
|
|
|
|
// Set exactly one of BaseURL or BaseURLs (New/NewMulti do this for you).
|
|
|
|
|
// When BaseURLs is set it takes priority.
|
2026-09-07 16:00:08 +02:00
|
|
|
BaseURL func(ctx context.Context) string
|
2026-09-11 11:37:56 +02:00
|
|
|
|
|
|
|
|
// 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
|
2026-10-20 15:27:53 +00:00
|
|
|
|
|
|
|
|
thumbnailMu sync.Mutex
|
|
|
|
|
thumbnailPaths map[string]thumbnailPathEntry
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const thumbnailPathCacheTTL = 5 * time.Minute
|
|
|
|
|
const thumbnailPathCacheLimit = 2048
|
|
|
|
|
|
|
|
|
|
type thumbnailPathEntry struct {
|
|
|
|
|
path string
|
|
|
|
|
expires time.Time
|
2026-09-07 16:00:08 +02:00
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:37:56 +02:00
|
|
|
// 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).
|
2026-09-07 16:00:08 +02:00
|
|
|
func New(internalServiceSecret string, baseURL func(ctx context.Context) string) *Client {
|
|
|
|
|
return &Client{InternalServiceSecret: internalServiceSecret, BaseURL: baseURL}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:37:56 +02:00
|
|
|
// 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.
|
2026-09-11 11:56:55 +02:00
|
|
|
// - Read operations tied to one file (Proxy, Probe, FetchToScratch,
|
|
|
|
|
// ProbeMedia) try each instance in order and use the first one that
|
|
|
|
|
// actually has the file, so playback/thumbnails/metadata for a file
|
|
|
|
|
// living on a non-primary storage backend still work, and a replica
|
|
|
|
|
// standing in for a downed primary is still found.
|
|
|
|
|
// - Writes (PushThumbnail, DeleteThumbnail, PushOutput, PushInput,
|
2026-09-11 11:37:56 +02:00
|
|
|
// 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 ""
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-29 22:23:11 +02:00
|
|
|
// Configured reports whether the client currently has at least one non-empty
|
|
|
|
|
// CarrierNode URL. It is useful when a caller has another local fallback it
|
|
|
|
|
// can try if shared storage has not been configured.
|
|
|
|
|
func (c *Client) Configured(ctx context.Context) bool {
|
|
|
|
|
for _, baseURL := range c.candidateBaseURLs(ctx) {
|
|
|
|
|
if strings.TrimSpace(baseURL) != "" {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:37:56 +02:00
|
|
|
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)
|
2026-09-07 16:00:08 +02:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2026-09-16 19:52:57 +02:00
|
|
|
secret := c.InternalServiceSecret
|
|
|
|
|
if c.InternalServiceSecretFunc != nil {
|
|
|
|
|
secret = strings.TrimSpace(c.InternalServiceSecretFunc(ctx))
|
|
|
|
|
}
|
|
|
|
|
if secret != "" {
|
|
|
|
|
request.Header.Set("X-Internal-Auth", secret)
|
2026-09-07 16:00:08 +02:00
|
|
|
}
|
2026-09-18 11:21:06 +02:00
|
|
|
if project := strings.TrimSpace(c.ProjectKey); project != "" {
|
|
|
|
|
request.Header.Set("X-Project-Key", project)
|
|
|
|
|
}
|
2026-09-07 16:00:08 +02:00
|
|
|
return request, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Proxy streams a CarrierNode response straight through to the original
|
|
|
|
|
// client, preserving range/conditional-request semantics so video scrubbing
|
2026-09-11 11:56:55 +02:00
|
|
|
// keeps working without reimplementing http.ServeContent on this side. Every
|
|
|
|
|
// configured instance is tried in order (see NewMulti's doc comment); the
|
|
|
|
|
// first one that doesn't answer with an error is the one actually streamed,
|
|
|
|
|
// so a file living on a non-primary instance still plays and a downed
|
|
|
|
|
// primary doesn't block a replica from serving it. The last candidate's
|
|
|
|
|
// response (success or error) is always the one forwarded, matching
|
|
|
|
|
// single-instance Proxy's behavior of passing even an error status through
|
|
|
|
|
// to the caller rather than swallowing it.
|
2026-09-07 16:00:08 +02:00
|
|
|
func (c *Client) Proxy(w http.ResponseWriter, r *http.Request, carrierNodePath string) {
|
2026-09-11 11:56:55 +02:00
|
|
|
candidates := c.candidateBaseURLs(r.Context())
|
|
|
|
|
if len(candidates) == 0 {
|
|
|
|
|
candidates = []string{""}
|
2026-09-07 16:00:08 +02:00
|
|
|
}
|
2026-09-11 11:56:55 +02:00
|
|
|
for i, baseURL := range candidates {
|
|
|
|
|
last := i == len(candidates)-1
|
|
|
|
|
request, err := c.newRequest(r.Context(), baseURL, r.Method, carrierNodePath, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
if last {
|
|
|
|
|
writeError(w, http.StatusBadGateway, "media service unavailable")
|
|
|
|
|
}
|
|
|
|
|
continue
|
2026-09-07 16:00:08 +02:00
|
|
|
}
|
2026-09-11 11:56:55 +02:00
|
|
|
for _, header := range forwardRequestHeaders {
|
|
|
|
|
if value := r.Header.Get(header); value != "" {
|
|
|
|
|
request.Header.Set(header, value)
|
|
|
|
|
}
|
2026-09-07 16:00:08 +02:00
|
|
|
}
|
2026-09-11 11:56:55 +02:00
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
if last {
|
|
|
|
|
writeError(w, http.StatusBadGateway, "media service unavailable")
|
|
|
|
|
}
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if response.StatusCode >= 400 && !last {
|
|
|
|
|
response.Body.Close()
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
for _, header := range forwardResponseHeaders {
|
|
|
|
|
if value := response.Header.Get(header); value != "" {
|
|
|
|
|
w.Header().Set(header, value)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
w.WriteHeader(response.StatusCode)
|
|
|
|
|
if r.Method != http.MethodHead {
|
|
|
|
|
_, _ = io.Copy(w, response.Body)
|
|
|
|
|
}
|
|
|
|
|
return
|
2026-09-07 16:00:08 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-29 22:23:11 +02:00
|
|
|
// MountFileEntry describes one direct child returned from CarrierNode's
|
|
|
|
|
// project-specific mount listing endpoint. Path is relative to the requested
|
|
|
|
|
// directory and Directory is true for folders.
|
|
|
|
|
type MountFileEntry struct {
|
|
|
|
|
Name string `json:"name"`
|
|
|
|
|
Path string `json:"path"`
|
|
|
|
|
Directory bool `json:"directory"`
|
|
|
|
|
Size int64 `json:"size"`
|
|
|
|
|
Modified time.Time `json:"modifiedAt"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MountPath builds a project/type-specific CarrierNode API path. It escapes
|
|
|
|
|
// each path segment independently so directory separators remain separators.
|
|
|
|
|
func MountPath(project, mountType, relative string) string {
|
|
|
|
|
if strings.TrimSpace(project) == "" || strings.TrimSpace(mountType) == "" {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
parts := []string{"api", "mount", project, mountType}
|
|
|
|
|
for _, segment := range strings.Split(strings.Trim(relative, "/\\"), "/") {
|
|
|
|
|
if segment == "" || segment == "." {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if segment == ".." {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
parts = append(parts, segment)
|
|
|
|
|
}
|
|
|
|
|
for i := range parts {
|
|
|
|
|
parts[i] = url.PathEscape(parts[i])
|
|
|
|
|
}
|
|
|
|
|
return "/" + strings.Join(parts, "/")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ProxyMount streams a file from a project/type mount to the original client,
|
|
|
|
|
// preserving HTTP range and conditional headers. It is intended as a fallback
|
|
|
|
|
// after the caller's local volume has been checked.
|
|
|
|
|
func (c *Client) ProxyMount(w http.ResponseWriter, r *http.Request, project, mountType, relative string) {
|
|
|
|
|
if strings.Trim(strings.TrimSpace(relative), "/\\") == "" {
|
|
|
|
|
writeError(w, http.StatusNotFound, "file not found")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
path := MountPath(project, mountType, relative)
|
|
|
|
|
if path == "" {
|
|
|
|
|
writeError(w, http.StatusNotFound, "file not found")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if !c.Configured(r.Context()) {
|
|
|
|
|
writeError(w, http.StatusNotFound, "file not found")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
c.Proxy(w, r, path)
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-15 13:56:24 +00:00
|
|
|
// ErrMountNotFound is returned by ListMountFiles when every CarrierNode
|
|
|
|
|
// instance that answered said the directory does not exist and none failed
|
|
|
|
|
// some other way. It is a definitive "not there", unlike an unreachable
|
|
|
|
|
// instance or an error response, where the directory may well exist but could
|
|
|
|
|
// not be checked - callers can use errors.Is to tell the two apart.
|
|
|
|
|
var ErrMountNotFound = errors.New("carriernode mount directory not found")
|
|
|
|
|
|
2026-09-29 22:23:11 +02:00
|
|
|
// ListMountFiles lists the direct children of a project/type mount directory.
|
|
|
|
|
// An empty relative path lists the mount root. The CarrierNode endpoint
|
|
|
|
|
// returns both files and directories so callers can build directory browsers.
|
2026-10-15 13:56:24 +00:00
|
|
|
// When no instance can list the directory, the error wraps ErrMountNotFound
|
|
|
|
|
// only if every instance answered 404; any unreachable instance or other
|
|
|
|
|
// failure yields a plain error instead, since the directory may live there.
|
2026-09-29 22:23:11 +02:00
|
|
|
func (c *Client) ListMountFiles(ctx context.Context, project, mountType, relative string) ([]MountFileEntry, error) {
|
|
|
|
|
candidates := c.candidateBaseURLs(ctx)
|
|
|
|
|
if len(candidates) == 0 {
|
|
|
|
|
return nil, fmt.Errorf("carriernode is not configured")
|
|
|
|
|
}
|
|
|
|
|
path := MountPath(project, mountType, "")
|
|
|
|
|
if path == "" {
|
|
|
|
|
return nil, fmt.Errorf("invalid mount path")
|
|
|
|
|
}
|
|
|
|
|
query := url.Values{}
|
|
|
|
|
if strings.TrimSpace(relative) != "" {
|
|
|
|
|
query.Set("path", relative)
|
|
|
|
|
}
|
|
|
|
|
if encoded := query.Encode(); encoded != "" {
|
|
|
|
|
path += "?" + encoded
|
|
|
|
|
}
|
|
|
|
|
var entries []MountFileEntry
|
|
|
|
|
var lastErr error
|
|
|
|
|
loaded := false
|
2026-10-15 13:56:24 +00:00
|
|
|
missing := false
|
2026-09-29 22:23:11 +02:00
|
|
|
for _, baseURL := range candidates {
|
|
|
|
|
request, err := c.newRequest(ctx, baseURL, http.MethodGet, path, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
lastErr = err
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
lastErr = err
|
|
|
|
|
continue
|
|
|
|
|
}
|
2026-10-15 13:56:24 +00:00
|
|
|
if response.StatusCode == http.StatusNotFound {
|
|
|
|
|
response.Body.Close()
|
|
|
|
|
missing = true
|
|
|
|
|
continue
|
|
|
|
|
}
|
2026-09-29 22:23:11 +02:00
|
|
|
if response.StatusCode != http.StatusOK {
|
|
|
|
|
response.Body.Close()
|
|
|
|
|
lastErr = fmt.Errorf("carriernode mount listing failed: %s", response.Status)
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
var payload struct {
|
|
|
|
|
Files []MountFileEntry `json:"files"`
|
|
|
|
|
}
|
|
|
|
|
decodeErr := json.NewDecoder(response.Body).Decode(&payload)
|
|
|
|
|
response.Body.Close()
|
|
|
|
|
if decodeErr != nil {
|
|
|
|
|
lastErr = decodeErr
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
loaded = true
|
|
|
|
|
entries = append(entries, payload.Files...)
|
|
|
|
|
}
|
2026-10-15 13:56:24 +00:00
|
|
|
if !loaded {
|
|
|
|
|
if lastErr != nil {
|
|
|
|
|
return nil, lastErr
|
|
|
|
|
}
|
|
|
|
|
if missing {
|
|
|
|
|
return nil, ErrMountNotFound
|
|
|
|
|
}
|
2026-09-29 22:23:11 +02:00
|
|
|
}
|
|
|
|
|
unique := make([]MountFileEntry, 0, len(entries))
|
|
|
|
|
seen := make(map[string]struct{}, len(entries))
|
|
|
|
|
for _, entry := range entries {
|
|
|
|
|
key := entry.Path
|
|
|
|
|
if key == "" {
|
|
|
|
|
key = entry.Name
|
|
|
|
|
}
|
|
|
|
|
if _, exists := seen[key]; exists {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
seen[key] = struct{}{}
|
|
|
|
|
unique = append(unique, entry)
|
|
|
|
|
}
|
|
|
|
|
return unique, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// UploadMountFile streams a local file into a project/type mount on the
|
|
|
|
|
// primary CarrierNode. Writes intentionally target only the primary instance.
|
|
|
|
|
func (c *Client) UploadMountFile(ctx context.Context, project, mountType, relative, localPath string) error {
|
|
|
|
|
if strings.Trim(strings.TrimSpace(relative), "/\\") == "" {
|
|
|
|
|
return fmt.Errorf("invalid mount path")
|
|
|
|
|
}
|
|
|
|
|
path := MountPath(project, mountType, relative)
|
|
|
|
|
if path == "" {
|
|
|
|
|
return fmt.Errorf("invalid mount path")
|
|
|
|
|
}
|
|
|
|
|
response, err := c.push(ctx, http.MethodPost, path, localPath)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
response.Body.Close()
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// FetchMountToScratch downloads a project/type mount file to an ephemeral
|
|
|
|
|
// local file for callers that need to inspect or transform it. Callers must
|
|
|
|
|
// invoke cleanup once done.
|
|
|
|
|
func (c *Client) FetchMountToScratch(ctx context.Context, project, mountType, relative, suffix string) (string, func(), error) {
|
|
|
|
|
if strings.Trim(strings.TrimSpace(relative), "/\\") == "" {
|
|
|
|
|
return "", nil, fmt.Errorf("invalid mount path")
|
|
|
|
|
}
|
|
|
|
|
if len(c.candidateBaseURLs(ctx)) == 0 {
|
|
|
|
|
return "", nil, fmt.Errorf("carriernode is not configured")
|
|
|
|
|
}
|
|
|
|
|
path := MountPath(project, mountType, relative)
|
|
|
|
|
if path == "" {
|
|
|
|
|
return "", nil, fmt.Errorf("invalid mount path")
|
|
|
|
|
}
|
|
|
|
|
return c.FetchToScratch(ctx, path, suffix)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// UploadMountBytes writes a byte slice to a project/type mount on the primary
|
|
|
|
|
// CarrierNode. Callers should prefer this for bounded request bodies; large
|
|
|
|
|
// files should use UploadMountFile to avoid buffering them in memory.
|
|
|
|
|
func (c *Client) UploadMountBytes(ctx context.Context, project, mountType, relative string, data []byte) error {
|
|
|
|
|
if strings.Trim(strings.TrimSpace(relative), "/\\") == "" {
|
|
|
|
|
return fmt.Errorf("invalid mount path")
|
|
|
|
|
}
|
|
|
|
|
path := MountPath(project, mountType, relative)
|
|
|
|
|
if path == "" {
|
|
|
|
|
return fmt.Errorf("invalid mount path")
|
|
|
|
|
}
|
|
|
|
|
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodPost, path, bytes.NewReader(data))
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
request.ContentLength = int64(len(data))
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
if response.StatusCode >= 400 {
|
|
|
|
|
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
|
|
|
|
return fmt.Errorf("carriernode mount upload failed: %s: %s", response.Status, strings.TrimSpace(string(body)))
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// DeleteMountFile removes one file from a project/type mount on the primary
|
|
|
|
|
// CarrierNode. A missing file is treated as already deleted.
|
|
|
|
|
func (c *Client) DeleteMountFile(ctx context.Context, project, mountType, relative string) error {
|
|
|
|
|
if strings.Trim(strings.TrimSpace(relative), "/\\") == "" {
|
|
|
|
|
return fmt.Errorf("invalid mount path")
|
|
|
|
|
}
|
|
|
|
|
path := MountPath(project, mountType, relative)
|
|
|
|
|
if path == "" {
|
|
|
|
|
return fmt.Errorf("invalid mount path")
|
|
|
|
|
}
|
|
|
|
|
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, path, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
|
|
|
|
|
return fmt.Errorf("carriernode mount delete failed: %s", response.Status)
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-15 13:56:24 +00:00
|
|
|
// ThumbnailMountType is the mount type ProjectConfigurator configures for a project's
|
|
|
|
|
// generated thumbnails. Each thumbnail is one "<id>.jpg" file under that mount.
|
|
|
|
|
const ThumbnailMountType = "thumbnails"
|
|
|
|
|
|
|
|
|
|
// thumbnailFile is the file name a thumbnail id is stored under. Ids are UUIDs that
|
|
|
|
|
// ContentScanner generates, so anything that could name a path outside the thumbnails
|
|
|
|
|
// directory is refused.
|
|
|
|
|
func thumbnailFile(id string) (string, error) {
|
|
|
|
|
if id == "" || id == "." || id == ".." || strings.ContainsAny(id, `/\`) {
|
|
|
|
|
return "", fmt.Errorf("invalid thumbnail id %q", id)
|
|
|
|
|
}
|
|
|
|
|
return id + ".jpg", nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-19 21:46:52 +00:00
|
|
|
// validName reports an error unless name can be used as one path segment: it must not be empty,
|
|
|
|
|
// ".", ".." or contain a path separator. Every push and delete helper checks its name with this.
|
|
|
|
|
func validName(name string) error {
|
|
|
|
|
if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\`) {
|
|
|
|
|
return fmt.Errorf("invalid name %q", name)
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// validRelativeName is validName for outputs, inputs and copies, which may sit in nested
|
|
|
|
|
// directories (for example CraftStudio's "<user>/<workflow>/<file>"). It refuses an empty or
|
|
|
|
|
// absolute name, a backslash, and any empty, "." or ".." segment.
|
|
|
|
|
func validRelativeName(name string) error {
|
|
|
|
|
if name == "" || strings.HasPrefix(name, "/") || strings.ContainsRune(name, '\\') {
|
|
|
|
|
return fmt.Errorf("invalid name %q", name)
|
|
|
|
|
}
|
|
|
|
|
for _, segment := range strings.Split(name, "/") {
|
|
|
|
|
if segment == "" || segment == "." || segment == ".." {
|
|
|
|
|
return fmt.Errorf("invalid name %q", name)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-15 13:56:24 +00:00
|
|
|
// thumbnailPaths lists every CarrierNode path a thumbnail may live at, in lookup order: the
|
|
|
|
|
// project's thumbnails mount first, then CarrierNode's legacy thumbnail root. Thumbnails
|
|
|
|
|
// stored before the mount existed sit in the legacy root, and reads keep finding them there
|
|
|
|
|
// until they are regenerated or deleted.
|
|
|
|
|
func thumbnailPaths(project, id string) ([]string, error) {
|
|
|
|
|
file, err := thumbnailFile(id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
var paths []string
|
|
|
|
|
if path := MountPath(project, ThumbnailMountType, file); path != "" {
|
|
|
|
|
paths = append(paths, path)
|
|
|
|
|
}
|
|
|
|
|
return append(paths, "/thumbnails/"+file), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// StoreThumbnail uploads a generated thumbnail into the project's thumbnails mount on the
|
|
|
|
|
// primary CarrierNode and returns its size in bytes. CarrierNode only accepts mount writes
|
|
|
|
|
// under its /mount volume, so the configured thumbnails path has to be there.
|
|
|
|
|
func (c *Client) StoreThumbnail(ctx context.Context, project, id, localPath string) (int64, error) {
|
|
|
|
|
file, err := thumbnailFile(id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
|
|
|
|
info, err := os.Stat(localPath)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
|
|
|
|
if err := c.UploadMountFile(ctx, project, ThumbnailMountType, file, localPath); err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
|
|
|
|
return info.Size(), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// DeleteStoredThumbnail removes a thumbnail from the project's thumbnails mount and from the
|
|
|
|
|
// legacy root, since one stored before the mount existed may still be there. A thumbnail
|
|
|
|
|
// missing from both is already deleted.
|
|
|
|
|
func (c *Client) DeleteStoredThumbnail(ctx context.Context, project, id string) error {
|
|
|
|
|
file, err := thumbnailFile(id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
mountErr := c.DeleteMountFile(ctx, project, ThumbnailMountType, file)
|
|
|
|
|
legacyErr := c.DeleteThumbnail(ctx, id)
|
|
|
|
|
return errors.Join(mountErr, legacyErr)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ProxyThumbnail streams a stored thumbnail to the original client, looking in the project's
|
|
|
|
|
// thumbnails mount and then the legacy root. It reports false without writing anything when
|
|
|
|
|
// neither holds the thumbnail, so the caller can fall back to another source.
|
|
|
|
|
func (c *Client) ProxyThumbnail(w http.ResponseWriter, r *http.Request, project, id string) bool {
|
|
|
|
|
paths, err := thumbnailPaths(project, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return false
|
|
|
|
|
}
|
2026-10-20 15:27:53 +00:00
|
|
|
cacheKey := project + "\x00" + id
|
|
|
|
|
cachedPath := c.cachedThumbnailPath(cacheKey)
|
|
|
|
|
if cachedPath != "" {
|
|
|
|
|
ordered := make([]string, 0, len(paths))
|
|
|
|
|
ordered = append(ordered, cachedPath)
|
|
|
|
|
for _, path := range paths {
|
|
|
|
|
if path != cachedPath {
|
|
|
|
|
ordered = append(ordered, path)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
paths = ordered
|
|
|
|
|
}
|
2026-10-15 13:56:24 +00:00
|
|
|
for _, path := range paths {
|
2026-10-20 15:27:53 +00:00
|
|
|
for _, baseURL := range c.candidateBaseURLs(r.Context()) {
|
|
|
|
|
request, err := c.newRequest(r.Context(), baseURL, r.Method, path, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
for _, header := range forwardRequestHeaders {
|
|
|
|
|
if value := r.Header.Get(header); value != "" {
|
|
|
|
|
request.Header.Set(header, value)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if response.StatusCode >= http.StatusBadRequest {
|
|
|
|
|
response.Body.Close()
|
|
|
|
|
if path == cachedPath {
|
|
|
|
|
c.forgetThumbnailPath(cacheKey)
|
|
|
|
|
}
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
for _, header := range forwardResponseHeaders {
|
|
|
|
|
if value := response.Header.Get(header); value != "" {
|
|
|
|
|
w.Header().Set(header, value)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
w.WriteHeader(response.StatusCode)
|
|
|
|
|
if r.Method != http.MethodHead {
|
|
|
|
|
_, _ = io.Copy(w, response.Body)
|
|
|
|
|
}
|
|
|
|
|
response.Body.Close()
|
|
|
|
|
c.rememberThumbnailPath(cacheKey, path)
|
2026-10-15 13:56:24 +00:00
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-20 15:27:53 +00:00
|
|
|
func (c *Client) cachedThumbnailPath(key string) string {
|
|
|
|
|
c.thumbnailMu.Lock()
|
|
|
|
|
defer c.thumbnailMu.Unlock()
|
|
|
|
|
entry, ok := c.thumbnailPaths[key]
|
|
|
|
|
if !ok {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
if !time.Now().Before(entry.expires) {
|
|
|
|
|
delete(c.thumbnailPaths, key)
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
return entry.path
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *Client) rememberThumbnailPath(key, path string) {
|
|
|
|
|
c.thumbnailMu.Lock()
|
|
|
|
|
defer c.thumbnailMu.Unlock()
|
|
|
|
|
if c.thumbnailPaths == nil {
|
|
|
|
|
c.thumbnailPaths = make(map[string]thumbnailPathEntry)
|
|
|
|
|
}
|
|
|
|
|
now := time.Now()
|
|
|
|
|
for cacheKey, entry := range c.thumbnailPaths {
|
|
|
|
|
if !now.Before(entry.expires) {
|
|
|
|
|
delete(c.thumbnailPaths, cacheKey)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if len(c.thumbnailPaths) >= thumbnailPathCacheLimit {
|
|
|
|
|
var oldestKey string
|
|
|
|
|
var oldest time.Time
|
|
|
|
|
first := true
|
|
|
|
|
for cacheKey, entry := range c.thumbnailPaths {
|
|
|
|
|
if first || entry.expires.Before(oldest) {
|
|
|
|
|
oldestKey, oldest, first = cacheKey, entry.expires, false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
delete(c.thumbnailPaths, oldestKey)
|
|
|
|
|
}
|
|
|
|
|
c.thumbnailPaths[key] = thumbnailPathEntry{path: path, expires: now.Add(thumbnailPathCacheTTL)}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *Client) forgetThumbnailPath(key string) {
|
|
|
|
|
c.thumbnailMu.Lock()
|
|
|
|
|
delete(c.thumbnailPaths, key)
|
|
|
|
|
c.thumbnailMu.Unlock()
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-15 13:56:24 +00:00
|
|
|
// FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking
|
|
|
|
|
// in the project's thumbnails mount and then the legacy root. Callers must invoke the returned
|
|
|
|
|
// cleanup once done.
|
|
|
|
|
func (c *Client) FetchThumbnailToScratch(ctx context.Context, project, id, suffix string) (string, func(), error) {
|
|
|
|
|
paths, err := thumbnailPaths(project, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return "", nil, err
|
|
|
|
|
}
|
|
|
|
|
var lastErr error
|
|
|
|
|
for _, path := range paths {
|
|
|
|
|
scratch, cleanup, fetchErr := c.FetchToScratch(ctx, path, suffix)
|
|
|
|
|
if fetchErr == nil {
|
|
|
|
|
return scratch, cleanup, nil
|
|
|
|
|
}
|
|
|
|
|
lastErr = fetchErr
|
|
|
|
|
}
|
|
|
|
|
return "", nil, lastErr
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:37:56 +02:00
|
|
|
// 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)
|
2026-09-07 16:00:08 +02:00
|
|
|
if err != nil {
|
|
|
|
|
return false, 0, time.Time{}, err
|
|
|
|
|
}
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return false, 0, time.Time{}, err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
if response.StatusCode == http.StatusNotFound {
|
|
|
|
|
return false, 0, time.Time{}, nil
|
|
|
|
|
}
|
|
|
|
|
if response.StatusCode >= 400 {
|
|
|
|
|
return false, 0, time.Time{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
|
|
|
|
|
}
|
|
|
|
|
size, _ = strconv.ParseInt(response.Header.Get("Content-Length"), 10, 64)
|
|
|
|
|
modTime, _ = http.ParseTime(response.Header.Get("Last-Modified"))
|
|
|
|
|
return true, size, modTime, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:37:56 +02:00
|
|
|
// 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)
|
2026-09-07 16:00:08 +02:00
|
|
|
if err != nil {
|
|
|
|
|
return "", nil, err
|
|
|
|
|
}
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return "", nil, err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
if response.StatusCode != http.StatusOK {
|
|
|
|
|
return "", nil, fmt.Errorf("carriernode fetch failed: %s", response.Status)
|
|
|
|
|
}
|
|
|
|
|
scratch, err := os.CreateTemp("", "carriernode-src-*"+suffix)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return "", nil, err
|
|
|
|
|
}
|
|
|
|
|
cleanup = func() { _ = os.Remove(scratch.Name()) }
|
|
|
|
|
if _, err := io.Copy(scratch, response.Body); err != nil {
|
|
|
|
|
scratch.Close()
|
|
|
|
|
cleanup()
|
|
|
|
|
return "", nil, err
|
|
|
|
|
}
|
|
|
|
|
if err := scratch.Close(); err != nil {
|
|
|
|
|
cleanup()
|
|
|
|
|
return "", nil, err
|
|
|
|
|
}
|
|
|
|
|
return scratch.Name(), cleanup, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:37:56 +02:00
|
|
|
// 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
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-07 16:00:08 +02:00
|
|
|
// push streams a local file as the request body without buffering it in
|
2026-09-11 11:37:56 +02:00
|
|
|
// memory. Always targets the primary instance - see NewMulti's doc comment.
|
2026-09-07 16:00:08 +02:00
|
|
|
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()
|
2026-09-11 11:37:56 +02:00
|
|
|
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), method, carrierNodePath, file)
|
2026-09-07 16:00:08 +02:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
if info, statErr := file.Stat(); statErr == nil {
|
|
|
|
|
request.ContentLength = info.Size()
|
|
|
|
|
}
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
if response.StatusCode >= 400 {
|
|
|
|
|
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
|
|
|
|
response.Body.Close()
|
|
|
|
|
return nil, fmt.Errorf("carriernode push failed: %s: %s", response.Status, string(body))
|
|
|
|
|
}
|
|
|
|
|
return response, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func pushedSize(response *http.Response) int64 {
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
var payload struct {
|
|
|
|
|
Size int64 `json:"size"`
|
|
|
|
|
}
|
|
|
|
|
_ = json.NewDecoder(response.Body).Decode(&payload)
|
|
|
|
|
return payload.Size
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// PushThumbnail uploads a locally-generated thumbnail to CarrierNode.
|
|
|
|
|
func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
|
2026-10-19 21:46:52 +00:00
|
|
|
if err := validName(id); err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
2026-09-07 16:00:08 +02:00
|
|
|
response, err := c.push(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
|
|
|
|
return pushedSize(response), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// DeleteThumbnail removes a thumbnail from CarrierNode. A 404 is treated as
|
2026-09-11 11:37:56 +02:00
|
|
|
// already-deleted, not an error. Always targets the primary instance.
|
2026-09-07 16:00:08 +02:00
|
|
|
func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
|
2026-10-19 21:46:52 +00:00
|
|
|
if err := validName(id); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2026-09-11 11:37:56 +02:00
|
|
|
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
|
2026-09-07 16:00:08 +02:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
|
|
|
|
|
return fmt.Errorf("carriernode delete thumbnail failed: %s", response.Status)
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// PushOutput uploads a locally-produced output file (e.g. a converted or
|
|
|
|
|
// generated media file) to CarrierNode's OutputRoot.
|
|
|
|
|
func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64, error) {
|
2026-10-19 21:46:52 +00:00
|
|
|
if err := validRelativeName(name); err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
2026-09-07 16:00:08 +02:00
|
|
|
response, err := c.push(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
|
|
|
|
return pushedSize(response), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// PushInput uploads a local file to CarrierNode's InputRoot.
|
|
|
|
|
func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64, error) {
|
2026-10-19 21:46:52 +00:00
|
|
|
if err := validRelativeName(name); err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
2026-09-07 16:00:08 +02:00
|
|
|
response, err := c.push(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
|
|
|
|
return pushedSize(response), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// PushCopy uploads a local file to CarrierNode's CopyRoot.
|
|
|
|
|
func (c *Client) PushCopy(ctx context.Context, name, localPath string) (int64, error) {
|
2026-10-19 21:46:52 +00:00
|
|
|
if err := validRelativeName(name); err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
2026-09-07 16:00:08 +02:00
|
|
|
response, err := c.push(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
|
|
|
|
return pushedSize(response), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// UploadDownload streams a locally-produced file (e.g. a completed yt-dlp
|
|
|
|
|
// download staged in a scratch dir) into CarrierNode's DownloadsRoot via its
|
|
|
|
|
// raw-upload endpoint.
|
|
|
|
|
func (c *Client) UploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
|
|
|
|
|
response, err := c.push(ctx, http.MethodPost, "/api/upload?filename="+url.QueryEscape(filename), localPath)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
var payload map[string]any
|
|
|
|
|
_ = json.NewDecoder(response.Body).Decode(&payload)
|
|
|
|
|
return payload, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// StoreDownload catalogs an already-uploaded file into CarrierNode's
|
2026-09-11 11:37:56 +02:00
|
|
|
// media/downloaded_media tables via its /api/store endpoint. Always targets
|
|
|
|
|
// the primary instance.
|
2026-09-07 16:00:08 +02:00
|
|
|
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
|
|
|
|
|
}
|
2026-09-11 11:37:56 +02:00
|
|
|
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodPost, "/api/store", bytes.NewReader(body))
|
2026-09-07 16:00:08 +02:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
request.Header.Set("Content-Type", "application/json")
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
if response.StatusCode >= 400 {
|
|
|
|
|
errorBody, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
|
|
|
|
return nil, fmt.Errorf("carriernode store failed: %s: %s", response.Status, string(errorBody))
|
|
|
|
|
}
|
|
|
|
|
var payload map[string]any
|
|
|
|
|
_ = json.NewDecoder(response.Body).Decode(&payload)
|
|
|
|
|
return payload, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// FileEntry describes one file CarrierNode reports via /api/files(/recent).
|
|
|
|
|
type FileEntry struct {
|
|
|
|
|
Rel string `json:"rel"`
|
|
|
|
|
Path string `json:"path"`
|
|
|
|
|
Type string `json:"type"`
|
|
|
|
|
Size int64 `json:"size"`
|
|
|
|
|
Mtime int64 `json:"mtime"`
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:37:56 +02:00
|
|
|
func (c *Client) listFilesOne(ctx context.Context, baseURL, relative string, recent bool, limit int) ([]FileEntry, error) {
|
2026-09-07 16:00:08 +02:00
|
|
|
endpoint := "/api/files"
|
|
|
|
|
if recent {
|
|
|
|
|
endpoint = "/api/files/recent"
|
|
|
|
|
}
|
|
|
|
|
query := url.Values{}
|
|
|
|
|
if relative != "" {
|
|
|
|
|
query.Set("path", relative)
|
|
|
|
|
}
|
|
|
|
|
if limit > 0 {
|
|
|
|
|
query.Set("limit", strconv.Itoa(limit))
|
|
|
|
|
}
|
|
|
|
|
if encoded := query.Encode(); encoded != "" {
|
|
|
|
|
endpoint += "?" + encoded
|
|
|
|
|
}
|
2026-09-11 11:37:56 +02:00
|
|
|
request, err := c.newRequest(ctx, baseURL, http.MethodGet, endpoint, nil)
|
2026-09-07 16:00:08 +02:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
if response.StatusCode != http.StatusOK {
|
|
|
|
|
return nil, fmt.Errorf("carriernode file listing failed: %s", response.Status)
|
|
|
|
|
}
|
|
|
|
|
var payload struct {
|
|
|
|
|
Files []FileEntry `json:"files"`
|
|
|
|
|
}
|
|
|
|
|
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return payload.Files, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:37:56 +02:00
|
|
|
// 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
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-07 16:00:08 +02:00
|
|
|
// ProbeResult is the ffprobe-derived metadata CarrierNode's /api/probe
|
|
|
|
|
// endpoint reports for a media file.
|
|
|
|
|
type ProbeResult struct {
|
|
|
|
|
DurationMs int64 `json:"durationMs"`
|
|
|
|
|
Width int `json:"width"`
|
|
|
|
|
Height int `json:"height"`
|
2026-09-23 15:48:17 +02:00
|
|
|
IsVR bool `json:"isVr"`
|
|
|
|
|
// Pointers keep the distinction between a newer CarrierNode explicitly
|
|
|
|
|
// reporting false and an older one that does not return these fields yet.
|
|
|
|
|
HasVideo *bool `json:"hasVideo"`
|
|
|
|
|
HasAudio *bool `json:"hasAudio"`
|
2026-09-07 16:00:08 +02:00
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:37:56 +02:00
|
|
|
func (c *Client) probeMediaOne(ctx context.Context, baseURL, relative string) (ProbeResult, error) {
|
2026-09-07 16:00:08 +02:00
|
|
|
query := url.Values{}
|
|
|
|
|
query.Set("path", relative)
|
2026-09-11 11:37:56 +02:00
|
|
|
request, err := c.newRequest(ctx, baseURL, http.MethodGet, "/api/probe?"+query.Encode(), nil)
|
2026-09-07 16:00:08 +02:00
|
|
|
if err != nil {
|
|
|
|
|
return ProbeResult{}, err
|
|
|
|
|
}
|
|
|
|
|
response, err := httpClient.Do(request)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return ProbeResult{}, err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
if response.StatusCode != http.StatusOK {
|
|
|
|
|
return ProbeResult{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
|
|
|
|
|
}
|
|
|
|
|
var result ProbeResult
|
|
|
|
|
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
|
|
|
|
return ProbeResult{}, err
|
|
|
|
|
}
|
|
|
|
|
return result, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:37:56 +02:00
|
|
|
// 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
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-07 16:00:08 +02:00
|
|
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
|
|
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
|
|
|
w.WriteHeader(status)
|
|
|
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func writeError(w http.ResponseWriter, status int, message string) {
|
|
|
|
|
writeJSON(w, status, map[string]string{"error": message, "message": message})
|
|
|
|
|
}
|