import { describe, expect, it, vi } from "vitest"; import type { OutboxEvent, Prisma } from "../generated/prisma/client/client.js"; import { OUTBOX_DISPATCH_KEY_PATTERN, OUTBOX_EVENT_TYPE_PATTERN, OUTBOX_MAX_PAYLOAD_BYTES, OutboxPublishError, publishOutboxEvent, type OutboxEventWriterTx, type OutboxPublisherTransaction, } from "./outbox.js"; type FakeTx = OutboxEventWriterTx & { __isFakeTx: true }; function createFakeTx(overrides?: { create?: OutboxEventWriterTx["outboxEvent"]["create"]; findUnique?: OutboxEventWriterTx["outboxEvent"]["findUnique"]; }): FakeTx { const defaultCreate: OutboxEventWriterTx["outboxEvent"]["create"] = vi.fn(async ({ data }) => ({ id: "outbox_event_1", tenantId: data.tenantId ?? null, eventType: data.eventType, payload: data.payload as Prisma.JsonValue, status: data.status ?? "PENDING", createdAt: new Date("2026-05-17T08:00:00.000Z"), processedAt: null, retries: data.retries ?? 0, lastError: null, scheduledAt: data.scheduledAt ? new Date(data.scheduledAt) : new Date("2026-05-17T08:00:00.000Z"), dispatchKey: data.dispatchKey ?? null, priority: data.priority ?? 0, lockedUntil: null, }) as OutboxEvent); const defaultFindUnique: OutboxEventWriterTx["outboxEvent"]["findUnique"] = vi.fn(async () => null); return { __isFakeTx: true, outboxEvent: { create: overrides?.create ?? defaultCreate, findUnique: overrides?.findUnique ?? defaultFindUnique, }, }; } function asPublisherTx(tx: FakeTx): OutboxPublisherTransaction { return tx as unknown as OutboxPublisherTransaction; } describe("publishOutboxEvent", () => { it("inserts an event with sensible defaults", async () => { const tx = createFakeTx(); const created = await publishOutboxEvent(asPublisherTx(tx), { tenantId: "tenant_1", type: "billing.subscription.updated", payload: { customerId: "cus_1" }, }); expect(tx.outboxEvent.create).toHaveBeenCalledTimes(1); const createCall = (tx.outboxEvent.create as unknown as { mock: { calls: Array<[{ data: Prisma.OutboxEventUncheckedCreateInput }]> } }).mock.calls[0]?.[0]; expect(createCall?.data).toMatchObject({ tenantId: "tenant_1", eventType: "billing.subscription.updated", payload: { customerId: "cus_1" }, dispatchKey: null, }); // scheduledAt/priority default to DB defaults — they are NOT passed when undefined. expect(createCall?.data.scheduledAt).toBeUndefined(); expect(createCall?.data.priority).toBeUndefined(); expect(created.eventType).toBe("billing.subscription.updated"); }); it("passes scheduledAt and priority when provided", async () => { const tx = createFakeTx(); const future = new Date("2026-05-17T10:00:00.000Z"); await publishOutboxEvent(asPublisherTx(tx), { tenantId: null, type: "audit.log.recorded", payload: { actor: "system" }, scheduledAt: future, priority: 10, }); const callArgs = (tx.outboxEvent.create as unknown as { mock: { calls: Array<[{ data: Prisma.OutboxEventUncheckedCreateInput }]> } }).mock.calls[0]?.[0]; expect(callArgs?.data.scheduledAt).toBe(future); expect(callArgs?.data.priority).toBe(10); expect(callArgs?.data.tenantId).toBeNull(); }); it("returns the existing event when dispatchKey already exists", async () => { const existing: OutboxEvent = { id: "outbox_event_existing", tenantId: "tenant_1", eventType: "mail.send.queued", payload: { to: "u@example.com" } as Prisma.JsonValue, status: "PENDING", createdAt: new Date("2026-05-17T07:00:00.000Z"), processedAt: null, retries: 0, lastError: null, scheduledAt: new Date("2026-05-17T07:00:00.000Z"), dispatchKey: "billing:evt_1ABC", priority: 0, lockedUntil: null, }; const uniqueError = Object.assign(new Error("Unique constraint failed"), { code: "P2002" }); const tx = createFakeTx({ create: vi.fn(async () => { throw uniqueError; }), findUnique: vi.fn(async () => existing), }); const result = await publishOutboxEvent(asPublisherTx(tx), { tenantId: "tenant_1", type: "mail.send.queued", payload: { to: "u@example.com" }, dispatchKey: "billing:evt_1ABC", }); expect(result.id).toBe("outbox_event_existing"); expect(tx.outboxEvent.findUnique).toHaveBeenCalledWith({ where: { dispatchKey: "billing:evt_1ABC" }, }); }); it("rethrows unique violations when no dispatchKey was set", async () => { const uniqueError = Object.assign(new Error("unique violation"), { code: "P2002" }); const tx = createFakeTx({ create: vi.fn(async () => { throw uniqueError; }), }); await expect( publishOutboxEvent(asPublisherTx(tx), { type: "mail.send.queued", payload: { to: "u@example.com" }, }) ).rejects.toBe(uniqueError); }); it("rethrows non-unique-violation errors", async () => { const error = Object.assign(new Error("disk full"), { code: "P9999" }); const tx = createFakeTx({ create: vi.fn(async () => { throw error; }), }); await expect( publishOutboxEvent(asPublisherTx(tx), { type: "mail.send.queued", payload: {}, dispatchKey: "key-1", }) ).rejects.toBe(error); }); it("rejects malformed eventType values", async () => { const tx = createFakeTx(); await expect( publishOutboxEvent(asPublisherTx(tx), { type: "bad-format", payload: {}, }) ).rejects.toMatchObject({ name: "OutboxPublishError", code: "INVALID_EVENT_TYPE", }); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("rejects malformed dispatchKey values", async () => { const tx = createFakeTx(); await expect( publishOutboxEvent(asPublisherTx(tx), { type: "mail.send.queued", payload: {}, dispatchKey: "has spaces and bad ;chars", }) ).rejects.toMatchObject({ name: "OutboxPublishError", code: "INVALID_DISPATCH_KEY", }); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("rejects payloads larger than 64 KiB", async () => { const tx = createFakeTx(); const huge = "x".repeat(OUTBOX_MAX_PAYLOAD_BYTES + 1); await expect( publishOutboxEvent(asPublisherTx(tx), { type: "mail.send.queued", payload: { blob: huge }, }) ).rejects.toMatchObject({ name: "OutboxPublishError", code: "PAYLOAD_TOO_LARGE", }); }); it("constants are aligned with regex expectations", () => { expect(OUTBOX_EVENT_TYPE_PATTERN.test("billing.subscription.updated")).toBe(true); expect(OUTBOX_EVENT_TYPE_PATTERN.test("billing.subscription")).toBe(false); expect(OUTBOX_DISPATCH_KEY_PATTERN.test("billing:evt_1.subscription")).toBe(true); expect(OUTBOX_DISPATCH_KEY_PATTERN.test("")).toBe(false); }); it("exports OutboxPublishError with the documented codes", () => { const error = new OutboxPublishError("nope", "INVALID_EVENT_TYPE"); expect(error.name).toBe("OutboxPublishError"); expect(error.code).toBe("INVALID_EVENT_TYPE"); }); });