Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
raea cloud: a farm job's media by hash, from R2 and back to it, never through the box (CR23)
shinyobjectz2c84003a832c
diff --git a/sdk/cloud/deploy/modal/farm.py b/sdk/cloud/deploy/modal/farm.pyindex daf9d8c2..98f3567c 100644--- a/sdk/cloud/deploy/modal/farm.py+++ b/sdk/cloud/deploy/modal/farm.py@@ -7,6 +7,11 @@# POST /v1/jobs?args=JSON[&gpus=N][&gpu=KIND][&max_usd=X] body: the project as a tar. {id}# GET /v1/jobs/ID?from=N {log, next, exit?}, held up to 20 s for more# GET /v1/jobs/ID/out?as=zst|gz|tar the files the job made or changed; the job is removed+# GET /v1/jobs/ID/media with media=1: the job's media outputs [{path, oid, size}],+# left out of /out+# POST /v1/jobs/ID/media {objects: [{path, oid, href, header}]} PUTs each to its signed URL in R2 (farm_media.py)+# A job's folder may hold .raea-cloud-media.json: its media by Git LFS object id with URLs signed for it, fetched from+# R2 through a cache on the volume keyed by hash instead of coming in the tar (docs/cloud-render.feature CR23).## - `raea render X.tsx -o OUT.mp4|DIR`: frame 0 renders first on one GPU, to learn the piece's length and the price of# a frame; the frames then go out in runs to up to `gpus` GPUs (farm_plan.py sizes them), come back as PNGs, and the@@ -60,7 +65,7 @@ image = (.add_local_file(os.path.join(CLOUD, "image", "nvidia_icd.json"), "/usr/share/vulkan/icd.d/nvidia_icd.json", copy=True).env({"WGPU_BACKEND": "vulkan", "NVIDIA_DRIVER_CAPABILITIES": "all", "RAEA_CLIP_CHECK": "0", "RAEA_AUDIO_MUTE": "1","RAEA_MODELS": "/models/raea", "RAEA_FEED_MODELS": "/models/feed", "RAEA_LIBRARY_MODELS": "/models/library"})- .add_local_python_source("farm_plan", "prices")+ .add_local_python_source("farm_plan", "farm_media", "prices"))app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image)@@ -222,12 +227,20 @@ def blender_run(id: str, blend: str, start: int, end: int, opts: dict) -> dict:@app.function(cpu=2, memory=4096, volumes={ROOT: vol}, timeout=24 * 3600, secrets=[secret])def coordinate(id: str, args: list[str], opts: dict):+ import farm_mediaimport farm_planlog = Log(id)log(f"raea farm: raea {' '.join(args)}")vol.reload()work = f"{JOBS}/{id}/work"+ try:+ farm_media.fetch(work, f"{ROOT}/blobs", log)+ except Exception as e: # a file that didn't come, or came back as another: the job doesn't run+ log(f"raea farm: {e}", err=True)+ vol.commit()+ log.end(1)+ returnbefore = snapshot(work)try:code = farm_plan.dispatch(args, {**opts, "id": id}, work, log, raea_run, blender_run, CPU_ENV, run, vol.reload)@@ -236,8 +249,16 @@ def coordinate(id: str, args: list[str], opts: dict):code = 1vol.commit()after = snapshot(work)+ changed = [p for p, v in after.items() if before.get(p) != v]+ if opts.get("media"):+ # the job's media stays here until the box names where in R2 it goes (POST media); the rest comes back in /out+ media = farm_media.outputs(work, changed)+ with open(f"{JOBS}/{id}/media.json", "w") as f:+ json.dump(media, f)+ kept = {m["path"] for m in media}+ changed = [p for p in changed if p not in kept]with open(f"{JOBS}/{id}/changed.txt", "w") as f:- f.write("".join(p + "\n" for p, v in after.items() if before.get(p) != v))+ f.write("".join(p + "\n" for p in changed))shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True)vol.commit()log.end(code)@@ -276,7 +297,7 @@ def api():if not isinstance(args, list) or not all(isinstance(a, str) for a in args):raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments")q = req.query_params- opts = {"gpus": min(int(q.get("gpus", GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None}+ opts = {"gpus": min(int(q.get("gpus", GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}id = str(uuid.uuid4())work = f"{JOBS}/{id}/work"os.makedirs(work)@@ -310,6 +331,33 @@ def api():return JSONResponse(body if code is None else {**body, "exit": code})await asyncio.sleep(0.5)+ @web.get("/v1/jobs/{id}/media")+ def media_list(id: str, req: Request):+ check(req)+ if logs.get(f"{id}:exit") is None:+ raise HTTPException(404, "no such finished job")+ vol.reload()+ p = f"{JOBS}/{id}/media.json"+ return {"objects": json.load(open(p)) if os.path.exists(p) else []}++ @web.post("/v1/jobs/{id}/media")+ async def media_send(id: str, req: Request):+ import farm_media++ check(req)+ if logs.get(f"{id}:exit") is None:+ raise HTTPException(404, "no such finished job")+ await vol.reload.aio()+ body = await req.json()+ objects = body.get("objects") if isinstance(body, dict) else None+ if not isinstance(objects, list):+ raise HTTPException(400, "objects: [{path, oid, href, header}]")+ # said in this container's log, not the job's (its log is done, and Log would start it again)+ try:+ return await asyncio.to_thread(farm_media.upload, f"{JOBS}/{id}/work", objects, print)+ except ValueError as e:+ raise HTTPException(400, str(e))+@web.get("/v1/jobs/{id}/out")def out(id: str, req: Request):check(req)diff --git a/sdk/cloud/deploy/modal/farm_media.py b/sdk/cloud/deploy/modal/farm_media.pynew file mode 100644index 00000000..73502d95--- /dev/null+++ b/sdk/cloud/deploy/modal/farm_media.py@@ -0,0 +1,123 @@+# A farm job's media by hash (docs/cloud-render.feature CR23): its inputs come from R2 by their Git LFS object ids,+# through URLs raea's LFS signed for the box that sent the job, into a cache on the farm's volume keyed by hash, so a+# file is fetched once across every job and each is checked against its hash; the job's own media (a render, a+# sound) goes to R2 the same way, PUT to URLs signed for it, and the box writes only pointer files. The farm never holds+# a raea credential, only signed URLs that each reach one object.+#+# .raea-cloud-media.json in the job's folder, from the box: {"objects": [{"path", "oid", "size", "href", "header"}]}+# fetch(work, cache, ...) each object into the cache (once), then into its path in the job's folder+# outputs(work, changed) the job's media among what it made or changed: [{"path", "oid", "size"}]+# upload(work, objects) PUTs each to its signed URL: [{"path", "oid", "href", "header"}]++import hashlib+import json+import os+import shutil+import urllib.request++MANIFEST = ".raea-cloud-media.json"+# media by type, whatever the size, and anything at or over LARGE (the app's host/repo.ts MEDIA and LARGE)+MEDIA = set(+ "mp4 mov m4v webm mkv avi mxf mp3 wav aiff aif flac m4a ogg opus caf png jpg jpeg heic heif webp gif tif tiff exr hdr "+ "psd blend glb gltf fbx obj usd usdz abc ply splat spz ktx2 ttf otf woff woff2 zip tar gz zst safetensors onnx bin npz "+ "npy pdf".split()+)+LARGE = 4 * 1024 * 1024+CHUNK = 1 << 20+++def sha256(path):+ h = hashlib.sha256()+ with open(path, "rb") as f:+ for b in iter(lambda: f.read(CHUNK), b""):+ h.update(b)+ return h.hexdigest()+++def inside(work, rel):+ p = os.path.realpath(os.path.join(work, rel))+ return p == os.path.realpath(work) or p.startswith(os.path.realpath(work) + os.sep)+++def get(href, header, dest):+ req = urllib.request.Request(href, headers=header or {})+ with urllib.request.urlopen(req, timeout=600) as r, open(dest, "wb") as f:+ shutil.copyfileobj(r, f, CHUNK)+++def put(href, header, src, size):+ with open(src, "rb") as f:+ req = urllib.request.Request(href, data=f, method="PUT", headers={**(header or {}), "content-length": str(size)})+ with urllib.request.urlopen(req, timeout=1800) as r:+ r.read()+++def fetch(work, cache, log=print, download=get):+ """The job's media from R2 into its folder, through the cache: {objects, fetched, cached} (bytes)."""+ m = os.path.join(work, MANIFEST)+ if not os.path.exists(m):+ return {"objects": 0, "fetched": 0, "cached": 0}+ with open(m) as f:+ objects = json.load(f)["objects"]+ os.remove(m)+ os.makedirs(cache, exist_ok=True)+ fetched = cached = 0+ for o in objects:+ oid, path, size = o["oid"], o["path"], int(o["size"])+ if len(oid) != 64 or any(c not in "0123456789abcdef" for c in oid) or not inside(work, path):+ raise ValueError(f"media: {path!r} ({oid}) isn't a path in the job or an object id")+ blob = os.path.join(cache, oid)+ if os.path.exists(blob) and os.path.getsize(blob) == size:+ cached += size+ else:+ tmp = f"{blob}.part-{os.getpid()}"+ download(o["href"], o.get("header"), tmp)+ got = sha256(tmp)+ if got != oid or os.path.getsize(tmp) != size:+ os.remove(tmp)+ raise ValueError(f"media: {path} came back as {got[:12]}…, not {oid[:12]}…")+ os.replace(tmp, blob)+ fetched += size+ dest = os.path.join(work, path)+ os.makedirs(os.path.dirname(dest), exist_ok=True)+ if os.path.lexists(dest):+ os.remove(dest)+ shutil.copyfile(blob, dest)+ log(f"raea farm: {len(objects)} media files by hash, {fetched / 1e6:.1f} MB from R2, {cached / 1e6:.1f} MB already here")+ return {"objects": len(objects), "fetched": fetched, "cached": cached}+++def is_media(path, size):+ ext = path.rsplit(".", 1)[-1].lower() if "." in os.path.basename(path) else ""+ return ext in MEDIA or size >= LARGE+++def outputs(work, changed):+ """The job's media among the files it made or changed (paths relative to work), each with its hash and size. Files+ meant for outside the project (.raea-cloud-out) aren't: they go back whole, to be moved where the box asked."""+ out = []+ for rel in changed:+ p = os.path.join(work, rel)+ if rel.startswith(".raea-cloud-out") or not os.path.isfile(p) or os.path.islink(p):+ continue+ size = os.path.getsize(p)+ if is_media(rel, size):+ out.append({"path": rel, "oid": sha256(p), "size": size})+ return out+++def upload(work, objects, log=print, send=put):+ """Each named output PUT to its signed URL: {uploaded, bytes}. An object without an href is one R2 has already."""+ n = total = 0+ for o in objects:+ if not o.get("href"):+ continue+ if not inside(work, o["path"]):+ raise ValueError(f"media: {o['path']!r} isn't a path in the job")+ p = os.path.join(work, o["path"])+ size = os.path.getsize(p)+ send(o["href"], o.get("header"), p, size)+ n += 1+ total += size+ log(f"raea farm: {n} media files to R2, {total / 1e6:.1f} MB")+ return {"uploaded": n, "bytes": total}diff --git a/sdk/cloud/server/media.ts b/sdk/cloud/server/media.tsnew file mode 100644index 00000000..74e5a498--- /dev/null+++ b/sdk/cloud/server/media.ts@@ -0,0 +1,123 @@+// A GPU job's media by hash (docs/cloud-render.feature CR23), on the box's side. When the project is a raea repo (its+// .lfsconfig points at raea's LFS) and this box is signed in (RAEA_AGENT_KEY, an agent key with the repos scope, or+// RAEA_TOKEN), its media doesn't go to the farm in the tar:+// inputs each LFS file whose copy here is its committed one (or still a pointer) goes by its object id, with a+// download URL raea's LFS signs for it; the farm fetches it from R2 itself (farm_media.py). A media file+// changed here and not pushed goes in the tar as before.+// outputs the job's media stays on the farm; raea's LFS signs an upload URL for each, the farm PUTs it to R2, the+// upload is verified (so it counts in the account's storage), and here it becomes a pointer file, so its+// bytes never pass through this box. `git lfs pull PATH` brings one here when something wants it.++import { createHash } from "node:crypto"+import { spawnSync } from "node:child_process"+import { createReadStream, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"+import path from "node:path"+import type { Media } from "../src/index.ts"++const LFS = "application/vnd.git-lfs+json"+const POINTER = "version https://git-lfs.github.com/spec/v1"++interface Action {+ href: string+ header?: Record<string, string>+}+interface BatchObject {+ oid: string+ size: number+ actions?: { download?: Action; upload?: Action; verify?: Action }+ error?: { code: number; message: string }+}++export interface Lfs {+ url: string+ token: string+}++/** The project's raea LFS and this box's sign-in, or why its media goes in the tar. */+export function lfsOf(root: string): Lfs | string {+ if (process.env.RAEA_CLOUD_GPU_MEDIA === "0") return "RAEA_CLOUD_GPU_MEDIA=0"+ const token = process.env.RAEA_AGENT_KEY ?? process.env.RAEA_TOKEN+ if (!token) return "no raea sign-in here (RAEA_AGENT_KEY)"+ const cfg = path.join(root, ".lfsconfig")+ if (!existsSync(cfg)) return "the project has no .lfsconfig"+ const url = spawnSync("git", ["config", "-f", cfg, "--get", "lfs.url"], { encoding: "utf8" }).stdout.trim()+ if (!url) return "the project's .lfsconfig names no LFS"+ if (spawnSync("git", ["lfs", "version"]).status !== 0) return "git-lfs isn't here"+ return { url, token }+}++async function batch(lfs: Lfs, operation: "download" | "upload", objects: { oid: string; size: number }[]): Promise<BatchObject[]> {+ if (!objects.length) return []+ const r = await fetch(`${lfs.url}/objects/batch`, {+ method: "POST",+ headers: { authorization: `Bearer ${lfs.token}`, accept: LFS, "content-type": LFS },+ body: JSON.stringify({ operation, transfers: ["basic"], objects }),+ })+ if (!r.ok) throw new Error(`raea's LFS answered ${r.status} for a ${operation}: ${(await r.text()).slice(0, 200)}`)+ return ((await r.json()) as { objects: BatchObject[] }).objects+}++function sha256(file: string): Promise<string> {+ return new Promise((ok, fail) => {+ const h = createHash("sha256")+ createReadStream(file).on("data", (b) => h.update(b)).on("end", () => ok(h.digest("hex"))).on("error", fail)+ })+}++const isPointer = (file: string) => {+ try {+ return readFileSync(file).subarray(0, POINTER.length).toString() === POINTER+ } catch {+ return false+ }+}++/** The project's media that can go by hash: each with its signed download URL. */+export async function inputs(root: string, lfs: Lfs): Promise<Media[]> {+ const ls = spawnSync("git", ["-C", root, "lfs", "ls-files", "--json"], { encoding: "utf8", maxBuffer: 64 << 20 })+ if (ls.status !== 0) return []+ const files = ((JSON.parse(ls.stdout || "{}") as { files?: { name: string; oid: string; size: number }[] }).files ?? [])+ const same: { path: string; oid: string; size: number }[] = []+ for (const f of files) {+ const p = path.join(root, f.name)+ if (!existsSync(p)) continue+ if (isPointer(p) || (await sha256(p)) === f.oid) same.push({ path: f.name, oid: f.oid, size: f.size })+ }+ const got = new Map((await batch(lfs, "download", same.map(({ oid, size }) => ({ oid, size })))).map((o) => [o.oid, o]))+ return same.flatMap((f) => {+ const d = got.get(f.oid)?.actions?.download+ return d ? [{ ...f, href: d.href, header: d.header ?? {} }] : []+ })+}++/** The job's media outputs with where in R2 each goes; `done` then verifies them and writes their pointers here. */+export async function outputs(root: string, lfs: Lfs, made: Media[]): Promise<{ send: Media[]; done: () => Promise<number> }> {+ const asked = new Map((await batch(lfs, "upload", made.map(({ oid, size }) => ({ oid, size })))).map((o) => [o.oid, o]))+ const send = made.map((m) => {+ const up = asked.get(m.oid)?.actions?.upload+ return up ? { ...m, href: up.href, header: up.header ?? {} } : m+ })+ const done = async () => {+ let bytes = 0+ for (const m of made) {+ const v = asked.get(m.oid)?.actions?.verify+ if (v) {+ const r = await fetch(v.href, { method: "POST", headers: { ...v.header, accept: LFS, "content-type": LFS }, body: JSON.stringify({ oid: m.oid, size: m.size }) })+ if (!r.ok) throw new Error(`raea's LFS didn't verify ${m.path}: ${r.status}`)+ }+ const p = path.join(root, m.path)+ mkdirSync(path.dirname(p), { recursive: true })+ writeFileSync(p, `${POINTER}\noid sha256:${m.oid}\nsize ${m.size}\n`)+ const attr = spawnSync("git", ["-C", root, "check-attr", "filter", "--", m.path], { encoding: "utf8" }).stdout+ if (!/: lfs$/m.test(attr)) spawnSync("git", ["-C", root, "lfs", "track", "--filename", m.path])+ bytes += m.size+ }+ // its objects are in R2, not in this clone's LFS store: a push sends the pointers and git-lfs leaves the rest+ if (made.length) spawnSync("git", ["-C", root, "config", "lfs.allowincompletepush", "true"])+ return bytes+ }+ return { send, done }+}++/** tar's exclude-from lines for paths that go by hash: each matched as written (glob characters escaped) */+export const excludes = (media: Media[]) => media.map((m) => "./" + m.path.replace(/[\\*?[\]]/g, (c) => "\\" + c)).join("\n") + "\n"diff --git a/sdk/cloud/server/offload.ts b/sdk/cloud/server/offload.tsindex 8e2ce1d7..97cbf8c5 100644--- a/sdk/cloud/server/offload.ts+++ b/sdk/cloud/server/offload.ts@@ -8,6 +8,8 @@// it comes;// 3. the files it made or changed land back here: an output path outside the folder (-o /tmp/x.mp4) is written// there under .raea-cloud-out and moved to its place after.+// In a raea repo, with this box signed in, the project's media goes by hash instead (media.ts, CR23): the farm fetches+// it from R2, and the media the render makes goes to R2 from the farm, here only as pointer files.//// A render that reads a path outside its project (an input, --words, ...) can't go: it runs here, on the CPU, and// says why. So does every render when the worker can't be reached and RAEA_CLOUD_GPU_FALLBACK=cpu; otherwise that@@ -19,6 +21,7 @@ import os from "node:os"import path from "node:path"import { pathToFileURL } from "node:url"import { RaeaCloud } from "../src/index.ts"+import { excludes as mediaExcludes, inputs, lfsOf, outputs } from "./media.ts"const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"// flags whose value is a path raea writes; the rest of a render's path arguments are read@@ -94,7 +97,16 @@ async function main() {// zstd with GNU tar (the image's); gzip with another tar (a Mac's), whose zstd needs a program of its ownconst gnu = spawnSync("tar", ["--version"], { encoding: "utf8" }).stdout?.includes("GNU")const sent = path.join(tmp, "in.tar")- const pack = spawnSync("tar", [gnu ? "--zstd" : "-z", "-cf", sent, ...excludes.map((e) => `--exclude=${e}`), "-C", p.root, "."], { encoding: "utf8" })+ // the media that goes by hash: out of the tar, named in its manifest+ const lfs = lfsOf(p.root)+ const byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs)+ const extra: string[] = []+ if (byHash.length) {+ writeFileSync(path.join(tmp, "media-excludes"), mediaExcludes(byHash))+ writeFileSync(path.join(tmp, ".raea-cloud-media.json"), JSON.stringify({ objects: byHash }))+ extra.push("-X", path.join(tmp, "media-excludes"))+ }+ const pack = spawnSync("tar", [gnu ? "--zstd" : "-z", "-cf", sent, ...excludes.map((e) => `--exclude=${e}`), ...extra, "-C", p.root, ".", ...(byHash.length ? ["-C", tmp, ".raea-cloud-media.json"] : [])], { encoding: "utf8" })if (pack.status !== 0) throw new Error(`the project didn't pack: ${pack.stderr.trim()}`)const folder = new Uint8Array(readFileSync(sent))@@ -108,10 +120,18 @@ async function main() {throw new Error(`the GPU worker at ${url} didn't answer: ${(e as Error).message} (RAEA_CLOUD_GPU_FALLBACK=cpu renders here instead)`)}say(`rendering on ${new URL(url).host}, ${h.device.renders === "gpu" ? `GPU ${h.device.name}` : `its CPU (${h.device.name})`}: ${p.root} (${(folder.length / 1e6).toFixed(1)} MB) sent`)+ if (byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash: the farm fetches them from R2`)+ else if (typeof lfs === "string" && existsSync(path.join(p.root, ".lfsconfig"))) say(`media goes in the tar: ${lfs}`)// a render farm's choices (deploy/modal/farm.py): RAEA_CLOUD_GPUS, RAEA_CLOUD_GPU_KIND, RAEA_CLOUD_MAX_USDconst n = (v?: string) => (v ? Number(v) : undefined)- const farm = { gpus: n(process.env.RAEA_CLOUD_GPUS), gpu: process.env.RAEA_CLOUD_GPU_KIND, maxUsd: n(process.env.RAEA_CLOUD_MAX_USD) }- const { exit, files } = await cloud.job(p.args, folder, { as: gnu ? "zst" : "gz", farm, onOutput: (t, s) => (s === "out" ? process.stdout : process.stderr).write(t) })+ const farm = { gpus: n(process.env.RAEA_CLOUD_GPUS), gpu: process.env.RAEA_CLOUD_GPU_KIND, maxUsd: n(process.env.RAEA_CLOUD_MAX_USD), media: typeof lfs !== "string" }+ let finish: (() => Promise<number>) | undefined+ const media = typeof lfs === "string" ? undefined : async (made: Parameters<typeof outputs>[2]) => {+ const o = await outputs(p.root, lfs, made)+ finish = o.done+ return o.send+ }+ const { exit, files } = await cloud.job(p.args, folder, { as: gnu ? "zst" : "gz", farm, media, onOutput: (t, s) => (s === "out" ? process.stdout : process.stderr).write(t) })const back = path.join(tmp, "out.tar")writeFileSync(back, files)@@ -129,6 +149,10 @@ async function main() {}}rmSync(path.join(p.root, ".raea-cloud-out"), { recursive: true, force: true })+ if (finish) {+ const bytes = await finish()+ say(`its media (${(bytes / 1e6).toFixed(1)} MB) went from the farm to R2; here it's pointers (git lfs pull PATH brings one here)`)+ }say(`done on the GPU worker in ${((performance.now() - t0) / 1000).toFixed(1)} s, exit ${exit}`)process.exitCode = exit} finally {diff --git a/sdk/cloud/src/index.ts b/sdk/cloud/src/index.tsindex 92f764fa..c4d34e3f 100644--- a/sdk/cloud/src/index.ts+++ b/sdk/cloud/src/index.ts@@ -34,6 +34,17 @@ export interface Farm {gpus?: numbergpu?: stringmaxUsd?: number+ /** the job's media outputs stay on the farm for `media` to send to R2 (docs/cloud-render.feature CR23) */+ media?: boolean+}++/** A media file a farm job made, by its Git LFS object id; with `href`, where in R2 it goes (signed for it) */+export interface Media {+ path: string+ oid: string+ size: number+ href?: string+ header?: Record<string, string>}export interface JobLog {@@ -120,6 +131,7 @@ export class RaeaCloud {if (farm.gpus !== undefined) q.set("gpus", String(farm.gpus))if (farm.gpu) q.set("gpu", farm.gpu)if (farm.maxUsd !== undefined) q.set("max_usd", String(farm.maxUsd))+ if (farm.media) q.set("media", "1")const r = await this.call(`/v1/jobs?${q}`, { method: "POST", body: new Blob([folder as BlobPart]), headers: { "content-type": "application/octet-stream" }, signal })return ((await r.json()) as { id: string }).id}@@ -135,9 +147,22 @@ export class RaeaCloud {return new Uint8Array(await (await this.call(`/v1/jobs/${id}/out?as=${as}`)).arrayBuffer())}+ /** A finished job's media outputs (a job started with farm.media), held on the farm until sendMedia. */+ async jobMedia(id: string): Promise<Media[]> {+ return ((await (await this.call(`/v1/jobs/${id}/media`)).json()) as { objects: Media[] }).objects+ }++ /** Sends a job's media outputs to R2: each with an href goes there (a signed PUT), straight from the farm. */+ async sendMedia(id: string, objects: Media[]): Promise<{ uploaded: number; bytes: number }> {+ const r = await this.call(`/v1/jobs/${id}/media`, { method: "POST", body: JSON.stringify({ objects }), headers: { "content-type": "application/json" } })+ return r.json()+ }+/** A job from start to end: its output to onOutput as it comes; its exit code and the files it made or changed. A- * dropped follow request (a platform's proxy, a cold start) is tried again, up to five times in a row. */- async job(args: string[], folder: Uint8Array, o: { onOutput?: (text: string, stream: "out" | "err") => void; signal?: AbortSignal; as?: "zst" | "gz" | "tar"; farm?: Farm } = {}): Promise<{ exit: number; files: Uint8Array }> {+ * dropped follow request (a platform's proxy, a cold start) is tried again, up to five times in a row. With+ * `media` (and farm.media), the job's media outputs are handed to it first: it answers where in R2 each goes, the+ * farm sends them there, and they come back in `media`, not in `files`. */+ async job(args: string[], folder: Uint8Array, o: { onOutput?: (text: string, stream: "out" | "err") => void; signal?: AbortSignal; as?: "zst" | "gz" | "tar"; farm?: Farm; media?: (m: Media[]) => Promise<Media[]> } = {}): Promise<{ exit: number; files: Uint8Array; media: Media[] }> {const id = await this.startJob(args, folder, o.signal, o.farm)let from = 0for (let misses = 0; ; ) {@@ -152,7 +177,16 @@ export class RaeaCloud {}for (const l of f.log) "out" in l ? o.onOutput?.(l.out, "out") : o.onOutput?.(l.err, "err")from = f.next- if (f.exit !== undefined) return { exit: f.exit, files: await this.jobFiles(id, o.as) }+ if (f.exit === undefined) continue+ let media: Media[] = []+ if (o.farm?.media && o.media) {+ const made = await this.jobMedia(id)+ if (made.length) {+ media = await o.media(made)+ await this.sendMedia(id, media)+ }+ }+ return { exit: f.exit, files: await this.jobFiles(id, o.as), media }}}diff --git a/sdk/cloud/test/farm_media.py b/sdk/cloud/test/farm_media.pynew file mode 100644index 00000000..650db15a--- /dev/null+++ b/sdk/cloud/test/farm_media.py@@ -0,0 +1,107 @@+# The farm's media by hash (deploy/modal/farm_media.py) against a local HTTP server standing in for R2's signed URLs:+# python3 test/farm_media.py from sdk/cloud. Checked: a job's inputs come by hash into the cache once (a second job+# fetches nothing), a wrong hash and a path out of the job are refused, its media outputs are found by type and size+# and PUT to their URLs, and outputs meant for outside the project aren't.++import hashlib+import http.server+import json+import os+import sys+import tempfile+import threading++sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "deploy", "modal"))+import farm_media as fm # noqa: E402++ok = lambda m: print(f"ok {m}")+r2 = tempfile.mkdtemp()+hits = {"GET": 0, "PUT": 0}+++class R2(http.server.BaseHTTPRequestHandler):+ def log_message(self, *a):+ pass++ def do_GET(self):+ hits["GET"] += 1+ p = os.path.join(r2, self.path.strip("/"))+ if not os.path.exists(p):+ self.send_response(404)+ self.end_headers()+ return+ self.send_response(200)+ self.end_headers()+ self.wfile.write(open(p, "rb").read())++ def do_PUT(self):+ hits["PUT"] += 1+ if self.headers.get("x-signed") != "yes":+ self.send_response(403)+ self.end_headers()+ return+ n = int(self.headers["content-length"])+ open(os.path.join(r2, self.path.strip("/")), "wb").write(self.rfile.read(n))+ self.send_response(200)+ self.end_headers()+++srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), R2)+threading.Thread(target=srv.serve_forever, daemon=True).start()+base = f"http://127.0.0.1:{srv.server_address[1]}"++take = os.urandom(300_000)+oid = hashlib.sha256(take).hexdigest()+open(os.path.join(r2, oid), "wb").write(take)+cache = tempfile.mkdtemp()+++def job(objects):+ work = tempfile.mkdtemp()+ with open(os.path.join(work, fm.MANIFEST), "w") as f:+ json.dump({"objects": objects}, f)+ return work+++obj = {"path": "footage/take.mov", "oid": oid, "size": len(take), "href": f"{base}/{oid}", "header": {}}+w1 = job([obj])+s1 = fm.fetch(w1, cache, log=lambda _: None)+assert open(os.path.join(w1, "footage/take.mov"), "rb").read() == take+assert not os.path.exists(os.path.join(w1, fm.MANIFEST))+assert s1 == {"objects": 1, "fetched": len(take), "cached": 0}, s1+w2 = job([obj])+before = hits["GET"]+s2 = fm.fetch(w2, cache, log=lambda _: None)+assert hits["GET"] == before and s2["cached"] == len(take) and s2["fetched"] == 0, s2+ok("a job's input came from R2 by hash into the cache; the next job's came from the cache, nothing fetched")++bad = dict(obj, oid="0" * 64)+try:+ fm.fetch(job([bad]), tempfile.mkdtemp(), log=lambda _: None)+ raise SystemExit("FAIL a file with the wrong hash was taken")+except ValueError:+ pass+try:+ fm.fetch(job([dict(obj, path="../escape.mov")]), cache, log=lambda _: None)+ raise SystemExit("FAIL a path out of the job was taken")+except ValueError:+ pass+ok("a file that isn't its hash, and a path out of the job, are refused")++out = tempfile.mkdtemp()+os.makedirs(os.path.join(out, "out"))+render = os.urandom(200_000)+open(os.path.join(out, "out/edit.mp4"), "wb").write(render)+open(os.path.join(out, "out/notes.json"), "w").write("{}")+os.makedirs(os.path.join(out, ".raea-cloud-out"))+open(os.path.join(out, ".raea-cloud-out/0-x.mp4"), "wb").write(render)+found = fm.outputs(out, ["out/edit.mp4", "out/notes.json", ".raea-cloud-out/0-x.mp4"])+assert [o["path"] for o in found] == ["out/edit.mp4"] and found[0]["oid"] == hashlib.sha256(render).hexdigest(), found+ok("the job's media outputs are its video, not its small JSON, nor a file meant for outside the project")++send = [dict(found[0], href=f"{base}/{found[0]['oid']}", header={"x-signed": "yes"}), {"path": "out/kept.wav", "oid": "1" * 64, "size": 1}]+u = fm.upload(out, send, log=lambda _: None)+assert u == {"uploaded": 1, "bytes": len(render)}, u+assert open(os.path.join(r2, found[0]["oid"]), "rb").read() == render+ok("the render went to its signed URL in R2; an object R2 already has (no href) wasn't sent")+srv.shutdown()