@relaybus/core 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,8 +1,5 @@
1
- /** Source of the current time. Replace it in tests to control retries and leases. */
2
- interface Clock {
3
- now(): Date;
4
- }
5
- declare const systemClock: Clock;
1
+ import { E as EventEnvelope, D as DomainEvent, S as StandardSchemaV1, P as PayloadOf, a as EventHeaders, b as EventReference, C as Clock, c as EventClass } from './event-DCRTuYKI.js';
2
+ export { d as DefineEventKeyOptions, e as DefineEventOptions, f as EventKeyFunction, g as assertEventType, h as defineEvent, s as systemClock, v as validatePayload } from './event-DCRTuYKI.js';
6
3
 
7
4
  /**
8
5
  * A duration in milliseconds, or a string such as `'250ms'`, `'30s'`, `'5m'`,
@@ -14,102 +11,6 @@ declare function toMilliseconds(value: Duration, name: string): number;
14
11
  /** Largest delay Node.js timers support. Longer values fire after 1ms instead. */
15
12
  declare const MAX_TIMER_DELAY_MS = 2147483647;
16
13
 
17
- /**
18
- * The Standard Schema interface (https://standardschema.dev), copied as the
19
- * specification recommends so relaybus needs no runtime dependency. Zod,
20
- * Valibot, ArkType and other libraries implement it.
21
- */
22
- interface StandardSchemaV1<Input = unknown, Output = Input> {
23
- readonly '~standard': StandardSchemaV1.Props<Input, Output>;
24
- }
25
- declare namespace StandardSchemaV1 {
26
- interface Props<Input = unknown, Output = Input> {
27
- readonly version: 1;
28
- readonly vendor: string;
29
- readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
30
- readonly types?: Types<Input, Output> | undefined;
31
- }
32
- type Result<Output> = SuccessResult<Output> | FailureResult;
33
- interface SuccessResult<Output> {
34
- readonly value: Output;
35
- readonly issues?: undefined;
36
- }
37
- interface FailureResult {
38
- readonly issues: ReadonlyArray<Issue>;
39
- }
40
- interface Issue {
41
- readonly message: string;
42
- readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
43
- }
44
- interface PathSegment {
45
- readonly key: PropertyKey;
46
- }
47
- interface Types<Input = unknown, Output = Input> {
48
- readonly input: Input;
49
- readonly output: Output;
50
- }
51
- type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
52
- type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
53
- }
54
-
55
- /** String metadata carried with an event, such as `traceparent`. */
56
- type EventHeaders = Readonly<Record<string, string>>;
57
- /**
58
- * An event as stored and delivered. Field names follow CloudEvents where they
59
- * overlap (`id`, `type`, `source`, `time` as `occurredAt`, `subject` as `key`).
60
- */
61
- interface EventEnvelope<TPayload = unknown> {
62
- /** Globally unique id. Handlers and transports deduplicate on it. */
63
- readonly id: string;
64
- /** Event type, for example `order.created.v1`. */
65
- readonly type: string;
66
- /** Logical name of the publishing service. */
67
- readonly source: string;
68
- /** Ordering and partition key. Events sharing a key are handled in publish order. */
69
- readonly key: string | null;
70
- readonly payload: TPayload;
71
- readonly headers: EventHeaders;
72
- /** Id shared by every event of one business flow. */
73
- readonly correlationId: string | null;
74
- /** Id of the event whose handler published this one. */
75
- readonly causationId: string | null;
76
- readonly occurredAt: Date;
77
- }
78
- /** An instance of a class created with {@link defineEvent}. */
79
- interface DomainEvent<TPayload = unknown> {
80
- readonly type: string;
81
- readonly payload: TPayload;
82
- }
83
- /** A class created with {@link defineEvent}. */
84
- interface EventClass<TPayload = unknown> {
85
- new (payload: TPayload): DomainEvent<TPayload>;
86
- readonly type: string;
87
- readonly schema: StandardSchemaV1<unknown, TPayload> | undefined;
88
- }
89
- /** Payload type of an event class: `PayloadOf<typeof OrderPlaced>`. */
90
- type PayloadOf<TEvent> = TEvent extends EventClass<infer TPayload> ? TPayload : never;
91
- /** Anything that names an event type: an event class or the type string itself. */
92
- type EventReference = {
93
- readonly type: string;
94
- } | string;
95
- interface DefineEventOptions<TSchema extends StandardSchemaV1> {
96
- /** Validates the payload on publish and before every handler call. */
97
- readonly schema: TSchema;
98
- }
99
- declare function assertEventType(type: string): void;
100
- /**
101
- * Defines an event type. Extend the returned class to name it:
102
- *
103
- * ```ts
104
- * export class OrderPlaced extends defineEvent<{ orderId: string }>('order.placed.v1') {}
105
- * export class OrderShipped extends defineEvent('order.shipped.v1', { schema: orderShippedSchema }) {}
106
- * ```
107
- */
108
- declare function defineEvent<TSchema extends StandardSchemaV1>(type: string, options: DefineEventOptions<TSchema>): EventClass<StandardSchemaV1.InferOutput<TSchema>>;
109
- declare function defineEvent<TPayload>(type: string): EventClass<TPayload>;
110
- /** Runs a Standard Schema and returns its output, or throws {@link EventValidationError}. */
111
- declare function validatePayload<TPayload>(type: string, schema: StandardSchemaV1<unknown, TPayload> | undefined, payload: unknown): Promise<TPayload>;
112
-
113
14
  /**
114
15
  * How the delay between attempts is randomized.
115
16
  * - `full`: uniform in [0, delay]. Spreads retries the most (AWS recommendation).
@@ -430,7 +331,7 @@ interface CatalogDeclaration<TCatalog extends Catalog = Catalog, TName extends k
430
331
  * Declares that this service consumes events of a catalog, typically one
431
332
  * shared between services through a contracts package. `start()` fails unless
432
333
  * every declared event has a local handler (`subscribeCatalog`, `subscribe`,
433
- * `@EventConsumer`, `@Subscribe`); a route to a transport does not count.
334
+ * `@RelayBusCatalogConsumer`, `@RelayBusConsumer`); a route to a transport does not count.
434
335
  * Without `events`, every event of the catalog is declared. Unknown names do
435
336
  * not compile and are rejected at runtime with a {@link ConfigurationError}.
436
337
  *
@@ -462,10 +363,17 @@ declare function produce<TCatalog extends Catalog, const TName extends keyof TCa
462
363
  */
463
364
  declare class RelayBusError extends Error {
464
365
  name: string;
366
+ /**
367
+ * Stable, machine-readable identifier of the error class, such as `RELAYBUS_LEASE_LOST`.
368
+ * Unlike `name` and `message`, a code is never renamed once released; branch on it in
369
+ * alerts and dashboards. Subclasses declared outside relaybus inherit `RELAYBUS_ERROR`.
370
+ */
371
+ readonly code: string;
465
372
  }
466
373
  /** Invalid options passed to a relaybus component. */
467
374
  declare class ConfigurationError extends RelayBusError {
468
375
  name: string;
376
+ readonly code: string;
469
377
  }
470
378
  /**
471
379
  * Thrown by `publish` when no transaction can be found and the bus runs with
@@ -474,6 +382,16 @@ declare class ConfigurationError extends RelayBusError {
474
382
  */
475
383
  declare class TransactionRequiredError extends RelayBusError {
476
384
  name: string;
385
+ readonly code: string;
386
+ }
387
+ /**
388
+ * A `bus.transaction` (or `@RelayBusTransaction()` method) ran past its `transactionTimeout` and
389
+ * was rolled back. Its `cause` is the error the database raised when it ended the transaction,
390
+ * when there was one. Usually a slow call to another service made inside the transaction.
391
+ */
392
+ declare class TransactionTimeoutError extends RelayBusError {
393
+ name: string;
394
+ readonly code: string;
477
395
  }
478
396
  /**
479
397
  * Throw from a handler to dead-letter the delivery immediately, skipping the
@@ -481,11 +399,13 @@ declare class TransactionRequiredError extends RelayBusError {
481
399
  */
482
400
  declare class NonRetryableError extends RelayBusError {
483
401
  name: string;
402
+ readonly code: string;
484
403
  }
485
404
  /** A payload failed its event schema. Never retried: the payload will not change. */
486
405
  declare class EventValidationError extends NonRetryableError {
487
406
  readonly issues: readonly ValidationIssue[];
488
407
  name: string;
408
+ readonly code: string;
489
409
  constructor(message: string, issues: readonly ValidationIssue[]);
490
410
  }
491
411
  /**
@@ -494,10 +414,12 @@ declare class EventValidationError extends NonRetryableError {
494
414
  */
495
415
  declare class InvalidEnvelopeError extends NonRetryableError {
496
416
  name: string;
417
+ readonly code: string;
497
418
  }
498
419
  /** The worker no longer owns the delivery it was processing. */
499
420
  declare class LeaseLostError extends RelayBusError {
500
421
  name: string;
422
+ readonly code: string;
501
423
  /**
502
424
  * Whether the store said so (a fenced write returned false). A worker that only noticed
503
425
  * locally that its lease ran out may still own the delivery in the store and has to give it back.
@@ -510,6 +432,7 @@ declare class LeaseLostError extends RelayBusError {
510
432
  /** A handler did not settle within its configured timeout. Retried like any failure. */
511
433
  declare class HandlerTimeoutError extends RelayBusError {
512
434
  name: string;
435
+ readonly code: string;
513
436
  }
514
437
  /**
515
438
  * Reason of a handler's abort signal when the bus stops before the handler
@@ -517,6 +440,25 @@ declare class HandlerTimeoutError extends RelayBusError {
517
440
  */
518
441
  declare class DispatcherStoppedError extends RelayBusError {
519
442
  name: string;
443
+ readonly code: string;
444
+ }
445
+ /**
446
+ * A delivery came back after its lease expired on its last attempt, so it is
447
+ * dead-lettered without running its handler again.
448
+ */
449
+ declare class AttemptsExhaustedError extends RelayBusError {
450
+ name: string;
451
+ readonly code: string;
452
+ }
453
+ /** A lifecycle method was called in a state that does not allow it, such as starting a bus twice. */
454
+ declare class LifecycleError extends RelayBusError {
455
+ name: string;
456
+ readonly code: string;
457
+ }
458
+ /** `drain` still found due deliveries after its maximum number of batches. */
459
+ declare class DrainIncompleteError extends RelayBusError {
460
+ name: string;
461
+ readonly code: string;
520
462
  }
521
463
  interface ValidationIssue {
522
464
  readonly message: string;
@@ -527,6 +469,8 @@ interface ErrorInfo {
527
469
  readonly name: string;
528
470
  readonly message: string;
529
471
  readonly stack?: string | undefined;
472
+ /** The {@link RelayBusError.code} of a relaybus error; absent for any other error. */
473
+ readonly code?: string | undefined;
530
474
  }
531
475
  declare function toErrorInfo(error: unknown): ErrorInfo;
532
476
 
@@ -635,6 +579,26 @@ interface EventStoreStatistics {
635
579
  /** `availableAt` of the oldest delivery that is due but not yet processed. */
636
580
  readonly oldestDueAt: Date | null;
637
581
  }
582
+ /** How `stop` closes a transport or a store. */
583
+ interface CloseOptions {
584
+ /**
585
+ * Aborted when the shutdown deadline passes (`bus.stop({ timeout })`), possibly before `close` is
586
+ * called. From then on, close what you opened yourself at once (destroy connections, cancel
587
+ * running queries) instead of waiting for it to finish; the bus no longer waits for `close`.
588
+ * Leave alone what the application passed in.
589
+ */
590
+ readonly signal?: AbortSignal;
591
+ }
592
+ /** How a store runs one transaction of `bus.transaction`. */
593
+ interface EventStoreTransactionOptions {
594
+ /**
595
+ * Time budget of the whole transaction, in milliseconds. A store makes the database enforce it
596
+ * where it can (for example a statement or idle-in-transaction timeout), so a transaction that
597
+ * waits on something slow is ended by the server and its locks are released. The bus rolls back
598
+ * a transaction that still ran past the budget, so a store may also ignore it.
599
+ */
600
+ readonly timeoutMs: number;
601
+ }
638
602
  /**
639
603
  * Storage port. Implementations persist events and deliveries in the same
640
604
  * database as the application's business data so that both commit atomically.
@@ -644,8 +608,11 @@ interface EventStoreStatistics {
644
608
  interface EventStore<TTransaction = unknown> {
645
609
  /** Creates tables, collections and indexes when they do not exist. */
646
610
  setup?(): Promise<void>;
647
- /** Runs `work` inside a new database transaction and commits when it resolves. */
648
- transaction<T>(work: (transaction: TTransaction) => Promise<T>): Promise<T>;
611
+ /**
612
+ * Runs `work` inside a new database transaction and commits when it resolves. `options` come
613
+ * from `bus.transaction`; the store's own transactions and the dispatcher's pass none.
614
+ */
615
+ transaction<T>(work: (transaction: TTransaction) => Promise<T>, options?: EventStoreTransactionOptions): Promise<T>;
649
616
  /**
650
617
  * Writes events and their deliveries inside `transaction`. Idempotent on
651
618
  * event id and on (event id, handler). Assigns a per-key sequence to keyed
@@ -707,8 +674,8 @@ interface EventStore<TTransaction = unknown> {
707
674
  * that stops listening, or with `undefined` when this store cannot listen. Optional.
708
675
  */
709
676
  watchNewDeliveries?(listener: () => void): Promise<(() => Promise<void>) | undefined>;
710
- /** Releases connections the store opened itself. */
711
- close?(): Promise<void>;
677
+ /** Releases connections the store opened itself; forced once `options.signal` aborts. */
678
+ close?(options?: CloseOptions): Promise<void>;
712
679
  }
713
680
 
714
681
  /**
@@ -720,7 +687,167 @@ declare function createUuidV7(timestamp?: number): string;
720
687
  /** Produces unique identifiers for events, deliveries and lease tokens. */
721
688
  type IdentifierGenerator = () => string;
722
689
 
723
- type FailureStage = 'claim' | 'dispatch' | 'complete' | 'reschedule' | 'bury' | 'release' | 'relinquish' | 'extend-lease' | 'purge' | 'watch' | 'observer';
690
+ /** Event header that carries the W3C trace context (`version-traceid-parentid-flags`). */
691
+ declare const TRACEPARENT_HEADER = "traceparent";
692
+ /** Event header that carries the vendor part of the W3C trace context. */
693
+ declare const TRACESTATE_HEADER = "tracestate";
694
+ /** A W3C Trace Context as it travels in event headers. */
695
+ interface TraceContext {
696
+ readonly traceparent: string;
697
+ readonly tracestate?: string;
698
+ }
699
+ /**
700
+ * The W3C trace context an event carries in its headers, or undefined when it has none or a
701
+ * malformed one. A handler or a consumer span continues the publisher's trace from it.
702
+ *
703
+ * ```ts
704
+ * bus.subscribe(OrderPlaced, (event) => startSpan({ parent: traceContextOf(event.headers) }), ...)
705
+ * ```
706
+ */
707
+ declare function traceContextOf(headers: EventHeaders): TraceContext | undefined;
708
+ /** A `publish` or `publishAll` call. */
709
+ interface PublishTraceInput {
710
+ /** The type of every event of the call, in order. */
711
+ readonly eventTypes: readonly string[];
712
+ }
713
+ /** A route sending one event to its transport. */
714
+ interface SendTraceInput {
715
+ readonly envelope: EventEnvelope;
716
+ readonly transport: string;
717
+ /** The messaging system of the transport (`kafka`, `rabbitmq`), else its name. */
718
+ readonly system: string;
719
+ readonly destination: string;
720
+ }
721
+ /** A local handler running for one claimed delivery. */
722
+ interface ProcessTraceInput {
723
+ readonly delivery: ClaimedDelivery;
724
+ }
725
+ /**
726
+ * Tracing hooks, for example from `@relaybus/otel`. Each one wraps an operation: it starts a span,
727
+ * calls `run` inside it and ends the span when the returned promise settles, passing its result or
728
+ * error through unchanged. relaybus itself depends on no tracing library.
729
+ */
730
+ interface RelayBusTracer {
731
+ /**
732
+ * Wraps one publish call. `run` takes the trace headers (`traceparent`, `tracestate`) to write
733
+ * into every event of the call, so its consumers continue the trace; headers passed to
734
+ * `publish` explicitly win.
735
+ */
736
+ publish?<T>(input: PublishTraceInput, run: (headers: EventHeaders) => Promise<T>): Promise<T>;
737
+ /**
738
+ * Wraps one send of a route. `run` takes the trace headers to send the event with, in place of
739
+ * the ones it was stored with, so the consumer's trace continues from this send.
740
+ */
741
+ send?<T>(input: SendTraceInput, run: (headers: EventHeaders) => Promise<T>): Promise<T>;
742
+ /**
743
+ * Wraps one run of a local handler; the handler runs inside `run`, so what it publishes or calls
744
+ * joins the span. The event's own trace context is in `traceContextOf(delivery.event.headers)`.
745
+ */
746
+ process?<T>(input: ProcessTraceInput, run: () => Promise<T>): Promise<T>;
747
+ }
748
+
749
+ type FailureStage = 'claim' | 'dispatch' | 'complete' | 'reschedule' | 'bury' | 'release' | 'relinquish' | 'extend-lease' | 'purge' | 'watch' | 'backlog' | 'observer';
750
+ /** How a timed operation ended. On `error` the event carries the error. */
751
+ type OperationOutcome = 'success' | 'error';
752
+ /** Whether a delivery runs a local handler or forwards its event to a transport (a route). */
753
+ type DeliveryKind = 'handler' | 'route';
754
+ /** A `publish` or `publishAll` call returned or threw. */
755
+ interface PublishFinishedEvent {
756
+ /** The type of every event of the call, in order. */
757
+ readonly eventTypes: readonly string[];
758
+ readonly durationMs: number;
759
+ readonly outcome: OperationOutcome;
760
+ readonly error?: ErrorInfo;
761
+ }
762
+ /** One claim query of the dispatcher answered or failed. */
763
+ interface ClaimFinishedEvent {
764
+ /** Handler ids the claim asked for. */
765
+ readonly handlers: readonly string[];
766
+ /** Most deliveries the claim asked for (the batch size of this query). */
767
+ readonly requested: number;
768
+ readonly claimed: number;
769
+ /** Distinct leases among the claimed deliveries: a store that leases lanes counts each lane once. */
770
+ readonly lanes: number;
771
+ readonly durationMs: number;
772
+ readonly outcome: OperationOutcome;
773
+ readonly error?: ErrorInfo;
774
+ }
775
+ /** A handler (or a route's send) is about to run for a claimed delivery. */
776
+ interface HandlerStartedEvent {
777
+ readonly delivery: ClaimedDelivery;
778
+ readonly kind: DeliveryKind;
779
+ /** From the event's `occurredAt` to this start, across services for a received event. */
780
+ readonly endToEndLatencyMs: number;
781
+ }
782
+ /**
783
+ * A handler run ended: it resolved (`success`) or threw, timed out, lost its lease or was
784
+ * stopped (`error`). What happens to the delivery next is reported by the delivery hooks.
785
+ */
786
+ interface HandlerFinishedEvent {
787
+ readonly delivery: ClaimedDelivery;
788
+ readonly kind: DeliveryKind;
789
+ readonly durationMs: number;
790
+ readonly outcome: OperationOutcome;
791
+ readonly error?: ErrorInfo;
792
+ }
793
+ /** A route handed an event to its transport, which acknowledged it or failed. */
794
+ interface TransportSentEvent {
795
+ readonly envelope: EventEnvelope;
796
+ /** Name of the transport. */
797
+ readonly transport: string;
798
+ /** The messaging system of the transport (`kafka`, `rabbitmq`), else its name. */
799
+ readonly system: string;
800
+ readonly destination: string;
801
+ readonly durationMs: number;
802
+ readonly outcome: OperationOutcome;
803
+ readonly error?: ErrorInfo;
804
+ }
805
+ /**
806
+ * What `receive` did with an event from a broker: stored it (`accepted`), found it stored already
807
+ * (`duplicate`), had no handler for it (`ignored`), rejected it as malformed (`invalid`) or failed
808
+ * (`error`, the broker redelivers it).
809
+ */
810
+ type ReceiveOutcome = 'accepted' | 'duplicate' | 'ignored' | 'invalid' | 'error';
811
+ /** One event from a broker went through `receive`. */
812
+ interface ReceiveFinishedEvent {
813
+ /** Name of the transport that delivered it; undefined when `bus.receive` was called directly. */
814
+ readonly transport: string | undefined;
815
+ /** Messaging system of that transport (`kafka`, `rabbitmq`), else its name. */
816
+ readonly system: string | undefined;
817
+ /** Topic, routing key or queue it arrived on, when the transport tells. */
818
+ readonly destination: string | undefined;
819
+ /** The event's type and source as received; undefined when missing or not text. */
820
+ readonly eventType: string | undefined;
821
+ readonly source: string | undefined;
822
+ /** W3C trace context the event carries, to continue the trace of its publisher. */
823
+ readonly traceContext: TraceContext | undefined;
824
+ readonly outcome: ReceiveOutcome;
825
+ readonly durationMs: number;
826
+ readonly error?: ErrorInfo;
827
+ }
828
+ /**
829
+ * A transport could not decode an inbound message (codec failure, malformed record) and
830
+ * dead-lettered or skipped it. It never reached the bus, so `onReceiveFinished` does not see it.
831
+ */
832
+ interface InvalidMessageEvent {
833
+ /** Name of the transport. */
834
+ readonly transport: string;
835
+ /** The messaging system of the transport (`kafka`, `rabbitmq`), else its name. */
836
+ readonly system: string;
837
+ /** Topic, routing key or queue the message arrived on. */
838
+ readonly destination: string;
839
+ /** Why the message was rejected. */
840
+ readonly reason: string;
841
+ readonly error: ErrorInfo;
842
+ }
843
+ /** A periodic reading of the store's backlog (`RelayBusOptions.backlogInterval`). */
844
+ interface BacklogEvent {
845
+ /** Deliveries waiting to run, due or not. */
846
+ readonly pending: number;
847
+ /** How long the oldest due delivery has waited; 0 when none is due. */
848
+ readonly oldestPendingAgeMs: number;
849
+ readonly statistics: EventStoreStatistics;
850
+ }
724
851
  /**
725
852
  * Hooks for logging, metrics and tracing. Every method is optional, runs
726
853
  * synchronously on the hot path and must not throw; errors it throws are
@@ -769,6 +896,17 @@ interface RelayBusObserver {
769
896
  readonly stage: FailureStage;
770
897
  readonly error: ErrorInfo;
771
898
  }): void;
899
+ /** A publish call ended; called before the publishing transaction commits. */
900
+ onPublishFinished?(event: PublishFinishedEvent): void;
901
+ onClaimFinished?(event: ClaimFinishedEvent): void;
902
+ onHandlerStarted?(event: HandlerStartedEvent): void;
903
+ onHandlerFinished?(event: HandlerFinishedEvent): void;
904
+ onTransportSent?(event: TransportSentEvent): void;
905
+ onReceiveFinished?(event: ReceiveFinishedEvent): void;
906
+ /** A transport rejected an inbound message it could not decode. */
907
+ onInvalidMessage?(event: InvalidMessageEvent): void;
908
+ /** Called every `backlogInterval` while the bus runs, when that option is set. */
909
+ onBacklog?(event: BacklogEvent): void;
772
910
  }
773
911
  /** Minimal logger. Nest's `Logger` and `console` both satisfy it. */
774
912
  interface RelayBusLogger {
@@ -777,8 +915,35 @@ interface RelayBusLogger {
777
915
  error(message: string): void;
778
916
  }
779
917
 
780
- /** Receives an event from a broker. Resolve only after it is durably stored. */
781
- type TransportMessageHandler = (envelope: EventEnvelope) => Promise<void>;
918
+ /** Where an incoming message came from, for observers and traces. */
919
+ interface TransportMessage {
920
+ /** Topic, routing key or queue the message arrived on. */
921
+ readonly destination: string;
922
+ }
923
+ /** A message the transport could not turn into an event, so it never reaches the bus. */
924
+ interface InvalidTransportMessage {
925
+ /** Topic, routing key or queue the message arrived on. */
926
+ readonly destination: string;
927
+ /** What the codec or decoder threw. */
928
+ readonly error: unknown;
929
+ }
930
+ /**
931
+ * What the bus offers a transport at `subscribe`, beyond the message handler. Present only when
932
+ * an observer implements the matching hook, so a transport can skip the work otherwise.
933
+ */
934
+ interface TransportSubscriptionHooks {
935
+ /**
936
+ * Call once for each inbound message the transport rejected as undecodable (dead-lettered or
937
+ * skipped) before it reached `onMessage`. Messages the bus rejected itself are reported by
938
+ * `onReceiveFinished` and must not be reported here. Never throws.
939
+ */
940
+ readonly onInvalidMessage: (message: InvalidTransportMessage) => void;
941
+ }
942
+ /**
943
+ * Receives an event from a broker. Resolve only after it is durably stored. Transports pass
944
+ * `message` to tell where the event arrived; it is optional for transports written before it.
945
+ */
946
+ type TransportMessageHandler = (envelope: EventEnvelope, message?: TransportMessage) => Promise<void>;
782
947
  /**
783
948
  * Broker port used to exchange events between services.
784
949
  *
@@ -792,17 +957,25 @@ type TransportMessageHandler = (envelope: EventEnvelope) => Promise<void>;
792
957
  interface Transport {
793
958
  /** Unique name referenced by routes and subscriptions. */
794
959
  readonly name: string;
960
+ /**
961
+ * The messaging system, as OpenTelemetry names it (`kafka`, `rabbitmq`), reported to observers
962
+ * and traces. Default: the transport's name.
963
+ */
964
+ readonly system?: string;
795
965
  connect?(): Promise<void>;
796
966
  publish(envelope: EventEnvelope, destination: string): Promise<void>;
797
- subscribe?(destinations: readonly string[], onMessage: TransportMessageHandler): Promise<void>;
967
+ subscribe?(destinations: readonly string[], onMessage: TransportMessageHandler, hooks?: TransportSubscriptionHooks): Promise<void>;
798
968
  /**
799
969
  * Whether the transport can currently publish and, when subscribed, is
800
970
  * consuming. Health checks use it to report a dead consumer or a lost
801
971
  * connection. Transports without it count as ready.
802
972
  */
803
973
  isReady?(): boolean;
804
- /** Releases connections. A closed transport is not reopened. */
805
- close(): Promise<void>;
974
+ /**
975
+ * Releases connections. A closed transport is not reopened. Once `options.signal` aborts (the
976
+ * shutdown deadline passed), stop waiting and drop the connections it opened itself.
977
+ */
978
+ close(options?: CloseOptions): Promise<void>;
806
979
  }
807
980
 
808
981
  /**
@@ -830,7 +1003,11 @@ interface DispatcherOptions {
830
1003
  readonly pollInterval?: Duration;
831
1004
  /** Lease length; renewed every third of it while the handler runs. Default `'30s'`. */
832
1005
  readonly leaseDuration?: Duration;
833
- /** How long `stop` waits for running handlers before aborting them. Default `'30s'`. */
1006
+ /**
1007
+ * Longest `stop` takes in all, and its default `timeout`: waiting for running handlers, handing
1008
+ * back leases, closing transports and the store. Past it, `stop` aborts the handlers still
1009
+ * running, force-closes what relaybus opened itself and resolves. Default `'30s'`.
1010
+ */
834
1011
  readonly shutdownTimeout?: Duration;
835
1012
  /**
836
1013
  * Longest a finished delivery waits so that deliveries finishing around the
@@ -855,6 +1032,11 @@ interface RetentionOptions {
855
1032
  /** How often the cleanup runs. Default `'1h'`. */
856
1033
  readonly interval?: Duration;
857
1034
  }
1035
+ /**
1036
+ * Every route to one destination of one transport is one handler,
1037
+ * `relaybus.transport:<transport>:<destination>`: its events of one key are sent in commit
1038
+ * order whatever their types. Such routes must resolve to the same `retry` and `timeout`.
1039
+ */
858
1040
  interface RouteOptions {
859
1041
  /** Event class or type forwarded to the transport. */
860
1042
  readonly event: EventReference;
@@ -877,6 +1059,15 @@ interface RelayBusOptions<TTransaction = unknown> {
877
1059
  readonly source?: string;
878
1060
  /** Default `'required'`. */
879
1061
  readonly transactionMode?: TransactionMode;
1062
+ /**
1063
+ * Time budget of every `bus.transaction` (and `@RelayBusTransaction()` method). The store makes
1064
+ * the database enforce it where it can (PostgreSQL: `statement_timeout`, plus
1065
+ * `idle_in_transaction_session_timeout` and on PostgreSQL 17+ `transaction_timeout`; MongoDB:
1066
+ * `maxCommitTimeMS`), and a transaction that still runs past
1067
+ * it is rolled back with a {@link TransactionTimeoutError}. Keep calls to other services out of
1068
+ * transactions instead of raising it. Default `'5s'`.
1069
+ */
1070
+ readonly transactionTimeout?: Duration;
880
1071
  /**
881
1072
  * Finds the caller's active transaction when none is passed to `publish`
882
1073
  * and none was opened with `bus.transaction`, for example from
@@ -898,7 +1089,23 @@ interface RelayBusOptions<TTransaction = unknown> {
898
1089
  readonly subscriptions?: readonly InboundSubscriptionOptions[];
899
1090
  /** Create tables and indexes on start. Default true. */
900
1091
  readonly setupStore?: boolean;
1092
+ /**
1093
+ * Hooks for logging and metrics. The hooks an observer implements are read when the bus is
1094
+ * created; the newer ones (`onPublishFinished` and the other timed hooks) are skipped entirely,
1095
+ * clock reads included, when no observer implements them.
1096
+ */
901
1097
  readonly observers?: readonly RelayBusObserver[];
1098
+ /**
1099
+ * Spans around publish, send and handler runs, and the W3C trace context written into published
1100
+ * events (`traceparent`, `tracestate` headers). `@relaybus/otel` provides one. Default: none.
1101
+ */
1102
+ readonly tracer?: RelayBusTracer;
1103
+ /**
1104
+ * Reads `statistics()` this often while the bus runs and reports the backlog (pending deliveries,
1105
+ * age of the oldest due one) to the observers' `onBacklog`. Each reading is a store query, so it
1106
+ * is off unless set; `'15s'` to `'1m'` suits metrics scraped every minute. Default: off.
1107
+ */
1108
+ readonly backlogInterval?: Duration;
902
1109
  /** Default: `console`. */
903
1110
  readonly logger?: RelayBusLogger;
904
1111
  readonly clock?: Clock;
@@ -921,7 +1128,9 @@ interface PublishOptions<TTransaction = unknown> {
921
1128
  /**
922
1129
  * Ordering and partition key. Events with the same key are handled one at a
923
1130
  * time per handler, in commit order. A delayed or retrying event holds back
924
- * later events of its key.
1131
+ * later events of its key. Default: the `key` of the event's definition
1132
+ * (`defineEvent(type, { key })`), else none. An explicit key wins over the definition's, and in
1133
+ * `publishAll` applies to every event of the call.
925
1134
  */
926
1135
  readonly key?: string;
927
1136
  /** Deliver no earlier than this delay from now. */
@@ -942,6 +1151,27 @@ interface PublishOneOptions<TTransaction = unknown> extends PublishOptions<TTran
942
1151
  readonly id?: string;
943
1152
  }
944
1153
  type ReceiveStatus = 'accepted' | 'duplicate' | 'ignored';
1154
+
1155
+ interface StopOptions {
1156
+ /**
1157
+ * Longest the whole `stop` may take. Default: `dispatcher.shutdownTimeout`. Keep it below the time
1158
+ * the platform waits before killing the process (Kubernetes `terminationGracePeriodSeconds`).
1159
+ */
1160
+ readonly timeout?: Duration;
1161
+ }
1162
+ /** How a `stop` went. */
1163
+ interface StopResult {
1164
+ /** False when the deadline passed and `stop` aborted handlers or force-closed connections. */
1165
+ readonly graceful: boolean;
1166
+ /**
1167
+ * Deliveries whose handlers still ran at the deadline. Their leases expire after
1168
+ * `dispatcher.leaseDuration` and another process runs them again (at-least-once).
1169
+ */
1170
+ readonly abandonedDeliveries: number;
1171
+ /** Time `stop` took, on the bus clock. */
1172
+ readonly durationMs: number;
1173
+ }
1174
+
945
1175
  /**
946
1176
  * Reliable event bus: events are stored with business data in one transaction,
947
1177
  * then dispatched to every subscribed handler and route with independent
@@ -1005,9 +1235,16 @@ declare class RelayBus<TTransaction = unknown> {
1005
1235
  publishAll(events: readonly DomainEvent[], options?: PublishOptions<TTransaction>): Promise<EventEnvelope[]>;
1006
1236
  /**
1007
1237
  * Runs `work` in a new store transaction. `publish` calls inside it join the
1008
- * transaction without passing it explicitly.
1238
+ * transaction without passing it explicitly. The transaction is held to `transactionTimeout`
1239
+ * and rolled back with a {@link TransactionTimeoutError} when it runs past it.
1009
1240
  */
1010
1241
  transaction<T>(work: (transaction: TTransaction) => Promise<T>): Promise<T>;
1242
+ /**
1243
+ * The transaction `publish` would join right now: the one of the enclosing `bus.transaction`
1244
+ * (or `@RelayBusTransaction()` method, or transactional handler), else the one
1245
+ * `transactionResolver` finds. Repositories use it to write in the same transaction.
1246
+ */
1247
+ currentTransaction(): TTransaction | undefined;
1011
1248
  /**
1012
1249
  * Stores an event received from a broker and schedules it for local handlers.
1013
1250
  * Idempotent on the event id. Transports call it and acknowledge the message
@@ -1022,10 +1259,15 @@ declare class RelayBus<TTransaction = unknown> {
1022
1259
  */
1023
1260
  start(): Promise<void>;
1024
1261
  /**
1025
- * Stops dispatching, waits for running handlers, closes transports and the
1026
- * store. Waits for a start in progress first. Safe to call more than once.
1262
+ * Stops claiming, waits for running handlers, hands back leases, closes transports and the store,
1263
+ * all within `options.timeout` (default `dispatcher.shutdownTimeout`). When the deadline passes it
1264
+ * aborts the handlers still running, force-closes what relaybus opened itself (never pools or
1265
+ * clients the application passed in) and resolves anyway: it never rejects because of the
1266
+ * deadline. Abandoned deliveries stay leased until their lease expires and then run again
1267
+ * (at-least-once). Waits for a start in progress first. Safe to call more than once: later calls
1268
+ * get the result of the first.
1027
1269
  */
1028
- stop(): Promise<void>;
1270
+ stop(options?: StopOptions): Promise<StopResult>;
1029
1271
  /**
1030
1272
  * Claims and runs one batch of due deliveries, resolving when they settle.
1031
1273
  * Returns how many ran. Intended for tests and scripts.
@@ -1077,6 +1319,17 @@ declare class CatalogPublisher<TCatalog extends Catalog, TTransaction = unknown,
1077
1319
  publishAll(events: readonly CatalogEvents<TCatalog, TName>[], options?: PublishOptions<TTransaction>): Promise<EventEnvelope[]>;
1078
1320
  }
1079
1321
 
1322
+ /** Transaction handle of {@link InMemoryEventStore}. Writes apply on commit only. */
1323
+ declare class InMemoryTransaction {
1324
+ #private;
1325
+ get state(): 'open' | 'committed' | 'rolled-back';
1326
+ enqueue(operation: () => void): void;
1327
+ /** Runs `finisher` once the transaction commits or rolls back, like a lock release. */
1328
+ onFinish(finisher: () => void): void;
1329
+ commit(): void;
1330
+ rollback(): void;
1331
+ }
1332
+
1080
1333
  interface InMemoryEventStoreOptions {
1081
1334
  /** Allow use when `NODE_ENV` is `production`. Data is lost on restart. Default false. */
1082
1335
  readonly allowInProduction?: boolean;
@@ -1088,16 +1341,6 @@ interface InMemoryEventStoreOptions {
1088
1341
  */
1089
1342
  readonly retainCompleted?: boolean;
1090
1343
  }
1091
- /** Transaction handle of {@link InMemoryEventStore}. Writes apply on commit only. */
1092
- declare class InMemoryTransaction {
1093
- #private;
1094
- get state(): 'open' | 'committed' | 'rolled-back';
1095
- enqueue(operation: () => void): void;
1096
- /** Runs `finisher` once the transaction commits or rolls back, like a lock release. */
1097
- onFinish(finisher: () => void): void;
1098
- commit(): void;
1099
- rollback(): void;
1100
- }
1101
1344
  /**
1102
1345
  * Event store kept in process memory, with the same semantics as the database
1103
1346
  * stores: transactional appends, leases, fencing and per-key ordering. Payloads
@@ -1122,4 +1365,4 @@ declare class InMemoryEventStore implements EventStore<InMemoryTransaction> {
1122
1365
  statistics(now: Date): Promise<EventStoreStatistics>;
1123
1366
  }
1124
1367
 
1125
- export { type AppendEntry, type AppendResult, type Catalog, type CatalogDeclaration, type CatalogDescription, type CatalogEntry, type CatalogEventClass, type CatalogEventName, type CatalogEventSelection, type CatalogEvents, CatalogPublisher, type CatalogRole, type ClaimRequest, type ClaimedDelivery, type Clock, ConfigurationError, DEFAULT_RETRY_POLICY, DEFAULT_ROUTE_RETRY_POLICY, DELIVERY_STATUSES, type DefineCatalogOptions, type DefineEventOptions, type DeliveryQuery, type DeliveryRecord, type DeliveryStatus, type DispatcherOptions, DispatcherStoppedError, type DomainEvent, type Duration, type ErrorInfo, type EventClass, type EventEnvelope, type EventHandler, type EventHeaders, type EventOf, type EventReference, type EventStore, type EventStoreStatistics, EventValidationError, type FailureStage, type HandlerContext, type HandlerDescriptor, type HandlerShapeOf, HandlerTimeoutError, type HandlersOf, type IdentifierGenerator, InMemoryEventStore, type InMemoryEventStoreOptions, InMemoryTransaction, type InboundSubscriptionOptions, InvalidEnvelopeError, type JitterStrategy, LeaseLostError, type LeaseReference, MAX_TIMER_DELAY_MS, type MatchingHandlers, type NewDelivery, type NoExtraHandlers, NonRetryableError, type PartialHandlersOf, type PayloadOf, type PublishOneOptions, type PublishOptions, type PublishTarget, type PurgeRequest, type PurgeResult, type ReceiveStatus, RelayBus, RelayBusError, type RelayBusLogger, type RelayBusObserver, type RelayBusOptions, type RetentionOptions, type RetryPolicy, type RetryPolicyOptions, type RouteOptions, StandardSchemaV1, type SubscribeCatalogOptions, type SubscribeOptions, type TransactionMode, TransactionRequiredError, type Transport, type TransportMessageHandler, type UnroutedEventPolicy, type ValidationIssue, assertEventType, computeRetryDelay, consume, createRetryPolicy, createUuidV7, defineCatalog, defineEvent, defineHandlers, describeCatalog, isRetryableError, produce, systemClock, toErrorInfo, toMilliseconds, validatePayload };
1368
+ export { type AppendEntry, type AppendResult, AttemptsExhaustedError, type BacklogEvent, type Catalog, type CatalogDeclaration, type CatalogDescription, type CatalogEntry, type CatalogEventClass, type CatalogEventName, type CatalogEventSelection, type CatalogEvents, CatalogPublisher, type CatalogRole, type ClaimFinishedEvent, type ClaimRequest, type ClaimedDelivery, Clock, type CloseOptions, ConfigurationError, DEFAULT_RETRY_POLICY, DEFAULT_ROUTE_RETRY_POLICY, DELIVERY_STATUSES, type DefineCatalogOptions, type DeliveryKind, type DeliveryQuery, type DeliveryRecord, type DeliveryStatus, type DispatcherOptions, DispatcherStoppedError, DomainEvent, DrainIncompleteError, type Duration, type ErrorInfo, EventClass, EventEnvelope, type EventHandler, EventHeaders, type EventOf, EventReference, type EventStore, type EventStoreStatistics, type EventStoreTransactionOptions, EventValidationError, type FailureStage, type HandlerContext, type HandlerDescriptor, type HandlerFinishedEvent, type HandlerShapeOf, type HandlerStartedEvent, HandlerTimeoutError, type HandlersOf, type IdentifierGenerator, InMemoryEventStore, type InMemoryEventStoreOptions, InMemoryTransaction, type InboundSubscriptionOptions, InvalidEnvelopeError, type InvalidMessageEvent, type InvalidTransportMessage, type JitterStrategy, LeaseLostError, type LeaseReference, LifecycleError, MAX_TIMER_DELAY_MS, type MatchingHandlers, type NewDelivery, type NoExtraHandlers, NonRetryableError, type OperationOutcome, type PartialHandlersOf, PayloadOf, type ProcessTraceInput, type PublishFinishedEvent, type PublishOneOptions, type PublishOptions, type PublishTarget, type PublishTraceInput, type PurgeRequest, type PurgeResult, type ReceiveFinishedEvent, type ReceiveOutcome, type ReceiveStatus, RelayBus, RelayBusError, type RelayBusLogger, type RelayBusObserver, type RelayBusOptions, type RelayBusTracer, type RetentionOptions, type RetryPolicy, type RetryPolicyOptions, type RouteOptions, type SendTraceInput, StandardSchemaV1, type StopOptions, type StopResult, type SubscribeCatalogOptions, type SubscribeOptions, TRACEPARENT_HEADER, TRACESTATE_HEADER, type TraceContext, type TransactionMode, TransactionRequiredError, TransactionTimeoutError, type Transport, type TransportMessage, type TransportMessageHandler, type TransportSentEvent, type TransportSubscriptionHooks, type UnroutedEventPolicy, type ValidationIssue, computeRetryDelay, consume, createRetryPolicy, createUuidV7, defineCatalog, defineHandlers, describeCatalog, isRetryableError, produce, toErrorInfo, toMilliseconds, traceContextOf };