Extract shared media backend library; remove dead multi-flavor app/binary
Adds mediaauth/mediacore/carriernodeclient/syncsocket packages under backend/, extracting everything genuinely cross-service (auth, shared media/tags/playlists/sync/profile routes, the CarrierNode HTTP client, the playback-sync websocket hub) out of the old media-backend monolith. The 7 media-family services (CarrierNode, ContentScanner, CraftStudio, MediaViewer, MediaKiosk, ModerationHub, ProjectConfigurator) each now have their own independent frontend and backend built on this library, instead of sharing one generic multi-flavor webui/media-backend selected by a MEDIA_SERVICE/VITE_MEDIA_APP flag. That generic app and binary (webui/, media-backend/) are now dead and removed here, along with their dedicated CI workflows. sync-consumers.ps1 and README.md updated to describe the new architecture. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2e6baaa70c
commit
d1a02a8c4d
80 files changed
+1139
-16583
No files matched your search
@@ -0,0 +1,381 @@
|
||||
// Package carriernodeclient is the HTTP client the 6 non-CarrierNode
|
||||
// media-family services (MediaViewer, CraftStudio, ContentScanner,
|
||||
// ModerationHub, ProjectConfigurator, MediaKiosk) use to store and serve
|
||||
// media by calling CarrierNode's API, instead of touching a local
|
||||
// MediaRoots/ThumbnailRoot/OutputRoot/DownloadsRoot/InputRoot/CopyRoot
|
||||
// filesystem directly. CarrierNode's own backend keeps resolving and
|
||||
// serving those roots itself - this client is never used from CarrierNode's
|
||||
// own code path.
|
||||
//
|
||||
// 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"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// httpClient has no blanket timeout since it streams large media files;
|
||||
// callers bound individual calls with a context deadline instead.
|
||||
var httpClient = &http.Client{}
|
||||
|
||||
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"}
|
||||
|
||||
// Client calls CarrierNode's HTTP API on behalf of one of the other 6
|
||||
// media-family services.
|
||||
type Client struct {
|
||||
// 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
|
||||
|
||||
// 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.
|
||||
BaseURL func(ctx context.Context) string
|
||||
}
|
||||
|
||||
// New returns a Client. 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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.InternalServiceSecret != "" {
|
||||
request.Header.Set("X-Internal-Auth", c.InternalServiceSecret)
|
||||
}
|
||||
return request, nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (c *Client) Proxy(w http.ResponseWriter, r *http.Request, carrierNodePath string) {
|
||||
request, err := c.newRequest(r.Context(), r.Method, carrierNodePath, nil)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadGateway, "media service unavailable")
|
||||
return
|
||||
}
|
||||
for _, header := range forwardRequestHeaders {
|
||||
if value := r.Header.Get(header); value != "" {
|
||||
request.Header.Set(header, value)
|
||||
}
|
||||
}
|
||||
response, err := httpClient.Do(request)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadGateway, "media service unavailable")
|
||||
return
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
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
|
||||
}
|
||||
|
||||
// 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)
|
||||
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
|
||||
}
|
||||
|
||||
// push streams a local file as the request body without buffering it in
|
||||
// memory.
|
||||
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)
|
||||
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) {
|
||||
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
|
||||
// already-deleted, not an error.
|
||||
func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
|
||||
request, err := c.newRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), 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 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) {
|
||||
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) {
|
||||
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) {
|
||||
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
|
||||
// media/downloaded_media tables via its /api/store endpoint.
|
||||
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))
|
||||
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"`
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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
|
||||
}
|
||||
request, err := c.newRequest(ctx, http.MethodGet, endpoint, nil)
|
||||
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
|
||||
}
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// 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) {
|
||||
query := url.Values{}
|
||||
query.Set("path", relative)
|
||||
request, err := c.newRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
|
||||
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
|
||||
}
|
||||
|
||||
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})
|
||||
}
|
||||
Reference in new issue
Block a user