diff --git a/scripts/bvh-to-fbx.py b/scripts/bvh-to-fbx.py new file mode 100644 index 0000000..313add1 --- /dev/null +++ b/scripts/bvh-to-fbx.py @@ -0,0 +1,52 @@ +# Converts one Kimodo standard-T-pose BVH to one FBX. Blender converts formats and nothing else: no retarget, no +# rename, no key reduction, no resample, no in-place bake. Run by the daemon (scripts/vili-daemon.mjs exportClip): +# blender -b --factory-startup --python-use-system-env --python-exit-code 1 --python bvh-to-fbx.py -- +# with PYTHONHASHSEED=0 in the environment. The settings are Blender API parameters, cross-checked against the +# 'unity' preset of wifimetas/kimodo-mcp blender_export.py (Apache-2.0, 83b5361); no code is copied. +import datetime +import json +import sys +import types + +import bpy + +# io_scene_fbx hashes strings for UUIDs (fbx_utils.py) and stamps the file with now() (export_fbx_bin.py): a fixed +# hash seed and a fixed time make one BVH on one host body give one set of FBX bytes. +if sys.flags.hash_randomization != 0: + sys.exit(3) + +bvh, fbx, clip = sys.argv[sys.argv.index("--") + 1:] + +bpy.ops.wm.read_factory_settings(use_empty=True) +scene = bpy.context.scene +scene.unit_settings.system = "METRIC" +scene.unit_settings.scale_length = 1.0 + +import io_scene_fbx.export_fbx_bin as fbx_bin # after the factory reset, which the pin must outlive + +if not hasattr(fbx_bin, "datetime"): + raise RuntimeError("io_scene_fbx.export_fbx_bin no longer stamps with datetime: the pin must move") +fixed_time = datetime.datetime(1970, 1, 1) +fbx_bin.datetime = types.SimpleNamespace(datetime=types.SimpleNamespace(now=lambda: fixed_time)) + +bpy.ops.import_anim.bvh( + filepath=bvh, global_scale=0.01, axis_forward="-Z", axis_up="Y", rotate_mode="NATIVE", + use_fps_scale=False, update_scene_fps=True, frame_start=1, +) +armature = bpy.context.view_layer.objects.active +action = armature.animation_data.action +# The FBX take takes the scene's name. +armature.name = armature.data.name = action.name = scene.name = clip +first, last = (int(frame) for frame in action.frame_range) +scene.frame_start, scene.frame_end = first, last + +bpy.ops.object.select_all(action="DESELECT") +armature.select_set(True) +bpy.ops.export_scene.fbx( + filepath=fbx, use_selection=True, object_types={"ARMATURE"}, apply_unit_scale=True, + apply_scale_options="FBX_SCALE_ALL", axis_forward="-Z", axis_up="Y", add_leaf_bones=False, + primary_bone_axis="Y", secondary_bone_axis="X", armature_nodetype="NULL", bake_anim=True, + bake_anim_use_all_bones=True, bake_anim_use_nla_strips=False, bake_anim_use_all_actions=False, + bake_anim_force_startend_keying=True, bake_anim_step=1.0, bake_anim_simplify_factor=0.0, +) +print("VILI-FBX " + json.dumps({"bones": len(armature.data.bones), "frames": [first, last], "fps": scene.render.fps})) diff --git a/scripts/idunn-entry.mjs b/scripts/idunn-entry.mjs index 9fb062c..75883a0 100644 --- a/scripts/idunn-entry.mjs +++ b/scripts/idunn-entry.mjs @@ -104,7 +104,7 @@ function parseEntryArgs(argv) { } // What the daemon reads from its environment, derived from Idunn's bind and the sealed release's own layout: -// the interpreter sits beside the vili tree, and the environment's identity is the hash of the two lock files. +// the interpreter and Blender sit beside the vili tree, and the environment's identity is the hash of the two lock files. export function daemonEnvironment(bind, entryDir) { const { host, port } = splitBind(bind); const locks = ["requirements-build.lock", "requirements.lock"].map((name) => @@ -115,6 +115,7 @@ export function daemonEnvironment(bind, entryDir) { VILI_DAEMON_HOST: host, VILI_DAEMON_PORT: port, VILI_PYTHON: path.resolve(entryDir, "..", "..", "python", "bin", "python3.12"), + VILI_BLENDER: path.resolve(entryDir, "..", "..", "blender", "blender"), VILI_PYTHON_ENV: `locks-sha256:${createHash("sha256").update(Buffer.concat(locks)).digest("hex")}`, }; } diff --git a/scripts/vili-daemon.mjs b/scripts/vili-daemon.mjs index e7977ae..3e7042e 100644 --- a/scripts/vili-daemon.mjs +++ b/scripts/vili-daemon.mjs @@ -1,9 +1,9 @@ #!/usr/bin/env node import http from "node:http"; import os from "node:os"; -import { createHash } from "node:crypto"; -import { closeSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; -import { mkdir, writeFile } from "node:fs/promises"; +import { createHash, randomInt } from "node:crypto"; +import { closeSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; +import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import readline from "node:readline"; import net from "node:net"; @@ -74,6 +74,7 @@ const viliDocumentRegistry = defineDocumentRegistry( ); const MAX_THREADS = 16; +const CLIP_NAME = /^[A-Za-z0-9_-]{1,64}$/; // The state root's one identity: symlinks resolved as far as the path exists. The hand-run lock's name, reclaim's // marker and the worker's environment all derive from args.stateRoot, so two spellings of one root are one root. @@ -98,6 +99,7 @@ function parseArgs(argv) { threads: env.VILI_THREADS || "8", kimodoCommit: env.VILI_KIMODO_COMMIT || "", pythonEnv: env.VILI_PYTHON_ENV || "", + blender: env.VILI_BLENDER || "", }; for (let index = 0; index < argv.length; index += 1) { @@ -111,6 +113,7 @@ function parseArgs(argv) { else if (arg === "--threads") args.threads = argv[++index]; else if (arg === "--kimodo-commit") args.kimodoCommit = argv[++index]; else if (arg === "--python-env") args.pythonEnv = argv[++index]; + else if (arg === "--blender") args.blender = argv[++index]; } if (!/^[0-9]{1,2}$/.test(String(args.threads)) || Number(args.threads) < 1 || Number(args.threads) > MAX_THREADS) { console.error(`threads must be an integer from 1 to ${MAX_THREADS}`); @@ -119,16 +122,27 @@ function parseArgs(argv) { args.threads = Number(args.threads); args.stateRoot = canonicalPath(args.stateRoot); if (args.modelsRoot) args.modelsRoot = path.resolve(args.modelsRoot); + if (args.blender) args.blender = path.resolve(args.blender); return args; } const args = parseArgs(process.argv.slice(2)); const startedAt = new Date().toISOString(); +// The rest pose Kimodo ships, in the worker interpreter's own tree (/lib/python3.12/site-packages), once. +const restBvh = path.isAbsolute(args.python) + ? path.join(path.dirname(path.dirname(args.python)), "lib", "python3.12", "site-packages", "kimodo", "assets", "skeletons", "somaskel77", "somaskel77_standard_tpose.bvh") + : null; + // The worker child. Display state only: nothing reads `worker` to decide anything but ensureWorker. const worker = { state: "stopped", proc: null, pid: null, port: null, servedModels: [], lastError: null }; let starting = null; +// Blender, probed once after the lease. Display and admission state: it decides only whether an fbx request is +// refused early. `version` is the first line of `blender --version`, or null (unconfigured, or the probe failed). +const blender = { version: null }; +const blenderReady = () => blender.version !== null; + function firstDefined(...values) { return values.find((value) => value !== undefined && value !== null); } @@ -175,6 +189,7 @@ function backendStatus() { kimodoCommit: args.kimodoCommit || null, modelsRoot: args.modelsRoot || null, lastError: worker.lastError, + blender: blender.version ?? (args.blender ? "unavailable" : "unconfigured"), }; } @@ -192,6 +207,7 @@ function operatorState() { "animation job intake", "worker process lifecycle", "motion artifact references", + "clip export to FBX", ], doesNotOwn: [ "Persona speech generation", @@ -204,6 +220,8 @@ function operatorState() { health: "/health", operatorState: "/operator-state", generate: "/motion/generate", + artifacts: "/motion/artifacts/{jobId}/{name}", + restFbx: "/motion/rest-fbx", }, }; } @@ -225,8 +243,20 @@ function commandBoundary() { "worker process lifecycle", "timeout handling", "motion artifact references", + "clip export", ], }, + restFbx: { + method: "POST", + path: "/motion/rest-fbx", + owns: ["the rest-pose FBX job"], + }, + artifacts: { + method: "GET", + path: "/motion/artifacts/{jobId}/{name}", + owns: ["read-only artifact bytes"], + doesNotOwn: ["any path outside the job's artifact directory"], + }, liveness: { method: "GET", path: "/health", @@ -294,6 +324,21 @@ function childEnv() { return env; } +// The whole Blender environment, in one place: nothing else from process.env reaches it. The libraries the sealed +// release carries sit in blender/lib; PYTHONHASHSEED=0 is half of byte-reproducible export (scripts/bvh-to-fbx.py). +function exportEnv() { + const env = { + HOME: "/nonexistent", + PYTHONHASHSEED: "0", + PYTHONNOUSERSITE: "1", + LD_LIBRARY_PATH: path.join(path.dirname(args.blender), "lib"), + }; + for (const name of ["PATH", "LANG"]) { + if (process.env[name] !== undefined) env[name] = process.env[name]; + } + return env; +} + function workerUnconfigured() { return !args.modelsRoot || !args.kimodoCommit || !args.pythonEnv; } @@ -407,17 +452,187 @@ export function handRunRuntime(stateRoot) { }; } -// A requested stop gives the worker its grace (SIGTERM, then SIGKILL); a lost writer gets SIGKILL at once. -async function stopWorker(signals = ["SIGTERM", "SIGKILL"]) { +// A requested stop gives a process group its grace (SIGTERM, then SIGKILL); a lost writer gets SIGKILL at once. The +// worker and the exports are stopped by this one path. +async function stopGroups(procs, signals) { + for (const signal of signals) { + for (const proc of procs) if (proc.pid !== undefined) killGroup(proc.pid, signal); + const gone = await Promise.all(procs.map((proc) => waitForExit(proc, signal === "SIGTERM" ? 10000 : 5000))); + if (gone.every(Boolean)) break; + } +} + +const STOP_SIGNALS = ["SIGTERM", "SIGKILL"]; + +async function stopWorker(signals = STOP_SIGNALS) { const proc = worker.proc; if (!proc || proc.pid === undefined) return; worker.state = "stopped"; - for (const signal of signals) { - killGroup(proc.pid, signal); - if (await waitForExit(proc, signal === "SIGTERM" ? 10000 : 5000)) break; + await stopGroups([proc], signals); +} + +// Blender's process groups in flight. A finished export removes itself; a model switch (ensureWorker) leaves them alone. +const exportGroups = new Set(); +const stopExports = (signals = STOP_SIGNALS) => stopGroups([...exportGroups], signals); + +function isRegularFile(file) { + try { + return lstatSync(file).isFile(); + } catch { + return false; } } +// A regular file (no symlink, in the file or any directory above it) strictly inside `directory`, which is canonical. +function regularFileInside(file, directory) { + const relative = path.relative(directory, file); + if (!relative || path.isAbsolute(relative) || relative.split(path.sep)[0] === "..") return false; + try { + return lstatSync(file).isFile() && realpathSync(file) === file; + } catch { + return false; + } +} + +const exportScript = path.join(__dirname, "bvh-to-fbx.py"); +const EXPORT_SETTINGS = "standard-tpose soma77 metres hashseed0 time1970"; +const EXPORT_TIMEOUT_MS = 120000; +let exportScriptDigest = null; +const scriptDigest = () => (exportScriptDigest ??= `sha256:${createHash("sha256").update(readFileSync(exportScript)).digest("hex")}`); + +// Runs the sealed Blender in its own process group, niced, under the write gate. Both streams go to +// logs/export.log line by line through mayWrite(), and only there. Resolves { code, signal, first, result }: the +// exit, the first stdout line and the last `VILI-FBX ` line's payload. It rejects only with LeaseLost. +async function runBlender(argv, timeoutMs) { + guard(); + await mkdir(path.join(args.stateRoot, "logs"), { recursive: true }); + guard(); // synchronous with the log open and the spawn below: no await between them + const sink = openSync(path.join(args.stateRoot, "logs", "export.log"), "a"); + const proc = spawn(args.blender, argv, { + cwd: __dirname, + env: exportEnv(), + stdio: ["ignore", "pipe", "pipe"], + shell: false, + detached: true, + }); + exportGroups.add(proc); + const seen = { first: null, result: null }; + let sinkOpen = true; + for (const [stream, isStdout] of [[proc.stdout, true], [proc.stderr, false]]) { + if (!stream) continue; + readline.createInterface({ input: stream }).on("line", (line) => { + if (isStdout) { + seen.first ??= line; + if (line.startsWith("VILI-FBX ")) seen.result = line.slice("VILI-FBX ".length); + } + if (sinkOpen && mayWrite()) writeSync(sink, `${line}\n`); + }); + } + const finished = new Promise((resolve) => { + proc.once("error", () => resolve({ code: null, signal: null })); + proc.once("close", (code, signal) => resolve({ code, signal })); + }); + proc.once("exit", () => { + exportGroups.delete(proc); + if (proc.pid !== undefined) killGroup(proc.pid, "SIGKILL"); // whatever Blender left running + }); + try { + os.setPriority(proc.pid, 10); + } catch { + if (proc.pid !== undefined) killGroup(proc.pid, "SIGKILL"); + } + const timer = setTimeout(() => { + if (proc.pid !== undefined) killGroup(proc.pid, "SIGKILL"); + }, timeoutMs); + const exit = await finished; + clearTimeout(timer); + exportGroups.delete(proc); + sinkOpen = false; + closeSync(sink); + return { ...exit, ...seen }; +} + +// Blender answers once at start: `blender --version`, 15 s. Ready only when it exits 0 and names itself. +async function probeBlender() { + if (!args.blender) return; + const run = await runBlender(["-b", "--factory-startup", "--version"], 15000); + guard(); + blender.version = run.code === 0 && run.first?.startsWith("Blender ") ? run.first : null; +} + +// One BVH to one FBX beside it. The FBX counts only if Blender exits 0, prints its result line and the file exists. +// A failure names the exit or the signal and never Blender's output. +async function exportClip(bvh, fbx, clipName, timeoutMs) { + const run = await runBlender([ + "-b", "--factory-startup", "--python-use-system-env", "--python-exit-code", "1", + "--python", exportScript, "--", bvh, fbx, clipName, + ], timeoutMs); + guard(); // the writer may have been lost while Blender ran + let info = null; + if (run.code === 0 && run.result !== null) { + try { + const parsed = JSON.parse(run.result); + if (Number.isInteger(parsed.bones) && Array.isArray(parsed.frames) && parsed.frames.length === 2 + && parsed.frames.every(Number.isInteger) && Number.isFinite(parsed.fps)) info = parsed; + } catch { + // not the result line + } + } + if (info && isRegularFile(fbx)) return { clip: { file: fbx, clipName, bones: info.bones, frames: info.frames, fps: info.fps } }; + const how = run.code === 0 ? "no result" : run.code !== null ? `exit ${run.code}` : `signal ${run.signal ?? "none"}`; + return { error: `fbx-export-failed (${how})` }; +} + +// Every BVH the worker listed becomes an FBX, or the job fails. A listed BVH must be a regular file inside the job's +// artifact directory, and all are checked before Blender starts for any. Sample N of several is _NN. +async function exportListed(listed, artifactDir, clipName, timeoutMs) { + const bvhs = []; + for (const file of Array.isArray(listed) ? listed : []) { + if (typeof file !== "string" || !file.endsWith(".bvh")) continue; + const full = path.resolve(artifactDir, file); + if (!regularFileInside(full, artifactDir)) return { clips: [], error: "fbx-export-refused" }; + bvhs.push(full); + } + if (bvhs.length === 0) return { clips: [], error: "fbx-export-failed (no bvh)" }; + bvhs.sort(); + const clips = []; + for (const [index, bvh] of bvhs.entries()) { + const name = bvhs.length === 1 ? clipName : `${clipName}_${String(index).padStart(2, "0")}`; + const done = await exportClip(bvh, `${bvh.slice(0, -".bvh".length)}.fbx`, name, timeoutMs); + if (done.error) return { clips, error: done.error }; + clips.push({ ...done.clip, file: path.relative(artifactDir, done.clip.file).split(path.sep).join("/") }); + } + return { clips, error: null }; +} + +// Every regular file under the artifact directory, named relative to it, sorted. +async function artifactFiles(directory) { + const files = []; + const walk = async (relative) => { + for (const entry of readdirSync(path.join(directory, relative), { withFileTypes: true })) { + const name = path.join(relative, entry.name); + if (entry.isDirectory()) await walk(name); + else if (entry.isFile()) { + const bytes = await readFile(path.join(directory, name)); + files.push({ name: name.split(path.sep).join("/"), bytes: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex") }); + } + } + }; + await walk(""); + return files.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); +} + +// The one job record, for a generate job and a rest job alike: what the job was, which files it left and, for an +// export, the exact Blender and script that made them. +async function writeJobRecord(job, exported) { + guard(); + const record = { schema: "gamecult.vili.motion_job.v1", ...job, files: await artifactFiles(job.artifactDir) }; + if (exported) record.export = { blender: blender.version, script: scriptDigest(), settings: EXPORT_SETTINGS, clips: exported.clips }; + guard(); + await writeFile(path.join(args.stateRoot, "jobs", `${job.jobId}.json`), JSON.stringify(record, null, 2)); + return record; +} + async function startWorker(model, timeoutMs) { guard(); await mkdir(path.join(args.stateRoot, "logs"), { recursive: true }); @@ -524,9 +739,9 @@ async function readRequestBody(request) { return raw ? JSON.parse(raw) : {}; } -async function generateMotion(request, response) { +async function underLease(response, run) { try { - await generate(request, response); + await run(); } catch (error) { if (!(error instanceof LeaseLost)) throw error; json(response, 503, { ok: false, code: stopping ? "stopping" : runtime.refusal() }); @@ -562,7 +777,25 @@ async function generate(request, response) { return; } + // One export plan: fbx implies the BVH and its standard T-pose, which the FBX is made from. + const fbx = boolValue(body.fbx); + const askedTpose = firstDefined(body.bvhStandardTpose, body.bvh_standard_tpose); + if (fbx && ((askedTpose !== undefined && !boolValue(askedTpose)) + || (body.clipName !== undefined && !(typeof body.clipName === "string" && CLIP_NAME.test(body.clipName))))) { + json(response, 400, { ok: false, error: "Invalid fbx request." }); + return; + } + if (fbx && !blenderReady()) { + json(response, 503, { ok: false, code: "blender-unavailable" }); + return; + } + const plan = { + bvh: fbx || boolValue(body.bvh), + bvhStandardTpose: fbx || boolValue(askedTpose), + }; + const jobId = `vili-${Date.now()}`; + const clipName = fbx ? (body.clipName ?? jobId) : undefined; const artifactDir = path.join(args.stateRoot, "artifacts", jobId); guard(); await mkdir(artifactDir, { recursive: true }); @@ -574,7 +807,8 @@ async function generate(request, response) { bodyMeta.diffusion_steps, 20, ))); - const seed = body.seed === undefined ? null : Number(body.seed); + const askedSeed = Number(firstDefined(body.seed, bodyMeta.seed)); + const seed = Number.isFinite(askedSeed) ? askedSeed : randomInt(0, 2 ** 31); const numSamples = Math.max(1, Number(firstDefined( body.numSamples, body.num_samples, @@ -591,7 +825,7 @@ async function generate(request, response) { }; meta.num_samples = Math.max(1, Number(firstDefined(body.numSamples, body.num_samples, meta.num_samples, 1))); meta.diffusion_steps = diffusionSteps; - if (Number.isFinite(seed)) meta.seed = seed; + meta.seed = seed; if (body.cfg) meta.cfg = body.cfg; const constraintsPath = (() => { if (typeof body.constraints === "string") return body.constraints; @@ -615,12 +849,13 @@ async function generate(request, response) { diffusion_steps: diffusionSteps, numTransitionFrames: firstDefined(body.numTransitionFrames, body.num_transition_frames), constraints: constraintsPath, - seed: Number.isFinite(seed) ? seed : undefined, + seed, + fbx: fbx || undefined, + clipName, cfg: body.cfg, cfgType: firstDefined(body.cfgType, body.cfg_type), cfgWeight: firstDefined(body.cfgWeight, body.cfg_weight), - bvh: boolValue(body.bvh), - bvhStandardTpose: boolValue(firstDefined(body.bvhStandardTpose, body.bvh_standard_tpose)), + ...plan, noPostprocess: boolValue(firstDefined(body.noPostprocess, body.no_postprocess)), saveExampleDir: boolValue(firstDefined(body.saveExampleDir, body.save_example_dir)), inputFolder: firstDefined(body.inputFolder, body.input_folder), @@ -645,12 +880,11 @@ async function generate(request, response) { numSamples, numTransitionFrames: firstDefined(body.numTransitionFrames, body.num_transition_frames), constraints: constraintsPath, - seed: Number.isFinite(seed) ? seed : undefined, + seed, cfg: body.cfg, cfgType: firstDefined(body.cfgType, body.cfg_type), cfgWeight: firstDefined(body.cfgWeight, body.cfg_weight), - bvh: boolValue(body.bvh), - bvhStandardTpose: boolValue(firstDefined(body.bvhStandardTpose, body.bvh_standard_tpose)), + ...plan, noPostprocess: boolValue(firstDefined(body.noPostprocess, body.no_postprocess)), saveExampleDir: boolValue(firstDefined(body.saveExampleDir, body.save_example_dir)), output: path.join(artifactDir, "motion"), @@ -670,9 +904,15 @@ async function generate(request, response) { result = { ok: false, error: `the worker request failed (${error?.name || "Error"})`, body: null }; } + let exported = null; + if (fbx && result.ok) { + const timeoutMs = Math.min(EXPORT_TIMEOUT_MS, Math.max(1, Number(firstDefined(body.exportTimeoutMs, EXPORT_TIMEOUT_MS)) || EXPORT_TIMEOUT_MS)); + exported = await exportListed(result.body?.files, artifactDir, clipName, timeoutMs); + if (exported.error) result = { ok: false, error: exported.error, body: result.body }; + } + guard(); // the writer may have been lost while the job ran - const job = { - schema: "gamecult.vili.motion_job.v0", + const job = await writeJobRecord({ jobId, createdAt: new Date().toISOString(), prompt: prompt || null, @@ -685,11 +925,69 @@ async function generate(request, response) { ok: result.ok, error: result.error, worker: result.body, - }; - await writeFile(path.join(args.stateRoot, "jobs", `${jobId}.json`), JSON.stringify(job, null, 2)); + }, exported); json(response, result.ok ? 200 : 502, job); } +// The release's own rest pose, exported as the avatar cut's source: a job like any other, made from Kimodo's +// standard-T-pose BVH that the worker interpreter's site-packages carries. +async function restFbx(response) { + guard(); + if (!blenderReady()) { + json(response, 503, { ok: false, code: "blender-unavailable" }); + return; + } + if (!restBvh || !isRegularFile(restBvh)) { + json(response, 503, { ok: false, code: "rest-skeleton-missing" }); + return; + } + const jobId = `rest-${Date.now()}`; + const artifactDir = path.join(args.stateRoot, "artifacts", jobId); + guard(); + await mkdir(artifactDir, { recursive: true }); + guard(); + await copyFile(restBvh, path.join(artifactDir, "SOMA77_Rest.bvh")); + const exported = await exportListed([path.join(artifactDir, "SOMA77_Rest.bvh")], artifactDir, "SOMA77_Rest", EXPORT_TIMEOUT_MS); + guard(); + const job = await writeJobRecord({ + jobId, + createdAt: new Date().toISOString(), + prompt: null, + model: null, + request: null, + durationSeconds: null, + diffusionSteps: null, + seed: null, + artifactDir, + ok: !exported.error, + error: exported.error, + worker: null, + }, exported); + json(response, job.ok ? 200 : 502, job); +} + +// Reads only: a job's own FBX and BVH files, by exact name, regular files inside the job's artifact directory. +const ARTIFACT_ROUTE = /^\/motion\/artifacts\/((?:vili|rest)-[0-9]{13})\/(motion\.fbx|motion\.bvh|SOMA77_Rest\.fbx|motion\/motion_[0-9]{2}\.(?:fbx|bvh))$/; + +async function serveArtifact(response, jobId, name) { + const directory = path.join(args.stateRoot, "artifacts", jobId); + const file = path.join(directory, name); + let bytes = null; + if (regularFileInside(file, directory)) { + try { + bytes = await readFile(file); + } catch { + // gone between the check and the read + } + } + if (bytes === null) { + text(response, 404, "not found\n"); + return; + } + response.writeHead(200, { "content-type": "application/octet-stream", "cache-control": "no-store" }); + response.end(bytes); +} + const SNAPSHOT_BODY_MAX = 64 * 1024; // Idunn's route challenge: a msgpack POST from the host, answered from local authority. A browser page can send @@ -732,6 +1030,11 @@ async function handleRequest(request, response) { await answerRouteChallenge(request, response); return; } + const artifact = request.method === "GET" ? ARTIFACT_ROUTE.exec(url.pathname) : null; + if (artifact) { + await serveArtifact(response, artifact[1], artifact[2]); + return; + } if (request.method === "POST" && refuseCrossSite(request, response)) return; if (url.pathname === "/" || url.pathname === "/health") { @@ -739,7 +1042,9 @@ async function handleRequest(request, response) { } else if (url.pathname === "/operator-state") { json(response, 200, operatorState()); } else if (url.pathname === "/motion/generate" && request.method === "POST") { - await generateMotion(request, response); + await underLease(response, () => generate(request, response)); + } else if (url.pathname === "/motion/rest-fbx" && request.method === "POST") { + await underLease(response, () => restFbx(response)); } else { text(response, 404, "not found\n"); } @@ -792,7 +1097,7 @@ export async function serve(rt) { server.close(); server.closeIdleConnections(); clearInterval(tick); - await stopWorker(); + await Promise.all([stopWorker(), stopExports()]); runtime.release(); process.exit(0); }; @@ -805,13 +1110,14 @@ export async function serve(rt) { if (lost) return; lost = true; clearInterval(tick); - stopWorker(["SIGKILL"]).finally(() => runtime.reportHealth?.("degraded")); + Promise.all([stopWorker(["SIGKILL"]), stopExports(["SIGKILL"])]).finally(() => runtime.reportHealth?.("degraded")); }; runtime.watch(onLost); // held() reports a loss through this the moment any gate sees it try { guard(); await mkdir(path.join(args.stateRoot, "jobs"), { recursive: true }); await persistSurfaces(); + await probeBlender(); } catch (error) { if (error instanceof LeaseLost) return; // lost while opening the state root: onLost has run, and nothing is active throw error;