import type { OutboxEvent, Prisma } from "../generated/prisma/client/client.js"; export type { OutboxEvent } from "../generated/prisma/client/client.js"; /** * Publisher API for the transactional outbox pattern. * * Producers call `publishOutboxEvent(tx, args)` from inside a Prisma * `$transaction` callback. The event row is committed atomically with the * surrounding DB writes, guaranteeing crash-safe side-effect delivery: the * dispatcher worker (apps/worker/src/outbox/dispatcher.ts) later claims * PENDING rows and dispatches them to BullMQ queues. * * The first argument is typed as {@link Prisma.TransactionClient} (a Prisma * client missing `$transaction`, `$connect`, etc) so that calling this helper * with a top-level `PrismaClient` singleton fails to type-check. * * See docs/architecture/outbox-pattern.md. */ /** * Event types follow the `..` convention (lowercase, * dot-separated). The dispatcher routes by the first segment, e.g. * `billing.subscription.updated` → `notification` queue. */ export const OUTBOX_EVENT_TYPE_PATTERN = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*){2,}$/u; /** * dispatchKey must be safe to use as a unique row key and must not leak * PII. The pattern allows alphanumerics, dashes, underscores, dots and * colons (good for namespaced keys like `billing:evt_1ABC.subscription`). */ export const OUTBOX_DISPATCH_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,256}$/u; export const OUTBOX_MAX_PAYLOAD_BYTES = 64 * 1024; export type OutboxPublishArgs = { /** * Nullable for system events that have no tenant context (e.g. * platform-wide maintenance). Set when the side-effect is tenant-scoped * so receivers can enforce tenant boundary checks on the payload. */ tenantId?: string | null; /** Event type, e.g. `billing.subscription.updated`. */ type: string; /** JSON payload. Must serialize cleanly to JSONB and stay under 64 KiB. */ payload: Prisma.InputJsonValue; /** * Optional idempotency key. When set, repeated publishes with the same * dispatchKey trigger a unique-constraint conflict and the helper returns * the existing event rather than inserting a duplicate. */ dispatchKey?: string | null; /** Schedule the event for later dispatch (default: immediately). */ scheduledAt?: Date; /** Higher = dispatched first when multiple events compete for capacity. */ priority?: number; }; /** * Minimal Prisma transaction surface the publisher needs. Tests inject * a fake matching this shape rather than a full PrismaClient stub. */ export type OutboxEventWriterTx = { outboxEvent: { create(args: { data: Prisma.OutboxEventUncheckedCreateInput }): Promise; findUnique(args: { where: { dispatchKey: string }; }): Promise; }; }; /** * Constrained TransactionClient type: the helper only accepts a * `Prisma.TransactionClient`, never a full `PrismaClient`. This is the * type-system guard that enforces "publish must run inside a transaction". */ export type OutboxPublisherTransaction = Prisma.TransactionClient & OutboxEventWriterTx; export class OutboxPublishError extends Error { public override readonly name = "OutboxPublishError"; public readonly code: | "INVALID_EVENT_TYPE" | "INVALID_DISPATCH_KEY" | "PAYLOAD_TOO_LARGE" | "INVALID_PAYLOAD"; constructor(message: string, code: OutboxPublishError["code"]) { super(message); this.code = code; } } function validateEventType(type: string): void { if (typeof type !== "string" || !OUTBOX_EVENT_TYPE_PATTERN.test(type)) { throw new OutboxPublishError( `Outbox eventType must match .. (got: ${JSON.stringify(type)}).`, "INVALID_EVENT_TYPE" ); } } function validateDispatchKey(dispatchKey: string | null | undefined): void { if (dispatchKey === null || dispatchKey === undefined) { return; } if (!OUTBOX_DISPATCH_KEY_PATTERN.test(dispatchKey)) { throw new OutboxPublishError( `Outbox dispatchKey must match ${OUTBOX_DISPATCH_KEY_PATTERN.source}.`, "INVALID_DISPATCH_KEY" ); } } function validatePayload(payload: Prisma.InputJsonValue): string { let serialized: string; try { serialized = JSON.stringify(payload); } catch (error) { throw new OutboxPublishError( `Outbox payload is not JSON-serializable: ${(error as Error).message}.`, "INVALID_PAYLOAD" ); } if (typeof serialized !== "string") { throw new OutboxPublishError("Outbox payload serialized to non-string.", "INVALID_PAYLOAD"); } if (Buffer.byteLength(serialized, "utf8") > OUTBOX_MAX_PAYLOAD_BYTES) { throw new OutboxPublishError( `Outbox payload exceeds ${OUTBOX_MAX_PAYLOAD_BYTES} bytes.`, "PAYLOAD_TOO_LARGE" ); } return serialized; } function isUniqueViolation(error: unknown): boolean { if (!error || typeof error !== "object") return false; const candidate = error as { code?: unknown }; return candidate.code === "P2002"; } /** * Insert an OutboxEvent row inside the surrounding Prisma transaction. * * - When `dispatchKey` collides with an existing row, the existing event is * returned (idempotent publish). * - When `scheduledAt` is set in the future, the event is queued but the * dispatcher skips it until `now()` catches up. * - When `payload` exceeds 64 KiB or fails JSON serialization, the helper * throws {@link OutboxPublishError} so callers can surface validation * errors before the surrounding transaction commits. */ export async function publishOutboxEvent( tx: OutboxPublisherTransaction, args: OutboxPublishArgs ): Promise { validateEventType(args.type); validateDispatchKey(args.dispatchKey); validatePayload(args.payload); try { return await tx.outboxEvent.create({ data: { tenantId: args.tenantId ?? null, eventType: args.type, payload: args.payload, dispatchKey: args.dispatchKey ?? null, ...(args.scheduledAt ? { scheduledAt: args.scheduledAt } : {}), ...(typeof args.priority === "number" ? { priority: args.priority } : {}), }, }); } catch (error) { if (isUniqueViolation(error) && args.dispatchKey) { const existing = await tx.outboxEvent.findUnique({ where: { dispatchKey: args.dispatchKey }, }); if (existing) { return existing; } } throw error; } }