@relaybus/core 0.3.0 → 0.3.1

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/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,IAAA;AAAA,EACH,CAAA,EAAG;AACL,CAAA;AAEA,IAAM,gBAAA,GAAmB,+BAAA;AAElB,SAAS,cAAA,CAAe,OAAiB,IAAA,EAAsB;AACpE,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,IAAK,QAAQ,CA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E","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"]}
1
+ {"version":3,"sources":["../src/clock.ts","../src/catalog.ts","../src/catalog-publisher.ts","../src/catalog-coverage.ts","../src/event-store.ts","../src/identifier.ts","../src/in-memory/stored-records.ts","../src/in-memory/in-memory-maintenance.ts","../src/in-memory/in-memory-row-locks.ts","../src/in-memory/in-memory-settlement.ts","../src/in-memory/in-memory-tables.ts","../src/in-memory-transaction.ts","../src/in-memory-event-store.ts","../src/shutdown-deadline.ts","../src/bus/bus-lifecycle.ts","../src/bus/handler-descriptions.ts","../src/tracing.ts","../src/bus-observation.ts","../src/dispatch-observation.ts","../src/dispatch/claim-loop.ts","../src/dispatch/claim-planner.ts","../src/dispatch/dispatch-context.ts","../src/lease-heartbeat.ts","../src/dispatch/delivery-executor.ts","../src/retry-policy.ts","../src/dispatch/delivery-outcomes.ts","../src/execution-scope.ts","../src/dispatch/handler-invocation.ts","../src/dispatch/in-flight-deliveries.ts","../src/dispatch/settlement-recovery.ts","../src/completion-batcher.ts","../src/delivery-timers.ts","../src/dispatcher.ts","../src/handler-registry.ts","../src/notifier.ts","../src/relay-bus-settings.ts","../src/route-groups.ts","../src/bus/bus-connections.ts","../src/bus/bus-maintenance.ts","../src/bus/event-publisher.ts","../src/received-envelope.ts","../src/bus/event-receiver.ts","../src/bus/relay-bus-assembly.ts","../src/transaction-budget.ts","../src/relay-bus.ts"],"names":["ConfigurationError","assertEventType","randomBytes","LeaseSettlement","CompositeKey","schedule","LifecycleError","toErrorInfo","InvalidEnvelopeError","durationMs","LeaseLostError","AttemptsExhaustedError","DispatcherStoppedError","validatePayload","Milliseconds","NonRetryableError","AsyncLocalStorage","HandlerTimeoutError","DeliveryLeaseIdentity","PositiveInteger","hostname","TransactionRequiredError","keyFromDefinition","TransactionTimeoutError","DrainIncompleteError"],"mappings":";;;;;;;;AAiBO,IAAM,WAAA,GAAqB;AAAA,EAChC,GAAA,EAAK,sBAAM,IAAI,IAAA;AACjB;;;ACoIA,IAAM,kBAAA,GAAqB,0BAAA;AAE3B,IAAM,YAAA,uBAAmB,OAAA,EAAoC;AAoBtD,SAAS,aAAA,CACd,MAAA,EACA,OAAA,GAAgC,EAAC,EACb;AACpB,EAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA,KAAS,SAAY,SAAA,GAAY,CAAA,SAAA,EAAY,QAAQ,IAAI,CAAA,CAAA,CAAA;AAC/E,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AAChC,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,IAAA,MAAM,IAAIA,oCAAA,CAAmB,CAAA,EAAG,KAAK,CAAA,gCAAA,CAAkC,CAAA;AAAA,EACzE;AACA,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAoB;AACvC,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,G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A,KAAA,MAAW,SAAA,IAAa,IAAA,CAAK,MAAA,CAAO,WAAA,CAAY,UAAA,EAAY;AAC1D,MAAA,IAAI;AACF,QAAA,MAAM,QAAA,CAAS,IAAA,CAAK,SAAA,CAAU,KAAA,CAAM,OAAO,CAAC,CAAA;AAAA,MAC9C,SAAS,KAAA,EAAO;AACd,QAAA,IAAA,CAAK,OAAO,MAAA,CAAO,KAAA;AAAA,UACjB,qEAAqE,SAAA,CAAU,IAAI,UAAUE,6BAAA,CAAY,KAAK,EAAE,OAAO,CAAA;AAAA,SACzH;AAAA,MACF;AAAA,IACF;AAAA,EACF;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 * 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';\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-options.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 type { ErrorInfo } from '../errors.js';\nimport type { DeliveryQuery, DeliveryStatus, PurgeRequest } from '../event-store.js';\nimport type { EventEnvelope } from '../event.js';\nimport type { SettlementChange } from '../store-kit/lease-settlement.js';\n\n// The rows of the in-memory store and the rules that read them, as pure functions.\n\nexport interface SerializedEnvelope extends Omit<EventEnvelope, 'occurredAt'> {\n readonly occurredAt: string;\n}\n\nexport interface 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\nexport interface 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/** Applies a retry, a release or a burial to a running delivery and clears its lease. */\nexport function applyTransition(delivery: StoredDelivery, change: SettlementChange): void {\n if (change.kind === 'reschedule') {\n delivery.status = 'pending';\n delivery.availableAt = change.availableAt;\n delivery.lastError = change.error;\n } else if (change.kind === 'release') {\n delivery.status = 'pending';\n delivery.attempts -= 1;\n delivery.availableAt = change.now;\n } else {\n delivery.status = 'dead';\n delivery.lastError = change.error;\n }\n delivery.updatedAt = change.now;\n clearLease(delivery);\n}\n\n/** Whether `other`, another delivery of the same handler and key, holds `delivery` back. */\nexport function 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 */\nexport function eventCutoffs(request: PurgeRequest): {\n orphanCutoff: number;\n completedCutoff: number;\n} {\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\nexport function serializeEnvelope(envelope: EventEnvelope): SerializedEnvelope {\n return JSON.parse(JSON.stringify(envelope)) as SerializedEnvelope;\n}\n\nexport function 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\nexport function dueAtOf(delivery: StoredDelivery): Date {\n return delivery.status === 'pending' ? delivery.availableAt : delivery.leaseExpiresAt!;\n}\n\nexport function 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\nexport function compareIds(left: string, right: string): number {\n return Number(left > right) - Number(left < right);\n}\n\nexport function clearLease(delivery: StoredDelivery): void {\n delivery.leaseOwner = null;\n delivery.leaseToken = null;\n delivery.leaseExpiresAt = null;\n}\n\nexport function 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\nexport function 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 {\n DeliveryQuery,\n DeliveryRecord,\n DeliveryStatus,\n EventStoreStatistics,\n PurgeRequest,\n PurgeResult,\n} from '../event-store.js';\nimport type { InMemoryRowLocks } from './in-memory-row-locks.js';\nimport type { InMemoryTables } from './in-memory-tables.js';\nimport {\n compareIds,\n dueAtOf,\n eventCutoffs,\n isDue,\n isPurgeable,\n matchesQuery,\n} from './stored-records.js';\n\nconst DEFAULT_LIST_LIMIT = 100;\n\n/** Listing, requeueing, purging and counting the deliveries of the in-memory store. */\nexport class InMemoryMaintenance {\n readonly #tables: InMemoryTables;\n readonly #locks: InMemoryRowLocks;\n\n constructor(tables: InMemoryTables, locks: InMemoryRowLocks) {\n this.#tables = tables;\n this.#locks = locks;\n }\n\n listDeliveries(query: DeliveryQuery): DeliveryRecord[] {\n const limit = query.limit ?? DEFAULT_LIST_LIMIT;\n const { events, deliveries } = this.#tables;\n return [...deliveries.values()]\n .filter((delivery) => matchesQuery(delivery, { event: 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.#tables.readEnvelope(delivery.eventId),\n }));\n }\n\n requeue(deliveryIds: readonly string[], now: Date): number {\n let moved = 0;\n for (const deliveryId of new Set(deliveryIds)) {\n const delivery = this.#tables.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 purge(request: PurgeRequest): PurgeResult {\n let deletedDeliveries = 0;\n const touchedEventIds = new Set<string>();\n for (const delivery of [...this.#tables.deliveries.values()]) {\n if (isPurgeable(delivery, request)) {\n this.#tables.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 statistics(now: Date): 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.#tables.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 /** Deletes the events no delivery references whose retention ran out; returns how many. */\n #purgeEvents(request: PurgeRequest, touchedEventIds: ReadonlySet<string>): number {\n const { events, deliveries } = this.#tables;\n const referencedEventIds = new Set(\n [...deliveries.values()].map((delivery) => delivery.eventId),\n );\n const { orphanCutoff, completedCutoff } = eventCutoffs(request);\n let deletedEvents = 0;\n for (const [eventId, event] of [...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.isHeld(`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 events.delete(eventId);\n deletedEvents += 1;\n }\n }\n return deletedEvents;\n }\n}\n","import type { InMemoryTransaction } from '../in-memory-transaction.js';\n\ninterface HeldLock {\n readonly owner: InMemoryTransaction;\n readonly released: Promise<void>;\n}\n\n/** The events and deliveries a transaction appended so far, which are not applied before it commits. */\nexport type PendingWrites = { eventIds: Set<string>; deliveryKeys: Set<string> };\n\n/** Row-lock emulation: event ids and ordering keys written by open transactions. */\nexport class InMemoryRowLocks {\n readonly #locks = new Map<string, HeldLock>();\n readonly #writes = new WeakMap<InMemoryTransaction, PendingWrites>();\n\n /** Whether an open transaction holds `name`. */\n isHeld(name: string): boolean {\n return this.#locks.has(name);\n }\n\n /** The events and deliveries the transaction appended so far, which are not applied before it commits. */\n written(transaction: InMemoryTransaction): PendingWrites {\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 /**\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","import type { LeaseReference } from '../event-store.js';\nimport type { InMemoryTransaction } from '../in-memory-transaction.js';\nimport {\n LeaseSettlement,\n type LeaseChange,\n type LeaseExtension,\n} from '../store-kit/lease-settlement.js';\nimport type { InMemoryTables } from './in-memory-tables.js';\nimport { applyTransition, clearLease, type StoredDelivery } from './stored-records.js';\n\n/**\n * Settles the claims of the in-memory store: a lease is held while its delivery is processing\n * under exactly that token. The store keeps no bookkeeping of handed-out leases.\n */\nexport class InMemorySettlement extends LeaseSettlement<StoredDelivery> {\n readonly #tables: InMemoryTables;\n readonly #retainCompleted: boolean;\n\n constructor(tables: InMemoryTables, retainCompleted: boolean) {\n super();\n this.#tables = tables;\n this.#retainCompleted = retainCompleted;\n }\n\n /** Completes now, or when `transaction` commits if the lease is still held then. */\n complete(\n lease: LeaseReference,\n { now, transaction }: { readonly now: Date; readonly transaction?: InMemoryTransaction },\n ): boolean {\n const delivery = this.findHeld(lease);\n if (delivery === undefined) {\n return false;\n }\n if (transaction === undefined) {\n this.#finish(delivery, now);\n return true;\n }\n transaction.enqueue(() => {\n const held = this.findHeld(lease);\n if (held !== undefined) {\n this.#finish(held, now);\n }\n });\n return true;\n }\n\n protected findHeld(lease: LeaseReference): StoredDelivery | undefined {\n const delivery = this.#tables.deliveries.get(lease.deliveryId);\n if (delivery?.status === 'processing' && delivery.leaseToken === lease.leaseToken) {\n return delivery;\n }\n return undefined;\n }\n\n protected writeChange(held: StoredDelivery, { change }: LeaseChange): boolean {\n applyTransition(held, change);\n return true;\n }\n\n /** The in-memory store always passes `now`: its `extendLease` takes it from the port. */\n protected writeExtension(held: StoredDelivery, { leaseExpiresAt, now }: LeaseExtension): boolean {\n held.leaseExpiresAt = leaseExpiresAt;\n held.updatedAt = now!;\n return true;\n }\n\n protected forgetHandedOut(): void {\n // Nothing is handed out: the store answers from the delivery itself.\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.#tables.events.get(delivery.eventId)!;\n if (event.completedAt === null || event.completedAt < now) {\n event.completedAt = now;\n }\n if (!this.#retainCompleted) {\n this.#tables.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","import type { EventEnvelope } from '../event.js';\nimport type { SerializedEnvelope, StoredDelivery, StoredEvent } from './stored-records.js';\n\n/** The rows of the in-memory store: events, deliveries and the sequence counter of each key. */\nexport class InMemoryTables {\n readonly events = new Map<string, StoredEvent>();\n readonly deliveries = new Map<string, StoredDelivery>();\n readonly #keySequences = new Map<string, number>();\n\n /** The next sequence of `key`; null for an unkeyed event. */\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 /** A fresh copy of a stored event, as a database would read it back. */\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","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 EventStore,\n EventStoreStatistics,\n LeaseReference,\n NewDelivery,\n PurgeRequest,\n PurgeResult,\n} from './event-store.js';\nimport { createUuidV7, type IdentifierGenerator } from './identifier.js';\nimport { InMemoryMaintenance } from './in-memory/in-memory-maintenance.js';\nimport { InMemoryRowLocks } from './in-memory/in-memory-row-locks.js';\nimport { InMemorySettlement } from './in-memory/in-memory-settlement.js';\nimport { InMemoryTables } from './in-memory/in-memory-tables.js';\nimport {\n blocksKey,\n compareDue,\n isDue,\n serializeEnvelope,\n type SerializedEnvelope,\n type StoredDelivery,\n} from './in-memory/stored-records.js';\nimport { InMemoryTransaction } from './in-memory-transaction.js';\nimport { CompositeKey } from './values/composite-key.js';\n\nexport interface InMemoryEventStoreOptions {\n /** Allow use when `NODE_ENV` is `production`. Data is lost on restart. Default false. */\n readonly allowInProduction?: boolean;\n readonly generateIdentifier?: IdentifierGenerator;\n /**\n * Keep a record of completed deliveries (status `completed`, listed, counted\n * and purged by `retention.completed`). Default false: a completed delivery\n * is deleted, like in the database stores.\n */\n readonly retainCompleted?: boolean;\n}\n\n/** 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\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 #tables = new InMemoryTables();\n readonly #locks = new InMemoryRowLocks();\n readonly #settlement: InMemorySettlement;\n readonly #maintenance = new InMemoryMaintenance(this.#tables, this.#locks);\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 this.#settlement = new InMemorySettlement(this.#tables, 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.#locks.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.#locks.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.#tables.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 = CompositeKey.of(eventId, delivery.handler);\n if (\n pendingDeliveryKeys.has(deliveryKey) ||\n this.#tables.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 const { events, deliveries } = this.#tables;\n if (!isDuplicate) {\n events.set(eventId, {\n envelope: serialized,\n sequence: this.#tables.nextSequence(serialized.key),\n createdAt: now,\n handlers: new Set(),\n completedAt: null,\n });\n }\n const stored = events.get(eventId)!;\n for (const delivery of newDeliveries) {\n stored.handlers.add(delivery.handler);\n 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.#tables.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.#tables.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.#settlement.extendLease({ lease, leaseExpiresAt, now });\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 return this.#settlement.complete(\n lease,\n transaction === undefined ? { now } : { now, transaction },\n );\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.#settlement.changeClaim({\n lease,\n change: { kind: 'reschedule', availableAt, error, now },\n });\n }\n\n async release(lease: LeaseReference, now: Date): Promise<boolean> {\n return this.#settlement.changeClaim({ lease, change: { kind: 'release', now } });\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.#settlement.changeClaim({ lease, change: { kind: 'bury', error, now } });\n }\n\n async listDeliveries(query: DeliveryQuery): Promise<DeliveryRecord[]> {\n return this.#maintenance.listDeliveries(query);\n }\n\n async requeue(deliveryIds: readonly string[], now: Date): Promise<number> {\n return this.#maintenance.requeue(deliveryIds, now);\n }\n\n async purge(request: PurgeRequest): Promise<PurgeResult> {\n return this.#maintenance.purge(request);\n }\n\n async statistics(now: Date): Promise<EventStoreStatistics> {\n return this.#maintenance.statistics(now);\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.#tables.deliveries.values()) {\n if (blocksKey(other, { delivery, now })) {\n return true;\n }\n }\n return false;\n }\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 type { Dispatcher } from '../dispatcher.js';\nimport { LifecycleError } from '../errors.js';\nimport type { CloseOptions, EventStore } from '../event-store.js';\nimport { withinDeadline, type ShutdownDeadline, type StopResult } from '../shutdown-deadline.js';\nimport type { BusMaintenance } from './bus-maintenance.js';\n\n/** Where a bus is in its one life: it starts once and, once stopped, stays stopped. */\nexport type BusState = 'idle' | 'starting' | 'running' | 'stopping' | 'stopped';\n\n/** What stopping a bus closes. */\nexport type BusLifecycleParts = {\n readonly store: EventStore;\n readonly clock: Clock;\n readonly dispatcher: Dispatcher;\n readonly maintenance: BusMaintenance;\n /** Closes every transport, each at most until the deadline. */\n readonly closeTransports: (deadline: ShutdownDeadline) => Promise<void>;\n};\n\n/** A stop request: the shared stop of every caller, and whether this caller started it. */\nexport type StopRequest = { readonly stopping: Promise<StopResult>; readonly first: boolean };\n\n/**\n * The state machine of a bus (idle, starting, running, stopping, stopped) and the shutdown that\n * moves it to stopped: stop the background jobs and the dispatcher, then close the transports\n * and the store, all within one deadline.\n */\nexport class BusLifecycle {\n readonly #parts: BusLifecycleParts;\n #state: BusState = 'idle';\n #starting: Promise<void> | undefined;\n #stopping: Promise<StopResult> | undefined;\n\n constructor(parts: BusLifecycleParts) {\n this.#parts = parts;\n }\n\n get state(): BusState {\n return this.#state;\n }\n\n /** Throws unless the bus is idle: a bus starts once. */\n assertStartable(): 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 }\n\n /** Runs `startComponents` as the start in progress, which a stop waits for; returns it. */\n beginStart(startComponents: () => Promise<void>): Promise<void> {\n this.#state = 'starting';\n this.#starting = startComponents();\n return this.#starting;\n }\n\n /** The start in progress settled. */\n endStart(): void {\n this.#starting = undefined;\n }\n\n markRunning(): void {\n this.#state = 'running';\n }\n\n markStopped(): void {\n this.#state = 'stopped';\n }\n\n /** The stop of the bus within `timeoutMs`; a later call shares the first one's. */\n stop(timeoutMs: number): StopRequest {\n if (this.#stopping !== undefined) {\n return { stopping: this.#stopping, first: false };\n }\n if (this.#state !== 'running' && this.#state !== 'starting') {\n return { stopping: this.#stopOutsideRun(timeoutMs), first: false };\n }\n this.#stopping = this.#stopComponents(timeoutMs);\n return { stopping: this.#stopping, first: true };\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.#parts.clock, timeoutMs }, (deadline) =>\n this.#parts.dispatcher.stop(deadline),\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.#parts.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.#parts.maintenance.stop();\n const abandoned = await this.#parts.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.#parts.closeTransports(deadline);\n const options: CloseOptions = { signal: deadline.signal };\n await deadline.race(Promise.resolve(this.#parts.store.close?.(options)));\n }\n}\n","import { assertEventType, type EventClass, type EventReference } from '../event.js';\nimport type { HandlerDescriptor, HandlerRegistration } from '../handler-registry.js';\nimport type { StandardSchemaV1 } from '../standard-schema.js';\n\n/** A registration as `bus.handlers()` lists it, once per event type. */\nexport function toDescriptor(\n registration: HandlerRegistration,\n eventType: string,\n): 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\n/** The type and schema of an event class, or of an event type given by name. */\nexport function 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","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 { ClaimedDelivery } from '../event-store.js';\nimport { schedule, type CancelTimer } from '../internal/timers.js';\nimport type { ClaimPlanner } from './claim-planner.js';\nimport type { DispatcherDependencies, ShutdownLatch } from './dispatch-context.js';\nimport type { InFlightDeliveries, InFlightDelivery } from './in-flight-deliveries.js';\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/** What the loop needs from the dispatcher. */\nexport type ClaimLoopParts = {\n readonly dependencies: DispatcherDependencies;\n readonly inFlight: InFlightDeliveries;\n readonly planner: ClaimPlanner;\n readonly shutdown: ShutdownLatch;\n /** Starts running a claimed delivery. */\n readonly start: (delivery: ClaimedDelivery) => InFlightDelivery;\n};\n\n/**\n * Decides when to claim: after a wake-up (merged over a short cooldown), when a group of slots\n * freed up, when a lone slot stayed free for a while, or at the poll interval. Claims for every\n * handler with room and starts what it got.\n */\nexport class ClaimLoop {\n readonly #parts: ClaimLoopParts;\n #running = false;\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\n constructor(parts: ClaimLoopParts) {\n this.#parts = parts;\n const { concurrency, batchSize } = parts.dependencies.settings;\n this.#refillThreshold = Math.ceil(Math.min(concurrency, batchSize) * REFILL_FRACTION);\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n /** Marks the loop running; {@link ClaimLoop.run} then claims until {@link ClaimLoop.halt}. */\n open(): void {\n this.#running = true;\n }\n\n /** Stops claiming: the running pass ends at its next wait. */\n halt(): void {\n this.#running = false;\n }\n\n /** Cancels the claims waiting for a timer and ends the current wait, so a halted loop returns. */\n interrupt(): void {\n this.#cooldownTimer?.();\n this.#cooldownTimer = undefined;\n this.#quietRefillTimer?.();\n this.#quietRefillTimer = undefined;\n this.#signal(this.#refillThreshold);\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.#parts.dependencies.clock, {\n run: () => {\n this.#cooldownTimer = undefined;\n this.#requestClaim();\n },\n delayMs: wait,\n });\n }\n\n /**\n * Claims until halted. 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 run(): 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.#parts.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 /**\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 /** Claims for every handler with room and starts what was claimed. */\n async claimAndStart(): Promise<ClaimRound & { readonly started: InFlightDelivery[] }> {\n const { dependencies, planner, shutdown, start } = this.#parts;\n const { store, registry, clock, settings, observation } = dependencies;\n const started: InFlightDelivery[] = [];\n let requested = 0;\n for (const request of planner.plan(registry.all(), this.#freeSlots())) {\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 // A wake-up that arrived while the claim ran may have brought what this claim could not see.\n this.#markExhausted(\n request.handlers,\n claimed.length < request.limit && wakeGeneration === this.#wakeGeneration,\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 shutdown.abandoned ? [] : claimed) {\n started.push(start(delivery));\n }\n }\n return { requested, claimed: started.length, started };\n }\n\n #markExhausted(handlers: readonly string[], exhausted: boolean): void {\n for (const handler of handlers) {\n if (exhausted) {\n this.#exhaustedHandlers.add(handler);\n } else {\n this.#exhaustedHandlers.delete(handler);\n }\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 /** 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.#parts.dependencies.clock, {\n run: () => {\n this.#signalledMinimum = 1;\n resolve();\n },\n delayMs: this.#parts.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 * 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.#parts.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.#parts.dependencies.settings.concurrency - this.#parts.inFlight.size;\n }\n}\n","import type { HandlerRegistration } from '../handler-registry.js';\nimport type { InFlightDeliveries } from './in-flight-deliveries.js';\n\n/** One claim of a round: the handlers it claims for and how many deliveries it may take. */\nexport interface ClaimPlan {\n readonly handlers: string[];\n readonly limit: number;\n}\n\n/**\n * Splits the free slots of a dispatcher into claims: one per handler with a concurrency limit and\n * room left, then one for every handler without a limit. A round never asks for more than a batch.\n */\nexport class ClaimPlanner {\n readonly #inFlight: InFlightDeliveries;\n readonly #batchSize: number;\n\n constructor(inFlight: InFlightDeliveries, batchSize: number) {\n this.#inFlight = inFlight;\n this.#batchSize = batchSize;\n }\n\n /** One claim for handlers without a concurrency limit, one per limited handler with room. */\n plan(registrations: readonly HandlerRegistration[], freeSlots: number): ClaimPlan[] {\n let free = Math.min(freeSlots, this.#batchSize);\n const plans: ClaimPlan[] = [];\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.#inFlight.countOf(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","import type { Clock } from '../clock.js';\nimport type { DispatchObservation } from '../dispatch-observation.js';\nimport type { EventStore } from '../event-store.js';\nimport type { HandlerRegistry } from '../handler-registry.js';\nimport type { Notifier } from '../notifier.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 * Whether a stop gave up at its deadline. Then the store may be closed: nothing more is\n * started, retried or written, and running deliveries are left to lease expiry.\n */\nexport class ShutdownLatch {\n #abandoned = false;\n\n get abandoned(): boolean {\n return this.#abandoned;\n }\n\n abandon(): void {\n this.#abandoned = true;\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 * The renewal state of one delivery's lease: the last expiry the store confirmed, and whether a\n * renewal is on its way.\n */\nclass LeaseRenewal {\n readonly #dependencies: HeartbeatDependencies;\n readonly #target: HeartbeatTarget;\n #confirmedExpiry: number;\n #renewing = false;\n\n constructor(dependencies: HeartbeatDependencies, target: HeartbeatTarget) {\n this.#dependencies = dependencies;\n this.#target = target;\n this.#confirmedExpiry = target.delivery.leaseExpiresAt.getTime();\n }\n\n /** One beat: aborts once the confirmed expiry passed, else renews unless a renewal is running. */\n beat(): void {\n const { store, clock, notifier, settings } = this.#dependencies;\n const now = clock.now();\n if (now.getTime() >= this.#confirmedExpiry) {\n this.#abortLeaseLost();\n return;\n }\n if (this.#renewing) {\n return;\n }\n this.#renewing = true;\n const expiry = now.getTime() + settings.leaseDurationMs;\n store\n .extendLease(this.#target.delivery, new Date(expiry), now)\n .then((extended) => {\n if (extended) {\n this.#confirmedExpiry = expiry;\n } else {\n this.#abortLeaseLost(true);\n }\n })\n .catch((error: unknown) => notifier.failure('extend-lease', error))\n .finally(() => {\n this.#renewing = false;\n });\n }\n\n #abortLeaseLost(storeConfirmed = false): void {\n const { delivery, controller } = this.#target;\n controller.abort(\n new LeaseLostError(`Lease on delivery ${delivery.deliveryId} was lost`, { storeConfirmed }),\n );\n }\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 dependencies: HeartbeatDependencies,\n target: HeartbeatTarget,\n): () => void {\n const renewal = new LeaseRenewal(dependencies, target);\n const { clock, settings } = dependencies;\n return schedule(clock, {\n run: () => renewal.beat(),\n delayMs: Math.max(1, Math.floor(settings.leaseDurationMs / RENEWALS_PER_LEASE)),\n repeat: true,\n unref: true,\n });\n}\n","import type { DeliveryTimers } from '../delivery-timers.js';\nimport { AttemptsExhaustedError, DispatcherStoppedError, LeaseLostError } from '../errors.js';\nimport { validatePayload, type EventEnvelope } from '../event.js';\nimport type { ClaimedDelivery } from '../event-store.js';\nimport type { HandlerRegistration } from '../handler-registry.js';\nimport { schedule } from '../internal/timers.js';\nimport { startLeaseHeartbeat } from '../lease-heartbeat.js';\nimport type { DispatcherDependencies, ShutdownLatch } from './dispatch-context.js';\nimport type { DeliveryOutcomes, HandlerOutcome } from './delivery-outcomes.js';\nimport type { HandlerInvocation } from './handler-invocation.js';\nimport type { InFlightDeliveries, InFlightDelivery } from './in-flight-deliveries.js';\nimport type { SettlementRecovery } from './settlement-recovery.js';\n\n/** A claimed delivery and the controller that aborts its handler. */\ntype DeliveryRun = { readonly delivery: ClaimedDelivery; readonly controller: AbortController };\n\n/** What runs a delivery. */\nexport type DeliveryExecutorParts = {\n readonly dependencies: DispatcherDependencies;\n readonly inFlight: InFlightDeliveries;\n readonly recovery: SettlementRecovery;\n readonly outcomes: DeliveryOutcomes;\n readonly invocation: HandlerInvocation;\n readonly timers: DeliveryTimers;\n readonly shutdown: ShutdownLatch;\n /** Told when a delivery settled, and whether its handler succeeded. */\n readonly onSettled: (delivery: ClaimedDelivery, succeeded: boolean) => void;\n};\n\n/**\n * Runs claimed deliveries: keeps each lease (heartbeat, or one extension for a transactional\n * handler), validates the payload, calls the handler and records the outcome.\n */\nexport class DeliveryExecutor {\n readonly #parts: DeliveryExecutorParts;\n /** Stops the lease renewal (or transactional lease guard) of each delivery whose handler runs. */\n readonly #leaseKeepers = new Map<ClaimedDelivery, () => void>();\n\n constructor(parts: DeliveryExecutorParts) {\n this.#parts = parts;\n }\n\n /** Starts a delivery and tracks it as in flight until it settled. */\n start(delivery: ClaimedDelivery): InFlightDelivery {\n const { dependencies, inFlight, onSettled } = this.#parts;\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) => dependencies.notifier.failure('dispatch', error))\n .finally(() => {\n inFlight.delete(entry);\n onSettled(delivery, succeeded);\n }),\n };\n inFlight.add(entry);\n return entry;\n }\n\n /** Stop gave up: lets every lease run out, so that another process takes the deliveries. */\n abandon(): void {\n for (const stopKeeping of this.#leaseKeepers.values()) {\n stopKeeping();\n }\n this.#leaseKeepers.clear();\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 { dependencies, recovery, outcomes } = this.#parts;\n const { registry, notifier, clock } = dependencies;\n const registration = registry.get(delivery.handler)!;\n recovery.forgetEarlierClaims(delivery);\n notifier.notify('onDeliveryStarted', { delivery });\n const startedAt = clock.now().getTime();\n if (delivery.attempt > registration.retry.attempts) {\n await outcomes.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(dependencies, { delivery, controller });\n this.#leaseKeepers.set(delivery, stopHeartbeat);\n const outcome = await this.#runHandler(registration, { delivery, controller });\n this.#reportSuccess(delivery, { outcome, durationMs: clock.now().getTime() - startedAt });\n return true;\n } catch (error) {\n if (this.#parts.shutdown.abandoned) {\n // Stop gave this delivery up and the store may be closed: its lease expires instead.\n return false;\n }\n const recording = this.#recordFailure(registration, { delivery, error });\n if (recording !== undefined) {\n await recording;\n }\n return false;\n } finally {\n stopHeartbeat();\n this.#leaseKeepers.delete(delivery);\n }\n }\n\n /** Reports a success now, or once a completion the store did not confirm is recovered. */\n #reportSuccess(\n delivery: ClaimedDelivery,\n { outcome, durationMs }: { readonly outcome: HandlerOutcome; readonly durationMs: number },\n ): void {\n const { dependencies, outcomes, recovery } = this.#parts;\n const { notifier } = dependencies;\n if (outcome === 'completed') {\n notifier.notify('onDeliverySucceeded', { delivery, durationMs });\n } else {\n recovery.retain({\n delivery,\n settle: () => outcomes.complete(delivery),\n applied: () => notifier.notify('onDeliverySucceeded', { delivery, durationMs }),\n });\n }\n }\n\n /** Records a failed run; undefined when there is nothing to record (the store confirmed the lost lease). */\n #recordFailure(\n registration: HandlerRegistration,\n { delivery, error }: { readonly delivery: ClaimedDelivery; readonly error: unknown },\n ): Promise<void> | undefined {\n const { dependencies, outcomes } = this.#parts;\n if (error instanceof LeaseLostError) {\n dependencies.notifier.notify('onLeaseLost', { delivery });\n return error.storeConfirmed\n ? undefined\n : outcomes.giveBack(registration, { delivery, error });\n }\n if (error instanceof DispatcherStoppedError) {\n return outcomes.release(delivery);\n }\n return outcomes.fail(registration, { delivery, error });\n }\n\n async #runHandler(\n registration: HandlerRegistration,\n { delivery, controller }: DeliveryRun,\n ): Promise<HandlerOutcome> {\n const { dependencies, invocation, outcomes } = this.#parts;\n const { store, clock } = 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 invocation.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 invocation.invoke({ registration, event, delivery, controller, transaction: undefined });\n return outcomes.confirmCompletion(delivery);\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, controller }: DeliveryRun,\n ): Promise<() => void> {\n const { store, clock, settings } = this.#parts.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","import { type Duration } from './duration.js';\nimport { Milliseconds } from './values/milliseconds.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 : Milliseconds.of(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 : Milliseconds.of(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 { CompletionBatcher } from '../completion-batcher.js';\nimport { LeaseLostError, toErrorInfo } from '../errors.js';\nimport type { ClaimedDelivery } from '../event-store.js';\nimport type { HandlerRegistration } from '../handler-registry.js';\nimport { computeRetryDelay, isRetryableError } from '../retry-policy.js';\nimport type { DispatcherDependencies, ShutdownLatch } from './dispatch-context.js';\nimport type { SettlementRecovery } from './settlement-recovery.js';\n\n/** How a handler run ended for the store: recorded, or left to lease expiry. */\nexport type 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/** A delivery and why its run failed. */\ntype FailedRun<TError = unknown> = { readonly delivery: ClaimedDelivery; readonly error: TError };\n\n/** One state change of a finished delivery, with what to report once the store applied it. */\ntype StateChange = {\n readonly operation: 'reschedule' | 'bury' | 'release';\n readonly delivery: ClaimedDelivery;\n /** Writes the change now. */\n readonly write: () => Promise<boolean>;\n /** Writes it again when the store failed; recovered later. */\n readonly rewrite: () => Promise<boolean>;\n readonly applied: () => void;\n};\n\n/** What the dispatcher needs to record the outcome of a delivery. */\nexport type DeliveryOutcomesParts = {\n readonly dependencies: DispatcherDependencies;\n readonly recovery: SettlementRecovery;\n readonly shutdown: ShutdownLatch;\n readonly completions: CompletionBatcher | undefined;\n readonly sleep: (milliseconds: number) => Promise<void>;\n};\n\n/**\n * Records how deliveries ended: completion (confirmed against transient store errors), retry with\n * backoff, dead-lettering and release. A state change the store fails to apply is handed to\n * {@link SettlementRecovery}; one the store refuses means the lease is lost. The state changes are\n * not async themselves: each awaits the store once, inside `#change`.\n */\nexport class DeliveryOutcomes {\n readonly #parts: DeliveryOutcomesParts;\n\n constructor(parts: DeliveryOutcomesParts) {\n this.#parts = parts;\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 { dependencies, shutdown, sleep } = this.#parts;\n for (let attempt = 0; ; attempt += 1) {\n if (shutdown.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 dependencies.notifier.failure('complete', error);\n return 'unconfirmed';\n }\n await 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 { dependencies, completions } = this.#parts;\n const { store, clock } = dependencies;\n return completions === undefined\n ? store.complete(delivery, clock.now())\n : completions.submit(delivery);\n }\n\n async fail(registration: HandlerRegistration, { delivery, error }: FailedRun): 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 /**\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 }: FailedRun<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 bury(delivery: ClaimedDelivery, error: unknown): Promise<void> {\n const { store, clock, notifier } = this.#parts.dependencies;\n const errorInfo = toErrorInfo(error);\n return this.#change({\n operation: 'bury',\n delivery,\n write: () => store.bury(delivery, errorInfo, clock.now()),\n rewrite: () => store.bury(delivery, errorInfo, clock.now()),\n applied: () => notifier.notify('onDeliveryDead', { delivery, error: errorInfo }),\n });\n }\n\n release(delivery: ClaimedDelivery): Promise<void> {\n const { store, clock, notifier } = this.#parts.dependencies;\n return this.#change({\n operation: 'release',\n delivery,\n write: () => store.release(delivery, clock.now()),\n rewrite: () => store.release(delivery, clock.now()),\n applied: () => notifier.notify('onDeliveryReleased', { delivery }),\n });\n }\n\n /** Schedules the next attempt with the retry policy's backoff. */\n #reschedule(registration: HandlerRegistration, { delivery, error }: FailedRun): Promise<void> {\n const { store, clock, random, notifier } = this.#parts.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 const write = (): Promise<boolean> => store.reschedule(delivery, availableAt, errorInfo, now);\n return this.#change({\n operation: 'reschedule',\n delivery,\n write,\n rewrite: write,\n applied: () =>\n notifier.notify('onDeliveryRetryScheduled', { delivery, error: errorInfo, availableAt }),\n });\n }\n\n /** Writes a state change; reports it, or the lost lease, or retains it when the store failed. */\n async #change(change: StateChange): Promise<void> {\n const { dependencies, recovery } = this.#parts;\n const { delivery } = change;\n let changed: boolean;\n try {\n changed = await change.write();\n } catch (storeError) {\n dependencies.notifier.failure(change.operation, storeError);\n recovery.retain({ delivery, settle: change.rewrite, applied: change.applied });\n return;\n }\n if (changed) {\n change.applied();\n } else {\n dependencies.notifier.notify('onLeaseLost', { delivery });\n }\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { EventEnvelope } from './event.js';\n\nexport interface ExecutionScope {\n /** Transaction that `publish` joins when none is passed explicitly. */\n readonly transaction?: unknown;\n /** Event being handled. Events published while handling it inherit correlation. */\n readonly event?: EventEnvelope;\n}\n\nconst storage = new AsyncLocalStorage<ExecutionScope>();\n\n/** Runs `work` in `scope`, layered over the caller's scope. */\nexport function runInScope<T>(scope: ExecutionScope, work: () => T): T {\n return storage.run({ ...storage.getStore(), ...scope }, work);\n}\n\n/** Runs `work` in exactly `scope`, ignoring the caller's scope. */\nexport function runInIsolatedScope<T>(scope: ExecutionScope, work: () => T): T {\n return storage.run(scope, work);\n}\n\nexport function getCurrentScope(): ExecutionScope | undefined {\n return storage.getStore();\n}\n","import type { Clock } from '../clock.js';\nimport type { DeliveryTimers } from '../delivery-timers.js';\nimport { DispatcherStoppedError, HandlerTimeoutError } from '../errors.js';\nimport type { EventEnvelope } from '../event.js';\nimport type { ClaimedDelivery } from '../event-store.js';\nimport { runInIsolatedScope } from '../execution-scope.js';\nimport type { HandlerContext, HandlerRegistration } from '../handler-registry.js';\nimport { schedule, type CancelTimer } from '../internal/timers.js';\nimport type { DispatcherDependencies } from './dispatch-context.js';\n\n/** One run of a handler: the delivery, its validated event and the transaction it runs in, if any. */\nexport type InvokeInput = {\n readonly registration: HandlerRegistration;\n readonly event: EventEnvelope;\n readonly delivery: ClaimedDelivery;\n readonly controller: AbortController;\n readonly transaction: unknown;\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\n/**\n * Calls a handler: in an isolated execution scope, observed when the bus is, bounded by its\n * timeout and abortable. A handler that is abandoned (aborted) is still waited for before the\n * delivery moves on, so a retry never overlaps it.\n */\nexport class HandlerInvocation {\n readonly #dependencies: DispatcherDependencies;\n readonly #timers: DeliveryTimers;\n\n constructor(dependencies: DispatcherDependencies, timers: DeliveryTimers) {\n this.#dependencies = dependencies;\n this.#timers = timers;\n }\n\n async invoke(input: InvokeInput): Promise<void> {\n const { registration, event, delivery, controller, transaction } = input;\n const context = contextOf(input);\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 const cancelTimeout = this.#startTimeout(registration, controller);\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 /** Aborts the handler when its timeout passes; undefined for a handler without one. */\n #startTimeout(\n registration: HandlerRegistration,\n controller: AbortController,\n ): CancelTimer | undefined {\n if (registration.timeoutMs === null) {\n return undefined;\n }\n const timeoutMs = registration.timeoutMs;\n return 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\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 waitUntil(this.#dependencies.clock, { work: settledWork, deadline });\n }\n}\n\n/** What the handler learns about its delivery. */\nfunction contextOf(input: InvokeInput): HandlerContext {\n const { registration, delivery, controller, transaction } = input;\n return {\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}\n\nasync function waitUntil(\n clock: Clock,\n { work, deadline }: { readonly work: Promise<unknown>; readonly deadline: number },\n): Promise<'done' | 'timeout'> {\n let cancel: CancelTimer | undefined;\n const timedOut = new Promise<'timeout'>((resolve) => {\n cancel = schedule(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","import type { HandlerRegistration } from '../handler-registry.js';\n\n/** A delivery whose handler runs: what aborts it and what settles when it is done. */\nexport interface InFlightDelivery {\n readonly handler: string;\n readonly controller: AbortController;\n readonly settled: Promise<void>;\n}\n\n/** The deliveries a dispatcher runs right now: its concurrency budget and its shutdown list. */\nexport class InFlightDeliveries {\n readonly #deliveries = new Set<InFlightDelivery>();\n\n get size(): number {\n return this.#deliveries.size;\n }\n\n add(delivery: InFlightDelivery): void {\n this.#deliveries.add(delivery);\n }\n\n delete(delivery: InFlightDelivery): void {\n this.#deliveries.delete(delivery);\n }\n\n /** How many of the deliveries run a handler of `registration`. */\n countOf(registration: HandlerRegistration): number {\n let count = 0;\n for (const delivery of this.#deliveries) {\n if (registration.claimIds.includes(delivery.handler)) {\n count += 1;\n }\n }\n return count;\n }\n\n /** Settles once every delivery running now settled, whatever its outcome. */\n allSettled(): Promise<PromiseSettledResult<void>[]> {\n return Promise.allSettled([...this.#deliveries].map((delivery) => delivery.settled));\n }\n\n abortAll(reason: Error): void {\n for (const delivery of this.#deliveries) {\n delivery.controller.abort(reason);\n }\n }\n}\n","import type { ClaimedDelivery } from '../event-store.js';\nimport { schedule, type CancelTimer } from '../internal/timers.js';\nimport type { ShutdownDeadline } from '../shutdown-deadline.js';\nimport { DeliveryLeaseIdentity } from '../values/delivery-lease-identity.js';\nimport type { DispatcherDependencies, ShutdownLatch } from './dispatch-context.js';\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 */\nexport interface 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\n/** Settlements are pending per claim: an older claim of a delivery must never replace or remove the newer one's. */\nfunction pendingKeyOf(delivery: ClaimedDelivery): string {\n return DeliveryLeaseIdentity.of(delivery.deliveryId, delivery.leaseToken);\n}\n\n/** Retries, every poll interval, the settlements the store failed to apply, until it answers. */\nexport class SettlementRecovery {\n readonly #dependencies: DispatcherDependencies;\n readonly #shutdown: ShutdownLatch;\n readonly #pending = new Map<string, PendingSettlement>();\n #recoveryTimer: CancelTimer | undefined;\n #recovery: Promise<void> | undefined;\n\n constructor(dependencies: DispatcherDependencies, shutdown: ShutdownLatch) {\n this.#dependencies = dependencies;\n this.#shutdown = shutdown;\n }\n\n retain(entry: PendingSettlement): void {\n if (this.#shutdown.abandoned) {\n return;\n }\n this.#pending.set(pendingKeyOf(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 /** A new claim of this delivery makes whatever was pending for its earlier claims moot. */\n forgetEarlierClaims(delivery: ClaimedDelivery): void {\n for (const key of [...this.#pending.keys()].filter((pending) =>\n pending.startsWith(DeliveryLeaseIdentity.prefixOf(delivery.deliveryId)),\n )) {\n this.#pending.delete(key);\n }\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 close(deadline: ShutdownDeadline): Promise<void> {\n this.#stopTimer();\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 /** Stop gave up: forgets every settlement still to retry, which may reach a closed store. */\n abandon(): void {\n this.#stopTimer();\n this.#pending.clear();\n }\n\n #stopTimer(): void {\n this.#recoveryTimer?.();\n this.#recoveryTimer = undefined;\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(pendingKeyOf(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","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 { ClaimLoop } from './dispatch/claim-loop.js';\nimport { ClaimPlanner } from './dispatch/claim-planner.js';\nimport { ShutdownLatch, type DispatcherDependencies } from './dispatch/dispatch-context.js';\nimport { DeliveryExecutor } from './dispatch/delivery-executor.js';\nimport { DeliveryOutcomes } from './dispatch/delivery-outcomes.js';\nimport { HandlerInvocation } from './dispatch/handler-invocation.js';\nimport { InFlightDeliveries } from './dispatch/in-flight-deliveries.js';\nimport { SettlementRecovery } from './dispatch/settlement-recovery.js';\nimport { CompletionBatcher } from './completion-batcher.js';\nimport { DeliveryTimers } from './delivery-timers.js';\nimport { DispatcherStoppedError } from './errors.js';\nimport { ShutdownDeadline } from './shutdown-deadline.js';\n\nexport type { DispatcherDependencies, DispatcherSettings } from './dispatch/dispatch-context.js';\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. A facade over its parts: the {@link ClaimLoop} decides when to claim, the\n * {@link DeliveryExecutor} runs what was claimed, {@link DeliveryOutcomes} records how it ended\n * and {@link SettlementRecovery} retries what the store failed to record.\n */\nexport class Dispatcher {\n readonly #dependencies: DispatcherDependencies;\n readonly #inFlight = new InFlightDeliveries();\n readonly #shutdown = new ShutdownLatch();\n readonly #timers: DeliveryTimers;\n readonly #completions: CompletionBatcher | undefined;\n readonly #recovery: SettlementRecovery;\n readonly #executor: DeliveryExecutor;\n readonly #loop: ClaimLoop;\n #looping: Promise<void> | undefined;\n #unwatch: (() => Promise<void>) | undefined;\n #watching: Promise<void> | undefined;\n\n constructor(dependencies: DispatcherDependencies) {\n this.#dependencies = dependencies;\n this.#timers = new DeliveryTimers(dependencies.clock);\n this.#completions = this.#createCompletionBatcher();\n this.#recovery = new SettlementRecovery(dependencies, this.#shutdown);\n this.#executor = this.#createExecutor();\n this.#loop = new ClaimLoop({\n dependencies,\n inFlight: this.#inFlight,\n planner: new ClaimPlanner(this.#inFlight, dependencies.settings.batchSize),\n shutdown: this.#shutdown,\n start: (delivery) => this.#executor.start(delivery),\n });\n }\n\n #createCompletionBatcher(): CompletionBatcher | undefined {\n const { store, clock, settings } = this.#dependencies;\n const { completionBatchWindowMs: windowMs = 0, completionBatchSize: maxBatchSize = 1 } =\n settings;\n if (store.completeMany === undefined || !(windowMs > 0)) {\n return undefined;\n }\n return new CompletionBatcher(\n { completeMany: (leases, now) => store.completeMany!(leases, now) },\n clock,\n { windowMs, maxBatchSize },\n () => this.#inFlight.size,\n );\n }\n\n #createExecutor(): DeliveryExecutor {\n const dependencies = this.#dependencies;\n const outcomes = new DeliveryOutcomes({\n dependencies,\n recovery: this.#recovery,\n shutdown: this.#shutdown,\n completions: this.#completions,\n sleep: dependencies.sleep ?? ((milliseconds) => this.#timers.sleep(milliseconds)),\n });\n return new DeliveryExecutor({\n dependencies,\n inFlight: this.#inFlight,\n recovery: this.#recovery,\n outcomes,\n invocation: new HandlerInvocation(dependencies, this.#timers),\n timers: this.#timers,\n shutdown: this.#shutdown,\n onSettled: (delivery, succeeded) => this.#loop.onSettled(delivery, succeeded),\n });\n }\n\n get isRunning(): boolean {\n return this.#loop.isRunning;\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.#loop.isRunning) {\n return;\n }\n this.#loop.open();\n this.#completions?.setClosing(false);\n this.#watching = this.#watchNewDeliveries();\n this.#looping = this.#loop.run();\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 this.#loop.wake();\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.#loop.isRunning) {\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.#loop.isRunning) {\n // Batches run by hand (`runOnce`) leave settlements to recover without ever starting the loop.\n await this.#recovery.close(deadline);\n return 0;\n }\n this.#loop.halt();\n this.#completions?.setClosing(true);\n this.#loop.interrupt();\n await deadline.race(this.#stopWatching());\n await deadline.race(this.#looping!);\n const settled = this.#inFlight.allSettled();\n if ((await deadline.raceDrain(settled)) === 'timeout') {\n this.#inFlight.abortAll(new DispatcherStoppedError('relaybus dispatcher stopped'));\n if ((await deadline.race(settled)) === 'timeout') {\n return this.#abandon();\n }\n }\n await this.#recovery.close(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.#shutdown.abandon();\n // Their leases must run out, so that another process takes the deliveries.\n this.#executor.abandon();\n this.#timers.cancelAll();\n this.#recovery.abandon();\n return this.#inFlight.size;\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.#loop.claimAndStart();\n await Promise.allSettled(started.map((delivery) => delivery.settled));\n return started.length;\n }\n}\n","import { type Duration } from './duration.js';\nimport { Milliseconds } from './values/milliseconds.js';\nimport { ConfigurationError } from './errors.js';\nimport { PositiveInteger } from './values/positive-integer.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 PositiveInteger.of(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 Milliseconds.forTimer(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 { hostname } from 'node:os';\nimport type { DispatcherSettings } from './dispatcher.js';\nimport { Milliseconds } from './values/milliseconds.js';\nimport { ConfigurationError } from './errors.js';\nimport type { RegistrationDefaults } from './handler-registry.js';\nimport type { IdentifierGenerator } from './identifier.js';\nimport { PositiveInteger } from './values/positive-integer.js';\nimport type { DispatcherOptions, RelayBusOptions, RetentionOptions } from './relay-bus-options.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 : Milliseconds.forTimer(options.backlogInterval, 'backlogInterval');\n}\n\nexport function resolveTransactionTimeout<TTransaction>(\n options: RelayBusOptions<TTransaction>,\n): number {\n return Milliseconds.forTimer(\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 : Milliseconds.forTimer(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 = PositiveInteger.of(\n dispatcher.concurrency ?? DEFAULTS.concurrency,\n 'dispatcher.concurrency',\n );\n return {\n owner: `${hostname()}:${process.pid}:${generateIdentifier()}`,\n concurrency,\n batchSize: PositiveInteger.of(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: Milliseconds.forTimer(\n dispatcher.pollInterval ?? DEFAULTS.pollInterval,\n 'dispatcher.pollInterval',\n ),\n leaseDurationMs: Milliseconds.forTimer(\n dispatcher.leaseDuration ?? DEFAULTS.leaseDuration,\n 'dispatcher.leaseDuration',\n ),\n shutdownTimeoutMs: Milliseconds.forTimer(\n dispatcher.shutdownTimeout ?? DEFAULTS.shutdownTimeout,\n 'dispatcher.shutdownTimeout',\n ),\n completionBatchWindowMs: Milliseconds.of(\n dispatcher.completionBatchWindow ?? DEFAULTS.completionBatchWindow,\n 'dispatcher.completionBatchWindow',\n ),\n completionBatchSize: PositiveInteger.of(\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 : Milliseconds.of(completed, 'retention.completed'),\n deadMs: dead === false ? null : Milliseconds.of(dead, 'retention.dead'),\n intervalMs: Milliseconds.forTimer(\n options?.interval ?? DEFAULTS.retentionInterval,\n 'retention.interval',\n ),\n };\n}\n","import { Milliseconds } from './values/milliseconds.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-options.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 : Milliseconds.forTimer(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 { BusObservation, ReceiveOrigin } from '../bus-observation.js';\nimport { ConfigurationError, toErrorInfo } from '../errors.js';\nimport type { EventEnvelope } from '../event.js';\nimport type { HandlerRegistry } from '../handler-registry.js';\nimport type { Notifier } from '../notifier.js';\nimport type { InboundSubscriptionOptions, RouteOptions } from '../relay-bus-options.js';\nimport { DEFAULTS } from '../relay-bus-settings.js';\nimport { DEFAULT_ROUTE_RETRY_POLICY } from '../retry-policy.js';\nimport { groupRoutes, type RouteGroup } from '../route-groups.js';\nimport type { Transport, TransportSubscriptionHooks } from '../transport.js';\n\n/** What the connections of a bus need. */\nexport type BusConnectionsParts = {\n readonly registry: HandlerRegistry;\n readonly notifier: Notifier;\n readonly observation: BusObservation | undefined;\n};\n\n/** The transports, routes and subscriptions a bus was configured with. */\nexport type BusConnectionsOptions = {\n readonly transports: readonly Transport[];\n readonly routes: readonly RouteOptions[];\n readonly subscriptions: readonly InboundSubscriptionOptions[];\n};\n\n/**\n * The transports of a bus by name, its routes (registered as forwarding handlers) and its inbound\n * subscriptions: checked when the bus is built, connected when it starts.\n */\nexport class BusConnections {\n readonly #parts: BusConnectionsParts;\n readonly #transports = new Map<string, Transport>();\n readonly #subscriptions: readonly InboundSubscriptionOptions[];\n\n constructor(parts: BusConnectionsParts, subscriptions: readonly InboundSubscriptionOptions[]) {\n this.#parts = parts;\n this.#subscriptions = subscriptions;\n }\n\n /** Every transport, in the order it was configured. */\n get transports(): Iterable<Transport> {\n return this.#transports.values();\n }\n\n /** Registers the transports, then the routes, and checks the subscriptions. */\n register({ transports, routes }: Omit<BusConnectionsOptions, 'subscriptions'>): void {\n for (const transport of 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(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 }\n\n /** True while every transport reports itself ready. */\n allReady(): boolean {\n for (const transport of this.#transports.values()) {\n if (transport.isReady?.() === false) {\n return false;\n }\n }\n return true;\n }\n\n /** The inbound subscriptions, each with a transport that can subscribe. */\n get subscriptions(): readonly InboundSubscriptionOptions[] {\n return this.#subscriptions;\n }\n\n /** Subscribes one subscription, handing its messages to `receive`; the transport's own promise. */\n subscribe(\n subscription: InboundSubscriptionOptions,\n receive: (envelope: EventEnvelope, origin: ReceiveOrigin) => Promise<unknown>,\n ): Promise<void> {\n const transport = this.#transports.get(subscription.transport)!;\n return transport.subscribe!(\n subscription.destinations,\n async (envelope, message) => {\n await receive(envelope, { transport, destination: message?.destination });\n },\n this.#subscriptionHooks(transport),\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 const { notifier } = this.#parts;\n if (!notifier.wants('onInvalidMessage')) {\n return undefined;\n }\n return {\n onInvalidMessage: ({ destination, error }) => {\n const errorInfo = toErrorInfo(error);\n 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 #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.#parts.registry.register(\n {\n eventTypes: group.eventTypes,\n legacyIds: group.legacyIds,\n schema: undefined,\n handle:\n this.#parts.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","import type { BusObservation } from '../bus-observation.js';\nimport type { Clock } from '../clock.js';\nimport type { EventStore, EventStoreStatistics, PurgeResult } from '../event-store.js';\nimport { schedule, type CancelTimer } from '../internal/timers.js';\nimport type { Notifier } from '../notifier.js';\n\n/** How long completed and dead deliveries are kept (null: for ever), and how often that is applied. */\nexport type RetentionSettings = {\n readonly completedMs: number | null;\n readonly deadMs: number | null;\n readonly intervalMs: number;\n};\n\n/** What the background jobs of a running bus need. */\nexport type BusMaintenanceParts = {\n readonly store: EventStore;\n readonly clock: Clock;\n readonly notifier: Notifier;\n readonly observation: BusObservation | undefined;\n readonly retention: RetentionSettings;\n /** How often the backlog is reported; undefined when nobody wants it. */\n readonly backlogIntervalMs: number | undefined;\n readonly statistics: () => Promise<EventStoreStatistics>;\n};\n\n/** The background jobs of a running bus: the retention purge and the backlog report. */\nexport class BusMaintenance {\n readonly #parts: BusMaintenanceParts;\n #retentionTimer: CancelTimer | undefined;\n #backlogTimer: CancelTimer | undefined;\n\n constructor(parts: BusMaintenanceParts) {\n this.#parts = parts;\n }\n\n /** Applies the retention policy once. */\n async purgeExpired(): Promise<PurgeResult> {\n const { store, clock, notifier, retention } = this.#parts;\n const now = clock.now().getTime();\n const { completedMs, deadMs } = retention;\n try {\n const result = await store.purge({\n ...(completedMs === null ? {} : { completedBefore: new Date(now - completedMs) }),\n ...(deadMs === null ? {} : { deadBefore: new Date(now - deadMs) }),\n });\n notifier.notify('onPurged', { result });\n return result;\n } catch (error) {\n notifier.failure('purge', error);\n throw error;\n }\n }\n\n /** Starts the retention purge and the backlog report, each when it has anything to do. */\n start(): void {\n this.#scheduleRetention();\n this.#scheduleBacklog();\n }\n\n stop(): void {\n this.#retentionTimer?.();\n this.#backlogTimer?.();\n }\n\n /** Applies the retention policy every `retention.interval` while the bus runs, when it deletes anything. */\n #scheduleRetention(): void {\n const { clock, retention } = this.#parts;\n if (retention.completedMs !== null || retention.deadMs !== null) {\n this.#retentionTimer = schedule(clock, {\n run: () => {\n this.purgeExpired().catch(() => undefined);\n },\n delayMs: 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 const { observation, backlogIntervalMs, statistics } = this.#parts;\n if (backlogIntervalMs !== undefined) {\n this.#backlogTimer = observation?.startBacklog({ intervalMs: backlogIntervalMs, statistics });\n }\n }\n}\n","import { withTraceHeaders, type BusObservation } from '../bus-observation.js';\nimport type { Clock } from '../clock.js';\nimport { ConfigurationError, TransactionRequiredError } from '../errors.js';\nimport type { AppendEntry, AppendResult, EventStore, NewDelivery } from '../event-store.js';\nimport {\n assertEventType,\n keyFromDefinition,\n validatePayload,\n type DomainEvent,\n type EventClass,\n type EventEnvelope,\n} from '../event.js';\nimport { getCurrentScope, type ExecutionScope } from '../execution-scope.js';\nimport type { HandlerRegistration, HandlerRegistry } from '../handler-registry.js';\nimport type { IdentifierGenerator } from '../identifier.js';\nimport type { Notifier } from '../notifier.js';\nimport type { PublishOptions, TransactionMode } from '../relay-bus-options.js';\nimport { Milliseconds } from '../values/milliseconds.js';\n\n/** The options of one publish call, and the id `publish` (not `publishAll`) may fix. */\nexport type PublishCall<TTransaction> = {\n readonly options: PublishOptions<TTransaction>;\n readonly id: string | undefined;\n};\n\n/** What a publish call inherits from the running handler and the clock. */\ntype PublishContext<TTransaction> = PublishCall<TTransaction> & {\n readonly scope: ExecutionScope | undefined;\n readonly now: Date;\n};\n\n/** One event of a publish call with what it inherits from the call and the running handler. */\ntype CreateEnvelopeInput<TTransaction> = PublishContext<TTransaction> & {\n readonly event: DomainEvent;\n readonly correlationId: string | undefined;\n};\n\n/** What publishing needs from the bus. */\nexport type EventPublisherParts<TTransaction> = {\n readonly store: EventStore<TTransaction>;\n readonly registry: HandlerRegistry;\n readonly clock: Clock;\n readonly notifier: Notifier;\n readonly observation: BusObservation | undefined;\n readonly source: string;\n readonly transactionMode: TransactionMode;\n readonly transactionResolver: (() => TTransaction | undefined) | undefined;\n readonly generateIdentifier: IdentifierGenerator;\n readonly createDelivery: (registration: HandlerRegistration, availableAt: Date) => NewDelivery;\n /** Logs or throws for an event no handler or route takes. */\n readonly reportUnrouted: (envelope: EventEnvelope) => void;\n /** Wakes the dispatcher shortly after new deliveries were stored. */\n readonly scheduleWake: () => void;\n};\n\n/**\n * Stores published events in the caller's transaction: builds each envelope (id, key,\n * correlation and causation from the running handler), a delivery per registration of its type,\n * and appends what has deliveries: the outbox side of the bus.\n */\nexport class EventPublisher<TTransaction> {\n readonly #parts: EventPublisherParts<TTransaction>;\n\n constructor(parts: EventPublisherParts<TTransaction>) {\n this.#parts = parts;\n }\n\n /** Publishes inside the tracer's span, with its trace headers, when the bus is observed. */\n publish(\n events: readonly DomainEvent[],\n call: PublishCall<TTransaction>,\n ): Promise<EventEnvelope[]> {\n const { observation } = this.#parts;\n if (observation === undefined) {\n return this.#publish(events, call);\n }\n return observation.publish(\n { eventTypes: events.map((event) => String(event.type)) },\n (headers) =>\n this.#publish(events, { ...call, options: withTraceHeaders(call.options, headers) }),\n );\n }\n\n async #publish(\n events: readonly DomainEvent[],\n { options, id }: PublishCall<TTransaction>,\n ): Promise<EventEnvelope[]> {\n if (events.length === 0) {\n return [];\n }\n const now = this.#parts.clock.now();\n const delayMs = options.delay === undefined ? 0 : Milliseconds.of(options.delay, 'delay');\n const availableAt = new Date(now.getTime() + delayMs);\n const context: PublishContext<TTransaction> = { options, id, scope: getCurrentScope(), now };\n const entries = await this.#createEntries(events, { context, availableAt });\n const deliverable = entries.filter((entry) => entry.deliveries.length > 0);\n if (deliverable.length > 0) {\n await this.#appendDeliverable(deliverable, { context, 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(\n events: readonly DomainEvent[],\n {\n context,\n availableAt,\n }: { readonly context: PublishContext<TTransaction>; readonly availableAt: Date },\n ): Promise<AppendEntry[]> {\n const { registry, createDelivery, reportUnrouted } = this.#parts;\n const entries: AppendEntry[] = [];\n const { options, scope } = context;\n let correlationId = options.correlationId ?? scope?.event?.correlationId ?? scope?.event?.id;\n for (const event of events) {\n const envelope = await this.#createEnvelope({ ...context, event, correlationId });\n correlationId = envelope.correlationId!;\n const registrations = registry.forEventType(envelope.type);\n if (registrations.length === 0) {\n reportUnrouted(envelope);\n }\n entries.push({\n event: envelope,\n deliveries: registrations.map((registration) => createDelivery(registration, availableAt)),\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(\n entries: readonly AppendEntry[],\n {\n context,\n delayMs,\n }: { readonly context: PublishContext<TTransaction>; readonly delayMs: number },\n ): Promise<void> {\n const result = await this.#appendInTransaction(entries, context);\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.#parts.notifier.notify('onPublished', {\n envelopes: published,\n deliveries: result.appendedDeliveryCount,\n });\n if (delayMs === 0) {\n this.#parts.scheduleWake();\n }\n }\n }\n\n async #appendInTransaction(\n entries: readonly AppendEntry[],\n { options, scope, now }: PublishContext<TTransaction>,\n ): Promise<AppendResult> {\n const { store, transactionMode, transactionResolver } = this.#parts;\n const transaction =\n options.transaction ??\n (scope?.transaction as TTransaction | undefined) ??\n transactionResolver?.();\n if (transaction !== undefined) {\n return store.append(transaction, entries, now);\n }\n if (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 store.transaction((ownTransaction) => store.append(ownTransaction, entries, now));\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.#parts.generateIdentifier();\n return {\n id: eventId,\n type: event.type,\n source: this.#parts.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","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 type { BusObservation, ReceiveOrigin } from '../bus-observation.js';\nimport type { Clock } from '../clock.js';\nimport type { AppendEntry, EventStore, NewDelivery } from '../event-store.js';\nimport type { EventEnvelope } from '../event.js';\nimport type { HandlerRegistration, HandlerRegistry } from '../handler-registry.js';\nimport type { Notifier } from '../notifier.js';\nimport { normalizeEnvelope } from '../received-envelope.js';\nimport type { ReceiveStatus } from '../relay-bus-options.js';\n\n/** What receiving needs from the bus. */\nexport type EventReceiverParts = {\n readonly store: EventStore;\n readonly registry: HandlerRegistry;\n readonly clock: Clock;\n readonly notifier: Notifier;\n readonly observation: BusObservation | undefined;\n readonly createDelivery: (registration: HandlerRegistration, availableAt: Date) => NewDelivery;\n /** Wakes the dispatcher shortly after new deliveries were stored. */\n readonly scheduleWake: () => void;\n};\n\n/**\n * Stores events received from brokers for the local handlers (never for routes), once per\n * event id: the inbox side of the bus.\n */\nexport class EventReceiver {\n readonly #parts: EventReceiverParts;\n\n constructor(parts: EventReceiverParts) {\n this.#parts = parts;\n }\n\n /** Stores `envelope` for local handlers; observed when the bus is, with where it came from. */\n receive(envelope: EventEnvelope, origin?: ReceiveOrigin): Promise<ReceiveStatus> {\n // Not async: the store's promise is returned as is, so an unobserved receive allocates nothing extra.\n const { observation } = this.#parts;\n return observation === undefined\n ? this.#receive(envelope)\n : observation.receive({ envelope, origin }, () => this.#receive(envelope));\n }\n\n async #receive(envelope: EventEnvelope): Promise<ReceiveStatus> {\n const { store, registry, clock, notifier, createDelivery, scheduleWake } = this.#parts;\n const normalized = normalizeEnvelope(envelope);\n const registrations = registry\n .forEventType(normalized.type)\n .filter((registration) => !registration.forwardsToTransport);\n if (registrations.length === 0) {\n notifier.notify('onReceived', { envelope: normalized, status: 'ignored' });\n return 'ignored';\n }\n const now = clock.now();\n const entry: AppendEntry = {\n event: normalized,\n deliveries: registrations.map((registration) => createDelivery(registration, now)),\n };\n const result = await store.transaction((transaction) =>\n store.append(transaction, [entry], now),\n );\n const status: ReceiveStatus = result.duplicateEventIds.length > 0 ? 'duplicate' : 'accepted';\n notifier.notify('onReceived', { envelope: normalized, status });\n if (result.appendedDeliveryCount > 0) {\n scheduleWake();\n }\n return status;\n }\n}\n","import { BusObservation } from '../bus-observation.js';\nimport { toCatalogRequirement, type CatalogRequirement } from '../catalog-coverage.js';\nimport { systemClock, type Clock } from '../clock.js';\nimport { DispatchObservation } from '../dispatch-observation.js';\nimport { Dispatcher } from '../dispatcher.js';\nimport type { EventEnvelope } from '../event.js';\nimport type { EventStore, EventStoreStatistics, NewDelivery } from '../event-store.js';\nimport {\n HandlerRegistry,\n type HandlerRegistration,\n type RegistrationDefaults,\n} from '../handler-registry.js';\nimport { createUuidV7, type IdentifierGenerator } from '../identifier.js';\nimport { Notifier } from '../notifier.js';\nimport type { RelayBusLogger } from '../observer.js';\nimport type { RelayBusOptions, UnroutedEventPolicy } from '../relay-bus-options.js';\nimport {\n createDispatcherSettings,\n createHandlerDefaults,\n createRetentionSettings,\n isDispatcherEnabled,\n oneOf,\n resolveBacklogInterval,\n resolveTransactionTimeout,\n} from '../relay-bus-settings.js';\nimport { BusConnections } from './bus-connections.js';\nimport { BusMaintenance } from './bus-maintenance.js';\nimport { EventPublisher } from './event-publisher.js';\nimport { EventReceiver } from './event-receiver.js';\n\n/** What the parts of a bus call back into the bus for. */\nexport type RelayBusHooks = {\n /** Logs or throws for an event no handler or route takes. */\n readonly reportUnrouted: (envelope: EventEnvelope) => void;\n /** Wakes the dispatcher shortly after new deliveries were stored. */\n readonly scheduleWake: () => void;\n readonly statistics: () => Promise<EventStoreStatistics>;\n};\n\n/** The settings and services every part of a bus shares, resolved from its options. */\ntype BusCore<TTransaction> = {\n readonly store: EventStore<TTransaction>;\n readonly source: string;\n readonly transactionMode: 'required' | 'optional';\n readonly unroutedEvents: UnroutedEventPolicy;\n readonly transactionResolver: (() => TTransaction | undefined) | undefined;\n readonly transactionTimeoutMs: number;\n readonly registry: HandlerRegistry;\n readonly defaults: RegistrationDefaults;\n readonly logger: RelayBusLogger;\n readonly notifier: Notifier;\n readonly clock: Clock;\n readonly observation: BusObservation | undefined;\n readonly generateIdentifier: IdentifierGenerator;\n readonly setupStore: boolean;\n};\n\n/** Everything a {@link RelayBus} is made of. */\nexport type RelayBusParts<TTransaction> = BusCore<TTransaction> & {\n readonly maintenance: BusMaintenance;\n readonly connections: BusConnections;\n readonly catalogRequirements: CatalogRequirement[];\n readonly dispatcherEnabled: boolean;\n readonly shutdownTimeoutMs: number;\n readonly dispatcher: Dispatcher;\n readonly publisher: EventPublisher<TTransaction>;\n readonly receiver: EventReceiver;\n};\n\n/**\n * Builds the parts of a bus from its options. Options are read and checked in a fixed order, so\n * the first invalid one is the one reported.\n */\nexport function assembleRelayBus<TTransaction>(\n options: RelayBusOptions<TTransaction>,\n hooks: RelayBusHooks,\n): RelayBusParts<TTransaction> {\n const core = resolveCore(options);\n const backlogIntervalMs = resolveBacklogInterval(options);\n const maintenance = new BusMaintenance({\n ...core,\n retention: createRetentionSettings(options.retention),\n backlogIntervalMs,\n statistics: hooks.statistics,\n });\n const connections = new BusConnections(core, options.subscriptions ?? []);\n connections.register({ transports: options.transports ?? [], routes: options.routes ?? [] });\n const catalogRequirements: CatalogRequirement[] = [];\n for (const catalog of options.catalogs ?? []) {\n catalogRequirements.push(toCatalogRequirement(catalog));\n }\n const dispatcherEnabled = isDispatcherEnabled(options);\n const settings = createDispatcherSettings(options.dispatcher, core.generateIdentifier);\n const dispatcher = new Dispatcher({\n ...core,\n random: options.random ?? Math.random,\n settings,\n observation: DispatchObservation.create({ ...core, tracer: options.tracer }),\n });\n return {\n ...core,\n maintenance,\n connections,\n catalogRequirements,\n dispatcherEnabled,\n shutdownTimeoutMs: settings.shutdownTimeoutMs,\n dispatcher,\n ...createInboxAndOutbox(core, hooks),\n };\n}\n\nfunction resolveCore<TTransaction>(options: RelayBusOptions<TTransaction>): BusCore<TTransaction> {\n const source = options.source ?? 'relaybus';\n const transactionMode = oneOf(options.transactionMode ?? 'required', {\n allowed: ['required', 'optional'],\n name: 'transactionMode',\n });\n const unroutedEvents = oneOf(options.unroutedEvents ?? 'warn', {\n allowed: ['warn', 'throw'],\n name: 'unroutedEvents',\n });\n const transactionTimeoutMs = resolveTransactionTimeout(options);\n const defaults = createHandlerDefaults(options);\n const logger = options.logger ?? console;\n const notifier = new Notifier(options.observers ?? [], logger);\n const clock = options.clock ?? systemClock;\n return {\n store: options.store,\n source,\n transactionMode,\n unroutedEvents,\n transactionResolver: options.transactionResolver,\n transactionTimeoutMs,\n registry: new HandlerRegistry(),\n defaults,\n logger,\n notifier,\n clock,\n observation: BusObservation.create({ notifier, tracer: options.tracer, clock }),\n generateIdentifier: options.generateIdentifier ?? (() => createUuidV7()),\n setupStore: options.setupStore ?? true,\n };\n}\n\n/** The publisher (outbox side) and the receiver (inbox side) of a bus. */\nfunction createInboxAndOutbox<TTransaction>(\n core: BusCore<TTransaction>,\n hooks: RelayBusHooks,\n): { publisher: EventPublisher<TTransaction>; receiver: EventReceiver } {\n const createDelivery = (registration: HandlerRegistration, availableAt: Date): NewDelivery => ({\n id: core.generateIdentifier(),\n handler: registration.id,\n availableAt,\n });\n return {\n publisher: new EventPublisher<TTransaction>({\n ...core,\n createDelivery,\n reportUnrouted: hooks.reportUnrouted,\n scheduleWake: hooks.scheduleWake,\n }),\n receiver: new EventReceiver({ ...core, createDelivery, scheduleWake: hooks.scheduleWake }),\n };\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 EventTypeRegistrations,\n} from './catalog-coverage.js';\nimport { BusLifecycle } from './bus/bus-lifecycle.js';\nimport { describeEvent, toDescriptor } from './bus/handler-descriptions.js';\nimport { assembleRelayBus, type RelayBusParts } from './bus/relay-bus-assembly.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 { ConfigurationError, DrainIncompleteError, LifecycleError, toErrorInfo } from './errors.js';\nimport type {\n CloseOptions,\n DeliveryQuery,\n DeliveryRecord,\n EventStore,\n EventStoreStatistics,\n PurgeResult,\n} from './event-store.js';\nimport type { DomainEvent, EventClass, EventEnvelope } from './event.js';\nimport { getCurrentScope, runInScope } from './execution-scope.js';\nimport type { EventHandler, HandlerDescriptor, SubscribeOptions } from './handler-registry.js';\nimport { schedule } from './internal/timers.js';\nimport type {\n PublishOneOptions,\n PublishOptions,\n ReceiveStatus,\n RelayBusOptions,\n} from './relay-bus-options.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 { Milliseconds } from './values/milliseconds.js';\n\n/** Batches `drain` runs at most before it gives up. */\nconst DEFAULT_DRAIN_BATCHES = 1_000;\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 #parts: RelayBusParts<TTransaction>;\n readonly #lifecycle: BusLifecycle;\n\n constructor(options: RelayBusOptions<TTransaction>) {\n this.#parts = assembleRelayBus(options, {\n reportUnrouted: (envelope) => this.#reportUnrouted(envelope),\n scheduleWake: () => this.#scheduleWake(),\n statistics: () => this.statistics(),\n });\n this.#lifecycle = new BusLifecycle({\n ...this.#parts,\n closeTransports: (deadline) => this.#closeTransports(deadline),\n });\n }\n\n get store(): EventStore<TTransaction> {\n return this.#parts.store;\n }\n\n get isRunning(): boolean {\n return this.#lifecycle.state === 'running';\n }\n\n /** True while the bus runs and every transport reports itself ready. */\n isReady(): boolean {\n return this.#lifecycle.state === 'running' && this.#parts.connections.allReady();\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.#parts.registry.register(\n {\n eventTypes: [type],\n schema,\n handle: handler as EventHandler,\n options,\n forwardsToTransport: false,\n },\n this.#parts.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.#parts.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.#parts.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.#parts.publisher.publish([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.#parts.publisher.publish(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.#parts.store, {\n clock: this.#parts.clock,\n timeoutMs: this.#parts.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) ??\n this.#parts.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 return this.#parts.receiver.receive(envelope);\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 this.#lifecycle.assertStartable();\n // Before any side effect, so a failed check leaves the bus idle and startable.\n assertCatalogsCovered(this.#parts.catalogRequirements, (type) => this.#registrationsOf(type));\n const starting = this.#lifecycle.beginStart(() => this.#startComponents());\n try {\n await starting;\n } finally {\n this.#lifecycle.endStart();\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.#parts.shutdownTimeoutMs\n : Milliseconds.forTimer(options.timeout, 'timeout');\n const { stopping, first } = this.#lifecycle.stop(timeoutMs);\n if (!first) {\n return stopping;\n }\n const result = await stopping;\n if (!result.graceful) {\n this.#parts.logger.warn(\n `[RelayBus](stop) Shutdown deadline passed, forced close | abandoned=${result.abandonedDeliveries} | timeoutMs=${timeoutMs}`,\n );\n }\n return result;\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.#parts.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.#parts.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.#parts.store.requeue(deliveryIds, this.#parts.clock.now());\n if (moved > 0) {\n this.#parts.dispatcher.wake();\n }\n return moved;\n }\n\n statistics(): Promise<EventStoreStatistics> {\n return this.#parts.store.statistics(this.#parts.clock.now());\n }\n\n /** Applies the retention policy once. Runs automatically while the bus is running. */\n purgeExpired(): Promise<PurgeResult> {\n return this.#parts.maintenance.purgeExpired();\n }\n\n // The awaits stay in this method, as many as before: with no store setup and no transport a\n // start completes synchronously, so the bus is running as soon as start() returns.\n async #startComponents(): Promise<void> {\n const { setupStore, store, connections } = this.#parts;\n try {\n if (setupStore) {\n await store.setup?.();\n }\n for (const transport of connections.transports) {\n await transport.connect?.();\n }\n for (const subscription of connections.subscriptions) {\n await connections.subscribe(subscription, (envelope, origin) =>\n this.#parts.receiver.receive(envelope, origin),\n );\n }\n } catch (error) {\n await this.#closeAfterFailedStart();\n this.#lifecycle.markStopped();\n throw error;\n }\n if (this.#lifecycle.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.#parts.dispatcherEnabled) {\n this.#parts.dispatcher.start();\n }\n this.#parts.maintenance.start();\n this.#lifecycle.markRunning();\n this.#parts.logger.log(\n `[RelayBus](startComponents) relaybus started | handlers=${this.#parts.registry.all().length} dispatcher=${this.#parts.dispatcherEnabled}`,\n );\n }\n\n /** Closes the transports a failed start may have connected, within the shutdown timeout. */\n #closeAfterFailedStart(): Promise<StopResult> {\n return withinDeadline(\n { clock: this.#parts.clock, timeoutMs: this.#parts.shutdownTimeoutMs },\n async (deadline) => {\n await this.#closeTransports(deadline);\n return 0;\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.#parts.unroutedEvents === 'throw') {\n throw new ConfigurationError(message);\n }\n this.#parts.logger.warn(`[RelayBus](reportUnrouted) ${message}`);\n }\n\n #registrationsOf(eventType: string): EventTypeRegistrations {\n const registrations = this.#parts.registry.forEventType(eventType);\n const routes = registrations.filter((registration) => registration.forwardsToTransport).length;\n return { handlers: registrations.length - routes, routes };\n }\n\n #scheduleWake(): void {\n // A store that reports new deliveries wakes the dispatcher itself, right after the commit.\n if (this.#lifecycle.state !== 'running' || this.#parts.dispatcher.watchesNewDeliveries) {\n return;\n }\n // The publishing transaction commits after publish returns; claim shortly after.\n schedule(this.#parts.clock, {\n run: () => this.#parts.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.#parts.connections.transports) {\n try {\n await deadline.race(transport.close(options));\n } catch (error) {\n this.#parts.logger.error(\n `[RelayBus](closeTransports) Failed to close transport | transport=${transport.name} error=${toErrorInfo(error).message}`,\n );\n }\n }\n }\n}\n"]}