Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Results: a provider's EXR zip is streamed to disk past the 200 MB cap, and its link stays on offer

Claude86e878158ecd
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index c2156f4d..2222b7c8 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -91,11 +91,13 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
case "video": {
link("extend", "Extend", `/extend?video=${q(o.url)}`, "primary");
out.push(file);
- // An HDR or export job's EXR frames ride along on its preview clip (meta.artifacts.exr, a stored zip).
+ // An HDR or export job's EXR frames ride along on its preview clip (meta.artifacts.exr): a stored zip, or
+ // the provider's own link when it couldn't be kept (unreachable when the job finished; it expires).
const exr = (o.meta?.artifacts as Record<string, unknown> | undefined)?.exr;
- if (typeof exr === "string" && exr.startsWith("/api/files/")) {
+ if (typeof exr === "string" && /^(\/api\/files\/|https?:\/\/)/.test(exr)) {
const zip = name.replace(/\.[^.]+$/, "-exr.zip");
- out.push({ id: "download-exr", label: "Download EXR frames (.zip)", placement: "bar", href: downloadHref(exr, zip), download: zip });
+ const stored = exr.startsWith("/api/files/");
+ out.push({ id: "download-exr", label: stored ? "Download EXR frames (.zip)" : "Download EXR frames (.zip, provider link)", placement: "bar", href: stored ? downloadHref(exr, zip) : exr, download: zip });
}
out.push({ id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });
link("reframe", "Reframe", `/reframe?video=${q(o.url)}`);
diff --git a/src/server/generations.ts b/src/server/generations.ts
index a3f52d20..e39c6389 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -33,7 +33,8 @@ import type { PollContext, PollResult, RemoteOutput } from "./providers/types";
import { mediaFacts } from "./media-facts";
import { convertMask } from "./png";
import { engineMode, getSetting } from "./settings";
-import { contentTypeFor, deleteAsset, readRef, saveFile } from "./storage";
+import { fetchRemoteToFile } from "./remote-fetch";
+import { adoptFile, contentTypeFor, deleteAsset, readRef, saveFile, scratchDir } from "./storage";
interface Row {
id: string;
@@ -917,9 +918,10 @@ function inlineText(text: string | undefined, meta: Record<string, unknown> | un
/**
* Extra files a result carries as links (meta.artifacts: LTX HDR's EXR zip, Higgsfield's fbx / zip) are kept
- * too, so the Library never depends on a provider's expiring URL. A link that can't be fetched stays as it was.
+ * too, so the Library never depends on a provider's expiring URL. Links are streamed to disk (an EXR zip runs
+ * to gigabytes); one that can't be fetched stays as it was (the result's actions still offer it).
*/
-async function persistArtifacts(meta: Record<string, unknown> | undefined, generationId: string): Promise<Record<string, unknown> | undefined> {
+export async function persistArtifacts(meta: Record<string, unknown> | undefined, generationId: string): Promise<Record<string, unknown> | undefined> {
const links = meta?.artifacts;
if (!links || typeof links !== "object" || Array.isArray(links)) return meta;
const kept: Record<string, unknown> = {};
@@ -927,10 +929,16 @@ async function persistArtifacts(meta: Record<string, unknown> | undefined, gener
kept[k] = v;
if (typeof v !== "string" || !/^(https?:|data:)/.test(v)) continue;
try {
- const f = await readRef(v);
- const name = /^https?:/.test(v) ? new URL(v).pathname.split("/").pop() || undefined : undefined;
- const type = f.contentType === "application/octet-stream" ? contentTypeFor(name ?? "", f.contentType) : f.contentType;
- kept[k] = saveFile({ data: f.data, contentType: type, name, source: "generation", generationId }).url;
+ if (v.startsWith("data:")) {
+ const f = await readRef(v);
+ kept[k] = saveFile({ data: f.data, contentType: f.contentType, source: "generation", generationId }).url;
+ continue;
+ }
+ const dest = path.join(scratchDir(), `${generationId}-${k}-${nanoid(6)}`);
+ const res = await fetchRemoteToFile(v, dest);
+ const name = new URL(res.url).pathname.split("/").pop() || undefined;
+ const header = res.contentType && res.contentType !== "application/octet-stream" ? res.contentType : null;
+ kept[k] = adoptFile({ from: dest, contentType: header ?? contentTypeFor(name ?? "", "application/octet-stream"), name, source: "generation", generationId }).url;
} catch (e) {
console.warn(`[fuobe] could not keep the ${k} file of ${generationId}: ${(e as Error).message}`);
}
diff --git a/src/server/remote-fetch.ts b/src/server/remote-fetch.ts
index cbd2602f..e70e7584 100644
--- a/src/server/remote-fetch.ts
+++ b/src/server/remote-fetch.ts
@@ -1,5 +1,6 @@
import "server-only";
import dns from "node:dns/promises";
+import fs from "node:fs";
import http from "node:http";
import https from "node:https";
import net from "node:net";
@@ -88,6 +89,28 @@ function refuse(host: string): RemoteFetchError {
/** GET a public http(s) URL into memory, with a timeout, a size cap and checked redirects. */
export async function fetchRemote(url: string, o: RemoteFetchOptions = {}): Promise<{ data: Buffer; contentType: string | null; url: string }> {
+ const res = await download(url, o);
+ return { data: res.data!, contentType: res.contentType, url: res.url };
+}
+
+/** Big results a provider links to (LTX HDR's EXR frames as a zip): streamed to disk, never held in memory. */
+export const MAX_REMOTE_FILE_BYTES = 16 * 2 ** 30;
+
+/**
+ * GET a public http(s) URL straight into the file `dest` (the same checks as fetchRemote; the cap defaults
+ * to MAX_REMOTE_FILE_BYTES and the deadline to 30 minutes). A failed download leaves no file behind.
+ */
+export async function fetchRemoteToFile(url: string, dest: string, o: RemoteFetchOptions = {}): Promise<{ bytes: number; contentType: string | null; url: string }> {
+ try {
+ const res = await download(url, { maxBytes: MAX_REMOTE_FILE_BYTES, timeoutMs: 30 * 60_000, ...o }, dest);
+ return { bytes: res.bytes, contentType: res.contentType, url: res.url };
+ } catch (e) {
+ fs.rmSync(dest, { force: true });
+ throw e;
+ }
+}
+
+async function download(url: string, o: RemoteFetchOptions, dest?: string): Promise<{ data?: Buffer; bytes: number; contentType: string | null; url: string }> {
const maxBytes = o.maxBytes ?? MAX_REMOTE_BYTES;
const blocked = o.blocked ?? ((ip: string) => !allowPrivate() && isPrivateAddress(ip));
const resolve = o.resolve ?? (async (host: string) => (await dns.lookup(host, { all: true, verbatim: true })).map((a) => a.address));
@@ -98,20 +121,20 @@ export async function fetchRemote(url: string, o: RemoteFetchOptions = {}): Prom
if (current.username || current.password) throw new RemoteFetchError("Links with a user name or password aren't fetched");
const host = current.hostname.replace(/^\[|\]$/g, "");
if (net.isIP(host) && blocked(host)) throw refuse(current.host);
- const res = await get(current, { host, maxBytes, deadline, resolve, blocked });
+ const res = await get(current, { host, maxBytes, deadline, resolve, blocked, dest });
if (res.location) {
current = new URL(res.location, current);
continue;
}
- return { data: res.data!, contentType: res.contentType, url: current.toString() };
+ return { data: res.data, bytes: res.bytes ?? 0, contentType: res.contentType, url: current.toString() };
}
throw new RemoteFetchError(`Too many redirects fetching ${url}`);
}
function get(
url: URL,
- o: { host: string; maxBytes: number; deadline: number; resolve: (host: string) => Promise<string[]>; blocked: (ip: string) => boolean },
-): Promise<{ location?: string; data?: Buffer; contentType: string | null }> {
+ o: { host: string; maxBytes: number; deadline: number; resolve: (host: string) => Promise<string[]>; blocked: (ip: string) => boolean; dest?: string },
+): Promise<{ location?: string; data?: Buffer; bytes?: number; contentType: string | null }> {
// Checked at connect time, on the address actually used.
const lookup: net.LookupFunction = (hostname, options, cb) => {
o.resolve(hostname).then(
@@ -132,12 +155,15 @@ function get(
req.destroy();
reject(new RemoteFetchError(`Timed out fetching ${url.host}`));
}, left);
- const resolvePromise = (v: { location?: string; data?: Buffer; contentType: string | null }) => {
+ const resolvePromise = (v: { location?: string; data?: Buffer; bytes?: number; contentType: string | null }) => {
clearTimeout(timer);
resolveOuter(v);
};
+ // To a file (o.dest): written as it arrives; closed on any failure.
+ let file: fs.WriteStream | null = null;
const reject = (e: Error) => {
clearTimeout(timer);
+ file?.destroy();
rejectOuter(e);
};
const req = (url.protocol === "https:" ? https : http).request(url, { method: "GET", lookup, headers: { "User-Agent": "Fuobe", Accept: "*/*" }, timeout: left }, (res) => {
@@ -155,7 +181,15 @@ function get(
res.destroy();
return reject(new RemoteFetchError(`That file is over ${Math.round(o.maxBytes / 1024 / 1024)} MB`));
}
+ const contentType = res.headers["content-type"]?.split(";")[0].trim() || null;
const chunks: Buffer[] = [];
+ // The response pauses while the disk catches up.
+ file = o.dest ? fs.createWriteStream(o.dest) : null;
+ file?.on("error", (e) => {
+ res.destroy();
+ req.destroy();
+ reject(e);
+ });
let size = 0;
res.on("data", (c: Buffer) => {
size += c.length;
@@ -165,9 +199,16 @@ function get(
reject(new RemoteFetchError(`That file is over ${Math.round(o.maxBytes / 1024 / 1024)} MB`));
return;
}
- chunks.push(c);
+ if (!file) return void chunks.push(c);
+ if (!file.write(c)) {
+ res.pause();
+ file.once("drain", () => res.resume());
+ }
+ });
+ res.on("end", () => {
+ if (!file) return resolvePromise({ data: Buffer.concat(chunks), bytes: size, contentType });
+ file.end(() => resolvePromise({ bytes: size, contentType }));
});
- res.on("end", () => resolvePromise({ data: Buffer.concat(chunks), contentType: res.headers["content-type"]?.split(";")[0].trim() || null }));
res.on("error", reject);
});
req.on("timeout", () => req.destroy(new RemoteFetchError(`Timed out fetching ${url.host}`)));