import test from "node:test"; import assert from "node:assert/strict"; import { handOffSlot, type StartedJob } from "./handOff"; import type { JobDoneResult } from "./streamCommand"; // A started job whose log is `lines` and whose `done` settles when `finish` // is called. function fakeJob(jobId: string, lines: string[]) { let finish!: (status: JobDoneResult["status"]) => void; const done = new Promise((res) => { finish = (status) => res({ status, jobId }); }); let cancelled = false; const stream = new ReadableStream({ start(c) { for (const l of lines) c.enqueue(l); c.close(); }, cancel() { cancelled = true; }, }); const job: StartedJob = { ok: true, jobId, stream, done }; return { job, finish, wasCancelled: () => cancelled }; } async function readAll(stream: ReadableStream): Promise { const reader = stream.getReader(); let out = ""; for (;;) { const { value, done } = await reader.read(); if (done) return out; out += value; } } test("the caller reads both jobs' logs as one, and done settles with the second", async () => { const slot = handOffSlot(); const parent = fakeJob("w1", ["downloading\n", "handed off\n"]); const child = fakeJob("t1", ["Transcribe v done\n"]); const wrapped = slot.wrap(parent.job); assert.equal(wrapped.jobId, "w1"); slot.set(child.job); parent.finish("done"); assert.equal(await readAll(wrapped.stream), "downloading\nhanded off\nTranscribe v done\n"); let settled = false; const d = wrapped.done.then((r) => { settled = true; return r; }); await new Promise((r) => setTimeout(r, 10)); assert.equal(settled, false, "the download is done, the work is not"); child.finish("failed"); assert.deepEqual(await d, { status: "failed", jobId: "t1" }); }); test("a first job that fails, or hands nothing off, is the whole answer", async () => { const slot = handOffSlot(); const parent = fakeJob("w2", ["no url\n"]); const wrapped = slot.wrap(parent.job); parent.finish("failed"); assert.equal(await readAll(wrapped.stream), "no url\n"); assert.deepEqual(await wrapped.done, { status: "failed", jobId: "w2" }); }); test("a consumer that goes away cancels the second stream too, even before it exists", async () => { const slot = handOffSlot(); const parent = fakeJob("w3", ["downloading\n"]); const wrapped = slot.wrap(parent.job); await wrapped.stream.cancel(); assert.equal(parent.wasCancelled(), true); const child = fakeJob("t3", ["long log\n"]); slot.set(child.job); assert.equal(child.wasCancelled(), true, "an unread transcription log is not buffered"); });