SPB Git

Repository Public

worker.ts 9.6 KB 144 lines typescript

1/**2 * The media worker: drains the job queue with bounded concurrency. It runs as its own process3 * (scripts/worker.ts, a second PM2 process in production) so that an encode never blocks the web server.4 *5 * While it lives it writes a heartbeat (shown on the dashboard and in the health output), refreshes the6 * heartbeat of every job it holds, stops a job that was cancelled in the studio, puts back in the queue the7 * jobs of a worker that died, and clears abandoned uploads.8 */9import { existsSync } from "node:fs";10import { mkdir, rename, rm } from "node:fs/promises";11import { join } from "node:path";12import { env } from "../lib/env";13import { audit } from "./audit";14import { getCapsule, writeCapsule, type CapsuleStatus } from "./content";15import { randomId } from "./crypto";16import { get, run, tx } from "./db";17import { PermanentJobError, beat, claim, fail, heartbeat, recoverStale, succeed, type Job } from "./jobs";18import { log } from "./log";19import { paths } from "./storage";20import { ffmpegStatus, probe, transcode } from "./transcode";21import { masterFile, sweepUploads } from "./uploads";2223export interface JobContext { signal: AbortSignal; progress: (fraction: number, step: string) => void; timeoutMs: number; attempt: number }24export type Handler = (job: Job, ctx: JobContext) => Promise<unknown>;2526interface TranscodePayload { sessionId: string; capsuleId: string; masterSha: string }2728function setCapsuleStatus(p: TranscodePayload, status: CapsuleStatus) {29  tx(() => {30    const row = get<{ master_sha: string | null }>("SELECT master_sha FROM capsules WHERE session_id = ? AND id = ?", p.sessionId, p.capsuleId);31    if (row?.master_sha === p.masterSha) run("UPDATE capsules SET status = ? WHERE session_id = ? AND id = ?", status, p.sessionId, p.capsuleId);32  });33}34/** Where a capsule stands when its encode did not finish: still playable if an earlier encode exists. */35const restStatus = (p: TranscodePayload, failed: boolean): CapsuleStatus => {36  const row = get<{ data: string }>("SELECT data FROM capsules WHERE session_id = ? AND id = ?", p.sessionId, p.capsuleId);37  const hasMedia = row ? Boolean((JSON.parse(row.data) as { media?: { hls?: string } }).media?.hls) : false;38  return failed ? "failed" : hasMedia ? "ready" : "empty";39};4041/** validate with ffprobe → encode the ladder → poster and thumbnails → move into media/ → update the capsule. */42export const transcodeHandler: Handler = async (job, ctx) => {43  const p = job.payload as TranscodePayload;44  const master = masterFile(p.masterSha);45  if (!master) throw new PermanentJobError("Le fichier maître n'est plus dans le stockage.");46  const tools = await ffmpegStatus(true);47  if (!tools.ok) throw new PermanentJobError(tools.message!);48  setCapsuleStatus(p, "processing");49  ctx.progress(0.01, "validation du fichier (ffprobe)");50  const info = await probe(master, { signal: ctx.signal });51  run("UPDATE masters SET probe = ? WHERE sha256 = ?", JSON.stringify(info), p.masterSha);52  const scratch = join(paths.work, `job-${job.id}-${ctx.attempt}`);53  await rm(scratch, { recursive: true, force: true });54  try {55    const result = await transcode({ master, outDir: scratch, probe: info, timeoutMs: ctx.timeoutMs, signal: ctx.signal, onProgress: ctx.progress });56    // Each encode gets its own directory: files that a publication already names are never rewritten.57    const rev = `r${Date.now().toString(36)}${randomId(3)}`, rel = `${p.sessionId}/${p.capsuleId}/${rev}`, target = join(paths.media, rel);58    await mkdir(join(paths.media, p.sessionId, p.capsuleId), { recursive: true });59    await rename(scratch, target);60    const kept = tx(() => {61      const row = get<{ master_sha: string | null }>("SELECT master_sha FROM capsules WHERE session_id = ? AND id = ?", p.sessionId, p.capsuleId);62      if (row?.master_sha !== p.masterSha) return false; // the capsule was deleted, or another master replaced this one meanwhile63      const cur = getCapsule(p.sessionId, p.capsuleId), meta = get<{ filename: string; bytes: number }>("SELECT filename, bytes FROM masters WHERE sha256 = ?", p.masterSha);64      const data = {65        ...cur.data, durationSeconds: result.duration,66        media: { ...cur.data.media, hls: `${rel}/${result.files.hls}`, mp4: `${rel}/${result.files.mp4}`, poster: `${rel}/${result.files.poster}` },67        thumbs: result.files.thumbs.map((t) => `${rel}/${t}`),68        source: { width: info.width, height: info.height, fps: info.fps, videoCodec: info.videoCodec, audioCodec: info.audioCodec, bytes: meta?.bytes ?? 0, filename: meta?.filename ?? "" },69        renditions: result.renditions.map((r) => ({ height: r.height, width: r.width, bandwidth: r.bandwidth })),70      };71      writeCapsule({ ...cur, status: "ready", data }, "worker");72      audit("capsule.transcoded", { actor: "worker", target: `session:${p.sessionId}/capsule:${p.capsuleId}`, before: cur.data.media, after: data.media, detail: { jobId: job.id, renditions: result.renditions.map((r) => `${r.height}p`), duration: result.duration, bytes: result.bytes } });73      return true;74    });75    if (!kept) { await rm(target, { recursive: true, force: true }); return { discarded: "la capsule a changé pendant l'encodage" }; }76    return { media: rel, duration: result.duration, renditions: result.renditions, bytes: result.bytes };77  } finally { if (existsSync(scratch)) await rm(scratch, { recursive: true, force: true }); }78};7980export const HANDLERS: Record<string, Handler> = { transcode: transcodeHandler };8182export interface WorkerOptions {83  workerId?: string; concurrency?: number; pollMs?: number; timeoutMs?: number; heartbeatMs?: number; handlers?: Record<string, Handler>;84  /** Stop when the queue is empty and nothing is running (tests and one-shot runs). */85  drain?: boolean; signal?: AbortSignal;86}8788/** Runs one claimed job to its end state. Exported for the tests of the state machine. */89export async function runJob(job: Job, o: Required<Pick<WorkerOptions, "workerId" | "timeoutMs" | "heartbeatMs">> & { handlers: Record<string, Handler>; signal?: AbortSignal }): Promise<void> {90  const abort = new AbortController(), started = Date.now();91  let last = 0, shuttingDown = false;92  const onStop = () => { shuttingDown = true; abort.abort(); };93  o.signal?.addEventListener("abort", onStop, { once: true });94  const tick = setInterval(() => { if (!heartbeat(job.id, o.workerId)) abort.abort(); }, o.heartbeatMs);95  const progress = (fraction: number, step: string) => { if (Date.now() - last < 500 && fraction < 1) return; last = Date.now(); if (!heartbeat(job.id, o.workerId, fraction, step)) abort.abort(); };96  try {97    const handler = o.handlers[job.kind];98    if (!handler) throw new PermanentJobError(`Type de traitement inconnu : ${job.kind}.`);99    const result = await handler(job, { signal: abort.signal, progress, timeoutMs: o.timeoutMs, attempt: job.attempts });100    succeed(job.id, o.workerId, result);101    log("info", "job.succeeded", { id: job.id, kind: job.kind, seconds: Math.round((Date.now() - started) / 1000) });102  } catch (e) {103    if (shuttingDown) {104      // The worker is being stopped: give the job back without counting the attempt.105      run("UPDATE jobs SET state = 'queued', attempts = max(0, attempts - 1), locked_by = NULL, step = 'remis en file (arrêt du processus de traitement)' WHERE id = ? AND state = 'running' AND locked_by = ?", job.id, o.workerId);106      if (job.kind === "transcode") setCapsuleStatus(job.payload as TranscodePayload, "queued");107      log("warn", "job.released", { id: job.id, kind: job.kind });108      return;109    }110    const state = fail(job.id, o.workerId, e); // cancelled, queued again with back-off, or failed for good111    if (job.kind === "transcode") { const p = job.payload as TranscodePayload; setCapsuleStatus(p, state === "queued" ? "queued" : restStatus(p, state === "failed")); }112    log(state === "failed" ? "error" : "warn", `job.${state}`, { id: job.id, kind: job.kind, attempt: job.attempts, error: e });113  } finally { clearInterval(tick); o.signal?.removeEventListener("abort", onStop); }114}115116export async function runWorker(o: WorkerOptions = {}): Promise<{ processed: number }> {117  const workerId = o.workerId ?? `w_${process.pid}_${randomId(3)}`, concurrency = o.concurrency ?? env.workerConcurrency, pollMs = o.pollMs ?? 2000;118  const opts = { workerId, timeoutMs: o.timeoutMs ?? env.jobTimeoutSeconds * 1000, heartbeatMs: o.heartbeatMs ?? 5000, handlers: o.handlers ?? HANDLERS, signal: o.signal };119  const running = new Set<Promise<void>>();120  let processed = 0, lastSweep = 0;121  log("info", "worker.started", { workerId, concurrency, timeoutSeconds: opts.timeoutMs / 1000 });122  while (!o.signal?.aborted) {123    const tools = await ffmpegStatus();124    beat(workerId, { pid: process.pid, concurrency, running: running.size, ffmpeg: tools.ok });125    recoverStale();126    if (Date.now() - lastSweep > 3_600_000) { lastSweep = Date.now(); const n = await sweepUploads().catch(() => 0); if (n) log("info", "uploads.swept", { count: n }); }127    let claimed = false;128    while (running.size < concurrency) {129      const job = claim(workerId, Object.keys(opts.handlers));130      if (!job) break;131      claimed = true; processed++;132      log("info", "job.started", { id: job.id, kind: job.kind, attempt: job.attempts });133      const p: Promise<void> = runJob(job, opts).finally(() => running.delete(p));134      running.add(p);135    }136    if (o.drain && !running.size && !claimed) break;137    // Wake up when a job ends or after the poll interval, whichever comes first.138    await Promise.race([...running, new Promise((r) => setTimeout(r, running.size ? Math.min(pollMs, 1000) : pollMs))]);139  }140  await Promise.allSettled([...running]);141  log("info", "worker.stopped", { workerId, processed });142  return { processed };143}144
Files main
Menu

Theme