Add self-info endpoint for ProjectConfigurator discovery, sync shared updates
Lint / Lint (push) Successful in 1m5s
Tests / Go backend (push) Successful in 46s
Docker / Docker Build & Push (push) Failing after 2m1s
Tests / Dashboard checks (push) Successful in 49s

GET /api/info reports name/tabs/mount types (empty - state lives in Postgres,
no shared file mounts) so ProjectConfigurator's Projects workspace can
register this instance from just a URL.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Sonnet 5 committed 2026-09-04 15:07:02 +02:00
1 parent 557a61b4ee
commit bbf5d8bb05
126 files changed
+2897 -8542

No files matched your search

+4 -4
View File
@@ -1,4 +1,4 @@
// Package auth is the media-collection family's /auth/... and /api/auth/...
// Package auth is the shared media-backend family's /auth/... and /api/auth/...
// handlers, proxied to AuthGuard.
//
// AuthGuard migration
@@ -15,7 +15,7 @@
// resolved through this module's own `repos.gfranz.ch/Gabriel20xx/shared/backend`
// dependency - same module that already provided `sharedauth`). This
// service's own /auth/... and /api/auth/... URL paths and JSON response
// shapes are UNCHANGED - the frontend (media-webui) was not touched - only
// shapes are UNCHANGED - the frontend (webui) was not touched - only
// what backs them changed. This mirrors the migration
// Original/GameStream/backend/cmd/gamestreamd/auth.go and
// Forks/Bitmagnet/backend/internal/auth/service.go already did; read either
@@ -44,7 +44,7 @@
// the bearer token on its server-to-server calls to AuthGuard
// (sessionToken/CurrentUser below). This service mints no session token of
// its own any more. The pre-migration SESSION_COOKIE name (configurable,
// default "mediacollection_session") is retained only as something Logout
// default "session") is retained only as something Logout
// additionally clears, so a browser that still holds one from before this
// migration doesn't keep sending a now-meaningless cookie forever.
//
@@ -78,7 +78,7 @@
// username/email/password via AuthGuard today; see UpdateMe.
// - The `bio`/`avatarUrl` fields the pre-migration User type carried are
// dropped entirely: AuthGuard has no such concept, and grepping the
// frontend (media-webui) confirms neither field was ever actually read
// frontend (webui) confirms neither field was ever actually read
// or set by any UI - they were dead weight even before this migration.
//
// Auth-disabled mode (AUTHGUARD_URL unset)
@@ -11,7 +11,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"mediacollection/internal/database"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/database"
)
// testPool returns a connection pool against a real (throwaway) Postgres
@@ -129,7 +129,7 @@ func newRequest(method, target string, body string) *http.Request {
}
func TestCurrentUserDisabledModeReturnsLocalSuperadmin(t *testing.T) {
svc := New(nil, "mediacollection_session", false, "")
svc := New(nil, "session", false, "")
user, err := svc.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil))
if err != nil {
t.Fatalf("CurrentUser() error = %v", err)
@@ -143,7 +143,7 @@ func TestSignupLoginLogoutProxyToAuthGuard(t *testing.T) {
pool := testPool(t)
guard := newFakeAuthGuard()
defer guard.close()
svc := New(pool, "mediacollection_session", false, guard.server.URL)
svc := New(pool, "session", false, guard.server.URL)
ctx := context.Background()
// Signup
@@ -207,7 +207,7 @@ func TestSecondProjectSetupIsRejectedWhenAuthGuardAlreadyHasAnAccount(t *testing
guard.hasAccount = true // simulate a different project (or AuthGuard's own web UI) having already created one
guard.username, guard.email, guard.role, guard.password = "existing", "existing@example.com", "superadmin", "hunter2!!"
svc := New(pool, "mediacollection_session", false, guard.server.URL)
svc := New(pool, "session", false, guard.server.URL)
req := newRequest(http.MethodPost, "/auth/signup", `{"email":"new@example.com","username":"new","password":"correct horse battery staple"}`)
rec := httptest.NewRecorder()
svc.Signup(rec, req)
@@ -223,7 +223,7 @@ func TestSecondProjectSetupIsRejectedWhenAuthGuardAlreadyHasAnAccount(t *testing
func TestLoginRequiredToggleIsIndependentOfAuthGuard(t *testing.T) {
pool := testPool(t)
svc := New(pool, "mediacollection_session", false, "")
svc := New(pool, "session", false, "")
required, err := svc.LoginRequired(context.Background())
if err != nil || !required {
+29 -29
View File
@@ -17,27 +17,27 @@ const (
ConfigService Service = "config"
Moderator Service = "moderator"
Kiosk Service = "kiosk"
Servant Service = "servant"
CarrierNode Service = "carriernode"
)
type Config struct {
Port string
DatabaseURL string
Service Service
ServiceName string
WebRoot string
MediaRoots []string
InputRoot string
CopyRoot string
WorkflowsRoot string
ThumbnailRoot string
OutputRoot string
DownloadsRoot string
ModelsRoot string
AllowedOrigin string
PublicURL string
SessionCookie string
SecureCookies bool
Port string
DatabaseURL string
Service Service
ServiceName string
WebRoot string
MediaRoots []string
InputRoot string
CopyRoot string
WorkflowsRoot string
ThumbnailRoot string
OutputRoot string
DownloadsRoot string
ModelsRoot string
AllowedOrigin string
PublicURL string
SessionCookie string
SecureCookies bool
// AuthGuardURL is AuthGuard's base URL (see Web/Central/AuthGuard);
// empty means auth-disabled mode (see internal/auth's package doc
// comment). Read raw via os.Getenv rather than envOr since "" is a
@@ -49,7 +49,7 @@ type Config struct {
YTDLP string
ComfyURL string
AnalyzerModelsURL string
ServantURL string
CarrierNodeURL string
MaxUploadBytes int64
TLSCertFile string
TLSKeyFile string
@@ -96,7 +96,7 @@ func Load() (*Config, error) {
ModelsRoot: filepath.Clean(envOr("MODEL_CACHE_DIR", "./models")),
AllowedOrigin: envOr("CORS_ORIGIN", "http://localhost:5173"),
PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("PUBLIC_URL")), "/"),
SessionCookie: envOr("SESSION_COOKIE", "mediacollection_session"),
SessionCookie: envOr("SESSION_COOKIE", "session"),
SecureCookies: envBool("COOKIE_SECURE", os.Getenv("TLS_CERT_FILE") != ""),
AuthGuardURL: strings.TrimSpace(os.Getenv("AUTHGUARD_URL")),
InternalServiceSecret: strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET")),
@@ -105,7 +105,7 @@ func Load() (*Config, error) {
YTDLP: envOr("YT_DLP_PATH", "yt-dlp"),
ComfyURL: strings.TrimRight(envOr("COMFYUI_URL", "http://127.0.0.1:8188"), "/"),
AnalyzerModelsURL: strings.TrimRight(envOr("ANALYZER_MODELS_URL", "http://127.0.0.1:8801"), "/"),
ServantURL: strings.TrimRight(envOr("SERVANT_URL", "http://127.0.0.1:3003"), "/"),
CarrierNodeURL: strings.TrimRight(envOr("CARRIERNODE_URL", "http://127.0.0.1:3003"), "/"),
MaxUploadBytes: maxUpload,
TLSCertFile: strings.TrimSpace(os.Getenv("TLS_CERT_FILE")),
TLSKeyFile: strings.TrimSpace(os.Getenv("TLS_KEY_FILE")),
@@ -128,14 +128,14 @@ func normalizeService(value string) Service {
return Tools
case "analyzer", "mediaanalyzer":
return Analyzer
case "config", "mediaconfig":
case "config", "mediaconfig", "projectconfigurator":
return ConfigService
case "moderator", "mediamoderator":
return Moderator
case "kiosk", "mediakiosk":
return Kiosk
case "servant", "mediaservant":
return Servant
case "carriernode":
return CarrierNode
default:
return ""
}
@@ -150,15 +150,15 @@ func serviceName(service Service) string {
case Analyzer:
return "MediaAnalyzer"
case ConfigService:
return "MediaConfig"
return "ProjectConfigurator"
case Moderator:
return "MediaModerator"
case Kiosk:
return "MediaKiosk"
case Servant:
return "MediaServant"
case CarrierNode:
return "CarrierNode"
default:
return "MediaCollection"
return "Shared Service"
}
}
@@ -168,7 +168,7 @@ func defaultPort(service Service) string {
return "3005"
case Moderator:
return "8090"
case Servant:
case CarrierNode:
return "3003"
default:
return "3000"
@@ -11,6 +11,7 @@ import (
"net/url"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
@@ -18,6 +19,8 @@ import (
"time"
"github.com/go-chi/chi/v5"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
)
func (s *Server) mountConfigRoutes(r chi.Router) {
@@ -25,6 +28,9 @@ func (s *Server) mountConfigRoutes(r chi.Router) {
admin.Get("/settings", s.settings)
admin.Post("/settings", s.saveSettings)
admin.Post("/check-connection", s.checkConnection)
admin.Post("/discover-service", s.discoverService)
admin.Post("/settings/sync", s.settingsSync)
r.With(s.internalServiceAuth).Get("/settings/export", s.settingsExport)
r.Get("/info", s.configInfo)
r.With(s.internalServiceAuth).Get("/mounts/paths", s.mountPaths)
admin.Post("/mounts/paths", s.saveMountPaths)
@@ -77,6 +83,151 @@ func (s *Server) saveSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"success": true, "updated": count})
}
// settingsExport is the full-fidelity counterpart to settings: every row (sensitive ones
// included, since this is only ever reachable with the shared X-Internal-Auth secret) plus each
// key's updated_at, so a peer ProjectConfigurator instance can merge it with its own by recency.
// This is what makes running more than one ProjectConfigurator instance for high availability
// actually converge, whether or not the instances share a single Postgres database.
func (s *Server) settingsExport(w http.ResponseWriter, r *http.Request) {
rows, err := s.db.Query(r.Context(), `SELECT key, COALESCE(value, ''), updated_at FROM settings ORDER BY key`)
if err != nil {
writeError(w, http.StatusInternalServerError, "settings unavailable")
return
}
defer rows.Close()
values := map[string]any{}
for rows.Next() {
var key, value string
var updatedAt time.Time
if rows.Scan(&key, &value, &updatedAt) != nil {
continue
}
values[key] = map[string]any{"value": value, "updatedAt": updatedAt}
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "settings": values})
}
// projectConfiguratorPeers reads the other ProjectConfigurator instances an operator has
// registered in the Projects workspace's Central services section (configured_central, the same
// setting regularProjects/centralInstancesFor reads client-side) - every instance whose base name
// is "ProjectConfigurator" except the unsuffixed entry, which by convention represents this
// instance itself rather than a remote peer.
func (s *Server) projectConfiguratorPeers(ctx context.Context) []string {
raw := s.settingValue(ctx, "configured_central", "")
var central []string
if raw == "" || json.Unmarshal([]byte(raw), &central) != nil {
return nil
}
peers := make([]string, 0, len(central))
for _, project := range central {
key := strings.ToLower(strings.TrimSpace(project))
if key == "" || key == "projectconfigurator" || instanceBaseKey(key) != "projectconfigurator" {
continue
}
if peerURL := strings.TrimSpace(s.settingValue(ctx, key+"_url", "")); peerURL != "" {
peers = append(peers, peerURL)
}
}
return peers
}
// pullSettingsFrom fetches one peer's full settings export and applies every key that peer last
// touched more recently than this instance did - last-write-wins per key, the same rule
// saveSettings already applies within a single instance, just extended across instances.
func (s *Server) pullSettingsFrom(ctx context.Context, peerURL string) (int, error) {
target, err := normalizeServiceURL(peerURL)
if err != nil {
return 0, err
}
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
request, err := http.NewRequestWithContext(reqCtx, http.MethodGet, strings.TrimRight(target, "/")+"/api/settings/export", nil)
if err != nil {
return 0, err
}
if s.cfg.InternalServiceSecret != "" {
request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
return 0, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return 0, fmt.Errorf("peer returned status %d", response.StatusCode)
}
var body struct {
Settings map[string]struct {
Value string `json:"value"`
UpdatedAt time.Time `json:"updatedAt"`
} `json:"settings"`
}
if err := json.NewDecoder(io.LimitReader(response.Body, 4<<20)).Decode(&body); err != nil {
return 0, err
}
updated := 0
for key, remote := range body.Settings {
key = strings.TrimSpace(key)
if key == "" || len(key) > 160 {
continue
}
result, err := s.db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,$3)
ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=EXCLUDED.updated_at
WHERE settings.updated_at < EXCLUDED.updated_at`, key, remote.Value, remote.UpdatedAt)
if err != nil {
continue
}
if result.RowsAffected() > 0 {
updated++
}
}
return updated, nil
}
// settingsSync is the "Sync now" button's endpoint: pull every registered ProjectConfigurator
// peer's settings on demand, on top of the periodic background sync (runSettingsSyncScheduler).
func (s *Server) settingsSync(w http.ResponseWriter, r *http.Request) {
peers := s.projectConfiguratorPeers(r.Context())
results := make([]map[string]any, 0, len(peers))
updated := 0
for _, peer := range peers {
count, err := s.pullSettingsFrom(r.Context(), peer)
result := map[string]any{"url": peer}
if err != nil {
result["ok"] = false
result["error"] = err.Error()
} else {
result["ok"] = true
result["updated"] = count
updated += count
}
results = append(results, result)
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "peers": len(peers), "updated": updated, "results": results})
}
// runSettingsSyncScheduler periodically pulls every registered peer's settings so multiple
// ProjectConfigurator instances converge on their own, without an operator needing to click
// "Sync now" - the actual high-availability behavior. Only started for the config service (see
// Run). A fresh deployment with no peers registered yet just polls configured_central and finds
// nothing to do each tick, which is cheap enough not to bother special-casing.
func (s *Server) runSettingsSyncScheduler(ctx context.Context) {
ticker := time.NewTicker(2 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
for _, peer := range s.projectConfiguratorPeers(ctx) {
if _, err := s.pullSettingsFrom(ctx, peer); err != nil {
log.Printf("settings sync: pulling from %s: %v", peer, err)
}
}
}
}
}
func (s *Server) checkConnection(w http.ResponseWriter, r *http.Request) {
var input struct {
URL string `json:"url"`
@@ -117,7 +268,119 @@ func (s *Server) configInfo(w http.ResponseWriter, r *http.Request) {
if s.cfg.PublicURL != "" {
host = s.cfg.PublicURL
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "hostname": host, "port": s.cfg.Port, "url": host})
writeJSON(w, http.StatusOK, map[string]any{
"ok": true, "hostname": host, "port": s.cfg.Port, "url": host,
"name": s.cfg.ServiceName, "service": s.cfg.ServiceName,
"tabs": serviceTabs(s.cfg.Service), "mountTypes": serviceMountTypes(s.cfg.Service),
})
}
// tabOption mirrors one entry of a project's nav (see webui's app-config.ts) plus the
// global About dialog every instance exposes - the set of "pages" ProjectConfigurator's Projects
// workspace lets an operator require login for individually.
type tabOption struct {
Label string `json:"label"`
Token string `json:"token"`
}
// serviceTabsByService mirrors webui/src/lib/app-config.ts's nav per Service, plus the
// About dialog (AppShell.svelte, not itself part of app.nav). Kept in sync by hand - there is no
// single source of truth shared between the Go backend and the SvelteKit frontend for this.
var serviceTabsByService = map[config.Service][]tabOption{
config.Viewer: {
{"Library", "/"}, {"Feed", "/feed"}, {"Tags", "/tags"}, {"Playlists", "/playlists"}, {"About", "/about"},
},
config.Tools: {
{"Generator", "/"}, {"Downloader", "/downloader"}, {"Converter", "/converter"},
{"Schedules", "/schedules"}, {"Library", "/library"}, {"About", "/about"},
},
config.Analyzer: {
{"Dashboard", "/"}, {"Discover", "/discover"}, {"Images", "/images"}, {"Videos", "/videos"},
{"Audios", "/audios"}, {"Funscripts", "/funscripts"}, {"Schedules", "/schedules"}, {"About", "/about"},
},
config.ConfigService: {{"Projects", "/"}, {"About", "/about"}},
config.Moderator: {
{"Dashboard", "/"}, {"Users", "/users"}, {"Media", "/media"}, {"About", "/about"},
},
config.Kiosk: {{"Kiosk", "/"}, {"About", "/about"}},
config.CarrierNode: {{"Overview", "/"}, {"Files", "/files"}, {"About", "/about"}},
}
// serviceMountTypesByService mirrors ConfigWorkspace.svelte's PROJECT_AVAILABLE_MOUNTS - the
// mount "type" values each service's own tab accepts when configuring its mounts.
var serviceMountTypesByService = map[config.Service][]string{
config.Viewer: {"media", "thumbnails", "funscripts"},
config.Tools: {"downloads", "generated", "converted", "converter input", "generator input", "generator copy"},
config.Analyzer: {"images", "videos", "audios", "funscripts", "models", "thumbnails"},
config.Moderator: {"media", "thumbnails"},
config.Kiosk: {"media"},
config.CarrierNode: {"media", "output"},
config.ConfigService: {},
}
func serviceTabs(service config.Service) []tabOption {
if tabs, ok := serviceTabsByService[service]; ok {
return tabs
}
return []tabOption{{"Main", "/"}, {"About", "/about"}}
}
func serviceMountTypes(service config.Service) []string {
if types, ok := serviceMountTypesByService[service]; ok {
return types
}
return []string{}
}
// discoverService lets ProjectConfigurator's Projects workspace populate a new service's name,
// tabs, and mount types from just its URL: it fetches the target's own public GET /api/info
// server-side (avoiding a browser CORS round-trip, same reasoning as checkConnection) and relays
// whatever it reports. A target that doesn't implement this yet (or is unreachable) reports
// {"ok":false} so the caller can fall back to manual entry instead of erroring out.
func (s *Server) discoverService(w http.ResponseWriter, r *http.Request) {
var input struct {
URL string `json:"url"`
}
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
target, err := normalizeServiceURL(input.URL)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(target, "/")+"/api/info", nil)
response, err := http.DefaultClient.Do(request)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "unreachable"})
return
}
defer response.Body.Close()
var body struct {
OK bool `json:"ok"`
Name string `json:"name"`
Service string `json:"service"`
Tabs []tabOption `json:"tabs"`
MountTypes []string `json:"mountTypes"`
}
if response.StatusCode >= 300 || json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&body) != nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "invalid response"})
return
}
name := strings.TrimSpace(body.Name)
if name == "" {
name = strings.TrimSpace(body.Service)
}
if name == "" {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "service did not report a name"})
return
}
writeJSON(w, http.StatusOK, map[string]any{
"ok": true, "name": name, "tabs": body.Tabs, "mountTypes": body.MountTypes,
})
}
func (s *Server) mountPaths(w http.ResponseWriter, r *http.Request) {
@@ -191,15 +454,15 @@ func (s *Server) resolveMount(w http.ResponseWriter, r *http.Request) {
}
// mountEntry mirrors WebUI's ConfigWorkspace.svelte MountEntry ({type, path}) - one row in a
// project's mount list in MediaConfig's Mounts workspace.
// project's mount list in ProjectConfigurator's Projects workspace.
type mountEntry struct {
Type string `json:"type"`
Path string `json:"path"`
}
// configuredMounts parses the configured_mounts setting - the live source MediaConfig's Mounts
// workspace actually saves to (see ConfigWorkspace.svelte's buildPayload) - into project key ->
// mount entries. Returns nil if unset or malformed.
// configuredMounts parses the configured_mounts setting - the live source ProjectConfigurator's
// Projects workspace actually saves to (see ConfigWorkspace.svelte's buildPayload) - into project
// key -> mount entries. Returns nil if unset or malformed.
func (s *Server) configuredMounts(ctx context.Context) map[string][]mountEntry {
raw := s.settingValue(ctx, "configured_mounts", "")
if raw == "" {
@@ -213,9 +476,9 @@ func (s *Server) configuredMounts(ctx context.Context) map[string][]mountEntry {
}
// mountMappings returns each project's mount configuration as project -> mount type -> path(s),
// the shape /mounts/resolve and /mounts/paths (and MediaServant's own "Mount health" panel via
// the shape /mounts/resolve and /mounts/paths (and CarrierNode's own "Mount health" panel via
// /mounts) expect. configured_mounts is the live source and wins per-project when present;
// mounts_path_mappings is an older format nothing has written since the Mounts workspace moved
// mounts_path_mappings is an older format nothing has written since the Projects workspace moved
// to configured_mounts, kept only so a deployment that hasn't resaved its mounts since upgrading
// doesn't lose data it already had. Keys are used as stored, not case-normalized - configured_mounts
// is processed first so a legacy entry for a project already covered there (under the exact same
@@ -270,13 +533,13 @@ func (s *Server) mountMappings(ctx context.Context) map[string]any {
return mappings
}
// mediaLibraryMountTypes are the mount "type" values MediaConfig's Mounts workspace (the
// mediaLibraryMountTypes are the mount "type" values ProjectConfigurator's Projects workspace (the
// configured_mounts setting) accepts that describe an actual media-library directory, as
// opposed to a project-specific working directory like "downloads", "generated",
// "thumbnails", or "models", which have their own dedicated Root config fields instead and
// are deliberately left out here. A path is entered under whichever project's tab happens to
// need it (MediaAnalyzer's "images"/"videos"/"audios", MediaViewer/MediaKiosk's "media", ...)
// but they're all describing locations MediaServant itself has to walk, since it's the only
// but they're all describing locations CarrierNode itself has to walk, since it's the only
// service with the volume mounted - see effectiveMediaRoots.
var mediaLibraryMountTypes = map[string]bool{
"media": true, "images": true, "videos": true, "audios": true, "funscripts": true,
@@ -304,11 +567,11 @@ func (s *Server) mediaRootsFromMounts(ctx context.Context) []string {
return roots
}
// effectiveMediaRoots is what Servant actually walks and resolves files under: the static
// effectiveMediaRoots is what CarrierNode actually walks and resolves files under: the static
// MEDIA_ROOTS/MEDIA_ROOT env config (if any) plus every media-library path configured through
// MediaConfig's Mounts workspace, deduped. Settings are read fresh from the DB on every call
// (no caching, same as mediaservant_url/servantBaseURL), so a mount saved in MediaConfig takes
// effect on Servant's very next request - no reload or restart needed.
// ProjectConfigurator's Projects workspace, deduped. Settings are read fresh from the DB on every
// call (no caching, same as carriernode_url/carrierNodeBaseURL), so a mount saved in
// ProjectConfigurator takes effect on CarrierNode's very next request - no reload or restart needed.
func (s *Server) effectiveMediaRoots(ctx context.Context) []string {
seen := map[string]bool{}
roots := make([]string, 0, len(s.cfg.MediaRoots))
@@ -510,32 +773,158 @@ func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"users": users, "media": media, "likes": likes, "views": views})
}
func (s *Server) mountServantRoutes(r chi.Router) {
r.Get("/stats", s.servantStats)
r.Get("/mounts", s.servantMounts)
r.Get("/files/recent", s.servantRecentFiles)
r.Get("/files", s.servantFiles)
r.Get("/files/count", s.servantFileCount)
r.Get("/folders", s.servantFolders)
r.Get("/browse", s.servantBrowse)
r.Get("/watch", s.servantWatch)
r.With(s.internalServiceAuth).Get("/downloads", s.servantDownloads)
r.With(s.internalServiceAuth).Post("/reload-mounts", s.servantReloadMounts)
r.With(s.internalServiceAuth).Get("/probe", s.servantProbeFile)
func (s *Server) mountCarrierNodeRoutes(r chi.Router) {
r.Get("/stats", s.carrierNodeStats)
r.Get("/mounts", s.carrierNodeMounts)
r.Get("/files/recent", s.carrierNodeRecentFiles)
r.Get("/files", s.carrierNodeFiles)
r.Get("/files/count", s.carrierNodeFileCount)
r.Get("/folders", s.carrierNodeFolders)
r.Get("/browse", s.carrierNodeBrowse)
r.Get("/watch", s.carrierNodeWatch)
r.With(s.internalServiceAuth).Get("/downloads", s.carrierNodeDownloads)
r.With(s.internalServiceAuth).Post("/reload-mounts", s.carrierNodeReloadMounts)
r.With(s.internalServiceAuth).Get("/probe", s.carrierNodeProbeFile)
protected := r.With(s.auth.Optional, s.requireAdminOrInternal)
protected.Post("/upload", s.servantUpload)
protected.Post("/upload-mounted", s.servantUpload)
protected.Delete("/downloads/{filename}", s.servantDeleteDownload)
protected.Post("/store", s.servantStore)
protected.Post("/upload", s.carrierNodeUpload)
protected.Post("/upload-mounted", s.carrierNodeUpload)
protected.Delete("/downloads/{filename}", s.carrierNodeDeleteDownload)
protected.Post("/store", s.carrierNodeStore)
internal := r.With(s.internalServiceAuth)
internal.Post("/thumbnails/{id}", s.servantThumbnailUpload)
internal.Delete("/thumbnails/{id}", s.servantThumbnailDelete)
internal.Post("/outputs/{name}", s.servantOutputUpload)
internal.Post("/inputs/{name}", s.servantInputUpload)
internal.Post("/copies/{name}", s.servantCopyUpload)
internal.Post("/thumbnails/{id}", s.carrierNodeThumbnailUpload)
internal.Delete("/thumbnails/{id}", s.carrierNodeThumbnailDelete)
internal.Post("/outputs/{name}", s.carrierNodeOutputUpload)
internal.Post("/inputs/{name}", s.carrierNodeInputUpload)
internal.Post("/copies/{name}", s.carrierNodeCopyUpload)
// Generic, project-agnostic mount access: any project registered in
// ProjectConfigurator's Projects workspace with a mount path configured under
// {type} can read/list/write/delete files there, not just the handful of
// hardcoded media-family routes above (/media, /mount/generated, /thumbnails, ...).
// See carrierNodeMountRoots's doc comment for why no cross-service call is needed.
internal.Get("/mount/{project}/{type}", s.carrierNodeListMount)
internal.Get("/mount/{project}/{type}/*", s.carrierNodeMountFile)
internal.Post("/mount/{project}/{type}/*", s.carrierNodeMountUpload)
internal.Delete("/mount/{project}/{type}/*", s.carrierNodeMountDelete)
}
func (s *Server) servantStats(w http.ResponseWriter, r *http.Request) {
// carrierNodeMountRoots resolves every root path registered for {project, type} through
// ProjectConfigurator's Projects workspace (the same configured_mounts setting
// /api/mounts/resolve serves) - not limited to the media-family's own hardcoded mount
// categories (media/output/generated/...), any project name and any mount type an
// operator has configured there works. No HTTP call to ProjectConfigurator is needed: every
// MEDIA_SERVICE instance, CarrierNode included, reads the same settings table directly (see
// mountMappings), the same way effectiveMediaRoots already resolves CarrierNode's own roots.
func (s *Server) carrierNodeMountRoots(ctx context.Context, project, mountType string) []string {
mappings := s.mountMappings(ctx)
projectValue, ok := mappings[project]
if !ok {
for key, value := range mappings {
if strings.EqualFold(key, project) {
projectValue, ok = value, true
break
}
}
}
if !ok {
return nil
}
functions, ok := projectValue.(map[string]any)
if !ok {
return nil
}
value, ok := functions[mountType]
if !ok {
for key, candidate := range functions {
if strings.EqualFold(key, mountType) {
value, ok = candidate, true
break
}
}
}
if !ok {
return nil
}
return normalizeMappingPaths(value)
}
// carrierNodeListMount lists the files directly under every root configured for
// {project, type} (non-recursive - each root is typically a flat upload/output directory).
func (s *Server) carrierNodeListMount(w http.ResponseWriter, r *http.Request) {
project := chi.URLParam(r, "project")
mountType := chi.URLParam(r, "type")
roots := s.carrierNodeMountRoots(r.Context(), project, mountType)
if len(roots) == 0 {
writeError(w, http.StatusNotFound, "no mount configured for this project/type")
return
}
entries := make([]map[string]any, 0)
for _, root := range roots {
items, err := os.ReadDir(root)
if err != nil {
continue
}
for _, item := range items {
if item.IsDir() {
continue
}
info, err := item.Info()
if err != nil {
continue
}
entries = append(entries, map[string]any{"name": item.Name(), "size": info.Size(), "modifiedAt": info.ModTime()})
}
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "project": project, "type": mountType, "files": entries})
}
// carrierNodeMountFile downloads one file by relative path from {project, type}'s mount.
func (s *Server) carrierNodeMountFile(w http.ResponseWriter, r *http.Request) {
roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type"))
if len(roots) == 0 {
writeError(w, http.StatusNotFound, "no mount configured for this project/type")
return
}
full, err := s.resolveUnderRoots(chi.URLParam(r, "*"), roots)
if err != nil {
writeError(w, http.StatusNotFound, "file not found")
return
}
s.serveFile(w, r, full)
}
// carrierNodeMountUpload stores the request body as a file under {project, type}'s first
// configured root. Like carrierNodeStreamUpload (which this delegates to), the destination
// filename is flattened to its base name - no subdirectories.
func (s *Server) carrierNodeMountUpload(w http.ResponseWriter, r *http.Request) {
roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type"))
if len(roots) == 0 {
writeError(w, http.StatusNotFound, "no mount configured for this project/type")
return
}
s.carrierNodeStreamUpload(w, r, roots[0], chi.URLParam(r, "*"))
}
// carrierNodeMountDelete removes one file by relative path from {project, type}'s mount.
func (s *Server) carrierNodeMountDelete(w http.ResponseWriter, r *http.Request) {
roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type"))
if len(roots) == 0 {
writeError(w, http.StatusNotFound, "no mount configured for this project/type")
return
}
full, err := s.resolveUnderRoots(chi.URLParam(r, "*"), roots)
if err != nil {
writeError(w, http.StatusNotFound, "file not found")
return
}
if err := os.Remove(full); err != nil {
writeError(w, http.StatusInternalServerError, "file could not be removed")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) carrierNodeStats(w http.ResponseWriter, r *http.Request) {
files := s.walkFiles(r.Context(), "")
roots := s.effectiveMediaRoots(r.Context())
byType := map[string]int{"image": 0, "video": 0, "audio": 0, "other": 0}
@@ -546,7 +935,7 @@ func (s *Server) servantStats(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "stats": stats, "bandwidth": map[string]any{"bytesOut": 0, "requests": 0}, "count": len(files), "total": len(files), "active": len(roots), "files": byType, "roots": roots})
}
func (s *Server) servantMounts(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeMounts(w http.ResponseWriter, r *http.Request) {
roots := s.effectiveMediaRoots(r.Context())
writeJSON(w, http.StatusOK, map[string]any{"mappings": s.mountMappings(r.Context()), "roots": roots, "count": len(roots)})
}
@@ -559,18 +948,18 @@ type fileEntry struct {
Mtime int64 `json:"mtime"`
}
func (s *Server) servantRecentFiles(w http.ResponseWriter, r *http.Request) {
s.writeServantFiles(w, r, true)
func (s *Server) carrierNodeRecentFiles(w http.ResponseWriter, r *http.Request) {
s.writeCarrierNodeFiles(w, r, true)
}
func (s *Server) servantFiles(w http.ResponseWriter, r *http.Request) {
s.writeServantFiles(w, r, false)
func (s *Server) carrierNodeFiles(w http.ResponseWriter, r *http.Request) {
s.writeCarrierNodeFiles(w, r, false)
}
func (s *Server) servantFileCount(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeFileCount(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "count": len(s.walkFiles(r.Context(), r.URL.Query().Get("path")))})
}
func (s *Server) writeServantFiles(w http.ResponseWriter, r *http.Request, recent bool) {
func (s *Server) writeCarrierNodeFiles(w http.ResponseWriter, r *http.Request, recent bool) {
files := s.walkFiles(r.Context(), r.URL.Query().Get("path"))
if recent {
sort.Slice(files, func(i, j int) bool { return files[i].Mtime > files[j].Mtime })
@@ -588,7 +977,7 @@ func (s *Server) writeServantFiles(w http.ResponseWriter, r *http.Request, recen
writeJSON(w, http.StatusOK, map[string]any{"files": files, "items": files, "total": len(files)})
}
func (s *Server) servantFolders(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeFolders(w http.ResponseWriter, r *http.Request) {
seen := map[string]bool{}
for _, file := range s.walkFiles(r.Context(), r.URL.Query().Get("path")) {
seen[filepath.Dir(file.Rel)] = true
@@ -601,9 +990,9 @@ func (s *Server) servantFolders(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"folders": folders})
}
func (s *Server) servantBrowse(w http.ResponseWriter, r *http.Request) { s.servantFiles(w, r) }
func (s *Server) carrierNodeBrowse(w http.ResponseWriter, r *http.Request) { s.carrierNodeFiles(w, r) }
func (s *Server) servantWatch(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeWatch(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
_, _ = io.WriteString(w, "event: ready\ndata: {\"ok\":true}\n\n")
@@ -613,11 +1002,11 @@ func (s *Server) servantWatch(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done()
}
func (s *Server) servantReloadMounts(w http.ResponseWriter, _ *http.Request) {
func (s *Server) carrierNodeReloadMounts(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Server) servantDownloads(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeDownloads(w http.ResponseWriter, r *http.Request) {
limit := optionalInt(r.URL.Query().Get("limit"), 500, 1, 1000)
rows, err := s.db.Query(r.Context(), `SELECT file_name, file_path, media_type, source_url, file_size_bytes, created_at FROM downloaded_media WHERE file_name IS NOT NULL ORDER BY created_at DESC LIMIT $1`, limit)
if err != nil {
@@ -639,8 +1028,9 @@ func (s *Server) servantDownloads(w http.ResponseWriter, r *http.Request) {
}
// walkRootTimeout bounds how long a single root's filesystem walk can run before walkFiles gives
// up on it. effectiveMediaRoots now includes every media-library path configured in MediaConfig's
// Mounts workspace across every project, not just the operator's own verified MEDIA_ROOTS - a
// up on it. effectiveMediaRoots now includes every media-library path configured in
// ProjectConfigurator's Projects workspace across every project, not just the operator's own
// verified MEDIA_ROOTS - a
// typo'd path or a mount that isn't actually reachable from this container (an unresponsive
// network share, say) would otherwise be able to hang every caller of walkFiles (discovery,
// /api/stats, browsing) indefinitely, since a blocked stat/readdir syscall can't be interrupted by
@@ -680,7 +1070,7 @@ func (s *Server) walkFiles(ctx context.Context, relative string) []fileEntry {
case found := <-done:
result = append(result, found...)
case <-time.After(walkRootTimeout):
log.Printf("servant: walking root %q took too long (>%s) - skipping it for this request, it may be an unreachable mount", root, walkRootTimeout)
log.Printf("carriernode: walking root %q took too long (>%s) - skipping it for this request, it may be an unreachable mount", root, walkRootTimeout)
case <-ctx.Done():
return result
}
@@ -688,9 +1078,9 @@ func (s *Server) walkFiles(ctx context.Context, relative string) []fileEntry {
return result
}
func (s *Server) servantUpload(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeUpload(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/") {
s.servantRawUpload(w, r)
s.carrierNodeRawUpload(w, r)
return
}
if s.cfg.MaxUploadBytes > 0 {
@@ -729,7 +1119,7 @@ func (s *Server) servantUpload(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "filename": name, "path": name})
}
func (s *Server) servantDeleteDownload(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeDeleteDownload(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "filename")
if !safeRelative(name) {
writeError(w, http.StatusBadRequest, "invalid filename")
@@ -747,7 +1137,7 @@ func (s *Server) servantDeleteDownload(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Server) servantStore(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeStore(w http.ResponseWriter, r *http.Request) {
var input map[string]any
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
@@ -784,8 +1174,8 @@ func (s *Server) servantStore(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaKey": mediaKey, "mediaId": mediaID})
}
// resolveStoreFile is Servant's own local-filesystem lookup for /api/store, which catalogs a
// file MediaTools already pushed into one of Servant's mounts (InputRoot, MediaRoots,
// resolveStoreFile is CarrierNode's own local-filesystem lookup for /api/store, which catalogs a
// file MediaTools already pushed into one of CarrierNode's mounts (InputRoot, MediaRoots,
// DownloadsRoot, OutputRoot) - unlike everything else in this file, it's called with a path that
// isn't necessarily under MediaRoots, so it can't just use resolveMediaPath.
func (s *Server) resolveStoreFile(value string) (string, error) {
@@ -820,7 +1210,7 @@ func (s *Server) resolveStoreFile(value string) (string, error) {
return "", os.ErrNotExist
}
func (s *Server) servantRawUpload(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeRawUpload(w http.ResponseWriter, r *http.Request) {
name := filepath.Base(strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("filename"), r.URL.Query().Get("file_name"))))
if name == "." || name == "" || !safeRelative(name) || strings.ContainsAny(name, `<>:"|?*`) {
writeError(w, http.StatusBadRequest, "valid filename query parameter is required")
@@ -880,7 +1270,7 @@ func infoSize(info os.FileInfo) int64 {
return info.Size()
}
func (s *Server) servantMedia(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeMedia(w http.ResponseWriter, r *http.Request) {
relative := chi.URLParam(r, "*")
if relative == "" {
relative = strings.TrimPrefix(r.URL.Path, "/media/")
@@ -893,7 +1283,7 @@ func (s *Server) servantMedia(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
func (s *Server) servantDownloadMedia(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeDownloadMedia(w http.ResponseWriter, r *http.Request) {
relative := strings.TrimPrefix(r.URL.Path, "/media/downloads/")
full, err := s.resolveUnderRoots(relative, []string{s.cfg.DownloadsRoot})
if err != nil {
@@ -903,7 +1293,7 @@ func (s *Server) servantDownloadMedia(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
func (s *Server) servantGeneratedMedia(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeGeneratedMedia(w http.ResponseWriter, r *http.Request) {
relative := strings.TrimPrefix(r.URL.Path, "/mount/generated/")
full, err := s.resolveUnderRoots(relative, []string{s.cfg.OutputRoot})
if err != nil {
@@ -913,7 +1303,7 @@ func (s *Server) servantGeneratedMedia(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
func (s *Server) servantThumbnail(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeThumbnail(w http.ResponseWriter, r *http.Request) {
relative := chi.URLParam(r, "*")
if relative == "" {
relative = strings.TrimPrefix(r.URL.Path, "/thumbnails/")
@@ -926,7 +1316,7 @@ func (s *Server) servantThumbnail(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
func (s *Server) servantInputMedia(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeInputMedia(w http.ResponseWriter, r *http.Request) {
relative := strings.TrimPrefix(r.URL.Path, "/mount/inputs/")
full, err := s.resolveUnderRoots(relative, []string{s.cfg.InputRoot})
if err != nil {
@@ -936,7 +1326,7 @@ func (s *Server) servantInputMedia(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
func (s *Server) servantCopyMedia(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeCopyMedia(w http.ResponseWriter, r *http.Request) {
relative := strings.TrimPrefix(r.URL.Path, "/mount/copies/")
full, err := s.resolveUnderRoots(relative, []string{s.cfg.CopyRoot})
if err != nil {
@@ -946,11 +1336,11 @@ func (s *Server) servantCopyMedia(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
// servantStreamUpload writes a raw request body into root/name, used by every internal
// carrierNodeStreamUpload writes a raw request body into root/name, used by every internal
// push-result endpoint (thumbnails, outputs, inputs, copies). name is always reduced to its
// base component - callers never need nested directories, and this keeps every write flat and
// trivially contained within root (mirrors servantRawUpload's existing filename handling).
func (s *Server) servantStreamUpload(w http.ResponseWriter, r *http.Request, root, name string) {
// trivially contained within root (mirrors carrierNodeRawUpload's existing filename handling).
func (s *Server) carrierNodeStreamUpload(w http.ResponseWriter, r *http.Request, root, name string) {
name = filepath.Base(strings.TrimSpace(name))
if name == "." || name == "" || !safeRelative(name) || strings.ContainsAny(name, `<>:"|?*`) {
writeError(w, http.StatusBadRequest, "invalid filename")
@@ -983,16 +1373,16 @@ func (s *Server) servantStreamUpload(w http.ResponseWriter, r *http.Request, roo
writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "name": name, "size": written})
}
func (s *Server) servantThumbnailUpload(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeThumbnailUpload(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
if !safeRelative(id) || strings.ContainsAny(id, `/\`) {
writeError(w, http.StatusBadRequest, "invalid thumbnail id")
return
}
s.servantStreamUpload(w, r, s.cfg.ThumbnailRoot, id+".jpg")
s.carrierNodeStreamUpload(w, r, s.cfg.ThumbnailRoot, id+".jpg")
}
func (s *Server) servantThumbnailDelete(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeThumbnailDelete(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
if !safeRelative(id) || strings.ContainsAny(id, `/\`) {
writeError(w, http.StatusBadRequest, "invalid thumbnail id")
@@ -1004,19 +1394,19 @@ func (s *Server) servantThumbnailDelete(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Server) servantOutputUpload(w http.ResponseWriter, r *http.Request) {
s.servantStreamUpload(w, r, s.cfg.OutputRoot, chi.URLParam(r, "name"))
func (s *Server) carrierNodeOutputUpload(w http.ResponseWriter, r *http.Request) {
s.carrierNodeStreamUpload(w, r, s.cfg.OutputRoot, chi.URLParam(r, "name"))
}
func (s *Server) servantInputUpload(w http.ResponseWriter, r *http.Request) {
s.servantStreamUpload(w, r, s.cfg.InputRoot, chi.URLParam(r, "name"))
func (s *Server) carrierNodeInputUpload(w http.ResponseWriter, r *http.Request) {
s.carrierNodeStreamUpload(w, r, s.cfg.InputRoot, chi.URLParam(r, "name"))
}
func (s *Server) servantCopyUpload(w http.ResponseWriter, r *http.Request) {
s.servantStreamUpload(w, r, s.cfg.CopyRoot, chi.URLParam(r, "name"))
func (s *Server) carrierNodeCopyUpload(w http.ResponseWriter, r *http.Request) {
s.carrierNodeStreamUpload(w, r, s.cfg.CopyRoot, chi.URLParam(r, "name"))
}
func (s *Server) servantProbeFile(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeProbeFile(w http.ResponseWriter, r *http.Request) {
full, err := s.resolveAnyMediaPath(r.Context(), r.URL.Query().Get("path"))
if err != nil {
writeError(w, http.StatusNotFound, "file not found")
@@ -1079,6 +1469,15 @@ func fileType(value string) string {
}
}
// trailingInstanceSuffix strips a "_2", "_3", ... instance suffix, mirroring
// ConfigWorkspace.svelte's getBaseProject - the same "AuthGuard" / "AuthGuard_2" / "AuthGuard_3"
// naming convention every multi-instance central/main service in the Projects workspace uses.
var trailingInstanceSuffix = regexp.MustCompile(`_\d+$`)
func instanceBaseKey(key string) string {
return trailingInstanceSuffix.ReplaceAllString(key, "")
}
func sensitiveSetting(key string) bool {
switch strings.ToLower(key) {
case "session_secret", "internal_service_secret", "smtp_pass":
@@ -18,7 +18,7 @@ import (
"github.com/go-chi/chi/v5"
"mediacollection/internal/config"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
)
func (s *Server) mountAnalyzerRoutes(r chi.Router) {
@@ -147,7 +147,7 @@ func (s *Server) analyzerStatus(w http.ResponseWriter, r *http.Request) {
running := clear.Running || scan.Running || thumbnail.Running || analysis.Running || processing > 0
// scan/clear have no dedicated status endpoint of their own (thumbnail/analysis do, via
// generate/status and analyze/status) - this is the only place their LastError ever reaches
// the UI, so a discover/metadata/cleanup run that fails fast (e.g. MediaServant unreachable)
// the UI, so a discover/metadata/cleanup run that fails fast (e.g. CarrierNode unreachable)
// is reported here instead of just looking like it silently reverted to idle.
lastError := firstNonEmpty(scan.LastError, clear.LastError)
@@ -925,7 +925,7 @@ func (s *Server) createThumbnail(ctx context.Context, candidate thumbnailCandida
return "", fmt.Errorf("unsupported media type for %s", sourcePath)
}
sourceScratch, cleanupSource, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
sourceScratch, cleanupSource, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return "", fmt.Errorf("fetch %s: %w", sourcePath, err)
}
@@ -972,7 +972,7 @@ func (s *Server) createThumbnail(ctx context.Context, candidate thumbnailCandida
if err != nil || info.Size() == 0 {
return "", fmt.Errorf("ffmpeg produced no thumbnail")
}
size, err := s.servantPushThumbnail(ctx, thumbnailID, temporaryPath)
size, err := s.carrierNodePushThumbnail(ctx, thumbnailID, temporaryPath)
if err != nil {
return "", fmt.Errorf("store thumbnail: %w", err)
}
@@ -981,11 +981,11 @@ func (s *Server) createThumbnail(ctx context.Context, candidate thumbnailCandida
VALUES ($1, $2, $3)
ON CONFLICT (source_path) DO NOTHING`, thumbnailID, sourcePath, size)
if err != nil {
_ = s.servantDeleteThumbnail(ctx, thumbnailID)
_ = s.carrierNodeDeleteThumbnail(ctx, thumbnailID)
return "", fmt.Errorf("save thumbnail record: %w", err)
}
if insertTag.RowsAffected() == 0 {
_ = s.servantDeleteThumbnail(ctx, thumbnailID)
_ = s.carrierNodeDeleteThumbnail(ctx, thumbnailID)
return "", nil
}
return thumbnailID, nil
@@ -1017,7 +1017,7 @@ func (s *Server) analyzerThumb(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid thumbnail id")
return
}
s.proxyServant(w, r, "/thumbnails/"+id+".jpg")
s.proxyCarrierNode(w, r, "/thumbnails/"+id+".jpg")
}
func (s *Server) analyzerAction(w http.ResponseWriter, r *http.Request, action string) {
@@ -1255,7 +1255,7 @@ func (s *Server) cleanupStaleMedia() {
s.scan.FilesIndexed++
s.scanMu.Unlock()
if exists, _, _, err := s.probeServant(ctx, "/media/"+urlPath(item.filePath)); err == nil && exists {
if exists, _, _, err := s.probeCarrierNode(ctx, "/media/"+urlPath(item.filePath)); err == nil && exists {
continue // file still exists on disk - nothing stale about this one
}
removed++
@@ -1264,7 +1264,7 @@ func (s *Server) cleanupStaleMedia() {
var thumbnailID string
if s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, item.filePath).Scan(&thumbnailID) == nil {
_ = s.servantDeleteThumbnail(ctx, thumbnailID)
_ = s.carrierNodeDeleteThumbnail(ctx, thumbnailID)
_, _ = s.db.Exec(ctx, `DELETE FROM thumbnails WHERE id = $1`, thumbnailID)
}
_, _ = s.db.Exec(ctx, `DELETE FROM media_worker_jobs WHERE file_path = $1`, item.filePath)
@@ -1296,19 +1296,19 @@ func (s *Server) scanMediaFiles(selectedTypes map[string]bool) {
}()
batch := time.Now().UTC().Format("20060102T150405.000000000Z")
files, err := s.servantListFiles(ctx, "", false, 0)
files, err := s.carrierNodeListFiles(ctx, "", false, 0)
if err != nil {
log.Printf("analyzer: discovery scan: failed to list files: %v", err)
runErr = fmt.Errorf("could not reach MediaServant to list files: %w", err)
runErr = fmt.Errorf("could not reach CarrierNode to list files: %w", err)
return
}
// MediaServant reachable but reporting an empty library is otherwise indistinguishable from
// CarrierNode reachable but reporting an empty library is otherwise indistinguishable from
// a successful no-op run - every existing file re-indexes (and increments FilesIndexed) on
// every scan, so a real library can never legitimately finish at zero. Flag it instead of
// letting "discovery started" silently revert to idle with nothing to show for it.
if len(files) == 0 {
log.Printf("analyzer: discovery scan: MediaServant reported zero files")
runErr = fmt.Errorf("MediaServant reported no files under its configured media root(s) - check the Mounts settings in MediaConfig")
log.Printf("analyzer: discovery scan: CarrierNode reported zero files")
runErr = fmt.Errorf("CarrierNode reported no files under its configured media root(s) - check the Projects settings in ProjectConfigurator")
return
}
for _, file := range files {
@@ -1345,9 +1345,9 @@ func (s *Server) indexMediaFile(ctx context.Context, key string, size int64, mod
var width, height int
var probeErr error
var hasFunscript bool
// Servant has the storage mounted and can probe/stat locally; every other service goes
// through Servant's HTTP API instead of touching MediaRoots itself (see servant_client.go).
if s.cfg.Service == config.Servant {
// CarrierNode has the storage mounted and can probe/stat locally; every other service goes
// through CarrierNode's HTTP API instead of touching MediaRoots itself (see carriernode_client.go).
if s.cfg.Service == config.CarrierNode {
fullPath, resolveErr := s.resolveAnyMediaPath(ctx, key)
if metadataAttempted && resolveErr == nil {
var probe map[string]any
@@ -1361,8 +1361,8 @@ func (s *Server) indexMediaFile(ctx context.Context, key string, size int64, mod
hasFunscript = s.pipelineStageEnabled(ctx, "funscript", "metadata") && resolveErr == nil && hasFunscriptSidecar(fullPath)
} else {
if metadataAttempted {
var probe servantProbeResult
probe, probeErr = s.servantProbe(ctx, key)
var probe carrierNodeProbeResult
probe, probeErr = s.carrierNodeProbe(ctx, key)
duration = nullableInt64(probe.DurationMs)
width, height = probe.Width, probe.Height
}
@@ -1447,7 +1447,7 @@ func (s *Server) refreshMetadataForTypes(selectedTypes map[string]bool) {
s.scan.FilesIndexed++
s.scanMu.Unlock()
if exists, _, _, err := s.probeServant(ctx, "/media/"+urlPath(item.filePath)); err != nil || !exists {
if exists, _, _, err := s.probeCarrierNode(ctx, "/media/"+urlPath(item.filePath)); err != nil || !exists {
continue
}
@@ -1463,7 +1463,7 @@ func (s *Server) refreshMetadataForTypes(selectedTypes map[string]bool) {
if !s.pipelineStageEnabled(ctx, item.mediaType, "metadata") {
continue
}
probe, probeErr := s.servantProbe(ctx, item.filePath)
probe, probeErr := s.carrierNodeProbe(ctx, item.filePath)
if probeErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, item.filePath, probeErr.Error())
continue
@@ -1501,11 +1501,11 @@ func hasFunscriptSidecar(filePath string) bool {
}
// funscriptSidecarExists is hasFunscriptSidecar for callers without local filesystem access
// (MediaAnalyzer) - it checks for the sidecar on Servant instead of statting a local path.
// (MediaAnalyzer) - it checks for the sidecar on CarrierNode instead of statting a local path.
func (s *Server) funscriptSidecarExists(ctx context.Context, key string) bool {
base := strings.TrimSuffix(key, filepath.Ext(key))
for _, candidate := range []string{base + ".funscript", base + ".json"} {
if exists, _, _, err := s.probeServant(ctx, "/media/"+urlPath(candidate)); err == nil && exists {
if exists, _, _, err := s.probeCarrierNode(ctx, "/media/"+urlPath(candidate)); err == nil && exists {
return true
}
}
@@ -1747,7 +1747,7 @@ func (s *Server) deleteThumbnailsForType(ctx context.Context, mediaType string)
}
rows.Close()
for _, id := range ids {
_ = s.servantDeleteThumbnail(ctx, id)
_ = s.carrierNodeDeleteThumbnail(ctx, id)
}
if len(ids) > 0 {
if _, err := s.db.Exec(ctx, `DELETE FROM thumbnails WHERE id = ANY($1::uuid[])`, ids); err != nil {
@@ -1779,7 +1779,7 @@ func (s *Server) clearFunscriptFlag(ctx context.Context) error {
// picked back up fresh on the next discovery run.
func (s *Server) clearPipelineSelection(w http.ResponseWriter, r *http.Request) {
var payload struct {
Types []string `json:"types"`
Types []string `json:"types"`
Stages []string `json:"stages"`
}
if err := decodeRequestJSON(r, &payload); err != nil {
@@ -345,7 +345,7 @@ func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask)
sourcePath := filepath.ToSlash(item.filePath)
// Video frames come from an existing thumbnail when possible (see videoAnalysisFrame) rather
// than always fetching the whole video across the wire to Servant just to grab one frame.
// than always fetching the whole video across the wire to CarrierNode just to grab one frame.
if item.mediaType == "video" && item.model != "laplacian" {
framePath, cleanup, err := s.videoAnalysisFrame(ctx, sourcePath)
if err != nil {
@@ -357,7 +357,7 @@ func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask)
return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, framePath)
}
scratchPath, cleanup, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
scratchPath, cleanup, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return nil, fmt.Errorf("fetch %s: %w", item.filePath, err)
}
@@ -385,12 +385,12 @@ func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask)
func (s *Server) videoAnalysisFrame(ctx context.Context, sourcePath string) (string, func(), error) {
var thumbnailID string
if err := s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, sourcePath).Scan(&thumbnailID); err == nil {
if scratchPath, cleanup, fetchErr := s.fetchServantToScratch(ctx, "/thumbnails/"+thumbnailID+".jpg", ".jpg"); fetchErr == nil {
if scratchPath, cleanup, fetchErr := s.fetchCarrierNodeToScratch(ctx, "/thumbnails/"+thumbnailID+".jpg", ".jpg"); fetchErr == nil {
return scratchPath, cleanup, nil
}
}
videoScratch, cleanupVideo, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
videoScratch, cleanupVideo, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return "", nil, fmt.Errorf("fetch %s: %w", sourcePath, err)
}
@@ -678,7 +678,7 @@ func (s *Server) retryMetadataErrors(mediaType string) {
if ctx.Err() != nil {
return
}
if probe, probeErr := s.servantProbe(ctx, filepath.ToSlash(filePath)); probeErr != nil {
if probe, probeErr := s.carrierNodeProbe(ctx, filepath.ToSlash(filePath)); probeErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, filePath, probeErr.Error())
} else {
duration := nullableInt64(probe.DurationMs)
@@ -0,0 +1,331 @@
package server
// CarrierNode client: every non-CarrierNode service serves and stores media by calling CarrierNode's
// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/
// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. CarrierNode's own handlers keep using those
// roots directly (see media.go, admin_storage.go) - this file is never called from CarrierNode's
// own code path.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// carrierNodeHTTPClient has no blanket timeout since it streams large media files; callers bound
// individual calls with a context deadline instead.
var carrierNodeHTTPClient = &http.Client{}
func (s *Server) carrierNodeClient() *http.Client {
return carrierNodeHTTPClient
}
// carrierNodeBaseURL is configured in ProjectConfigurator and stored in the settings table (key
// "carriernode_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for
// every project's connection URL) - not a static env var, so a change in ProjectConfigurator
// takes effect on every service's very next request without a restart. CARRIERNODE_URL is only the
// bootstrap fallback before that setting has ever been saved.
func (s *Server) carrierNodeBaseURL(ctx context.Context) string {
return strings.TrimRight(s.settingValue(ctx, "carriernode_url", s.cfg.CarrierNodeURL), "/")
}
func (s *Server) newCarrierNodeRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, method, s.carrierNodeBaseURL(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 carrierNodeForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var carrierNodeForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
// proxyCarrierNode 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 (s *Server) proxyCarrierNode(w http.ResponseWriter, r *http.Request, carrierNodePath string) {
request, err := s.newCarrierNodeRequest(r.Context(), r.Method, carrierNodePath, nil)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
for _, header := range carrierNodeForwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
defer response.Body.Close()
for _, header := range carrierNodeForwardResponseHeaders {
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)
}
}
// probeCarrierNode 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 (s *Server) probeCarrierNode(ctx context.Context, carrierNodePath string) (bool, int64, time.Time, error) {
request, err := s.newCarrierNodeRequest(ctx, http.MethodHead, carrierNodePath, nil)
if err != nil {
return false, 0, time.Time{}, err
}
response, err := s.carrierNodeClient().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
}
// fetchCarrierNodeToScratch 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 (s *Server) fetchCarrierNodeToScratch(ctx context.Context, carrierNodePath, suffix string) (string, func(), error) {
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, carrierNodePath, nil)
if err != nil {
return "", nil, err
}
response, err := s.carrierNodeClient().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
}
// pushToCarrierNode streams a local file as the request body without buffering it in memory.
func (s *Server) pushToCarrierNode(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 := s.newCarrierNodeRequest(ctx, method, carrierNodePath, file)
if err != nil {
return nil, err
}
if info, statErr := file.Stat(); statErr == nil {
request.ContentLength = info.Size()
}
response, err := s.carrierNodeClient().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 carrierNodePushedSize(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) carrierNodePushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
func (s *Server) carrierNodeDeleteThumbnail(ctx context.Context, id string) error {
request, err := s.newCarrierNodeRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil {
return err
}
response, err := s.carrierNodeClient().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
}
func (s *Server) carrierNodePushOutput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
func (s *Server) carrierNodePushInput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
func (s *Server) carrierNodePushCopy(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
// carrierNodeUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download
// staged in a scratch dir) into CarrierNode's DownloadsRoot via its existing raw-upload endpoint.
func (s *Server) carrierNodeUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
response, err := s.pushToCarrierNode(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
}
// carrierNodeStoreDownload catalogs an already-uploaded file into CarrierNode'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) carrierNodeStoreDownload(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.newCarrierNodeRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := s.carrierNodeClient().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
}
// carrierNodeListFiles lists files under CarrierNode's MediaRoots via its existing /api/files(/recent)
// endpoints - the replacement for a local filepath.WalkDir over MediaRoots.
func (s *Server) carrierNodeListFiles(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.newCarrierNodeRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
response, err := s.carrierNodeClient().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
}
type carrierNodeProbeResult struct {
DurationMs int64 `json:"durationMs"`
Width int `json:"width"`
Height int `json:"height"`
}
// carrierNodeProbe runs ffprobe on CarrierNode against a MediaRoots-relative path and returns just the
// metadata fields - bytes never leave CarrierNode, unlike every other helper in this file.
func (s *Server) carrierNodeProbe(ctx context.Context, relative string) (carrierNodeProbeResult, error) {
query := url.Values{}
query.Set("path", relative)
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
if err != nil {
return carrierNodeProbeResult{}, err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return carrierNodeProbeResult{}, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return carrierNodeProbeResult{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
}
var result carrierNodeProbeResult
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return carrierNodeProbeResult{}, err
}
return result, nil
}
@@ -13,7 +13,7 @@ import (
"github.com/coder/websocket"
"github.com/go-chi/chi/v5"
"mediacollection/internal/config"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
)
type kioskMessage struct {
@@ -120,7 +120,7 @@ func (s *Server) kioskPoll(ctx context.Context) {
}
func (s *Server) kioskPollOnce(ctx context.Context) {
files, err := s.servantListFiles(ctx, "", false, 0)
files, err := s.carrierNodeListFiles(ctx, "", false, 0)
if err != nil {
return
}
@@ -179,7 +179,7 @@ func (s *Server) kioskImage(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "image not found")
return
}
s.proxyServant(w, r, "/media/"+urlPath(relative))
s.proxyCarrierNode(w, r, "/media/"+urlPath(relative))
}
func kioskDuration(value string) int64 {
@@ -17,7 +17,7 @@ import (
"github.com/go-chi/chi/v5"
"mediacollection/internal/auth"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/auth"
)
func (s *Server) mountSharedRoutes(r chi.Router) {
@@ -242,7 +242,7 @@ func (s *Server) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, i
writeError(w, http.StatusNotFound, "media not found")
return
}
s.proxyServant(w, r, "/media/"+urlPath(record.FilePath))
s.proxyCarrierNode(w, r, "/media/"+urlPath(record.FilePath))
}
func (s *Server) thumbnailMedia(w http.ResponseWriter, r *http.Request) {
@@ -261,8 +261,8 @@ func (s *Server) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request
}
if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") {
thumbnailPath := "/thumbnails/" + id + ".jpg"
if exists, _, _, err := s.probeServant(r.Context(), thumbnailPath); err == nil && exists {
s.proxyServant(w, r, thumbnailPath)
if exists, _, _, err := s.probeCarrierNode(r.Context(), thumbnailPath); err == nil && exists {
s.proxyCarrierNode(w, r, thumbnailPath)
return
}
}
@@ -271,7 +271,7 @@ func (s *Server) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
s.proxyServant(w, r, "/media/"+urlPath(record.FilePath))
s.proxyCarrierNode(w, r, "/media/"+urlPath(record.FilePath))
}
func (s *Server) funscriptMedia(w http.ResponseWriter, r *http.Request) {
@@ -283,8 +283,8 @@ func (s *Server) funscriptMedia(w http.ResponseWriter, r *http.Request) {
base := strings.TrimSuffix(record.FilePath, filepath.Ext(record.FilePath))
for _, candidate := range []string{base + ".funscript", base + ".json"} {
candidatePath := "/media/" + urlPath(candidate)
if exists, _, _, err := s.probeServant(r.Context(), candidatePath); err == nil && exists {
s.proxyServant(w, r, candidatePath)
if exists, _, _, err := s.probeCarrierNode(r.Context(), candidatePath); err == nil && exists {
s.proxyCarrierNode(w, r, candidatePath)
return
}
}
@@ -298,7 +298,7 @@ func (s *Server) mediaFileInfo(w http.ResponseWriter, r *http.Request) {
return
}
response := record.toJSON()
if exists, size, modTime, err := s.probeServant(r.Context(), "/media/"+urlPath(record.FilePath)); err == nil && exists {
if exists, size, modTime, err := s.probeCarrierNode(r.Context(), "/media/"+urlPath(record.FilePath)); err == nil && exists {
response["absolutePath"] = ""
response["sizeBytes"] = size
response["modifiedAt"] = modTime
@@ -1,331 +0,0 @@
package server
// Servant client: every non-Servant service serves and stores media by calling MediaServant'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
}
+15 -12
View File
@@ -18,8 +18,8 @@ import (
chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/jackc/pgx/v5/pgxpool"
"mediacollection/internal/auth"
"mediacollection/internal/config"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/auth"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
)
type Server struct {
@@ -129,7 +129,7 @@ type scanState struct {
Total int64
StartedAt *time.Time
// LastError survives the end-of-run reset (unlike every other field here) so a run that
// failed fast - e.g. MediaServant unreachable - doesn't just look like it silently reverted
// failed fast - e.g. CarrierNode unreachable - doesn't just look like it silently reverted
// to idle; analyzerStatus reports it until the next run overwrites or clears it.
LastError string
}
@@ -192,14 +192,14 @@ func (s *Server) Handler() http.Handler {
if s.cfg.Service != config.Kiosk {
router.HandleFunc("/ws", s.syncWebsocket)
}
if s.cfg.Service == config.Servant {
if s.cfg.Service == config.CarrierNode {
internal := s.internalServiceAuth
router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.servantDownloadMedia)))
router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.servantGeneratedMedia)))
router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.servantInputMedia)))
router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.servantCopyMedia)))
router.Handle("/media/*", internal(http.HandlerFunc(s.servantMedia)))
router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.servantThumbnail)))
router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.carrierNodeDownloadMedia)))
router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.carrierNodeGeneratedMedia)))
router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.carrierNodeInputMedia)))
router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.carrierNodeCopyMedia)))
router.Handle("/media/*", internal(http.HandlerFunc(s.carrierNodeMedia)))
router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.carrierNodeThumbnail)))
}
router.NotFound(s.staticHandler)
@@ -221,8 +221,8 @@ func (s *Server) mountServiceRoutes(r chi.Router) {
s.mountModeratorRoutes(r)
case config.Kiosk:
s.mountKioskRoutes(r)
case config.Servant:
s.mountServantRoutes(r)
case config.CarrierNode:
s.mountCarrierNodeRoutes(r)
}
}
@@ -340,6 +340,9 @@ func (s *Server) Run(ctx context.Context) error {
if s.cfg.Service == config.Analyzer {
go s.runAnalyzerScheduler(ctx)
}
if s.cfg.Service == config.ConfigService {
go s.runSettingsSyncScheduler(ctx)
}
return s.listenAndServe(ctx)
}
@@ -21,7 +21,7 @@ import (
"github.com/go-chi/chi/v5"
"mediacollection/internal/auth"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/auth"
)
func (s *Server) mountToolsRoutes(r chi.Router) {
@@ -298,7 +298,7 @@ func (s *Server) executeConversion(ctx context.Context, job WorkflowJob) (map[st
if sourceName == "" {
return nil, fmt.Errorf("converter input path is required")
}
source, cleanupSource, err := s.fetchWorkflowFileFromServant(ctx, sourceName)
source, cleanupSource, err := s.fetchWorkflowFileFromCarrierNode(ctx, sourceName)
if err != nil {
return nil, fmt.Errorf("converter input is not an allowed file: %w", err)
}
@@ -334,7 +334,7 @@ func (s *Server) executeConversion(ctx context.Context, job WorkflowJob) (map[st
if err != nil || info.IsDir() {
return nil, fmt.Errorf("ffmpeg did not produce an output file")
}
size, err := s.servantPushOutput(ctx, outputName, outputPath)
size, err := s.carrierNodePushOutput(ctx, outputName, outputPath)
if err != nil {
return nil, fmt.Errorf("converted output could not be stored: %w", err)
}
@@ -371,9 +371,9 @@ func (s *Server) executeDownload(ctx context.Context, job WorkflowJob) (map[stri
return nil, fmt.Errorf("downloaded file is unavailable")
}
filename := filepath.Base(filePath)
// Pushing through Servant's upload endpoint also catalogs the file into media/media_worker_jobs
// (see servantRawUpload) - no separate indexMediaFile call needed here.
if _, err := s.servantUploadDownload(ctx, filePath, filename); err != nil {
// Pushing through CarrierNode's upload endpoint also catalogs the file into media/media_worker_jobs
// (see carrierNodeRawUpload) - no separate indexMediaFile call needed here.
if _, err := s.carrierNodeUploadDownload(ctx, filePath, filename); err != nil {
return nil, fmt.Errorf("downloaded file could not be stored: %w", err)
}
_, _ = s.db.Exec(ctx, `INSERT INTO downloaded_media (source_url, tool, file_path, file_name, file_size_bytes, status, started_at, finished_at) VALUES ($1,'yt-dlp',$2,$3,$4,'completed',$5,NOW())`, sourceURL, filename, filename, info.Size(), job.CreatedAt)
@@ -439,25 +439,25 @@ func firstString(values map[string]any, keys ...string) string {
return ""
}
// workflowFileServantPaths mirrors the search order resolveWorkflowFile used to walk locally
// (InputRoot, MediaRoots, DownloadsRoot, OutputRoot) but as Servant-side mount prefixes, since
// workflowFileCarrierNodePaths mirrors the search order resolveWorkflowFile used to walk locally
// (InputRoot, MediaRoots, DownloadsRoot, OutputRoot) but as CarrierNode-side mount prefixes, since
// MediaTools no longer has any of those roots mounted on its own filesystem.
var workflowFileServantPaths = []string{"/mount/inputs/", "/media/", "/media/downloads/", "/mount/generated/"}
var workflowFileCarrierNodePaths = []string{"/mount/inputs/", "/media/", "/media/downloads/", "/mount/generated/"}
// fetchWorkflowFileFromServant locates a converter input under any of Servant's mounts and
// fetchWorkflowFileFromCarrierNode locates a converter input under any of CarrierNode's mounts and
// downloads it into an ephemeral scratch file for ffmpeg to read; the caller must invoke the
// returned cleanup once done.
func (s *Server) fetchWorkflowFileFromServant(ctx context.Context, value string) (string, func(), error) {
func (s *Server) fetchWorkflowFileFromCarrierNode(ctx context.Context, value string) (string, func(), error) {
value = strings.TrimSpace(value)
if !safeRelative(value) {
return "", nil, os.ErrNotExist
}
for _, prefix := range workflowFileServantPaths {
servantPath := prefix + urlPath(value)
if exists, _, _, err := s.probeServant(ctx, servantPath); err != nil || !exists {
for _, prefix := range workflowFileCarrierNodePaths {
carrierNodePath := prefix + urlPath(value)
if exists, _, _, err := s.probeCarrierNode(ctx, carrierNodePath); err != nil || !exists {
continue
}
return s.fetchServantToScratch(ctx, servantPath, filepath.Ext(value))
return s.fetchCarrierNodeToScratch(ctx, carrierNodePath, filepath.Ext(value))
}
return "", nil, os.ErrNotExist
}
@@ -723,7 +723,7 @@ func (s *Server) uploadCopy(w http.ResponseWriter, r *http.Request) {
if s.cfg.MaxUploadBytes > 0 {
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes)
}
filename, size, err := s.saveMultipartUpload(r, s.servantPushCopy)
filename, size, err := s.saveMultipartUpload(r, s.carrierNodePushCopy)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
@@ -736,7 +736,7 @@ func (s *Server) toolUpload(w http.ResponseWriter, r *http.Request) {
if s.cfg.MaxUploadBytes > 0 {
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes)
}
filename, size, err := s.saveMultipartUpload(r, s.servantPushInput)
filename, size, err := s.saveMultipartUpload(r, s.carrierNodePushInput)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
@@ -815,7 +815,7 @@ func (s *Server) toolFile(w http.ResponseWriter, r *http.Request, mountPrefix st
writeError(w, http.StatusNotFound, "file not found")
return
}
s.proxyServant(w, r, mountPrefix+urlPath(relative))
s.proxyCarrierNode(w, r, mountPrefix+urlPath(relative))
}
func (s *Server) workflowList(w http.ResponseWriter, _ *http.Request) {
@@ -895,13 +895,13 @@ func (s *Server) downloadWorkflowResult(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusNotFound, "job result not found")
return
}
servantPath := "/mount/generated/" + urlPath(filename)
if exists, _, _, err := s.probeServant(r.Context(), servantPath); err != nil || !exists {
carrierNodePath := "/mount/generated/" + urlPath(filename)
if exists, _, _, err := s.probeCarrierNode(r.Context(), carrierNodePath); err != nil || !exists {
writeError(w, http.StatusGone, "job result is no longer available")
return
}
w.Header().Set("Content-Disposition", `attachment; filename="`+filepath.Base(filename)+`"`)
s.proxyServant(w, r, servantPath)
s.proxyCarrierNode(w, r, carrierNodePath)
}
func scanWorkflowJob(row interface{ Scan(...any) error }) (WorkflowJob, error) {