From bd5b74ff3b7790b876266a37dd0c9d6c70724645 Mon Sep 17 00:00:00 2001 From: Gabriel20xx Date: Tue, 29 Sep 2026 22:23:11 +0200 Subject: [PATCH] Sync shared snapshot from 6ef2335 --- .../carriernodeclient/carriernodeclient.go | 239 +++++++++++++++++- 1 file changed, 229 insertions(+), 10 deletions(-) diff --git a/shared/backend/carriernodeclient/carriernodeclient.go b/shared/backend/carriernodeclient/carriernodeclient.go index e106b98..de39f6e 100644 --- a/shared/backend/carriernodeclient/carriernodeclient.go +++ b/shared/backend/carriernodeclient/carriernodeclient.go @@ -1,11 +1,9 @@ -// Package carriernodeclient is the HTTP client the 6 non-CarrierNode -// media-family services (MediaViewer, CraftStudio, ContentScanner, -// ModerationHub, ProjectConfigurator, KioskDisplay) use to store and serve -// media by calling CarrierNode's API, instead of touching a local -// MediaRoots/ThumbnailRoot/OutputRoot/DownloadsRoot/InputRoot/CopyRoot -// filesystem directly. CarrierNode's own backend keeps resolving and -// serving those roots itself - this client is never used from CarrierNode's -// own code path. +// Package carriernodeclient is the HTTP client non-CarrierNode services use +// to access CarrierNode's media and project-specific mount APIs. Existing +// media services use it for central file storage; other projects use its +// generic project/type methods after preferring their local volumes. +// CarrierNode's own backend keeps resolving and serving configured roots - +// this client is never used from CarrierNode's own code path. // // Promoted unchanged (aside from being detached from a shared *Server type) // from each service's own internal carriernode_client.go into this shared @@ -33,8 +31,7 @@ var httpClient = &http.Client{} var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"} var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"} -// Client calls CarrierNode's HTTP API on behalf of one of the other 6 -// media-family services. +// Client calls CarrierNode's HTTP API on behalf of another workspace service. type Client struct { // ProjectKey identifies the service making a request to CarrierNode. It is // optional for backwards compatibility, but when set it lets CarrierNode @@ -130,6 +127,18 @@ func (c *Client) primaryBaseURL(ctx context.Context) string { return "" } +// Configured reports whether the client currently has at least one non-empty +// CarrierNode URL. It is useful when a caller has another local fallback it +// can try if shared storage has not been configured. +func (c *Client) Configured(ctx context.Context) bool { + for _, baseURL := range c.candidateBaseURLs(ctx) { + if strings.TrimSpace(baseURL) != "" { + return true + } + } + return false +} + func (c *Client) newRequest(ctx context.Context, baseURL, method, path string, body io.Reader) (*http.Request, error) { request, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(baseURL, "/")+path, body) if err != nil { @@ -202,6 +211,216 @@ func (c *Client) Proxy(w http.ResponseWriter, r *http.Request, carrierNodePath s } } +// MountFileEntry describes one direct child returned from CarrierNode's +// project-specific mount listing endpoint. Path is relative to the requested +// directory and Directory is true for folders. +type MountFileEntry struct { + Name string `json:"name"` + Path string `json:"path"` + Directory bool `json:"directory"` + Size int64 `json:"size"` + Modified time.Time `json:"modifiedAt"` +} + +// MountPath builds a project/type-specific CarrierNode API path. It escapes +// each path segment independently so directory separators remain separators. +func MountPath(project, mountType, relative string) string { + if strings.TrimSpace(project) == "" || strings.TrimSpace(mountType) == "" { + return "" + } + parts := []string{"api", "mount", project, mountType} + for _, segment := range strings.Split(strings.Trim(relative, "/\\"), "/") { + if segment == "" || segment == "." { + continue + } + if segment == ".." { + return "" + } + parts = append(parts, segment) + } + for i := range parts { + parts[i] = url.PathEscape(parts[i]) + } + return "/" + strings.Join(parts, "/") +} + +// ProxyMount streams a file from a project/type mount to the original client, +// preserving HTTP range and conditional headers. It is intended as a fallback +// after the caller's local volume has been checked. +func (c *Client) ProxyMount(w http.ResponseWriter, r *http.Request, project, mountType, relative string) { + if strings.Trim(strings.TrimSpace(relative), "/\\") == "" { + writeError(w, http.StatusNotFound, "file not found") + return + } + path := MountPath(project, mountType, relative) + if path == "" { + writeError(w, http.StatusNotFound, "file not found") + return + } + if !c.Configured(r.Context()) { + writeError(w, http.StatusNotFound, "file not found") + return + } + c.Proxy(w, r, path) +} + +// ListMountFiles lists the direct children of a project/type mount directory. +// An empty relative path lists the mount root. The CarrierNode endpoint +// returns both files and directories so callers can build directory browsers. +func (c *Client) ListMountFiles(ctx context.Context, project, mountType, relative string) ([]MountFileEntry, error) { + candidates := c.candidateBaseURLs(ctx) + if len(candidates) == 0 { + return nil, fmt.Errorf("carriernode is not configured") + } + path := MountPath(project, mountType, "") + if path == "" { + return nil, fmt.Errorf("invalid mount path") + } + query := url.Values{} + if strings.TrimSpace(relative) != "" { + query.Set("path", relative) + } + if encoded := query.Encode(); encoded != "" { + path += "?" + encoded + } + var entries []MountFileEntry + var lastErr error + loaded := false + for _, baseURL := range candidates { + request, err := c.newRequest(ctx, baseURL, http.MethodGet, path, nil) + if err != nil { + lastErr = err + continue + } + response, err := httpClient.Do(request) + if err != nil { + lastErr = err + continue + } + if response.StatusCode != http.StatusOK { + response.Body.Close() + lastErr = fmt.Errorf("carriernode mount listing failed: %s", response.Status) + continue + } + var payload struct { + Files []MountFileEntry `json:"files"` + } + decodeErr := json.NewDecoder(response.Body).Decode(&payload) + response.Body.Close() + if decodeErr != nil { + lastErr = decodeErr + continue + } + loaded = true + entries = append(entries, payload.Files...) + } + if !loaded && lastErr != nil { + return nil, lastErr + } + unique := make([]MountFileEntry, 0, len(entries)) + seen := make(map[string]struct{}, len(entries)) + for _, entry := range entries { + key := entry.Path + if key == "" { + key = entry.Name + } + if _, exists := seen[key]; exists { + continue + } + seen[key] = struct{}{} + unique = append(unique, entry) + } + return unique, nil +} + +// UploadMountFile streams a local file into a project/type mount on the +// primary CarrierNode. Writes intentionally target only the primary instance. +func (c *Client) UploadMountFile(ctx context.Context, project, mountType, relative, localPath string) error { + if strings.Trim(strings.TrimSpace(relative), "/\\") == "" { + return fmt.Errorf("invalid mount path") + } + path := MountPath(project, mountType, relative) + if path == "" { + return fmt.Errorf("invalid mount path") + } + response, err := c.push(ctx, http.MethodPost, path, localPath) + if err != nil { + return err + } + response.Body.Close() + return nil +} + +// FetchMountToScratch downloads a project/type mount file to an ephemeral +// local file for callers that need to inspect or transform it. Callers must +// invoke cleanup once done. +func (c *Client) FetchMountToScratch(ctx context.Context, project, mountType, relative, suffix string) (string, func(), error) { + if strings.Trim(strings.TrimSpace(relative), "/\\") == "" { + return "", nil, fmt.Errorf("invalid mount path") + } + if len(c.candidateBaseURLs(ctx)) == 0 { + return "", nil, fmt.Errorf("carriernode is not configured") + } + path := MountPath(project, mountType, relative) + if path == "" { + return "", nil, fmt.Errorf("invalid mount path") + } + return c.FetchToScratch(ctx, path, suffix) +} + +// UploadMountBytes writes a byte slice to a project/type mount on the primary +// CarrierNode. Callers should prefer this for bounded request bodies; large +// files should use UploadMountFile to avoid buffering them in memory. +func (c *Client) UploadMountBytes(ctx context.Context, project, mountType, relative string, data []byte) error { + if strings.Trim(strings.TrimSpace(relative), "/\\") == "" { + return fmt.Errorf("invalid mount path") + } + path := MountPath(project, mountType, relative) + if path == "" { + return fmt.Errorf("invalid mount path") + } + request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodPost, path, bytes.NewReader(data)) + if err != nil { + return err + } + request.ContentLength = int64(len(data)) + response, err := httpClient.Do(request) + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode >= 400 { + body, _ := io.ReadAll(io.LimitReader(response.Body, 4096)) + return fmt.Errorf("carriernode mount upload failed: %s: %s", response.Status, strings.TrimSpace(string(body))) + } + return nil +} + +// DeleteMountFile removes one file from a project/type mount on the primary +// CarrierNode. A missing file is treated as already deleted. +func (c *Client) DeleteMountFile(ctx context.Context, project, mountType, relative string) error { + if strings.Trim(strings.TrimSpace(relative), "/\\") == "" { + return fmt.Errorf("invalid mount path") + } + path := MountPath(project, mountType, relative) + if path == "" { + return fmt.Errorf("invalid mount path") + } + request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, path, nil) + if err != nil { + return err + } + response, err := httpClient.Do(request) + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound { + return fmt.Errorf("carriernode mount delete failed: %s", response.Status) + } + return nil +} + // probeOne runs Probe's HEAD request against a single base URL. func (c *Client) probeOne(ctx context.Context, baseURL, carrierNodePath string) (exists bool, size int64, modTime time.Time, err error) { request, err := c.newRequest(ctx, baseURL, http.MethodHead, carrierNodePath, nil)