Skip to content

Open source CapCut alternative.

TypeScript

feat(site): overlay rasterization renders on a server canvas [rebuild]

David Le9a7059c6c22a
diff --git a/site/packages/effects-kit/src/render.ts b/site/packages/effects-kit/src/render.ts
index bca8cdfe..82faef84 100644
--- a/site/packages/effects-kit/src/render.ts
+++ b/site/packages/effects-kit/src/render.ts
@@ -87,6 +87,12 @@ export interface StickerImage {
export interface RenderEnv {
/** CSS font-family stack for a host font id. */
fontStack(font: string): string;
+ /** Canvas surface for rasterization. The host injects a server canvas here
+ * to render headless; unset, the DOM canvas is used. */
+ createCanvas?(w: number, h: number): HTMLCanvasElement;
+ /** PNG encode for a canvas made by `createCanvas`. Required alongside it —
+ * a server canvas encodes through its own API. */
+ canvasToPngBlob?(canvas: HTMLCanvasElement): Promise<Blob>;
/** Decoded image for a sticker asset id; null when the asset is gone. */
resolveAsset?(assetId: string): Promise<StickerImage | null>;
/** Seekable player for a Lottie sticker asset id; null when the asset is
@@ -440,7 +446,8 @@ export async function paintElement(
}
}
-function pngBlob(canvas: HTMLCanvasElement): Promise<Blob> {
+function pngBlob(canvas: HTMLCanvasElement, env: RenderEnv): Promise<Blob> {
+ if (env.canvasToPngBlob) return env.canvasToPngBlob(canvas);
return new Promise((resolve, reject) =>
canvas.toBlob(
(b) => (b ? resolve(b) : reject(new Error("Could not render the overlay."))),
@@ -449,6 +456,14 @@ function pngBlob(canvas: HTMLCanvasElement): Promise<Blob> {
);
}
+function newCanvas(env: RenderEnv, w: number, h: number): HTMLCanvasElement {
+ if (env.createCanvas) return env.createCanvas(Math.max(1, w), Math.max(1, h));
+ const c = document.createElement("canvas");
+ c.width = Math.max(1, w);
+ c.height = Math.max(1, h);
+ return c;
+}
+
/**
* Rasterize one element to a transparent full-frame PNG at the given output
* size. Rotation and opacity apply here, around the element center, so every
@@ -463,9 +478,7 @@ export async function renderElementPng(
// Element sizes are design pixels with a 1080 short side, so scaling by the
// short side keeps them the same visual size in any aspect and resolution.
const scale = Math.min(width, height) / 1080;
- const canvas = document.createElement("canvas");
- canvas.width = width;
- canvas.height = height;
+ const canvas = newCanvas(env, width, height);
const ctx = canvas.getContext("2d")!;
const frame: PaintFrame = { width, height, scale };
@@ -485,7 +498,7 @@ export async function renderElementPng(
// animated frame sampler; here its resting (first) geometry applies.
applyMaskToCanvas(
ctx,
- document.createElement("canvas"),
+ newCanvas(env, 1, 1),
overlay.mask,
0,
frame,
@@ -493,7 +506,7 @@ export async function renderElementPng(
ctx.getTransform()
);
}
- return pngBlob(canvas);
+ return pngBlob(canvas, env);
}
/** An element's resting box in output pixels (center + size), rotation left
@@ -535,7 +548,7 @@ export async function measureElementBounds(
const fpx = o.size * frame.scale;
const cssFont = textCssFont(o, fpx, env);
await ensureFontLoaded(cssFont, o.text);
- const scratch = document.createElement("canvas");
+ const scratch = newCanvas(env, 1, 1);
const ctx = scratch.getContext("2d")!;
ctx.font = cssFont;
if ("letterSpacing" in ctx) ctx.letterSpacing = `${(o.letterSpacing ?? 0) * fpx}px`;
@@ -703,17 +716,15 @@ export async function renderOverlayFrames(
const rw = Math.max(2, x1 - x0);
const rh = Math.max(2, y1 - y0);
- const canvas = document.createElement("canvas");
- canvas.width = rw;
- canvas.height = rh;
+ const canvas = newCanvas(env, rw, rh);
const ctx = canvas.getContext("2d")!;
- const maskScratch = overlay.mask ? document.createElement("canvas") : null;
+ const maskScratch = overlay.mask ? newCanvas(env, 1, 1) : null;
const drawAt = async (tLocal: number): Promise<Blob> => {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, rw, rh);
const ev = evalOverlayFrame(overlay, tLocal);
- if (ev.opacity <= 0.001) return pngBlob(canvas); // fully transparent frame
+ if (ev.opacity <= 0.001) return pngBlob(canvas, env); // fully transparent frame
ctx.globalAlpha = ev.opacity;
ctx.translate(-x0, -y0);
// The pose places the element; the preset's travel rides on top of it.
@@ -746,7 +757,7 @@ export async function renderOverlayFrames(
maskTransform
);
}
- return pngBlob(canvas);
+ return pngBlob(canvas, env);
};
const images: Blob[] = [];
@@ -767,7 +778,7 @@ export async function renderOverlayFrames(
}
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, rw, rh);
- return { x: x0, y: y0, w: rw, h: rh, images, blank: await pngBlob(canvas), entries };
+ return { x: x0, y: y0, w: rw, h: rh, images, blank: await pngBlob(canvas, env), entries };
}
// Head ramp, frame by frame; the last frame absorbs the rounding so the
// segment lengths sum exactly.
@@ -808,6 +819,6 @@ export async function renderOverlayFrames(
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, rw, rh);
- const blank = await pngBlob(canvas);
+ const blank = await pngBlob(canvas, env);
return { x: x0, y: y0, w: rw, h: rh, images, blank, entries };
}
diff --git a/site/scripts/eval-cut-headless-export.ts b/site/scripts/eval-cut-headless-export.ts
new file mode 100644
index 00000000..979cbcad
--- /dev/null
+++ b/site/scripts/eval-cut-headless-export.ts
@@ -0,0 +1,97 @@
+#!/usr/bin/env bun
+/**
+ * Doc-only export smoke: a headless process takes a project from empty to a
+ * finished mp4 with no page anywhere. It seeds a cloud project, imports a
+ * real video, places a clip and a title, rasterizes the title PNG on the
+ * skia server canvas, queues the export, and waits for the worker to render.
+ *
+ * Run with the site dev server up and a local worker running:
+ * bun run scripts/eval-cut-headless-export.ts [--base http://localhost:3000]
+ */
+
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { runAiTool } from "../src/cut/lib/aiTools";
+import { createExportJob, EXPORT_PRESETS, pollExport, presetSettings, type ExportDoc } from "../src/cut/lib/exportClient";
+import { bindHeadlessSession, type HeadlessSession } from "../src/cut/lib/headless/bind";
+import { openCloudProject, pushCloudProject } from "../src/cut/lib/headless/docSession";
+import { installSkiaRaster } from "../src/cut/lib/headless/skiaRaster";
+import { importFileToProject } from "../src/cut/lib/media";
+import { useEditor } from "../src/cut/lib/store";
+
+const arg = (name: string): string | undefined => {
+ const i = process.argv.indexOf(`--${name}`);
+ return i >= 0 ? process.argv[i + 1] : undefined;
+};
+const base = arg("base") ?? "http://localhost:3000";
+const session: HeadlessSession = {
+ base,
+ headers: { "x-donkey-client-id": "donkey-cut-eval", "x-donkey-dev-auth-bypass": "1" },
+};
+const api = (path: string, init?: RequestInit) =>
+ fetch(base + path, {
+ ...init,
+ headers: { "Content-Type": "application/json", ...session.headers, ...init?.headers },
+ });
+const fail = (msg: string): never => {
+ process.exitCode = 1;
+ throw new Error(`FAIL ${msg}`);
+};
+
+if (!(await installSkiaRaster())) fail("skia-canvas is unavailable in this process");
+bindHeadlessSession(session);
+
+const created = await api("/api/cut-cloud/projects", {
+ method: "POST",
+ body: JSON.stringify({ name: `headless-export-${Date.now()}` }),
+});
+if (!created.ok) fail(`could not create project (${created.status}) — is the dev server up?`);
+const projectId = ((await created.json()) as { id: string }).id;
+console.log(`seeded project ${projectId}`);
+
+try {
+ const docSession = await openCloudProject(session, projectId);
+
+ // A real clip: one of the starter videos, imported the same way generated
+ // media lands (upload, probe from the bytes in hand, store row).
+ const mp4 = readFileSync(
+ join(import.meta.dir, "../public/cut-starter/media/ai-watercolor-and-loose-black-ink-sketch-il.mp4")
+ );
+ const file = new File([new Uint8Array(mp4)], "clip.mp4", { type: "video/mp4" });
+ const asset = await importFileToProject(projectId, file);
+ if (!asset) fail("could not import the starter video");
+ useEditor.getState().addAsset(asset!);
+ await runAiTool("add_clip", { asset_id: asset!.id });
+ await runAiTool("add_title", { text: "HEADLESS EXPORT", start: 0 });
+ const s = useEditor.getState();
+ console.log(`timeline: ${s.clips.length} clip(s), ${s.overlays.length} overlay(s)`);
+
+ await pushCloudProject(session, docSession);
+ const doc = useEditor.getState();
+ const exportDoc: ExportDoc = {
+ aspect: doc.aspect,
+ assets: doc.assets,
+ clips: doc.clips,
+ audioClips: doc.audioClips,
+ overlays: doc.overlays,
+ subtitles: doc.subtitles,
+ fadeIn: doc.fadeIn,
+ fadeOut: doc.fadeOut,
+ };
+ const settings = presetSettings(EXPORT_PRESETS[2], doc.aspect);
+ const jobId = await createExportJob(projectId, exportDoc, settings);
+ console.log(`queued export ${jobId} — waiting on the worker`);
+
+ let lastLogged = -1;
+ const onProgress = (_stage: string, ratio: number) => {
+ const pct = Math.round(ratio * 100);
+ if (pct >= lastLogged + 20) {
+ lastLogged = pct;
+ console.log(` rendering ${pct}%`);
+ }
+ };
+ const outName = await pollExport(jobId, onProgress);
+ console.log(`PASS export finished: ${outName}`);
+} finally {
+ await api(`/api/cut-cloud/projects/${projectId}`, { method: "DELETE" });
+}
diff --git a/site/src/cut/lib/composite.ts b/site/src/cut/lib/composite.ts
index 24b6acd2..0a22ee97 100644
--- a/site/src/cut/lib/composite.ts
+++ b/site/src/cut/lib/composite.ts
@@ -20,6 +20,7 @@
*/
import { applyMaskToCanvas, gradeTint, gradeToCssFilter, grainTile, isNeutralGrade, lookCssFilter, lookPost, maskComposite } from "@donkeycut/effects-kit";
+import { createRasterCanvas } from "./raster";
import { clipKeyed, clipPoseAt, isFullRect, rectOf } from "./types";
import type { FrameRect, TransitionStyle, VideoClip } from "./types";
@@ -124,10 +125,7 @@ export class FrameCompositor {
): { surface: Surface; resized: boolean } {
let surface = this[field];
if (!surface) {
- surface =
- typeof document === "undefined"
- ? new OffscreenCanvas(Math.max(1, w), Math.max(1, h))
- : document.createElement("canvas");
+ surface = createRasterCanvas(w, h);
this[field] = surface;
}
// Match both dimensions — a transition alternates two differently-sized
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 1bf26ebd..2f3734c7 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -5,6 +5,7 @@ import { quotaErrorMessage } from "./backend/cloud";
import { downloadFromUrl } from "./download";
import { renderProjectToMp4 } from "./exportRender";
import { putSigned } from "./media";
+import { createRasterCanvas, rasterCanvasToPng } from "./raster";
import { clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence, useEditor } from "./store";
import { captionStyle, cueOverlay, cueWordWindows, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";
import { isMaskAnimated, isOverlayAnimated, normalizeGrade, paintMaskLuma } from "@donkeycut/effects-kit";
@@ -226,9 +227,7 @@ async function renderClipMaskPictures(
const rb = rp
? { x: rp.rx - box.x, y: rp.ry - box.y, w: rp.rw, h: rp.rh }
: { x: -box.x, y: -box.y, w: W, h: H };
- const canvas = document.createElement("canvas");
- canvas.width = box.w;
- canvas.height = box.h;
+ const canvas = createRasterCanvas(box.w, box.h);
const blobAt = (tLocal: number) => {
const ctx = canvas.getContext("2d")!;
if (radius > 0) {
@@ -257,9 +256,7 @@ async function renderClipMaskPictures(
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "source-over";
}
- return new Promise<Blob>((resolve, reject) =>
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Could not render the mask."))), "image/png")
- );
+ return rasterCanvasToPng(canvas);
};
if (!(m && isMaskAnimated(m)) && !opacityVaries) {
const name = `${tag}.png`;
@@ -294,18 +291,14 @@ function renderClipBorderPng(
const scale = Math.min(W, H) / 1080;
const bw = bs.borderWidth * scale;
const rad = Math.max(0, (bs.radius ?? 0) * scale);
- const canvas = document.createElement("canvas");
- canvas.width = seg.w;
- canvas.height = seg.h;
- const ctx = canvas.getContext("2d")!;
+ const canvas = createRasterCanvas(seg.w, seg.h);
+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
ctx.strokeStyle = bs.borderColor ?? "#ffffff";
ctx.lineWidth = bw;
ctx.beginPath();
ctx.roundRect(ring.x + bw / 2, ring.y + bw / 2, ring.w - bw, ring.h - bw, Math.max(0, rad - bw / 2));
ctx.stroke();
- return new Promise((resolve, reject) =>
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Could not render the border."))), "image/png")
- );
+ return rasterCanvasToPng(canvas);
}
/** Build the export spec + overlay PNGs from the cut. Media already lives in
@@ -709,13 +702,8 @@ async function buildExportPayload(
}
}
if (captions.length > 0) {
- const blank = document.createElement("canvas");
- blank.width = settings.width;
- blank.height = settings.height;
- const png = await new Promise<Blob>((resolve, reject) =>
- blank.toBlob((b) => (b ? resolve(b) : reject(new Error("Could not render captions."))), "image/png")
- );
- pngs.push({ name: "sub_blank.png", blob: png });
+ const blank = createRasterCanvas(settings.width, settings.height);
+ pngs.push({ name: "sub_blank.png", blob: await rasterCanvasToPng(blank) });
}
}
diff --git a/site/src/cut/lib/headless/skiaRaster.ts b/site/src/cut/lib/headless/skiaRaster.ts
new file mode 100644
index 00000000..552df642
--- /dev/null
+++ b/site/src/cut/lib/headless/skiaRaster.ts
@@ -0,0 +1,36 @@
+import { setRasterFactory, type RasterImage, type RasterSurface } from "../raster";
+
+// The server canvas: skia-canvas standing in for the DOM surfaces behind the
+// raster seam. Installed once at a headless process's startup; the drawing
+// code in composite/textRender/exportClient then renders overlay PNGs the
+// same way the page does. The import is dynamic so the page bundle and any
+// process without the native module stay unaffected.
+
+export async function installSkiaRaster(): Promise<boolean> {
+ try {
+ const skia = await import("skia-canvas");
+ setRasterFactory({
+ createCanvas: (w, h) =>
+ new skia.Canvas(Math.max(1, w), Math.max(1, h)) as unknown as RasterSurface,
+ decodeImage: async (blob) => {
+ try {
+ const img = await skia.loadImage(Buffer.from(await blob.arrayBuffer()));
+ return {
+ source: img as unknown as CanvasImageSource,
+ width: img.width || 512,
+ height: img.height || 512,
+ } satisfies RasterImage;
+ } catch {
+ return null;
+ }
+ },
+ canvasToPngBlob: async (canvas) => {
+ const buf = await (canvas as unknown as InstanceType<typeof skia.Canvas>).toBuffer("png");
+ return new Blob([new Uint8Array(buf)], { type: "image/png" });
+ },
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/site/src/cut/lib/raster.ts b/site/src/cut/lib/raster.ts
new file mode 100644
index 00000000..70ddf7d7
--- /dev/null
+++ b/site/src/cut/lib/raster.ts
@@ -0,0 +1,66 @@
+// The one seam every rasterization surface goes through: canvases the export
+// path draws overlays on, and the images it decodes to draw them. The page
+// uses the DOM implementations below; a headless process installs a server
+// canvas (skia) at startup, and the same drawing code renders the same PNGs.
+
+export type RasterSurface = HTMLCanvasElement | OffscreenCanvas;
+
+export interface RasterImage {
+ source: CanvasImageSource;
+ width: number;
+ height: number;
+}
+
+export interface RasterFactory {
+ createCanvas(w: number, h: number): RasterSurface;
+ /** Decode one image blob; null when the bytes are undecodable. */
+ decodeImage(blob: Blob): Promise<RasterImage | null>;
+ canvasToPngBlob(canvas: RasterSurface): Promise<Blob>;
+}
+
+const domFactory: RasterFactory = {
+ createCanvas: (w, h) => {
+ if (typeof document === "undefined") return new OffscreenCanvas(Math.max(1, w), Math.max(1, h));
+ const c = document.createElement("canvas");
+ c.width = Math.max(1, w);
+ c.height = Math.max(1, h);
+ return c;
+ },
+ decodeImage: (blob) =>
+ new Promise((resolve) => {
+ const objectUrl = URL.createObjectURL(blob);
+ const img = new Image();
+ img.onload = () => {
+ URL.revokeObjectURL(objectUrl);
+ // An SVG with no intrinsic size reports 0×0; treat it as square.
+ resolve({ source: img, width: img.naturalWidth || 512, height: img.naturalHeight || 512 });
+ };
+ img.onerror = () => {
+ URL.revokeObjectURL(objectUrl);
+ resolve(null);
+ };
+ img.src = objectUrl;
+ }),
+ canvasToPngBlob: (canvas) => {
+ if (typeof OffscreenCanvas !== "undefined" && canvas instanceof OffscreenCanvas)
+ return canvas.convertToBlob({ type: "image/png" });
+ return new Promise((resolve, reject) =>
+ (canvas as HTMLCanvasElement).toBlob(
+ (b) => (b ? resolve(b) : reject(new Error("Could not render the image."))),
+ "image/png"
+ )
+ );
+ },
+};
+
+let factory: RasterFactory = domFactory;
+
+/** Install a replacement surface, e.g. the skia factory in a headless
+ * process. Affects every later createRasterCanvas/decodeRasterImage call. */
+export function setRasterFactory(f: RasterFactory): void {
+ factory = f;
+}
+
+export const createRasterCanvas = (w: number, h: number): RasterSurface => factory.createCanvas(w, h);
+export const decodeRasterImage = (blob: Blob): Promise<RasterImage | null> => factory.decodeImage(blob);
+export const rasterCanvasToPng = (canvas: RasterSurface): Promise<Blob> => factory.canvasToPngBlob(canvas);
diff --git a/site/src/cut/lib/textRender.ts b/site/src/cut/lib/textRender.ts
index 6cd95548..ce46ee26 100644
--- a/site/src/cut/lib/textRender.ts
+++ b/site/src/cut/lib/textRender.ts
@@ -7,6 +7,7 @@ import {
type RenderEnv,
type StickerImage,
} from "@donkeycut/effects-kit";
+import { createRasterCanvas, decodeRasterImage, rasterCanvasToPng } from "./raster";
import { fontStack, type MediaAsset, type Overlay } from "./types";
// The shared text metrics and painters live in the effects kit; these
@@ -30,26 +31,7 @@ const stickerCache = new Map<string, Promise<StickerImage | null>>();
function decodeSticker(url: string): Promise<StickerImage | null> {
return fetch(url)
.then((res) => (res.ok ? res.blob() : Promise.reject(new Error("fetch failed"))))
- .then(
- (blob) =>
- new Promise<StickerImage | null>((resolve) => {
- const objectUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.onload = () => {
- URL.revokeObjectURL(objectUrl);
- resolve({
- source: img,
- // An SVG with no intrinsic size reports 0×0; treat it as square.
- width: img.naturalWidth || 512,
- height: img.naturalHeight || 512,
- });
- };
- img.onerror = () => {
- URL.revokeObjectURL(objectUrl);
- resolve(null);
- };
- img.src = objectUrl;
- })
+ .then((blob) => decodeRasterImage(blob)
)
.catch(() => null);
}
@@ -60,6 +42,8 @@ function decodeSticker(url: string): Promise<StickerImage | null> {
export function cutRenderEnv(assets: MediaAsset[]): RenderEnv {
return {
fontStack,
+ createCanvas: (w, h) => createRasterCanvas(w, h) as HTMLCanvasElement,
+ canvasToPngBlob: (canvas) => rasterCanvasToPng(canvas),
resolveLottie: (assetId) =>
import("./lottieAssets").then((m) => m.sharedLottieHandle(assetId, assets)),
resolveAsset: (assetId) => {
diff --git a/site/src/cut/worker/Dockerfile b/site/src/cut/worker/Dockerfile
index 84c4cb00..26354367 100644
--- a/site/src/cut/worker/Dockerfile
+++ b/site/src/cut/worker/Dockerfile
@@ -30,6 +30,10 @@ RUN ffmpeg -hide_banner -encoders 2>&1 | grep -q '\blibx264\b' \
|| { echo "ffmpeg has no libx264: the share HLS ladder cannot encode." >&2; exit 1; }
WORKDIR /app
+# The server canvas for headless overlay rasterization. Kept out of the
+# bundle (worker:build marks it external) so its native binary installs for
+# this platform here.
+RUN npm install --no-package-lock --omit=dev skia-canvas@^3.0.8
COPY dist/cut-worker/main.js ./main.js
ENV NODE_ENV=production
diff --git a/site/src/cut/worker/r2.ts b/site/src/cut/worker/r2.ts
index f172d78e..0d72d09e 100644
--- a/site/src/cut/worker/r2.ts
+++ b/site/src/cut/worker/r2.ts
@@ -1,5 +1,5 @@
import { createReadStream } from "node:fs";
-import { mkdir, stat, writeFile } from "node:fs/promises";
+import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import type { Readable } from "node:stream";
import {
@@ -60,25 +60,57 @@ export async function deleteObjects(keys: string[]): Promise<void> {
/** Stream one R2 object to `dest`, creating its directory. */
export async function downloadToFile(key: string, dest: string): Promise<void> {
- const res = await r2().send(new GetObjectCommand({ Bucket: R2_BUCKET, Key: key }));
- if (!res.Body) throw new Error(`Empty R2 object: ${key}`);
- await mkdir(path.dirname(dest), { recursive: true });
- await writeFile(dest, res.Body as Readable);
+ // The GET is idempotent, and a streamed body can break mid-transfer on a
+ // network blip; a broken attempt rewrites the file whole on the retry.
+ let lastErr: unknown;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt > 0) await new Promise((r) => setTimeout(r, 500 * 2 ** (attempt - 1)));
+ try {
+ const res = await r2().send(new GetObjectCommand({ Bucket: R2_BUCKET, Key: key }));
+ if (!res.Body) throw new Error(`Empty R2 object: ${key}`);
+ await mkdir(path.dirname(dest), { recursive: true });
+ // Bun's fetch layer breaks on the SDK's Node stream; a dev worker run
+ // under Bun buffers the object. The container runs Node and streams.
+ if (process.versions.bun) {
+ await writeFile(dest, Buffer.from(await res.Body.transformToByteArray()));
+ } else {
+ await writeFile(dest, res.Body as Readable);
+ }
+ return;
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw lastErr;
}
/** Upload a local file to `key`, returning its byte size. */
export async function uploadFile(key: string, file: string, contentType: string): Promise<number> {
const info = await stat(file);
- await r2().send(
- new PutObjectCommand({
- Bucket: R2_BUCKET,
- Key: key,
- Body: createReadStream(file),
- ContentLength: info.size,
- ContentType: contentType,
- })
- );
- return info.size;
+ // A whole-object PUT is idempotent, and its streamed body can break on a
+ // network blip; each retry streams the file from the top.
+ let lastErr: unknown;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt > 0) await new Promise((r) => setTimeout(r, 500 * 2 ** (attempt - 1)));
+ try {
+ // Bun's fetch layer breaks on a Node stream body here; a dev worker run
+ // under Bun buffers the file instead. The container runs Node and streams.
+ const body = process.versions.bun ? await readFile(file) : createReadStream(file);
+ await r2().send(
+ new PutObjectCommand({
+ Bucket: R2_BUCKET,
+ Key: key,
+ Body: body,
+ ContentLength: info.size,
+ ContentType: contentType,
+ })
+ );
+ return info.size;
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw lastErr;
}
/** Upload `files` (paths relative to `dir`) under `keyPrefix`, a few at a time.