diff --git a/backend/src/events/__tests__/bus.test.ts b/backend/src/events/__tests__/bus.test.ts new file mode 100644 index 00000000..d21cf77b --- /dev/null +++ b/backend/src/events/__tests__/bus.test.ts @@ -0,0 +1,466 @@ +/** + * backend/src/events/__tests__/bus.test.ts + * + * Unit tests for the typed domain event bus (issue #2258). Every documented + * behaviour — defaults, validation, dispatch, async handlers, failure + * isolation, unsubscribe, batches, malformed/unknown events and observability — + * is pinned here. + */ + +import { + createEventBus, + validateEventBusConfig, + EventBusError, + EventBusErrorCode, + DomainEventType, + DOMAIN_EVENT_TYPES, + DEFAULT_EVENT_BUS_CONFIG, + noopEventBusMetrics, + noopEventBusLogger, + type DomainEvent, + type EventBusMetrics, + type EventBusLogger, +} from '../bus'; + +/** Build a valid invoice.paid event, with optional field overrides. */ +function makeEvent( + type: DomainEventType = DomainEventType.INVOICE_PAID, + overrides: Partial = {} +): DomainEvent { + const base: DomainEvent = { + id: 'evt-1', + type, + occurredAt: '2026-01-01T00:00:00.000Z', + aggregateId: 'inv-1', + payload: { + invoiceId: 'inv-1', + subscriptionId: 'sub-1', + userId: 'user-1', + amountCents: 1299, + currency: 'USD', + }, + }; + return { ...base, ...overrides }; +} + +/** Build a spy metrics object that records every hook invocation. */ +function makeMetrics(): EventBusMetrics & { + calls: Array<{ method: string; args: unknown[] }>; +} { + const calls: Array<{ method: string; args: unknown[] }> = []; + const method = (name: string) => (...args: unknown[]) => { + calls.push({ method: name, args }); + }; + return { + calls, + recordPublished: method('recordPublished'), + recordDelivered: method('recordDelivered'), + recordHandlerFailed: method('recordHandlerFailed'), + recordNoHandlers: method('recordNoHandlers'), + recordRejected: method('recordRejected'), + recordSubscribed: method('recordSubscribed'), + recordUnsubscribed: method('recordUnsubscribed'), + recordBatchPublished: method('recordBatchPublished'), + recordCleared: method('recordCleared'), + }; +} + +/** Build a spy logger that records every level invocation. */ +function makeLogger(): EventBusLogger & { + calls: Array<{ level: string; message: string }>; +} { + const calls: Array<{ level: string; message: string }> = []; + const level = (name: string) => (message: string) => { + calls.push({ level: name, message }); + }; + return { + calls, + debug: level('debug'), + info: level('info'), + warn: level('warn'), + error: level('error'), + }; +} + +/** Assert that an async function rejects with an EventBusError of a given code. */ +async function expectCode(fn: () => Promise, code: string): Promise { + try { + await fn(); + throw new Error('expected function to reject'); + } catch (error) { + expect(error instanceof EventBusError).toBe(true); + expect((error as EventBusError).code).toBe(code); + } +} + +describe('error surface and constants', () => { + it('exposes stable error codes', () => { + expect(EventBusErrorCode.INVALID_CONFIG).toBe('INVALID_CONFIG'); + expect(EventBusErrorCode.INVALID_EVENT).toBe('INVALID_EVENT'); + expect(EventBusErrorCode.UNKNOWN_EVENT_TYPE).toBe('UNKNOWN_EVENT_TYPE'); + expect(EventBusErrorCode.INVALID_HANDLER).toBe('INVALID_HANDLER'); + expect(EventBusErrorCode.DUPLICATE_HANDLER).toBe('DUPLICATE_HANDLER'); + expect(EventBusErrorCode.MAX_HANDLERS_EXCEEDED).toBe('MAX_HANDLERS_EXCEEDED'); + }); + + it('exposes all lifecycle event types', () => { + expect(DomainEventType.SUBSCRIPTION_CREATED).toBe('subscription.created'); + expect(DomainEventType.SUBSCRIPTION_CANCELLED).toBe('subscription.cancelled'); + expect(DomainEventType.INVOICE_PAID).toBe('invoice.paid'); + expect(DomainEventType.HOUSEHOLD_INVITE_ACCEPTED).toBe('household.invite.accepted'); + expect(DomainEventType.PAYMENT_FAILED).toBe('payment.failed'); + expect(DOMAIN_EVENT_TYPES).toHaveLength(5); + }); + + it('builds a typed EventBusError with code and details', () => { + const error = new EventBusError(EventBusErrorCode.INVALID_EVENT, 'bad event', { + field: 'id', + }); + expect(error instanceof Error).toBe(true); + expect(error.name).toBe('EventBusError'); + expect(error.code).toBe('INVALID_EVENT'); + expect(error.message).toBe('bad event'); + expect(error.details).toEqual({ field: 'id' }); + }); + + it('provides no-op observability defaults', () => { + expect(typeof noopEventBusMetrics.recordPublished).toBe('function'); + expect(typeof noopEventBusMetrics.recordHandlerFailed).toBe('function'); + expect(typeof noopEventBusLogger.warn).toBe('function'); + expect(typeof noopEventBusLogger.error).toBe('function'); + }); +}); + +describe('validateEventBusConfig', () => { + it('fills in documented defaults', () => { + const config = validateEventBusConfig({}); + expect(config.maxHandlersPerEvent).toBe(32); + expect(config.strict).toBe(true); + expect(typeof config.clock).toBe('function'); + expect(DEFAULT_EVENT_BUS_CONFIG.maxHandlersPerEvent).toBe(32); + }); + + it('preserves valid overrides including a custom clock', () => { + const clock = () => 99; + const config = validateEventBusConfig({ + maxHandlersPerEvent: 3, + strict: false, + clock, + }); + expect(config.maxHandlersPerEvent).toBe(3); + expect(config.strict).toBe(false); + expect(config.clock()).toBe(99); + }); + + it('rejects invalid limits, strict flags, clocks and configs', () => { + expect(() => validateEventBusConfig({ maxHandlersPerEvent: 0 })).toThrow(EventBusError); + expect(() => validateEventBusConfig({ maxHandlersPerEvent: 1.5 })).toThrow(EventBusError); + expect(() => validateEventBusConfig({ strict: 'yes' as never })).toThrow(EventBusError); + expect(() => validateEventBusConfig({ clock: 12 as never })).toThrow(EventBusError); + expect(() => validateEventBusConfig(null as never)).toThrow(EventBusError); + }); +}); + +describe('publish', () => { + it('dispatches to every handler in registration order', async () => { + const bus = createEventBus(); + const seen: string[] = []; + bus.subscribe(DomainEventType.INVOICE_PAID, () => { + seen.push('first'); + }); + bus.subscribe(DomainEventType.INVOICE_PAID, () => { + seen.push('second'); + }); + const result = await bus.publish(makeEvent()); + expect(result.delivered).toBe(2); + expect(result.failed).toBe(0); + expect(result.handlerCount).toBe(2); + expect(seen).toEqual(['first', 'second']); + expect(result.event.id).toBe('evt-1'); + expect(result.durationMs).toBeGreaterThanOrEqual(0); + }); + + it('only dispatches to handlers for the matching event type', async () => { + const bus = createEventBus(); + const seen: string[] = []; + bus.subscribe(DomainEventType.SUBSCRIPTION_CREATED, () => seen.push('created')); + bus.subscribe(DomainEventType.INVOICE_PAID, () => seen.push('paid')); + await bus.publish(makeEvent()); + expect(seen).toEqual(['paid']); + }); + + it('awaits asynchronous handlers before resolving', async () => { + const bus = createEventBus(); + let finished = false; + bus.subscribe(DomainEventType.INVOICE_PAID, async () => { + await Promise.resolve(); + await Promise.resolve(); + finished = true; + }); + const result = await bus.publish(makeEvent()); + expect(finished).toBe(true); + expect(result.delivered).toBe(1); + expect(typeof result.durationMs).toBe('number'); + }); + + it('isolates a throwing handler from the remaining handlers', async () => { + const bus = createEventBus(); + const seen: string[] = []; + bus.subscribe(DomainEventType.PAYMENT_FAILED, () => { + throw new Error('boom'); + }); + bus.subscribe(DomainEventType.PAYMENT_FAILED, () => { + seen.push('survivor'); + }); + const result = await bus.publish(makeEvent(DomainEventType.PAYMENT_FAILED)); + expect(result.delivered).toBe(1); + expect(result.failed).toBe(1); + expect(result.handlerCount).toBe(2); + expect(result.failures).toHaveLength(1); + expect(result.failures[0]?.message).toBe('boom'); + expect(seen).toEqual(['survivor']); + }); + + it('isolates a rejecting async handler', async () => { + const bus = createEventBus(); + const seen: string[] = []; + bus.subscribe(DomainEventType.PAYMENT_FAILED, async () => { + await Promise.resolve(); + throw new Error('async boom'); + }); + bus.subscribe(DomainEventType.PAYMENT_FAILED, () => seen.push('survivor')); + const result = await bus.publish(makeEvent(DomainEventType.PAYMENT_FAILED)); + expect(result.failures[0]?.message).toBe('async boom'); + expect(seen).toEqual(['survivor']); + }); + + it('handles publishing with no registered handlers', async () => { + const bus = createEventBus(); + const result = await bus.publish(makeEvent()); + expect(result.handlerCount).toBe(0); + expect(result.delivered).toBe(0); + expect(result.failures).toHaveLength(0); + }); + + it('uses the injected clock for the duration metric', async () => { + let tick = 0; + const bus = createEventBus({ clock: () => (tick += 5) }); + const result = await bus.publish(makeEvent()); + expect(result.durationMs).toBe(5); + }); + + it('does not let a handler that unsubscribes affect the in-flight snapshot', async () => { + const bus = createEventBus(); + const seen: string[] = []; + const second = bus.subscribe(DomainEventType.INVOICE_PAID, () => seen.push('second')); + bus.subscribe(DomainEventType.INVOICE_PAID, () => { + seen.push('first'); + second.unsubscribe(); + }); + const result = await bus.publish(makeEvent()); + expect(seen).toEqual(['second', 'first']); + expect(result.handlerCount).toBe(2); + }); +}); + +describe('malformed and unknown events', () => { + it('rejects an event with missing fields', async () => { + const bus = createEventBus(); + await expectCode( + () => bus.publish({ id: 'evt-1', type: DomainEventType.INVOICE_PAID } as DomainEvent), + EventBusErrorCode.INVALID_EVENT + ); + }); + + it('rejects a non-object event, a blank id and an invalid timestamp', async () => { + const bus = createEventBus(); + await expectCode(() => bus.publish(null as never), EventBusErrorCode.INVALID_EVENT); + await expectCode( + () => bus.publish(makeEvent(DomainEventType.INVOICE_PAID, { id: '' })), + EventBusErrorCode.INVALID_EVENT + ); + await expectCode( + () => bus.publish(makeEvent(DomainEventType.INVOICE_PAID, { occurredAt: 'not-a-date' })), + EventBusErrorCode.INVALID_EVENT + ); + }); + + it('rejects an array payload and a blank aggregate id', async () => { + const bus = createEventBus(); + await expectCode( + () => bus.publish(makeEvent(DomainEventType.INVOICE_PAID, { payload: [] as never })), + EventBusErrorCode.INVALID_EVENT + ); + await expectCode( + () => bus.publish(makeEvent(DomainEventType.INVOICE_PAID, { aggregateId: '' })), + EventBusErrorCode.INVALID_EVENT + ); + }); + + it('rejects an unknown event type in strict mode', async () => { + const bus = createEventBus(); + await expectCode( + () => bus.publish(makeEvent('mystery.event' as DomainEventType)), + EventBusErrorCode.UNKNOWN_EVENT_TYPE + ); + }); + + it('accepts and dispatches an unknown type in non-strict mode', async () => { + const bus = createEventBus({ strict: false }); + let seen = false; + bus.subscribe('mystery.event' as DomainEventType, () => { + seen = true; + }); + const result = await bus.publish(makeEvent('mystery.event' as DomainEventType)); + expect(result.delivered).toBe(1); + expect(seen).toBe(true); + }); +}); + +describe('subscribe, unsubscribe, handlers and clear', () => { + it('registers handlers and exposes read-only snapshots', () => { + const bus = createEventBus(); + const handler = () => {}; + const sub = bus.subscribe(DomainEventType.SUBSCRIPTION_CREATED, handler); + expect(sub.id).toBe('handler-1'); + expect(sub.type).toBe('subscription.created'); + expect(bus.handlers(DomainEventType.SUBSCRIPTION_CREATED)).toHaveLength(1); + expect(bus.handlers()).toHaveLength(1); + expect(bus.handlers(DomainEventType.PAYMENT_FAILED)).toHaveLength(0); + }); + + it('rejects duplicate handlers and non-function handlers', () => { + const bus = createEventBus(); + const handler = () => {}; + bus.subscribe(DomainEventType.PAYMENT_FAILED, handler); + expect(() => bus.subscribe(DomainEventType.PAYMENT_FAILED, handler)).toThrow(EventBusError); + expect(() => bus.subscribe(DomainEventType.PAYMENT_FAILED, 42 as never)).toThrow(EventBusError); + }); + + it('enforces the maximum handlers per event type', () => { + const bus = createEventBus({ maxHandlersPerEvent: 1 }); + bus.subscribe(DomainEventType.PAYMENT_FAILED, () => {}); + expect(() => bus.subscribe(DomainEventType.PAYMENT_FAILED, () => {})).toThrow(EventBusError); + expect(bus.handlers(DomainEventType.PAYMENT_FAILED)).toHaveLength(1); + }); + + it('unsubscribes by id and by handler reference', () => { + const bus = createEventBus(); + const handler = () => {}; + const sub = bus.subscribe(DomainEventType.PAYMENT_FAILED, handler); + const other = () => {}; + bus.subscribe(DomainEventType.PAYMENT_FAILED, other); + expect(bus.unsubscribe(DomainEventType.PAYMENT_FAILED, sub.id)).toBe(true); + expect(bus.unsubscribe(DomainEventType.PAYMENT_FAILED, other)).toBe(true); + expect(bus.unsubscribe(DomainEventType.PAYMENT_FAILED, other)).toBe(false); + expect(bus.handlers(DomainEventType.PAYMENT_FAILED)).toHaveLength(0); + }); + + it('removes just this handler through the subscription handle', () => { + const bus = createEventBus(); + const sub = bus.subscribe(DomainEventType.INVOICE_PAID, () => {}); + expect(sub.unsubscribe()).toBe(true); + expect(sub.unsubscribe()).toBe(false); + expect(bus.handlers()).toHaveLength(0); + }); + + it('clears all handlers or only one event type', () => { + const bus = createEventBus(); + bus.subscribe(DomainEventType.INVOICE_PAID, () => {}); + bus.subscribe(DomainEventType.PAYMENT_FAILED, () => {}); + expect(bus.clear(DomainEventType.INVOICE_PAID)).toBe(1); + expect(bus.handlers()).toHaveLength(1); + expect(bus.clear()).toBe(1); + expect(bus.handlers()).toHaveLength(0); + expect(bus.clear()).toBe(0); + }); + + it('rejects unknown event types at subscribe time in strict mode', () => { + const bus = createEventBus(); + expect(() => bus.subscribe('mystery.event' as DomainEventType, () => {})).toThrow(EventBusError); + }); +}); + +describe('publishBatch', () => { + it('publishes events in order and returns one result each', async () => { + const bus = createEventBus(); + const seen: string[] = []; + bus.subscribe(DomainEventType.INVOICE_PAID, (event) => seen.push(event.payload.invoiceId)); + const results = await bus.publishBatch([ + makeEvent(DomainEventType.INVOICE_PAID), + makeEvent(DomainEventType.INVOICE_PAID, { + id: 'evt-2', + payload: { + invoiceId: 'inv-2', + subscriptionId: 'sub-1', + userId: 'user-1', + amountCents: 500, + currency: 'USD', + }, + }), + ]); + expect(results).toHaveLength(2); + expect(seen).toEqual(['inv-1', 'inv-2']); + expect(results[1]?.event.id).toBe('evt-2'); + }); + + it('rejects a non-array batch', async () => { + const bus = createEventBus(); + await expectCode( + () => bus.publishBatch('nope' as never), + EventBusErrorCode.INVALID_EVENT + ); + }); +}); + +describe('observability', () => { + it('emits metrics and logs across the full lifecycle', async () => { + const metrics = makeMetrics(); + const logger = makeLogger(); + const bus = createEventBus({}, metrics, logger); + const sub = bus.subscribe(DomainEventType.INVOICE_PAID, () => {}); + bus.subscribe(DomainEventType.PAYMENT_FAILED, () => { + throw new Error('handler failed'); + }); + await bus.publish(makeEvent()); + await bus.publish(makeEvent(DomainEventType.PAYMENT_FAILED)); + await bus.publish(makeEvent(DomainEventType.SUBSCRIPTION_CREATED)); + await bus.publishBatch([makeEvent()]); + sub.unsubscribe(); + bus.clear(); + + const names = metrics.calls.map((call) => call.method); + expect(names).toContain('recordSubscribed'); + expect(names).toContain('recordPublished'); + expect(names).toContain('recordDelivered'); + expect(names).toContain('recordHandlerFailed'); + expect(names).toContain('recordNoHandlers'); + expect(names).toContain('recordUnsubscribed'); + expect(names).toContain('recordBatchPublished'); + expect(names).toContain('recordCleared'); + + const levels = logger.calls.map((call) => call.level); + expect(levels).toContain('debug'); + expect(levels).toContain('info'); + expect(levels).toContain('error'); + }); + + it('emits a rejection metric and a warning log for a malformed event', async () => { + const metrics = makeMetrics(); + const logger = makeLogger(); + const bus = createEventBus({}, metrics, logger); + await expectCode( + () => bus.publish({ id: 'evt-1' } as DomainEvent), + EventBusErrorCode.INVALID_EVENT + ); + expect(metrics.calls.map((call) => call.method)).toContain('recordRejected'); + expect(logger.calls.map((call) => call.level)).toContain('warn'); + }); + + it('uses partial metrics and logger implementations safely', async () => { + const bus = createEventBus({}, { recordPublished: () => {} }, { info: () => {} }); + const result = await bus.publish(makeEvent()); + expect(result.delivered).toBe(0); + expect(result.failed).toBe(0); + }); +}); diff --git a/backend/src/events/bus.ts b/backend/src/events/bus.ts new file mode 100644 index 00000000..0230db8b --- /dev/null +++ b/backend/src/events/bus.ts @@ -0,0 +1,673 @@ +/** + * backend/src/events/bus.ts + * + * Typed in-process domain event bus for lifecycle changes between services + * (issue #2258). + * + * Backend services publish lifecycle events (subscription created/cancelled, + * invoice paid, household invite accepted, payment failed, ...); background + * workers subscribe to the exact same typed contracts and handle them. The bus + * is deliberately small and dependency-free so it can be used in unit tests, + * in the API process and in workers without adapters or transport concerns. + * + * Design rules: + * - Zero dependencies, no I/O, no ambient state. All state lives in the + * controller returned by {@link createEventBus}. + * - The clock is injectable, so dispatch timing is deterministic in tests. + * - Every rejection is a typed `EventBusError` carrying a stable `code`. + * - Handlers are isolated: a throwing or rejecting handler is recorded and + * reported, but never prevents the remaining handlers from running. + * - Subscriber snapshots are taken at publish time, so subscribing or + * unsubscribing from inside a handler cannot mutate an in-flight dispatch. + * - Metrics and logger hooks are optional; no-op defaults are provided. + * + * Usage: + * const bus = createEventBus({}, metrics, logger); + * const sub = bus.subscribe('invoice.paid', async (event) => reconcile(event)); + * await bus.publish({ id: 'evt-1', type: 'invoice.paid', + * occurredAt: new Date().toISOString(), aggregateId: 'inv-9', + * payload: { invoiceId: 'inv-9', subscriptionId: 'sub-1', + * userId: 'u-1', amountCents: 1299, currency: 'USD' } }); + * sub.unsubscribe(); + */ + +// --------------------------------------------------------------------------- +// Error surface +// --------------------------------------------------------------------------- + +/** Stable machine-readable codes emitted by this module. */ +export const EventBusErrorCode = { + INVALID_CONFIG: 'INVALID_CONFIG', + INVALID_EVENT: 'INVALID_EVENT', + UNKNOWN_EVENT_TYPE: 'UNKNOWN_EVENT_TYPE', + INVALID_HANDLER: 'INVALID_HANDLER', + DUPLICATE_HANDLER: 'DUPLICATE_HANDLER', + MAX_HANDLERS_EXCEEDED: 'MAX_HANDLERS_EXCEEDED', +} as const; + +/** Union of every stable error code emitted by this module. */ +export type EventBusErrorCode = (typeof EventBusErrorCode)[keyof typeof EventBusErrorCode]; + +/** Typed error thrown for invalid config, events, handlers and subscriptions. */ +export class EventBusError extends Error { + readonly code: EventBusErrorCode; + readonly details: Readonly>; + + constructor( + code: EventBusErrorCode, + message: string, + details: Readonly> = {} + ) { + super(message); + this.name = 'EventBusError'; + this.code = code; + this.details = details; + } +} + +// --------------------------------------------------------------------------- +// Event vocabulary +// --------------------------------------------------------------------------- + +/** Lifecycle event types understood by the bus. */ +export const DomainEventType = { + SUBSCRIPTION_CREATED: 'subscription.created', + SUBSCRIPTION_CANCELLED: 'subscription.cancelled', + INVOICE_PAID: 'invoice.paid', + HOUSEHOLD_INVITE_ACCEPTED: 'household.invite.accepted', + PAYMENT_FAILED: 'payment.failed', +} as const; + +/** Union of every supported domain event type. */ +export type DomainEventType = (typeof DomainEventType)[keyof typeof DomainEventType]; + +/** Frozen, ordered list of every supported domain event type. */ +export const DOMAIN_EVENT_TYPES: readonly DomainEventType[] = Object.freeze([ + DomainEventType.SUBSCRIPTION_CREATED, + DomainEventType.SUBSCRIPTION_CANCELLED, + DomainEventType.INVOICE_PAID, + DomainEventType.HOUSEHOLD_INVITE_ACCEPTED, + DomainEventType.PAYMENT_FAILED, +]); + +/** Payload published when a subscription is created. */ +export interface SubscriptionCreatedPayload { + readonly subscriptionId: string; + readonly userId: string; + readonly planId: string; + readonly email: string; + readonly householdId?: string; +} + +/** Payload published when a subscription is cancelled. */ +export interface SubscriptionCancelledPayload { + readonly subscriptionId: string; + readonly userId: string; + readonly reason?: string; +} + +/** Payload published when an invoice is paid. */ +export interface InvoicePaidPayload { + readonly invoiceId: string; + readonly subscriptionId: string; + readonly userId: string; + readonly amountCents: number; + readonly currency: string; +} + +/** Payload published when a household invitation is accepted. */ +export interface HouseholdInviteAcceptedPayload { + readonly householdId: string; + readonly userId: string; + readonly invitedByUserId: string; +} + +/** Payload published when a payment attempt fails. */ +export interface PaymentFailedPayload { + readonly paymentId: string; + readonly invoiceId: string; + readonly userId: string; + readonly reason: string; +} + +/** Mapping from event type to its typed payload. Single source of truth. */ +export interface DomainEventPayloadMap { + readonly 'subscription.created': SubscriptionCreatedPayload; + readonly 'subscription.cancelled': SubscriptionCancelledPayload; + readonly 'invoice.paid': InvoicePaidPayload; + readonly 'household.invite.accepted': HouseholdInviteAcceptedPayload; + readonly 'payment.failed': PaymentFailedPayload; +} + +/** + * Envelope shared by every lifecycle event. `id` is the event id (not the + * aggregate id), `occurredAt` is an ISO-8601 timestamp and `aggregateId` is + * the identifier of the entity whose lifecycle changed. + */ +export interface DomainEvent { + readonly id: string; + readonly type: T; + readonly occurredAt: string; + readonly aggregateId: string; + readonly payload: DomainEventPayloadMap[T]; +} + +/** Event aliases for callers that want a fully typed handler parameter. */ +export type SubscriptionCreatedEvent = DomainEvent<'subscription.created'>; +export type SubscriptionCancelledEvent = DomainEvent<'subscription.cancelled'>; +export type InvoicePaidEvent = DomainEvent<'invoice.paid'>; +export type HouseholdInviteAcceptedEvent = DomainEvent<'household.invite.accepted'>; +export type PaymentFailedEvent = DomainEvent<'payment.failed'>; + +// --------------------------------------------------------------------------- +// Configuration, observability and public results +// --------------------------------------------------------------------------- + +/** + * Fully resolved bus configuration. Callers pass a `Partial` to + * {@link createEventBus}; defaults are filled by {@link validateEventBusConfig}. + */ +export interface EventBusConfig { + /** Maximum number of handlers accepted per event type. Default: 32. */ + readonly maxHandlersPerEvent: number; + /** + * When true (default), unknown event types are rejected at publish and at + * subscribe time. When false they are accepted, logged and dispatched to + * handlers registered for that raw type (forward-compatible consumers). + */ + readonly strict: boolean; + /** Injectable clock used to measure dispatch duration. Defaults to `Date.now`. */ + readonly clock: () => number; +} + +/** Default configuration, mirroring the documented behaviour. */ +export const DEFAULT_EVENT_BUS_CONFIG: EventBusConfig = Object.freeze({ + maxHandlersPerEvent: 32, + strict: true, + clock: Date.now, +}); + +/** Optional metrics sink. Every method is called on the path it describes. */ +export interface EventBusMetrics { + recordPublished(type: string, handlerCount: number, durationMs: number): void; + recordDelivered(type: string, handlerId: string, durationMs: number): void; + recordHandlerFailed(type: string, handlerId: string, message: string): void; + recordNoHandlers(type: string): void; + recordRejected(operation: string, code: EventBusErrorCode): void; + recordSubscribed(type: string, handlerId: string): void; + recordUnsubscribed(type: string, handlerId: string): void; + recordBatchPublished(count: number): void; + recordCleared(count: number): void; +} + +/** Optional logging hook. No-op defaults keep tests and development quiet. */ +export interface EventBusLogger { + debug(message: string, details: Record): void; + info(message: string, details: Record): void; + warn(message: string, details: Record): void; + error(message: string, details: Record): void; +} + +/** No-op metrics implementation. */ +export const noopEventBusMetrics: EventBusMetrics = Object.freeze({ + recordPublished: () => {}, + recordDelivered: () => {}, + recordHandlerFailed: () => {}, + recordNoHandlers: () => {}, + recordRejected: () => {}, + recordSubscribed: () => {}, + recordUnsubscribed: () => {}, + recordBatchPublished: () => {}, + recordCleared: () => {}, +}); + +/** No-op logger implementation. */ +export const noopEventBusLogger: EventBusLogger = Object.freeze({ + debug: () => {}, + info: () => {}, + warn: () => {}, + error: () => {}, +}); + +/** A handler receives its typed event and may be synchronous or asynchronous. */ +export type EventHandler = ( + event: T +) => void | Promise; + +/** Immutable view of a registered handler. */ +export interface EventHandlerRegistration { + readonly id: string; + readonly type: string; + readonly handler: EventHandler; +} + +/** Registration plus a convenience method to remove just this handler. */ +export interface EventSubscription extends EventHandlerRegistration { + unsubscribe(): boolean; +} + +/** A single isolated handler failure, preserved for observability and tests. */ +export interface HandlerFailure { + readonly handlerId: string; + readonly error: unknown; + readonly message: string; +} + +/** Deterministic outcome of one {@link EventBus.publish} call. */ +export interface PublishResult { + readonly event: DomainEvent; + readonly handlerCount: number; + readonly delivered: number; + readonly failed: number; + readonly failures: readonly HandlerFailure[]; + readonly durationMs: number; +} + +/** Stateful façade returned by {@link createEventBus}. */ +export interface EventBus { + /** Publish one event, awaiting every handler and isolating failures. */ + publish(event: DomainEvent): Promise; + /** Register a handler for an event type; returns its subscription handle. */ + subscribe( + type: T, + handler: EventHandler> + ): EventSubscription; + /** Remove a handler by subscription id or by handler reference. */ + unsubscribe(type: DomainEventType, handlerOrId: EventHandler | string): boolean; + /** Read-only snapshot of registrations, optionally filtered by event type. */ + handlers(type?: DomainEventType): readonly EventHandlerRegistration[]; + /** Publish several events in order; returns one result per event. */ + publishBatch(events: readonly DomainEvent[]): Promise; + /** Remove all handlers (or only those for one type); returns the count removed. */ + clear(type?: DomainEventType): number; + /** The fully resolved, frozen configuration. */ + readonly config: EventBusConfig; +} + +interface MutableRegistration { + id: string; + type: string; + handler: (event: DomainEvent) => void | Promise; +} + +// --------------------------------------------------------------------------- +// Validation +// --------------------------------------------------------------------------- + +/** + * Validate and resolve a partial configuration into a complete, frozen + * `EventBusConfig`. Throws `EventBusError(INVALID_CONFIG)` on bad values. + */ +export function validateEventBusConfig( + config: Partial = {} +): EventBusConfig { + if (config === null || typeof config !== 'object' || Array.isArray(config)) { + throw new EventBusError(EventBusErrorCode.INVALID_CONFIG, 'config must be an object', { + config, + }); + } + + const maxHandlersPerEvent = + config.maxHandlersPerEvent ?? DEFAULT_EVENT_BUS_CONFIG.maxHandlersPerEvent; + if ( + typeof maxHandlersPerEvent !== 'number' || + !Number.isInteger(maxHandlersPerEvent) || + maxHandlersPerEvent < 1 || + maxHandlersPerEvent > 1024 + ) { + throw new EventBusError( + EventBusErrorCode.INVALID_CONFIG, + 'maxHandlersPerEvent must be an integer in 1..1024', + { maxHandlersPerEvent } + ); + } + + const strict = config.strict ?? DEFAULT_EVENT_BUS_CONFIG.strict; + if (typeof strict !== 'boolean') { + throw new EventBusError(EventBusErrorCode.INVALID_CONFIG, 'strict must be a boolean', { + strict, + }); + } + + const clock = config.clock ?? DEFAULT_EVENT_BUS_CONFIG.clock; + if (typeof clock !== 'function') { + throw new EventBusError(EventBusErrorCode.INVALID_CONFIG, 'clock must be a function', { + clock, + }); + } + + return Object.freeze({ maxHandlersPerEvent, strict, clock }); +} + +// --------------------------------------------------------------------------- +// Factory +// --------------------------------------------------------------------------- + +/** + * Create a domain event bus with optional metrics and logger hooks. + * + * `publish` validates the envelope, snapshots the handlers registered for its + * type, then awaits each handler in registration order. A handler that throws + * (or returns a rejecting promise) contributes a `HandlerFailure` to the + * result and emits `recordHandlerFailed` plus an error log; the remaining + * handlers still run. Validation rejections emit `recordRejected` and a warn + * log before throwing the original `EventBusError`. + * + * @param config Partial configuration; see {@link DEFAULT_EVENT_BUS_CONFIG}. + * @param metrics Optional metrics sink (partial implementations allowed). + * @param logger Optional logging sink (partial implementations allowed). + */ +export function createEventBus( + config: Partial = {}, + metrics: Partial = {}, + logger: Partial = {} +): EventBus { + const cfg = validateEventBusConfig(config); + const m: EventBusMetrics = { ...noopEventBusMetrics, ...metrics }; + const l: EventBusLogger = { ...noopEventBusLogger, ...logger }; + const handlersByType = new Map(); + let handlerCounter = 0; + + /** Reject with a typed error, emitting the standard rejection observability. */ + function fail( + operation: string, + code: EventBusErrorCode, + message: string, + details: Record + ): never { + m.recordRejected(operation, code); + l.warn('domain event bus rejected an operation', { + operation, + code, + message, + ...details, + }); + throw new EventBusError(code, message, details); + } + + /** Validate an event envelope and return a frozen, normalised copy. */ + function assertEvent(input: DomainEvent): DomainEvent { + if (input === null || typeof input !== 'object' || Array.isArray(input)) { + return fail('publish', EventBusErrorCode.INVALID_EVENT, 'event must be an object', { + event: input, + }); + } + const candidate = input as Partial; + const missing: string[] = []; + if (typeof candidate.id !== 'string' || candidate.id.trim().length === 0) { + missing.push('id'); + } + if (typeof candidate.type !== 'string' || candidate.type.trim().length === 0) { + missing.push('type'); + } + if ( + typeof candidate.occurredAt !== 'string' || + candidate.occurredAt.trim().length === 0 || + Number.isNaN(Date.parse(candidate.occurredAt)) + ) { + missing.push('occurredAt'); + } + if (typeof candidate.aggregateId !== 'string' || candidate.aggregateId.trim().length === 0) { + missing.push('aggregateId'); + } + if ( + candidate.payload === null || + typeof candidate.payload !== 'object' || + Array.isArray(candidate.payload) + ) { + missing.push('payload'); + } + if (missing.length > 0) { + return fail( + 'publish', + EventBusErrorCode.INVALID_EVENT, + `domain event has missing or invalid fields: ${missing.join(', ')}`, + { missing, event: input } + ); + } + + const type = candidate.type as DomainEventType; + if (!DOMAIN_EVENT_TYPES.includes(type)) { + if (cfg.strict) { + return fail( + 'publish', + EventBusErrorCode.UNKNOWN_EVENT_TYPE, + `unknown domain event type '${type}'`, + { type } + ); + } + l.warn('publishing an unknown event type in non-strict mode', { + type, + eventId: candidate.id, + }); + } + + return Object.freeze({ + id: candidate.id, + type, + occurredAt: candidate.occurredAt, + aggregateId: candidate.aggregateId, + payload: candidate.payload, + }) as DomainEvent; + } + + /** Validate and return the registration list for a type, creating it lazily. */ + function listFor(type: DomainEventType): MutableRegistration[] { + let list = handlersByType.get(type); + if (!list) { + list = []; + handlersByType.set(type, list); + } + return list; + } + + /** Remove a registration by id or handler reference. */ + function remove(type: DomainEventType, handlerOrId: EventHandler | string): boolean { + const list = handlersByType.get(type); + if (!list) return false; + const index = list.findIndex( + (registration) => + registration.id === handlerOrId || registration.handler === handlerOrId + ); + if (index === -1) return false; + const removed = list.splice(index, 1)[0]!; + if (list.length === 0) handlersByType.delete(type); + m.recordUnsubscribed(type, removed.id); + l.debug('domain event handler unsubscribed', { type, handlerId: removed.id }); + return true; + } + + /** Produce an immutable view of a registration. */ + function snapshot(registration: MutableRegistration): EventHandlerRegistration { + return Object.freeze({ + id: registration.id, + type: registration.type, + handler: registration.handler as EventHandler, + }); + } + + async function publish(input: DomainEvent): Promise { + const event = assertEvent(input); + const start = cfg.clock(); + const registrations = (handlersByType.get(event.type) ?? []).slice(); + const failures: HandlerFailure[] = []; + let delivered = 0; + + for (const registration of registrations) { + try { + await registration.handler(event); + delivered += 1; + m.recordDelivered( + event.type, + registration.id, + Math.max(0, cfg.clock() - start) + ); + l.debug('domain event handler completed', { + type: event.type, + handlerId: registration.id, + eventId: event.id, + }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + failures.push( + Object.freeze({ handlerId: registration.id, error, message }) + ); + m.recordHandlerFailed(event.type, registration.id, message); + l.error('domain event handler failed', { + type: event.type, + handlerId: registration.id, + eventId: event.id, + message, + }); + } + } + + const durationMs = Math.max(0, cfg.clock() - start); + const result: PublishResult = Object.freeze({ + event, + handlerCount: registrations.length, + delivered, + failed: failures.length, + failures: Object.freeze(failures), + durationMs, + }); + + if (registrations.length === 0) { + m.recordNoHandlers(event.type); + l.info('domain event published with no subscribers', { + type: event.type, + eventId: event.id, + }); + } else { + l.info('domain event published', { + type: event.type, + eventId: event.id, + delivered, + failed: failures.length, + }); + } + m.recordPublished(event.type, registrations.length, durationMs); + return result; + } + + function subscribe( + type: T, + handler: EventHandler> + ): EventSubscription { + if (typeof type !== 'string' || type.trim().length === 0) { + return fail( + 'subscribe', + EventBusErrorCode.INVALID_EVENT, + 'event type must be a non-empty string', + { type } + ); + } + if (typeof handler !== 'function') { + return fail( + 'subscribe', + EventBusErrorCode.INVALID_HANDLER, + 'handler must be a function', + { type, handler } + ); + } + if (cfg.strict && !DOMAIN_EVENT_TYPES.includes(type)) { + return fail( + 'subscribe', + EventBusErrorCode.UNKNOWN_EVENT_TYPE, + `unknown domain event type '${type}'`, + { type } + ); + } + + const list = listFor(type); + if (list.some((registration) => registration.handler === handler)) { + return fail( + 'subscribe', + EventBusErrorCode.DUPLICATE_HANDLER, + `handler is already registered for '${type}'`, + { type } + ); + } + if (list.length >= cfg.maxHandlersPerEvent) { + return fail( + 'subscribe', + EventBusErrorCode.MAX_HANDLERS_EXCEEDED, + `event type '${type}' already has ${list.length} handlers`, + { type, limit: cfg.maxHandlersPerEvent } + ); + } + + const id = `handler-${++handlerCounter}`; + const registration: MutableRegistration = { + id, + type, + handler: handler as (event: DomainEvent) => void | Promise, + }; + list.push(registration); + m.recordSubscribed(type, id); + l.debug('domain event handler subscribed', { type, handlerId: id }); + return Object.freeze({ + id, + type, + handler: registration.handler as EventHandler, + unsubscribe: (): boolean => remove(type, id), + }); + } + + function unsubscribe(type: DomainEventType, handlerOrId: EventHandler | string): boolean { + return remove(type, handlerOrId); + } + + function handlers(type?: DomainEventType): readonly EventHandlerRegistration[] { + if (type !== undefined) { + return Object.freeze((handlersByType.get(type) ?? []).map(snapshot)); + } + const all: EventHandlerRegistration[] = []; + for (const list of handlersByType.values()) { + for (const registration of list) all.push(snapshot(registration)); + } + return Object.freeze(all); + } + + function clear(type?: DomainEventType): number { + let removed = 0; + if (type !== undefined) { + removed = handlersByType.get(type)?.length ?? 0; + handlersByType.delete(type); + } else { + for (const list of handlersByType.values()) removed += list.length; + handlersByType.clear(); + } + m.recordCleared(removed); + l.info('domain event handlers cleared', { type: type ?? null, removed }); + return removed; + } + + async function publishBatch( + events: readonly DomainEvent[] + ): Promise { + if (!Array.isArray(events)) { + return fail( + 'publishBatch', + EventBusErrorCode.INVALID_EVENT, + 'events must be an array', + { events } + ); + } + const results: PublishResult[] = []; + for (const event of events) results.push(await publish(event)); + m.recordBatchPublished(results.length); + l.info('domain event batch published', { count: results.length }); + return Object.freeze(results); + } + + return Object.freeze({ + publish, + subscribe, + unsubscribe, + handlers, + publishBatch, + clear, + config: cfg, + }); +} diff --git a/workers/src/handlers/__tests__/index.test.ts b/workers/src/handlers/__tests__/index.test.ts new file mode 100644 index 00000000..cf6bd057 --- /dev/null +++ b/workers/src/handlers/__tests__/index.test.ts @@ -0,0 +1,180 @@ +/** + * workers/src/handlers/__tests__/index.test.ts + * + * Unit tests for the default worker lifecycle handlers (issue #2258). Tests + * registration, dispatch through the shared bus, typed payload handling and + * handler isolation using only in-memory sinks. + */ + +import { createEventBus, DomainEventType, type DomainEvent } from '../../../../backend/src/events/bus'; +import { + createHandlerContext, + handleSubscriptionCreated, + handleInvoicePaid, + registerDefaultHandlers, + type WorkerHandlerContext, +} from '../index'; + +/** Build a typed event for tests. */ +function makeEvent( + type: DomainEventType, + payload: Record, + id: string = 'evt-1' +): DomainEvent { + return { + id, + type, + occurredAt: '2026-01-01T00:00:00.000Z', + aggregateId: id, + payload, + } as DomainEvent; +} + +describe('createHandlerContext', () => { + it('starts with empty, independent sinks', () => { + const a = createHandlerContext(); + const b = createHandlerContext(); + expect(a.emailsSent).toHaveLength(0); + expect(a.ledgerEntries).toHaveLength(0); + expect(a.audit).toHaveLength(0); + a.emailsSent.push({ to: 'x', template: 'y', data: {} }); + expect(b.emailsSent).toHaveLength(0); + }); +}); + +describe('individual handlers', () => { + it('queues a welcome email for a created subscription', () => { + const context = createHandlerContext(); + handleSubscriptionCreated( + makeEvent(DomainEventType.SUBSCRIPTION_CREATED, { + subscriptionId: 'sub-1', + userId: 'user-1', + planId: 'pro', + email: 'user@example.com', + }) as never, + context + ); + expect(context.emailsSent).toHaveLength(1); + expect(context.emailsSent[0]?.to).toBe('user@example.com'); + expect(context.emailsSent[0]?.template).toBe('subscription-welcome'); + expect(context.audit).toHaveLength(1); + expect(context.audit[0]?.type).toBe('subscription.created'); + }); + + it('records a ledger credit for a paid invoice', () => { + const context = createHandlerContext(); + handleInvoicePaid( + makeEvent(DomainEventType.INVOICE_PAID, { + invoiceId: 'inv-1', + subscriptionId: 'sub-1', + userId: 'user-1', + amountCents: 1299, + currency: 'USD', + }) as never, + context + ); + expect(context.ledgerEntries).toHaveLength(1); + expect(context.ledgerEntries[0]?.kind).toBe('credit'); + expect(context.ledgerEntries[0]?.amountCents).toBe(1299); + expect(context.audit[0]?.detail).toContain('inv-1'); + }); +}); + +describe('registerDefaultHandlers', () => { + it('registers one handler for every lifecycle event type', () => { + const bus = createEventBus(); + const { context, registrations } = registerDefaultHandlers(bus); + expect(registrations).toHaveLength(5); + expect(bus.handlers()).toHaveLength(5); + expect(context.emailsSent).toHaveLength(0); + expect(context.ledgerEntries).toHaveLength(0); + expect(context.audit).toHaveLength(0); + }); + + it('dispatches a subscription.created event to the welcome-email handler', async () => { + const bus = createEventBus(); + const { context } = registerDefaultHandlers(bus); + const result = await bus.publish( + makeEvent(DomainEventType.SUBSCRIPTION_CREATED, { + subscriptionId: 'sub-2', + userId: 'user-2', + planId: 'starter', + email: 'new@example.com', + householdId: 'house-1', + }) + ); + expect(result.delivered).toBe(1); + expect(result.failed).toBe(0); + expect(context.emailsSent).toHaveLength(1); + expect(context.emailsSent[0]?.data).toEqual({ + subscriptionId: 'sub-2', + planId: 'starter', + userId: 'user-2', + householdId: 'house-1', + }); + expect(context.audit).toHaveLength(1); + }); + + it('dispatches an invoice.paid event to the ledger handler', async () => { + const bus = createEventBus(); + const { context } = registerDefaultHandlers(bus); + await bus.publish( + makeEvent(DomainEventType.INVOICE_PAID, { + invoiceId: 'inv-9', + subscriptionId: 'sub-9', + userId: 'user-9', + amountCents: 2500, + currency: 'EUR', + }) + ); + expect(context.ledgerEntries).toHaveLength(1); + expect(context.ledgerEntries[0]?.invoiceId).toBe('inv-9'); + expect(context.ledgerEntries[0]?.currency).toBe('EUR'); + }); + + it('handles the remaining lifecycle events through the shared bus', async () => { + const bus = createEventBus(); + const { context } = registerDefaultHandlers(bus); + await bus.publish( + makeEvent(DomainEventType.SUBSCRIPTION_CANCELLED, { + subscriptionId: 'sub-3', + userId: 'user-3', + reason: 'too expensive', + }) + ); + await bus.publish( + makeEvent(DomainEventType.HOUSEHOLD_INVITE_ACCEPTED, { + householdId: 'house-1', + userId: 'user-4', + invitedByUserId: 'user-2', + }) + ); + await bus.publish( + makeEvent(DomainEventType.PAYMENT_FAILED, { + paymentId: 'pay-1', + invoiceId: 'inv-1', + userId: 'user-1', + reason: 'card declined', + }) + ); + expect(context.audit).toHaveLength(3); + expect(context.audit[0]?.detail).toContain('too expensive'); + expect(context.audit[1]?.detail).toContain('house-1'); + expect(context.audit[2]?.detail).toContain('card declined'); + }); + + it('supports an injected context and unregistering handlers', async () => { + const bus = createEventBus(); + const context: WorkerHandlerContext = createHandlerContext(); + const { registrations } = registerDefaultHandlers(bus, context); + expect(registrations[1]?.unsubscribe()).toBe(true); + expect(bus.handlers()).toHaveLength(4); + await bus.publish( + makeEvent(DomainEventType.SUBSCRIPTION_CANCELLED, { + subscriptionId: 'sub-4', + userId: 'user-4', + }) + ); + expect(context.audit).toHaveLength(0); + }); +}); diff --git a/workers/src/handlers/index.ts b/workers/src/handlers/index.ts new file mode 100644 index 00000000..dd8c6a7c --- /dev/null +++ b/workers/src/handlers/index.ts @@ -0,0 +1,208 @@ +/** + * workers/src/handlers/index.ts + * + * Default lifecycle event handlers for background workers (issue #2258). + * + * These handlers are the worker-side counterparts of the event contracts in + * `backend/src/events/bus.ts`. They are production-shaped but deliberately + * side-effect-free: instead of calling an email provider or a ledger service, + * they append intent records to an injected in-memory context. Real adapters + * can replace those sinks without changing the handler logic or the bus. + * + * Design rules: + * - Zero new dependencies. No network, no database, no ambient state. + * - Every handler is synchronous and deterministic for a given event/context. + * - Handler failures are isolated by the bus; handlers here never throw for + * well-formed events. + * - The same bus instance can be shared by backend publishers and workers. + * + * Usage: + * const { context } = registerDefaultHandlers(bus); + * await bus.publish(subscriptionCreatedEvent); + * // context.emailsSent[0].template === 'subscription-welcome' + */ + +import { + DomainEventType, + type DomainEvent, + type EventBus, + type EventSubscription, + type HouseholdInviteAcceptedEvent, + type InvoicePaidEvent, + type PaymentFailedEvent, + type SubscriptionCancelledEvent, + type SubscriptionCreatedEvent, +} from '../../../backend/src/events/bus.ts'; + +// --------------------------------------------------------------------------- +// Handler side-effect records (pure stubs, no external I/O) +// --------------------------------------------------------------------------- + +/** An email intent recorded by a handler; a real adapter would send it. */ +export interface EmailMessage { + readonly to: string; + readonly template: string; + readonly data: Readonly>; +} + +/** A ledger intent recorded by a handler; a real adapter would persist it. */ +export interface LedgerEntry { + readonly invoiceId: string; + readonly userId: string; + readonly amountCents: number; + readonly currency: string; + readonly kind: 'credit' | 'debit'; +} + +/** An audit line recorded for every handled lifecycle change. */ +export interface AuditLine { + readonly eventId: string; + readonly type: string; + readonly aggregateId: string; + readonly detail: string; +} + +/** In-memory sinks collected while handlers run. */ +export interface WorkerHandlerContext { + readonly emailsSent: EmailMessage[]; + readonly ledgerEntries: LedgerEntry[]; + readonly audit: AuditLine[]; +} + +/** Create an empty, isolated context for one worker run or one unit test. */ +export function createHandlerContext(): WorkerHandlerContext { + return { emailsSent: [], ledgerEntries: [], audit: [] }; +} + +/** Append an audit line describing a handled event. */ +function audit(context: WorkerHandlerContext, event: DomainEvent, detail: string): void { + context.audit.push({ + eventId: event.id, + type: event.type, + aggregateId: event.aggregateId, + detail, + }); +} + +// --------------------------------------------------------------------------- +// Individual handlers +// --------------------------------------------------------------------------- + +/** + * Handle `subscription.created`: queue a welcome email for the new subscriber. + * No I/O is performed; the message is appended to `context.emailsSent`. + */ +export function handleSubscriptionCreated( + event: SubscriptionCreatedEvent, + context: WorkerHandlerContext +): void { + context.emailsSent.push({ + to: event.payload.email, + template: 'subscription-welcome', + data: { + subscriptionId: event.payload.subscriptionId, + planId: event.payload.planId, + userId: event.payload.userId, + householdId: event.payload.householdId ?? null, + }, + }); + audit(context, event, `welcome email queued for ${event.payload.email}`); +} + +/** + * Handle `subscription.cancelled`: record the cancellation reason for the + * retention workflow. A reason is optional and defaults to `unspecified`. + */ +export function handleSubscriptionCancelled( + event: SubscriptionCancelledEvent, + context: WorkerHandlerContext +): void { + const reason = event.payload.reason ?? 'unspecified'; + audit(context, event, `cancellation recorded (${reason})`); +} + +/** + * Handle `invoice.paid`: reconcile the payment into the ledger as a credit. + * The ledger entry is appended to `context.ledgerEntries` for a real adapter. + */ +export function handleInvoicePaid( + event: InvoicePaidEvent, + context: WorkerHandlerContext +): void { + context.ledgerEntries.push({ + invoiceId: event.payload.invoiceId, + userId: event.payload.userId, + amountCents: event.payload.amountCents, + currency: event.payload.currency, + kind: 'credit', + }); + audit(context, event, `ledger credit for ${event.payload.invoiceId}`); +} + +/** + * Handle `household.invite.accepted`: audit that the invitee joined the + * household and which member invited them. + */ +export function handleHouseholdInviteAccepted( + event: HouseholdInviteAcceptedEvent, + context: WorkerHandlerContext +): void { + audit( + context, + event, + `${event.payload.userId} joined ${event.payload.householdId} via ${event.payload.invitedByUserId}` + ); +} + +/** + * Handle `payment.failed`: audit the failed attempt so the dunning workflow + * can pick it up. The reason is preserved verbatim. + */ +export function handlePaymentFailed( + event: PaymentFailedEvent, + context: WorkerHandlerContext +): void { + audit(context, event, `payment ${event.payload.paymentId} failed: ${event.payload.reason}`); +} + +// --------------------------------------------------------------------------- +// Registration +// --------------------------------------------------------------------------- + +/** Result of {@link registerDefaultHandlers}. */ +export interface DefaultHandlers { + /** The context all default handlers write into. */ + readonly context: WorkerHandlerContext; + /** The five subscriptions, in registration order. */ + readonly registrations: readonly EventSubscription[]; +} + +/** + * Register one handler for every supported lifecycle event type on `bus`. + * + * @param bus The shared event bus used by backend publishers and workers. + * @param context Optional sink context; a fresh one is created by default. + */ +export function registerDefaultHandlers( + bus: EventBus, + context: WorkerHandlerContext = createHandlerContext() +): DefaultHandlers { + const registrations: EventSubscription[] = [ + bus.subscribe(DomainEventType.SUBSCRIPTION_CREATED, (event: SubscriptionCreatedEvent) => + handleSubscriptionCreated(event, context) + ), + bus.subscribe(DomainEventType.SUBSCRIPTION_CANCELLED, (event: SubscriptionCancelledEvent) => + handleSubscriptionCancelled(event, context) + ), + bus.subscribe(DomainEventType.INVOICE_PAID, (event: InvoicePaidEvent) => + handleInvoicePaid(event, context) + ), + bus.subscribe(DomainEventType.HOUSEHOLD_INVITE_ACCEPTED, (event: HouseholdInviteAcceptedEvent) => + handleHouseholdInviteAccepted(event, context) + ), + bus.subscribe(DomainEventType.PAYMENT_FAILED, (event: PaymentFailedEvent) => + handlePaymentFailed(event, context) + ), + ]; + return { context, registrations: Object.freeze(registrations) }; +}