@relaybus/core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/clock.ts","../src/errors.ts","../src/duration.ts","../src/event.ts","../src/event-store.ts","../src/identifier.ts","../src/in-memory-event-store.ts","../src/execution-scope.ts","../src/retry-policy.ts","../src/dispatcher.ts","../src/handler-registry.ts","../src/notifier.ts","../src/relay-bus.ts"],"names":["randomBytes","AsyncLocalStorage","hostname"],"mappings":";;;;;;;AAKO,IAAM,WAAA,GAAqB;AAAA,EAChC,GAAA,EAAK,sBAAM,IAAI,IAAA;AACjB;;;ACJO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA;AAAA,EAE9B,IAAA,GAAO,eAAA;AAClB;AAGO,IAAM,kBAAA,GAAN,cAAiC,aAAA,CAAc;AAAA,EAC3C,IAAA,GAAO,oBAAA;AAClB;AAOO,IAAM,wBAAA,GAAN,cAAuC,aAAA,CAAc;AAAA,EACjD,IAAA,GAAO,0BAAA;AAClB;AAMO,IAAM,iBAAA,GAAN,cAAgC,aAAA,CAAc;AAAA,EAC1C,IAAA,GAAO,mBAAA;AAClB;AAGO,IAAM,oBAAA,GAAN,cAAmC,iBAAA,CAAkB;AAAA,EAG1D,WAAA,CACE,SACS,MAAA,EACT;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFJ,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAGX;AAAA,EAHW,MAAA;AAAA,EAJF,IAAA,GAAO,sBAAA;AAQlB;AAMO,IAAM,oBAAA,GAAN,cAAmC,iBAAA,CAAkB;AAAA,EACjD,IAAA,GAAO,sBAAA;AAClB;AAGO,IAAM,cAAA,GAAN,cAA6B,aAAA,CAAc;AAAA,EACvC,IAAA,GAAO,gBAAA;AAClB;AAGO,IAAM,mBAAA,GAAN,cAAkC,aAAA,CAAc;AAAA,EAC5C,IAAA,GA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AA;AAAA,IACpF,cAAA,EAAgB,mBAAA;AAAA,MACd,OAAA,EAAS,gBAAgB,QAAA,CAAS,YAAA;AAAA,MAClC;AAAA,KACF;AAAA,IACA,eAAA,EAAiB,mBAAA;AAAA,MACf,OAAA,EAAS,iBAAiB,QAAA,CAAS,aAAA;AAAA,MACnC;AAAA,KACF;AAAA,IACA,iBAAA,EAAmB,mBAAA;AAAA,MACjB,OAAA,EAAS,mBAAmB,QAAA,CAAS,eAAA;AAAA,MACrC;AAAA;AACF,GACF;AACF;AAEA,SAAS,wBAAwB,OAAA,EAI/B;AACA,EAAA,MAAM,SAAA,GAAY,OAAA,EAAS,SAAA,IAAa,QAAA,CAAS,kBAAA;AACjD,EAAA,MAAM,IAAA,GAAO,SAAS,IAAA,IAAQ,KAAA;AAC9B,EAAA,OAAO;AAAA,IACL,aAAa,SAAA,KAAc,KAAA,GAAQ,IAAA,GAAO,cAAA,CAAe,WAAW,qBAAqB,CAAA;AAAA,IACzF,QAAQ,IAAA,KAAS,KAAA,GAAQ,IAAA,GAAO,cAAA,CAAe,MAAM,gBAAgB,CAAA;AAAA,IACrE,UAAA,EAAY,mBAAA;AAAA,MACV,OAAA,EAAS,YAAY,QAAA,CAAS,iBAAA;AAAA,MAC9B;AAAA;AACF,GACF;AACF","file":"index.cjs","sourcesContent":["/** Source of the current time. Replace it in tests to control retries and leases. */\nexport interface Clock {\n now(): Date;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n};\n","/**\n * Base class of every error thrown by relaybus.\n */\nexport class RelayBusError extends Error {\n // Explicit names survive minification, unlike `new.target.name`.\n override name = 'RelayBusError';\n}\n\n/** Invalid options passed to a relaybus component. */\nexport class ConfigurationError extends RelayBusError {\n override name = 'ConfigurationError';\n}\n\n/**\n * Thrown by `publish` when no transaction can be found and the bus runs with\n * `transactionMode: 'required'` (the default). Publishing outside a transaction\n * would reintroduce the dual-write problem the outbox exists to prevent.\n */\nexport class TransactionRequiredError extends RelayBusError {\n override name = 'TransactionRequiredError';\n}\n\n/**\n * Throw from a handler to dead-letter the delivery immediately, skipping the\n * remaining retry attempts.\n */\nexport class NonRetryableError extends RelayBusError {\n override name = 'NonRetryableError';\n}\n\n/** A payload failed its event schema. Never retried: the payload will not change. */\nexport class EventValidationError extends NonRetryableError {\n override name = 'EventValidationError';\n\n constructor(\n message: string,\n readonly issues: readonly ValidationIssue[],\n ) {\n super(message);\n }\n}\n\n/**\n * A message received from a broker is not a valid event. Never retried:\n * transports should dead-letter it instead of redelivering it forever.\n */\nexport class InvalidEnvelopeError extends NonRetryableError {\n override name = 'InvalidEnvelopeError';\n}\n\n/** The worker no longer owns the delivery it was processing. */\nexport class LeaseLostError extends RelayBusError {\n override name = 'LeaseLostError';\n}\n\n/** A handler did not settle within its configured timeout. Retried like any failure. */\nexport class HandlerTimeoutError extends RelayBusError {\n override name = 'HandlerTimeoutError';\n}\n\n/**\n * Reason of a handler's abort signal when the bus stops before the handler\n * finished. The delivery is released and runs again without losing an attempt.\n */\nexport class DispatcherStoppedError extends RelayBusError {\n override name = 'DispatcherStoppedError';\n}\n\nexport interface ValidationIssue {\n readonly message: string;\n readonly path?: readonly PropertyKey[] | undefined;\n}\n\n/** Serializable snapshot of an error, stored with failed deliveries. */\nexport interface ErrorInfo {\n readonly name: string;\n readonly message: string;\n readonly stack?: string | undefined;\n}\n\nexport function toErrorInfo(error: unknown): ErrorInfo {\n if (error instanceof Error) {\n return { name: error.name, message: error.message, stack: error.stack };\n }\n return { name: 'NonError', message: safeStringify(error) };\n}\n\nfunction safeStringify(value: unknown): string {\n if (typeof value === 'string') {\n return value;\n }\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n","import { ConfigurationError } from './errors.js';\n\n/**\n * A duration in milliseconds, or a string such as `'250ms'`, `'30s'`, `'5m'`,\n * `'1h'` or `'7d'`.\n */\nexport type Duration = number | `${number}${DurationUnit}`;\n\ntype DurationUnit = 'ms' | 's' | 'm' | 'h' | 'd';\n\nconst MILLISECONDS_PER_UNIT: Record<DurationUnit, number> = {\n ms: 1,\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n};\n\nconst DURATION_PATTERN = /^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d)$/;\n\nexport function toMilliseconds(value: Duration, name: string): number {\n if (typeof value === 'number') {\n if (!Number.isFinite(value) || value < 0) {\n throw new ConfigurationError(\n `${name} must be a non-negative finite number of milliseconds, received ${value}`,\n );\n }\n return value;\n }\n const match = DURATION_PATTERN.exec(value);\n if (match === null) {\n throw new ConfigurationError(\n `${name} must look like '500ms', '30s', '5m', '1h' or '7d', received '${value}'`,\n );\n }\n const [, amount, unit] = match as unknown as [string, string, DurationUnit];\n return Number(amount) * MILLISECONDS_PER_UNIT[unit];\n}\n\n/** Largest delay Node.js timers support. Longer values fire after 1ms instead. */\nexport const MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/** Converts a duration that drives a timer, rejecting zero and values timers cannot represent. */\nexport function toTimerMilliseconds(value: Duration, name: string): number {\n const milliseconds = toMilliseconds(value, name);\n if (milliseconds === 0) {\n throw new ConfigurationError(`${name} must be greater than zero`);\n }\n if (milliseconds > MAX_TIMER_DELAY_MS) {\n throw new ConfigurationError(\n `${name} must not exceed ${MAX_TIMER_DELAY_MS}ms (about 24.8 days), received ${milliseconds}ms`,\n );\n }\n return milliseconds;\n}\n","import { ConfigurationError, EventValidationError } from './errors.js';\nimport type { StandardSchemaV1 } from './standard-schema.js';\n\n/** String metadata carried with an event, such as `traceparent`. */\nexport type EventHeaders = Readonly<Record<string, string>>;\n\n/**\n * An event as stored and delivered. Field names follow CloudEvents where they\n * overlap (`id`, `type`, `source`, `time` as `occurredAt`, `subject` as `key`).\n */\nexport interface EventEnvelope<TPayload = unknown> {\n /** Globally unique id. Handlers and transports deduplicate on it. */\n readonly id: string;\n /** Event type, for example `order.created.v1`. */\n readonly type: string;\n /** Logical name of the publishing service. */\n readonly source: string;\n /** Ordering and partition key. Events sharing a key are handled in publish order. */\n readonly key: string | null;\n readonly payload: TPayload;\n readonly headers: EventHeaders;\n /** Id shared by every event of one business flow. */\n readonly correlationId: string | null;\n /** Id of the event whose handler published this one. */\n readonly causationId: string | null;\n readonly occurredAt: Date;\n}\n\n/** An instance of a class created with {@link defineEvent}. */\nexport interface DomainEvent<TPayload = unknown> {\n readonly type: string;\n readonly payload: TPayload;\n}\n\n/** A class created with {@link defineEvent}. */\nexport interface EventClass<TPayload = unknown> {\n new (payload: TPayload): DomainEvent<TPayload>;\n readonly type: string;\n readonly schema: StandardSchemaV1<unknown, TPayload> | undefined;\n}\n\n/** Payload type of an event class: `PayloadOf<typeof OrderPlaced>`. */\nexport type PayloadOf<TEvent> = TEvent extends EventClass<infer TPayload> ? TPayload : never;\n\n/** Anything that names an event type: an event class or the type string itself. */\nexport type EventReference = { readonly type: string } | string;\n\nexport interface DefineEventOptions<TSchema extends StandardSchemaV1> {\n /** Validates the payload on publish and before every handler call. */\n readonly schema: TSchema;\n}\n\nconst EVENT_TYPE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;\n\nexport function assertEventType(type: string): void {\n if (!EVENT_TYPE_PATTERN.test(type)) {\n throw new ConfigurationError(\n `Event type '${type}' must be 1-255 characters of letters, digits, '.', '_', ':', '/' or '-', starting with a letter or digit`,\n );\n }\n}\n\n/**\n * Defines an event type. Extend the returned class to name it:\n *\n * ```ts\n * export class OrderPlaced extends defineEvent<{ orderId: string }>('order.placed.v1') {}\n * export class OrderShipped extends defineEvent('order.shipped.v1', { schema: orderShippedSchema }) {}\n * ```\n */\nexport function defineEvent<TSchema extends StandardSchemaV1>(\n type: string,\n options: DefineEventOptions<TSchema>,\n): EventClass<StandardSchemaV1.InferOutput<TSchema>>;\nexport function defineEvent<TPayload>(type: string): EventClass<TPayload>;\nexport function defineEvent(\n type: string,\n options?: DefineEventOptions<StandardSchemaV1>,\n): EventClass<unknown> {\n assertEventType(type);\n const schema = options?.schema;\n return class DefinedEvent implements DomainEvent<unknown> {\n static readonly type = type;\n static readonly schema = schema;\n readonly type = type;\n constructor(readonly payload: unknown) {}\n };\n}\n\n/** Runs a Standard Schema and returns its output, or throws {@link EventValidationError}. */\nexport async function validatePayload<TPayload>(\n type: string,\n schema: StandardSchemaV1<unknown, TPayload> | undefined,\n payload: unknown,\n): Promise<TPayload> {\n if (schema === undefined) {\n return payload as TPayload;\n }\n const result = await schema['~standard'].validate(payload);\n if (result.issues !== undefined) {\n const issues = result.issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map((segment) => (typeof segment === 'object' ? segment.key : segment)),\n }));\n throw new EventValidationError(\n `Payload of '${type}' failed validation: ${issues.map((issue) => issue.message).join('; ')}`,\n issues,\n );\n }\n return result.value;\n}\n","import type { ErrorInfo } from './errors.js';\nimport type { EventEnvelope } from './event.js';\n\n/**\n * Lifecycle of one handler's delivery of one event.\n * `pending` (waiting or scheduled for retry) -> `processing` (leased by a worker)\n * -> `completed` | `pending` (retry) | `dead` (exhausted or non-retryable).\n * `dead` -> `pending` only through an explicit requeue.\n */\nexport type DeliveryStatus = 'pending' | 'processing' | 'completed' | 'dead';\n\nexport const DELIVERY_STATUSES: readonly DeliveryStatus[] = [\n 'pending',\n 'processing',\n 'completed',\n 'dead',\n];\n\nexport interface NewDelivery {\n readonly id: string;\n /** Stable handler id. Together with the event id it is unique. */\n readonly handler: string;\n readonly availableAt: Date;\n}\n\nexport interface AppendEntry {\n readonly event: EventEnvelope;\n readonly deliveries: readonly NewDelivery[];\n}\n\nexport interface AppendResult {\n /** Events written by this call. */\n readonly appendedEventIds: readonly string[];\n /** Events that already existed. Their missing deliveries were still added. */\n readonly duplicateEventIds: readonly string[];\n /** Deliveries written by this call. Existing (event, handler) pairs are skipped. */\n readonly appendedDeliveryCount: number;\n}\n\n/**\n * Lease expiry is compared with the `now` the caller passes, taken from the\n * bus clock. Keep worker clocks synchronized (NTP): a skew larger than a third\n * of the lease duration lets another worker reclaim a delivery that is still running.\n */\nexport interface ClaimRequest {\n /** Only deliveries of these handlers are claimed. */\n readonly handlers: readonly string[];\n readonly limit: number;\n readonly leaseOwner: string;\n readonly leaseExpiresAt: Date;\n readonly now: Date;\n}\n\n/**\n * Proof of ownership. Every state change after a claim must present it\n * (fencing). A lease stays valid until another claim replaces it, even after\n * its expiry time; expiry only makes the delivery claimable again.\n */\nexport interface LeaseReference {\n readonly deliveryId: string;\n readonly leaseToken: string;\n}\n\nexport interface ClaimedDelivery extends LeaseReference {\n readonly handler: string;\n /** Attempt number of this claim, starting at 1. */\n readonly attempt: number;\n readonly leaseExpiresAt: Date;\n readonly event: EventEnvelope;\n}\n\nexport interface DeliveryRecord {\n readonly id: string;\n readonly handler: string;\n readonly status: DeliveryStatus;\n readonly attempts: number;\n readonly availableAt: Date;\n readonly leaseOwner: string | null;\n readonly leaseExpiresAt: Date | null;\n readonly lastError: ErrorInfo | null;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly completedAt: Date | null;\n readonly event: EventEnvelope;\n}\n\nexport interface DeliveryQuery {\n readonly status?: DeliveryStatus;\n readonly handler?: string;\n readonly eventType?: string;\n readonly eventId?: string;\n /** Default 100. */\n readonly limit?: number;\n}\n\nexport interface PurgeRequest {\n /** Delete completed deliveries completed before this instant. */\n readonly completedBefore?: Date;\n /** Delete dead deliveries last updated before this instant. */\n readonly deadBefore?: Date;\n}\n\nexport interface PurgeResult {\n readonly deletedDeliveries: number;\n /** Events deleted because no delivery referenced them any more. */\n readonly deletedEvents: number;\n}\n\nexport interface EventStoreStatistics {\n readonly pending: number;\n readonly processing: number;\n readonly completed: number;\n readonly dead: number;\n /** `availableAt` of the oldest delivery that is due but not yet processed. */\n readonly oldestDueAt: Date | null;\n}\n\n/**\n * Storage port. Implementations persist events and deliveries in the same\n * database as the application's business data so that both commit atomically.\n *\n * Every implementation must pass the contract suite in `@relaybus/testing`.\n */\nexport interface EventStore<TTransaction = unknown> {\n /** Creates tables, collections and indexes when they do not exist. */\n setup?(): Promise<void>;\n /** Runs `work` inside a new database transaction and commits when it resolves. */\n transaction<T>(work: (transaction: TTransaction) => Promise<T>): Promise<T>;\n /**\n * Writes events and their deliveries inside `transaction`. Idempotent on\n * event id and on (event id, handler). Assigns a per-key sequence to keyed\n * events in commit order.\n */\n append(\n transaction: TTransaction,\n entries: readonly AppendEntry[],\n now: Date,\n ): Promise<AppendResult>;\n /**\n * Leases up to `limit` deliveries that are due: pending with `availableAt <= now`,\n * or processing with an expired lease. A keyed delivery is only claimable when\n * no earlier delivery of the same handler and key is pending or processing.\n * Increments the attempt count. Safe to call from many processes at once.\n */\n claim(request: ClaimRequest): Promise<ClaimedDelivery[]>;\n /** Extends a lease the caller still holds. Returns false when the lease was lost. */\n extendLease(lease: LeaseReference, leaseExpiresAt: Date, now: Date): Promise<boolean>;\n /**\n * Marks a leased delivery completed. With `transaction` the change commits\n * together with the handler's own writes. Returns false when the lease was lost.\n */\n complete(lease: LeaseReference, now: Date, transaction?: TTransaction): Promise<boolean>;\n /** Returns a leased delivery to pending, due at `availableAt`. */\n reschedule(\n lease: LeaseReference,\n availableAt: Date,\n error: ErrorInfo,\n now: Date,\n ): Promise<boolean>;\n /**\n * Gives a leased delivery back without counting the attempt: pending, due\n * now, attempts decremented. Used when a handler is aborted at shutdown.\n */\n release(lease: LeaseReference, now: Date): Promise<boolean>;\n /** Moves a leased delivery to dead. */\n bury(lease: LeaseReference, error: ErrorInfo, now: Date): Promise<boolean>;\n listDeliveries(query: DeliveryQuery): Promise<DeliveryRecord[]>;\n /** Moves dead deliveries back to pending with a fresh attempt budget. Returns how many moved. */\n requeue(deliveryIds: readonly string[], now: Date): Promise<number>;\n purge(request: PurgeRequest): Promise<PurgeResult>;\n statistics(now: Date): Promise<EventStoreStatistics>;\n /** Releases connections the store opened itself. */\n close?(): Promise<void>;\n}\n","import { randomBytes } from 'node:crypto';\n\n/**\n * RFC 9562 UUID version 7: 48-bit Unix millisecond timestamp followed by random\n * bits. Time-ordered, so it keeps B-tree indexes compact, and globally unique,\n * so it is safe as an idempotency key across services.\n */\nexport function createUuidV7(timestamp: number = Date.now()): string {\n const bytes = randomBytes(16);\n let remaining = timestamp;\n for (let index = 5; index >= 0; index -= 1) {\n bytes[index] = remaining % 256;\n remaining = Math.floor(remaining / 256);\n }\n bytes[6] = (bytes[6]! & 0x0f) | 0x70;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = bytes.toString('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/** Produces unique identifiers for events, deliveries and lease tokens. */\nexport type IdentifierGenerator = () => string;\n","import { ConfigurationError, type ErrorInfo } from './errors.js';\nimport type { EventEnvelope } from './event.js';\nimport type {\n AppendEntry,\n AppendResult,\n ClaimRequest,\n ClaimedDelivery,\n DeliveryQuery,\n DeliveryRecord,\n DeliveryStatus,\n EventStore,\n EventStoreStatistics,\n LeaseReference,\n PurgeRequest,\n PurgeResult,\n} from './event-store.js';\nimport { createUuidV7, type IdentifierGenerator } from './identifier.js';\n\nexport interface InMemoryEventStoreOptions {\n /** Allow use when `NODE_ENV` is `production`. Data is lost on restart. Default false. */\n readonly allowInProduction?: boolean;\n readonly generateIdentifier?: IdentifierGenerator;\n}\n\n/** Transaction handle of {@link InMemoryEventStore}. Writes apply on commit only. */\nexport class InMemoryTransaction {\n readonly #operations: Array<() => void> = [];\n readonly #finishers: Array<() => void> = [];\n #state: 'open' | 'committed' | 'rolled-back' = 'open';\n\n get state(): 'open' | 'committed' | 'rolled-back' {\n return this.#state;\n }\n\n enqueue(operation: () => void): void {\n if (this.#state !== 'open') {\n throw new ConfigurationError(`Cannot write through a ${this.#state} in-memory transaction`);\n }\n this.#operations.push(operation);\n }\n\n /** Runs `finisher` once the transaction commits or rolls back, like a lock release. */\n onFinish(finisher: () => void): void {\n this.#finishers.push(finisher);\n }\n\n commit(): void {\n this.#state = 'committed';\n for (const operation of this.#operations) {\n operation();\n }\n this.#finish();\n }\n\n rollback(): void {\n this.#state = 'rolled-back';\n this.#finish();\n }\n\n #finish(): void {\n for (const finisher of this.#finishers.splice(0)) {\n finisher();\n }\n }\n}\n\ninterface HeldLock {\n readonly owner: InMemoryTransaction;\n readonly released: Promise<void>;\n}\n\ninterface StoredEvent {\n readonly envelope: SerializedEnvelope;\n readonly sequence: number | null;\n}\n\ninterface SerializedEnvelope extends Omit<EventEnvelope, 'occurredAt'> {\n readonly occurredAt: string;\n}\n\ninterface StoredDelivery {\n readonly id: string;\n readonly eventId: string;\n readonly handler: string;\n readonly key: string | null;\n readonly sequence: number | null;\n status: DeliveryStatus;\n attempts: number;\n availableAt: Date;\n leaseOwner: string | null;\n leaseToken: string | null;\n leaseExpiresAt: Date | null;\n lastError: ErrorInfo | null;\n readonly createdAt: Date;\n updatedAt: Date;\n completedAt: Date | null;\n}\n\n/**\n * Event store kept in process memory, with the same semantics as the database\n * stores: transactional appends, leases, fencing and per-key ordering. Payloads\n * are round-tripped through JSON exactly like a database would store them.\n * Meant for tests and local development.\n */\nexport class InMemoryEventStore implements EventStore<InMemoryTransaction> {\n readonly #events = new Map<string, StoredEvent>();\n readonly #deliveries = new Map<string, StoredDelivery>();\n readonly #keySequences = new Map<string, number>();\n /** Row-lock emulation: event ids and ordering keys written by open transactions. */\n readonly #locks = new Map<string, HeldLock>();\n readonly #generateIdentifier: IdentifierGenerator;\n\n constructor(options: InMemoryEventStoreOptions = {}) {\n if (process.env['NODE_ENV'] === 'production' && options.allowInProduction !== true) {\n throw new ConfigurationError(\n 'InMemoryEventStore loses every event on restart. Use a database store in production, or pass allowInProduction: true',\n );\n }\n this.#generateIdentifier = options.generateIdentifier ?? (() => createUuidV7());\n }\n\n async transaction<T>(work: (transaction: InMemoryTransaction) => Promise<T>): Promise<T> {\n const transaction = new InMemoryTransaction();\n try {\n const result = await work(transaction);\n transaction.commit();\n return result;\n } catch (error) {\n transaction.rollback();\n throw error;\n }\n }\n\n async append(\n transaction: InMemoryTransaction,\n entries: readonly AppendEntry[],\n now: Date,\n ): Promise<AppendResult> {\n await this.#lock(\n transaction,\n entries.flatMap((entry) => [\n `event:${entry.event.id}`,\n ...(entry.event.key === null ? [] : [`key:${entry.event.key}`]),\n ]),\n );\n const pendingEventIds = new Set<string>();\n const pendingDeliveryKeys = new Set<string>();\n const appendedEventIds: string[] = [];\n const duplicateEventIds: string[] = [];\n let appendedDeliveryCount = 0;\n for (const entry of entries) {\n const eventId = entry.event.id;\n const isDuplicate = this.#events.has(eventId) || pendingEventIds.has(eventId);\n if (isDuplicate) {\n duplicateEventIds.push(eventId);\n } else {\n appendedEventIds.push(eventId);\n pendingEventIds.add(eventId);\n }\n const newDeliveries = entry.deliveries.filter((delivery) => {\n const deliveryKey = `${eventId}\\u0000${delivery.handler}`;\n if (pendingDeliveryKeys.has(deliveryKey) || this.#hasDelivery(eventId, delivery.handler)) {\n return false;\n }\n pendingDeliveryKeys.add(deliveryKey);\n return true;\n });\n appendedDeliveryCount += newDeliveries.length;\n const serialized = serializeEnvelope(entry.event);\n transaction.enqueue(() => {\n if (!isDuplicate) {\n this.#events.set(eventId, {\n envelope: serialized,\n sequence: this.#nextSequence(serialized.key),\n });\n }\n const stored = this.#events.get(eventId)!;\n for (const delivery of newDeliveries) {\n this.#deliveries.set(delivery.id, {\n id: delivery.id,\n eventId,\n handler: delivery.handler,\n key: stored.envelope.key,\n sequence: stored.sequence,\n status: 'pending',\n attempts: 0,\n availableAt: delivery.availableAt,\n leaseOwner: null,\n leaseToken: null,\n leaseExpiresAt: null,\n lastError: null,\n createdAt: now,\n updatedAt: now,\n completedAt: null,\n });\n }\n });\n }\n return { appendedEventIds, duplicateEventIds, appendedDeliveryCount };\n }\n\n async claim(request: ClaimRequest): Promise<ClaimedDelivery[]> {\n const handlers = new Set(request.handlers);\n const due = [...this.#deliveries.values()]\n .filter((delivery) => handlers.has(delivery.handler) && isDue(delivery, request.now))\n .sort(compareDue);\n const claimed: ClaimedDelivery[] = [];\n for (const delivery of due) {\n if (claimed.length >= request.limit) {\n break;\n }\n if (this.#isKeyBlocked(delivery, request.now)) {\n continue;\n }\n delivery.status = 'processing';\n delivery.attempts += 1;\n delivery.leaseOwner = request.leaseOwner;\n delivery.leaseToken = this.#generateIdentifier();\n delivery.leaseExpiresAt = request.leaseExpiresAt;\n delivery.updatedAt = request.now;\n claimed.push({\n deliveryId: delivery.id,\n leaseToken: delivery.leaseToken,\n handler: delivery.handler,\n attempt: delivery.attempts,\n leaseExpiresAt: request.leaseExpiresAt,\n event: this.#readEnvelope(delivery.eventId),\n });\n }\n return claimed;\n }\n\n async extendLease(lease: LeaseReference, leaseExpiresAt: Date, now: Date): Promise<boolean> {\n return this.#updateLeased(lease, (delivery) => {\n delivery.leaseExpiresAt = leaseExpiresAt;\n delivery.updatedAt = now;\n });\n }\n\n async complete(\n lease: LeaseReference,\n now: Date,\n transaction?: InMemoryTransaction,\n ): Promise<boolean> {\n const finish = (delivery: StoredDelivery): void => {\n delivery.status = 'completed';\n delivery.completedAt = now;\n delivery.updatedAt = now;\n clearLease(delivery);\n };\n if (transaction === undefined) {\n return this.#updateLeased(lease, finish);\n }\n if (this.#findLeased(lease) === undefined) {\n return false;\n }\n transaction.enqueue(() => {\n const delivery = this.#findLeased(lease);\n if (delivery !== undefined) {\n finish(delivery);\n }\n });\n return true;\n }\n\n async reschedule(\n lease: LeaseReference,\n availableAt: Date,\n error: ErrorInfo,\n now: Date,\n ): Promise<boolean> {\n return this.#updateLeased(lease, (delivery) => {\n delivery.status = 'pending';\n delivery.availableAt = availableAt;\n delivery.lastError = error;\n delivery.updatedAt = now;\n clearLease(delivery);\n });\n }\n\n async release(lease: LeaseReference, now: Date): Promise<boolean> {\n return this.#updateLeased(lease, (delivery) => {\n delivery.status = 'pending';\n delivery.attempts -= 1;\n delivery.availableAt = now;\n delivery.updatedAt = now;\n clearLease(delivery);\n });\n }\n\n async bury(lease: LeaseReference, error: ErrorInfo, now: Date): Promise<boolean> {\n return this.#updateLeased(lease, (delivery) => {\n delivery.status = 'dead';\n delivery.lastError = error;\n delivery.updatedAt = now;\n clearLease(delivery);\n });\n }\n\n async listDeliveries(query: DeliveryQuery): Promise<DeliveryRecord[]> {\n const limit = query.limit ?? 100;\n return [...this.#deliveries.values()]\n .filter((delivery) => matchesQuery(delivery, this.#events.get(delivery.eventId)!, query))\n .sort(\n (left, right) =>\n left.createdAt.getTime() - right.createdAt.getTime() || compareIds(left.id, right.id),\n )\n .slice(0, limit)\n .map((delivery) => ({\n id: delivery.id,\n handler: delivery.handler,\n status: delivery.status,\n attempts: delivery.attempts,\n availableAt: delivery.availableAt,\n leaseOwner: delivery.leaseOwner,\n leaseExpiresAt: delivery.leaseExpiresAt,\n lastError: delivery.lastError,\n createdAt: delivery.createdAt,\n updatedAt: delivery.updatedAt,\n completedAt: delivery.completedAt,\n event: this.#readEnvelope(delivery.eventId),\n }));\n }\n\n async requeue(deliveryIds: readonly string[], now: Date): Promise<number> {\n let moved = 0;\n for (const deliveryId of new Set(deliveryIds)) {\n const delivery = this.#deliveries.get(deliveryId);\n if (delivery?.status !== 'dead') {\n continue;\n }\n delivery.status = 'pending';\n delivery.attempts = 0;\n delivery.availableAt = now;\n delivery.updatedAt = now;\n moved += 1;\n }\n return moved;\n }\n\n async purge(request: PurgeRequest): Promise<PurgeResult> {\n let deletedDeliveries = 0;\n const touchedEventIds = new Set<string>();\n for (const delivery of [...this.#deliveries.values()]) {\n if (isPurgeable(delivery, request)) {\n this.#deliveries.delete(delivery.id);\n touchedEventIds.add(delivery.eventId);\n deletedDeliveries += 1;\n }\n }\n const referencedEventIds = new Set(\n [...this.#deliveries.values()].map((delivery) => delivery.eventId),\n );\n let deletedEvents = 0;\n for (const eventId of touchedEventIds) {\n if (!referencedEventIds.has(eventId)) {\n this.#events.delete(eventId);\n deletedEvents += 1;\n }\n }\n return { deletedDeliveries, deletedEvents };\n }\n\n async statistics(now: Date): Promise<EventStoreStatistics> {\n const counts: Record<DeliveryStatus, number> = {\n pending: 0,\n processing: 0,\n completed: 0,\n dead: 0,\n };\n let oldestDueAt: Date | null = null;\n for (const delivery of this.#deliveries.values()) {\n counts[delivery.status] += 1;\n if (isDue(delivery, now)) {\n const dueAt = dueAtOf(delivery);\n if (oldestDueAt === null || dueAt < oldestDueAt) {\n oldestDueAt = dueAt;\n }\n }\n }\n return { ...counts, oldestDueAt };\n }\n\n /**\n * Waits for other open transactions holding any of `names`, then holds them\n * until `transaction` finishes, the way a database holds row locks. Sorted\n * acquisition keeps two transactions from waiting on each other.\n */\n async #lock(transaction: InMemoryTransaction, names: readonly string[]): Promise<void> {\n for (const name of [...new Set(names)].sort()) {\n let held = this.#locks.get(name);\n while (held !== undefined && held.owner !== transaction) {\n await held.released;\n held = this.#locks.get(name);\n }\n if (held !== undefined) {\n continue;\n }\n let release!: () => void;\n const released = new Promise<void>((resolve) => {\n release = resolve;\n });\n this.#locks.set(name, { owner: transaction, released });\n transaction.onFinish(() => {\n this.#locks.delete(name);\n release();\n });\n }\n }\n\n #hasDelivery(eventId: string, handler: string): boolean {\n for (const delivery of this.#deliveries.values()) {\n if (delivery.eventId === eventId && delivery.handler === handler) {\n return true;\n }\n }\n return false;\n }\n\n #nextSequence(key: string | null): number | null {\n if (key === null) {\n return null;\n }\n const next = (this.#keySequences.get(key) ?? 0) + 1;\n this.#keySequences.set(key, next);\n return next;\n }\n\n /**\n * A keyed delivery waits while an earlier delivery of the same handler and\n * key is unfinished, or while any other delivery of that handler and key is\n * running under a live lease (a requeued dead letter must not run alongside\n * its successor).\n */\n #isKeyBlocked(delivery: StoredDelivery, now: Date): boolean {\n if (delivery.key === null) {\n return false;\n }\n for (const other of this.#deliveries.values()) {\n if (other === delivery || other.handler !== delivery.handler || other.key !== delivery.key) {\n continue;\n }\n const unfinishedPredecessor =\n other.sequence! < delivery.sequence! &&\n (other.status === 'pending' || other.status === 'processing');\n const runningUnderLiveLease = other.status === 'processing' && other.leaseExpiresAt! > now;\n if (unfinishedPredecessor || runningUnderLiveLease) {\n return true;\n }\n }\n return false;\n }\n\n #findLeased(lease: LeaseReference): StoredDelivery | undefined {\n const delivery = this.#deliveries.get(lease.deliveryId);\n if (delivery?.status === 'processing' && delivery.leaseToken === lease.leaseToken) {\n return delivery;\n }\n return undefined;\n }\n\n #updateLeased(lease: LeaseReference, update: (delivery: StoredDelivery) => void): boolean {\n const delivery = this.#findLeased(lease);\n if (delivery === undefined) {\n return false;\n }\n update(delivery);\n return true;\n }\n\n #readEnvelope(eventId: string): EventEnvelope {\n const serialized = this.#events.get(eventId)!.envelope;\n const copy = JSON.parse(JSON.stringify(serialized)) as SerializedEnvelope;\n return { ...copy, occurredAt: new Date(copy.occurredAt) };\n }\n}\n\nfunction serializeEnvelope(envelope: EventEnvelope): SerializedEnvelope {\n return JSON.parse(JSON.stringify(envelope)) as SerializedEnvelope;\n}\n\nfunction isDue(delivery: StoredDelivery, now: Date): boolean {\n if (delivery.status === 'pending') {\n return delivery.availableAt <= now;\n }\n return delivery.status === 'processing' && delivery.leaseExpiresAt! <= now;\n}\n\nfunction dueAtOf(delivery: StoredDelivery): Date {\n return delivery.status === 'pending' ? delivery.availableAt : delivery.leaseExpiresAt!;\n}\n\nfunction compareDue(left: StoredDelivery, right: StoredDelivery): number {\n const byDueTime = dueAtOf(left).getTime() - dueAtOf(right).getTime();\n return byDueTime === 0 ? compareIds(left.id, right.id) : byDueTime;\n}\n\nfunction compareIds(left: string, right: string): number {\n return Number(left > right) - Number(left < right);\n}\n\nfunction clearLease(delivery: StoredDelivery): void {\n delivery.leaseOwner = null;\n delivery.leaseToken = null;\n delivery.leaseExpiresAt = null;\n}\n\nfunction matchesQuery(delivery: StoredDelivery, event: StoredEvent, query: DeliveryQuery): boolean {\n return (\n (query.status === undefined || delivery.status === query.status) &&\n (query.handler === undefined || delivery.handler === query.handler) &&\n (query.eventType === undefined || event.envelope.type === query.eventType) &&\n (query.eventId === undefined || delivery.eventId === query.eventId)\n );\n}\n\nfunction isPurgeable(delivery: StoredDelivery, request: PurgeRequest): boolean {\n if (delivery.status === 'completed' && request.completedBefore !== undefined) {\n return delivery.completedAt! < request.completedBefore;\n }\n if (delivery.status === 'dead' && request.deadBefore !== undefined) {\n return delivery.updatedAt < request.deadBefore;\n }\n return false;\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { EventEnvelope } from './event.js';\n\nexport interface ExecutionScope {\n /** Transaction that `publish` joins when none is passed explicitly. */\n readonly transaction?: unknown;\n /** Event being handled. Events published while handling it inherit correlation. */\n readonly event?: EventEnvelope;\n}\n\nconst storage = new AsyncLocalStorage<ExecutionScope>();\n\n/** Runs `work` in `scope`, layered over the caller's scope. */\nexport function runInScope<T>(scope: ExecutionScope, work: () => T): T {\n return storage.run({ ...storage.getStore(), ...scope }, work);\n}\n\n/** Runs `work` in exactly `scope`, ignoring the caller's scope. */\nexport function runInIsolatedScope<T>(scope: ExecutionScope, work: () => T): T {\n return storage.run(scope, work);\n}\n\nexport function getCurrentScope(): ExecutionScope | undefined {\n return storage.getStore();\n}\n","import { toMilliseconds, type Duration } from './duration.js';\nimport { ConfigurationError, NonRetryableError } from './errors.js';\n\n/**\n * How the delay between attempts is randomized.\n * - `full`: uniform in [0, delay]. Spreads retries the most (AWS recommendation).\n * - `equal`: uniform in [delay / 2, delay].\n * - `none`: exactly `delay`. Synchronized retries can stampede a recovering dependency.\n */\nexport type JitterStrategy = 'full' | 'equal' | 'none';\n\nexport interface RetryPolicyOptions {\n /**\n * Total attempts including the first one. Default 10 for handlers, which\n * gives up after roughly 17 minutes of failures with the default delays.\n * `Infinity` retries until the delivery succeeds.\n */\n readonly attempts?: number;\n /** Delay before the second attempt. Default `'1s'`. */\n readonly initialDelay?: Duration;\n /** Growth factor of the delay per attempt. Default 2. */\n readonly factor?: number;\n /** Upper bound of a single delay. Default `'10m'`. */\n readonly maxDelay?: Duration;\n /** Default `'full'`. */\n readonly jitter?: JitterStrategy;\n /** Return false to dead-letter an error without retrying it. */\n readonly retryIf?: (error: unknown) => boolean;\n}\n\nexport interface RetryPolicy {\n readonly attempts: number;\n readonly initialDelayMs: number;\n readonly factor: number;\n readonly maxDelayMs: number;\n readonly jitter: JitterStrategy;\n readonly retryIf: ((error: unknown) => boolean) | undefined;\n}\n\n/** Default policy of handlers. */\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n attempts: 10,\n initialDelayMs: 1_000,\n factor: 2,\n maxDelayMs: 600_000,\n jitter: 'full',\n retryIf: undefined,\n};\n\n/**\n * Default policy of routes to transports: a broker outage must only delay\n * events, so routes retry until the broker accepts them, at most every 5 minutes.\n */\nexport const DEFAULT_ROUTE_RETRY_POLICY: RetryPolicy = {\n attempts: Number.POSITIVE_INFINITY,\n initialDelayMs: 1_000,\n factor: 2,\n maxDelayMs: 300_000,\n jitter: 'full',\n retryIf: undefined,\n};\n\nconst JITTER_STRATEGIES: readonly JitterStrategy[] = ['full', 'equal', 'none'];\n\nexport function createRetryPolicy(\n options: RetryPolicyOptions | undefined,\n base: RetryPolicy = DEFAULT_RETRY_POLICY,\n): RetryPolicy {\n const initialDelayMs =\n options?.initialDelay === undefined\n ? base.initialDelayMs\n : toMilliseconds(options.initialDelay, 'retry.initialDelay');\n const policy: RetryPolicy = {\n attempts: options?.attempts ?? base.attempts,\n initialDelayMs,\n factor: options?.factor ?? base.factor,\n maxDelayMs:\n options?.maxDelay === undefined\n ? // Raising only the initial delay must not trip the inherited cap.\n Math.max(base.maxDelayMs, initialDelayMs)\n : toMilliseconds(options.maxDelay, 'retry.maxDelay'),\n jitter: options?.jitter ?? base.jitter,\n retryIf: options?.retryIf ?? base.retryIf,\n };\n if (\n policy.attempts !== Number.POSITIVE_INFINITY &&\n (!Number.isInteger(policy.attempts) || policy.attempts < 1)\n ) {\n throw new ConfigurationError(\n `retry.attempts must be a positive integer or Infinity, received ${policy.attempts}`,\n );\n }\n if (!Number.isFinite(policy.factor) || policy.factor < 1) {\n throw new ConfigurationError(`retry.factor must be at least 1, received ${policy.factor}`);\n }\n if (policy.maxDelayMs < policy.initialDelayMs) {\n throw new ConfigurationError('retry.maxDelay must not be smaller than retry.initialDelay');\n }\n if (!JITTER_STRATEGIES.includes(policy.jitter)) {\n throw new ConfigurationError(\n `retry.jitter must be one of ${JITTER_STRATEGIES.join(', ')}, received '${String(policy.jitter)}'`,\n );\n }\n return policy;\n}\n\n/**\n * Delay before the next attempt after `failedAttempts` failures (1-based):\n * capped exponential backoff with the policy's jitter.\n */\nexport function computeRetryDelay(\n policy: RetryPolicy,\n failedAttempts: number,\n random: () => number = Math.random,\n): number {\n const exponential = policy.initialDelayMs * policy.factor ** (failedAttempts - 1);\n const capped = Math.min(policy.maxDelayMs, exponential);\n switch (policy.jitter) {\n case 'full':\n return Math.round(random() * capped);\n case 'equal':\n return Math.round(capped / 2 + (random() * capped) / 2);\n case 'none':\n return Math.round(capped);\n }\n}\n\nexport function isRetryableError(policy: RetryPolicy, error: unknown): boolean {\n if (error instanceof NonRetryableError) {\n return false;\n }\n if (policy.retryIf === undefined) {\n return true;\n }\n try {\n return policy.retryIf(error);\n } catch {\n // A broken predicate must not lose the event: keep retrying until the budget runs out.\n return true;\n }\n}\n","import type { Clock } from './clock.js';\nimport {\n DispatcherStoppedError,\n HandlerTimeoutError,\n LeaseLostError,\n RelayBusError,\n toErrorInfo,\n} from './errors.js';\nimport { validatePayload, type EventEnvelope } from './event.js';\nimport type { ClaimedDelivery, EventStore } from './event-store.js';\nimport { runInIsolatedScope } from './execution-scope.js';\nimport type { HandlerContext, HandlerRegistration, HandlerRegistry } from './handler-registry.js';\nimport type { Notifier } from './notifier.js';\nimport { computeRetryDelay, isRetryableError } from './retry-policy.js';\n\nexport interface DispatcherSettings {\n readonly owner: string;\n readonly concurrency: number;\n readonly batchSize: number;\n readonly pollIntervalMs: number;\n readonly leaseDurationMs: number;\n readonly shutdownTimeoutMs: number;\n}\n\nexport interface DispatcherDependencies {\n readonly store: EventStore;\n readonly registry: HandlerRegistry;\n readonly clock: Clock;\n readonly random: () => number;\n readonly notifier: Notifier;\n readonly settings: DispatcherSettings;\n /** Waits between attempts to confirm a completion. Replaceable in tests. */\n readonly sleep?: (milliseconds: number) => Promise<void>;\n}\n\ninterface InFlightDelivery {\n readonly handler: string;\n readonly controller: AbortController;\n readonly settled: Promise<void>;\n}\n\ntype HandlerOutcome = 'completed' | 'unconfirmed';\n\n/** Delays between attempts to record a completion before leaving it to lease expiry. */\nconst COMPLETION_RETRY_DELAYS_MS = [50, 250, 1_000] as const;\n\nconst defaultSleep = (milliseconds: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, milliseconds));\n\n/**\n * Claims due deliveries and runs their handlers: bounded concurrency, lease\n * heartbeats with self-fencing, fenced completion, retries with backoff and\n * dead-lettering.\n */\nexport class Dispatcher {\n readonly #dependencies: DispatcherDependencies;\n readonly #sleep: (milliseconds: number) => Promise<void>;\n readonly #inFlight = new Set<InFlightDelivery>();\n #running = false;\n #loop: Promise<void> | undefined;\n #wakeUp: (() => void) | undefined;\n #wakeRequested = false;\n\n constructor(dependencies: DispatcherDependencies) {\n this.#dependencies = dependencies;\n this.#sleep = dependencies.sleep ?? defaultSleep;\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n get inFlightCount(): number {\n return this.#inFlight.size;\n }\n\n start(): void {\n if (this.#running) {\n return;\n }\n this.#running = true;\n this.#loop = this.#runLoop();\n }\n\n /** Shortens the wait before the next claim, for example right after a publish. */\n wake(): void {\n this.#wakeRequested = true;\n this.#wakeUp?.();\n }\n\n /**\n * Stops claiming, waits up to the shutdown timeout for running handlers,\n * then aborts the rest and releases their deliveries for another process.\n */\n async stop(): Promise<void> {\n if (!this.#running) {\n return;\n }\n this.#running = false;\n this.wake();\n const deadline = Date.now() + this.#dependencies.settings.shutdownTimeoutMs;\n await this.#waitUntil(this.#loop!, deadline);\n const settled = Promise.allSettled([...this.#inFlight].map((delivery) => delivery.settled));\n if ((await this.#waitUntil(settled, deadline)) === 'timeout') {\n for (const delivery of this.#inFlight) {\n delivery.controller.abort(new DispatcherStoppedError('relaybus dispatcher stopped'));\n }\n await settled;\n }\n }\n\n /** Claims one batch and resolves when every claimed delivery settled. Returns how many ran. */\n async processBatch(): Promise<number> {\n const started = await this.#claimAndStart();\n await Promise.allSettled(started.map((delivery) => delivery.settled));\n return started.length;\n }\n\n async #waitUntil(work: Promise<unknown>, deadline: number): Promise<'done' | 'timeout'> {\n let timer: NodeJS.Timeout | undefined;\n const timedOut = new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), Math.max(0, deadline - Date.now()));\n });\n const outcome = await Promise.race([work.then(() => 'done' as const), timedOut]);\n clearTimeout(timer);\n return outcome;\n }\n\n async #runLoop(): Promise<void> {\n while (this.#running) {\n let claimedCount = 0;\n try {\n claimedCount = (await this.#claimAndStart()).length;\n } catch (error) {\n this.#dependencies.notifier.failure('claim', error);\n }\n if (claimedCount > 0 && this.#freeSlots() > 0) {\n continue;\n }\n await this.#waitForWakeUp();\n }\n }\n\n async #waitForWakeUp(): Promise<void> {\n if (this.#wakeRequested) {\n this.#wakeRequested = false;\n return;\n }\n await new Promise<void>((resolve) => {\n const timer = setTimeout(done, this.#dependencies.settings.pollIntervalMs);\n function done(): void {\n clearTimeout(timer);\n resolve();\n }\n this.#wakeUp = done;\n });\n this.#wakeUp = undefined;\n this.#wakeRequested = false;\n }\n\n #freeSlots(): number {\n return this.#dependencies.settings.concurrency - this.#inFlight.size;\n }\n\n async #claimAndStart(): Promise<InFlightDelivery[]> {\n const { store, registry, clock, settings } = this.#dependencies;\n const started: InFlightDelivery[] = [];\n for (const request of this.#planClaims(registry.all())) {\n const now = clock.now();\n const claimed = await store.claim({\n handlers: request.handlers,\n limit: request.limit,\n leaseOwner: settings.owner,\n leaseExpiresAt: new Date(now.getTime() + settings.leaseDurationMs),\n now,\n });\n for (const delivery of claimed) {\n started.push(this.#start(delivery));\n }\n }\n return started;\n }\n\n /** One claim for handlers without a concurrency limit, one per limited handler with room. */\n #planClaims(\n registrations: readonly HandlerRegistration[],\n ): Array<{ handlers: string[]; limit: number }> {\n let free = Math.min(this.#freeSlots(), this.#dependencies.settings.batchSize);\n const plans: Array<{ handlers: string[]; limit: number }> = [];\n const unlimited = registrations.filter((registration) => registration.concurrency === null);\n for (const registration of registrations) {\n if (registration.concurrency === null || free === 0) {\n continue;\n }\n const room = registration.concurrency - this.#countInFlight(registration.id);\n const limit = Math.min(room, free);\n if (limit > 0) {\n plans.push({ handlers: [registration.id], limit });\n free -= limit;\n }\n }\n if (unlimited.length > 0 && free > 0) {\n plans.push({ handlers: unlimited.map((registration) => registration.id), limit: free });\n }\n return plans;\n }\n\n #countInFlight(handler: string): number {\n let count = 0;\n for (const delivery of this.#inFlight) {\n if (delivery.handler === handler) {\n count += 1;\n }\n }\n return count;\n }\n\n #start(delivery: ClaimedDelivery): InFlightDelivery {\n const controller = new AbortController();\n const entry: InFlightDelivery = {\n handler: delivery.handler,\n controller,\n settled: Promise.resolve()\n .then(() => this.#execute(delivery, controller))\n // Safety net: #execute handles every expected failure itself.\n .catch((error: unknown) => this.#dependencies.notifier.failure('dispatch', error))\n .finally(() => {\n this.#inFlight.delete(entry);\n this.wake();\n }),\n };\n this.#inFlight.add(entry);\n return entry;\n }\n\n async #execute(delivery: ClaimedDelivery, controller: AbortController): Promise<void> {\n const { registry, notifier, clock } = this.#dependencies;\n const registration = registry.get(delivery.handler)!;\n notifier.notify('onDeliveryStarted', { delivery });\n const startedAt = clock.now().getTime();\n if (delivery.attempt > registration.retry.attempts) {\n await this.#bury(\n delivery,\n new RelayBusError(\n `Delivery reached attempt ${delivery.attempt} of ${registration.retry.attempts} after its lease expired`,\n ),\n );\n return;\n }\n let stopHeartbeat = (): void => undefined;\n try {\n stopHeartbeat = registration.transactional\n ? await this.#guardTransactionalLease(registration, delivery, controller)\n : this.#startHeartbeat(delivery, controller);\n const outcome = await this.#runHandler(registration, delivery, controller);\n if (outcome === 'completed') {\n notifier.notify('onDeliverySucceeded', {\n delivery,\n durationMs: clock.now().getTime() - startedAt,\n });\n }\n } catch (error) {\n if (error instanceof LeaseLostError) {\n notifier.notify('onLeaseLost', { delivery });\n } else if (error instanceof DispatcherStoppedError) {\n await this.#release(delivery);\n } else {\n await this.#fail(registration, delivery, error);\n }\n } finally {\n stopHeartbeat();\n }\n }\n\n async #runHandler(\n registration: HandlerRegistration,\n delivery: ClaimedDelivery,\n controller: AbortController,\n ): Promise<HandlerOutcome> {\n const { store, clock } = this.#dependencies;\n const payload = await validatePayload(\n delivery.event.type,\n registration.schema,\n delivery.event.payload,\n );\n const event: EventEnvelope = { ...delivery.event, payload };\n if (registration.transactional) {\n await store.transaction(async (transaction) => {\n await this.#invoke(registration, event, delivery, controller, transaction);\n if (!(await store.complete(delivery, clock.now(), transaction))) {\n throw new LeaseLostError(`Lease on delivery ${delivery.deliveryId} was lost`);\n }\n });\n return 'completed';\n }\n await this.#invoke(registration, event, delivery, controller, undefined);\n return this.#confirmCompletion(delivery);\n }\n\n /**\n * Records a completion, retrying transient store errors while the lease is\n * still held. Gives up to lease expiry, which reruns the handler: at-least-once.\n */\n async #confirmCompletion(delivery: ClaimedDelivery): Promise<HandlerOutcome> {\n const { store, clock, notifier } = this.#dependencies;\n for (let attempt = 0; ; attempt += 1) {\n let completed: boolean;\n try {\n completed = await store.complete(delivery, clock.now());\n } catch (error) {\n const delay = COMPLETION_RETRY_DELAYS_MS[attempt];\n if (delay === undefined) {\n notifier.failure('complete', error);\n return 'unconfirmed';\n }\n await this.#sleep(delay);\n continue;\n }\n if (!completed) {\n throw new LeaseLostError(`Lease on delivery ${delivery.deliveryId} was lost`);\n }\n return 'completed';\n }\n }\n\n async #invoke(\n registration: HandlerRegistration,\n event: EventEnvelope,\n delivery: ClaimedDelivery,\n controller: AbortController,\n transaction: unknown,\n ): Promise<void> {\n const context: HandlerContext = {\n deliveryId: delivery.deliveryId,\n handler: delivery.handler,\n attempt: delivery.attempt,\n maxAttempts: registration.retry.attempts,\n signal: controller.signal,\n transaction,\n };\n // An isolated scope keeps a caller's transaction (for example a test calling\n // runOnce inside bus.transaction) from leaking into the handler.\n const scope = transaction === undefined ? { event } : { event, transaction };\n if (controller.signal.aborted) {\n // The lease was lost (or the bus stopped) while the payload was validated.\n throw controller.signal.reason;\n }\n const work = Promise.resolve().then(() =>\n runInIsolatedScope(scope, () => registration.handle(event, context)),\n );\n work.catch(() => undefined);\n let timer: NodeJS.Timeout | undefined;\n if (registration.timeoutMs !== null) {\n const timeoutMs = registration.timeoutMs;\n timer = setTimeout(() => {\n controller.abort(\n new HandlerTimeoutError(\n `Handler '${registration.id}' did not settle within ${timeoutMs}ms`,\n ),\n );\n }, timeoutMs);\n }\n try {\n await Promise.race([work, rejectOnAbort(controller.signal)]);\n } catch (error) {\n await this.#awaitAbandonedHandler(work, error, transaction !== undefined);\n throw error;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * After an abort the handler may still be running. Waiting for it keeps a\n * retry from overlapping the abandoned run, and keeps a transactional\n * handler from writing through a transaction that was already released.\n * Transactional handlers are always awaited; others for one lease duration,\n * except at shutdown, which already waited.\n */\n async #awaitAbandonedHandler(\n work: Promise<unknown>,\n reason: unknown,\n transactional: boolean,\n ): Promise<void> {\n const settledWork = work.then(\n () => undefined,\n () => undefined,\n );\n if (transactional) {\n await settledWork;\n return;\n }\n if (reason instanceof DispatcherStoppedError) {\n return;\n }\n const deadline = Date.now() + this.#dependencies.settings.leaseDurationMs;\n await this.#waitUntil(settledWork, deadline);\n }\n\n /**\n * Transactional handlers get no renewals: a renewal would write the delivery\n * the open transaction completes, which databases with snapshot isolation\n * (MongoDB) turn into a write conflict that reruns the handler. Instead the\n * lease is extended once to cover the handler timeout, and the handler is\n * aborted when that lease ends.\n */\n async #guardTransactionalLease(\n registration: HandlerRegistration,\n delivery: ClaimedDelivery,\n controller: AbortController,\n ): Promise<() => void> {\n const { store, clock, settings } = this.#dependencies;\n const now = clock.now();\n let expiry = delivery.leaseExpiresAt.getTime();\n if (registration.timeoutMs !== null && now.getTime() + registration.timeoutMs >= expiry) {\n expiry = now.getTime() + registration.timeoutMs + settings.leaseDurationMs;\n if (!(await store.extendLease(delivery, new Date(expiry), now))) {\n throw new LeaseLostError(`Lease on delivery ${delivery.deliveryId} was lost`);\n }\n }\n const timer = setTimeout(\n () => {\n controller.abort(new LeaseLostError(`Lease on delivery ${delivery.deliveryId} expired`));\n },\n Math.max(0, expiry - clock.now().getTime()),\n );\n timer.unref();\n return () => clearTimeout(timer);\n }\n\n /**\n * Renews the lease every third of its duration. A worker that cannot renew\n * aborts its handler once the last confirmed expiry passes, because another\n * worker may then claim the delivery (self-fencing).\n */\n #startHeartbeat(delivery: ClaimedDelivery, controller: AbortController): () => void {\n const { store, clock, notifier, settings } = this.#dependencies;\n let confirmedExpiry = delivery.leaseExpiresAt.getTime();\n let renewing = false;\n const abortLeaseLost = (): void => {\n controller.abort(new LeaseLostError(`Lease on delivery ${delivery.deliveryId} was lost`));\n };\n const timer = setInterval(\n () => {\n const now = clock.now();\n if (now.getTime() >= confirmedExpiry) {\n abortLeaseLost();\n return;\n }\n if (renewing) {\n return;\n }\n renewing = true;\n const expiry = now.getTime() + settings.leaseDurationMs;\n store\n .extendLease(delivery, new Date(expiry), now)\n .then((extended) => {\n if (extended) {\n confirmedExpiry = expiry;\n } else {\n abortLeaseLost();\n }\n })\n .catch((error: unknown) => notifier.failure('extend-lease', error))\n .finally(() => {\n renewing = false;\n });\n },\n Math.max(1, Math.floor(settings.leaseDurationMs / 3)),\n );\n timer.unref();\n return () => clearInterval(timer);\n }\n\n async #fail(\n registration: HandlerRegistration,\n delivery: ClaimedDelivery,\n error: unknown,\n ): Promise<void> {\n const { store, clock, random, notifier } = this.#dependencies;\n const policy = registration.retry;\n if (delivery.attempt >= policy.attempts || !isRetryableError(policy, error)) {\n await this.#bury(delivery, error);\n return;\n }\n const errorInfo = toErrorInfo(error);\n const now = clock.now();\n const availableAt = new Date(\n now.getTime() + computeRetryDelay(policy, delivery.attempt, random),\n );\n let rescheduled: boolean;\n try {\n rescheduled = await store.reschedule(delivery, availableAt, errorInfo, now);\n } catch (storeError) {\n notifier.failure('reschedule', storeError);\n return;\n }\n if (rescheduled) {\n notifier.notify('onDeliveryRetryScheduled', { delivery, error: errorInfo, availableAt });\n } else {\n notifier.notify('onLeaseLost', { delivery });\n }\n }\n\n async #bury(delivery: ClaimedDelivery, error: unknown): Promise<void> {\n const { store, clock, notifier } = this.#dependencies;\n const errorInfo = toErrorInfo(error);\n let buried: boolean;\n try {\n buried = await store.bury(delivery, errorInfo, clock.now());\n } catch (storeError) {\n notifier.failure('bury', storeError);\n return;\n }\n if (buried) {\n notifier.notify('onDeliveryDead', { delivery, error: errorInfo });\n } else {\n notifier.notify('onLeaseLost', { delivery });\n }\n }\n\n async #release(delivery: ClaimedDelivery): Promise<void> {\n const { store, clock, notifier } = this.#dependencies;\n let released: boolean;\n try {\n released = await store.release(delivery, clock.now());\n } catch (storeError) {\n notifier.failure('release', storeError);\n return;\n }\n if (released) {\n notifier.notify('onDeliveryReleased', { delivery });\n } else {\n notifier.notify('onLeaseLost', { delivery });\n }\n }\n}\n\nfunction rejectOnAbort(signal: AbortSignal): Promise<never> {\n return new Promise<never>((_, reject) => {\n // The reason is always an Error: the dispatcher aborts with LeaseLostError,\n // HandlerTimeoutError or DispatcherStoppedError.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n signal.addEventListener('abort', () => reject(signal.reason), { once: true });\n });\n}\n","import { toTimerMilliseconds, type Duration } from './duration.js';\nimport { ConfigurationError } from './errors.js';\nimport type { EventEnvelope } from './event.js';\nimport { createRetryPolicy, type RetryPolicy, type RetryPolicyOptions } from './retry-policy.js';\nimport type { StandardSchemaV1 } from './standard-schema.js';\n\n/** Passed to every handler call. */\nexport interface HandlerContext<TTransaction = unknown> {\n readonly deliveryId: string;\n readonly handler: string;\n /** Attempt number, starting at 1. */\n readonly attempt: number;\n readonly maxAttempts: number;\n /** Aborted when the handler times out, the lease is lost or the bus stops. */\n readonly signal: AbortSignal;\n /**\n * Transaction the delivery completes in, for handlers subscribed with\n * `transactional: true`. Write through it to make the handler's effects and\n * the completion atomic. Undefined otherwise.\n */\n readonly transaction: TTransaction | undefined;\n}\n\nexport type EventHandler<TPayload = unknown, TTransaction = unknown> = (\n event: EventEnvelope<TPayload>,\n context: HandlerContext<TTransaction>,\n) => unknown;\n\nexport interface SubscribeOptions {\n /**\n * Stable id of the handler. Deliveries are recorded under it, so renaming it\n * orphans pending deliveries. Letters, digits and `._:/-`.\n */\n readonly id: string;\n /** Overrides the bus retry policy field by field. */\n readonly retry?: RetryPolicyOptions;\n /** Abort and retry when a call takes longer. `false` disables the bus default. */\n readonly timeout?: Duration | false;\n /** Maximum concurrent deliveries of this handler in this process. */\n readonly concurrency?: number;\n /**\n * Run the handler inside a store transaction that also completes the\n * delivery: its writes and the completion commit or roll back together,\n * so a handler that writes only through `context.transaction` (or through\n * events it publishes) takes effect exactly once.\n *\n * The lease is not renewed while the transaction is open. A transactional\n * handler must finish within the lease duration (default 30s), or within its\n * `timeout`, which extends the lease once to cover it; otherwise it is aborted.\n */\n readonly transactional?: boolean;\n}\n\n/** Public description of a registered handler or route. */\nexport interface HandlerDescriptor {\n readonly id: string;\n readonly eventType: string;\n readonly retry: RetryPolicy;\n readonly timeoutMs: number | null;\n readonly concurrency: number | null;\n readonly transactional: boolean;\n /** True for routes that forward events to a transport. */\n readonly forwardsToTransport: boolean;\n}\n\nexport interface HandlerRegistration extends HandlerDescriptor {\n readonly schema: StandardSchemaV1 | undefined;\n readonly handle: EventHandler;\n}\n\nexport interface RegistrationDefaults {\n readonly retry: RetryPolicy;\n readonly timeoutMs: number | null;\n}\n\nconst HANDLER_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;\n\nexport interface RegistrationInput {\n readonly eventType: string;\n readonly schema: StandardSchemaV1 | undefined;\n readonly handle: EventHandler;\n readonly options: SubscribeOptions;\n readonly forwardsToTransport: boolean;\n}\n\nexport class HandlerRegistry {\n readonly #byId = new Map<string, HandlerRegistration>();\n readonly #byEventType = new Map<string, HandlerRegistration[]>();\n\n register(input: RegistrationInput, defaults: RegistrationDefaults): HandlerRegistration {\n const { options } = input;\n if (!HANDLER_ID_PATTERN.test(options.id)) {\n throw new ConfigurationError(\n `Handler id '${options.id}' must be 1-255 characters of letters, digits, '.', '_', ':', '/' or '-'`,\n );\n }\n if (this.#byId.has(options.id)) {\n throw new ConfigurationError(`Handler id '${options.id}' is already registered`);\n }\n if (\n options.concurrency !== undefined &&\n (!Number.isInteger(options.concurrency) || options.concurrency < 1)\n ) {\n throw new ConfigurationError(\n `Concurrency of handler '${options.id}' must be a positive integer, received ${options.concurrency}`,\n );\n }\n const registration: HandlerRegistration = {\n id: options.id,\n eventType: input.eventType,\n schema: input.schema,\n handle: input.handle,\n retry: createRetryPolicy(options.retry, defaults.retry),\n timeoutMs: resolveTimeout(options.timeout, defaults.timeoutMs, options.id),\n concurrency: options.concurrency ?? null,\n transactional: options.transactional ?? false,\n forwardsToTransport: input.forwardsToTransport,\n };\n this.#byId.set(registration.id, registration);\n const forType = this.#byEventType.get(registration.eventType) ?? [];\n forType.push(registration);\n this.#byEventType.set(registration.eventType, forType);\n return registration;\n }\n\n get(id: string): HandlerRegistration | undefined {\n return this.#byId.get(id);\n }\n\n forEventType(eventType: string): readonly HandlerRegistration[] {\n return this.#byEventType.get(eventType) ?? [];\n }\n\n all(): readonly HandlerRegistration[] {\n return [...this.#byId.values()];\n }\n}\n\nfunction resolveTimeout(\n timeout: Duration | false | undefined,\n fallback: number | null,\n handlerId: string,\n): number | null {\n if (timeout === undefined) {\n return fallback;\n }\n if (timeout === false) {\n return null;\n }\n return toTimerMilliseconds(timeout, `Timeout of handler '${handlerId}'`);\n}\n","import { toErrorInfo } from './errors.js';\nimport type { FailureStage, RelayBusLogger, RelayBusObserver } from './observer.js';\n\ntype ObserverMethod = Exclude<keyof RelayBusObserver, 'onFailure'>;\ntype ObserverArgument<TMethod extends keyof RelayBusObserver> = Parameters<\n NonNullable<RelayBusObserver[TMethod]>\n>[0];\n\n/** Fans hook calls out to every observer, isolating the bus from observer bugs. */\nexport class Notifier {\n readonly #observers: readonly RelayBusObserver[];\n readonly #logger: RelayBusLogger;\n\n constructor(observers: readonly RelayBusObserver[], logger: RelayBusLogger) {\n this.#observers = observers;\n this.#logger = logger;\n }\n\n notify<TMethod extends ObserverMethod>(\n method: TMethod,\n argument: ObserverArgument<TMethod>,\n ): void {\n for (const observer of this.#observers) {\n try {\n (observer[method] as ((value: ObserverArgument<TMethod>) => void) | undefined)?.call(\n observer,\n argument,\n );\n } catch (error) {\n this.#reportObserverFailure(observer, error);\n }\n }\n }\n\n failure(stage: FailureStage, error: unknown): void {\n const errorInfo = toErrorInfo(error);\n this.#logger.error(\n `[Notifier](failure) relaybus ${stage} failed | ${errorInfo.name}: ${errorInfo.message}`,\n );\n for (const observer of this.#observers) {\n try {\n observer.onFailure?.({ stage, error: errorInfo });\n } catch (observerError) {\n this.#logObserverFailure(observerError);\n }\n }\n }\n\n #reportObserverFailure(failedObserver: RelayBusObserver, error: unknown): void {\n this.#logObserverFailure(error);\n const errorInfo = toErrorInfo(error);\n for (const observer of this.#observers) {\n if (observer === failedObserver) {\n continue;\n }\n try {\n observer.onFailure?.({ stage: 'observer', error: errorInfo });\n } catch (observerError) {\n this.#logObserverFailure(observerError);\n }\n }\n }\n\n #logObserverFailure(error: unknown): void {\n const errorInfo = toErrorInfo(error);\n this.#logger.warn(\n `[Notifier](notify) relaybus observer threw | ${errorInfo.name}: ${errorInfo.message}`,\n );\n }\n}\n","import { hostname } from 'node:os';\nimport { systemClock, type Clock } from './clock.js';\nimport { Dispatcher, type DispatcherSettings } from './dispatcher.js';\nimport { toMilliseconds, toTimerMilliseconds, type Duration } from './duration.js';\nimport {\n ConfigurationError,\n InvalidEnvelopeError,\n RelayBusError,\n TransactionRequiredError,\n toErrorInfo,\n} from './errors.js';\nimport {\n assertEventType,\n validatePayload,\n type DomainEvent,\n type EventClass,\n type EventEnvelope,\n type EventHeaders,\n type EventReference,\n} from './event.js';\nimport type {\n AppendEntry,\n DeliveryQuery,\n DeliveryRecord,\n EventStore,\n EventStoreStatistics,\n NewDelivery,\n PurgeResult,\n} from './event-store.js';\nimport { getCurrentScope, runInScope, type ExecutionScope } from './execution-scope.js';\nimport {\n HandlerRegistry,\n type EventHandler,\n type HandlerDescriptor,\n type HandlerRegistration,\n type RegistrationDefaults,\n type SubscribeOptions,\n} from './handler-registry.js';\nimport { createUuidV7, type IdentifierGenerator } from './identifier.js';\nimport { Notifier } from './notifier.js';\nimport type { RelayBusLogger, RelayBusObserver } from './observer.js';\nimport {\n DEFAULT_ROUTE_RETRY_POLICY,\n createRetryPolicy,\n type RetryPolicyOptions,\n} from './retry-policy.js';\nimport type { StandardSchemaV1 } from './standard-schema.js';\nimport type { Transport } from './transport.js';\n\n/**\n * - `required`: `publish` throws {@link TransactionRequiredError} when it finds no transaction.\n * - `optional`: `publish` opens its own transaction instead. The event is still durable,\n * but no longer atomic with business writes made outside that transaction.\n */\nexport type TransactionMode = 'required' | 'optional';\n\n/**\n * What `publish` does with an event that has no handler or route in this\n * process. Deliveries are created from the publisher's registrations, so a\n * process must register every handler and route of the events it publishes.\n * - `warn`: log a warning and store nothing.\n * - `throw`: throw a {@link ConfigurationError}, rolling back the caller's transaction.\n */\nexport type UnroutedEventPolicy = 'warn' | 'throw';\n\nexport interface DispatcherOptions {\n /** Run handlers in this process. Disable on publish-only processes. Default true. */\n readonly enabled?: boolean;\n /** Maximum handlers running at once. Default 10. */\n readonly concurrency?: number;\n /** Maximum deliveries claimed per query. Default equals concurrency. */\n readonly batchSize?: number;\n /** Wait between claims when idle. Retries are picked up on this cadence. Default `'1s'`. */\n readonly pollInterval?: Duration;\n /** Lease length; renewed every third of it while the handler runs. Default `'30s'`. */\n readonly leaseDuration?: Duration;\n /** How long `stop` waits for running handlers before aborting them. Default `'30s'`. */\n readonly shutdownTimeout?: Duration;\n}\n\nexport interface RetentionOptions {\n /**\n * Delete completed deliveries older than this. Default `'7d'`; `false` keeps them.\n * Deduplication of received events and of publishes with a caller-supplied id\n * only lasts as long as the event is kept: keep this longer than any broker\n * redelivery or publish retry window.\n */\n readonly completed?: Duration | false;\n /** Delete dead deliveries older than this. Default `false` (keep for inspection). */\n readonly dead?: Duration | false;\n /** How often the cleanup runs. Default `'1h'`. */\n readonly interval?: Duration;\n}\n\nexport interface RouteOptions {\n /** Event class or type forwarded to the transport. */\n readonly event: EventReference;\n /** Name of a configured transport. */\n readonly transport: string;\n /** Topic, exchange or queue. Default: the event type. */\n readonly destination?: string;\n /** Default: retry until the broker accepts the event, at most every 5 minutes. */\n readonly retry?: RetryPolicyOptions;\n /** Abort a publish that hangs and retry it. Default `'30s'`. */\n readonly timeout?: Duration;\n}\n\nexport interface InboundSubscriptionOptions {\n readonly transport: string;\n readonly destinations: readonly string[];\n}\n\nexport interface RelayBusOptions<TTransaction = unknown> {\n readonly store: EventStore<TTransaction>;\n /** Name of this service, recorded on every event. Default `'relaybus'`. */\n readonly source?: string;\n /** Default `'required'`. */\n readonly transactionMode?: TransactionMode;\n /**\n * Finds the caller's active transaction when none is passed to `publish`\n * and none was opened with `bus.transaction`, for example from\n * `@nestjs-cls/transactional`. Return undefined when there is none.\n */\n readonly transactionResolver?: () => TTransaction | undefined;\n /** Default `'warn'`. */\n readonly unroutedEvents?: UnroutedEventPolicy;\n /** Default retry policy of every handler. Routes have their own default. */\n readonly retry?: RetryPolicyOptions;\n /** Default handler timeout. Default `false` (no timeout). */\n readonly handlerTimeout?: Duration | false;\n readonly dispatcher?: DispatcherOptions;\n readonly retention?: RetentionOptions;\n readonly transports?: readonly Transport[];\n /** Events forwarded to brokers after they commit. */\n readonly routes?: readonly RouteOptions[];\n /** Broker destinations whose events are stored and dispatched to local handlers. */\n readonly subscriptions?: readonly InboundSubscriptionOptions[];\n /** Create tables and indexes on start. Default true. */\n readonly setupStore?: boolean;\n readonly observers?: readonly RelayBusObserver[];\n /** Default: `console`. */\n readonly logger?: RelayBusLogger;\n readonly clock?: Clock;\n readonly generateIdentifier?: IdentifierGenerator;\n readonly random?: () => number;\n}\n\nexport interface PublishOptions<TTransaction = unknown> {\n /** Transaction to write into. Default: the current scope, then `transactionResolver`. */\n readonly transaction?: TTransaction;\n /**\n * Ordering and partition key. Events with the same key are handled one at a\n * time per handler, in commit order. A delayed or retrying event holds back\n * later events of its key.\n */\n readonly key?: string;\n /** Deliver no earlier than this delay from now. */\n readonly delay?: Duration;\n readonly headers?: EventHeaders;\n /**\n * Default: inherited from the event being handled, otherwise the id of the\n * first published event (shared by every event of a `publishAll` call).\n */\n readonly correlationId?: string;\n}\n\nexport interface PublishOneOptions<TTransaction = unknown> extends PublishOptions<TTransaction> {\n /**\n * Event id. Pass a deterministic id (for example derived from a business key)\n * to make publishing idempotent: when an event with this id is already\n * stored, nothing is written and the stored event is left unchanged.\n */\n readonly id?: string;\n}\n\nexport type ReceiveStatus = 'accepted' | 'duplicate' | 'ignored';\n\ntype BusState = 'idle' | 'starting' | 'running' | 'stopping' | 'stopped';\n\nconst DEFAULTS = {\n concurrency: 10,\n pollInterval: '1s',\n leaseDuration: '30s',\n shutdownTimeout: '30s',\n completedRetention: '7d',\n retentionInterval: '1h',\n routeTimeoutMs: 30_000,\n} as const;\n\nconst TRANSPORT_HANDLER_PREFIX = 'relaybus.transport';\nconst WAKE_DELAY_MS = 25;\n\n/**\n * Reliable event bus: events are stored with business data in one transaction,\n * then dispatched to every subscribed handler and route with independent\n * retries, leases and dead-lettering. A bus instance can be started once.\n */\nexport class RelayBus<TTransaction = unknown> {\n readonly #store: EventStore<TTransaction>;\n readonly #source: string;\n readonly #transactionMode: TransactionMode;\n readonly #transactionResolver: (() => TTransaction | undefined) | undefined;\n readonly #unroutedEvents: UnroutedEventPolicy;\n readonly #registry = new HandlerRegistry();\n readonly #defaults: RegistrationDefaults;\n readonly #transports = new Map<string, Transport>();\n readonly #subscriptions: readonly InboundSubscriptionOptions[];\n readonly #notifier: Notifier;\n readonly #logger: RelayBusLogger;\n readonly #clock: Clock;\n readonly #generateIdentifier: IdentifierGenerator;\n readonly #dispatcher: Dispatcher;\n readonly #dispatcherEnabled: boolean;\n readonly #setupStore: boolean;\n readonly #retention: { completedMs: number | null; deadMs: number | null; intervalMs: number };\n #retentionTimer: NodeJS.Timeout | undefined;\n #state: BusState = 'idle';\n #starting: Promise<void> | undefined;\n #stopping: Promise<void> | undefined;\n\n constructor(options: RelayBusOptions<TTransaction>) {\n this.#store = options.store;\n this.#source = options.source ?? 'relaybus';\n this.#transactionMode = oneOf(\n options.transactionMode ?? 'required',\n ['required', 'optional'],\n 'transactionMode',\n );\n this.#unroutedEvents = oneOf(\n options.unroutedEvents ?? 'warn',\n ['warn', 'throw'],\n 'unroutedEvents',\n );\n this.#transactionResolver = options.transactionResolver;\n this.#defaults = {\n retry: createRetryPolicy(options.retry),\n timeoutMs:\n options.handlerTimeout === undefined || options.handlerTimeout === false\n ? null\n : toTimerMilliseconds(options.handlerTimeout, 'handlerTimeout'),\n };\n this.#logger = options.logger ?? console;\n this.#notifier = new Notifier(options.observers ?? [], this.#logger);\n this.#clock = options.clock ?? systemClock;\n this.#generateIdentifier = options.generateIdentifier ?? (() => createUuidV7());\n this.#setupStore = options.setupStore ?? true;\n this.#retention = createRetentionSettings(options.retention);\n for (const transport of options.transports ?? []) {\n if (this.#transports.has(transport.name)) {\n throw new ConfigurationError(`Transport name '${transport.name}' is used twice`);\n }\n this.#transports.set(transport.name, transport);\n }\n for (const route of options.routes ?? []) {\n this.#registerRoute(route);\n }\n this.#subscriptions = options.subscriptions ?? [];\n for (const subscription of this.#subscriptions) {\n const transport = this.#requireTransport(subscription.transport);\n if (transport.subscribe === undefined) {\n throw new ConfigurationError(`Transport '${transport.name}' cannot subscribe`);\n }\n }\n this.#dispatcherEnabled = options.dispatcher?.enabled ?? true;\n this.#dispatcher = new Dispatcher({\n store: this.#store,\n registry: this.#registry,\n clock: this.#clock,\n random: options.random ?? Math.random,\n notifier: this.#notifier,\n settings: createDispatcherSettings(options.dispatcher, this.#generateIdentifier),\n });\n }\n\n get store(): EventStore<TTransaction> {\n return this.#store;\n }\n\n get isRunning(): boolean {\n return this.#state === 'running';\n }\n\n /** True while the bus runs and every transport reports itself ready. */\n isReady(): boolean {\n if (this.#state !== 'running') {\n return false;\n }\n for (const transport of this.#transports.values()) {\n if (transport.isReady?.() === false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Subscribes a handler to an event class or type. Register handlers in every\n * process that publishes the event: deliveries are created at publish time\n * from the publisher's registrations.\n */\n subscribe<TPayload>(\n event: EventClass<TPayload>,\n handler: EventHandler<TPayload, TTransaction>,\n options: SubscribeOptions,\n ): void;\n subscribe(\n eventType: string,\n handler: EventHandler<unknown, TTransaction>,\n options: SubscribeOptions,\n ): void;\n subscribe(\n event: EventClass<unknown> | string,\n handler: EventHandler<unknown, TTransaction>,\n options: SubscribeOptions,\n ): void {\n const { type, schema } = describeEvent(event);\n this.#registry.register(\n {\n eventType: type,\n schema,\n handle: handler as EventHandler,\n options,\n forwardsToTransport: false,\n },\n this.#defaults,\n );\n }\n\n /** Registered handlers and routes, for diagnostics. */\n handlers(): readonly HandlerDescriptor[] {\n return this.#registry.all().map(toDescriptor);\n }\n\n /**\n * Stores an event in the current transaction. Handlers run after the\n * transaction commits. Returns the envelope that was written, or that would\n * have been written when the id already exists.\n */\n async publish<TPayload>(\n event: DomainEvent<TPayload>,\n options: PublishOneOptions<TTransaction> = {},\n ): Promise<EventEnvelope<TPayload>> {\n const [envelope] = await this.#publish([event], options, options.id);\n return envelope as EventEnvelope<TPayload>;\n }\n\n /** Stores several events atomically, in order, sharing one correlation id. */\n async publishAll(\n events: readonly DomainEvent[],\n options: PublishOptions<TTransaction> = {},\n ): Promise<EventEnvelope[]> {\n return this.#publish(events, options, undefined);\n }\n\n /**\n * Runs `work` in a new store transaction. `publish` calls inside it join the\n * transaction without passing it explicitly.\n */\n async transaction<T>(work: (transaction: TTransaction) => Promise<T>): Promise<T> {\n return this.#store.transaction((transaction) =>\n runInScope({ transaction }, () => work(transaction)),\n );\n }\n\n /**\n * Stores an event received from a broker and schedules it for local handlers.\n * Idempotent on the event id. Transports call it and acknowledge the message\n * only after it resolves. Throws {@link InvalidEnvelopeError} for malformed\n * events, which transports should dead-letter instead of redelivering.\n */\n async receive(envelope: EventEnvelope): Promise<ReceiveStatus> {\n const normalized = normalizeEnvelope(envelope);\n const registrations = this.#registry\n .forEventType(normalized.type)\n .filter((registration) => !registration.forwardsToTransport);\n if (registrations.length === 0) {\n this.#notifier.notify('onReceived', { envelope: normalized, status: 'ignored' });\n return 'ignored';\n }\n const now = this.#clock.now();\n const entry: AppendEntry = {\n event: normalized,\n deliveries: registrations.map((registration) => this.#createDelivery(registration, now)),\n };\n const result = await this.#store.transaction((transaction) =>\n this.#store.append(transaction, [entry], now),\n );\n const status: ReceiveStatus = result.duplicateEventIds.length > 0 ? 'duplicate' : 'accepted';\n this.#notifier.notify('onReceived', { envelope: normalized, status });\n if (result.appendedDeliveryCount > 0) {\n this.#scheduleWake();\n }\n return status;\n }\n\n /**\n * Creates the store schema, connects transports, subscribes and starts\n * dispatching. A bus starts once: after a failed start or a stop it is\n * stopped for good, because its transports are closed; create a new instance.\n */\n async start(): Promise<void> {\n if (this.#state !== 'idle') {\n throw new RelayBusError(\n this.#state === 'stopped'\n ? 'A stopped relaybus cannot be started again; create a new instance'\n : `Cannot start a relaybus that is ${this.#state}`,\n );\n }\n this.#state = 'starting';\n this.#starting = this.#startComponents();\n try {\n await this.#starting;\n } finally {\n this.#starting = undefined;\n }\n }\n\n /**\n * Stops dispatching, waits for running handlers, closes transports and the\n * store. Waits for a start in progress first. Safe to call more than once.\n */\n async stop(): Promise<void> {\n if (this.#stopping !== undefined) {\n return this.#stopping;\n }\n if (this.#state === 'starting') {\n await this.#starting!.catch(() => undefined);\n }\n if (this.#state !== 'running') {\n return;\n }\n this.#stopping = this.#stopComponents();\n return this.#stopping;\n }\n\n /**\n * Claims and runs one batch of due deliveries, resolving when they settle.\n * Returns how many ran. Intended for tests and scripts.\n */\n async runOnce(): Promise<number> {\n return this.#dispatcher.processBatch();\n }\n\n /**\n * Runs batches until nothing is due. Deliveries scheduled in the future\n * (retries, delays) are not waited for. Intended for tests.\n */\n async drain(maxBatches = 1_000): Promise<number> {\n let total = 0;\n for (let batch = 0; batch < maxBatches; batch += 1) {\n const processed = await this.runOnce();\n if (processed === 0) {\n return total;\n }\n total += processed;\n }\n throw new RelayBusError(`drain did not finish within ${maxBatches} batches`);\n }\n\n listDeliveries(query: DeliveryQuery = {}): Promise<DeliveryRecord[]> {\n return this.#store.listDeliveries(query);\n }\n\n /** Moves dead deliveries back to pending with a fresh attempt budget. */\n async requeue(deliveryIds: readonly string[]): Promise<number> {\n const moved = await this.#store.requeue(deliveryIds, this.#clock.now());\n if (moved > 0) {\n this.#dispatcher.wake();\n }\n return moved;\n }\n\n statistics(): Promise<EventStoreStatistics> {\n return this.#store.statistics(this.#clock.now());\n }\n\n /** Applies the retention policy once. Runs automatically while the bus is running. */\n async purgeExpired(): Promise<PurgeResult> {\n const now = this.#clock.now().getTime();\n const { completedMs, deadMs } = this.#retention;\n try {\n const result = await this.#store.purge({\n ...(completedMs === null ? {} : { completedBefore: new Date(now - completedMs) }),\n ...(deadMs === null ? {} : { deadBefore: new Date(now - deadMs) }),\n });\n this.#notifier.notify('onPurged', { result });\n return result;\n } catch (error) {\n this.#notifier.failure('purge', error);\n throw error;\n }\n }\n\n async #startComponents(): Promise<void> {\n try {\n if (this.#setupStore) {\n await this.#store.setup?.();\n }\n for (const transport of this.#transports.values()) {\n await transport.connect?.();\n }\n for (const subscription of this.#subscriptions) {\n const transport = this.#transports.get(subscription.transport)!;\n await transport.subscribe!(subscription.destinations, async (envelope) => {\n await this.receive(envelope);\n });\n }\n } catch (error) {\n await this.#closeTransports();\n this.#state = 'stopped';\n throw error;\n }\n if (this.#dispatcherEnabled) {\n this.#dispatcher.start();\n }\n if (this.#retention.completedMs !== null || this.#retention.deadMs !== null) {\n this.#retentionTimer = setInterval(() => {\n this.purgeExpired().catch(() => undefined);\n }, this.#retention.intervalMs);\n this.#retentionTimer.unref();\n }\n this.#state = 'running';\n this.#logger.log(\n `[RelayBus](start) relaybus started | handlers=${this.#registry.all().length} dispatcher=${this.#dispatcherEnabled}`,\n );\n }\n\n async #stopComponents(): Promise<void> {\n this.#state = 'stopping';\n clearInterval(this.#retentionTimer);\n try {\n await this.#dispatcher.stop();\n await this.#closeTransports();\n await this.#store.close?.();\n } finally {\n this.#state = 'stopped';\n }\n }\n\n async #publish(\n events: readonly DomainEvent[],\n options: PublishOptions<TTransaction>,\n id: string | undefined,\n ): Promise<EventEnvelope[]> {\n if (events.length === 0) {\n return [];\n }\n const now = this.#clock.now();\n const delayMs = options.delay === undefined ? 0 : toMilliseconds(options.delay, 'delay');\n const availableAt = new Date(now.getTime() + delayMs);\n const scope = getCurrentScope();\n const entries: AppendEntry[] = [];\n let correlationId = options.correlationId ?? scope?.event?.correlationId ?? scope?.event?.id;\n for (const event of events) {\n const envelope = await this.#createEnvelope(event, options, id, scope, now, correlationId);\n correlationId = envelope.correlationId!;\n const registrations = this.#registry.forEventType(envelope.type);\n if (registrations.length === 0) {\n this.#reportUnrouted(envelope);\n }\n entries.push({\n event: envelope,\n deliveries: registrations.map((registration) =>\n this.#createDelivery(registration, availableAt),\n ),\n });\n }\n const deliverable = entries.filter((entry) => entry.deliveries.length > 0);\n if (deliverable.length > 0) {\n const result = await this.#appendInTransaction(deliverable, options, scope, now);\n const appended = new Set(result.appendedEventIds);\n const published = deliverable\n .map((entry) => entry.event)\n .filter((envelope) => appended.has(envelope.id));\n if (published.length > 0) {\n this.#notifier.notify('onPublished', {\n envelopes: published,\n deliveries: result.appendedDeliveryCount,\n });\n if (delayMs === 0) {\n this.#scheduleWake();\n }\n }\n }\n return entries.map((entry) => entry.event);\n }\n\n #reportUnrouted(envelope: EventEnvelope): void {\n const message = `No handler or route for event type, event not stored | type=${envelope.type} id=${envelope.id}`;\n if (this.#unroutedEvents === 'throw') {\n throw new ConfigurationError(message);\n }\n this.#logger.warn(`[RelayBus](publish) ${message}`);\n }\n\n async #appendInTransaction(\n entries: readonly AppendEntry[],\n options: PublishOptions<TTransaction>,\n scope: ExecutionScope | undefined,\n now: Date,\n ): Promise<{ appendedEventIds: readonly string[]; appendedDeliveryCount: number }> {\n const transaction =\n options.transaction ??\n (scope?.transaction as TTransaction | undefined) ??\n this.#transactionResolver?.();\n if (transaction !== undefined) {\n return this.#store.append(transaction, entries, now);\n }\n if (this.#transactionMode === 'required') {\n throw new TransactionRequiredError(\n 'publish found no transaction. Pass { transaction }, publish inside bus.transaction(), configure transactionResolver, or set transactionMode to optional',\n );\n }\n return this.#store.transaction((ownTransaction) =>\n this.#store.append(ownTransaction, entries, now),\n );\n }\n\n async #createEnvelope(\n event: DomainEvent,\n options: PublishOptions<TTransaction>,\n id: string | undefined,\n scope: ExecutionScope | undefined,\n now: Date,\n correlationId: string | undefined,\n ): Promise<EventEnvelope> {\n if (typeof event.type !== 'string') {\n throw new ConfigurationError(\n 'publish expects an instance of a class created with defineEvent',\n );\n }\n assertEventType(event.type);\n const schema = (event.constructor as Partial<EventClass>).schema;\n const payload = await validatePayload(event.type, schema, event.payload);\n if (options.key !== undefined && options.key.length === 0) {\n throw new ConfigurationError('key must not be empty');\n }\n const eventId = id ?? this.#generateIdentifier();\n return {\n id: eventId,\n type: event.type,\n source: this.#source,\n key: options.key ?? null,\n payload,\n headers: { ...options.headers },\n correlationId: correlationId ?? eventId,\n causationId: scope?.event?.id ?? null,\n occurredAt: now,\n };\n }\n\n #createDelivery(registration: HandlerRegistration, availableAt: Date): NewDelivery {\n return { id: this.#generateIdentifier(), handler: registration.id, availableAt };\n }\n\n #registerRoute(route: RouteOptions): void {\n const transport = this.#requireTransport(route.transport);\n const { type } = describeEvent(route.event);\n const destination = route.destination ?? type;\n this.#registry.register(\n {\n eventType: type,\n schema: undefined,\n handle: (envelope) => transport.publish(envelope, destination),\n options: {\n id: `${TRANSPORT_HANDLER_PREFIX}:${transport.name}:${destination}:${type}`,\n ...(route.retry === undefined ? {} : { retry: route.retry }),\n ...(route.timeout === undefined ? {} : { timeout: route.timeout }),\n },\n forwardsToTransport: true,\n },\n { retry: DEFAULT_ROUTE_RETRY_POLICY, timeoutMs: DEFAULTS.routeTimeoutMs },\n );\n }\n\n #requireTransport(name: string): Transport {\n const transport = this.#transports.get(name);\n if (transport === undefined) {\n throw new ConfigurationError(`No transport named '${name}' is configured`);\n }\n return transport;\n }\n\n #scheduleWake(): void {\n if (this.#state !== 'running') {\n return;\n }\n // The publishing transaction commits after publish returns; claim shortly after.\n setTimeout(() => this.#dispatcher.wake(), WAKE_DELAY_MS).unref();\n }\n\n async #closeTransports(): Promise<void> {\n for (const transport of this.#transports.values()) {\n try {\n await transport.close();\n } catch (error) {\n this.#logger.error(\n `[RelayBus](closeTransports) Failed to close transport | transport=${transport.name} error=${toErrorInfo(error).message}`,\n );\n }\n }\n }\n}\n\nfunction toDescriptor(registration: HandlerRegistration): HandlerDescriptor {\n return {\n id: registration.id,\n eventType: registration.eventType,\n retry: registration.retry,\n timeoutMs: registration.timeoutMs,\n concurrency: registration.concurrency,\n transactional: registration.transactional,\n forwardsToTransport: registration.forwardsToTransport,\n };\n}\n\nfunction describeEvent(event: EventReference): {\n type: string;\n schema: StandardSchemaV1 | undefined;\n} {\n if (typeof event === 'string') {\n assertEventType(event);\n return { type: event, schema: undefined };\n }\n assertEventType(event.type);\n return { type: event.type, schema: (event as Partial<EventClass>).schema };\n}\n\n/**\n * Validates an event received from a broker and fills fields that JSON-based\n * wire formats commonly drop (`undefined` key, headers, correlation ids).\n */\nfunction normalizeEnvelope(envelope: EventEnvelope): EventEnvelope {\n if (typeof envelope.id !== 'string' || envelope.id.length === 0) {\n throw new InvalidEnvelopeError('Received event has no id');\n }\n if (typeof envelope.type !== 'string') {\n throw new InvalidEnvelopeError(`Received event ${envelope.id} has no type`);\n }\n try {\n assertEventType(envelope.type);\n } catch (error) {\n throw new InvalidEnvelopeError(toErrorInfo(error).message);\n }\n const occurredAt = toDate(envelope.occurredAt);\n if (occurredAt === undefined) {\n throw new InvalidEnvelopeError(`Received event ${envelope.id} has an invalid occurredAt`);\n }\n return {\n id: envelope.id,\n type: envelope.type,\n source: typeof envelope.source === 'string' ? envelope.source : 'unknown',\n key: optionalText(envelope.key),\n payload: envelope.payload,\n headers: { ...envelope.headers },\n correlationId: optionalText(envelope.correlationId),\n causationId: optionalText(envelope.causationId),\n occurredAt,\n };\n}\n\nfunction toDate(value: Date | string): Date | undefined {\n const date = typeof value === 'string' ? new Date(value) : value;\n return date instanceof Date && !Number.isNaN(date.getTime()) ? date : undefined;\n}\n\nfunction optionalText(value: string | null | undefined): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n\nfunction oneOf<T extends string>(value: T, allowed: readonly T[], name: string): T {\n if (!allowed.includes(value)) {\n throw new ConfigurationError(\n `${name} must be one of ${allowed.map((option) => `'${option}'`).join(', ')}, received '${String(value)}'`,\n );\n }\n return value;\n}\n\nfunction positiveInteger(value: number, name: string): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new ConfigurationError(`${name} must be a positive integer, received ${value}`);\n }\n return value;\n}\n\nfunction createDispatcherSettings(\n options: DispatcherOptions | undefined,\n generateIdentifier: IdentifierGenerator,\n): DispatcherSettings {\n const concurrency = positiveInteger(\n options?.concurrency ?? DEFAULTS.concurrency,\n 'dispatcher.concurrency',\n );\n return {\n owner: `${hostname()}:${process.pid}:${generateIdentifier()}`,\n concurrency,\n batchSize: positiveInteger(options?.batchSize ?? concurrency, 'dispatcher.batchSize'),\n pollIntervalMs: toTimerMilliseconds(\n options?.pollInterval ?? DEFAULTS.pollInterval,\n 'dispatcher.pollInterval',\n ),\n leaseDurationMs: toTimerMilliseconds(\n options?.leaseDuration ?? DEFAULTS.leaseDuration,\n 'dispatcher.leaseDuration',\n ),\n shutdownTimeoutMs: toTimerMilliseconds(\n options?.shutdownTimeout ?? DEFAULTS.shutdownTimeout,\n 'dispatcher.shutdownTimeout',\n ),\n };\n}\n\nfunction createRetentionSettings(options: RetentionOptions | undefined): {\n completedMs: number | null;\n deadMs: number | null;\n intervalMs: number;\n} {\n const completed = options?.completed ?? DEFAULTS.completedRetention;\n const dead = options?.dead ?? false;\n return {\n completedMs: completed === false ? null : toMilliseconds(completed, 'retention.completed'),\n deadMs: dead === false ? null : toMilliseconds(dead, 'retention.dead'),\n intervalMs: toTimerMilliseconds(\n options?.interval ?? DEFAULTS.retentionInterval,\n 'retention.interval',\n ),\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/clock.ts","../src/errors.ts","../src/duration.ts","../src/event.ts","../src/catalog.ts","../src/catalog-publisher.ts","../src/catalog-coverage.ts","../src/event-store.ts","../src/identifier.ts","../src/in-memory-event-store.ts","../src/completion-batcher.ts","../src/execution-scope.ts","../src/retry-policy.ts","../src/dispatcher.ts","../src/handler-registry.ts","../src/notifier.ts","../src/relay-bus.ts"],"names":["randomBytes","AsyncLocalStorage","hostname"],"mappings":";;;;;;;AAKO,IAAM,WAAA,GAAqB;AAAA,EAChC,GAAA,EAAK,sBAAM,IAAI,IAAA;AACjB;;;ACJO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA;AAAA,EAE9B,IAAA,GAAO,eAAA;AAClB;AAGO,IAAM,kBAAA,GAAN,cAAiC,aAAA,CAAc;AAAA,EAC3C,IAAA,GAAO,oBAAA;AAClB;AAOO,IAAM,wBAAA,GAAN,cAAuC,aAAA,CAAc;AAAA,EACjD,IAAA,GAAO,0BAAA;AAClB;AAMO,IAAM,iBAAA,GAAN,cAAgC,aAAA,CAAc;AAAA,EAC1C,IAAA,GAAO,mBAAA;AAClB;AAGO,IAAM,oBAAA,GAAN,cAAmC,iBAAA,CAAkB;AAAA,EAG1D,WAAA,CACE,SACS,MAAA,EACT;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFJ,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AA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AAA,KACF;AAAA,IACA,mBAAA,EAAqB,eAAA;AAAA,MACnB,OAAA,EAAS,uBAAuB,QAAA,CAAS,mBAAA;AAAA,MACzC;AAAA;AACF,GACF;AACF;AAEA,SAAS,wBAAwB,OAAA,EAI/B;AACA,EAAA,MAAM,SAAA,GAAY,OAAA,EAAS,SAAA,IAAa,QAAA,CAAS,kBAAA;AACjD,EAAA,MAAM,IAAA,GAAO,SAAS,IAAA,IAAQ,KAAA;AAC9B,EAAA,OAAO;AAAA,IACL,aAAa,SAAA,KAAc,KAAA,GAAQ,IAAA,GAAO,cAAA,CAAe,WAAW,qBAAqB,CAAA;AAAA,IACzF,QAAQ,IAAA,KAAS,KAAA,GAAQ,IAAA,GAAO,cAAA,CAAe,MAAM,gBAAgB,CAAA;AAAA,IACrE,UAAA,EAAY,mBAAA;AAAA,MACV,OAAA,EAAS,YAAY,QAAA,CAAS,iBAAA;AAAA,MAC9B;AAAA;AACF,GACF;AACF","file":"index.cjs","sourcesContent":["/** Source of the current time. Replace it in tests to control retries and leases. */\nexport interface Clock {\n now(): Date;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n};\n","/**\n * Base class of every error thrown by relaybus.\n */\nexport class RelayBusError extends Error {\n // Explicit names survive minification, unlike `new.target.name`.\n override name = 'RelayBusError';\n}\n\n/** Invalid options passed to a relaybus component. */\nexport class ConfigurationError extends RelayBusError {\n override name = 'ConfigurationError';\n}\n\n/**\n * Thrown by `publish` when no transaction can be found and the bus runs with\n * `transactionMode: 'required'` (the default). Publishing outside a transaction\n * would reintroduce the dual-write problem the outbox exists to prevent.\n */\nexport class TransactionRequiredError extends RelayBusError {\n override name = 'TransactionRequiredError';\n}\n\n/**\n * Throw from a handler to dead-letter the delivery immediately, skipping the\n * remaining retry attempts.\n */\nexport class NonRetryableError extends RelayBusError {\n override name = 'NonRetryableError';\n}\n\n/** A payload failed its event schema. Never retried: the payload will not change. */\nexport class EventValidationError extends NonRetryableError {\n override name = 'EventValidationError';\n\n constructor(\n message: string,\n readonly issues: readonly ValidationIssue[],\n ) {\n super(message);\n }\n}\n\n/**\n * A message received from a broker is not a valid event. Never retried:\n * transports should dead-letter it instead of redelivering it forever.\n */\nexport class InvalidEnvelopeError extends NonRetryableError {\n override name = 'InvalidEnvelopeError';\n}\n\n/** The worker no longer owns the delivery it was processing. */\nexport class LeaseLostError extends RelayBusError {\n override name = 'LeaseLostError';\n /**\n * Whether the store said so (a fenced write returned false). A worker that only noticed\n * locally that its lease ran out may still own the delivery in the store and has to give it back.\n */\n readonly storeConfirmed: boolean;\n\n constructor(message: string, options: { readonly storeConfirmed?: boolean } = {}) {\n super(message);\n this.storeConfirmed = options.storeConfirmed ?? false;\n }\n}\n\n/** A handler did not settle within its configured timeout. Retried like any failure. */\nexport class HandlerTimeoutError extends RelayBusError {\n override name = 'HandlerTimeoutError';\n}\n\n/**\n * Reason of a handler's abort signal when the bus stops before the handler\n * finished. The delivery is released and runs again without losing an attempt.\n */\nexport class DispatcherStoppedError extends RelayBusError {\n override name = 'DispatcherStoppedError';\n}\n\nexport interface ValidationIssue {\n readonly message: string;\n readonly path?: readonly PropertyKey[] | undefined;\n}\n\n/** Serializable snapshot of an error, stored with failed deliveries. */\nexport interface ErrorInfo {\n readonly name: string;\n readonly message: string;\n readonly stack?: string | undefined;\n}\n\nexport function toErrorInfo(error: unknown): ErrorInfo {\n if (error instanceof Error) {\n return { name: error.name, message: error.message, stack: error.stack };\n }\n return { name: 'NonError', message: safeStringify(error) };\n}\n\nfunction safeStringify(value: unknown): string {\n if (typeof value === 'string') {\n return value;\n }\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n","import { ConfigurationError } from './errors.js';\n\n/**\n * A duration in milliseconds, or a string such as `'250ms'`, `'30s'`, `'5m'`,\n * `'1h'` or `'7d'`.\n */\nexport type Duration = number | `${number}${DurationUnit}`;\n\ntype DurationUnit = 'ms' | 's' | 'm' | 'h' | 'd';\n\nconst MILLISECONDS_PER_UNIT: Record<DurationUnit, number> = {\n ms: 1,\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n};\n\nconst DURATION_PATTERN = /^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d)$/;\n\nexport function toMilliseconds(value: Duration, name: string): number {\n if (typeof value === 'number') {\n if (!Number.isFinite(value) || value < 0) {\n throw new ConfigurationError(\n `${name} must be a non-negative finite number of milliseconds, received ${value}`,\n );\n }\n return value;\n }\n const match = DURATION_PATTERN.exec(value);\n if (match === null) {\n throw new ConfigurationError(\n `${name} must look like '500ms', '30s', '5m', '1h' or '7d', received '${value}'`,\n );\n }\n const [, amount, unit] = match as unknown as [string, string, DurationUnit];\n return Number(amount) * MILLISECONDS_PER_UNIT[unit];\n}\n\n/** Largest delay Node.js timers support. Longer values fire after 1ms instead. */\nexport const MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/** Converts a duration that drives a timer, rejecting zero and values timers cannot represent. */\nexport function toTimerMilliseconds(value: Duration, name: string): number {\n const milliseconds = toMilliseconds(value, name);\n if (milliseconds === 0) {\n throw new ConfigurationError(`${name} must be greater than zero`);\n }\n if (milliseconds > MAX_TIMER_DELAY_MS) {\n throw new ConfigurationError(\n `${name} must not exceed ${MAX_TIMER_DELAY_MS}ms (about 24.8 days), received ${milliseconds}ms`,\n );\n }\n return milliseconds;\n}\n","import { ConfigurationError, EventValidationError } from './errors.js';\nimport type { StandardSchemaV1 } from './standard-schema.js';\n\n/** String metadata carried with an event, such as `traceparent`. */\nexport type EventHeaders = Readonly<Record<string, string>>;\n\n/**\n * An event as stored and delivered. Field names follow CloudEvents where they\n * overlap (`id`, `type`, `source`, `time` as `occurredAt`, `subject` as `key`).\n */\nexport interface EventEnvelope<TPayload = unknown> {\n /** Globally unique id. Handlers and transports deduplicate on it. */\n readonly id: string;\n /** Event type, for example `order.created.v1`. */\n readonly type: string;\n /** Logical name of the publishing service. */\n readonly source: string;\n /** Ordering and partition key. Events sharing a key are handled in publish order. */\n readonly key: string | null;\n readonly payload: TPayload;\n readonly headers: EventHeaders;\n /** Id shared by every event of one business flow. */\n readonly correlationId: string | null;\n /** Id of the event whose handler published this one. */\n readonly causationId: string | null;\n readonly occurredAt: Date;\n}\n\n/** An instance of a class created with {@link defineEvent}. */\nexport interface DomainEvent<TPayload = unknown> {\n readonly type: string;\n readonly payload: TPayload;\n}\n\n/** A class created with {@link defineEvent}. */\nexport interface EventClass<TPayload = unknown> {\n new (payload: TPayload): DomainEvent<TPayload>;\n readonly type: string;\n readonly schema: StandardSchemaV1<unknown, TPayload> | undefined;\n}\n\n/** Payload type of an event class: `PayloadOf<typeof OrderPlaced>`. */\nexport type PayloadOf<TEvent> = TEvent extends EventClass<infer TPayload> ? TPayload : never;\n\n/** Anything that names an event type: an event class or the type string itself. */\nexport type EventReference = { readonly type: string } | string;\n\nexport interface DefineEventOptions<TSchema extends StandardSchemaV1> {\n /** Validates the payload on publish and before every handler call. */\n readonly schema: TSchema;\n}\n\nconst EVENT_TYPE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;\n\nexport function assertEventType(type: string): void {\n if (!EVENT_TYPE_PATTERN.test(type)) {\n throw new ConfigurationError(\n `Event type '${type}' must be 1-255 characters of letters, digits, '.', '_', ':', '/' or '-', starting with a letter or digit`,\n );\n }\n}\n\n/**\n * Defines an event type. Extend the returned class to name it:\n *\n * ```ts\n * export class OrderPlaced extends defineEvent<{ orderId: string }>('order.placed.v1') {}\n * export class OrderShipped extends defineEvent('order.shipped.v1', { schema: orderShippedSchema }) {}\n * ```\n */\nexport function defineEvent<TSchema extends StandardSchemaV1>(\n type: string,\n options: DefineEventOptions<TSchema>,\n): EventClass<StandardSchemaV1.InferOutput<TSchema>>;\nexport function defineEvent<TPayload>(type: string): EventClass<TPayload>;\nexport function defineEvent(\n type: string,\n options?: DefineEventOptions<StandardSchemaV1>,\n): EventClass<unknown> {\n assertEventType(type);\n const schema = options?.schema;\n return class DefinedEvent implements DomainEvent<unknown> {\n static readonly type = type;\n static readonly schema = schema;\n readonly type = type;\n constructor(readonly payload: unknown) {}\n };\n}\n\n/** Runs a Standard Schema and returns its output, or throws {@link EventValidationError}. */\nexport async function validatePayload<TPayload>(\n type: string,\n schema: StandardSchemaV1<unknown, TPayload> | undefined,\n payload: unknown,\n): Promise<TPayload> {\n if (schema === undefined) {\n return payload as TPayload;\n }\n const result = await schema['~standard'].validate(payload);\n if (result.issues !== undefined) {\n const issues = result.issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map((segment) => (typeof segment === 'object' ? segment.key : segment)),\n }));\n throw new EventValidationError(\n `Payload of '${type}' failed validation: ${issues.map((issue) => issue.message).join('; ')}`,\n issues,\n );\n }\n return result.value;\n}\n","import { ConfigurationError } from './errors.js';\nimport { assertEventType, type DomainEvent, type EventEnvelope, type PayloadOf } from './event.js';\nimport type { EventHandler, HandlerContext, SubscribeOptions } from './handler-registry.js';\nimport type { StandardSchemaV1 } from './standard-schema.js';\n\n/**\n * An event class as a catalog stores it: any class created with `defineEvent`,\n * whatever its payload type. Use {@link PayloadOf} to recover the payload.\n */\nexport interface CatalogEventClass {\n new (payload: never): DomainEvent;\n readonly type: string;\n readonly schema: StandardSchemaV1 | undefined;\n}\n\n/**\n * The shape of a catalog: event classes by name. Create one with\n * {@link defineCatalog}; the name of each entry becomes part of the handler\n * method that consumes it (`OrderPlaced` is consumed by `onOrderPlaced`).\n */\nexport interface Catalog {\n readonly [eventName: string]: CatalogEventClass;\n}\n\n/** Names of the events of a catalog, as string literals. */\nexport type CatalogEventName<TCatalog extends Catalog> = Extract<keyof TCatalog, string>;\n\n/**\n * Union of the event instances a catalog can publish, for example\n * `OrderPlaced | OrderShipped`; with `TName`, only those of the named events.\n */\nexport type CatalogEvents<\n TCatalog extends Catalog,\n TName extends keyof TCatalog = keyof TCatalog,\n> = InstanceType<TCatalog[TName & CatalogEventName<TCatalog>]>;\n\n/**\n * Envelope a handler receives for an event class:\n * `EventOf<typeof OrderPlaced>` is `EventEnvelope<{ orderId: string }>`.\n */\nexport type EventOf<TEvent> = EventEnvelope<PayloadOf<TEvent>>;\n\n/**\n * Same as {@link HandlersOf} with a required list of events:\n * `PartialHandlersOf<typeof OrderEvents, 'OrderPlaced'>` equals\n * `HandlersOf<typeof OrderEvents, 'OrderPlaced'>`.\n *\n * ```ts\n * class AuditHandlers implements PartialHandlersOf<typeof OrderEvents, 'OrderPlaced'> {\n * onOrderPlaced(event: EventOf<typeof OrderPlaced>) {}\n * }\n * ```\n */\nexport type PartialHandlersOf<\n TCatalog extends Catalog,\n TName extends keyof TCatalog,\n TTransaction = unknown,\n> = {\n readonly [TKey in TName & string as `on${TKey}`]: (\n event: EventOf<TCatalog[TKey]>,\n context: HandlerContext<TTransaction>,\n ) => unknown;\n};\n\n/**\n * Handler methods for the events of a catalog: one `on${EventName}` method per\n * event, taking that event's envelope. A class that\n * `implements HandlersOf<typeof OrderEvents>` fails to compile until it has a\n * method with the right payload type for each event. `TName` narrows it to the\n * events a service consumes, which is how a service handles part of a catalog\n * shared between services:\n *\n * ```ts\n * class BillingHandlers implements HandlersOf<typeof OrderEvents, 'OrderPlaced'> {\n * onOrderPlaced(event: EventOf<typeof OrderPlaced>) {}\n * }\n * ```\n *\n * `TTransaction` types `context.transaction` for transactional handlers.\n */\nexport type HandlersOf<\n TCatalog extends Catalog,\n TName extends keyof TCatalog = keyof TCatalog,\n TTransaction = unknown,\n> = PartialHandlersOf<TCatalog, TName, TTransaction>;\n\n/**\n * Names of catalog events that an API call is limited to. Every name must be a\n * key of the catalog, which the compiler checks; duplicates and an empty list\n * are rejected at runtime with a {@link ConfigurationError}. Omitting the list\n * means every event of the catalog.\n */\nexport interface CatalogEventSelection<TName> {\n readonly events?: readonly TName[];\n}\n\n/** Options of {@link defineCatalog}. */\nexport interface DefineCatalogOptions {\n /**\n * Name of the catalog, used in boot-check messages and as the default prefix\n * of the handler ids that `subscribeCatalog` registers.\n */\n readonly name?: string;\n}\n\n/**\n * Options of `RelayBus.subscribeCatalog`: {@link SubscribeOptions} for every\n * handler of the catalog, and optionally the events to subscribe to. The plain\n * `SubscribeCatalogOptions`, without a catalog, names no events, so it fits\n * every catalog.\n */\nexport type SubscribeCatalogOptions<\n TCatalog extends Catalog = Catalog,\n TName extends keyof TCatalog = string extends keyof TCatalog ? never : keyof TCatalog,\n> = Omit<SubscribeOptions, 'id'> &\n CatalogEventSelection<TName> & {\n /**\n * Prefix of the handler ids, which become `${idPrefix}.on${EventName}`.\n * Default: the catalog name, then the class name of the handlers object.\n * Deliveries are recorded under these ids, so renaming them orphans pending\n * deliveries.\n */\n readonly idPrefix?: string;\n };\n\n/** One event of a catalog together with the handler method that consumes it. */\nexport interface CatalogEntry {\n /** Name under which the class was registered, for example `OrderPlaced`. */\n readonly name: string;\n readonly eventClass: CatalogEventClass;\n /** Event type string, for example `order.placed.v1`. */\n readonly type: string;\n /** Expected handler method, for example `onOrderPlaced`. */\n readonly handlerName: string;\n}\n\n/** What {@link describeCatalog} knows about a catalog. */\nexport interface CatalogDescription {\n readonly name: string | undefined;\n readonly entries: readonly CatalogEntry[];\n}\n\n/** A handler registration derived from a catalog by {@link resolveCatalogHandlers}. */\nexport interface CatalogHandlerBinding {\n readonly eventClass: CatalogEventClass;\n readonly handle: EventHandler;\n readonly options: SubscribeOptions;\n}\n\n// Letters, digits and underscores: the name becomes part of a method name and of\n// handler ids, which do not accept `$`.\nconst EVENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nconst descriptions = new WeakMap<object, CatalogDescription>();\n\n/**\n * Groups event classes into a catalog: the complete set of events one service\n * or domain owns. The catalog is frozen and keeps its keys and classes in its\n * type, which enables compile-time checks:\n *\n * ```ts\n * export const OrderEvents = defineCatalog({ OrderPlaced, OrderShipped }, { name: 'OrderEvents' });\n *\n * class ShippingHandlers implements HandlersOf<typeof OrderEvents> {\n * onOrderPlaced(event: EventOf<typeof OrderPlaced>) {}\n * // Compile error until onOrderShipped is added.\n * }\n * ```\n *\n * Throws {@link ConfigurationError} for an empty catalog, an entry that is not\n * an event class, a name that is not made of letters, digits and underscores,\n * or two entries with the same event type.\n */\nexport function defineCatalog<const TCatalog extends Catalog>(\n events: TCatalog,\n options: DefineCatalogOptions = {},\n): Readonly<TCatalog> {\n const label = options.name === undefined ? 'Catalog' : `Catalog '${options.name}'`;\n const names = Object.keys(events);\n if (names.length === 0) {\n throw new ConfigurationError(`${label} must contain at least one event`);\n }\n const owners = new Map<string, string>();\n const entries = names.map((name): CatalogEntry => {\n const eventClass = events[name] as CatalogEventClass;\n if (!EVENT_NAME_PATTERN.test(name)) {\n throw new ConfigurationError(\n `${label} entry '${name}' must be a valid identifier made of letters, digits and underscores ` +\n `because it names the handler method on${name} and its handler id`,\n );\n }\n if (typeof eventClass !== 'function' || typeof eventClass.type !== 'string') {\n throw new ConfigurationError(\n `${label} entry '${name}' must be an event class created with defineEvent`,\n );\n }\n assertEventType(eventClass.type);\n const owner = owners.get(eventClass.type);\n if (owner !== undefined) {\n throw new ConfigurationError(\n `${label} entries '${owner}' and '${name}' share the event type '${eventClass.type}'`,\n );\n }\n owners.set(eventClass.type, name);\n return Object.freeze({ name, eventClass, type: eventClass.type, handlerName: `on${name}` });\n });\n const catalog = Object.freeze({ ...events });\n descriptions.set(catalog, Object.freeze({ name: options.name, entries: Object.freeze(entries) }));\n return catalog;\n}\n\n/**\n * Describes a catalog created by {@link defineCatalog}. The description and its\n * entries are frozen. Throws {@link ConfigurationError} for any other object,\n * so a hand-written record cannot slip past the checks that rely on it.\n */\nexport function describeCatalog(catalog: Catalog): CatalogDescription {\n const description = descriptions.get(catalog);\n if (description === undefined) {\n throw new ConfigurationError('Expected a catalog created with defineCatalog');\n }\n return description;\n}\n\n/** How messages name a catalog: `catalog 'OrderEvents'`, or `the catalog` when it has no name. */\nexport function catalogLabel(catalog: Catalog): string {\n const { name } = describeCatalog(catalog);\n return name === undefined ? 'the catalog' : `catalog '${name}'`;\n}\n\n/**\n * Resolves the event names of a {@link CatalogEventSelection} to their catalog\n * entries, in catalog order; every entry when `events` is undefined. Throws\n * {@link ConfigurationError} for an empty list, a name the catalog does not\n * have, or a name listed twice.\n */\nexport function selectCatalogEntries(\n catalog: Catalog,\n events: readonly PropertyKey[] | undefined,\n): readonly CatalogEntry[] {\n const { entries } = describeCatalog(catalog);\n if (events === undefined) {\n return entries;\n }\n const label = catalogLabel(catalog);\n if (events.length === 0) {\n throw new ConfigurationError(\n `The events selected from ${label} must name at least one event; omit events to select all of them`,\n );\n }\n const selected = new Set<PropertyKey>();\n for (const event of events) {\n if (!entries.some((entry) => entry.name === event)) {\n throw new ConfigurationError(\n `${capitalize(label)} has no event named '${String(event)}'; its events are ${entries\n .map((entry) => entry.name)\n .join(', ')}`,\n );\n }\n if (selected.has(event)) {\n throw new ConfigurationError(`Event '${String(event)}' of ${label} is selected twice`);\n }\n selected.add(event);\n }\n return entries.filter((entry) => selected.has(entry.name));\n}\n\nfunction capitalize(text: string): string {\n return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;\n}\n\n/**\n * Returns the entry of `catalog` that `event` belongs to, matched by event type\n * so duplicate package copies still work. Throws {@link ConfigurationError}\n * when the event is not part of the catalog.\n */\nexport function requireCatalogEntry(catalog: Catalog, event: DomainEvent): CatalogEntry {\n const entry = describeCatalog(catalog).entries.find((candidate) => candidate.type === event.type);\n if (entry === undefined) {\n throw new ConfigurationError(\n `Event type '${String(event.type)}' is not part of ${catalogLabel(catalog)}`,\n );\n }\n return entry;\n}\n\n/**\n * Maps the `on${EventName}` methods of `handlers` to registrations with the\n * stable ids `${prefix}.on${EventName}`, for the events selected by\n * `options.events` (default: all). Methods of events that are not selected are\n * ignored. Throws {@link ConfigurationError} listing every missing method, or\n * when no prefix can be derived.\n */\nexport function resolveCatalogHandlers<TCatalog extends Catalog, TName extends keyof TCatalog>(\n catalog: TCatalog,\n handlers: object,\n options: SubscribeCatalogOptions<TCatalog, TName>,\n): CatalogHandlerBinding[] {\n const { name } = describeCatalog(catalog);\n const { idPrefix, events, ...subscribeOptions } = options;\n const entries = selectCatalogEntries(catalog, events);\n const lookup = handlers as Record<string, unknown>;\n const missing = entries.filter((entry) => typeof lookup[entry.handlerName] !== 'function');\n if (missing.length > 0) {\n throw new ConfigurationError(\n `Handlers for catalog ${name === undefined ? 'events' : `'${name}'`} lack methods: ${missing\n .map((entry) => entry.handlerName)\n .join(', ')}`,\n );\n }\n const prefix = idPrefix ?? name ?? classNameOf(handlers);\n if (prefix === undefined) {\n throw new ConfigurationError(\n 'Cannot derive handler ids: name the catalog, pass an idPrefix or use a class instance as handlers',\n );\n }\n return entries.map((entry) => {\n const method = lookup[entry.handlerName] as EventHandler;\n return {\n eventClass: entry.eventClass,\n handle: (envelope, context) => method.call(handlers, envelope, context),\n options: { ...subscribeOptions, id: `${prefix}.${entry.handlerName}` },\n };\n });\n}\n\nfunction classNameOf(handlers: object): string | undefined {\n const className = handlers.constructor.name;\n return className === 'Object' || className === '' ? undefined : className;\n}\n\n/**\n * Checks an object passed to {@link defineHandlers} against the selected\n * entries of its catalog: every `on${EventName}` method present, nothing else,\n * all functions.\n */\nfunction assertExactHandlers(\n catalog: Catalog,\n entries: readonly CatalogEntry[],\n handlers: object,\n): void {\n const expected = new Set(entries.map((entry) => entry.handlerName));\n const present = Object.keys(handlers);\n const missing = [...expected].filter((handlerName) => !present.includes(handlerName));\n const extra = present.filter((key) => !expected.has(key));\n const notFunctions = present.filter(\n (key) => expected.has(key) && typeof (handlers as Record<string, unknown>)[key] !== 'function',\n );\n if (missing.length + extra.length + notFunctions.length > 0) {\n const problems = [\n ...missing.map((key) => `missing ${key}`),\n ...extra.map((key) => `unexpected ${key}`),\n ...notFunctions.map((key) => `${key} is not a function`),\n ];\n throw new ConfigurationError(\n `Handlers do not match ${catalogLabel(catalog)}: ${problems.join(', ')}`,\n );\n }\n}\n\n/**\n * The handler signature of one catalog event, written as a method so that its\n * parameters are compared bivariantly: a handler may annotate its context as\n * `HandlerContext<PoolClient>` and still satisfy it. {@link MatchingHandlers}\n * restores the strict check of the event parameter.\n */\ntype BivariantHandler<TEvent> = {\n handle(event: EventOf<TEvent>, context: HandlerContext): unknown;\n}['handle'];\n\n/**\n * The shape {@link defineHandlers} constrains its handlers to: one method per\n * selected event, with the context typed loosely enough for any transaction type.\n */\nexport type HandlerShapeOf<TCatalog extends Catalog, TName extends keyof TCatalog> = {\n readonly [TKey in TName & string as `on${TKey}`]: BivariantHandler<TCatalog[TKey]>;\n};\n\n/**\n * Checks every key of `THandlers` against the selected events of a catalog:\n * keys that are no handler of a selected event become `never`, and a handler\n * whose event parameter does not accept the event's envelope becomes the\n * expected signature, so the compiler reports the mismatch at that key.\n */\nexport type MatchingHandlers<TCatalog extends Catalog, TName extends keyof TCatalog, THandlers> = {\n readonly [TKey in keyof THandlers]: TKey extends `on${infer TEventName extends TName & string}`\n ? THandlers[TKey] extends (event: infer TEvent, ...rest: never[]) => unknown\n ? EventOf<TCatalog[TEventName]> extends TEvent\n ? THandlers[TKey]\n : (event: EventOf<TCatalog[TEventName]>, context: HandlerContext) => unknown\n : (event: EventOf<TCatalog[TEventName]>, context: HandlerContext) => unknown\n : never;\n};\n\n/**\n * Declares the handlers of a catalog as an object: every event, or the events\n * named in `options.events`. Compilation fails when a handler is missing,\n * misnamed, extra (including a handler of an event that is not selected) or\n * takes the wrong payload; the same checks run at runtime for callers without\n * type checking. A handler may type its context with a transaction type, for\n * example `HandlerContext<PoolClient>`.\n *\n * ```ts\n * const handlers = defineHandlers(OrderEvents, {\n * onOrderPlaced: (event) => reserveStock(event.payload.orderId),\n * onOrderShipped: (event) => notify(event.payload.orderId),\n * });\n * bus.subscribeCatalog(OrderEvents, handlers, { idPrefix: 'fulfilment' });\n *\n * const billing = defineHandlers(\n * OrderEvents,\n * { onOrderPlaced: (event) => charge(event.payload.orderId) },\n * { events: ['OrderPlaced'] },\n * );\n * bus.subscribeCatalog(OrderEvents, billing, { events: ['OrderPlaced'] });\n * ```\n */\nexport function defineHandlers<\n TCatalog extends Catalog,\n THandlers extends HandlerShapeOf<TCatalog, TName>,\n const TName extends keyof TCatalog,\n>(\n catalog: TCatalog,\n handlers: THandlers & MatchingHandlers<TCatalog, TName, THandlers>,\n options: { readonly events: readonly TName[] },\n): THandlers;\n/** Without `events`, every handler of the catalog is required. */\nexport function defineHandlers<\n TCatalog extends Catalog,\n THandlers extends HandlerShapeOf<TCatalog, keyof TCatalog>,\n>(\n catalog: TCatalog,\n handlers: THandlers & MatchingHandlers<TCatalog, keyof TCatalog, THandlers>,\n options?: { readonly events?: undefined },\n): THandlers;\nexport function defineHandlers(\n catalog: Catalog,\n handlers: object,\n options: { readonly events?: readonly PropertyKey[] | undefined } = {},\n): object {\n assertExactHandlers(catalog, selectCatalogEntries(catalog, options.events), handlers);\n return handlers;\n}\n\n/**\n * Maps every key of `THandlers` that is not a handler of the selected events\n * of the catalog (default: all of them) to `never`.\n */\nexport type NoExtraHandlers<\n TCatalog extends Catalog,\n THandlers,\n TName extends keyof TCatalog = keyof TCatalog,\n> = {\n readonly [TKey in Exclude<keyof THandlers, keyof HandlersOf<TCatalog, TName>>]: never;\n};\n","import {\n requireCatalogEntry,\n catalogLabel,\n selectCatalogEntries,\n type Catalog,\n type CatalogEntry,\n type CatalogEventSelection,\n type CatalogEvents,\n} from './catalog.js';\nimport { ConfigurationError } from './errors.js';\nimport type { DomainEvent, EventEnvelope } from './event.js';\nimport type { PublishOneOptions, PublishOptions } from './relay-bus.js';\n\n/** The publishing half of a bus, which a {@link CatalogPublisher} delegates to. */\nexport interface PublishTarget<TTransaction> {\n publish<TPayload>(\n event: DomainEvent<TPayload>,\n options?: PublishOneOptions<TTransaction>,\n ): Promise<EventEnvelope<TPayload>>;\n publishAll(\n events: readonly DomainEvent[],\n options?: PublishOptions<TTransaction>,\n ): Promise<EventEnvelope[]>;\n}\n\n/**\n * A view of a bus that publishes only the events of one catalog, or only the\n * events a service produces from it. Obtain it with `bus.forCatalog(catalog)`\n * or `bus.forCatalog(catalog, { events: ['OrderPlaced'] })`. Publishing an\n * event outside the view fails to compile; a mistyped event that gets past the\n * compiler (a cast, plain JavaScript, or a class with a structurally identical\n * payload) is rejected with a {@link ConfigurationError} before anything is stored.\n *\n * ```ts\n * const orders = bus.forCatalog(OrderEvents);\n * await orders.publish(new OrderPlaced({ orderId }));\n * await orders.publish(new UserRegistered({ userId })); // compile error\n * ```\n */\nexport class CatalogPublisher<\n TCatalog extends Catalog,\n TTransaction = unknown,\n TName extends keyof TCatalog = keyof TCatalog,\n> {\n readonly #catalog: TCatalog;\n readonly #target: PublishTarget<TTransaction>;\n readonly #entries: readonly CatalogEntry[];\n /**\n * Whether the view publishes the event named `eventName`. Its parameter\n * makes a view of some events unassignable to a view of more events, which\n * the bivariant method parameters alone would allow.\n */\n readonly #publishes: (eventName: TName) => boolean;\n\n /**\n * Throws {@link ConfigurationError} when `catalog` was not created with\n * `defineCatalog` or `options.events` names no event, an unknown event or\n * the same event twice.\n */\n constructor(\n catalog: TCatalog,\n target: PublishTarget<TTransaction>,\n options: CatalogEventSelection<TName> = {},\n ) {\n this.#entries = selectCatalogEntries(catalog, options.events);\n const names = new Set<PropertyKey>(this.#entries.map((entry) => entry.name));\n this.#publishes = (eventName) => names.has(eventName);\n this.#catalog = catalog;\n this.#target = target;\n }\n\n /** Same as `bus.publish`, limited to the events of the view. */\n async publish<TEvent extends CatalogEvents<TCatalog, TName>>(\n event: TEvent,\n options?: PublishOneOptions<TTransaction>,\n ): Promise<EventEnvelope<TEvent['payload']>> {\n this.#assertPublishable(event);\n return this.#target.publish(event, options);\n }\n\n /** Same as `bus.publishAll`, limited to the events of the view. Nothing is stored unless every event belongs to it. */\n async publishAll(\n events: readonly CatalogEvents<TCatalog, TName>[],\n options?: PublishOptions<TTransaction>,\n ): Promise<EventEnvelope[]> {\n for (const event of events) {\n this.#assertPublishable(event);\n }\n return this.#target.publishAll(events, options);\n }\n\n #assertPublishable(event: DomainEvent): void {\n const { name } = requireCatalogEntry(this.#catalog, event);\n if (!this.#publishes(name as TName)) {\n throw new ConfigurationError(\n `Event type '${event.type}' is not one of the events this view of ${catalogLabel(\n this.#catalog,\n )} publishes (${this.#entries.map((entry) => entry.name).join(', ')})`,\n );\n }\n }\n}\n","import {\n describeCatalog,\n selectCatalogEntries,\n type Catalog,\n type CatalogEntry,\n type CatalogEventSelection,\n} from './catalog.js';\nimport { ConfigurationError } from './errors.js';\n\n/**\n * What a service does with the events of a catalog:\n * - `consume`: it handles them, so each needs a local handler.\n * - `produce`: it publishes them for other services, so each needs a route to a transport.\n */\nexport type CatalogRole = 'consume' | 'produce';\n\n/**\n * The part of a catalog that one service consumes or produces, created with\n * {@link consume} or {@link produce} and passed to the `catalogs` option of the\n * bus (or `bus.registerCatalog`). `start()` then verifies the role for each\n * declared event.\n */\nexport interface CatalogDeclaration<\n TCatalog extends Catalog = Catalog,\n TName extends keyof TCatalog = keyof TCatalog,\n> {\n readonly catalog: TCatalog;\n readonly role: CatalogRole;\n /** Names of the declared events, in catalog order. */\n readonly events: readonly Extract<TName, string>[];\n /** The declared events with their types and handler methods, in catalog order. */\n readonly entries: readonly CatalogEntry[];\n}\n\n/** What `start()` requires of a catalog event. */\ntype CoverageNeed = 'handler' | 'route' | 'handler-or-route';\n\n/** One catalog, or one role of a catalog, that `start()` checks. */\nexport interface CatalogRequirement {\n readonly catalogName: string | undefined;\n readonly entries: readonly CatalogEntry[];\n readonly need: CoverageNeed;\n}\n\n/** How many local handlers and transport routes this process has for an event type. */\nexport interface EventTypeRegistrations {\n readonly handlers: number;\n readonly routes: number;\n}\n\nconst declarations = new WeakSet<object>();\n\n/**\n * Declares that this service consumes events of a catalog, typically one\n * shared between services through a contracts package. `start()` fails unless\n * every declared event has a local handler (`subscribeCatalog`, `subscribe`,\n * `@EventConsumer`, `@Subscribe`); a route to a transport does not count.\n * Without `events`, every event of the catalog is declared. Unknown names do\n * not compile and are rejected at runtime with a {@link ConfigurationError}.\n *\n * ```ts\n * new RelayBus({ store, catalogs: [consume(OrderEvents, { events: ['OrderPlaced'] })] });\n * ```\n */\nexport function consume<\n TCatalog extends Catalog,\n const TName extends keyof TCatalog = keyof TCatalog,\n>(\n catalog: TCatalog,\n options: CatalogEventSelection<TName> = {},\n): CatalogDeclaration<TCatalog, TName> {\n return declare(catalog, 'consume', options);\n}\n\n/**\n * Declares that this service publishes events of a catalog for other services.\n * `start()` fails unless every declared event has a route to a transport, so\n * nothing is published without a destination; a local handler does not count.\n * Combine it with {@link consume} for events the service also handles itself.\n * Without `events`, every event of the catalog is declared.\n *\n * ```ts\n * new RelayBus({\n * store,\n * transports: [kafka],\n * routes: [{ event: OrderPlaced, transport: 'kafka', destination: 'orders' }],\n * catalogs: [produce(OrderEvents, { events: ['OrderPlaced'] })],\n * });\n * ```\n */\nexport function produce<\n TCatalog extends Catalog,\n const TName extends keyof TCatalog = keyof TCatalog,\n>(\n catalog: TCatalog,\n options: CatalogEventSelection<TName> = {},\n): CatalogDeclaration<TCatalog, TName> {\n return declare(catalog, 'produce', options);\n}\n\nfunction declare<TCatalog extends Catalog, TName extends keyof TCatalog>(\n catalog: TCatalog,\n role: CatalogRole,\n options: CatalogEventSelection<TName>,\n): CatalogDeclaration<TCatalog, TName> {\n const entries = selectCatalogEntries(catalog, options.events);\n const declaration = Object.freeze({\n catalog,\n role,\n events: Object.freeze(entries.map((entry) => entry.name as Extract<TName, string>)),\n entries,\n });\n declarations.add(declaration);\n return declaration;\n}\n\n/**\n * Turns an entry of the `catalogs` option into what `start()` checks. A bare\n * catalog requires a handler or a route for every event; a declaration\n * requires a handler (consume) or a route (produce) for its events. Throws\n * {@link ConfigurationError} for anything that is neither.\n */\nexport function toCatalogRequirement(value: Catalog | CatalogDeclaration): CatalogRequirement {\n if (declarations.has(value)) {\n const declaration = value as CatalogDeclaration;\n return {\n catalogName: describeCatalog(declaration.catalog).name,\n entries: declaration.entries,\n need: declaration.role === 'consume' ? 'handler' : 'route',\n };\n }\n const { name, entries } = describeCatalog(value as Catalog);\n return { catalogName: name, entries, need: 'handler-or-route' };\n}\n\n/**\n * Throws {@link ConfigurationError} listing, per event, what a requirement\n * lacks: the handler method a consumed event needs, the route a produced event\n * needs, or, for a bare catalog, any handler or route.\n */\nexport function assertCatalogsCovered(\n requirements: Iterable<CatalogRequirement>,\n registrationsOf: (eventType: string) => EventTypeRegistrations,\n): void {\n const problems = new Set<string>();\n let onlyBareCatalogs = true;\n for (const { catalogName, entries, need } of requirements) {\n for (const entry of entries) {\n const problem = describeGap(entry, need, registrationsOf(entry.type));\n if (problem !== undefined) {\n problems.add(`${catalogName === undefined ? '' : `${catalogName}.`}${problem}`);\n onlyBareCatalogs &&= need === 'handler-or-route';\n }\n }\n }\n if (problems.size > 0) {\n const heading = onlyBareCatalogs\n ? 'Catalog events without a handler or route:'\n : 'Catalog events this service does not cover:';\n throw new ConfigurationError(\n `${heading}\\n${[...problems].map((line) => ` - ${line}`).join('\\n')}`,\n );\n }\n}\n\nfunction describeGap(\n entry: CatalogEntry,\n need: CoverageNeed,\n { handlers, routes }: EventTypeRegistrations,\n): string | undefined {\n const subject = `${entry.name} (${entry.type})`;\n if (need === 'handler-or-route') {\n return handlers + routes > 0\n ? undefined\n : `${subject}: expected handler method ${entry.handlerName}`;\n }\n if (need === 'handler') {\n if (handlers > 0) {\n return undefined;\n }\n const routeNote = routes > 0 ? '; its route to a transport does not handle it here' : '';\n return `${subject}: consumed here, needs handler method ${entry.handlerName}${routeNote}`;\n }\n if (routes > 0) {\n return undefined;\n }\n const handlerNote = handlers > 0 ? '; a local handler does not deliver it to other services' : '';\n return `${subject}: produced here, needs a route to a transport${handlerNote}`;\n}\n","import type { ErrorInfo } from './errors.js';\nimport type { EventEnvelope } from './event.js';\n\n/**\n * Lifecycle of one handler's delivery of one event.\n * `pending` (waiting or scheduled for retry) -> `processing` (leased by a worker)\n * -> `completed` | `pending` (retry) | `dead` (exhausted or non-retryable).\n * `dead` -> `pending` only through an explicit requeue.\n *\n * A completed delivery is deleted. `completed` records exist only in stores\n * configured to keep a completion history (`retainCompleted` /\n * `completionHistory`), where they are listed, counted and purged like before.\n */\nexport type DeliveryStatus = 'pending' | 'processing' | 'completed' | 'dead';\n\nexport const DELIVERY_STATUSES: readonly DeliveryStatus[] = [\n 'pending',\n 'processing',\n 'completed',\n 'dead',\n];\n\nexport interface NewDelivery {\n readonly id: string;\n /** Stable handler id. Together with the event id it is unique. */\n readonly handler: string;\n readonly availableAt: Date;\n}\n\nexport interface AppendEntry {\n readonly event: EventEnvelope;\n readonly deliveries: readonly NewDelivery[];\n}\n\nexport interface AppendResult {\n /** Events written by this call. */\n readonly appendedEventIds: readonly string[];\n /** Events that already existed. Their missing deliveries were still added. */\n readonly duplicateEventIds: readonly string[];\n /** Deliveries written by this call. Existing (event, handler) pairs are skipped. */\n readonly appendedDeliveryCount: number;\n}\n\n/**\n * Lease expiry is compared with the `now` the caller passes, taken from the\n * bus clock. Keep worker clocks synchronized (NTP): a skew larger than a third\n * of the lease duration lets another worker reclaim a delivery that is still running.\n *\n * Stores may grant the lease on a group of deliveries (a lane) instead of on\n * each delivery. The group is exclusive to `leaseOwner` while the lease is\n * live, so other owners do not see its pending deliveries until it expires or\n * is relinquished; every delivery of the group carries the group's fencing token.\n */\nexport interface ClaimRequest {\n /** Only deliveries of these handlers are claimed. */\n readonly handlers: readonly string[];\n readonly limit: number;\n readonly leaseOwner: string;\n readonly leaseExpiresAt: Date;\n readonly now: Date;\n}\n\n/**\n * Proof of ownership. Every state change after a claim must present it\n * (fencing). A lease stays valid until another claim replaces it, even after\n * its expiry time; expiry only makes the delivery claimable again.\n */\nexport interface LeaseReference {\n readonly deliveryId: string;\n readonly leaseToken: string;\n}\n\nexport interface ClaimedDelivery extends LeaseReference {\n readonly handler: string;\n /** Attempt number of this claim, starting at 1. */\n readonly attempt: number;\n readonly leaseExpiresAt: Date;\n readonly event: EventEnvelope;\n}\n\nexport interface DeliveryRecord {\n readonly id: string;\n readonly handler: string;\n readonly status: DeliveryStatus;\n readonly attempts: number;\n readonly availableAt: Date;\n readonly leaseOwner: string | null;\n readonly leaseExpiresAt: Date | null;\n readonly lastError: ErrorInfo | null;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly completedAt: Date | null;\n readonly event: EventEnvelope;\n}\n\nexport interface DeliveryQuery {\n readonly status?: DeliveryStatus;\n readonly handler?: string;\n readonly eventType?: string;\n readonly eventId?: string;\n /** Default 100. */\n readonly limit?: number;\n}\n\nexport interface PurgeRequest {\n /** Delete completed deliveries completed before this instant. */\n readonly completedBefore?: Date;\n /** Delete dead deliveries last updated before this instant. */\n readonly deadBefore?: Date;\n}\n\nexport interface PurgeResult {\n readonly deletedDeliveries: number;\n /** Events deleted because no delivery referenced them any more. */\n readonly deletedEvents: number;\n}\n\nexport interface EventStoreStatistics {\n readonly pending: number;\n readonly processing: number;\n readonly completed: number;\n readonly dead: number;\n /** `availableAt` of the oldest delivery that is due but not yet processed. */\n readonly oldestDueAt: Date | null;\n}\n\n/**\n * Storage port. Implementations persist events and deliveries in the same\n * database as the application's business data so that both commit atomically.\n *\n * Every implementation must pass the contract suite in `@relaybus/testing`.\n */\nexport interface EventStore<TTransaction = unknown> {\n /** Creates tables, collections and indexes when they do not exist. */\n setup?(): Promise<void>;\n /** Runs `work` inside a new database transaction and commits when it resolves. */\n transaction<T>(work: (transaction: TTransaction) => Promise<T>): Promise<T>;\n /**\n * Writes events and their deliveries inside `transaction`. Idempotent on\n * event id and on (event id, handler). Assigns a per-key sequence to keyed\n * events in commit order.\n */\n append(\n transaction: TTransaction,\n entries: readonly AppendEntry[],\n now: Date,\n ): Promise<AppendResult>;\n /**\n * Leases up to `limit` deliveries that are due: pending with `availableAt <= now`,\n * or processing with an expired lease. A keyed delivery is only claimable when\n * no earlier delivery of the same handler and key is pending or processing.\n * Counts the attempt (`attempt` of the result; a store may persist the count\n * only when the attempt fails or its lease is lost). Safe to call from many\n * processes at once.\n */\n claim(request: ClaimRequest): Promise<ClaimedDelivery[]>;\n /** Extends a lease the caller still holds. Returns false when the lease was lost. */\n extendLease(lease: LeaseReference, leaseExpiresAt: Date, now: Date): Promise<boolean>;\n /**\n * Marks a leased delivery completed by deleting it (or moving it to the\n * completion history, when the store keeps one). With `transaction` the change\n * commits together with the handler's own writes. Returns false when the lease\n * was lost.\n */\n complete(lease: LeaseReference, now: Date, transaction?: TTransaction): Promise<boolean>;\n /** Returns a leased delivery to pending, due at `availableAt`. */\n reschedule(\n lease: LeaseReference,\n availableAt: Date,\n error: ErrorInfo,\n now: Date,\n ): Promise<boolean>;\n /**\n * Gives a leased delivery back without counting the attempt: pending, due\n * now, attempts decremented. Used when a handler is aborted at shutdown.\n */\n release(lease: LeaseReference, now: Date): Promise<boolean>;\n /**\n * Marks many leased deliveries completed with one round trip. Returns, for\n * every lease in the same order, whether it was completed (false: lease lost\n * or already finished). Each lease is fenced individually, exactly as in\n * {@link EventStore.complete}. Optional: the dispatcher falls back to\n * `complete` when a store does not implement it.\n */\n completeMany?(leases: readonly LeaseReference[], now: Date): Promise<boolean[]>;\n /** Moves a leased delivery to dead. */\n bury(lease: LeaseReference, error: ErrorInfo, now: Date): Promise<boolean>;\n listDeliveries(query: DeliveryQuery): Promise<DeliveryRecord[]>;\n /** Moves dead deliveries back to pending with a fresh attempt budget. Returns how many moved. */\n requeue(deliveryIds: readonly string[], now: Date): Promise<number>;\n purge(request: PurgeRequest): Promise<PurgeResult>;\n statistics(now: Date): Promise<EventStoreStatistics>;\n /**\n * Hands back every lease group that `leaseOwner` holds without running work,\n * so other workers can take them at once instead of after lease expiry.\n * Called at graceful shutdown after the owner's deliveries settled. Groups\n * with running deliveries stay leased. Optional.\n */\n relinquish?(leaseOwner: string, now: Date): Promise<void>;\n /**\n * Calls `listener` soon after a transaction that added deliveries due at once has committed, in this\n * process or in any other one, so an idle dispatcher claims them without waiting for its next poll.\n * A hint, never a guarantee: a report may be late, merged with others, or lost (while a connection\n * is re-established, for instance), and polling still finds every delivery. Resolves with a function\n * that stops listening, or with `undefined` when this store cannot listen. Optional.\n */\n watchNewDeliveries?(listener: () => void): Promise<(() => Promise<void>) | undefined>;\n /** Releases connections the store opened itself. */\n close?(): Promise<void>;\n}\n","import { randomBytes } from 'node:crypto';\n\n/**\n * RFC 9562 UUID version 7: 48-bit Unix millisecond timestamp followed by random\n * bits. Time-ordered, so it keeps B-tree indexes compact, and globally unique,\n * so it is safe as an idempotency key across services.\n */\nexport function createUuidV7(timestamp: number = Date.now()): string {\n const bytes = randomBytes(16);\n let remaining = timestamp;\n for (let index = 5; index >= 0; index -= 1) {\n bytes[index] = remaining % 256;\n remaining = Math.floor(remaining / 256);\n }\n bytes[6] = (bytes[6]! & 0x0f) | 0x70;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = bytes.toString('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/** Produces unique identifiers for events, deliveries and lease tokens. */\nexport type IdentifierGenerator = () => string;\n","import { ConfigurationError, type ErrorInfo } from './errors.js';\nimport type { EventEnvelope } from './event.js';\nimport type {\n AppendEntry,\n AppendResult,\n ClaimRequest,\n ClaimedDelivery,\n DeliveryQuery,\n DeliveryRecord,\n DeliveryStatus,\n EventStore,\n EventStoreStatistics,\n LeaseReference,\n PurgeRequest,\n PurgeResult,\n} from './event-store.js';\nimport { createUuidV7, type IdentifierGenerator } from './identifier.js';\n\nexport interface InMemoryEventStoreOptions {\n /** Allow use when `NODE_ENV` is `production`. Data is lost on restart. Default false. */\n readonly allowInProduction?: boolean;\n readonly generateIdentifier?: IdentifierGenerator;\n /**\n * Keep a record of completed deliveries (status `completed`, listed, counted\n * and purged by `retention.completed`). Default false: a completed delivery\n * is deleted, like in the database stores.\n */\n readonly retainCompleted?: boolean;\n}\n\n/** Transaction handle of {@link InMemoryEventStore}. Writes apply on commit only. */\nexport class InMemoryTransaction {\n readonly #operations: Array<() => void> = [];\n readonly #finishers: Array<() => void> = [];\n #state: 'open' | 'committed' | 'rolled-back' = 'open';\n\n get state(): 'open' | 'committed' | 'rolled-back' {\n return this.#state;\n }\n\n enqueue(operation: () => void): void {\n if (this.#state !== 'open') {\n throw new ConfigurationError(`Cannot write through a ${this.#state} in-memory transaction`);\n }\n this.#operations.push(operation);\n }\n\n /** Runs `finisher` once the transaction commits or rolls back, like a lock release. */\n onFinish(finisher: () => void): void {\n this.#finishers.push(finisher);\n }\n\n commit(): void {\n this.#state = 'committed';\n for (const operation of this.#operations) {\n operation();\n }\n this.#finish();\n }\n\n rollback(): void {\n this.#state = 'rolled-back';\n this.#finish();\n }\n\n #finish(): void {\n for (const finisher of this.#finishers.splice(0)) {\n finisher();\n }\n }\n}\n\ninterface HeldLock {\n readonly owner: InMemoryTransaction;\n readonly released: Promise<void>;\n}\n\ninterface StoredEvent {\n readonly envelope: SerializedEnvelope;\n readonly sequence: number | null;\n readonly createdAt: Date;\n /**\n * Handlers that ever got a delivery of this event, completed ones included.\n * A repeated append adds deliveries only for handlers not listed, so a\n * completed (deleted) delivery is never created again.\n */\n readonly handlers: Set<string>;\n /** When a delivery of this event last completed. Retention of completed deliveries is measured from here, not from creation. */\n completedAt: Date | null;\n}\n\ninterface SerializedEnvelope extends Omit<EventEnvelope, 'occurredAt'> {\n readonly occurredAt: string;\n}\n\ninterface StoredDelivery {\n readonly id: string;\n readonly eventId: string;\n readonly handler: string;\n readonly key: string | null;\n readonly sequence: number | null;\n status: DeliveryStatus;\n attempts: number;\n availableAt: Date;\n leaseOwner: string | null;\n leaseToken: string | null;\n leaseExpiresAt: Date | null;\n lastError: ErrorInfo | null;\n readonly createdAt: Date;\n updatedAt: Date;\n completedAt: Date | null;\n}\n\n/**\n * Event store kept in process memory, with the same semantics as the database\n * stores: transactional appends, leases, fencing and per-key ordering. Payloads\n * are round-tripped through JSON exactly like a database would store them.\n * Meant for tests and local development.\n */\nexport class InMemoryEventStore implements EventStore<InMemoryTransaction> {\n readonly #events = new Map<string, StoredEvent>();\n readonly #deliveries = new Map<string, StoredDelivery>();\n readonly #keySequences = new Map<string, number>();\n /** Row-lock emulation: event ids and ordering keys written by open transactions. */\n readonly #locks = new Map<string, HeldLock>();\n readonly #writes = new WeakMap<\n InMemoryTransaction,\n { eventIds: Set<string>; deliveryKeys: Set<string> }\n >();\n readonly #generateIdentifier: IdentifierGenerator;\n readonly #retainCompleted: boolean;\n\n constructor(options: InMemoryEventStoreOptions = {}) {\n if (process.env['NODE_ENV'] === 'production' && options.allowInProduction !== true) {\n throw new ConfigurationError(\n 'InMemoryEventStore loses every event on restart. Use a database store in production, or pass allowInProduction: true',\n );\n }\n this.#generateIdentifier = options.generateIdentifier ?? (() => createUuidV7());\n this.#retainCompleted = options.retainCompleted ?? false;\n }\n\n async transaction<T>(work: (transaction: InMemoryTransaction) => Promise<T>): Promise<T> {\n const transaction = new InMemoryTransaction();\n try {\n const result = await work(transaction);\n transaction.commit();\n return result;\n } catch (error) {\n transaction.rollback();\n throw error;\n }\n }\n\n async append(\n transaction: InMemoryTransaction,\n entries: readonly AppendEntry[],\n now: Date,\n ): Promise<AppendResult> {\n await this.#lock(\n transaction,\n entries.flatMap((entry) => [\n `event:${entry.event.id}`,\n ...(entry.event.key === null ? [] : [`key:${entry.event.key}`]),\n ]),\n );\n // What earlier appends of this transaction wrote is not applied yet, but it is visible to this one.\n const written = this.#written(transaction);\n const pendingEventIds = written.eventIds;\n const pendingDeliveryKeys = written.deliveryKeys;\n const appendedEventIds: string[] = [];\n const duplicateEventIds: string[] = [];\n let appendedDeliveryCount = 0;\n for (const entry of entries) {\n const eventId = entry.event.id;\n // Before anything is remembered: an event that cannot be serialized leaves no trace behind.\n const serialized = serializeEnvelope(entry.event);\n const isDuplicate = this.#events.has(eventId) || pendingEventIds.has(eventId);\n if (isDuplicate) {\n duplicateEventIds.push(eventId);\n } else {\n appendedEventIds.push(eventId);\n pendingEventIds.add(eventId);\n }\n const newDeliveries = entry.deliveries.filter((delivery) => {\n const deliveryKey = `${eventId}\\u0000${delivery.handler}`;\n if (\n pendingDeliveryKeys.has(deliveryKey) ||\n this.#events.get(eventId)?.handlers.has(delivery.handler) === true\n ) {\n return false;\n }\n pendingDeliveryKeys.add(deliveryKey);\n return true;\n });\n appendedDeliveryCount += newDeliveries.length;\n transaction.enqueue(() => {\n if (!isDuplicate) {\n this.#events.set(eventId, {\n envelope: serialized,\n sequence: this.#nextSequence(serialized.key),\n createdAt: now,\n handlers: new Set(),\n completedAt: null,\n });\n }\n const stored = this.#events.get(eventId)!;\n for (const delivery of newDeliveries) {\n stored.handlers.add(delivery.handler);\n this.#deliveries.set(delivery.id, {\n id: delivery.id,\n eventId,\n handler: delivery.handler,\n key: stored.envelope.key,\n sequence: stored.sequence,\n status: 'pending',\n attempts: 0,\n availableAt: delivery.availableAt,\n leaseOwner: null,\n leaseToken: null,\n leaseExpiresAt: null,\n lastError: null,\n createdAt: now,\n updatedAt: now,\n completedAt: null,\n });\n }\n });\n }\n return { appendedEventIds, duplicateEventIds, appendedDeliveryCount };\n }\n\n async claim(request: ClaimRequest): Promise<ClaimedDelivery[]> {\n const handlers = new Set(request.handlers);\n const due = [...this.#deliveries.values()]\n .filter((delivery) => handlers.has(delivery.handler) && isDue(delivery, request.now))\n .sort(compareDue);\n const claimed: ClaimedDelivery[] = [];\n for (const delivery of due) {\n if (claimed.length >= request.limit) {\n break;\n }\n if (this.#isKeyBlocked(delivery, request.now)) {\n continue;\n }\n delivery.status = 'processing';\n delivery.attempts += 1;\n delivery.leaseOwner = request.leaseOwner;\n delivery.leaseToken = this.#generateIdentifier();\n delivery.leaseExpiresAt = request.leaseExpiresAt;\n delivery.updatedAt = request.now;\n claimed.push({\n deliveryId: delivery.id,\n leaseToken: delivery.leaseToken,\n handler: delivery.handler,\n attempt: delivery.attempts,\n leaseExpiresAt: request.leaseExpiresAt,\n event: this.#readEnvelope(delivery.eventId),\n });\n }\n return claimed;\n }\n\n async extendLease(lease: LeaseReference, leaseExpiresAt: Date, now: Date): Promise<boolean> {\n return this.#updateLeased(lease, (delivery) => {\n delivery.leaseExpiresAt = leaseExpiresAt;\n delivery.updatedAt = now;\n });\n }\n\n async complete(\n lease: LeaseReference,\n now: Date,\n transaction?: InMemoryTransaction,\n ): Promise<boolean> {\n if (transaction === undefined) {\n return this.#updateLeased(lease, (delivery) => this.#finish(delivery, now));\n }\n if (this.#findLeased(lease) === undefined) {\n return false;\n }\n transaction.enqueue(() => {\n const delivery = this.#findLeased(lease);\n if (delivery !== undefined) {\n this.#finish(delivery, now);\n }\n });\n return true;\n }\n\n async completeMany(leases: readonly LeaseReference[], now: Date): Promise<boolean[]> {\n return Promise.all(leases.map((lease) => this.complete(lease, now)));\n }\n\n async reschedule(\n lease: LeaseReference,\n availableAt: Date,\n error: ErrorInfo,\n now: Date,\n ): Promise<boolean> {\n return this.#updateLeased(lease, (delivery) => {\n delivery.status = 'pending';\n delivery.availableAt = availableAt;\n delivery.lastError = error;\n delivery.updatedAt = now;\n clearLease(delivery);\n });\n }\n\n async release(lease: LeaseReference, now: Date): Promise<boolean> {\n return this.#updateLeased(lease, (delivery) => {\n delivery.status = 'pending';\n delivery.attempts -= 1;\n delivery.availableAt = now;\n delivery.updatedAt = now;\n clearLease(delivery);\n });\n }\n\n async bury(lease: LeaseReference, error: ErrorInfo, now: Date): Promise<boolean> {\n return this.#updateLeased(lease, (delivery) => {\n delivery.status = 'dead';\n delivery.lastError = error;\n delivery.updatedAt = now;\n clearLease(delivery);\n });\n }\n\n async listDeliveries(query: DeliveryQuery): Promise<DeliveryRecord[]> {\n const limit = query.limit ?? 100;\n return [...this.#deliveries.values()]\n .filter((delivery) => matchesQuery(delivery, this.#events.get(delivery.eventId)!, query))\n .sort(\n (left, right) =>\n left.createdAt.getTime() - right.createdAt.getTime() || compareIds(left.id, right.id),\n )\n .slice(0, limit)\n .map((delivery) => ({\n id: delivery.id,\n handler: delivery.handler,\n status: delivery.status,\n attempts: delivery.attempts,\n availableAt: delivery.availableAt,\n leaseOwner: delivery.leaseOwner,\n leaseExpiresAt: delivery.leaseExpiresAt,\n lastError: delivery.lastError,\n createdAt: delivery.createdAt,\n updatedAt: delivery.updatedAt,\n completedAt: delivery.completedAt,\n event: this.#readEnvelope(delivery.eventId),\n }));\n }\n\n async requeue(deliveryIds: readonly string[], now: Date): Promise<number> {\n let moved = 0;\n for (const deliveryId of new Set(deliveryIds)) {\n const delivery = this.#deliveries.get(deliveryId);\n if (delivery?.status !== 'dead') {\n continue;\n }\n delivery.status = 'pending';\n delivery.attempts = 0;\n delivery.availableAt = now;\n delivery.updatedAt = now;\n moved += 1;\n }\n return moved;\n }\n\n async purge(request: PurgeRequest): Promise<PurgeResult> {\n let deletedDeliveries = 0;\n const touchedEventIds = new Set<string>();\n for (const delivery of [...this.#deliveries.values()]) {\n if (isPurgeable(delivery, request)) {\n this.#deliveries.delete(delivery.id);\n touchedEventIds.add(delivery.eventId);\n deletedDeliveries += 1;\n }\n }\n const referencedEventIds = new Set(\n [...this.#deliveries.values()].map((delivery) => delivery.eventId),\n );\n // Events no delivery references go once their retention ran out. An event that had a delivery\n // complete is measured from that completion and only by the completed cutoff; any other\n // (dead-lettered or never delivered) from its creation and by the earliest cutoff.\n const cutoffs = [request.completedBefore, request.deadBefore]\n .filter((cutoff) => cutoff !== undefined)\n .map((cutoff) => cutoff.getTime());\n const orphanCutoff = cutoffs.length === 0 ? Number.NEGATIVE_INFINITY : Math.min(...cutoffs);\n const completedCutoff = request.completedBefore?.getTime() ?? Number.NEGATIVE_INFINITY;\n let deletedEvents = 0;\n for (const [eventId, event] of [...this.#events]) {\n // An open append transaction holds the event (like a row lock): it is about to attach a delivery.\n if (referencedEventIds.has(eventId) || this.#locks.has(`event:${eventId}`)) {\n continue;\n }\n const expired =\n event.completedAt === null\n ? touchedEventIds.has(eventId) || event.createdAt.getTime() < orphanCutoff\n : event.completedAt.getTime() < completedCutoff;\n if (expired) {\n this.#events.delete(eventId);\n deletedEvents += 1;\n }\n }\n return { deletedDeliveries, deletedEvents };\n }\n\n async statistics(now: Date): Promise<EventStoreStatistics> {\n const counts: Record<DeliveryStatus, number> = {\n pending: 0,\n processing: 0,\n completed: 0,\n dead: 0,\n };\n let oldestDueAt: Date | null = null;\n for (const delivery of this.#deliveries.values()) {\n counts[delivery.status] += 1;\n if (isDue(delivery, now)) {\n const dueAt = dueAtOf(delivery);\n if (oldestDueAt === null || dueAt < oldestDueAt) {\n oldestDueAt = dueAt;\n }\n }\n }\n return { ...counts, oldestDueAt };\n }\n\n /**\n * Waits for other open transactions holding any of `names`, then holds them\n * until `transaction` finishes, the way a database holds row locks. Sorted\n * acquisition keeps two transactions from waiting on each other.\n */\n /** The events and deliveries the transaction appended so far, which are not applied before it commits. */\n #written(transaction: InMemoryTransaction): { eventIds: Set<string>; deliveryKeys: Set<string> } {\n let written = this.#writes.get(transaction);\n if (written === undefined) {\n written = { eventIds: new Set(), deliveryKeys: new Set() };\n this.#writes.set(transaction, written);\n }\n return written;\n }\n\n async #lock(transaction: InMemoryTransaction, names: readonly string[]): Promise<void> {\n for (const name of [...new Set(names)].sort()) {\n let held = this.#locks.get(name);\n while (held !== undefined && held.owner !== transaction) {\n await held.released;\n held = this.#locks.get(name);\n }\n if (held !== undefined) {\n continue;\n }\n let release!: () => void;\n const released = new Promise<void>((resolve) => {\n release = resolve;\n });\n this.#locks.set(name, { owner: transaction, released });\n transaction.onFinish(() => {\n this.#locks.delete(name);\n release();\n });\n }\n }\n\n #nextSequence(key: string | null): number | null {\n if (key === null) {\n return null;\n }\n const next = (this.#keySequences.get(key) ?? 0) + 1;\n this.#keySequences.set(key, next);\n return next;\n }\n\n /**\n * A keyed delivery waits while an earlier delivery of the same handler and\n * key is unfinished, or while any other delivery of that handler and key is\n * running under a live lease (a requeued dead letter must not run alongside\n * its successor).\n */\n #isKeyBlocked(delivery: StoredDelivery, now: Date): boolean {\n if (delivery.key === null) {\n return false;\n }\n for (const other of this.#deliveries.values()) {\n if (other === delivery || other.handler !== delivery.handler || other.key !== delivery.key) {\n continue;\n }\n const unfinishedPredecessor =\n other.sequence! < delivery.sequence! &&\n (other.status === 'pending' || other.status === 'processing');\n const runningUnderLiveLease = other.status === 'processing' && other.leaseExpiresAt! > now;\n if (unfinishedPredecessor || runningUnderLiveLease) {\n return true;\n }\n }\n return false;\n }\n\n /** Deletes a completed delivery, or marks it completed when a history is kept. */\n #finish(delivery: StoredDelivery, now: Date): void {\n const event = this.#events.get(delivery.eventId)!;\n if (event.completedAt === null || event.completedAt < now) {\n event.completedAt = now;\n }\n if (!this.#retainCompleted) {\n this.#deliveries.delete(delivery.id);\n return;\n }\n delivery.status = 'completed';\n delivery.completedAt = now;\n delivery.updatedAt = now;\n clearLease(delivery);\n }\n\n #findLeased(lease: LeaseReference): StoredDelivery | undefined {\n const delivery = this.#deliveries.get(lease.deliveryId);\n if (delivery?.status === 'processing' && delivery.leaseToken === lease.leaseToken) {\n return delivery;\n }\n return undefined;\n }\n\n #updateLeased(lease: LeaseReference, update: (delivery: StoredDelivery) => void): boolean {\n const delivery = this.#findLeased(lease);\n if (delivery === undefined) {\n return false;\n }\n update(delivery);\n return true;\n }\n\n #readEnvelope(eventId: string): EventEnvelope {\n const serialized = this.#events.get(eventId)!.envelope;\n const copy = JSON.parse(JSON.stringify(serialized)) as SerializedEnvelope;\n return { ...copy, occurredAt: new Date(copy.occurredAt) };\n }\n}\n\nfunction serializeEnvelope(envelope: EventEnvelope): SerializedEnvelope {\n return JSON.parse(JSON.stringify(envelope)) as SerializedEnvelope;\n}\n\nfunction isDue(delivery: StoredDelivery, now: Date): boolean {\n if (delivery.status === 'pending') {\n return delivery.availableAt <= now;\n }\n return delivery.status === 'processing' && delivery.leaseExpiresAt! <= now;\n}\n\nfunction dueAtOf(delivery: StoredDelivery): Date {\n return delivery.status === 'pending' ? delivery.availableAt : delivery.leaseExpiresAt!;\n}\n\nfunction compareDue(left: StoredDelivery, right: StoredDelivery): number {\n const byDueTime = dueAtOf(left).getTime() - dueAtOf(right).getTime();\n return byDueTime === 0 ? compareIds(left.id, right.id) : byDueTime;\n}\n\nfunction compareIds(left: string, right: string): number {\n return Number(left > right) - Number(left < right);\n}\n\nfunction clearLease(delivery: StoredDelivery): void {\n delivery.leaseOwner = null;\n delivery.leaseToken = null;\n delivery.leaseExpiresAt = null;\n}\n\nfunction matchesQuery(delivery: StoredDelivery, event: StoredEvent, query: DeliveryQuery): boolean {\n return (\n (query.status === undefined || delivery.status === query.status) &&\n (query.handler === undefined || delivery.handler === query.handler) &&\n (query.eventType === undefined || event.envelope.type === query.eventType) &&\n (query.eventId === undefined || delivery.eventId === query.eventId)\n );\n}\n\nfunction isPurgeable(delivery: StoredDelivery, request: PurgeRequest): boolean {\n if (delivery.status === 'completed' && request.completedBefore !== undefined) {\n return delivery.completedAt! < request.completedBefore;\n }\n if (delivery.status === 'dead' && request.deadBefore !== undefined) {\n return delivery.updatedAt < request.deadBefore;\n }\n return false;\n}\n","import type { Clock } from './clock.js';\nimport type { EventStore, LeaseReference } from './event-store.js';\n\ninterface PendingCompletion {\n readonly lease: LeaseReference;\n readonly resolve: (completed: boolean) => void;\n readonly reject: (error: unknown) => void;\n}\n\nexport interface CompletionBatcherSettings {\n /** Longest a completion waits for company before it is written alone. */\n readonly windowMs: number;\n /** A batch is written as soon as it holds this many completions. */\n readonly maxBatchSize: number;\n}\n\n/**\n * Groups the completions of deliveries that finish close together into one\n * `completeMany` call. A completion is written at once when no other delivery\n * is still running (nothing to wait for), when the batch is full, or when the\n * window ends, so a lone delivery never pays the window and a busy dispatcher\n * writes one statement for many deliveries.\n *\n * Every lease is fenced by the store individually: the result of each\n * submission says whether that lease was still held.\n */\nexport class CompletionBatcher {\n readonly #store: Required<Pick<EventStore, 'completeMany'>>;\n readonly #clock: Clock;\n readonly #settings: CompletionBatcherSettings;\n readonly #runningCount: () => number;\n #pending: PendingCompletion[] = [];\n #timer: NodeJS.Timeout | undefined;\n #closing = false;\n\n /**\n * @param runningCount Number of deliveries the dispatcher is running right\n * now, including the ones waiting in this batcher.\n */\n constructor(\n store: Required<Pick<EventStore, 'completeMany'>>,\n clock: Clock,\n settings: CompletionBatcherSettings,\n runningCount: () => number,\n ) {\n this.#store = store;\n this.#clock = clock;\n this.#settings = settings;\n this.#runningCount = runningCount;\n }\n\n /**\n * Queues a completion. Resolves with whether the lease was still held;\n * rejects with the store error when the batch could not be written.\n */\n submit(lease: LeaseReference): Promise<boolean> {\n return new Promise<boolean>((resolve, reject) => {\n this.#pending.push({ lease, resolve, reject });\n if (\n this.#closing ||\n this.#pending.length >= this.#settings.maxBatchSize ||\n this.#pending.length >= this.#runningCount()\n ) {\n this.#flush();\n } else {\n this.#timer ??= setTimeout(() => this.#flush(), this.#settings.windowMs);\n }\n });\n }\n\n /**\n * Shutdown has begun (or ended): while closing, nothing waits for company any more, so the completions\n * already queued are written now and later ones at once.\n */\n setClosing(closing: boolean): void {\n this.#closing = closing;\n if (closing && this.#pending.length > 0) {\n this.#flush();\n }\n }\n\n #flush(): void {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n const batch = this.#pending;\n this.#pending = [];\n Promise.resolve()\n .then(() =>\n this.#store.completeMany(\n batch.map((entry) => entry.lease),\n this.#clock.now(),\n ),\n )\n .then(\n (outcomes) => batch.forEach((entry, index) => entry.resolve(outcomes[index]!)),\n (error: unknown) => batch.forEach((entry) => entry.reject(error)),\n );\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { EventEnvelope } from './event.js';\n\nexport interface ExecutionScope {\n /** Transaction that `publish` joins when none is passed explicitly. */\n readonly transaction?: unknown;\n /** Event being handled. Events published while handling it inherit correlation. */\n readonly event?: EventEnvelope;\n}\n\nconst storage = new AsyncLocalStorage<ExecutionScope>();\n\n/** Runs `work` in `scope`, layered over the caller's scope. */\nexport function runInScope<T>(scope: ExecutionScope, work: () => T): T {\n return storage.run({ ...storage.getStore(), ...scope }, work);\n}\n\n/** Runs `work` in exactly `scope`, ignoring the caller's scope. */\nexport function runInIsolatedScope<T>(scope: ExecutionScope, work: () => T): T {\n return storage.run(scope, work);\n}\n\nexport function getCurrentScope(): ExecutionScope | undefined {\n return storage.getStore();\n}\n","import { toMilliseconds, type Duration } from './duration.js';\nimport { ConfigurationError, NonRetryableError } from './errors.js';\n\n/**\n * How the delay between attempts is randomized.\n * - `full`: uniform in [0, delay]. Spreads retries the most (AWS recommendation).\n * - `equal`: uniform in [delay / 2, delay].\n * - `none`: exactly `delay`. Synchronized retries can stampede a recovering dependency.\n */\nexport type JitterStrategy = 'full' | 'equal' | 'none';\n\nexport interface RetryPolicyOptions {\n /**\n * Total attempts including the first one. Default 10 for handlers, which\n * gives up after roughly 17 minutes of failures with the default delays.\n * `Infinity` retries until the delivery succeeds.\n */\n readonly attempts?: number;\n /** Delay before the second attempt. Default `'1s'`. */\n readonly initialDelay?: Duration;\n /** Growth factor of the delay per attempt. Default 2. */\n readonly factor?: number;\n /** Upper bound of a single delay. Default `'10m'`. */\n readonly maxDelay?: Duration;\n /** Default `'full'`. */\n readonly jitter?: JitterStrategy;\n /** Return false to dead-letter an error without retrying it. */\n readonly retryIf?: (error: unknown) => boolean;\n}\n\nexport interface RetryPolicy {\n readonly attempts: number;\n readonly initialDelayMs: number;\n readonly factor: number;\n readonly maxDelayMs: number;\n readonly jitter: JitterStrategy;\n readonly retryIf: ((error: unknown) => boolean) | undefined;\n}\n\n/** Default policy of handlers. */\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n attempts: 10,\n initialDelayMs: 1_000,\n factor: 2,\n maxDelayMs: 600_000,\n jitter: 'full',\n retryIf: undefined,\n};\n\n/**\n * Default policy of routes to transports: a broker outage must only delay\n * events, so routes retry until the broker accepts them, at most every 5 minutes.\n */\nexport const DEFAULT_ROUTE_RETRY_POLICY: RetryPolicy = {\n attempts: Number.POSITIVE_INFINITY,\n initialDelayMs: 1_000,\n factor: 2,\n maxDelayMs: 300_000,\n jitter: 'full',\n retryIf: undefined,\n};\n\nconst JITTER_STRATEGIES: readonly JitterStrategy[] = ['full', 'equal', 'none'];\n\nexport function createRetryPolicy(\n options: RetryPolicyOptions | undefined,\n base: RetryPolicy = DEFAULT_RETRY_POLICY,\n): RetryPolicy {\n const initialDelayMs =\n options?.initialDelay === undefined\n ? base.initialDelayMs\n : toMilliseconds(options.initialDelay, 'retry.initialDelay');\n const policy: RetryPolicy = {\n attempts: options?.attempts ?? base.attempts,\n initialDelayMs,\n factor: options?.factor ?? base.factor,\n maxDelayMs:\n options?.maxDelay === undefined\n ? // Raising only the initial delay must not trip the inherited cap.\n Math.max(base.maxDelayMs, initialDelayMs)\n : toMilliseconds(options.maxDelay, 'retry.maxDelay'),\n jitter: options?.jitter ?? base.jitter,\n retryIf: options?.retryIf ?? base.retryIf,\n };\n if (\n policy.attempts !== Number.POSITIVE_INFINITY &&\n (!Number.isInteger(policy.attempts) || policy.attempts < 1)\n ) {\n throw new ConfigurationError(\n `retry.attempts must be a positive integer or Infinity, received ${policy.attempts}`,\n );\n }\n if (!Number.isFinite(policy.factor) || policy.factor < 1) {\n throw new ConfigurationError(`retry.factor must be at least 1, received ${policy.factor}`);\n }\n if (policy.maxDelayMs < policy.initialDelayMs) {\n throw new ConfigurationError('retry.maxDelay must not be smaller than retry.initialDelay');\n }\n if (!JITTER_STRATEGIES.includes(policy.jitter)) {\n throw new ConfigurationError(\n `retry.jitter must be one of ${JITTER_STRATEGIES.join(', ')}, received '${String(policy.jitter)}'`,\n );\n }\n return policy;\n}\n\n/**\n * Delay before the next attempt after `failedAttempts` failures (1-based):\n * capped exponential backoff with the policy's jitter.\n */\nexport function computeRetryDelay(\n policy: RetryPolicy,\n failedAttempts: number,\n random: () => number = Math.random,\n): number {\n const exponential = policy.initialDelayMs * policy.factor ** (failedAttempts - 1);\n const capped = Math.min(policy.maxDelayMs, exponential);\n switch (policy.jitter) {\n case 'full':\n return Math.round(random() * capped);\n case 'equal':\n return Math.round(capped / 2 + (random() * capped) / 2);\n case 'none':\n return Math.round(capped);\n }\n}\n\nexport function isRetryableError(policy: RetryPolicy, error: unknown): boolean {\n if (error instanceof NonRetryableError) {\n return false;\n }\n if (policy.retryIf === undefined) {\n return true;\n }\n try {\n return policy.retryIf(error);\n } catch {\n // A broken predicate must not lose the event: keep retrying until the budget runs out.\n return true;\n }\n}\n","import type { Clock } from './clock.js';\nimport { CompletionBatcher } from './completion-batcher.js';\nimport {\n DispatcherStoppedError,\n HandlerTimeoutError,\n LeaseLostError,\n RelayBusError,\n toErrorInfo,\n} from './errors.js';\nimport { validatePayload, type EventEnvelope } from './event.js';\nimport type { ClaimedDelivery, EventStore } from './event-store.js';\nimport { runInIsolatedScope } from './execution-scope.js';\nimport type { HandlerContext, HandlerRegistration, HandlerRegistry } from './handler-registry.js';\nimport type { Notifier } from './notifier.js';\nimport { computeRetryDelay, isRetryableError } from './retry-policy.js';\n\nexport interface DispatcherSettings {\n readonly owner: string;\n readonly concurrency: number;\n readonly batchSize: number;\n readonly pollIntervalMs: number;\n readonly leaseDurationMs: number;\n readonly shutdownTimeoutMs: number;\n /** Longest a completion waits to be written together with others. Absent or 0: written one by one. */\n readonly completionBatchWindowMs?: number;\n /** Completions written at once, at most. Used with `completionBatchWindowMs`. */\n readonly completionBatchSize?: number;\n}\n\nexport interface DispatcherDependencies {\n readonly store: EventStore;\n readonly registry: HandlerRegistry;\n readonly clock: Clock;\n readonly random: () => number;\n readonly notifier: Notifier;\n readonly settings: DispatcherSettings;\n /** Waits between attempts to confirm a completion. Replaceable in tests. */\n readonly sleep?: (milliseconds: number) => Promise<void>;\n}\n\n/**\n * A change of a delivery's state (complete, reschedule, bury, release) that the store did not answer.\n * It stays in the lane's in-flight list, and other deliveries of the lane keep renewing the lane\n * lease, so nothing else would ever recover it: the dispatcher retries it until the store applies it\n * (`settle` resolves true) or says the lease is gone (false).\n */\ninterface PendingSettlement {\n readonly delivery: ClaimedDelivery;\n readonly settle: () => Promise<boolean>;\n /** Reports the outcome that could not be reported when the store failed. */\n readonly applied: () => void;\n}\n\ninterface InFlightDelivery {\n readonly handler: string;\n readonly controller: AbortController;\n readonly settled: Promise<void>;\n}\n\ntype HandlerOutcome = 'completed' | 'unconfirmed';\n\n/** Delays between attempts to record a completion before leaving it to lease expiry. */\nconst COMPLETION_RETRY_DELAYS_MS = [50, 250, 1_000] as const;\n\n/**\n * Shortest time between the start of a claim and a claim caused by a wake-up (a publish, a notification\n * from the store). The first wake-up after a quiet period claims at once; wake-ups that follow quickly\n * are merged into one claim at the end of this time, so a stream of single publishes costs a claim per\n * few milliseconds instead of a claim per event.\n */\nconst WAKE_COOLDOWN_MS = 5;\n\n/**\n * Longest a free slot waits for others to free up before it is refilled alone. Fast handlers free a group\n * of slots well within it, so their claims stay large; a slot of a slow handler stays empty for at most\n * this long.\n */\nconst QUIET_REFILL_MS = 10;\n\n/**\n * Share of a batch (or of the concurrency, when smaller) that must be free before settled deliveries\n * trigger a claim. Measured with the claim-efficiency design test: at 0.5 a backlog drains with about\n * 14 claims per 100 deliveries, at 0.7 with 11 and fewer completion calls too.\n */\nconst REFILL_FRACTION = 0.7;\n\n/** What one round of claims asked for and got. */\ninterface ClaimRound {\n readonly requested: number;\n readonly claimed: number;\n}\n\nconst defaultSleep = (milliseconds: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, milliseconds));\n\n/**\n * Claims due deliveries and runs their handlers: bounded concurrency, lease\n * heartbeats with self-fencing, fenced completion, retries with backoff and\n * dead-lettering.\n */\nexport class Dispatcher {\n readonly #dependencies: DispatcherDependencies;\n readonly #sleep: (milliseconds: number) => Promise<void>;\n readonly #inFlight = new Set<InFlightDelivery>();\n readonly #completions: CompletionBatcher | undefined;\n readonly #pending = new Map<string, PendingSettlement>();\n #recoveryTimer: NodeJS.Timeout | undefined;\n #recovery: Promise<void> | undefined;\n #running = false;\n #loop: Promise<void> | undefined;\n #wakeUp: (() => void) | undefined;\n /** Free slots the claim the loop was woken for needs at least; undefined while nobody woke it. */\n #signalledMinimum: number | undefined;\n /** Free slots a claim needs unless the poll interval or the quiet refill time passed: claims refill in groups. */\n readonly #refillThreshold: number;\n /** Handlers whose last claim got less than it asked for: the store has nothing more for them right now. */\n readonly #exhaustedHandlers = new Set<string>();\n /** Grows with every wake-up: a claim that started before one must not mark a handler exhausted. */\n #wakeGeneration = 0;\n #lastClaimStartedAt = Number.NEGATIVE_INFINITY;\n #cooldownTimer: NodeJS.Timeout | undefined;\n #refillScheduled = false;\n #quietRefillTimer: NodeJS.Timeout | undefined;\n #unwatch: (() => Promise<void>) | undefined;\n #watching: Promise<void> | undefined;\n\n constructor(dependencies: DispatcherDependencies) {\n this.#dependencies = dependencies;\n this.#sleep = dependencies.sleep ?? defaultSleep;\n const { store, clock, settings } = dependencies;\n this.#refillThreshold = Math.ceil(\n Math.min(settings.concurrency, settings.batchSize) * REFILL_FRACTION,\n );\n const { completionBatchWindowMs: windowMs = 0, completionBatchSize: maxBatchSize = 1 } =\n settings;\n if (store.completeMany !== undefined && windowMs > 0) {\n this.#completions = new CompletionBatcher(\n { completeMany: (leases, now) => store.completeMany!(leases, now) },\n clock,\n { windowMs, maxBatchSize },\n () => this.#inFlight.size,\n );\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n get inFlightCount(): number {\n return this.#inFlight.size;\n }\n\n /**\n * True while the store reports new deliveries to this dispatcher by itself (see\n * {@link EventStore.watchNewDeliveries}), from every process: a publisher then has no reason to wake it.\n */\n get watchesNewDeliveries(): boolean {\n return this.#unwatch !== undefined;\n }\n\n start(): void {\n if (this.#running) {\n return;\n }\n this.#running = true;\n this.#completions?.setClosing(false);\n this.#watching = this.#watchNewDeliveries();\n this.#loop = this.#runLoop();\n }\n\n /**\n * Asks for a claim soon, for example right after a publish: at once after a quiet period, otherwise\n * at the end of a short cooldown that merges the wake-ups arriving meanwhile into one claim.\n */\n wake(): void {\n // New work may have arrived for handlers whose last claim found nothing.\n this.#exhaustedHandlers.clear();\n this.#wakeGeneration += 1;\n const wait = this.#lastClaimStartedAt + WAKE_COOLDOWN_MS - Date.now();\n if (wait <= 0) {\n this.#requestClaim();\n return;\n }\n this.#cooldownTimer ??= setTimeout(() => {\n this.#cooldownTimer = undefined;\n this.#requestClaim();\n }, wait);\n }\n\n /** Ends the current wait of the claim loop, or the next one at once, for a claim once `minimumFree` slots are free. */\n #signal(minimumFree: number): void {\n this.#signalledMinimum = Math.min(this.#signalledMinimum ?? minimumFree, minimumFree);\n this.#wakeUp?.();\n }\n\n /**\n * Starts listening to the store's reports of new deliveries. Polling stays the safety net: a store\n * that cannot listen, or fails to, only costs latency, so a failure is reported and otherwise ignored.\n */\n async #watchNewDeliveries(): Promise<void> {\n const { store, notifier } = this.#dependencies;\n try {\n const unwatch = await store.watchNewDeliveries?.(() => this.wake());\n if (unwatch !== undefined && !this.#running) {\n await unwatch();\n return;\n }\n this.#unwatch = unwatch;\n if (unwatch !== undefined) {\n // Deliveries committed after the first claim and before listening began were reported to nobody.\n this.wake();\n }\n } catch (error) {\n notifier.failure('watch', error);\n }\n }\n\n /** Stops listening to the store's reports of new deliveries. */\n async #stopWatching(): Promise<void> {\n await this.#watching;\n const unwatch = this.#unwatch;\n this.#unwatch = undefined;\n try {\n await unwatch?.();\n } catch (error) {\n this.#dependencies.notifier.failure('watch', error);\n }\n }\n\n /**\n * Stops claiming, waits up to the shutdown timeout for running handlers,\n * then aborts the rest and releases their deliveries for another process.\n */\n async stop(): Promise<void> {\n if (!this.#running) {\n // Batches run by hand (`runOnce`) leave settlements to recover without ever starting the loop.\n await this.#closeRecovery(Date.now() + this.#dependencies.settings.shutdownTimeoutMs);\n return;\n }\n this.#running = false;\n this.#completions?.setClosing(true);\n clearTimeout(this.#cooldownTimer);\n this.#cooldownTimer = undefined;\n clearTimeout(this.#quietRefillTimer);\n this.#quietRefillTimer = undefined;\n this.#signal(this.#refillThreshold);\n const deadline = Date.now() + this.#dependencies.settings.shutdownTimeoutMs;\n await this.#waitUntil(this.#stopWatching(), deadline);\n await this.#waitUntil(this.#loop!, deadline);\n const settled = Promise.allSettled([...this.#inFlight].map((delivery) => delivery.settled));\n if ((await this.#waitUntil(settled, deadline)) === 'timeout') {\n for (const delivery of this.#inFlight) {\n delivery.controller.abort(new DispatcherStoppedError('relaybus dispatcher stopped'));\n }\n await settled;\n }\n await this.#closeRecovery(deadline);\n await this.#waitUntil(this.#relinquish(), deadline);\n }\n\n /**\n * Gives the settlements still pending one last try and forgets them. A pass of the timer may be inside the\n * store: it ends before the last pass starts. A store that does not answer before the deadline gets no\n * further call, since it may be closed right after.\n */\n async #closeRecovery(deadline: number): Promise<void> {\n clearInterval(this.#recoveryTimer);\n this.#recoveryTimer = undefined;\n const lastTry = (async () => {\n await this.#recovery;\n await this.#recoverSettlements();\n })();\n await this.#waitUntil(lastTry, deadline);\n this.#pending.clear();\n }\n\n /**\n * Retries every pending settlement once; a pass that is already running is the one returned. A store that\n * still fails leaves the settlement for the next attempt (it was reported when it first failed).\n */\n #recoverSettlements(): Promise<void> {\n this.#recovery ??= this.#recoverAll().finally(() => {\n this.#recovery = undefined;\n });\n return this.#recovery;\n }\n\n async #recoverAll(): Promise<void> {\n for (const [key, entry] of [...this.#pending]) {\n // Shutdown gave up on this one (the pending map was cleared): the store may be closed by now.\n if (this.#pending.get(key) !== entry) {\n continue;\n }\n try {\n const applied = await entry.settle();\n this.#pending.delete(pendingKey(entry.delivery));\n if (applied) {\n entry.applied();\n } else {\n this.#dependencies.notifier.notify('onLeaseLost', { delivery: entry.delivery });\n }\n } catch {\n // Still down: the next tick tries again.\n }\n }\n }\n\n #retain(entry: PendingSettlement): void {\n this.#pending.set(pendingKey(entry.delivery), entry);\n this.#recoveryTimer ??= setInterval(\n () => void this.#recoverSettlements(),\n this.#dependencies.settings.pollIntervalMs,\n );\n this.#recoveryTimer.unref();\n }\n\n /** Gives lease groups the owner no longer works on back to the store, so other workers need not wait for expiry. */\n async #relinquish(): Promise<void> {\n const { store, clock, notifier, settings } = this.#dependencies;\n try {\n await store.relinquish?.(settings.owner, clock.now());\n } catch (error) {\n notifier.failure('relinquish', error);\n }\n }\n\n /** Claims one batch and resolves when every claimed delivery settled. Returns how many ran. */\n async processBatch(): Promise<number> {\n const { started } = await this.#claimAndStart();\n await Promise.allSettled(started.map((delivery) => delivery.settled));\n return started.length;\n }\n\n async #waitUntil(work: Promise<unknown>, deadline: number): Promise<'done' | 'timeout'> {\n let timer: NodeJS.Timeout | undefined;\n const timedOut = new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), Math.max(0, deadline - Date.now()));\n });\n const outcome = await Promise.race([work.then(() => 'done' as const), timedOut]);\n clearTimeout(timer);\n return outcome;\n }\n\n /**\n * Claims until stopped. A claim that filled its batch is followed by the next one at once while enough\n * slots are free. Otherwise the loop sleeps until a wake-up (a publish, a store notification, or enough\n * deliveries settling to refill a group of slots) or the poll interval. Only the poll interval claims\n * for fewer free slots than the refill threshold, so a busy dispatcher never claims slot by slot.\n */\n async #runLoop(): Promise<void> {\n let minimumFree = 1;\n while (this.#running) {\n let round: ClaimRound = { requested: 0, claimed: 0 };\n if (this.#freeSlots() >= minimumFree) {\n try {\n round = await this.#claimAndStart();\n } catch (error) {\n this.#dependencies.notifier.failure('claim', error);\n }\n }\n if (\n round.requested > 0 &&\n round.claimed === round.requested &&\n this.#freeSlots() >= this.#refillThreshold\n ) {\n minimumFree = this.#refillThreshold;\n continue;\n }\n minimumFree = await this.#waitForWakeUp();\n if (this.#freeSlots() < minimumFree) {\n // Woken for more free slots than there are now: ask again, so the wake-up is not lost.\n this.#requestClaim();\n }\n }\n }\n\n /** Waits for a wake-up or the poll interval. Resolves with the free slots the next claim needs. */\n async #waitForWakeUp(): Promise<number> {\n if (this.#signalledMinimum === undefined) {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n this.#signalledMinimum = 1;\n resolve();\n }, this.#dependencies.settings.pollIntervalMs);\n this.#wakeUp = () => {\n clearTimeout(timer);\n resolve();\n };\n });\n this.#wakeUp = undefined;\n }\n const minimumFree = this.#signalledMinimum!;\n this.#signalledMinimum = undefined;\n return minimumFree;\n }\n\n /**\n * A delivery settled. Its slot is worth refilling when the store may have more for its handler: a keyed\n * delivery unblocks the next one of its key, a delivery that did not succeed may be due again at once\n * (a retry without delay, a release), and a handler whose last claim was full may have a backlog.\n */\n #onSettled(delivery: ClaimedDelivery, succeeded: boolean): void {\n if (\n delivery.event.key !== null ||\n !succeeded ||\n !this.#exhaustedHandlers.has(delivery.handler)\n ) {\n this.#requestClaim();\n }\n }\n\n /**\n * Asks the loop for a claim. Once a group of slots is free the claim waits only for the deliveries\n * settling in the same tick, so they are claimed for together; fewer free slots are refilled when no\n * claim started for a short while. With no free slot the next settlement asks again.\n */\n #requestClaim(): void {\n const free = this.#freeSlots();\n if (free >= this.#refillThreshold) {\n if (!this.#refillScheduled) {\n this.#refillScheduled = true;\n setImmediate(() => {\n this.#refillScheduled = false;\n this.#signal(this.#refillThreshold);\n });\n }\n } else if (free > 0) {\n this.#quietRefillTimer ??= setTimeout(\n () => {\n this.#quietRefillTimer = undefined;\n this.#signal(1);\n },\n Math.max(0, this.#lastClaimStartedAt + QUIET_REFILL_MS - Date.now()),\n );\n }\n }\n\n #freeSlots(): number {\n return this.#dependencies.settings.concurrency - this.#inFlight.size;\n }\n\n /** Claims for every handler with room and starts what was claimed. */\n async #claimAndStart(): Promise<ClaimRound & { readonly started: InFlightDelivery[] }> {\n const { store, registry, clock, settings } = this.#dependencies;\n const started: InFlightDelivery[] = [];\n let requested = 0;\n for (const request of this.#planClaims(registry.all())) {\n const now = clock.now();\n const wakeGeneration = this.#wakeGeneration;\n this.#lastClaimStartedAt = Date.now();\n clearTimeout(this.#quietRefillTimer);\n this.#quietRefillTimer = undefined;\n requested += request.limit;\n const claimed = await store.claim({\n handlers: request.handlers,\n limit: request.limit,\n leaseOwner: settings.owner,\n leaseExpiresAt: new Date(now.getTime() + settings.leaseDurationMs),\n now,\n });\n for (const handler of request.handlers) {\n // A wake-up that arrived while the claim ran may have brought what this claim could not see.\n if (claimed.length < request.limit && wakeGeneration === this.#wakeGeneration) {\n this.#exhaustedHandlers.add(handler);\n } else {\n this.#exhaustedHandlers.delete(handler);\n }\n }\n for (const delivery of claimed) {\n started.push(this.#start(delivery));\n }\n }\n return { requested, claimed: started.length, started };\n }\n\n /** One claim for handlers without a concurrency limit, one per limited handler with room. */\n #planClaims(\n registrations: readonly HandlerRegistration[],\n ): Array<{ handlers: string[]; limit: number }> {\n let free = Math.min(this.#freeSlots(), this.#dependencies.settings.batchSize);\n const plans: Array<{ handlers: string[]; limit: number }> = [];\n const unlimited = registrations.filter((registration) => registration.concurrency === null);\n for (const registration of registrations) {\n if (registration.concurrency === null || free === 0) {\n continue;\n }\n const room = registration.concurrency - this.#countInFlight(registration.id);\n const limit = Math.min(room, free);\n if (limit > 0) {\n plans.push({ handlers: [registration.id], limit });\n free -= limit;\n }\n }\n if (unlimited.length > 0 && free > 0) {\n plans.push({ handlers: unlimited.map((registration) => registration.id), limit: free });\n }\n return plans;\n }\n\n #countInFlight(handler: string): number {\n let count = 0;\n for (const delivery of this.#inFlight) {\n if (delivery.handler === handler) {\n count += 1;\n }\n }\n return count;\n }\n\n #start(delivery: ClaimedDelivery): InFlightDelivery {\n const controller = new AbortController();\n let succeeded = false;\n const entry: InFlightDelivery = {\n handler: delivery.handler,\n controller,\n settled: Promise.resolve()\n .then(async () => {\n succeeded = await this.#execute(delivery, controller);\n })\n // Safety net: #execute handles every expected failure itself.\n .catch((error: unknown) => this.#dependencies.notifier.failure('dispatch', error))\n .finally(() => {\n this.#inFlight.delete(entry);\n this.#onSettled(delivery, succeeded);\n }),\n };\n this.#inFlight.add(entry);\n return entry;\n }\n\n /** Runs one delivery. Resolves true when its handler succeeded, so the delivery is done for good. */\n async #execute(delivery: ClaimedDelivery, controller: AbortController): Promise<boolean> {\n const { registry, notifier, clock } = this.#dependencies;\n const registration = registry.get(delivery.handler)!;\n // A new claim of this delivery makes whatever was pending for its earlier claims moot.\n for (const key of [...this.#pending.keys()].filter((pending) =>\n pending.startsWith(`${delivery.deliveryId}\\u0000`),\n )) {\n this.#pending.delete(key);\n }\n notifier.notify('onDeliveryStarted', { delivery });\n const startedAt = clock.now().getTime();\n if (delivery.attempt > registration.retry.attempts) {\n await this.#bury(\n delivery,\n new RelayBusError(\n `Delivery reached attempt ${delivery.attempt} of ${registration.retry.attempts} after its lease expired`,\n ),\n );\n return false;\n }\n let stopHeartbeat = (): void => undefined;\n try {\n stopHeartbeat = registration.transactional\n ? await this.#guardTransactionalLease(registration, delivery, controller)\n : this.#startHeartbeat(delivery, controller);\n const outcome = await this.#runHandler(registration, delivery, controller);\n const durationMs = clock.now().getTime() - startedAt;\n if (outcome === 'completed') {\n notifier.notify('onDeliverySucceeded', { delivery, durationMs });\n } else {\n this.#retain({\n delivery,\n settle: () => this.#complete(delivery),\n applied: () => notifier.notify('onDeliverySucceeded', { delivery, durationMs }),\n });\n }\n return true;\n } catch (error) {\n if (error instanceof LeaseLostError) {\n notifier.notify('onLeaseLost', { delivery });\n if (!error.storeConfirmed) {\n await this.#giveBack(registration, delivery, error);\n }\n } else if (error instanceof DispatcherStoppedError) {\n await this.#release(delivery);\n } else {\n await this.#fail(registration, delivery, error);\n }\n return false;\n } finally {\n stopHeartbeat();\n }\n }\n\n async #runHandler(\n registration: HandlerRegistration,\n delivery: ClaimedDelivery,\n controller: AbortController,\n ): Promise<HandlerOutcome> {\n const { store, clock } = this.#dependencies;\n const payload = await validatePayload(\n delivery.event.type,\n registration.schema,\n delivery.event.payload,\n );\n const event: EventEnvelope = { ...delivery.event, payload };\n if (registration.transactional) {\n await store.transaction(async (transaction) => {\n await this.#invoke(registration, event, delivery, controller, transaction);\n if (!(await store.complete(delivery, clock.now(), transaction))) {\n throw new LeaseLostError(`Lease on delivery ${delivery.deliveryId} was lost`, {\n storeConfirmed: true,\n });\n }\n });\n return 'completed';\n }\n await this.#invoke(registration, event, delivery, controller, undefined);\n return this.#confirmCompletion(delivery);\n }\n\n /**\n * Records a completion, retrying transient store errors while the lease is\n * still held. Gives up to lease expiry, which reruns the handler: at-least-once.\n */\n async #confirmCompletion(delivery: ClaimedDelivery): Promise<HandlerOutcome> {\n const { notifier } = this.#dependencies;\n for (let attempt = 0; ; attempt += 1) {\n let completed: boolean;\n try {\n completed = await this.#complete(delivery);\n } catch (error) {\n const delay = COMPLETION_RETRY_DELAYS_MS[attempt];\n if (delay === undefined) {\n notifier.failure('complete', error);\n return 'unconfirmed';\n }\n await this.#sleep(delay);\n continue;\n }\n if (!completed) {\n throw new LeaseLostError(`Lease on delivery ${delivery.deliveryId} was lost`, {\n storeConfirmed: true,\n });\n }\n return 'completed';\n }\n }\n\n /** Records one completion, grouped with its neighbours when the store can complete many at once. */\n #complete(delivery: ClaimedDelivery): Promise<boolean> {\n const { store, clock } = this.#dependencies;\n return this.#completions === undefined\n ? store.complete(delivery, clock.now())\n : this.#completions.submit(delivery);\n }\n\n async #invoke(\n registration: HandlerRegistration,\n event: EventEnvelope,\n delivery: ClaimedDelivery,\n controller: AbortController,\n transaction: unknown,\n ): Promise<void> {\n const context: HandlerContext = {\n deliveryId: delivery.deliveryId,\n handler: delivery.handler,\n attempt: delivery.attempt,\n maxAttempts: registration.retry.attempts,\n signal: controller.signal,\n transaction,\n };\n // An isolated scope keeps a caller's transaction (for example a test calling\n // runOnce inside bus.transaction) from leaking into the handler.\n const scope = transaction === undefined ? { event } : { event, transaction };\n if (controller.signal.aborted) {\n // The lease was lost (or the bus stopped) while the payload was validated.\n throw controller.signal.reason;\n }\n const work = Promise.resolve().then(() =>\n runInIsolatedScope(scope, () => registration.handle(event, context)),\n );\n work.catch(() => undefined);\n let timer: NodeJS.Timeout | undefined;\n if (registration.timeoutMs !== null) {\n const timeoutMs = registration.timeoutMs;\n timer = setTimeout(() => {\n controller.abort(\n new HandlerTimeoutError(\n `Handler '${registration.id}' did not settle within ${timeoutMs}ms`,\n ),\n );\n }, timeoutMs);\n }\n try {\n await Promise.race([work, rejectOnAbort(controller.signal)]);\n } catch (error) {\n await this.#awaitAbandonedHandler(work, error, transaction !== undefined);\n throw error;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * After an abort the handler may still be running. Waiting for it keeps a\n * retry from overlapping the abandoned run, and keeps a transactional\n * handler from writing through a transaction that was already released.\n * Transactional handlers are always awaited; others for one lease duration,\n * except at shutdown, which already waited.\n */\n async #awaitAbandonedHandler(\n work: Promise<unknown>,\n reason: unknown,\n transactional: boolean,\n ): Promise<void> {\n const settledWork = work.then(\n () => undefined,\n () => undefined,\n );\n if (transactional) {\n await settledWork;\n return;\n }\n if (reason instanceof DispatcherStoppedError) {\n return;\n }\n const deadline = Date.now() + this.#dependencies.settings.leaseDurationMs;\n await this.#waitUntil(settledWork, deadline);\n }\n\n /**\n * Transactional handlers get no renewals: a renewal would write the delivery\n * the open transaction completes, which databases with snapshot isolation\n * (MongoDB) turn into a write conflict that reruns the handler. Instead the\n * lease is extended once to cover the handler timeout, and the handler is\n * aborted when that lease ends.\n */\n async #guardTransactionalLease(\n registration: HandlerRegistration,\n delivery: ClaimedDelivery,\n controller: AbortController,\n ): Promise<() => void> {\n const { store, clock, settings } = this.#dependencies;\n const now = clock.now();\n let expiry = delivery.leaseExpiresAt.getTime();\n if (registration.timeoutMs !== null && now.getTime() + registration.timeoutMs >= expiry) {\n expiry = now.getTime() + registration.timeoutMs + settings.leaseDurationMs;\n if (!(await store.extendLease(delivery, new Date(expiry), now))) {\n throw new LeaseLostError(`Lease on delivery ${delivery.deliveryId} was lost`, {\n storeConfirmed: true,\n });\n }\n }\n const timer = setTimeout(\n () => {\n controller.abort(new LeaseLostError(`Lease on delivery ${delivery.deliveryId} expired`));\n },\n Math.max(0, expiry - clock.now().getTime()),\n );\n timer.unref();\n return () => clearTimeout(timer);\n }\n\n /**\n * Renews the lease every third of its duration. A worker that cannot renew\n * aborts its handler once the last confirmed expiry passes, because another\n * worker may then claim the delivery (self-fencing).\n */\n #startHeartbeat(delivery: ClaimedDelivery, controller: AbortController): () => void {\n const { store, clock, notifier, settings } = this.#dependencies;\n let confirmedExpiry = delivery.leaseExpiresAt.getTime();\n let renewing = false;\n const abortLeaseLost = (storeConfirmed = false): void => {\n controller.abort(\n new LeaseLostError(`Lease on delivery ${delivery.deliveryId} was lost`, { storeConfirmed }),\n );\n };\n const timer = setInterval(\n () => {\n const now = clock.now();\n if (now.getTime() >= confirmedExpiry) {\n abortLeaseLost();\n return;\n }\n if (renewing) {\n return;\n }\n renewing = true;\n const expiry = now.getTime() + settings.leaseDurationMs;\n store\n .extendLease(delivery, new Date(expiry), now)\n .then((extended) => {\n if (extended) {\n confirmedExpiry = expiry;\n } else {\n abortLeaseLost(true);\n }\n })\n .catch((error: unknown) => notifier.failure('extend-lease', error))\n .finally(() => {\n renewing = false;\n });\n },\n Math.max(1, Math.floor(settings.leaseDurationMs / 3)),\n );\n timer.unref();\n return () => clearInterval(timer);\n }\n\n async #fail(\n registration: HandlerRegistration,\n delivery: ClaimedDelivery,\n error: unknown,\n ): Promise<void> {\n const policy = registration.retry;\n if (delivery.attempt >= policy.attempts || !isRetryableError(policy, error)) {\n await this.#bury(delivery, error);\n return;\n }\n await this.#reschedule(registration, delivery, error);\n }\n\n /** Schedules the next attempt with the retry policy's backoff. */\n async #reschedule(\n registration: HandlerRegistration,\n delivery: ClaimedDelivery,\n error: unknown,\n ): Promise<void> {\n const { store, clock, random, notifier } = this.#dependencies;\n const policy = registration.retry;\n const errorInfo = toErrorInfo(error);\n const now = clock.now();\n const availableAt = new Date(\n now.getTime() + computeRetryDelay(policy, delivery.attempt, random),\n );\n let rescheduled: boolean;\n try {\n rescheduled = await store.reschedule(delivery, availableAt, errorInfo, now);\n } catch (storeError) {\n notifier.failure('reschedule', storeError);\n this.#retain({\n delivery,\n settle: () => store.reschedule(delivery, availableAt, errorInfo, now),\n applied: () =>\n notifier.notify('onDeliveryRetryScheduled', { delivery, error: errorInfo, availableAt }),\n });\n return;\n }\n if (rescheduled) {\n notifier.notify('onDeliveryRetryScheduled', { delivery, error: errorInfo, availableAt });\n } else {\n notifier.notify('onLeaseLost', { delivery });\n }\n }\n\n async #bury(delivery: ClaimedDelivery, error: unknown): Promise<void> {\n const { store, clock, notifier } = this.#dependencies;\n const errorInfo = toErrorInfo(error);\n let buried: boolean;\n try {\n buried = await store.bury(delivery, errorInfo, clock.now());\n } catch (storeError) {\n notifier.failure('bury', storeError);\n this.#retain({\n delivery,\n settle: () => store.bury(delivery, errorInfo, clock.now()),\n applied: () => notifier.notify('onDeliveryDead', { delivery, error: errorInfo }),\n });\n return;\n }\n if (buried) {\n notifier.notify('onDeliveryDead', { delivery, error: errorInfo });\n } else {\n notifier.notify('onLeaseLost', { delivery });\n }\n }\n\n /**\n * A worker that only noticed locally that its lease ran out may still own the delivery in the\n * store, where other deliveries of its lane keep renewing the lane: it must not stay in flight\n * for ever. The attempt took longer than its lease, so it counts as a failed attempt (an\n * exhausted delivery is dead-lettered, whatever a custom `retryIf` says): a handler that always\n * outlives its lease cannot run for ever at attempt 1. If the lease is gone for real the store\n * refuses and nothing changes. The lost lease was reported already.\n */\n async #giveBack(\n registration: HandlerRegistration,\n delivery: ClaimedDelivery,\n error: LeaseLostError,\n ): Promise<void> {\n if (delivery.attempt >= registration.retry.attempts) {\n await this.#bury(delivery, error);\n } else {\n await this.#reschedule(registration, delivery, error);\n }\n }\n\n async #release(delivery: ClaimedDelivery): Promise<void> {\n const { store, clock, notifier } = this.#dependencies;\n let released: boolean;\n try {\n released = await store.release(delivery, clock.now());\n } catch (storeError) {\n notifier.failure('release', storeError);\n this.#retain({\n delivery,\n settle: () => store.release(delivery, clock.now()),\n applied: () => notifier.notify('onDeliveryReleased', { delivery }),\n });\n return;\n }\n if (released) {\n notifier.notify('onDeliveryReleased', { delivery });\n } else {\n notifier.notify('onLeaseLost', { delivery });\n }\n }\n}\n\n/** Settlements are pending per claim: an older claim of a delivery must never replace or remove the newer one's. */\nfunction pendingKey(delivery: ClaimedDelivery): string {\n return `${delivery.deliveryId}\\u0000${delivery.leaseToken}`;\n}\n\nfunction rejectOnAbort(signal: AbortSignal): Promise<never> {\n return new Promise<never>((_, reject) => {\n // The reason is always an Error: the dispatcher aborts with LeaseLostError,\n // HandlerTimeoutError or DispatcherStoppedError.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n signal.addEventListener('abort', () => reject(signal.reason), { once: true });\n });\n}\n","import { toTimerMilliseconds, type Duration } from './duration.js';\nimport { ConfigurationError } from './errors.js';\nimport type { EventEnvelope } from './event.js';\nimport { createRetryPolicy, type RetryPolicy, type RetryPolicyOptions } from './retry-policy.js';\nimport type { StandardSchemaV1 } from './standard-schema.js';\n\n/** Passed to every handler call. */\nexport interface HandlerContext<TTransaction = unknown> {\n readonly deliveryId: string;\n readonly handler: string;\n /** Attempt number, starting at 1. */\n readonly attempt: number;\n readonly maxAttempts: number;\n /** Aborted when the handler times out, the lease is lost or the bus stops. */\n readonly signal: AbortSignal;\n /**\n * Transaction the delivery completes in, for handlers subscribed with\n * `transactional: true`. Write through it to make the handler's effects and\n * the completion atomic. Undefined otherwise.\n */\n readonly transaction: TTransaction | undefined;\n}\n\nexport type EventHandler<TPayload = unknown, TTransaction = unknown> = (\n event: EventEnvelope<TPayload>,\n context: HandlerContext<TTransaction>,\n) => unknown;\n\nexport interface SubscribeOptions {\n /**\n * Stable id of the handler. Deliveries are recorded under it, so renaming it\n * orphans pending deliveries. Letters, digits and `._:/-`.\n */\n readonly id: string;\n /** Overrides the bus retry policy field by field. */\n readonly retry?: RetryPolicyOptions;\n /** Abort and retry when a call takes longer. `false` disables the bus default. */\n readonly timeout?: Duration | false;\n /** Maximum concurrent deliveries of this handler in this process. */\n readonly concurrency?: number;\n /**\n * Run the handler inside a store transaction that also completes the\n * delivery: its writes and the completion commit or roll back together,\n * so a handler that writes only through `context.transaction` (or through\n * events it publishes) takes effect exactly once.\n *\n * The lease is not renewed while the transaction is open. A transactional\n * handler must finish within the lease duration (default 30s), or within its\n * `timeout`, which extends the lease once to cover it; otherwise it is aborted.\n */\n readonly transactional?: boolean;\n}\n\n/** Public description of a registered handler or route. */\nexport interface HandlerDescriptor {\n readonly id: string;\n readonly eventType: string;\n readonly retry: RetryPolicy;\n readonly timeoutMs: number | null;\n readonly concurrency: number | null;\n readonly transactional: boolean;\n /** True for routes that forward events to a transport. */\n readonly forwardsToTransport: boolean;\n}\n\nexport interface HandlerRegistration extends HandlerDescriptor {\n readonly schema: StandardSchemaV1 | undefined;\n readonly handle: EventHandler;\n}\n\nexport interface RegistrationDefaults {\n readonly retry: RetryPolicy;\n readonly timeoutMs: number | null;\n}\n\nconst HANDLER_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;\n\nexport interface RegistrationInput {\n readonly eventType: string;\n readonly schema: StandardSchemaV1 | undefined;\n readonly handle: EventHandler;\n readonly options: SubscribeOptions;\n readonly forwardsToTransport: boolean;\n}\n\nexport class HandlerRegistry {\n readonly #byId = new Map<string, HandlerRegistration>();\n readonly #byEventType = new Map<string, HandlerRegistration[]>();\n\n register(input: RegistrationInput, defaults: RegistrationDefaults): HandlerRegistration {\n const { options } = input;\n if (!HANDLER_ID_PATTERN.test(options.id)) {\n throw new ConfigurationError(\n `Handler id '${options.id}' must be 1-255 characters of letters, digits, '.', '_', ':', '/' or '-'`,\n );\n }\n if (this.#byId.has(options.id)) {\n throw new ConfigurationError(`Handler id '${options.id}' is already registered`);\n }\n if (\n options.concurrency !== undefined &&\n (!Number.isInteger(options.concurrency) || options.concurrency < 1)\n ) {\n throw new ConfigurationError(\n `Concurrency of handler '${options.id}' must be a positive integer, received ${options.concurrency}`,\n );\n }\n const registration: HandlerRegistration = {\n id: options.id,\n eventType: input.eventType,\n schema: input.schema,\n handle: input.handle,\n retry: createRetryPolicy(options.retry, defaults.retry),\n timeoutMs: resolveTimeout(options.timeout, defaults.timeoutMs, options.id),\n concurrency: options.concurrency ?? null,\n transactional: options.transactional ?? false,\n forwardsToTransport: input.forwardsToTransport,\n };\n this.#byId.set(registration.id, registration);\n const forType = this.#byEventType.get(registration.eventType) ?? [];\n forType.push(registration);\n this.#byEventType.set(registration.eventType, forType);\n return registration;\n }\n\n get(id: string): HandlerRegistration | undefined {\n return this.#byId.get(id);\n }\n\n forEventType(eventType: string): readonly HandlerRegistration[] {\n return this.#byEventType.get(eventType) ?? [];\n }\n\n all(): readonly HandlerRegistration[] {\n return [...this.#byId.values()];\n }\n}\n\nfunction resolveTimeout(\n timeout: Duration | false | undefined,\n fallback: number | null,\n handlerId: string,\n): number | null {\n if (timeout === undefined) {\n return fallback;\n }\n if (timeout === false) {\n return null;\n }\n return toTimerMilliseconds(timeout, `Timeout of handler '${handlerId}'`);\n}\n","import { toErrorInfo } from './errors.js';\nimport type { FailureStage, RelayBusLogger, RelayBusObserver } from './observer.js';\n\ntype ObserverMethod = Exclude<keyof RelayBusObserver, 'onFailure'>;\ntype ObserverArgument<TMethod extends keyof RelayBusObserver> = Parameters<\n NonNullable<RelayBusObserver[TMethod]>\n>[0];\n\n/** Fans hook calls out to every observer, isolating the bus from observer bugs. */\nexport class Notifier {\n readonly #observers: readonly RelayBusObserver[];\n readonly #logger: RelayBusLogger;\n\n constructor(observers: readonly RelayBusObserver[], logger: RelayBusLogger) {\n this.#observers = observers;\n this.#logger = logger;\n }\n\n notify<TMethod extends ObserverMethod>(\n method: TMethod,\n argument: ObserverArgument<TMethod>,\n ): void {\n for (const observer of this.#observers) {\n try {\n (observer[method] as ((value: ObserverArgument<TMethod>) => void) | undefined)?.call(\n observer,\n argument,\n );\n } catch (error) {\n this.#reportObserverFailure(observer, error);\n }\n }\n }\n\n failure(stage: FailureStage, error: unknown): void {\n const errorInfo = toErrorInfo(error);\n this.#logger.error(\n `[Notifier](failure) relaybus ${stage} failed | ${errorInfo.name}: ${errorInfo.message}`,\n );\n for (const observer of this.#observers) {\n try {\n observer.onFailure?.({ stage, error: errorInfo });\n } catch (observerError) {\n this.#logObserverFailure(observerError);\n }\n }\n }\n\n #reportObserverFailure(failedObserver: RelayBusObserver, error: unknown): void {\n this.#logObserverFailure(error);\n const errorInfo = toErrorInfo(error);\n for (const observer of this.#observers) {\n if (observer === failedObserver) {\n continue;\n }\n try {\n observer.onFailure?.({ stage: 'observer', error: errorInfo });\n } catch (observerError) {\n this.#logObserverFailure(observerError);\n }\n }\n }\n\n #logObserverFailure(error: unknown): void {\n const errorInfo = toErrorInfo(error);\n this.#logger.warn(\n `[Notifier](notify) relaybus observer threw | ${errorInfo.name}: ${errorInfo.message}`,\n );\n }\n}\n","import { hostname } from 'node:os';\nimport {\n resolveCatalogHandlers,\n type Catalog,\n type CatalogEventSelection,\n type HandlersOf,\n type SubscribeCatalogOptions,\n} from './catalog.js';\nimport {\n assertCatalogsCovered,\n toCatalogRequirement,\n type CatalogDeclaration,\n type CatalogRequirement,\n type EventTypeRegistrations,\n} from './catalog-coverage.js';\nimport { CatalogPublisher } from './catalog-publisher.js';\nimport { systemClock, type Clock } from './clock.js';\nimport { Dispatcher, type DispatcherSettings } from './dispatcher.js';\nimport { toMilliseconds, toTimerMilliseconds, type Duration } from './duration.js';\nimport {\n ConfigurationError,\n InvalidEnvelopeError,\n RelayBusError,\n TransactionRequiredError,\n toErrorInfo,\n} from './errors.js';\nimport {\n assertEventType,\n validatePayload,\n type DomainEvent,\n type EventClass,\n type EventEnvelope,\n type EventHeaders,\n type EventReference,\n} from './event.js';\nimport type {\n AppendEntry,\n DeliveryQuery,\n DeliveryRecord,\n EventStore,\n EventStoreStatistics,\n NewDelivery,\n PurgeResult,\n} from './event-store.js';\nimport { getCurrentScope, runInScope, type ExecutionScope } from './execution-scope.js';\nimport {\n HandlerRegistry,\n type EventHandler,\n type HandlerDescriptor,\n type HandlerRegistration,\n type RegistrationDefaults,\n type SubscribeOptions,\n} from './handler-registry.js';\nimport { createUuidV7, type IdentifierGenerator } from './identifier.js';\nimport { Notifier } from './notifier.js';\nimport type { RelayBusLogger, RelayBusObserver } from './observer.js';\nimport {\n DEFAULT_ROUTE_RETRY_POLICY,\n createRetryPolicy,\n type RetryPolicyOptions,\n} from './retry-policy.js';\nimport type { StandardSchemaV1 } from './standard-schema.js';\nimport type { Transport } from './transport.js';\n\n/**\n * - `required`: `publish` throws {@link TransactionRequiredError} when it finds no transaction.\n * - `optional`: `publish` opens its own transaction instead. The event is still durable,\n * but no longer atomic with business writes made outside that transaction.\n */\nexport type TransactionMode = 'required' | 'optional';\n\n/**\n * What `publish` does with an event that has no handler or route in this\n * process. Deliveries are created from the publisher's registrations, so a\n * process must register every handler and route of the events it publishes.\n * - `warn`: log a warning and store nothing.\n * - `throw`: throw a {@link ConfigurationError}, rolling back the caller's transaction.\n */\nexport type UnroutedEventPolicy = 'warn' | 'throw';\n\nexport interface DispatcherOptions {\n /** Run handlers in this process. Disable on publish-only processes. Default true. */\n readonly enabled?: boolean;\n /** Maximum handlers running at once. Default 10. */\n readonly concurrency?: number;\n /** Maximum deliveries claimed per query. Default equals concurrency. */\n readonly batchSize?: number;\n /** Wait between claims when idle. Retries are picked up on this cadence. Default `'1s'`. */\n readonly pollInterval?: Duration;\n /** Lease length; renewed every third of it while the handler runs. Default `'30s'`. */\n readonly leaseDuration?: Duration;\n /** How long `stop` waits for running handlers before aborting them. Default `'30s'`. */\n readonly shutdownTimeout?: Duration;\n /**\n * Longest a finished delivery waits so that deliveries finishing around the\n * same time are completed with one store call (when the store supports it).\n * A delivery that finishes while nothing else runs is completed at once.\n * `0` completes every delivery on its own. Default `'2ms'`.\n */\n readonly completionBatchWindow?: Duration;\n /** Most deliveries completed in one store call. Default 200. */\n readonly completionBatchSize?: number;\n}\n\nexport interface RetentionOptions {\n /**\n * Delete completed deliveries older than this. Default `'7d'`; `false` keeps them.\n * Deduplication of received events and of publishes with a caller-supplied id\n * only lasts as long as the event is kept: keep this longer than any broker\n * redelivery or publish retry window.\n */\n readonly completed?: Duration | false;\n /** Delete dead deliveries older than this. Default `false` (keep for inspection). */\n readonly dead?: Duration | false;\n /** How often the cleanup runs. Default `'1h'`. */\n readonly interval?: Duration;\n}\n\nexport interface RouteOptions {\n /** Event class or type forwarded to the transport. */\n readonly event: EventReference;\n /** Name of a configured transport. */\n readonly transport: string;\n /** Topic, exchange or queue. Default: the event type. */\n readonly destination?: string;\n /** Default: retry until the broker accepts the event, at most every 5 minutes. */\n readonly retry?: RetryPolicyOptions;\n /** Abort a publish that hangs and retry it. Default `'30s'`. */\n readonly timeout?: Duration;\n}\n\nexport interface InboundSubscriptionOptions {\n readonly transport: string;\n readonly destinations: readonly string[];\n}\n\nexport interface RelayBusOptions<TTransaction = unknown> {\n readonly store: EventStore<TTransaction>;\n /** Name of this service, recorded on every event. Default `'relaybus'`. */\n readonly source?: string;\n /** Default `'required'`. */\n readonly transactionMode?: TransactionMode;\n /**\n * Finds the caller's active transaction when none is passed to `publish`\n * and none was opened with `bus.transaction`, for example from\n * `@nestjs-cls/transactional`. Return undefined when there is none.\n */\n readonly transactionResolver?: () => TTransaction | undefined;\n /** Default `'warn'`. */\n readonly unroutedEvents?: UnroutedEventPolicy;\n /** Default retry policy of every handler. Routes have their own default. */\n readonly retry?: RetryPolicyOptions;\n /** Default handler timeout. Default `false` (no timeout). */\n readonly handlerTimeout?: Duration | false;\n readonly dispatcher?: DispatcherOptions;\n readonly retention?: RetentionOptions;\n readonly transports?: readonly Transport[];\n /** Events forwarded to brokers after they commit. */\n readonly routes?: readonly RouteOptions[];\n /** Broker destinations whose events are stored and dispatched to local handlers. */\n readonly subscriptions?: readonly InboundSubscriptionOptions[];\n /** Create tables and indexes on start. Default true. */\n readonly setupStore?: boolean;\n readonly observers?: readonly RelayBusObserver[];\n /** Default: `console`. */\n readonly logger?: RelayBusLogger;\n readonly clock?: Clock;\n readonly generateIdentifier?: IdentifierGenerator;\n readonly random?: () => number;\n /**\n * Catalogs this process is checked against when it starts. `start()` throws a\n * {@link ConfigurationError} listing every event that is not covered:\n * - a catalog: every event needs a handler or a route;\n * - `consume(catalog, { events })`: each declared event needs a local handler;\n * - `produce(catalog, { events })`: each declared event needs a route to a transport.\n *\n * See `registerCatalog`.\n */\n readonly catalogs?: readonly (Catalog | CatalogDeclaration)[];\n}\n\nexport interface PublishOptions<TTransaction = unknown> {\n /** Transaction to write into. Default: the current scope, then `transactionResolver`. */\n readonly transaction?: TTransaction;\n /**\n * Ordering and partition key. Events with the same key are handled one at a\n * time per handler, in commit order. A delayed or retrying event holds back\n * later events of its key.\n */\n readonly key?: string;\n /** Deliver no earlier than this delay from now. */\n readonly delay?: Duration;\n readonly headers?: EventHeaders;\n /**\n * Default: inherited from the event being handled, otherwise the id of the\n * first published event (shared by every event of a `publishAll` call).\n */\n readonly correlationId?: string;\n}\n\nexport interface PublishOneOptions<TTransaction = unknown> extends PublishOptions<TTransaction> {\n /**\n * Event id. Pass a deterministic id (for example derived from a business key)\n * to make publishing idempotent: when an event with this id is already\n * stored, nothing is written and the stored event is left unchanged.\n */\n readonly id?: string;\n}\n\nexport type ReceiveStatus = 'accepted' | 'duplicate' | 'ignored';\n\ntype BusState = 'idle' | 'starting' | 'running' | 'stopping' | 'stopped';\n\nconst DEFAULTS = {\n concurrency: 10,\n pollInterval: '1s',\n leaseDuration: '30s',\n shutdownTimeout: '30s',\n completionBatchWindow: '2ms',\n completionBatchSize: 200,\n completedRetention: '7d',\n retentionInterval: '1h',\n routeTimeoutMs: 30_000,\n} as const;\n\nconst TRANSPORT_HANDLER_PREFIX = 'relaybus.transport';\nconst WAKE_DELAY_MS = 25;\n\n/**\n * Reliable event bus: events are stored with business data in one transaction,\n * then dispatched to every subscribed handler and route with independent\n * retries, leases and dead-lettering. A bus instance can be started once.\n */\nexport class RelayBus<TTransaction = unknown> {\n readonly #store: EventStore<TTransaction>;\n readonly #source: string;\n readonly #transactionMode: TransactionMode;\n readonly #transactionResolver: (() => TTransaction | undefined) | undefined;\n readonly #unroutedEvents: UnroutedEventPolicy;\n readonly #registry = new HandlerRegistry();\n readonly #defaults: RegistrationDefaults;\n readonly #transports = new Map<string, Transport>();\n readonly #subscriptions: readonly InboundSubscriptionOptions[];\n readonly #notifier: Notifier;\n readonly #logger: RelayBusLogger;\n readonly #clock: Clock;\n readonly #generateIdentifier: IdentifierGenerator;\n readonly #dispatcher: Dispatcher;\n readonly #dispatcherEnabled: boolean;\n readonly #catalogRequirements: CatalogRequirement[] = [];\n readonly #setupStore: boolean;\n readonly #retention: { completedMs: number | null; deadMs: number | null; intervalMs: number };\n #retentionTimer: NodeJS.Timeout | undefined;\n #state: BusState = 'idle';\n #starting: Promise<void> | undefined;\n #stopping: Promise<void> | undefined;\n\n constructor(options: RelayBusOptions<TTransaction>) {\n this.#store = options.store;\n this.#source = options.source ?? 'relaybus';\n this.#transactionMode = oneOf(\n options.transactionMode ?? 'required',\n ['required', 'optional'],\n 'transactionMode',\n );\n this.#unroutedEvents = oneOf(\n options.unroutedEvents ?? 'warn',\n ['warn', 'throw'],\n 'unroutedEvents',\n );\n this.#transactionResolver = options.transactionResolver;\n this.#defaults = {\n retry: createRetryPolicy(options.retry),\n timeoutMs:\n options.handlerTimeout === undefined || options.handlerTimeout === false\n ? null\n : toTimerMilliseconds(options.handlerTimeout, 'handlerTimeout'),\n };\n this.#logger = options.logger ?? console;\n this.#notifier = new Notifier(options.observers ?? [], this.#logger);\n this.#clock = options.clock ?? systemClock;\n this.#generateIdentifier = options.generateIdentifier ?? (() => createUuidV7());\n this.#setupStore = options.setupStore ?? true;\n this.#retention = createRetentionSettings(options.retention);\n for (const transport of options.transports ?? []) {\n if (this.#transports.has(transport.name)) {\n throw new ConfigurationError(`Transport name '${transport.name}' is used twice`);\n }\n this.#transports.set(transport.name, transport);\n }\n for (const route of options.routes ?? []) {\n this.#registerRoute(route);\n }\n this.#subscriptions = options.subscriptions ?? [];\n for (const subscription of this.#subscriptions) {\n const transport = this.#requireTransport(subscription.transport);\n if (transport.subscribe === undefined) {\n throw new ConfigurationError(`Transport '${transport.name}' cannot subscribe`);\n }\n }\n for (const catalog of options.catalogs ?? []) {\n this.registerCatalog(catalog);\n }\n this.#dispatcherEnabled = options.dispatcher?.enabled ?? true;\n this.#dispatcher = new Dispatcher({\n store: this.#store,\n registry: this.#registry,\n clock: this.#clock,\n random: options.random ?? Math.random,\n notifier: this.#notifier,\n settings: createDispatcherSettings(options.dispatcher, this.#generateIdentifier),\n });\n }\n\n get store(): EventStore<TTransaction> {\n return this.#store;\n }\n\n get isRunning(): boolean {\n return this.#state === 'running';\n }\n\n /** True while the bus runs and every transport reports itself ready. */\n isReady(): boolean {\n if (this.#state !== 'running') {\n return false;\n }\n for (const transport of this.#transports.values()) {\n if (transport.isReady?.() === false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Subscribes a handler to an event class or type. Register handlers in every\n * process that publishes the event: deliveries are created at publish time\n * from the publisher's registrations.\n */\n subscribe<TPayload>(\n event: EventClass<TPayload>,\n handler: EventHandler<TPayload, TTransaction>,\n options: SubscribeOptions,\n ): void;\n subscribe(\n eventType: string,\n handler: EventHandler<unknown, TTransaction>,\n options: SubscribeOptions,\n ): void;\n subscribe(\n event: EventClass<unknown> | string,\n handler: EventHandler<unknown, TTransaction>,\n options: SubscribeOptions,\n ): void {\n const { type, schema } = describeEvent(event);\n this.#registry.register(\n {\n eventType: type,\n schema,\n handle: handler as EventHandler,\n options,\n forwardsToTransport: false,\n },\n this.#defaults,\n );\n }\n\n /**\n * Subscribes the `on${EventName}` methods of `handlers` to the events of\n * `catalog`, or to the events named in `options.events`, with the stable\n * handler ids `${prefix}.on${EventName}`. The prefix is `options.idPrefix`,\n * else the catalog name, else the class name of `handlers`. Methods run with\n * `this` bound to `handlers`; methods of events that are not selected are\n * ignored. A missing handler of a selected event fails to compile, and\n * throws {@link ConfigurationError} at runtime, as does an invalid or taken\n * id; handlers registered before the failure stay registered.\n *\n * ```ts\n * bus.subscribeCatalog(OrderEvents, new BillingHandlers(), { events: ['OrderPlaced'] });\n * ```\n */\n subscribeCatalog<TCatalog extends Catalog, const TName extends keyof TCatalog>(\n catalog: TCatalog,\n handlers: NoInfer<HandlersOf<TCatalog, TName, TTransaction>>,\n options: SubscribeCatalogOptions<NoInfer<TCatalog>, TName> & {\n readonly events: readonly TName[];\n },\n ): void;\n /** Without a statically known `events` list, every handler of the catalog is required. */\n subscribeCatalog<TCatalog extends Catalog>(\n catalog: TCatalog,\n handlers: HandlersOf<TCatalog, keyof TCatalog, TTransaction>,\n options?: SubscribeCatalogOptions<NoInfer<TCatalog>>,\n ): void;\n subscribeCatalog<TCatalog extends Catalog>(\n catalog: TCatalog,\n handlers: object,\n options: SubscribeCatalogOptions<TCatalog, keyof TCatalog> = {},\n ): void {\n for (const binding of resolveCatalogHandlers(catalog, handlers, options)) {\n this.subscribe(binding.eventClass as EventClass<unknown>, binding.handle, binding.options);\n }\n }\n\n /**\n * Adds a catalog, or a `consume` / `produce` declaration, to the checks\n * `start()` runs; `start()` throws a {@link ConfigurationError} naming each\n * event that is not covered and what it lacks. Equivalent to the `catalogs`\n * option.\n */\n registerCatalog(catalog: Catalog | CatalogDeclaration): void {\n this.#catalogRequirements.push(toCatalogRequirement(catalog));\n }\n\n /**\n * A view of this bus that publishes only the events of `catalog`, or only\n * the events named in `options.events` (for example the events this service\n * produces). Other events fail to compile and are rejected at runtime.\n */\n forCatalog<TCatalog extends Catalog, const TName extends keyof TCatalog = keyof TCatalog>(\n catalog: TCatalog,\n options: CatalogEventSelection<TName> = {},\n ): CatalogPublisher<TCatalog, TTransaction, TName> {\n return new CatalogPublisher<TCatalog, TTransaction, TName>(catalog, this, options);\n }\n\n /** Registered handlers and routes, for diagnostics. */\n handlers(): readonly HandlerDescriptor[] {\n return this.#registry.all().map(toDescriptor);\n }\n\n /**\n * Stores an event in the current transaction. Handlers run after the\n * transaction commits. Returns the envelope that was written, or that would\n * have been written when the id already exists.\n */\n async publish<TPayload>(\n event: DomainEvent<TPayload>,\n options: PublishOneOptions<TTransaction> = {},\n ): Promise<EventEnvelope<TPayload>> {\n const [envelope] = await this.#publish([event], options, options.id);\n return envelope as EventEnvelope<TPayload>;\n }\n\n /** Stores several events atomically, in order, sharing one correlation id. */\n async publishAll(\n events: readonly DomainEvent[],\n options: PublishOptions<TTransaction> = {},\n ): Promise<EventEnvelope[]> {\n return this.#publish(events, options, undefined);\n }\n\n /**\n * Runs `work` in a new store transaction. `publish` calls inside it join the\n * transaction without passing it explicitly.\n */\n async transaction<T>(work: (transaction: TTransaction) => Promise<T>): Promise<T> {\n return this.#store.transaction((transaction) =>\n runInScope({ transaction }, () => work(transaction)),\n );\n }\n\n /**\n * Stores an event received from a broker and schedules it for local handlers.\n * Idempotent on the event id. Transports call it and acknowledge the message\n * only after it resolves. Throws {@link InvalidEnvelopeError} for malformed\n * events, which transports should dead-letter instead of redelivering.\n */\n async receive(envelope: EventEnvelope): Promise<ReceiveStatus> {\n const normalized = normalizeEnvelope(envelope);\n const registrations = this.#registry\n .forEventType(normalized.type)\n .filter((registration) => !registration.forwardsToTransport);\n if (registrations.length === 0) {\n this.#notifier.notify('onReceived', { envelope: normalized, status: 'ignored' });\n return 'ignored';\n }\n const now = this.#clock.now();\n const entry: AppendEntry = {\n event: normalized,\n deliveries: registrations.map((registration) => this.#createDelivery(registration, now)),\n };\n const result = await this.#store.transaction((transaction) =>\n this.#store.append(transaction, [entry], now),\n );\n const status: ReceiveStatus = result.duplicateEventIds.length > 0 ? 'duplicate' : 'accepted';\n this.#notifier.notify('onReceived', { envelope: normalized, status });\n if (result.appendedDeliveryCount > 0) {\n this.#scheduleWake();\n }\n return status;\n }\n\n /**\n * Creates the store schema, connects transports, subscribes and starts\n * dispatching. A bus starts once: after a failed start or a stop it is\n * stopped for good, because its transports are closed; create a new instance.\n */\n async start(): Promise<void> {\n if (this.#state !== 'idle') {\n throw new RelayBusError(\n this.#state === 'stopped'\n ? 'A stopped relaybus cannot be started again; create a new instance'\n : `Cannot start a relaybus that is ${this.#state}`,\n );\n }\n // Before any side effect, so a failed check leaves the bus idle and startable.\n assertCatalogsCovered(this.#catalogRequirements, (type) => this.#registrationsOf(type));\n this.#state = 'starting';\n this.#starting = this.#startComponents();\n try {\n await this.#starting;\n } finally {\n this.#starting = undefined;\n }\n }\n\n /**\n * Stops dispatching, waits for running handlers, closes transports and the\n * store. Waits for a start in progress first. Safe to call more than once.\n */\n async stop(): Promise<void> {\n if (this.#stopping !== undefined) {\n return this.#stopping;\n }\n if (this.#state === 'starting') {\n await this.#starting!.catch(() => undefined);\n }\n if (this.#state === 'idle') {\n // Batches run by hand may have left settlements that the dispatcher keeps retrying in the background.\n await this.#dispatcher.stop();\n return;\n }\n if (this.#state !== 'running') {\n return;\n }\n this.#stopping = this.#stopComponents();\n return this.#stopping;\n }\n\n /**\n * Claims and runs one batch of due deliveries, resolving when they settle.\n * Returns how many ran. Intended for tests and scripts.\n */\n async runOnce(): Promise<number> {\n return this.#dispatcher.processBatch();\n }\n\n /**\n * Runs batches until nothing is due. Deliveries scheduled in the future\n * (retries, delays) are not waited for. Intended for tests.\n */\n async drain(maxBatches = 1_000): Promise<number> {\n let total = 0;\n for (let batch = 0; batch < maxBatches; batch += 1) {\n const processed = await this.runOnce();\n if (processed === 0) {\n return total;\n }\n total += processed;\n }\n throw new RelayBusError(`drain did not finish within ${maxBatches} batches`);\n }\n\n listDeliveries(query: DeliveryQuery = {}): Promise<DeliveryRecord[]> {\n return this.#store.listDeliveries(query);\n }\n\n /** Moves dead deliveries back to pending with a fresh attempt budget. */\n async requeue(deliveryIds: readonly string[]): Promise<number> {\n const moved = await this.#store.requeue(deliveryIds, this.#clock.now());\n if (moved > 0) {\n this.#dispatcher.wake();\n }\n return moved;\n }\n\n statistics(): Promise<EventStoreStatistics> {\n return this.#store.statistics(this.#clock.now());\n }\n\n /** Applies the retention policy once. Runs automatically while the bus is running. */\n async purgeExpired(): Promise<PurgeResult> {\n const now = this.#clock.now().getTime();\n const { completedMs, deadMs } = this.#retention;\n try {\n const result = await this.#store.purge({\n ...(completedMs === null ? {} : { completedBefore: new Date(now - completedMs) }),\n ...(deadMs === null ? {} : { deadBefore: new Date(now - deadMs) }),\n });\n this.#notifier.notify('onPurged', { result });\n return result;\n } catch (error) {\n this.#notifier.failure('purge', error);\n throw error;\n }\n }\n\n async #startComponents(): Promise<void> {\n try {\n if (this.#setupStore) {\n await this.#store.setup?.();\n }\n for (const transport of this.#transports.values()) {\n await transport.connect?.();\n }\n for (const subscription of this.#subscriptions) {\n const transport = this.#transports.get(subscription.transport)!;\n await transport.subscribe!(subscription.destinations, async (envelope) => {\n await this.receive(envelope);\n });\n }\n } catch (error) {\n await this.#closeTransports();\n this.#state = 'stopped';\n throw error;\n }\n if (this.#dispatcherEnabled) {\n this.#dispatcher.start();\n }\n if (this.#retention.completedMs !== null || this.#retention.deadMs !== null) {\n this.#retentionTimer = setInterval(() => {\n this.purgeExpired().catch(() => undefined);\n }, this.#retention.intervalMs);\n this.#retentionTimer.unref();\n }\n this.#state = 'running';\n this.#logger.log(\n `[RelayBus](start) relaybus started | handlers=${this.#registry.all().length} dispatcher=${this.#dispatcherEnabled}`,\n );\n }\n\n async #stopComponents(): Promise<void> {\n this.#state = 'stopping';\n clearInterval(this.#retentionTimer);\n try {\n await this.#dispatcher.stop();\n await this.#closeTransports();\n await this.#store.close?.();\n } finally {\n this.#state = 'stopped';\n }\n }\n\n async #publish(\n events: readonly DomainEvent[],\n options: PublishOptions<TTransaction>,\n id: string | undefined,\n ): Promise<EventEnvelope[]> {\n if (events.length === 0) {\n return [];\n }\n const now = this.#clock.now();\n const delayMs = options.delay === undefined ? 0 : toMilliseconds(options.delay, 'delay');\n const availableAt = new Date(now.getTime() + delayMs);\n const scope = getCurrentScope();\n const entries: AppendEntry[] = [];\n let correlationId = options.correlationId ?? scope?.event?.correlationId ?? scope?.event?.id;\n for (const event of events) {\n const envelope = await this.#createEnvelope(event, options, id, scope, now, correlationId);\n correlationId = envelope.correlationId!;\n const registrations = this.#registry.forEventType(envelope.type);\n if (registrations.length === 0) {\n this.#reportUnrouted(envelope);\n }\n entries.push({\n event: envelope,\n deliveries: registrations.map((registration) =>\n this.#createDelivery(registration, availableAt),\n ),\n });\n }\n const deliverable = entries.filter((entry) => entry.deliveries.length > 0);\n if (deliverable.length > 0) {\n const result = await this.#appendInTransaction(deliverable, options, scope, now);\n const appended = new Set(result.appendedEventIds);\n const published = deliverable\n .map((entry) => entry.event)\n .filter((envelope) => appended.has(envelope.id));\n if (published.length > 0) {\n this.#notifier.notify('onPublished', {\n envelopes: published,\n deliveries: result.appendedDeliveryCount,\n });\n if (delayMs === 0) {\n this.#scheduleWake();\n }\n }\n }\n return entries.map((entry) => entry.event);\n }\n\n #reportUnrouted(envelope: EventEnvelope): void {\n const message = `No handler or route for event type, event not stored | type=${envelope.type} id=${envelope.id}`;\n if (this.#unroutedEvents === 'throw') {\n throw new ConfigurationError(message);\n }\n this.#logger.warn(`[RelayBus](publish) ${message}`);\n }\n\n async #appendInTransaction(\n entries: readonly AppendEntry[],\n options: PublishOptions<TTransaction>,\n scope: ExecutionScope | undefined,\n now: Date,\n ): Promise<{ appendedEventIds: readonly string[]; appendedDeliveryCount: number }> {\n const transaction =\n options.transaction ??\n (scope?.transaction as TTransaction | undefined) ??\n this.#transactionResolver?.();\n if (transaction !== undefined) {\n return this.#store.append(transaction, entries, now);\n }\n if (this.#transactionMode === 'required') {\n throw new TransactionRequiredError(\n 'publish found no transaction. Pass { transaction }, publish inside bus.transaction(), configure transactionResolver, or set transactionMode to optional',\n );\n }\n return this.#store.transaction((ownTransaction) =>\n this.#store.append(ownTransaction, entries, now),\n );\n }\n\n async #createEnvelope(\n event: DomainEvent,\n options: PublishOptions<TTransaction>,\n id: string | undefined,\n scope: ExecutionScope | undefined,\n now: Date,\n correlationId: string | undefined,\n ): Promise<EventEnvelope> {\n if (typeof event.type !== 'string') {\n throw new ConfigurationError(\n 'publish expects an instance of a class created with defineEvent',\n );\n }\n assertEventType(event.type);\n const schema = (event.constructor as Partial<EventClass>).schema;\n const payload = await validatePayload(event.type, schema, event.payload);\n if (options.key !== undefined && options.key.length === 0) {\n throw new ConfigurationError('key must not be empty');\n }\n const eventId = id ?? this.#generateIdentifier();\n return {\n id: eventId,\n type: event.type,\n source: this.#source,\n key: options.key ?? null,\n payload,\n headers: { ...options.headers },\n correlationId: correlationId ?? eventId,\n causationId: scope?.event?.id ?? null,\n occurredAt: now,\n };\n }\n\n #createDelivery(registration: HandlerRegistration, availableAt: Date): NewDelivery {\n return { id: this.#generateIdentifier(), handler: registration.id, availableAt };\n }\n\n #registrationsOf(eventType: string): EventTypeRegistrations {\n const registrations = this.#registry.forEventType(eventType);\n const routes = registrations.filter((registration) => registration.forwardsToTransport).length;\n return { handlers: registrations.length - routes, routes };\n }\n\n #registerRoute(route: RouteOptions): void {\n const transport = this.#requireTransport(route.transport);\n const { type } = describeEvent(route.event);\n const destination = route.destination ?? type;\n this.#registry.register(\n {\n eventType: type,\n schema: undefined,\n handle: (envelope) => transport.publish(envelope, destination),\n options: {\n id: `${TRANSPORT_HANDLER_PREFIX}:${transport.name}:${destination}:${type}`,\n ...(route.retry === undefined ? {} : { retry: route.retry }),\n ...(route.timeout === undefined ? {} : { timeout: route.timeout }),\n },\n forwardsToTransport: true,\n },\n { retry: DEFAULT_ROUTE_RETRY_POLICY, timeoutMs: DEFAULTS.routeTimeoutMs },\n );\n }\n\n #requireTransport(name: string): Transport {\n const transport = this.#transports.get(name);\n if (transport === undefined) {\n throw new ConfigurationError(`No transport named '${name}' is configured`);\n }\n return transport;\n }\n\n #scheduleWake(): void {\n // A store that reports new deliveries wakes the dispatcher itself, right after the commit.\n if (this.#state !== 'running' || this.#dispatcher.watchesNewDeliveries) {\n return;\n }\n // The publishing transaction commits after publish returns; claim shortly after.\n setTimeout(() => this.#dispatcher.wake(), WAKE_DELAY_MS).unref();\n }\n\n async #closeTransports(): Promise<void> {\n for (const transport of this.#transports.values()) {\n try {\n await transport.close();\n } catch (error) {\n this.#logger.error(\n `[RelayBus](closeTransports) Failed to close transport | transport=${transport.name} error=${toErrorInfo(error).message}`,\n );\n }\n }\n }\n}\n\nfunction toDescriptor(registration: HandlerRegistration): HandlerDescriptor {\n return {\n id: registration.id,\n eventType: registration.eventType,\n retry: registration.retry,\n timeoutMs: registration.timeoutMs,\n concurrency: registration.concurrency,\n transactional: registration.transactional,\n forwardsToTransport: registration.forwardsToTransport,\n };\n}\n\nfunction describeEvent(event: EventReference): {\n type: string;\n schema: StandardSchemaV1 | undefined;\n} {\n if (typeof event === 'string') {\n assertEventType(event);\n return { type: event, schema: undefined };\n }\n assertEventType(event.type);\n return { type: event.type, schema: (event as Partial<EventClass>).schema };\n}\n\n/**\n * Validates an event received from a broker and fills fields that JSON-based\n * wire formats commonly drop (`undefined` key, headers, correlation ids).\n */\nfunction normalizeEnvelope(envelope: EventEnvelope): EventEnvelope {\n if (typeof envelope.id !== 'string' || envelope.id.length === 0) {\n throw new InvalidEnvelopeError('Received event has no id');\n }\n if (typeof envelope.type !== 'string') {\n throw new InvalidEnvelopeError(`Received event ${envelope.id} has no type`);\n }\n try {\n assertEventType(envelope.type);\n } catch (error) {\n throw new InvalidEnvelopeError(toErrorInfo(error).message);\n }\n const occurredAt = toDate(envelope.occurredAt);\n if (occurredAt === undefined) {\n throw new InvalidEnvelopeError(`Received event ${envelope.id} has an invalid occurredAt`);\n }\n return {\n id: envelope.id,\n type: envelope.type,\n source: typeof envelope.source === 'string' ? envelope.source : 'unknown',\n key: optionalText(envelope.key),\n payload: envelope.payload,\n headers: { ...envelope.headers },\n correlationId: optionalText(envelope.correlationId),\n causationId: optionalText(envelope.causationId),\n occurredAt,\n };\n}\n\nfunction toDate(value: Date | string): Date | undefined {\n const date = typeof value === 'string' ? new Date(value) : value;\n return date instanceof Date && !Number.isNaN(date.getTime()) ? date : undefined;\n}\n\nfunction optionalText(value: string | null | undefined): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n\nfunction oneOf<T extends string>(value: T, allowed: readonly T[], name: string): T {\n if (!allowed.includes(value)) {\n throw new ConfigurationError(\n `${name} must be one of ${allowed.map((option) => `'${option}'`).join(', ')}, received '${String(value)}'`,\n );\n }\n return value;\n}\n\nfunction positiveInteger(value: number, name: string): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new ConfigurationError(`${name} must be a positive integer, received ${value}`);\n }\n return value;\n}\n\nfunction createDispatcherSettings(\n options: DispatcherOptions | undefined,\n generateIdentifier: IdentifierGenerator,\n): DispatcherSettings {\n const concurrency = positiveInteger(\n options?.concurrency ?? DEFAULTS.concurrency,\n 'dispatcher.concurrency',\n );\n return {\n owner: `${hostname()}:${process.pid}:${generateIdentifier()}`,\n concurrency,\n batchSize: positiveInteger(options?.batchSize ?? concurrency, 'dispatcher.batchSize'),\n pollIntervalMs: toTimerMilliseconds(\n options?.pollInterval ?? DEFAULTS.pollInterval,\n 'dispatcher.pollInterval',\n ),\n leaseDurationMs: toTimerMilliseconds(\n options?.leaseDuration ?? DEFAULTS.leaseDuration,\n 'dispatcher.leaseDuration',\n ),\n shutdownTimeoutMs: toTimerMilliseconds(\n options?.shutdownTimeout ?? DEFAULTS.shutdownTimeout,\n 'dispatcher.shutdownTimeout',\n ),\n completionBatchWindowMs: toMilliseconds(\n options?.completionBatchWindow ?? DEFAULTS.completionBatchWindow,\n 'dispatcher.completionBatchWindow',\n ),\n completionBatchSize: positiveInteger(\n options?.completionBatchSize ?? DEFAULTS.completionBatchSize,\n 'dispatcher.completionBatchSize',\n ),\n };\n}\n\nfunction createRetentionSettings(options: RetentionOptions | undefined): {\n completedMs: number | null;\n deadMs: number | null;\n intervalMs: number;\n} {\n const completed = options?.completed ?? DEFAULTS.completedRetention;\n const dead = options?.dead ?? false;\n return {\n completedMs: completed === false ? null : toMilliseconds(completed, 'retention.completed'),\n deadMs: dead === false ? null : toMilliseconds(dead, 'retention.dead'),\n intervalMs: toTimerMilliseconds(\n options?.interval ?? DEFAULTS.retentionInterval,\n 'retention.interval',\n ),\n };\n}\n"]}