@relaybus/core 0.1.0 → 0.3.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/duration.ts","../src/catalog.ts","../src/catalog-publisher.ts","../src/catalog-coverage.ts","../src/event-store.ts","../src/identifier.ts","../src/in-memory-transaction.ts","../src/in-memory-event-store.ts","../src/tracing.ts","../src/bus-observation.ts","../src/dispatch-observation.ts","../src/completion-batcher.ts","../src/delivery-timers.ts","../src/dispatcher-support.ts","../src/execution-scope.ts","../src/shutdown-deadline.ts","../src/lease-heartbeat.ts","../src/retry-policy.ts","../src/dispatcher.ts","../src/handler-registry.ts","../src/notifier.ts","../src/received-envelope.ts","../src/relay-bus-settings.ts","../src/route-groups.ts","../src/transaction-budget.ts","../src/relay-bus.ts"],"names":["ConfigurationError","assertEventType","randomBytes","toErrorInfo","InvalidEnvelopeError","schedule","durationMs","AsyncLocalStorage","LeaseLostError","NonRetryableError","DispatcherStoppedError","AttemptsExhaustedError","validatePayload","HandlerTimeoutError","assertPositiveInteger","hostname","TransactionTimeoutError","LifecycleError","DrainIncompleteError","TransactionRequiredError","keyFromDefinition"],"mappings":";;;;;;;;AAiBO,IAAM,WAAA,GAAqB;AAAA,EAChC,GAAA,EAAK,sBAAM,IAAI,IAAA;AACjB;;;ACTA,IAAM,qBAAA,GAAsD;AAAA,EAC1D,EAAA,EAAI,CAAA;AAAA,EACJ,CAAA,EAAG,GAAA;AAAA,EACH,CAAA,EAAG,GAAA;AAAA,EACH,CAAA,EAAG,I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,CAAA;AACrB,IAAA,OAAO,EAAE,IAAA,EAAM,KAAA,EAAO,MAAA,EAAQ,MAAA,EAAU;AAAA,EAC1C;AACA,EAAAA,iCAAA,CAAgB,MAAM,IAAI,CAAA;AAC1B,EAAA,OAAO,EAAE,IAAA,EAAM,KAAA,CAAM,IAAA,EAAM,MAAA,EAAS,MAA8B,MAAA,EAAO;AAC3E","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 * Runs `task.run` after `task.delayMs` milliseconds, again every `delayMs` when `repeat` is set, and\n * returns a function that cancels it. `unref` marks a timer that must not keep the process alive.\n * Optional: without it relaybus uses the platform timers. Implement it to control timers in tests\n * (`FakeClock` does with `controlTimers: true`).\n */\n schedule?(task: {\n readonly run: () => void;\n readonly delayMs: number;\n readonly repeat?: boolean;\n readonly unref?: boolean;\n }): () => void;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\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 } 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 {\n handlers,\n options,\n }: { readonly handlers: object; readonly 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, handlers }: { readonly entries: readonly CatalogEntry[]; readonly 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;\n// eslint-disable-next-line relaybus/max-two-params -- exported API defineHandlers keeps its public signature\nexport function defineHandlers(\n catalog: Catalog,\n handlers: object,\n options: { readonly events?: readonly PropertyKey[] | undefined } = {},\n): object {\n assertExactHandlers(catalog, {\n entries: selectCatalogEntries(catalog, options.events),\n handlers,\n });\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 * `@RelayBusCatalogConsumer`, `@RelayBusConsumer`); 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, { role: '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, { role: 'produce', options });\n}\n\nfunction declare<TCatalog extends Catalog, TName extends keyof TCatalog>(\n catalog: TCatalog,\n { role, options }: { readonly role: CatalogRole; readonly 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, registrations: 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 {\n need,\n registrations: { handlers, routes },\n }: { readonly need: CoverageNeed; readonly registrations: 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/** How `stop` closes a transport or a store. */\nexport interface CloseOptions {\n /**\n * Aborted when the shutdown deadline passes (`bus.stop({ timeout })`), possibly before `close` is\n * called. From then on, close what you opened yourself at once (destroy connections, cancel\n * running queries) instead of waiting for it to finish; the bus no longer waits for `close`.\n * Leave alone what the application passed in.\n */\n readonly signal?: AbortSignal;\n}\n\n/** How a store runs one transaction of `bus.transaction`. */\nexport interface EventStoreTransactionOptions {\n /**\n * Time budget of the whole transaction, in milliseconds. A store makes the database enforce it\n * where it can (for example a statement or idle-in-transaction timeout), so a transaction that\n * waits on something slow is ended by the server and its locks are released. The bus rolls back\n * a transaction that still ran past the budget, so a store may also ignore it.\n */\n readonly timeoutMs: number;\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 /**\n * Runs `work` inside a new database transaction and commits when it resolves. `options` come\n * from `bus.transaction`; the store's own transactions and the dispatcher's pass none.\n */\n transaction<T>(\n work: (transaction: TTransaction) => Promise<T>,\n options?: EventStoreTransactionOptions,\n ): 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; forced once `options.signal` aborts. */\n close?(options?: CloseOptions): Promise<void>;\n}\n","import { randomBytes } from 'node:crypto';\n\nconst UUID_BYTES = 16;\n/** The 48-bit millisecond timestamp fills the first six bytes. */\nconst TIMESTAMP_BYTES = 6;\nconst BYTE_VALUES = 256;\nconst LOW_NIBBLE = 0x0f;\n/** Version 7 in the high nibble of byte 6. */\nconst VERSION_7 = 0x70;\nconst VARIANT_PAYLOAD = 0x3f;\n/** The `10` variant bits in the high bits of byte 8. */\nconst RFC_9562_VARIANT = 0x80;\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(UUID_BYTES);\n let remaining = timestamp;\n for (let index = TIMESTAMP_BYTES - 1; index >= 0; index -= 1) {\n bytes[index] = remaining % BYTE_VALUES;\n remaining = Math.floor(remaining / BYTE_VALUES);\n }\n bytes[6] = (bytes[6]! & LOW_NIBBLE) | VERSION_7;\n bytes[8] = (bytes[8]! & VARIANT_PAYLOAD) | RFC_9562_VARIANT;\n // 8-4-4-4-12 hex digits.\n return bytes.toString('hex').replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n}\n\n/** Produces unique identifiers for events, deliveries and lease tokens. */\nexport type IdentifierGenerator = () => string;\n","import { ConfigurationError } from './errors.js';\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","import { ConfigurationError, type ErrorInfo } from './errors.js';\nimport type {\n AppendEntry,\n AppendResult,\n ClaimRequest,\n ClaimedDelivery,\n DeliveryQuery,\n DeliveryRecord,\n DeliveryStatus,\n EventStore,\n EventStoreStatistics,\n LeaseReference,\n NewDelivery,\n PurgeRequest,\n PurgeResult,\n} from './event-store.js';\nimport type { EventEnvelope } from './event.js';\nimport { createUuidV7, type IdentifierGenerator } from './identifier.js';\nimport { InMemoryTransaction } from './in-memory-transaction.js';\n\nconst DEFAULT_LIST_LIMIT = 100;\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\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\n/** One entry of an append, applied when its transaction commits. */\ntype ApplyAppendInput = {\n readonly eventId: string;\n readonly serialized: SerializedEnvelope;\n readonly isDuplicate: boolean;\n readonly newDeliveries: readonly NewDelivery[];\n readonly now: Date;\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 // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature\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 = this.#newDeliveries(entry, pendingDeliveryKeys);\n appendedDeliveryCount += newDeliveries.length;\n transaction.enqueue(() => {\n this.#applyAppend({ eventId, serialized, isDuplicate, newDeliveries, now });\n });\n }\n return { appendedEventIds, duplicateEventIds, appendedDeliveryCount };\n }\n\n /**\n * The deliveries of `entry` whose handler the event neither has nor gets earlier in the\n * transaction; remembers them in `pendingDeliveryKeys`.\n */\n #newDeliveries(entry: AppendEntry, pendingDeliveryKeys: Set<string>): NewDelivery[] {\n const eventId = entry.event.id;\n return 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 }\n\n /** Applies one entry of an append when its transaction commits. */\n #applyAppend(input: ApplyAppendInput): void {\n const { eventId, serialized, isDuplicate, newDeliveries, now } = input;\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 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 // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature\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 // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature\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 // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature\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 // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature\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 ?? DEFAULT_LIST_LIMIT;\n return [...this.#deliveries.values()]\n .filter((delivery) =>\n matchesQuery(delivery, { event: this.#events.get(delivery.eventId)!, query }),\n )\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 return { deletedDeliveries, deletedEvents: this.#purgeEvents(request, touchedEventIds) };\n }\n\n /** Deletes the events no delivery references whose retention ran out; returns how many. */\n #purgeEvents(request: PurgeRequest, touchedEventIds: ReadonlySet<string>): number {\n const referencedEventIds = new Set(\n [...this.#deliveries.values()].map((delivery) => delivery.eventId),\n );\n const { orphanCutoff, completedCutoff } = eventCutoffs(request);\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 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 (blocksKey(other, { delivery, now })) {\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\n/** Whether `other`, another delivery of the same handler and key, holds `delivery` back. */\nfunction blocksKey(\n other: StoredDelivery,\n { delivery, now }: { readonly delivery: StoredDelivery; readonly now: Date },\n): boolean {\n if (other === delivery || other.handler !== delivery.handler || other.key !== delivery.key) {\n return false;\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 return unfinishedPredecessor || runningUnderLiveLease;\n}\n\n/**\n * The cutoffs of events no delivery references. An event that had a delivery complete is measured\n * from that completion and only by the completed cutoff; any other (dead-lettered or never\n * delivered) from its creation and by the earliest cutoff.\n */\nfunction eventCutoffs(request: PurgeRequest): { orphanCutoff: number; completedCutoff: number } {\n const cutoffs = [request.completedBefore, request.deadBefore]\n .filter((cutoff) => cutoff !== undefined)\n .map((cutoff) => cutoff.getTime());\n return {\n orphanCutoff: cutoffs.length === 0 ? Number.NEGATIVE_INFINITY : Math.min(...cutoffs),\n completedCutoff: request.completedBefore?.getTime() ?? Number.NEGATIVE_INFINITY,\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(\n delivery: StoredDelivery,\n { event, query }: { readonly event: StoredEvent; readonly query: DeliveryQuery },\n): 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 { EventEnvelope, EventHeaders } from './event.js';\nimport type { ClaimedDelivery } from './event-store.js';\n\n/** Event header that carries the W3C trace context (`version-traceid-parentid-flags`). */\nexport const TRACEPARENT_HEADER = 'traceparent';\n/** Event header that carries the vendor part of the W3C trace context. */\nexport const TRACESTATE_HEADER = 'tracestate';\n\n/** A W3C Trace Context as it travels in event headers. */\nexport interface TraceContext {\n readonly traceparent: string;\n readonly tracestate?: string;\n}\n\n/** `<version>-<trace id>-<span id>-<flags>`, lower-case hex, ids not all zero. */\nconst TRACEPARENT_FIELDS = '(?!0{32})[\\\\da-f]{32}-(?!0{16})[\\\\da-f]{16}-[\\\\da-f]{2}';\n/** Version 00 has exactly four fields; later versions (never ff) may append more. */\nconst TRACEPARENT = new RegExp(\n `^(?:00-${TRACEPARENT_FIELDS}|(?!00|ff)[\\\\da-f]{2}-${TRACEPARENT_FIELDS}(?:-.*)?)$`,\n);\n\n/**\n * The W3C trace context an event carries in its headers, or undefined when it has none or a\n * malformed one. A handler or a consumer span continues the publisher's trace from it.\n *\n * ```ts\n * bus.subscribe(OrderPlaced, (event) => startSpan({ parent: traceContextOf(event.headers) }), ...)\n * ```\n */\nexport function traceContextOf(headers: EventHeaders): TraceContext | undefined {\n const traceparent = headers[TRACEPARENT_HEADER];\n if (traceparent === undefined || !TRACEPARENT.test(traceparent)) {\n return undefined;\n }\n const tracestate = headers[TRACESTATE_HEADER];\n return tracestate === undefined ? { traceparent } : { traceparent, tracestate };\n}\n\n/** A `publish` or `publishAll` call. */\nexport interface PublishTraceInput {\n /** The type of every event of the call, in order. */\n readonly eventTypes: readonly string[];\n}\n\n/** A route sending one event to its transport. */\nexport interface SendTraceInput {\n readonly envelope: EventEnvelope;\n readonly transport: string;\n /** The messaging system of the transport (`kafka`, `rabbitmq`), else its name. */\n readonly system: string;\n readonly destination: string;\n}\n\n/** A local handler running for one claimed delivery. */\nexport interface ProcessTraceInput {\n readonly delivery: ClaimedDelivery;\n}\n\n/**\n * Tracing hooks, for example from `@relaybus/otel`. Each one wraps an operation: it starts a span,\n * calls `run` inside it and ends the span when the returned promise settles, passing its result or\n * error through unchanged. relaybus itself depends on no tracing library.\n */\nexport interface RelayBusTracer {\n /**\n * Wraps one publish call. `run` takes the trace headers (`traceparent`, `tracestate`) to write\n * into every event of the call, so its consumers continue the trace; headers passed to\n * `publish` explicitly win.\n */\n publish?<T>(input: PublishTraceInput, run: (headers: EventHeaders) => Promise<T>): Promise<T>;\n /**\n * Wraps one send of a route. `run` takes the trace headers to send the event with, in place of\n * the ones it was stored with, so the consumer's trace continues from this send.\n */\n send?<T>(input: SendTraceInput, run: (headers: EventHeaders) => Promise<T>): Promise<T>;\n /**\n * Wraps one run of a local handler; the handler runs inside `run`, so what it publishes or calls\n * joins the span. The event's own trace context is in `traceContextOf(delivery.event.headers)`.\n */\n process?<T>(input: ProcessTraceInput, run: () => Promise<T>): Promise<T>;\n}\n","import type { Clock } from './clock.js';\nimport { InvalidEnvelopeError, toErrorInfo } from './errors.js';\nimport type { EventStoreStatistics } from './event-store.js';\nimport type { EventEnvelope, EventHeaders } from './event.js';\nimport { schedule, type CancelTimer } from './internal/timers.js';\nimport type { Notifier } from './notifier.js';\nimport type { OperationOutcome, ReceiveOutcome } from './observer.js';\nimport { traceContextOf, type PublishTraceInput, type RelayBusTracer } from './tracing.js';\nimport type { Transport } from './transport.js';\n\ntype BusObservationInput = {\n readonly notifier: Notifier;\n readonly tracer: RelayBusTracer | undefined;\n readonly clock: Clock;\n};\n\n/** The transport and destination an event was received from; undefined for `bus.receive` calls. */\nexport type ReceiveOrigin = {\n readonly transport: Transport;\n readonly destination: string | undefined;\n};\n\n/** One event received from a broker, and where from. */\ntype ReceiveInput = {\n readonly envelope: EventEnvelope;\n readonly origin: ReceiveOrigin | undefined;\n};\n\n/** One send of a route: the event, the transport and its destination. */\ntype SendInput = {\n readonly envelope: EventEnvelope;\n readonly transport: Transport;\n readonly destination: string;\n};\n\n/** How the backlog is read and how often. */\ntype BacklogInput = {\n readonly intervalMs: number;\n readonly statistics: () => Promise<EventStoreStatistics>;\n};\n\n/** `options` with the trace headers added; headers the caller passed win. */\nexport function withTraceHeaders<T extends { readonly headers?: EventHeaders }>(\n options: T,\n headers: EventHeaders,\n): T {\n return Object.keys(headers).length === 0\n ? options\n : { ...options, headers: { ...headers, ...options.headers } };\n}\n\n/**\n * Reports publishes, receives, sends and the backlog to observers and runs them inside the\n * tracer's spans. A bus gets one only when something observes or traces these, so an unobserved\n * bus pays nothing for it.\n */\nexport class BusObservation {\n readonly #notifier: Notifier;\n readonly #tracer: RelayBusTracer | undefined;\n readonly #clock: Clock;\n readonly #publishes: boolean;\n readonly #receives: boolean;\n readonly #sends: boolean;\n\n private constructor(input: BusObservationInput) {\n this.#notifier = input.notifier;\n this.#tracer = input.tracer;\n this.#clock = input.clock;\n this.#publishes = input.notifier.wants('onPublishFinished');\n this.#receives = input.notifier.wants('onReceiveFinished');\n this.#sends = input.notifier.wants('onTransportSent');\n }\n\n /** An observation, or undefined when no observer hook and no tracer would see anything. */\n static create(input: BusObservationInput): BusObservation | undefined {\n const observed =\n input.tracer !== undefined ||\n (['onPublishFinished', 'onReceiveFinished', 'onTransportSent', 'onBacklog'] as const).some(\n (method) => input.notifier.wants(method),\n );\n return observed ? new BusObservation(input) : undefined;\n }\n\n /** Runs a publish call inside the tracer's publish span, reporting its duration and outcome. */\n async publish<T>(\n input: PublishTraceInput,\n run: (headers: EventHeaders) => Promise<T>,\n ): Promise<T> {\n const startedAt = this.#publishes ? this.#now() : 0;\n const tracer = this.#tracer;\n const traced = tracer?.publish === undefined ? run({}) : tracer.publish(input, run);\n if (!this.#publishes) {\n return traced;\n }\n const report = (outcome: OperationOutcome, error?: unknown): void => {\n this.#notifier.notify('onPublishFinished', {\n eventTypes: input.eventTypes,\n durationMs: this.#now() - startedAt,\n outcome,\n ...(error === undefined ? {} : { error: toErrorInfo(error) }),\n });\n };\n try {\n const result = await traced;\n report('success');\n return result;\n } catch (error) {\n report('error', error);\n throw error;\n }\n }\n\n /** Runs `receive` for one event, reporting where it came from and what became of it. */\n async receive<T extends ReceiveOutcome>(input: ReceiveInput, run: () => Promise<T>): Promise<T> {\n if (!this.#receives) {\n return run();\n }\n const startedAt = this.#now();\n try {\n const outcome = await run();\n this.#reportReceive(input, { outcome, startedAt, failure: undefined });\n return outcome;\n } catch (error) {\n const outcome = error instanceof InvalidEnvelopeError ? 'invalid' : 'error';\n this.#reportReceive(input, { outcome, startedAt, failure: error });\n throw error;\n }\n }\n\n #reportReceive(\n { envelope, origin }: ReceiveInput,\n report: { readonly outcome: ReceiveOutcome; readonly startedAt: number; failure: unknown },\n ): void {\n // A malformed event may lack its headers: its trace context is then unknown.\n const { headers } = envelope as Partial<EventEnvelope>;\n this.#notifier.notify('onReceiveFinished', {\n transport: origin?.transport.name,\n system: origin === undefined ? undefined : systemOf(origin.transport),\n destination: origin?.destination,\n eventType: textOrUndefined(envelope.type),\n source: textOrUndefined(envelope.source),\n traceContext: isObject(headers) ? traceContextOf(headers) : undefined,\n outcome: report.outcome,\n durationMs: this.#now() - report.startedAt,\n ...(report.failure === undefined ? {} : { error: toErrorInfo(report.failure) }),\n });\n }\n\n /** The handler of a route: sends inside the tracer's send span and reports each send. */\n sender(transport: Transport, destination: string): (envelope: EventEnvelope) => Promise<void> {\n if (this.#tracer?.send === undefined && !this.#sends) {\n return (envelope) => transport.publish(envelope, destination);\n }\n return (envelope) => this.#send({ envelope, transport, destination });\n }\n\n async #send({ envelope, transport, destination }: SendInput): Promise<void> {\n const startedAt = this.#sends ? this.#now() : 0;\n const system = systemOf(transport);\n const run = (headers: EventHeaders): Promise<void> =>\n transport.publish(\n Object.keys(headers).length === 0\n ? envelope\n : { ...envelope, headers: { ...envelope.headers, ...headers } },\n destination,\n );\n const tracer = this.#tracer;\n const sent =\n tracer?.send === undefined\n ? run({})\n : tracer.send({ envelope, transport: transport.name, system, destination }, run);\n if (!this.#sends) {\n return sent;\n }\n const report = (outcome: OperationOutcome, error?: unknown): void => {\n this.#notifier.notify('onTransportSent', {\n envelope,\n transport: transport.name,\n system,\n destination,\n durationMs: this.#now() - startedAt,\n outcome,\n ...(error === undefined ? {} : { error: toErrorInfo(error) }),\n });\n };\n try {\n await sent;\n report('success');\n } catch (error) {\n report('error', error);\n throw error;\n }\n }\n\n /**\n * Reads the backlog every `intervalMs` and reports it, when an observer wants it. A reading that\n * is still running when the next one is due is not overlapped. Returns the cancel of the timer.\n */\n startBacklog({ intervalMs, statistics }: BacklogInput): CancelTimer | undefined {\n if (!this.#notifier.wants('onBacklog')) {\n return undefined;\n }\n let reading = false;\n return schedule(this.#clock, {\n run: () => {\n if (reading) {\n return;\n }\n reading = true;\n statistics()\n .then((result) => this.#reportBacklog(result))\n .catch((error: unknown) => this.#notifier.failure('backlog', error))\n .finally(() => {\n reading = false;\n });\n },\n delayMs: intervalMs,\n repeat: true,\n unref: true,\n });\n }\n\n #reportBacklog(statistics: EventStoreStatistics): void {\n const oldestDueAt = statistics.oldestDueAt;\n this.#notifier.notify('onBacklog', {\n pending: statistics.pending,\n oldestPendingAgeMs:\n oldestDueAt === null ? 0 : Math.max(0, this.#now() - oldestDueAt.getTime()),\n statistics,\n });\n }\n\n #now(): number {\n return this.#clock.now().getTime();\n }\n}\n\n/** The messaging system of a transport, else its name. */\nfunction systemOf(transport: Transport): string {\n return transport.system ?? transport.name;\n}\n\nfunction textOrUndefined(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction isObject(value: unknown): value is EventHeaders {\n return typeof value === 'object' && value !== null;\n}\n","import type { Clock } from './clock.js';\nimport { toErrorInfo } from './errors.js';\nimport type { ClaimRequest, ClaimedDelivery, EventStore } from './event-store.js';\nimport type { HandlerRegistration } from './handler-registry.js';\nimport type { Notifier } from './notifier.js';\nimport type { DeliveryKind } from './observer.js';\nimport type { RelayBusTracer } from './tracing.js';\n\n/** One run of a handler for a claimed delivery. */\nexport type HandlerRun = {\n readonly registration: HandlerRegistration;\n readonly delivery: ClaimedDelivery;\n};\n\ntype DispatchObservationInput = {\n readonly notifier: Notifier;\n readonly tracer: RelayBusTracer | undefined;\n readonly clock: Clock;\n};\n\n/**\n * Reports the dispatcher's claims and handler runs to observers and wraps local handlers in the\n * tracer's process span. The dispatcher gets one only when something observes or traces, so an\n * unobserved bus pays nothing for it.\n */\nexport class DispatchObservation {\n readonly #notifier: Notifier;\n readonly #tracer: RelayBusTracer | undefined;\n readonly #clock: Clock;\n readonly #claims: boolean;\n readonly #runs: boolean;\n\n private constructor(input: DispatchObservationInput) {\n this.#notifier = input.notifier;\n this.#tracer = input.tracer;\n this.#clock = input.clock;\n this.#claims = input.notifier.wants('onClaimFinished');\n this.#runs =\n input.notifier.wants('onHandlerStarted') || input.notifier.wants('onHandlerFinished');\n }\n\n /** An observation, or undefined when no observer hook and no tracer would see anything. */\n static create(input: DispatchObservationInput): DispatchObservation | undefined {\n const observation = new DispatchObservation(input);\n return observation.#claims || observation.#runs || input.tracer?.process !== undefined\n ? observation\n : undefined;\n }\n\n /** Claims through `store`, reporting the query's size, lanes and duration. */\n async claim(store: EventStore, request: ClaimRequest): Promise<ClaimedDelivery[]> {\n if (!this.#claims) {\n return store.claim(request);\n }\n const startedAt = this.#clock.now().getTime();\n const report = { handlers: request.handlers, requested: request.limit };\n try {\n const claimed = await store.claim(request);\n this.#notifier.notify('onClaimFinished', {\n ...report,\n claimed: claimed.length,\n lanes: new Set(claimed.map((delivery) => delivery.leaseToken)).size,\n durationMs: this.#clock.now().getTime() - startedAt,\n outcome: 'success',\n });\n return claimed;\n } catch (error) {\n this.#notifier.notify('onClaimFinished', {\n ...report,\n claimed: 0,\n lanes: 0,\n durationMs: this.#clock.now().getTime() - startedAt,\n outcome: 'error',\n error: toErrorInfo(error),\n });\n throw error;\n }\n }\n\n /** Runs a local handler inside the tracer's process span; routes are traced as sends instead. */\n process(run: HandlerRun, handle: () => unknown): unknown {\n const tracer = this.#tracer;\n if (tracer?.process === undefined || run.registration.forwardsToTransport) {\n return handle();\n }\n return tracer.process({ delivery: run.delivery }, async () => handle());\n }\n\n /** Reports the start of a handler run now and its end when `settled` settles, passing it through. */\n async observe(run: HandlerRun, settled: Promise<unknown>): Promise<void> {\n if (!this.#runs) {\n await settled;\n return;\n }\n const { delivery } = run;\n const kind: DeliveryKind = run.registration.forwardsToTransport ? 'route' : 'handler';\n const startedAt = this.#clock.now().getTime();\n this.#notifier.notify('onHandlerStarted', {\n delivery,\n kind,\n endToEndLatencyMs: startedAt - delivery.event.occurredAt.getTime(),\n });\n try {\n await settled;\n } catch (error) {\n const durationMs = this.#clock.now().getTime() - startedAt;\n const errorInfo = toErrorInfo(error);\n this.#notifier.notify('onHandlerFinished', {\n delivery,\n kind,\n durationMs,\n outcome: 'error',\n error: errorInfo,\n });\n throw error;\n }\n const durationMs = this.#clock.now().getTime() - startedAt;\n this.#notifier.notify('onHandlerFinished', { delivery, kind, durationMs, outcome: 'success' });\n }\n}\n","import type { Clock } from './clock.js';\nimport type { EventStore, LeaseReference } from './event-store.js';\nimport { schedule, type CancelTimer } from './internal/timers.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: CancelTimer | 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 ??= schedule(this.#clock, {\n run: () => this.#flush(),\n delayMs: this.#settings.windowMs,\n });\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 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 type { Clock } from './clock.js';\nimport { schedule, type CancelTimer } from './internal/timers.js';\n\n/**\n * The timers of running deliveries (handler timeouts, waits between completion retries). A stop that\n * abandons the deliveries cancels them all, so none keeps the process alive or acts after the stop.\n */\nexport class DeliveryTimers {\n readonly #clock: Clock;\n /** Cancel of every timer still waiting, with what its cancellation must also do. */\n readonly #waiting = new Map<CancelTimer, () => void>();\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n /** Runs `task.run` after `task.delayMs`; returns what cancels it. */\n start(task: { readonly run: () => void; readonly delayMs: number }): CancelTimer {\n return this.#start(task, () => undefined);\n }\n\n /** Resolves after `milliseconds`, or at once when {@link DeliveryTimers.cancelAll} runs. */\n sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => {\n this.#start({ run: resolve, delayMs: milliseconds }, resolve);\n });\n }\n\n cancelAll(): void {\n for (const [cancel, onCancel] of [...this.#waiting]) {\n cancel();\n onCancel();\n }\n }\n\n #start(\n task: { readonly run: () => void; readonly delayMs: number },\n onCancel: () => void,\n ): CancelTimer {\n const cancel = (): void => {\n cancelTimer();\n this.#waiting.delete(cancel);\n };\n const cancelTimer = schedule(this.#clock, {\n run: () => {\n this.#waiting.delete(cancel);\n task.run();\n },\n delayMs: task.delayMs,\n });\n this.#waiting.set(cancel, onCancel);\n return cancel;\n }\n}\n","import type { ClaimedDelivery } from './event-store.js';\n\n// Small helpers of the Dispatcher, kept apart to hold dispatcher.ts under the file size limit.\n\n/** Settlements are pending per claim: an older claim of a delivery must never replace or remove the newer one's. */\nexport function pendingKey(delivery: ClaimedDelivery): string {\n return `${delivery.deliveryId}\\u0000${delivery.leaseToken}`;\n}\n\nexport function 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 { 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 type { Clock } from './clock.js';\nimport type { Duration } from './duration.js';\nimport { schedule, type CancelTimer } from './internal/timers.js';\n\nexport interface StopOptions {\n /**\n * Longest the whole `stop` may take. Default: `dispatcher.shutdownTimeout`. Keep it below the time\n * the platform waits before killing the process (Kubernetes `terminationGracePeriodSeconds`).\n */\n readonly timeout?: Duration;\n}\n\n/** How a `stop` went. */\nexport interface StopResult {\n /** False when the deadline passed and `stop` aborted handlers or force-closed connections. */\n readonly graceful: boolean;\n /**\n * Deliveries whose handlers still ran at the deadline. Their leases expire after\n * `dispatcher.leaseDuration` and another process runs them again (at-least-once).\n */\n readonly abandonedDeliveries: number;\n /** Time `stop` took, on the bus clock. */\n readonly durationMs: number;\n}\n\n/**\n * Share of the shutdown timeout running handlers get before they are aborted. The rest is left for\n * releasing their deliveries, handing back leases and closing transports and the store.\n */\nconst DRAIN_SHARE = 0.8;\n\n/**\n * The deadline of one `stop`. Running handlers are waited for until the drain point (four fifths of\n * the timeout), every other wait until the deadline itself, and the signal, aborted when the deadline\n * passes, tells the transports and the store to force-close what they opened themselves.\n */\nexport class ShutdownDeadline {\n readonly #controller = new AbortController();\n readonly #drained: Promise<'timeout'>;\n readonly #expired: Promise<'timeout'>;\n readonly #cancelTimers: CancelTimer[];\n\n constructor(clock: Clock, timeoutMs: number) {\n let drain!: () => void;\n this.#drained = new Promise((resolve) => {\n drain = () => resolve('timeout');\n });\n const signal = this.#controller.signal;\n this.#expired = new Promise((resolve) => {\n signal.addEventListener('abort', () => resolve('timeout'), { once: true });\n });\n this.#cancelTimers = [\n schedule(clock, { run: drain, delayMs: Math.floor(timeoutMs * DRAIN_SHARE) }),\n schedule(clock, { run: () => this.#controller.abort(), delayMs: timeoutMs }),\n ];\n }\n\n /** Aborted when the deadline passes. */\n get signal(): AbortSignal {\n return this.#controller.signal;\n }\n\n get passed(): boolean {\n return this.#controller.signal.aborted;\n }\n\n /** Waits for `work` until the deadline. Rejects when `work` rejects before it. */\n race(work: Promise<unknown>): Promise<'done' | 'timeout'> {\n return Promise.race([work.then(() => 'done' as const), this.#expired]);\n }\n\n /** Waits for running handlers until the drain point, when they are aborted. */\n raceDrain(work: Promise<unknown>): Promise<'done' | 'timeout'> {\n return Promise.race([work.then(() => 'done' as const), this.#drained]);\n }\n\n /** Cancels the timers once the shutdown is over. */\n dispose(): void {\n for (const cancel of this.#cancelTimers) {\n cancel();\n }\n }\n}\n\n/**\n * Runs one shutdown under a deadline of `timeoutMs` on `clock`. `work` resolves with the deliveries it\n * abandoned; the result says whether the deadline passed and how long it all took.\n */\nexport async function withinDeadline(\n { clock, timeoutMs }: { readonly clock: Clock; readonly timeoutMs: number },\n work: (deadline: ShutdownDeadline) => Promise<number>,\n): Promise<StopResult> {\n const startedAt = clock.now().getTime();\n const deadline = new ShutdownDeadline(clock, timeoutMs);\n try {\n const abandonedDeliveries = await work(deadline);\n return {\n graceful: !deadline.passed,\n abandonedDeliveries,\n durationMs: clock.now().getTime() - startedAt,\n };\n } finally {\n deadline.dispose();\n }\n}\n","import type { Clock } from './clock.js';\nimport { LeaseLostError } from './errors.js';\nimport type { ClaimedDelivery, EventStore } from './event-store.js';\nimport { schedule } from './internal/timers.js';\nimport type { Notifier } from './notifier.js';\n\n/** Lease renewals per lease duration. */\nconst RENEWALS_PER_LEASE = 3;\n\n/** What the heartbeat needs of the dispatcher. */\ntype HeartbeatDependencies = {\n readonly store: EventStore;\n readonly clock: Clock;\n readonly notifier: Notifier;\n readonly settings: { readonly leaseDurationMs: number };\n};\n\n/** The delivery whose lease is kept and the controller that aborts its handler. */\ntype HeartbeatTarget = {\n readonly delivery: ClaimedDelivery;\n readonly controller: AbortController;\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). Returns a function that stops it.\n */\nexport function startLeaseHeartbeat(\n { store, clock, notifier, settings }: HeartbeatDependencies,\n { delivery, controller }: HeartbeatTarget,\n): () => void {\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 return schedule(clock, {\n run: () => {\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 delayMs: Math.max(1, Math.floor(settings.leaseDurationMs / RENEWALS_PER_LEASE)),\n repeat: true,\n unref: true,\n });\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 policy = mergeRetryPolicy(options, base);\n assertValidRetryPolicy(policy);\n return policy;\n}\n\n/** `options` over `base`, durations converted, without validation. */\nfunction mergeRetryPolicy(options: RetryPolicyOptions | undefined, base: RetryPolicy): RetryPolicy {\n const overrides: RetryPolicyOptions = options ?? {};\n const initialDelayMs =\n overrides.initialDelay === undefined\n ? base.initialDelayMs\n : toMilliseconds(overrides.initialDelay, 'retry.initialDelay');\n return {\n attempts: overrides.attempts ?? base.attempts,\n initialDelayMs,\n factor: overrides.factor ?? base.factor,\n maxDelayMs:\n overrides.maxDelay === undefined\n ? // Raising only the initial delay must not trip the inherited cap.\n Math.max(base.maxDelayMs, initialDelayMs)\n : toMilliseconds(overrides.maxDelay, 'retry.maxDelay'),\n jitter: overrides.jitter ?? base.jitter,\n retryIf: overrides.retryIf ?? base.retryIf,\n };\n}\n\nfunction assertValidRetryPolicy(policy: RetryPolicy): void {\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}\n\n/**\n * Delay before the next attempt after `failedAttempts` failures (1-based):\n * capped exponential backoff with the policy's jitter.\n */\n// eslint-disable-next-line relaybus/max-two-params -- exported API computeRetryDelay keeps its public signature\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 { DeliveryTimers } from './delivery-timers.js';\nimport type { DispatchObservation } from './dispatch-observation.js';\nimport { pendingKey, rejectOnAbort } from './dispatcher-support.js';\nimport {\n DispatcherStoppedError,\n HandlerTimeoutError,\n LeaseLostError,\n AttemptsExhaustedError,\n toErrorInfo,\n} from './errors.js';\nimport { schedule, type CancelTimer } from './internal/timers.js';\nimport { validatePayload, type EventEnvelope } from './event.js';\nimport type { ClaimedDelivery, EventStore } from './event-store.js';\nimport { runInIsolatedScope } from './execution-scope.js';\nimport { ShutdownDeadline } from './shutdown-deadline.js';\nimport type { HandlerContext, HandlerRegistration, HandlerRegistry } from './handler-registry.js';\nimport { startLeaseHeartbeat } from './lease-heartbeat.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 /** Reports claims and handler runs; absent when nothing observes or traces them. */\n readonly observation?: DispatchObservation | undefined;\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 FIRST_COMPLETION_RETRY_MS = 50;\nconst SECOND_COMPLETION_RETRY_MS = 250;\nconst LAST_COMPLETION_RETRY_MS = 1_000;\nconst COMPLETION_RETRY_DELAYS_MS = [\n FIRST_COMPLETION_RETRY_MS,\n SECOND_COMPLETION_RETRY_MS,\n LAST_COMPLETION_RETRY_MS,\n] 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\n/** One run of a handler: the delivery, its validated event and the transaction it runs in, if any. */\ntype InvokeInput = {\n readonly registration: HandlerRegistration;\n readonly event: EventEnvelope;\n readonly delivery: ClaimedDelivery;\n readonly controller: AbortController;\n readonly transaction: unknown;\n};\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: CancelTimer | 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: CancelTimer | undefined;\n #refillScheduled = false;\n #quietRefillTimer: CancelTimer | undefined;\n #unwatch: (() => Promise<void>) | undefined;\n #watching: Promise<void> | undefined;\n /** Set when a stop gave up at its deadline: the store may be closed, so nothing more is started or retried. */\n #abandoned = false;\n /** Stops the lease renewal (or transactional lease guard) of each delivery whose handler runs. */\n readonly #leaseKeepers = new Map<ClaimedDelivery, () => void>();\n readonly #timers: DeliveryTimers;\n\n constructor(dependencies: DispatcherDependencies) {\n this.#dependencies = dependencies;\n this.#timers = new DeliveryTimers(dependencies.clock);\n this.#sleep = dependencies.sleep ?? ((milliseconds) => this.#timers.sleep(milliseconds));\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 ??= schedule(this.#dependencies.clock, {\n run: () => {\n this.#cooldownTimer = undefined;\n this.#requestClaim();\n },\n delayMs: wait,\n });\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 and waits for running handlers until the drain point of `deadline` (default: the\n * shutdown timeout from now), then aborts the rest and releases their deliveries for another\n * process. Deliveries still in flight when the deadline itself passes are abandoned: their leases\n * expire and they run again elsewhere. Resolves with how many were abandoned.\n */\n async stop(deadline?: ShutdownDeadline): Promise<number> {\n const { clock, settings } = this.#dependencies;\n const own = deadline ?? new ShutdownDeadline(clock, settings.shutdownTimeoutMs);\n try {\n return await this.#stopWithin(own);\n } finally {\n if (deadline === undefined) {\n own.dispose();\n }\n }\n }\n\n async #stopWithin(deadline: ShutdownDeadline): Promise<number> {\n if (!this.#running) {\n // Batches run by hand (`runOnce`) leave settlements to recover without ever starting the loop.\n await this.#closeRecovery(deadline);\n return 0;\n }\n this.#running = false;\n this.#completions?.setClosing(true);\n this.#cooldownTimer?.();\n this.#cooldownTimer = undefined;\n this.#quietRefillTimer?.();\n this.#quietRefillTimer = undefined;\n this.#signal(this.#refillThreshold);\n await deadline.race(this.#stopWatching());\n await deadline.race(this.#loop!);\n const settled = Promise.allSettled([...this.#inFlight].map((delivery) => delivery.settled));\n if ((await deadline.raceDrain(settled)) === 'timeout') {\n for (const delivery of this.#inFlight) {\n delivery.controller.abort(new DispatcherStoppedError('relaybus dispatcher stopped'));\n }\n if ((await deadline.race(settled)) === 'timeout') {\n return this.#abandon();\n }\n }\n await this.#closeRecovery(deadline);\n await deadline.race(this.#relinquish());\n return 0;\n }\n\n /**\n * The deadline passed with deliveries still in flight (aborted, their release not answered): forgets\n * them and every settlement still to retry. Whatever they release or complete from now on may reach a\n * closed store; a delivery whose state change is lost stays leased until the lease expires and then\n * runs again (at-least-once).\n */\n #abandon(): number {\n this.#abandoned = true;\n // Their leases must run out, so that another process takes the deliveries.\n for (const stopKeeping of this.#leaseKeepers.values()) {\n stopKeeping();\n }\n this.#leaseKeepers.clear();\n this.#timers.cancelAll();\n this.#recoveryTimer?.();\n this.#recoveryTimer = undefined;\n this.#pending.clear();\n return this.#inFlight.size;\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: ShutdownDeadline): Promise<void> {\n this.#recoveryTimer?.();\n this.#recoveryTimer = undefined;\n const lastTry = (async () => {\n await this.#recovery;\n await this.#recoverSettlements();\n })();\n await deadline.race(lastTry);\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 if (this.#abandoned) {\n return;\n }\n this.#pending.set(pendingKey(entry.delivery), entry);\n this.#recoveryTimer ??= schedule(this.#dependencies.clock, {\n run: () => void this.#recoverSettlements(),\n delayMs: this.#dependencies.settings.pollIntervalMs,\n repeat: true,\n unref: true,\n });\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 cancel: CancelTimer | undefined;\n const timedOut = new Promise<'timeout'>((resolve) => {\n cancel = schedule(this.#dependencies.clock, {\n run: () => resolve('timeout'),\n delayMs: Math.max(0, deadline - Date.now()),\n });\n });\n const outcome = await Promise.race([work.then(() => 'done' as const), timedOut]);\n cancel?.();\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 cancel = schedule(this.#dependencies.clock, {\n run: () => {\n this.#signalledMinimum = 1;\n resolve();\n },\n delayMs: this.#dependencies.settings.pollIntervalMs,\n });\n this.#wakeUp = () => {\n cancel();\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 ??= schedule(this.#dependencies.clock, {\n run: () => {\n this.#quietRefillTimer = undefined;\n this.#signal(1);\n },\n delayMs: 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, observation } = 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 this.#quietRefillTimer?.();\n this.#quietRefillTimer = undefined;\n requested += request.limit;\n const 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 const claimed = await (observation === undefined\n ? store.claim(claim)\n : observation.claim(store, claim));\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 // A claim that answers after a stop gave up is left to lease expiry: the store may be closed.\n for (const delivery of this.#abandoned ? [] : 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);\n const limit = Math.min(room, free);\n if (limit > 0) {\n plans.push({ handlers: [...registration.claimIds], limit });\n free -= limit;\n }\n }\n if (unlimited.length > 0 && free > 0) {\n plans.push({\n handlers: unlimited.flatMap((registration) => registration.claimIds),\n limit: free,\n });\n }\n return plans;\n }\n\n #countInFlight(registration: HandlerRegistration): number {\n let count = 0;\n for (const delivery of this.#inFlight) {\n if (registration.claimIds.includes(delivery.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 AttemptsExhaustedError(\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 : startLeaseHeartbeat(this.#dependencies, { delivery, controller });\n this.#leaseKeepers.set(delivery, stopHeartbeat);\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 (this.#abandoned) {\n // Stop gave this delivery up and the store may be closed: its lease expires instead.\n return false;\n }\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 this.#leaseKeepers.delete(delivery);\n }\n }\n\n async #runHandler(\n registration: HandlerRegistration,\n {\n delivery,\n controller,\n }: { readonly delivery: ClaimedDelivery; readonly 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, transaction: 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 if (this.#abandoned) {\n // Stop gave this delivery up: no completion may reach the store any more.\n return 'unconfirmed';\n }\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(input: InvokeInput): Promise<void> {\n const { registration, event, delivery, controller, transaction } = input;\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 handle = (): unknown =>\n runInIsolatedScope(scope, () => registration.handle(event, context));\n const { observation } = this.#dependencies;\n const work = Promise.resolve().then(\n observation === undefined\n ? handle\n : () => observation.process({ registration, delivery }, handle),\n );\n work.catch(() => undefined);\n let cancelTimeout: CancelTimer | undefined;\n if (registration.timeoutMs !== null) {\n const timeoutMs = registration.timeoutMs;\n cancelTimeout = this.#timers.start({\n run: () => {\n controller.abort(\n new HandlerTimeoutError(\n `Handler '${registration.id}' did not settle within ${timeoutMs}ms`,\n ),\n );\n },\n delayMs: timeoutMs,\n });\n }\n try {\n const settled = Promise.race([work, rejectOnAbort(controller.signal)]);\n await (observation === undefined\n ? settled\n : observation.observe({ registration, delivery }, settled));\n } catch (error) {\n await this.#awaitAbandonedHandler(work, {\n reason: error,\n transactional: transaction !== undefined,\n });\n throw error;\n } finally {\n cancelTimeout?.();\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, transactional }: { readonly reason: unknown; readonly 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 {\n delivery,\n controller,\n }: { readonly delivery: ClaimedDelivery; readonly 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 return schedule(clock, {\n run: () => {\n controller.abort(new LeaseLostError(`Lease on delivery ${delivery.deliveryId} expired`));\n },\n delayMs: Math.max(0, expiry - clock.now().getTime()),\n unref: true,\n });\n }\n\n async #fail(\n registration: HandlerRegistration,\n { delivery, error }: { readonly delivery: ClaimedDelivery; readonly 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, error }: { readonly delivery: ClaimedDelivery; readonly 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, error }: { readonly delivery: ClaimedDelivery; readonly 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","import { toTimerMilliseconds, type Duration } from './duration.js';\nimport { ConfigurationError } from './errors.js';\nimport { assertPositiveInteger } from './internal/validation.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 Omit<HandlerDescriptor, 'eventType'> {\n /** Event types it handles: one for a handler, every type routed to the destination for a route. */\n readonly eventTypes: readonly string[];\n /**\n * Handler ids whose deliveries it runs: its id, then for a route the per-type ids that 0.2.0\n * stored its deliveries under.\n */\n readonly claimIds: readonly string[];\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 eventTypes: readonly string[];\n /** Further ids of earlier versions whose stored deliveries this registration runs. */\n readonly legacyIds?: readonly 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 #byClaimId = 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 const claimIds = [options.id, ...(input.legacyIds ?? [])];\n this.#assertUnregistered(claimIds);\n if (options.concurrency !== undefined) {\n assertPositiveInteger(options.concurrency, `Concurrency of handler '${options.id}'`);\n }\n const registration: HandlerRegistration = {\n id: options.id,\n eventTypes: input.eventTypes,\n claimIds,\n schema: input.schema,\n handle: input.handle,\n retry: createRetryPolicy(options.retry, defaults.retry),\n timeoutMs: resolveTimeout(options.timeout, {\n fallback: defaults.timeoutMs,\n handlerId: options.id,\n }),\n concurrency: options.concurrency ?? null,\n transactional: options.transactional ?? false,\n forwardsToTransport: input.forwardsToTransport,\n };\n this.#index(registration);\n return registration;\n }\n\n #assertUnregistered(claimIds: readonly string[]): void {\n for (const id of claimIds) {\n if (this.#byClaimId.has(id)) {\n throw new ConfigurationError(`Handler id '${id}' is already registered`);\n }\n }\n }\n\n #index(registration: HandlerRegistration): void {\n this.#byId.set(registration.id, registration);\n for (const id of registration.claimIds) {\n this.#byClaimId.set(id, registration);\n }\n for (const eventType of registration.eventTypes) {\n const forType = this.#byEventType.get(eventType) ?? [];\n forType.push(registration);\n this.#byEventType.set(eventType, forType);\n }\n }\n\n /** The registration that runs deliveries stored under `id`, its own id or a legacy one. */\n get(id: string): HandlerRegistration | undefined {\n return this.#byClaimId.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, handlerId }: { readonly fallback: number | null; readonly 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 /** Hooks at least one observer implements, so callers skip building events nobody reads. */\n readonly #implemented: ReadonlySet<keyof RelayBusObserver>;\n\n constructor(observers: readonly RelayBusObserver[], logger: RelayBusLogger) {\n this.#observers = observers;\n this.#logger = logger;\n this.#implemented = new Set(\n observers.flatMap((observer) => hookNames(observer) as (keyof RelayBusObserver)[]),\n );\n }\n\n /** True when some observer implements `method`. */\n wants(method: ObserverMethod): boolean {\n return this.#implemented.has(method);\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](logObserverFailure) relaybus observer threw | ${errorInfo.name}: ${errorInfo.message}`,\n );\n }\n}\n\n/** Names of the functions of an observer, own or inherited (an observer may be a class instance). */\nfunction hookNames(observer: RelayBusObserver): string[] {\n const names: string[] = [];\n for (\n let target: object | null = observer;\n target !== null && target !== Object.prototype;\n target = Object.getPrototypeOf(target) as object | null\n ) {\n names.push(\n ...Object.getOwnPropertyNames(target).filter(\n (name) => typeof (observer as Record<string, unknown>)[name] === 'function',\n ),\n );\n }\n return names;\n}\n","import { InvalidEnvelopeError, toErrorInfo } from './errors.js';\nimport { assertEventType, type EventEnvelope } from './event.js';\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 */\nexport function 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","import { hostname } from 'node:os';\nimport type { DispatcherSettings } from './dispatcher.js';\nimport { toMilliseconds, toTimerMilliseconds } from './duration.js';\nimport { ConfigurationError } from './errors.js';\nimport type { RegistrationDefaults } from './handler-registry.js';\nimport type { IdentifierGenerator } from './identifier.js';\nimport { assertPositiveInteger } from './internal/validation.js';\nimport type { DispatcherOptions, RelayBusOptions, RetentionOptions } from './relay-bus.js';\nimport { createRetryPolicy } from './retry-policy.js';\n\n// Option resolution of RelayBus: defaults and validation, in the order the options are read.\n\nexport const 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 transactionTimeout: '5s',\n} as const;\n\nexport function oneOf<T extends string>(\n value: T,\n { allowed, name }: { readonly allowed: readonly T[]; readonly name: string },\n): 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\nexport function isDispatcherEnabled<TTransaction>(options: RelayBusOptions<TTransaction>): boolean {\n return options.dispatcher?.enabled ?? true;\n}\n\n/** Milliseconds every `bus.transaction` may take. */\n/** How often the backlog is read for `onBacklog`, in milliseconds; undefined when off. */\nexport function resolveBacklogInterval<TTransaction>(\n options: RelayBusOptions<TTransaction>,\n): number | undefined {\n return options.backlogInterval === undefined\n ? undefined\n : toTimerMilliseconds(options.backlogInterval, 'backlogInterval');\n}\n\nexport function resolveTransactionTimeout<TTransaction>(\n options: RelayBusOptions<TTransaction>,\n): number {\n return toTimerMilliseconds(\n options.transactionTimeout ?? DEFAULTS.transactionTimeout,\n 'transactionTimeout',\n );\n}\n\nexport function createHandlerDefaults<TTransaction>(\n options: RelayBusOptions<TTransaction>,\n): RegistrationDefaults {\n return {\n retry: createRetryPolicy(options.retry),\n timeoutMs:\n options.handlerTimeout === undefined || options.handlerTimeout === false\n ? null\n : toTimerMilliseconds(options.handlerTimeout, 'handlerTimeout'),\n };\n}\n\nexport function createDispatcherSettings(\n options: DispatcherOptions | undefined,\n generateIdentifier: IdentifierGenerator,\n): DispatcherSettings {\n const dispatcher: DispatcherOptions = options ?? {};\n const concurrency = assertPositiveInteger(\n dispatcher.concurrency ?? DEFAULTS.concurrency,\n 'dispatcher.concurrency',\n );\n return {\n owner: `${hostname()}:${process.pid}:${generateIdentifier()}`,\n concurrency,\n batchSize: assertPositiveInteger(dispatcher.batchSize ?? concurrency, 'dispatcher.batchSize'),\n ...createDispatcherTimings(dispatcher),\n };\n}\n\n/** The intervals and completion batching of the dispatcher, validated in declaration order. */\nexport function createDispatcherTimings(\n dispatcher: DispatcherOptions,\n): Omit<DispatcherSettings, 'owner' | 'concurrency' | 'batchSize'> {\n return {\n pollIntervalMs: toTimerMilliseconds(\n dispatcher.pollInterval ?? DEFAULTS.pollInterval,\n 'dispatcher.pollInterval',\n ),\n leaseDurationMs: toTimerMilliseconds(\n dispatcher.leaseDuration ?? DEFAULTS.leaseDuration,\n 'dispatcher.leaseDuration',\n ),\n shutdownTimeoutMs: toTimerMilliseconds(\n dispatcher.shutdownTimeout ?? DEFAULTS.shutdownTimeout,\n 'dispatcher.shutdownTimeout',\n ),\n completionBatchWindowMs: toMilliseconds(\n dispatcher.completionBatchWindow ?? DEFAULTS.completionBatchWindow,\n 'dispatcher.completionBatchWindow',\n ),\n completionBatchSize: assertPositiveInteger(\n dispatcher.completionBatchSize ?? DEFAULTS.completionBatchSize,\n 'dispatcher.completionBatchSize',\n ),\n };\n}\n\nexport function 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","import { toTimerMilliseconds } from './duration.js';\nimport { ConfigurationError } from './errors.js';\nimport { assertEventType, type EventReference } from './event.js';\nimport { DEFAULTS } from './relay-bus-settings.js';\nimport { DEFAULT_ROUTE_RETRY_POLICY, createRetryPolicy, type RetryPolicy } from './retry-policy.js';\nimport type { RouteOptions } from './relay-bus.js';\n\nconst TRANSPORT_HANDLER_PREFIX = 'relaybus.transport';\n\n/**\n * Every route to one destination of one transport. They share one handler id, so their deliveries\n * form one queue per ordering key: events of a key reach the destination in commit order, whatever\n * their types.\n */\nexport interface RouteGroup {\n readonly transport: string;\n readonly destination: string;\n /** `relaybus.transport:<transport>:<destination>`. */\n readonly id: string;\n /** The routed event types, in route order. */\n readonly eventTypes: string[];\n /** The 0.2.0 per-type ids (`<id>:<eventType>`), whose stored deliveries the group still sends. */\n readonly legacyIds: string[];\n /** Retry and timeout of the first route; every other route must resolve to the same. */\n readonly route: RouteOptions;\n readonly retry: RetryPolicy;\n readonly timeoutMs: number;\n}\n\n/** Groups `routes` by transport and destination, in order of first appearance. */\nexport function groupRoutes(routes: readonly RouteOptions[]): RouteGroup[] {\n const groups = new Map<string, RouteGroup>();\n for (const route of routes) {\n const type = routedType(route.event);\n const destination = route.destination ?? type;\n const id = `${TRANSPORT_HANDLER_PREFIX}:${route.transport}:${destination}`;\n const group = groups.get(id);\n if (group === undefined) {\n groups.set(id, createGroup(route, { id, destination, type }));\n } else {\n addRoute(group, { route, type, destination });\n }\n }\n return [...groups.values()];\n}\n\nfunction createGroup(\n route: RouteOptions,\n {\n id,\n destination,\n type,\n }: { readonly id: string; readonly destination: string; readonly type: string },\n): RouteGroup {\n return {\n transport: route.transport,\n destination,\n id,\n eventTypes: [type],\n legacyIds: [`${id}:${type}`],\n route,\n ...resolveSettings(route, id),\n };\n}\n\nfunction addRoute(\n group: RouteGroup,\n {\n route,\n type,\n destination,\n }: { readonly route: RouteOptions; readonly type: string; readonly destination: string },\n): void {\n const target = `'${group.destination}' of transport '${group.transport}'`;\n // Equal ids of one transport imply one destination; another transport can only collide through a ':' in a name.\n if (route.transport !== group.transport) {\n throw new ConfigurationError(\n `Routes to ${target} and to '${destination}' of transport '${route.transport}' would share the handler id '${group.id}'; rename the transport or the destination`,\n );\n }\n if (group.eventTypes.includes(type)) {\n throw new ConfigurationError(`Event type ${type} is routed to ${target} twice`);\n }\n const { retry, timeoutMs } = resolveSettings(route, group.id);\n if (timeoutMs !== group.timeoutMs || !sameRetryPolicy(retry, group.retry)) {\n throw new ConfigurationError(\n `Routes to ${target} must share retry and timeout, because their events are sent in one queue per key | types=${group.eventTypes[0]},${type}`,\n );\n }\n group.eventTypes.push(type);\n group.legacyIds.push(`${group.id}:${type}`);\n}\n\n/** The retry policy and timeout a route resolves to, validated as the registry validates them. */\nfunction resolveSettings(\n route: RouteOptions,\n id: string,\n): { retry: RetryPolicy; timeoutMs: number } {\n return {\n retry: createRetryPolicy(route.retry, DEFAULT_ROUTE_RETRY_POLICY),\n timeoutMs:\n route.timeout === undefined\n ? DEFAULTS.routeTimeoutMs\n : toTimerMilliseconds(route.timeout, `Timeout of handler '${id}'`),\n };\n}\n\nfunction sameRetryPolicy(left: RetryPolicy, right: RetryPolicy): boolean {\n return (Object.keys(left) as (keyof RetryPolicy)[]).every(\n (field) => left[field] === right[field],\n );\n}\n\nfunction routedType(event: EventReference): string {\n const type = typeof event === 'string' ? event : event.type;\n assertEventType(type);\n return type;\n}\n","import type { Clock } from './clock.js';\nimport { TransactionTimeoutError, toErrorInfo } from './errors.js';\nimport type { EventStore } from './event-store.js';\n\n/** One `bus.transaction` with the time it may take. */\nexport type BudgetedTransaction<TTransaction, T> = {\n readonly clock: Clock;\n readonly timeoutMs: number;\n readonly work: (transaction: TTransaction) => Promise<T>;\n};\n\n/**\n * Runs `work` in a store transaction held to `timeoutMs`. The store makes the database enforce the\n * budget where it can; whatever runs past it fails with {@link TransactionTimeoutError} and rolls\n * back: a `work` that resolved too late is rejected before the commit, and an error `work` raised\n * once the budget ran out (a statement the server cancelled, a session it ended) becomes the\n * timeout's cause. A failed commit keeps its own error, since the commit may have taken effect.\n */\nexport async function runBudgetedTransaction<TTransaction, T>(\n store: EventStore<TTransaction>,\n { clock, timeoutMs, work }: BudgetedTransaction<TTransaction, T>,\n): Promise<T> {\n const startedAt = clock.now().getTime();\n const overrun = (): boolean => clock.now().getTime() - startedAt >= timeoutMs;\n // Set once `work` succeeded within the budget: a later failure belongs to the commit, whose\n // outcome may be unknown (a lost response), so it is never reported as a rollback.\n let committing = false;\n try {\n return await store.transaction(\n async (transaction) => {\n committing = false;\n const result = await work(transaction);\n if (overrun()) {\n throw createTimeoutError(timeoutMs, undefined);\n }\n committing = true;\n return result;\n },\n { timeoutMs },\n );\n } catch (error) {\n if (error instanceof TransactionTimeoutError || committing || !overrun()) {\n throw error;\n }\n throw createTimeoutError(timeoutMs, error);\n }\n}\n\nfunction createTimeoutError(timeoutMs: number, cause: unknown): TransactionTimeoutError {\n const message =\n `The transaction ran past its ${timeoutMs} ms budget (transactionTimeout) and was rolled back. ` +\n 'The usual cause is a slow call to another service (HTTP, gRPC, a broker, a lock) inside the ' +\n 'transaction: make external calls before the transaction starts or after it commits, or raise ' +\n 'transactionTimeout';\n return cause === undefined\n ? new TransactionTimeoutError(message)\n : new TransactionTimeoutError(`${message} | cause=${toErrorInfo(cause).message}`, { cause });\n}\n","import {\n assertCatalogsCovered,\n toCatalogRequirement,\n type CatalogDeclaration,\n type CatalogRequirement,\n type EventTypeRegistrations,\n} from './catalog-coverage.js';\nimport { BusObservation, withTraceHeaders, type ReceiveOrigin } from './bus-observation.js';\nimport { CatalogPublisher } from './catalog-publisher.js';\nimport {\n resolveCatalogHandlers,\n type Catalog,\n type CatalogEventSelection,\n type HandlersOf,\n type SubscribeCatalogOptions,\n} from './catalog.js';\nimport { systemClock, type Clock } from './clock.js';\nimport { DispatchObservation } from './dispatch-observation.js';\nimport { Dispatcher, type DispatcherSettings } from './dispatcher.js';\nimport { toMilliseconds, toTimerMilliseconds } from './duration.js';\nimport {\n ConfigurationError,\n DrainIncompleteError,\n LifecycleError,\n TransactionRequiredError,\n toErrorInfo,\n} from './errors.js';\nimport type {\n AppendEntry,\n CloseOptions,\n DeliveryQuery,\n DeliveryRecord,\n EventStore,\n EventStoreStatistics,\n NewDelivery,\n PurgeResult,\n} from './event-store.js';\nimport {\n assertEventType,\n keyFromDefinition,\n validatePayload,\n type DomainEvent,\n type EventClass,\n type EventEnvelope,\n type EventReference,\n} from './event.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 { schedule, type CancelTimer } from './internal/timers.js';\nimport { Notifier } from './notifier.js';\nimport type { RelayBusLogger } from './observer.js';\nimport { normalizeEnvelope } from './received-envelope.js';\nimport type {\n InboundSubscriptionOptions,\n PublishOneOptions,\n PublishOptions,\n ReceiveStatus,\n RelayBusOptions,\n RouteOptions,\n TransactionMode,\n UnroutedEventPolicy,\n} from './relay-bus-options.js';\nimport {\n DEFAULTS,\n createDispatcherSettings,\n createHandlerDefaults,\n createRetentionSettings,\n isDispatcherEnabled,\n oneOf,\n resolveBacklogInterval,\n resolveTransactionTimeout,\n} from './relay-bus-settings.js';\nimport { DEFAULT_ROUTE_RETRY_POLICY } from './retry-policy.js';\nimport { groupRoutes, type RouteGroup } from './route-groups.js';\nimport {\n withinDeadline,\n type ShutdownDeadline,\n type StopOptions,\n type StopResult,\n} from './shutdown-deadline.js';\nimport { runBudgetedTransaction } from './transaction-budget.js';\nimport type { StandardSchemaV1 } from './standard-schema.js';\nimport type { Transport, TransportSubscriptionHooks } from './transport.js';\n\nexport type {\n DispatcherOptions,\n InboundSubscriptionOptions,\n PublishOneOptions,\n PublishOptions,\n ReceiveStatus,\n RelayBusOptions,\n RetentionOptions,\n RouteOptions,\n TransactionMode,\n UnroutedEventPolicy,\n} from './relay-bus-options.js';\n\ntype BusState = 'idle' | 'starting' | 'running' | 'stopping' | 'stopped';\n\n/** Batches `drain` runs at most before it gives up. */\nconst DEFAULT_DRAIN_BATCHES = 1_000;\nconst WAKE_DELAY_MS = 25;\n\n/** The events of one publish call with what their envelopes and deliveries inherit. */\ntype CreateEntriesInput<TTransaction> = {\n readonly events: readonly DomainEvent[];\n readonly options: PublishOptions<TTransaction>;\n readonly id: string | undefined;\n readonly scope: ExecutionScope | undefined;\n readonly now: Date;\n readonly availableAt: Date;\n};\n\n/** The entries of one publish call that have deliveries, and how to append them. */\ntype AppendDeliverableInput<TTransaction> = {\n readonly entries: readonly AppendEntry[];\n readonly options: PublishOptions<TTransaction>;\n readonly scope: ExecutionScope | undefined;\n readonly now: Date;\n readonly delayMs: number;\n};\n\n/** One event of a publish call with what it inherits from the call and the running handler. */\ntype CreateEnvelopeInput<TTransaction> = {\n readonly event: DomainEvent;\n readonly options: PublishOptions<TTransaction>;\n readonly id: string | undefined;\n readonly scope: ExecutionScope | undefined;\n readonly now: Date;\n readonly correlationId: string | undefined;\n};\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 #transactionTimeoutMs: number;\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: CancelTimer | undefined;\n readonly #observation: BusObservation | undefined;\n readonly #backlogIntervalMs: number | undefined;\n #backlogTimer: CancelTimer | undefined;\n readonly #shutdownTimeoutMs: number;\n #state: BusState = 'idle';\n #starting: Promise<void> | undefined;\n #stopping: Promise<StopResult> | undefined;\n\n constructor(options: RelayBusOptions<TTransaction>) {\n this.#store = options.store;\n this.#source = options.source ?? 'relaybus';\n this.#transactionMode = oneOf(options.transactionMode ?? 'required', {\n allowed: ['required', 'optional'],\n name: 'transactionMode',\n });\n this.#unroutedEvents = oneOf(options.unroutedEvents ?? 'warn', {\n allowed: ['warn', 'throw'],\n name: 'unroutedEvents',\n });\n this.#transactionResolver = options.transactionResolver;\n this.#transactionTimeoutMs = resolveTransactionTimeout(options);\n this.#defaults = createHandlerDefaults(options);\n this.#logger = options.logger ?? console;\n this.#notifier = new Notifier(options.observers ?? [], this.#logger);\n this.#clock = options.clock ?? systemClock;\n this.#observation = BusObservation.create({\n notifier: this.#notifier,\n tracer: options.tracer,\n clock: this.#clock,\n });\n this.#backlogIntervalMs = resolveBacklogInterval(options);\n this.#generateIdentifier = options.generateIdentifier ?? (() => createUuidV7());\n this.#setupStore = options.setupStore ?? true;\n this.#retention = createRetentionSettings(options.retention);\n this.#subscriptions = options.subscriptions ?? [];\n this.#registerConnections(options);\n this.#dispatcherEnabled = isDispatcherEnabled(options);\n const settings = createDispatcherSettings(options.dispatcher, this.#generateIdentifier);\n this.#shutdownTimeoutMs = settings.shutdownTimeoutMs;\n this.#dispatcher = this.#createDispatcher(settings, options);\n }\n\n #createDispatcher(\n settings: DispatcherSettings,\n options: RelayBusOptions<TTransaction>,\n ): Dispatcher {\n return 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,\n observation: DispatchObservation.create({\n notifier: this.#notifier,\n tracer: options.tracer,\n clock: this.#clock,\n }),\n });\n }\n\n /** Registers the transports, then the routes, checks the subscriptions and registers the catalogs. */\n #registerConnections(options: RelayBusOptions<TTransaction>): void {\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 this.#registerRoutes(options.routes ?? []);\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 }\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 // eslint-disable-next-line relaybus/max-two-params -- public RelayBus.subscribe signature\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 eventTypes: [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 // eslint-disable-next-line relaybus/max-two-params -- public RelayBus.subscribeCatalog signature\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\n .all()\n .flatMap((registration) =>\n registration.eventTypes.map((eventType) => toDescriptor(registration, eventType)),\n );\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.#observedPublish([event], { options, id: 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.#observedPublish(events, { options, id: undefined });\n }\n\n /**\n * Runs `work` in a new store transaction. `publish` calls inside it join the\n * transaction without passing it explicitly. The transaction is held to `transactionTimeout`\n * and rolled back with a {@link TransactionTimeoutError} when it runs past it.\n */\n async transaction<T>(work: (transaction: TTransaction) => Promise<T>): Promise<T> {\n return runBudgetedTransaction(this.#store, {\n clock: this.#clock,\n timeoutMs: this.#transactionTimeoutMs,\n work: (transaction) => runInScope({ transaction }, () => work(transaction)),\n });\n }\n\n /**\n * The transaction `publish` would join right now: the one of the enclosing `bus.transaction`\n * (or `@RelayBusTransaction()` method, or transactional handler), else the one\n * `transactionResolver` finds. Repositories use it to write in the same transaction.\n */\n currentTransaction(): TTransaction | undefined {\n return (\n (getCurrentScope()?.transaction as TTransaction | undefined) ?? this.#transactionResolver?.()\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 receive(envelope: EventEnvelope): Promise<ReceiveStatus> {\n // Not async: the store's promise is returned as is, so an unobserved receive allocates nothing extra.\n return this.#observation === undefined\n ? this.#receive(envelope)\n : this.#observedReceive(envelope, undefined);\n }\n\n #observedReceive(\n envelope: EventEnvelope,\n origin: ReceiveOrigin | undefined,\n ): Promise<ReceiveStatus> {\n return this.#observation!.receive({ envelope, origin }, () => this.#receive(envelope));\n }\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 LifecycleError(\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 claiming, waits for running handlers, hands back leases, closes transports and the store,\n * all within `options.timeout` (default `dispatcher.shutdownTimeout`). When the deadline passes it\n * aborts the handlers still running, force-closes what relaybus opened itself (never pools or\n * clients the application passed in) and resolves anyway: it never rejects because of the\n * deadline. Abandoned deliveries stay leased until their lease expires and then run again\n * (at-least-once). Waits for a start in progress first. Safe to call more than once: later calls\n * get the result of the first.\n */\n async stop(options: StopOptions = {}): Promise<StopResult> {\n const timeoutMs =\n options.timeout === undefined\n ? this.#shutdownTimeoutMs\n : toTimerMilliseconds(options.timeout, 'timeout');\n if (this.#stopping !== undefined) {\n return this.#stopping;\n }\n if (this.#state !== 'running' && this.#state !== 'starting') {\n return this.#stopOutsideRun(timeoutMs);\n }\n this.#stopping = this.#stopComponents(timeoutMs);\n const result = await this.#stopping;\n if (!result.graceful) {\n this.#logger.warn(\n `[RelayBus](stop) Shutdown deadline passed, forced close | abandoned=${result.abandonedDeliveries} | timeoutMs=${timeoutMs}`,\n );\n }\n return result;\n }\n\n /**\n * A bus that is not running: an idle one only settles what batches run by hand left behind (and\n * stays startable); a stopped one has nothing left to do.\n */\n async #stopOutsideRun(timeoutMs: number): Promise<StopResult> {\n if (this.#state !== 'idle') {\n return { graceful: true, abandonedDeliveries: 0, durationMs: 0 };\n }\n return withinDeadline({ clock: this.#clock, timeoutMs }, (deadline) =>\n this.#dispatcher.stop(deadline),\n );\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 = DEFAULT_DRAIN_BATCHES): 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 DrainIncompleteError(`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!(\n subscription.destinations,\n async (envelope, message) => {\n await (this.#observation === undefined\n ? this.#receive(envelope)\n : this.#observedReceive(envelope, { transport, destination: message?.destination }));\n },\n this.#subscriptionHooks(transport),\n );\n }\n } catch (error) {\n await withinDeadline(\n { clock: this.#clock, timeoutMs: this.#shutdownTimeoutMs },\n async (deadline) => {\n await this.#closeTransports(deadline);\n return 0;\n },\n );\n this.#state = 'stopped';\n throw error;\n }\n if (this.#state !== 'starting') {\n // A stop gave up waiting for this start and closed the transports and the store already.\n throw new LifecycleError('relaybus was stopped before it finished starting');\n }\n if (this.#dispatcherEnabled) {\n this.#dispatcher.start();\n }\n this.#scheduleRetention();\n this.#scheduleBacklog();\n this.#state = 'running';\n this.#logger.log(\n `[RelayBus](startComponents) relaybus started | handlers=${this.#registry.all().length} dispatcher=${this.#dispatcherEnabled}`,\n );\n }\n\n /** What a transport may report back while subscribed; undefined when no observer wants it. */\n #subscriptionHooks(transport: Transport): TransportSubscriptionHooks | undefined {\n if (!this.#notifier.wants('onInvalidMessage')) {\n return undefined;\n }\n return {\n onInvalidMessage: ({ destination, error }) => {\n const errorInfo = toErrorInfo(error);\n this.#notifier.notify('onInvalidMessage', {\n transport: transport.name,\n system: transport.system ?? transport.name,\n destination,\n reason: errorInfo.message,\n error: errorInfo,\n });\n },\n };\n }\n\n /** Applies the retention policy every `retention.interval` while the bus runs, when it deletes anything. */\n #scheduleRetention(): void {\n if (this.#retention.completedMs !== null || this.#retention.deadMs !== null) {\n this.#retentionTimer = schedule(this.#clock, {\n run: () => {\n this.purgeExpired().catch(() => undefined);\n },\n delayMs: this.#retention.intervalMs,\n repeat: true,\n unref: true,\n });\n }\n }\n\n /** Reports the backlog every `backlogInterval` while the bus runs, when an observer wants it. */\n #scheduleBacklog(): void {\n if (this.#backlogIntervalMs !== undefined) {\n this.#backlogTimer = this.#observation?.startBacklog({\n intervalMs: this.#backlogIntervalMs,\n statistics: () => this.statistics(),\n });\n }\n }\n\n /**\n * Waits for a start in progress (a failed start leaves nothing to stop), then stops the dispatcher\n * and closes the transports and the store. A start still running at the deadline is given up: the\n * transports and the store are force-closed and the start rejects when it resumes.\n */\n async #stopComponents(timeoutMs: number): Promise<StopResult> {\n try {\n return await withinDeadline({ clock: this.#clock, timeoutMs }, async (deadline) => {\n if (this.#state === 'starting') {\n const started = await deadline.race(this.#starting!.catch(() => undefined));\n if (started === 'timeout') {\n this.#state = 'stopping';\n await this.#closeConnections(deadline);\n return 0;\n }\n }\n if (this.#state !== 'running') {\n return 0;\n }\n this.#state = 'stopping';\n this.#retentionTimer?.();\n this.#backlogTimer?.();\n const abandoned = await this.#dispatcher.stop(deadline);\n await this.#closeConnections(deadline);\n return abandoned;\n });\n } finally {\n this.#state = 'stopped';\n }\n }\n\n async #closeConnections(deadline: ShutdownDeadline): Promise<void> {\n await this.#closeTransports(deadline);\n const options: CloseOptions = { signal: deadline.signal };\n await deadline.race(Promise.resolve(this.#store.close?.(options)));\n }\n\n /** Publishes inside the tracer's span, with its trace headers, when the bus is observed. */\n #observedPublish(\n events: readonly DomainEvent[],\n input: { readonly options: PublishOptions<TTransaction>; readonly id: string | undefined },\n ): Promise<EventEnvelope[]> {\n const observation = this.#observation;\n if (observation === undefined) {\n return this.#publish(events, input);\n }\n return observation.publish(\n { eventTypes: events.map((event) => String(event.type)) },\n (headers) =>\n this.#publish(events, { ...input, options: withTraceHeaders(input.options, headers) }),\n );\n }\n\n async #publish(\n events: readonly DomainEvent[],\n {\n options,\n id,\n }: { readonly options: PublishOptions<TTransaction>; readonly 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 = await this.#createEntries({ events, options, id, scope, now, availableAt });\n const deliverable = entries.filter((entry) => entry.deliveries.length > 0);\n if (deliverable.length > 0) {\n await this.#appendDeliverable({ entries: deliverable, options, scope, now, delayMs });\n }\n return entries.map((entry) => entry.event);\n }\n\n /** One entry per event, in order: its envelope and a delivery for every registration of its type. */\n async #createEntries(input: CreateEntriesInput<TTransaction>): Promise<AppendEntry[]> {\n const { events, options, id, scope, now, availableAt } = input;\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({\n event,\n options,\n id,\n scope,\n now,\n correlationId,\n });\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 return entries;\n }\n\n /** Appends the entries that have deliveries, reports what was new and wakes the dispatcher when it is due now. */\n async #appendDeliverable(input: AppendDeliverableInput<TTransaction>): Promise<void> {\n const { entries, options, scope, now, delayMs } = input;\n const result = await this.#appendInTransaction(entries, { options, scope, now });\n const appended = new Set(result.appendedEventIds);\n const published = entries\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\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](reportUnrouted) ${message}`);\n }\n\n async #appendInTransaction(\n entries: readonly AppendEntry[],\n {\n options,\n scope,\n now,\n }: {\n readonly options: PublishOptions<TTransaction>;\n readonly scope: ExecutionScope | undefined;\n readonly now: Date;\n },\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(input: CreateEnvelopeInput<TTransaction>): Promise<EventEnvelope> {\n const { event, options, id, scope, now, correlationId } = input;\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 ?? keyFromDefinition(event, payload),\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 #registerRoutes(routes: readonly RouteOptions[]): void {\n for (const route of routes) {\n this.#requireTransport(route.transport);\n }\n for (const group of groupRoutes(routes)) {\n this.#registerRoute(group);\n }\n }\n\n /** Registers one handler for every route to a destination, so a key's events reach it in commit order. */\n #registerRoute(group: RouteGroup): void {\n const transport = this.#transports.get(group.transport)!;\n const { route, destination } = group;\n this.#registry.register(\n {\n eventTypes: group.eventTypes,\n legacyIds: group.legacyIds,\n schema: undefined,\n handle:\n this.#observation?.sender(transport, destination) ??\n ((envelope) => transport.publish(envelope, destination)),\n options: {\n id: group.id,\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 schedule(this.#clock, {\n run: () => this.#dispatcher.wake(),\n delayMs: WAKE_DELAY_MS,\n unref: true,\n });\n }\n\n /** Closes every transport, each at most until the deadline; past it they are asked to force. */\n async #closeTransports(deadline: ShutdownDeadline): Promise<void> {\n const options: CloseOptions = { signal: deadline.signal };\n for (const transport of this.#transports.values()) {\n try {\n await deadline.race(transport.close(options));\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, eventType: string): HandlerDescriptor {\n return {\n id: registration.id,\n 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"]}