Repository Public
1import { afterAll, beforeEach, describe, expect, it } from "vitest";2import { get, run } from "@/server/db";3import { ApiError } from "@/server/http";4import { JobCancelled, PermanentJobError, backoffSeconds, beat, claim, enqueue, fail, getJob, heartbeat, jobCounts, listJobs, recoverStale, requestCancel, retryJob, succeed, workerStatus } from "@/server/jobs";5import { runWorker, type Handler } from "@/server/worker";6import { cleanup, freshDataDir } from "./studio-helpers";78const state = (id: number) => getJob(id)!.state;9const code = (fn: () => unknown) => { try { fn(); return "ok"; } catch (e) { return e instanceof ApiError ? e.code : `other:${String(e)}`; } };10/** Makes a job that was put back in the queue with a delay due at once. */11const due = () => run("UPDATE jobs SET run_after = ? WHERE state = 'queued'", new Date(Date.now() - 1000).toISOString());12const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));1314beforeEach(async () => { await freshDataDir(); });15afterAll(cleanup);1617describe("queue state machine", () => {18 it("queued → running → succeeded, oldest first, one worker per job", () => {19 const a = enqueue("essai", { n: 1 }, "ed"), b = enqueue("essai", { n: 2 }, "ed");20 expect(listJobs().map((j) => j.state)).toEqual(["queued", "queued"]);21 const first = claim("w1")!;22 expect(first).toMatchObject({ id: a, state: "running", attempts: 1, lockedBy: "w1", payload: { n: 1 } });23 expect(claim("w2")!.id).toBe(b); // the second worker gets the next job, never the same one24 expect(claim("w3")).toBeNull();25 succeed(a, "w2", { vol: true }); // not the holder: ignored26 expect(state(a)).toBe("running");27 succeed(a, "w1", { fait: true });28 expect(getJob(a)).toMatchObject({ state: "succeeded", progress: 1, result: { fait: true }, lockedBy: null });29 expect(jobCounts()).toEqual({ succeeded: 1, running: 1 });30 });3132 it("claims only the kinds a worker can handle, and only jobs that are due", () => {33 const later = enqueue("essai", {}, "ed", { runAfter: new Date(Date.now() + 60_000) }), other = enqueue("autre", {}, "ed");34 expect(claim("w", ["essai"])).toBeNull();35 expect(claim("w", ["autre"])!.id).toBe(other);36 expect(state(later)).toBe("queued");37 });3839 it("retries a failure with back-off, then fails for good when attempts run out", () => {40 const id = enqueue("essai", {}, "ed", { maxAttempts: 3 });41 for (const attempt of [1, 2]) {42 claim("w");43 expect(fail(id, "w", new Error(`panne ${attempt}`))).toBe("queued");44 const j = getJob(id)!;45 expect(j).toMatchObject({ state: "queued", attempts: attempt, error: `panne ${attempt}`, lockedBy: null });46 expect(Date.parse(j.runAfter) - Date.now()).toBeGreaterThan((backoffSeconds(attempt) - 2) * 1000); // not before the back-off47 expect(claim("w")).toBeNull();48 due();49 }50 claim("w");51 expect(fail(id, "w", new Error("panne 3"))).toBe("failed");52 expect(getJob(id)).toMatchObject({ state: "failed", attempts: 3, error: "panne 3" });53 expect(getJob(id)!.finishedAt).not.toBeNull();54 expect([backoffSeconds(1), backoffSeconds(2), backoffSeconds(3), backoffSeconds(9)]).toEqual([15, 60, 240, 900]);55 });5657 it("does not retry an error that retrying cannot fix", () => {58 const id = enqueue("essai", {}, "ed");59 claim("w");60 expect(fail(id, "w", new PermanentJobError("Aucune piste vidéo dans ce fichier."))).toBe("failed");61 expect(getJob(id)).toMatchObject({ attempts: 1, error: "Aucune piste vidéo dans ce fichier." });62 });6364 it("cancels a queued job at once and a running one at its next heartbeat", () => {65 const queued = enqueue("essai", {}, "ed"), running = enqueue("essai", {}, "ed");66 run("UPDATE jobs SET run_after = ? WHERE id = ?", new Date(Date.now() + 60_000).toISOString(), queued);67 expect(requestCancel(queued).state).toBe("cancelled");68 claim("w");69 expect(heartbeat(running, "w", 0.4, "encodage")).toBe(true);70 expect(getJob(running)).toMatchObject({ progress: 0.4, step: "encodage" });71 expect(requestCancel(running)).toMatchObject({ state: "running", cancelRequested: true });72 expect(heartbeat(running, "w")).toBe(false); // the worker learns it must stop73 expect(fail(running, "w", new JobCancelled())).toBe("cancelled");74 expect(code(() => requestCancel(running))).toBe("not_cancellable");75 expect(code(() => requestCancel(9999))).toBe("not_found");76 });7778 it("lets only a failed or cancelled job be retried by hand, with a fresh count of attempts", () => {79 const id = enqueue("essai", {}, "ed", { maxAttempts: 1 });80 expect(code(() => retryJob(id))).toBe("not_retryable");81 claim("w"); fail(id, "w", new Error("x"));82 expect(retryJob(id)).toMatchObject({ state: "queued", attempts: 0, error: null, cancelRequested: false });83 expect(claim("w")!.attempts).toBe(1);84 });8586 it("recovers the jobs of a worker that died: back in the queue, or failed when out of attempts", () => {87 const a = enqueue("essai", {}, "ed", { maxAttempts: 2 }), b = enqueue("essai", {}, "ed", { maxAttempts: 1 }), alive = enqueue("essai", {}, "ed");88 claim("mort"); claim("mort"); claim("vivant");89 run("UPDATE jobs SET heartbeat_at = ? WHERE locked_by = 'mort'", new Date(Date.now() - 10 * 60_000).toISOString());90 expect(recoverStale()).toBe(2);91 expect(getJob(a)).toMatchObject({ state: "queued", lockedBy: null });92 expect(getJob(b)).toMatchObject({ state: "failed" });93 expect(state(alive)).toBe("running");94 expect(heartbeat(a, "mort")).toBe(false); // the dead worker, should it wake up, no longer owns the job95 succeed(a, "mort", {});96 expect(state(a)).toBe("queued");97 });9899 it("keeps a heartbeat that says whether a worker is alive", () => {100 expect(workerStatus().state).toBe("absent");101 beat("w1", { pid: 123, ffmpeg: true });102 expect(workerStatus()).toMatchObject({ state: "ok", info: { workerId: "w1", pid: 123, ffmpeg: true } });103 run("UPDATE meta SET value = ? WHERE key = 'worker.heartbeat'", JSON.stringify({ at: new Date(Date.now() - 5 * 60_000).toISOString(), workerId: "w1" }));104 expect(workerStatus()).toMatchObject({ state: "stale", ageSeconds: 300 });105 });106});107108describe("the worker process loop", () => {109 const opts = { drain: true, pollMs: 20, heartbeatMs: 20, timeoutMs: 5000 };110111 it("drains the queue with bounded concurrency and records results", async () => {112 let active = 0, peak = 0;113 const slow: Handler = async (job, ctx) => { active++; peak = Math.max(peak, active); ctx.progress(0.5, "à mi-chemin"); await sleep(60); active--; return { echo: job.payload }; };114 const ids = [1, 2, 3, 4, 5].map((n) => enqueue("essai", { n }, "ed"));115 const r = await runWorker({ ...opts, concurrency: 2, handlers: { essai: slow } });116 expect(r.processed).toBe(5);117 expect(peak).toBe(2); // never more than the configured concurrency118 expect(ids.map(state)).toEqual(Array(5).fill("succeeded"));119 expect(getJob(ids[0]!)).toMatchObject({ result: { echo: { n: 1 } }, progress: 1 });120 expect(workerStatus().state).toBe("ok");121 });122123 it("retries a failing job and gives up on a permanent error, without stopping the others", async () => {124 let calls = 0;125 const flaky: Handler = async () => { if (++calls === 1) throw new Error("panne passagère"); return "ok"; };126 const a = enqueue("capricieux", {}, "ed"), b = enqueue("impossible", {}, "ed"), c = enqueue("inconnu", {}, "ed");127 await runWorker({ ...opts, handlers: { capricieux: flaky, impossible: async () => { throw new PermanentJobError("entrée invalide"); } } });128 expect(getJob(a)).toMatchObject({ state: "queued", attempts: 1, error: "panne passagère" }); // waiting for its back-off129 expect(getJob(b)).toMatchObject({ state: "failed", attempts: 1, error: "entrée invalide" });130 expect(state(c)).toBe("queued"); // no handler for this kind here: left for a worker that has one131 due();132 await runWorker({ ...opts, handlers: { capricieux: flaky } });133 expect(getJob(a)).toMatchObject({ state: "succeeded", attempts: 2, result: "ok" });134 });135136 it("stops a job that is cancelled while it runs", async () => {137 let aborted = false;138 const long: Handler = (_job, ctx) => new Promise((_res, rej) => { ctx.signal.addEventListener("abort", () => { aborted = true; rej(new JobCancelled()); }); });139 const id = enqueue("long", {}, "ed");140 const done = runWorker({ ...opts, handlers: { long } });141 while (state(id) !== "running") await sleep(10);142 requestCancel(id);143 await done;144 expect(aborted).toBe(true);145 expect(getJob(id)).toMatchObject({ state: "cancelled" });146 });147148 it("gives a job back, without counting the attempt, when the worker itself is asked to stop", async () => {149 const stop = new AbortController();150 const long: Handler = (_job, ctx) => new Promise((_res, rej) => { ctx.signal.addEventListener("abort", () => rej(new JobCancelled())); });151 const id = enqueue("long", {}, "ed");152 const done = runWorker({ ...opts, drain: false, signal: stop.signal, handlers: { long } });153 while (state(id) !== "running") await sleep(10);154 stop.abort();155 await done;156 expect(getJob(id)).toMatchObject({ state: "queued", attempts: 0, lockedBy: null });157 expect(get<{ n: number }>("SELECT count(*) AS n FROM jobs WHERE state = 'running'")!.n).toBe(0);158 });159});160