|
| 1 | +import { describe, expect, it, vi } from "vitest"; |
| 2 | +import { SessionCatalogListAdmission } from "./session-catalog-list-admission.js"; |
| 3 | + |
| 4 | +function deferred<T>() { |
| 5 | + let resolve!: (value: T) => void; |
| 6 | + let reject!: (reason: unknown) => void; |
| 7 | + const promise = new Promise<T>((resolvePromise, rejectPromise) => { |
| 8 | + resolve = resolvePromise; |
| 9 | + reject = rejectPromise; |
| 10 | + }); |
| 11 | + return { promise, reject, resolve }; |
| 12 | +} |
| 13 | + |
| 14 | +describe("SessionCatalogListAdmission", () => { |
| 15 | + it("starts at most the configured number of provider lists", async () => { |
| 16 | + const admission = new SessionCatalogListAdmission(2, 2); |
| 17 | + const gates = Array.from({ length: 4 }, () => deferred<number>()); |
| 18 | + const tasks = gates.map((gate) => vi.fn(() => gate.promise)); |
| 19 | + const pending = tasks.map((task) => admission.run(task)); |
| 20 | + |
| 21 | + expect(tasks.map((task) => task.mock.calls.length)).toEqual([1, 1, 0, 0]); |
| 22 | + gates[0]?.resolve(0); |
| 23 | + await expect(pending[0]).resolves.toBe(0); |
| 24 | + expect(tasks.map((task) => task.mock.calls.length)).toEqual([1, 1, 1, 0]); |
| 25 | + |
| 26 | + gates[1]?.resolve(1); |
| 27 | + gates[2]?.resolve(2); |
| 28 | + gates[3]?.resolve(3); |
| 29 | + await expect(Promise.all(pending)).resolves.toEqual([0, 1, 2, 3]); |
| 30 | + }); |
| 31 | + |
| 32 | + it("releases a slot after rejection and preserves FIFO order", async () => { |
| 33 | + const admission = new SessionCatalogListAdmission(1, 2); |
| 34 | + const active = deferred<void>(); |
| 35 | + const order: string[] = []; |
| 36 | + const first = admission.run(() => active.promise); |
| 37 | + const second = admission.run(async () => { |
| 38 | + order.push("second"); |
| 39 | + return 2; |
| 40 | + }); |
| 41 | + const third = admission.run(async () => { |
| 42 | + order.push("third"); |
| 43 | + return 3; |
| 44 | + }); |
| 45 | + |
| 46 | + active.reject(new Error("provider failed")); |
| 47 | + await expect(first).rejects.toThrow("provider failed"); |
| 48 | + await expect(Promise.all([second, third])).resolves.toEqual([2, 3]); |
| 49 | + expect(order).toEqual(["second", "third"]); |
| 50 | + }); |
| 51 | + |
| 52 | + it("rejects overflow without starting the provider", async () => { |
| 53 | + const admission = new SessionCatalogListAdmission(1, 1); |
| 54 | + const active = deferred<void>(); |
| 55 | + const first = admission.run(() => active.promise); |
| 56 | + const queued = admission.run(async () => undefined); |
| 57 | + const overflowTask = vi.fn(async () => undefined); |
| 58 | + |
| 59 | + await expect(admission.run(overflowTask)).rejects.toMatchObject({ code: "catalog_busy" }); |
| 60 | + expect(overflowTask).not.toHaveBeenCalled(); |
| 61 | + |
| 62 | + active.resolve(); |
| 63 | + await Promise.all([first, queued]); |
| 64 | + }); |
| 65 | +}); |
0 commit comments