import { describe, it, expect, vi } from "vitest"; import { normalizeStatus, normalizeTenantId, runOutboxRequeueById, runOutboxRequeueBulk, type OutboxRequeueClient, type OutboxRequeueEventRow, type OutboxRequeueOutput, type OutboxRequeueStatus, } from "./_lib.js"; describe("normalizeStatus", () => { it("throws on unknown database enum values", () => { expect(() => normalizeStatus("ARCHIVED")).toThrow(/Unrecognised OutboxStatus/); }); }); describe("normalizeTenantId", () => { it("trims the tenant identifier shared with the CLI RLS context", () => { expect(normalizeTenantId(" tenant-1 ")).toBe("tenant-1"); }); it("rejects empty and NUL-containing tenant identifiers", () => { expect(() => normalizeTenantId(" ")).toThrow(/--tenant/); expect(() => normalizeTenantId("tenant\u0000other")).toThrow(/--tenant/); }); }); interface FakeState { byId: Map; updates: Array<{ id: string; data: Record }>; updateMany: Array<{ ids: string[]; tenantId: string; status?: OutboxRequeueStatus[]; deliveryGeneration?: number; data: Record; }>; } function fakeClient(state: FakeState): OutboxRequeueClient { return { outboxEvent: { async findFirst({ where }) { const row = state.byId.get(where.id); return row?.tenantId === where.tenantId ? row : null; }, async update({ where, data }) { const row = state.byId.get(where.id); if (!row) throw new Error(`no row ${where.id}`); const next: OutboxRequeueEventRow = { ...row, status: data.status, retries: data.retries, deliveryGeneration: row.deliveryGeneration + data.deliveryGeneration.increment, }; state.byId.set(where.id, next); state.updates.push({ id: where.id, data: data as unknown as Record }); return next; }, async findMany({ where, take }) { const all = Array.from(state.byId.values()) .filter( (r) => r.tenantId === where.tenantId && r.eventType === where.eventType && r.createdAt >= where.createdAt.gte && where.status.in.includes(r.status) ) .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()) .slice(0, take); return all; }, async updateMany({ where, data }) { let count = 0; for (const id of where.id.in) { const row = state.byId.get(id); if (row) { if (row.tenantId !== where.tenantId) continue; if (where.status && !where.status.in.includes(row.status)) continue; if (where.deliveryGeneration !== undefined && row.deliveryGeneration !== where.deliveryGeneration) continue; state.byId.set(id, { ...row, status: data.status, retries: data.retries, deliveryGeneration: row.deliveryGeneration + data.deliveryGeneration.increment, }); count += 1; } } state.updateMany.push({ ids: where.id.in, tenantId: where.tenantId, ...(where.status ? { status: where.status.in } : {}), ...(where.deliveryGeneration !== undefined ? { deliveryGeneration: where.deliveryGeneration } : {}), data: data as unknown as Record, }); return { count }; }, }, }; } function makeOutput(): OutboxRequeueOutput & { logs: string[]; warns: string[]; errors: string[]; jsons: unknown[] } { const out = { logs: [] as string[], warns: [] as string[], errors: [] as string[], jsons: [] as unknown[], log(msg: string) { out.logs.push(msg); }, warn(msg: string) { out.warns.push(msg); }, error(msg: string) { out.errors.push(msg); }, json(payload: unknown) { out.jsons.push(payload); }, }; return out; } function row(id: string, overrides: Partial = {}): OutboxRequeueEventRow { return { id, eventType: "billing.subscription.ended", status: "FAILED", tenantId: "tenant-1", retries: 3, deliveryGeneration: 0, createdAt: new Date("2026-05-20T08:00:00Z"), ...overrides, }; } describe("runOutboxRequeueById", () => { it("re-queues a FAILED event and resets retry counters", async () => { const state: FakeState = { byId: new Map([["evt-1", row("evt-1", { status: "FAILED", retries: 5 })]]), updates: [], updateMany: [], }; const output = makeOutput(); const outcome = await runOutboxRequeueById( { tenantId: " tenant-1 ", eventId: "evt-1", now: new Date("2026-05-25T00:00:00Z") }, { client: fakeClient(state), output } ); expect(outcome.exitCode).toBe(0); expect(outcome.status).toBe("requeued"); expect(state.updateMany).toHaveLength(1); const update = state.updateMany[0]!.data as { status: OutboxRequeueStatus; retries: number; deliveryGeneration: { increment: number }; lastError: string | null; }; expect(update.status).toBe("PENDING"); expect(update.retries).toBe(0); expect(update.deliveryGeneration).toEqual({ increment: 1 }); expect(state.byId.get("evt-1")?.deliveryGeneration).toBe(1); expect(state.updateMany[0]).toMatchObject({ tenantId: "tenant-1", status: ["FAILED"], deliveryGeneration: 0 }); expect(update.lastError).toBeNull(); expect(output.logs.some((m) => m.includes("re-queued"))).toBe(true); }); it("emits JSON when --json is set", async () => { const state: FakeState = { byId: new Map([["evt-2", row("evt-2", { status: "FAILED" })]]), updates: [], updateMany: [], }; const output = makeOutput(); await runOutboxRequeueById({ tenantId: "tenant-1", eventId: "evt-2", json: true }, { client: fakeClient(state), output }); expect(output.jsons[0]).toEqual({ ok: true, eventId: "evt-2", previousStatus: "FAILED" }); expect(output.logs).toEqual([]); }); it("refuses to re-queue events still in PENDING", async () => { const state: FakeState = { byId: new Map([["evt-3", row("evt-3", { status: "PENDING" })]]), updates: [], updateMany: [], }; const output = makeOutput(); const outcome = await runOutboxRequeueById({ tenantId: "tenant-1", eventId: "evt-3" }, { client: fakeClient(state), output }); expect(outcome.exitCode).toBe(1); expect(outcome.status).toBe("refused"); expect(state.updates).toEqual([]); expect(output.errors[0]).toMatch(/refuse to re-queue/); }); it("refuses to re-queue events currently PROCESSING", async () => { const state: FakeState = { byId: new Map([["evt-4", row("evt-4", { status: "PROCESSING" })]]), updates: [], updateMany: [], }; const output = makeOutput(); const outcome = await runOutboxRequeueById({ tenantId: "tenant-1", eventId: "evt-4" }, { client: fakeClient(state), output }); expect(outcome.exitCode).toBe(1); expect(state.updates).toEqual([]); }); it("refuses DONE events because enqueue does not prove consumer completion", async () => { const state: FakeState = { byId: new Map([["evt-5", row("evt-5", { status: "DONE", retries: 0 })]]), updates: [], updateMany: [], }; const output = makeOutput(); const outcome = await runOutboxRequeueById({ tenantId: "tenant-1", eventId: "evt-5" }, { client: fakeClient(state), output }); expect(outcome.exitCode).toBe(1); expect(outcome.status).toBe("refused"); expect(state.updateMany).toHaveLength(0); expect(output.errors[0]).toMatch(/double-deliver/); }); it("returns not_found when the event does not exist", async () => { const state: FakeState = { byId: new Map(), updates: [], updateMany: [] }; const output = makeOutput(); const outcome = await runOutboxRequeueById({ tenantId: "tenant-1", eventId: "ghost" }, { client: fakeClient(state), output }); expect(outcome.exitCode).toBe(1); expect(outcome.status).toBe("not_found"); expect(output.errors[0]).toMatch(/not found/); }); it("emits JSON for not_found lookups when --json is set", async () => { const state: FakeState = { byId: new Map(), updates: [], updateMany: [] }; const output = makeOutput(); const outcome = await runOutboxRequeueById({ tenantId: "tenant-1", eventId: "ghost", json: true }, { client: fakeClient(state), output }); expect(outcome.status).toBe("not_found"); expect(output.jsons[0]).toEqual({ ok: false, reason: "not_found", eventId: "ghost" }); expect(output.errors).toEqual([]); }); it("does not reveal or update an event owned by another tenant", async () => { const state: FakeState = { byId: new Map([["evt-cross-tenant", row("evt-cross-tenant", { tenantId: "tenant-2" })]]), updates: [], updateMany: [], }; const output = makeOutput(); const outcome = await runOutboxRequeueById( { tenantId: "tenant-1", eventId: "evt-cross-tenant" }, { client: fakeClient(state), output } ); expect(outcome.status).toBe("not_found"); expect(state.updateMany).toEqual([]); expect(state.byId.get("evt-cross-tenant")?.status).toBe("FAILED"); }); }); describe("runOutboxRequeueBulk", () => { function bulkState(): FakeState { return { byId: new Map([ ["a", row("a", { status: "FAILED", createdAt: new Date("2026-05-21T00:00:00Z") })], ["b", row("b", { status: "FAILED", createdAt: new Date("2026-05-22T00:00:00Z") })], ["c", row("c", { status: "DONE", createdAt: new Date("2026-05-22T00:00:00Z") })], ["d", row("d", { status: "PENDING", createdAt: new Date("2026-05-22T00:00:00Z") })], ["e", row("e", { status: "FAILED", createdAt: new Date("2026-05-19T00:00:00Z") })], ["f", row("f", { eventType: "billing.subscription.cancelled", status: "FAILED", createdAt: new Date("2026-05-22T00:00:00Z") })], ["g", row("g", { tenantId: "tenant-2", status: "FAILED", createdAt: new Date("2026-05-22T00:00:00Z") })], ]), updates: [], updateMany: [], }; } it("previews matched count without writing when --apply is omitted", async () => { const state = bulkState(); const output = makeOutput(); const outcome = await runOutboxRequeueBulk( { tenantId: " tenant-1 ", type: "billing.subscription.ended", since: "2026-05-20T00:00:00Z" }, { client: fakeClient(state), output } ); expect(outcome.exitCode).toBe(0); expect(outcome.status).toBe("previewed"); expect(outcome.matched).toBe(2); expect(outcome.applied).toBe(0); expect(state.updateMany).toEqual([]); expect(output.logs[0]).toMatch(/dry-run/); }); it("re-queues matching events when --apply is set", async () => { const state = bulkState(); const output = makeOutput(); const outcome = await runOutboxRequeueBulk( { tenantId: "tenant-1", type: "billing.subscription.ended", since: "2026-05-20T00:00:00Z", apply: true, now: new Date("2026-05-25T00:00:00Z") }, { client: fakeClient(state), output } ); expect(outcome.exitCode).toBe(0); expect(outcome.status).toBe("requeued"); expect(outcome.applied).toBe(2); expect(state.updateMany).toHaveLength(2); expect(state.updateMany).toEqual( expect.arrayContaining([ expect.objectContaining({ tenantId: "tenant-1", status: ["FAILED"], deliveryGeneration: 0 }), ]) ); // FAILED rows a + b should have flipped to PENDING. expect(state.byId.get("a")?.status).toBe("PENDING"); expect(state.byId.get("b")?.status).toBe("PENDING"); expect(state.byId.get("a")?.deliveryGeneration).toBe(1); expect(state.byId.get("b")?.deliveryGeneration).toBe(1); expect(state.byId.get("c")?.status).toBe("DONE"); expect(state.byId.get("d")?.status).toBe("PENDING"); // already pending, untouched expect(state.byId.get("g")?.status).toBe("FAILED"); // same event type, different tenant }); it("rejects --include-done until consumer completion receipts exist", async () => { const state = bulkState(); const output = makeOutput(); const outcome = await runOutboxRequeueBulk( { tenantId: "tenant-1", type: "billing.subscription.ended", since: "2026-05-20T00:00:00Z", apply: true, includeDone: true }, { client: fakeClient(state), output } ); expect(outcome.exitCode).toBe(1); expect(outcome.status).toBe("invalid_args"); expect(state.byId.get("c")?.status).toBe("DONE"); }); it("rejects malformed event type", async () => { const state = bulkState(); const output = makeOutput(); const outcome = await runOutboxRequeueBulk( { tenantId: "tenant-1", type: "notavalidtype", since: "2026-05-20T00:00:00Z" }, { client: fakeClient(state), output } ); expect(outcome.exitCode).toBe(1); expect(outcome.status).toBe("invalid_args"); expect(output.errors[0]).toMatch(/must match/); }); it("rejects malformed --since", async () => { const state = bulkState(); const output = makeOutput(); const outcome = await runOutboxRequeueBulk( { tenantId: "tenant-1", type: "billing.subscription.ended", since: "not-a-date" }, { client: fakeClient(state), output } ); expect(outcome.exitCode).toBe(1); expect(outcome.status).toBe("invalid_args"); expect(output.errors[0]).toMatch(/ISO-8601/); }); it("emits JSON when --json is set", async () => { const state = bulkState(); const output = makeOutput(); await runOutboxRequeueBulk( { tenantId: "tenant-1", type: "billing.subscription.ended", since: "2026-05-20T00:00:00Z", apply: true, json: true }, { client: fakeClient(state), output } ); expect(output.jsons[0]).toMatchObject({ ok: true, applied: 2, matched: 2, eventType: "billing.subscription.ended" }); }); it("caps dry-run JSON previews at 10 rows", async () => { const state: FakeState = { byId: new Map( Array.from({ length: 12 }, (_, index) => { const id = `evt-${index + 1}`; return [id, row(id, { createdAt: new Date(`2026-05-${String(index + 1).padStart(2, "0")}T00:00:00Z`) })]; }) ), updates: [], updateMany: [], }; const output = makeOutput(); await runOutboxRequeueBulk( { tenantId: "tenant-1", type: "billing.subscription.ended", since: "2026-05-01T00:00:00Z", json: true }, { client: fakeClient(state), output } ); expect(output.jsons[0]).toMatchObject({ ok: true, applied: 0, matched: 12 }); expect((output.jsons[0] as { preview: unknown[] }).preview).toHaveLength(10); expect(state.updateMany).toEqual([]); }); it("returns matched=0 cleanly when no events match", async () => { const state = bulkState(); const output = makeOutput(); const outcome = await runOutboxRequeueBulk( { tenantId: "tenant-1", type: "billing.subscription.ended", since: "2030-01-01T00:00:00Z", apply: true }, { client: fakeClient(state), output } ); expect(outcome.exitCode).toBe(0); expect(outcome.matched).toBe(0); expect(outcome.applied).toBe(0); }); }); describe("outboxRequeueCommand argument handling", () => { it("is wired into the CLI subtree", async () => { const mod = await import("./index.js"); expect(mod.outboxCommand).toBeDefined(); expect(typeof mod.outboxRequeueCommand.run).toBe("function"); }); }); describe("OutboxRequeueClient narrowness", () => { it("only requires the four methods the runner consumes", () => { // This is a structural-typing sanity check: a client with extra // fields is still acceptable, but missing one of the four methods // must be a type error. The test is intentionally compile-time // adjacent; we keep one runtime assertion to keep vitest happy. const minimal: OutboxRequeueClient = { outboxEvent: { findFirst: vi.fn(async () => null), update: vi.fn( async (): Promise => ({ id: "x", eventType: "y.y.y", status: "PENDING" as OutboxRequeueStatus, tenantId: null, retries: 0, deliveryGeneration: 0, createdAt: new Date(), }) ), findMany: vi.fn(async () => []), updateMany: vi.fn(async () => ({ count: 0 })), }, }; expect(Object.keys(minimal.outboxEvent)).toHaveLength(4); }); });