import { expect, test, vi } from "vitest"; import { createDownloadHistoryService, HISTORY_MAX_PAGE, streamWithAccounting, } from "./stream"; const downloadId = "11111111-1111-4111-8111-111111111111"; function accounting() { return { failBeforeDelivery: vi.fn().mockResolvedValue(true), markCompleted: vi.fn().mockResolvedValue(true), markInterrupted: vi.fn().mockResolvedValue(true), }; } async function readAll(stream: ReadableStream) { const reader = stream.getReader(); const chunks: Uint8Array[] = []; while (true) { const { done, value } = await reader.read(); if (done) return chunks; chunks.push(value); } } test("marks a new usage failed and voidable when upstream fails before its first byte", async () => { const repository = accounting(); const upstream = new ReadableStream({ pull(controller) { controller.error(new Error("upstream unavailable")); }, }); await expect( readAll( streamWithAccounting({ downloadId, upstream, voidNewUsageOnFailure: true, repository, }), ), ).rejects.toThrow("upstream unavailable"); expect(repository.failBeforeDelivery).toHaveBeenCalledOnce(); expect(repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, { voidNewUsage: true, }); expect(repository.markInterrupted).not.toHaveBeenCalled(); expect(repository.markCompleted).not.toHaveBeenCalled(); }); test("marks a repeat attempt failed without voiding its original usage", async () => { const repository = accounting(); const upstream = new ReadableStream({ start(controller) { controller.error(new Error("upstream unavailable")); }, }); await expect( readAll( streamWithAccounting({ downloadId, upstream, voidNewUsageOnFailure: false, repository, }), ), ).rejects.toThrow("upstream unavailable"); expect(repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, { voidNewUsage: false, }); }); test("marks a stream interrupted with the exact delivered byte count", async () => { const repository = accounting(); let pull = 0; const upstream = new ReadableStream({ pull(controller) { if (pull++ === 0) { controller.enqueue(new Uint8Array([1, 2, 3, 4])); return; } controller.error(new Error("connection reset")); }, }); await expect( readAll( streamWithAccounting({ downloadId, upstream, voidNewUsageOnFailure: true, repository, }), ), ).rejects.toThrow("connection reset"); expect(repository.markInterrupted).toHaveBeenCalledOnce(); expect(repository.markInterrupted).toHaveBeenCalledWith(downloadId, 4); expect(repository.failBeforeDelivery).not.toHaveBeenCalled(); }); test("marks a successful close completed with all delivered bytes", async () => { const repository = accounting(); const upstream = new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array([1, 2])); controller.enqueue(new Uint8Array([3, 4, 5])); controller.close(); }, }); await expect( readAll( streamWithAccounting({ downloadId, upstream, voidNewUsageOnFailure: true, repository, }), ), ).resolves.toHaveLength(2); expect(repository.markCompleted).toHaveBeenCalledOnce(); expect(repository.markCompleted).toHaveBeenCalledWith(downloadId, 5); expect(repository.markInterrupted).not.toHaveBeenCalled(); }); test("cancels upstream and contains a rejecting upstream cancellation", async () => { const repository = accounting(); const cancelError = new Error("cancel failed"); const upstreamCancel = vi.fn().mockRejectedValue(cancelError); const upstream = new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); }, cancel: upstreamCancel, }); const stream = streamWithAccounting({ downloadId, upstream, voidNewUsageOnFailure: true, repository, }); const reader = stream.getReader(); await reader.read(); await expect(reader.cancel("browser disconnected")).resolves.toBeUndefined(); expect(upstreamCancel).toHaveBeenCalledWith("browser disconnected"); expect(repository.markInterrupted).toHaveBeenCalledWith(downloadId, 3); expect(repository.markCompleted).not.toHaveBeenCalled(); }); test("settles terminal accounting exactly once when error and cancel race", async () => { const repository = accounting(); let rejectRead: ((error: Error) => void) | undefined; const upstream = new ReadableStream({ pull() { return new Promise((_resolve, reject) => { rejectRead = reject; }); }, cancel: vi.fn().mockResolvedValue(undefined), }); const stream = streamWithAccounting({ downloadId, upstream, voidNewUsageOnFailure: true, repository, }); const reader = stream.getReader(); const pendingRead = reader.read(); await Promise.resolve(); const cancellation = reader.cancel("closed"); rejectRead?.(new Error("late upstream error")); await Promise.allSettled([pendingRead, cancellation]); expect( repository.failBeforeDelivery.mock.calls.length + repository.markInterrupted.mock.calls.length + repository.markCompleted.mock.calls.length, ).toBe(1); }); test("normalizes and bounds history pagination before the scoped repository query", async () => { const repository = { listEditorialUsageHistory: vi.fn().mockResolvedValue({ items: [], attempts: [], page: HISTORY_MAX_PAGE, pageSize: 20, hasNext: false, attemptPageSize: 25, }), }; const history = createDownloadHistoryService({ repository }); await history.listEditorialUsageHistory( "11111111-1111-4111-8111-111111111111", "999999999999999999999999", "1786314600000000.22222222-2222-4222-8222-222222222222", ); expect(repository.listEditorialUsageHistory).toHaveBeenCalledWith( "11111111-1111-4111-8111-111111111111", HISTORY_MAX_PAGE, { authorizedAtMicros: "1786314600000000", downloadId: "22222222-2222-4222-8222-222222222222", }, ); }); test("rejects an invalid editorial scope before querying usage history", async () => { const repository = { listEditorialUsageHistory: vi.fn() }; const history = createDownloadHistoryService({ repository }); await expect(history.listEditorialUsageHistory("other-editorial", 1)).rejects.toMatchObject({ code: "INVALID_INPUT", }); expect(repository.listEditorialUsageHistory).not.toHaveBeenCalled(); });