Repository Public
1/**2 * The job queue: a table in the studio database, drained by a separate worker process (scripts/worker.ts).3 *4 * queued ──claim──▶ running ──▶ succeeded5 * ▲ │ ├──▶ failed (attempts exhausted, or an error that retrying cannot fix)6 * │ │ └──▶ cancelled (asked for in the studio; the worker stops ffmpeg)7 * └── retry with back-off, or recovery of a job whose worker died (no heartbeat)8 * failed ──manual retry──▶ queued queued ──cancel──▶ cancelled9 *10 * A claim is one atomic UPDATE inside a write transaction, so two workers can never take the same job.11 */12import { all, get, now, run, setMeta, getMeta, tx } from "./db";13import { ApiError } from "./http";1415export type JobState = "queued" | "running" | "succeeded" | "failed" | "cancelled";16export interface Job<P = unknown> {17 id: number; kind: string; payload: P; state: JobState; attempts: number; maxAttempts: number; runAfter: string; cancelRequested: boolean;18 lockedBy: string | null; heartbeatAt: string | null; progress: number; step: string | null; error: string | null; result: unknown; log: string | null;19 createdAt: string; createdBy: string; startedAt: string | null; finishedAt: string | null;20}21interface Raw { id: number; kind: string; payload: string; state: JobState; attempts: number; max_attempts: number; run_after: string; cancel_requested: number; locked_by: string | null; heartbeat_at: string | null; progress: number; step: string | null; error: string | null; result: string | null; log: string | null; created_at: string; created_by: string; started_at: string | null; finished_at: string | null }22const toJob = (r: Raw): Job => ({23 id: r.id, kind: r.kind, payload: JSON.parse(r.payload) as unknown, state: r.state, attempts: r.attempts, maxAttempts: r.max_attempts, runAfter: r.run_after, cancelRequested: r.cancel_requested === 1,24 lockedBy: r.locked_by, heartbeatAt: r.heartbeat_at, progress: r.progress, step: r.step, error: r.error, result: r.result ? JSON.parse(r.result) as unknown : null, log: r.log,25 createdAt: r.created_at, createdBy: r.created_by, startedAt: r.started_at, finishedAt: r.finished_at,26});2728/** An error that a new attempt cannot fix (invalid input, missing master): the job fails at once. */29export class PermanentJobError extends Error {}30export class JobCancelled extends Error { constructor() { super("Traitement annulé."); } }3132export const HEARTBEAT_KEY = "worker.heartbeat";33export const STALE_AFTER_MS = 90_000;34export const backoffSeconds = (attempt: number) => Math.min(900, 15 * 4 ** Math.max(0, attempt - 1)); // 15 s, 1 min, 4 min, 15 min3536export function enqueue(kind: string, payload: unknown, actor: string, opts: { maxAttempts?: number; runAfter?: Date } = {}): number {37 const r = run("INSERT INTO jobs (kind, payload, state, max_attempts, run_after, created_at, created_by) VALUES (?, ?, 'queued', ?, ?, ?, ?)",38 kind, JSON.stringify(payload), opts.maxAttempts ?? 3, (opts.runAfter ?? new Date()).toISOString(), now(), actor);39 return Number(r.lastInsertRowid);40}4142export const getJob = (id: number) => { const r = get<Raw>("SELECT * FROM jobs WHERE id = ?", id); return r ? toJob(r) : null; };43export function listJobs(o: { states?: JobState[]; limit?: number } = {}): Job[] {44 const states = o.states?.length ? o.states : null;45 return all<Raw>(`SELECT * FROM jobs ${states ? `WHERE state IN (${states.map(() => "?").join(",")})` : ""} ORDER BY id DESC LIMIT ?`, ...(states ?? []), Math.min(o.limit ?? 50, 200)).map(toJob);46}47export const jobCounts = () => Object.fromEntries(all<{ state: JobState; n: number }>("SELECT state, count(*) AS n FROM jobs GROUP BY state").map((r) => [r.state, r.n])) as Partial<Record<JobState, number>>;4849/** Takes the oldest due job, or returns null. Atomic: safe with several workers. */50export function claim(workerId: string, kinds?: string[]): Job | null {51 return tx(() => {52 const next = get<{ id: number }>(`SELECT id FROM jobs WHERE state = 'queued' AND run_after <= ? ${kinds?.length ? `AND kind IN (${kinds.map(() => "?").join(",")})` : ""} ORDER BY run_after, id LIMIT 1`, now(), ...(kinds ?? []));53 if (!next) return null;54 run("UPDATE jobs SET state = 'running', attempts = attempts + 1, locked_by = ?, heartbeat_at = ?, started_at = ?, finished_at = NULL, progress = 0, step = 'démarrage', error = NULL WHERE id = ? AND state = 'queued'", workerId, now(), now(), next.id);55 return getJob(next.id);56 });57}5859/** Called by the worker while it works. Returns false when the job must stop (cancelled, or taken away). */60export function heartbeat(id: number, workerId: string, progress?: number, step?: string): boolean {61 const j = get<{ state: JobState; locked_by: string | null; cancel_requested: number }>("SELECT state, locked_by, cancel_requested FROM jobs WHERE id = ?", id);62 if (!j || j.state !== "running" || j.locked_by !== workerId) return false;63 run("UPDATE jobs SET heartbeat_at = ?, progress = coalesce(?, progress), step = coalesce(?, step) WHERE id = ?", now(), progress === undefined ? null : Math.max(0, Math.min(1, progress)), step ?? null, id);64 return j.cancel_requested === 0;65}6667export function succeed(id: number, workerId: string, result: unknown, log?: string): void {68 run("UPDATE jobs SET state = 'succeeded', progress = 1, step = 'terminé', result = ?, log = ?, finished_at = ?, locked_by = NULL WHERE id = ? AND state = 'running' AND locked_by = ?", JSON.stringify(result ?? null), log?.slice(-8000) ?? null, now(), id, workerId);69}7071/** Records a failure: queued again with back-off while attempts remain, failed for good otherwise. Returns the new state. */72export function fail(id: number, workerId: string, error: unknown, log?: string): JobState {73 return tx(() => {74 const j = getJob(id);75 if (!j || j.state !== "running" || j.lockedBy !== workerId) return j?.state ?? "failed";76 const message = (error instanceof Error ? error.message : String(error)).slice(0, 1000);77 if (error instanceof JobCancelled || j.cancelRequested) {78 run("UPDATE jobs SET state = 'cancelled', error = ?, log = ?, finished_at = ?, locked_by = NULL WHERE id = ?", "Annulé à la demande d'un éditeur.", log?.slice(-8000) ?? null, now(), id);79 return "cancelled";80 }81 const retry = !(error instanceof PermanentJobError) && j.attempts < j.maxAttempts;82 if (retry) run("UPDATE jobs SET state = 'queued', error = ?, log = ?, run_after = ?, locked_by = NULL, step = ? WHERE id = ?", message, log?.slice(-8000) ?? null, new Date(Date.now() + backoffSeconds(j.attempts) * 1000).toISOString(), `nouvel essai (${j.attempts + 1} sur ${j.maxAttempts})`, id);83 else run("UPDATE jobs SET state = 'failed', error = ?, log = ?, finished_at = ?, locked_by = NULL WHERE id = ?", message, log?.slice(-8000) ?? null, now(), id);84 return retry ? "queued" : "failed";85 });86}8788/** Jobs whose worker stopped giving signs of life go back to the queue (or fail when out of attempts). */89export function recoverStale(olderThanMs = STALE_AFTER_MS): number {90 return tx(() => {91 const stale = all<Raw>("SELECT * FROM jobs WHERE state = 'running' AND (heartbeat_at IS NULL OR heartbeat_at < ?)", new Date(Date.now() - olderThanMs).toISOString()).map(toJob);92 for (const j of stale) {93 if (j.attempts < j.maxAttempts) run("UPDATE jobs SET state = 'queued', locked_by = NULL, run_after = ?, error = ?, step = 'repris après une interruption' WHERE id = ?", now(), "Le processus de traitement s'est interrompu ; le travail a été remis en file.", j.id);94 else run("UPDATE jobs SET state = 'failed', locked_by = NULL, finished_at = ?, error = ? WHERE id = ?", now(), "Le processus de traitement s'est interrompu à chaque essai.", j.id);95 }96 return stale.length;97 });98}99100/** A queued job is cancelled at once; a running one is flagged and stopped by its worker at the next heartbeat. */101export function requestCancel(id: number): Job {102 return tx(() => {103 const j = getJob(id);104 if (!j) throw new ApiError(404, "not_found", "Traitement introuvable.");105 if (j.state === "queued") run("UPDATE jobs SET state = 'cancelled', finished_at = ?, error = ? WHERE id = ?", now(), "Annulé avant d'avoir commencé.", id);106 else if (j.state === "running") run("UPDATE jobs SET cancel_requested = 1 WHERE id = ?", id);107 else throw new ApiError(409, "not_cancellable", "Ce traitement est déjà terminé.");108 return getJob(id)!;109 });110}111112export function retryJob(id: number): Job {113 return tx(() => {114 const j = getJob(id);115 if (!j) throw new ApiError(404, "not_found", "Traitement introuvable.");116 if (j.state !== "failed" && j.state !== "cancelled") throw new ApiError(409, "not_retryable", "Seul un traitement échoué ou annulé peut être relancé.");117 run("UPDATE jobs SET state = 'queued', attempts = 0, cancel_requested = 0, run_after = ?, error = NULL, progress = 0, step = 'relancé', finished_at = NULL WHERE id = ?", now(), id);118 return getJob(id)!;119 });120}121122export const beat = (workerId: string, info: Record<string, unknown> = {}) => setMeta(HEARTBEAT_KEY, JSON.stringify({ at: now(), workerId, ...info }));123export function workerStatus(): { state: "ok" | "stale" | "absent"; at: string | null; ageSeconds: number | null; info: Record<string, unknown> } {124 const raw = getMeta(HEARTBEAT_KEY);125 if (!raw) return { state: "absent", at: null, ageSeconds: null, info: {} };126 const { at, ...info } = JSON.parse(raw) as { at: string } & Record<string, unknown>, age = (Date.now() - Date.parse(at)) / 1000;127 return { state: age < 60 ? "ok" : "stale", at, ageSeconds: Math.round(age), info };128}129