Skip to content

Open source CapCut alternative.

TypeScript
2.7 KB
Raw Blame
// Wake the render worker's container. Fire-and-forget: a lost wake self-heals
// because the client keeps polling its queued job, and every such poll wakes
// again. The address is a hostname, so it lives in code (lib/hosts.ts) with the
// route that serves it; the shared secret is the only environment input, and
// holding it is the single switch that turns waking on. Unset (local dev), the
// dev worker is run by hand and polls on its own.
import { prisma } from "@/lib/prisma";
import { CUT_WORKER_WAKE_URL } from "@/cut/lib/hosts";

const wakeSecret = () => process.env.CUT_RENDER_WAKE_SECRET;

// A wake is idempotent on the Worker side, and the clients poll their jobs
// several times a second, so one wake per window per process is all the
// container ever needs. Without this, one status loop starts every replica
// on every poll.
const WAKE_WINDOW_MS = 5_000;
let lastWakeAt = 0;

// A wake that never lands strands every render — the container is not started
// and jobs queue forever — and retrying can't help, because the address itself
// is wrong. Nothing waits on the result, so the log is the only place it can
// show up; swallowing it is what let a dead wake go unnoticed for two days.
export function wakeRenderWorker(): void {
  const secret = wakeSecret();
  if (!secret) return;
  const now = Date.now();
  if (now - lastWakeAt < WAKE_WINDOW_MS) return;
  lastWakeAt = now;
  void wake(secret).catch((e: unknown) => {
    console.error("[cut] render worker wake failed:", e instanceof Error ? e.message : e);
  });
}

// The wake carries the queue's depth so the Worker starts as many replicas as
// there is work for. A container bills its full provisioned memory for every
// second it is up, idle included, so a replica started with nothing to claim is
// the pool's one avoidable cost. Running jobs count too: each one holds a
// replica, and the Worker starts past them so the queued work still lands on
// an idle box. A burst that arrives inside the wake window is picked up by the
// next status poll's wake, which counts again.
async function wake(secret: string): Promise<void> {
  // Command batches run in the editor inside the ChatGPT card, never here.
  const [queued, running] = await Promise.all([
    prisma.cutRenderJob.count({ where: { state: "queued", kind: { not: "commands" } } }),
    prisma.cutRenderJob.count({ where: { state: "running", kind: { not: "commands" } } }),
  ]);
  const res = await fetch(CUT_WORKER_WAKE_URL, {
    method: "POST",
    headers: { authorization: `Bearer ${secret}`, "content-type": "application/json" },
    body: JSON.stringify({ queued, running }),
  });
  if (!res.ok) console.error(`[cut] render worker wake refused: HTTP ${res.status}`);
}