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

@@ -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":