Files
shared/media-backend/internal/server/servant_client.go
T
Gabriel20xxandClaude Sonnet 5 acde180086 Fold MediaEngine (media-backend, media-webui) into this repo
Per owner decision: MediaEngine (the Media product family's Go backend
and SvelteKit frontend, previously its own repo referenced by 7 thin
service repos via git submodule) is folded directly into shared/ as
media-backend/ and media-webui/, rather than staying separate.

media-backend/go.mod's replace directive now points at ../backend (a
true sibling within this repo) instead of a vendored ../shared/backend
copy, since there's no more nested vendoring - it's the real thing.

Also moved MediaEngine's own CI (media-backend-lint.yml,
media-backend-tests.yml) and dev tooling scripts (scripts/media/*,
audit/lint/enforce scripts for the media-backend+media-webui content),
fixing their path assumptions for the new layout, and dropped
scripts/media/sync-shared.mjs (confirmed dead code, and now doubly
obsolete since there's no more vendored shared/ subfolder for it to
check). Added media:* script aliases to package.json for the moved
tooling, namespaced to avoid colliding with this repo's own scripts.

Also fixed sync-consumers.ps1's workspace-root resolution to walk up
until it finds a directory containing both Original/ and Forks/,
instead of assuming shared/ is always a direct child of the workspace
root - it broke when shared/ moved from Web/shared to Web/Central/shared
earlier in this same restructuring. Removed the now-obsolete
Original/MediaEngine entry from its consumer list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:06:29 +02:00

332 lines
11 KiB
Go

package server
// Servant client: every non-Servant service serves and stores media by calling Porter's
// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/
// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. Servant's own handlers keep using those
// roots directly (see media.go, admin_storage.go) - this file is never called from Servant's
// own code path.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// servantHTTPClient has no blanket timeout since it streams large media files; callers bound
// individual calls with a context deadline instead.
var servantHTTPClient = &http.Client{}
func (s *Server) servantClient() *http.Client {
return servantHTTPClient
}
// servantBaseURL is configured in MediaConfig and stored in the settings table (key
// "mediaservant_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for
// every project's connection URL) - not a static env var, so a change in MediaConfig takes
// effect on every service's very next request without a restart. SERVANT_URL is only the
// bootstrap fallback before that setting has ever been saved.
func (s *Server) servantBaseURL(ctx context.Context) string {
return strings.TrimRight(s.settingValue(ctx, "mediaservant_url", s.cfg.ServantURL), "/")
}
func (s *Server) newServantRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, method, s.servantBaseURL(ctx)+path, body)
if err != nil {
return nil, err
}
if s.cfg.InternalServiceSecret != "" {
request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret)
}
return request, nil
}
var servantForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var servantForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
// proxyServant streams a Servant 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 (s *Server) proxyServant(w http.ResponseWriter, r *http.Request, servantPath string) {
request, err := s.newServantRequest(r.Context(), r.Method, servantPath, nil)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
for _, header := range servantForwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := s.servantClient().Do(request)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
defer response.Body.Close()
for _, header := range servantForwardResponseHeaders {
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)
}
}
// probeServant checks whether a Servant-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 (s *Server) probeServant(ctx context.Context, servantPath string) (bool, int64, time.Time, error) {
request, err := s.newServantRequest(ctx, http.MethodHead, servantPath, nil)
if err != nil {
return false, 0, time.Time{}, err
}
response, err := s.servantClient().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("servant 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
}
// fetchServantToScratch downloads a Servant-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 (s *Server) fetchServantToScratch(ctx context.Context, servantPath, suffix string) (string, func(), error) {
request, err := s.newServantRequest(ctx, http.MethodGet, servantPath, nil)
if err != nil {
return "", nil, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return "", nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return "", nil, fmt.Errorf("servant fetch failed: %s", response.Status)
}
scratch, err := os.CreateTemp("", "servant-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
}
// pushToServant streams a local file as the request body without buffering it in memory.
func (s *Server) pushToServant(ctx context.Context, method, servantPath, localPath string) (*http.Response, error) {
file, err := os.Open(localPath)
if err != nil {
return nil, err
}
defer file.Close()
request, err := s.newServantRequest(ctx, method, servantPath, file)
if err != nil {
return nil, err
}
if info, statErr := file.Stat(); statErr == nil {
request.ContentLength = info.Size()
}
response, err := s.servantClient().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("servant push failed: %s: %s", response.Status, string(body))
}
return response, nil
}
func servantPushedSize(response *http.Response) int64 {
defer response.Body.Close()
var payload struct {
Size int64 `json:"size"`
}
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload.Size
}
func (s *Server) servantPushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantDeleteThumbnail(ctx context.Context, id string) error {
request, err := s.newServantRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil {
return err
}
response, err := s.servantClient().Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
return fmt.Errorf("servant delete thumbnail failed: %s", response.Status)
}
return nil
}
func (s *Server) servantPushOutput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantPushInput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantPushCopy(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
// servantUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download
// staged in a scratch dir) into Servant's DownloadsRoot via its existing raw-upload endpoint.
func (s *Server) servantUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
response, err := s.pushToServant(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
}
// servantStoreDownload catalogs an already-uploaded file into Servant's media/downloaded_media
// tables via its existing /api/store endpoint - callers should stop duplicating that DB write
// locally once they migrate to this.
func (s *Server) servantStoreDownload(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 := s.newServantRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := s.servantClient().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("servant store failed: %s: %s", response.Status, string(errorBody))
}
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// servantListFiles lists files under Servant's MediaRoots via its existing /api/files(/recent)
// endpoints - the replacement for a local filepath.WalkDir over MediaRoots.
func (s *Server) servantListFiles(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 := s.newServantRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("servant 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
}
type servantProbeResult struct {
DurationMs int64 `json:"durationMs"`
Width int `json:"width"`
Height int `json:"height"`
}
// servantProbe runs ffprobe on Servant against a MediaRoots-relative path and returns just the
// metadata fields - bytes never leave Servant, unlike every other helper in this file.
func (s *Server) servantProbe(ctx context.Context, relative string) (servantProbeResult, error) {
query := url.Values{}
query.Set("path", relative)
request, err := s.newServantRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
if err != nil {
return servantProbeResult{}, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return servantProbeResult{}, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return servantProbeResult{}, fmt.Errorf("servant probe failed: %s", response.Status)
}
var result servantProbeResult
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return servantProbeResult{}, err
}
return result, nil
}