@sincpro/client-framework 1.3.0 → 1.4.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.
@@ -10,11 +10,13 @@
10
10
  * infrastructure/ `configureProcess`, `configureLogger`
11
11
  */
12
12
  export { type CommandBus, FeatureBus } from "./domain/bus.js";
13
+ export type { EventConsumer, EventKey, } from "./domain/consumers.js";
13
14
  export { type AnyCommand, Command, COMMAND_IDENTITY, type CommandClass, type CommandDescriptor, type CommandNamed, commandOf, DataTransferObject, DomainEvent, type DtoKey, type EventClass, type EventDescriptor, type Executable, type ExecutableOf, type RemoteCommand, type RemoteEvent, Response, } from "./domain/dto.js";
14
15
  export type { ErrorClass, ErrorHandler } from "./domain/errors.js";
15
16
  export type { CallNext, Cause, ExecuteOptions, ExecutionCompleted, ExecutionFailed, ExecutionStarted, Extension, InterceptedRun, Interceptor, Listener, PipelineLayer, } from "./domain/pipeline.js";
16
- export { ApplicationService, type ApplicationServiceWith, Feature, type FeatureWith, type ServiceInput, servicesWith, } from "./domain/services.js";
17
+ export { ApplicationService, type ApplicationServiceWith, type BoundedContextHandlerWith, EventHandler, type EventHandlerWith, Feature, type FeatureWith, type HandledEvent, handlersWith, type ServiceInput, servicesWith, } from "./domain/services.js";
17
18
  export { BoundedContext, type Registrar, type RegistrationOptions, } from "./entrypoint/bounded-context.js";
18
19
  export { screensTransport } from "./entrypoint/screens.js";
19
20
  export { processListeners } from "./infrastructure/listeners.js";
20
21
  export { configureLogger, configureProcess, type LoggerConfiguration, type ProcessOptions, } from "./infrastructure/process.js";
22
+ export type { HandlerRegistrar } from "./services/event-handlers.js";
@@ -11,7 +11,7 @@
11
11
  */
12
12
  export { FeatureBus } from "./domain/bus.js";
13
13
  export { Command, COMMAND_IDENTITY, commandOf, DataTransferObject, DomainEvent, Response, } from "./domain/dto.js";
14
- export { ApplicationService, Feature, servicesWith, } from "./domain/services.js";
14
+ export { ApplicationService, EventHandler, Feature, handlersWith, servicesWith, } from "./domain/services.js";
15
15
  export { BoundedContext, } from "./entrypoint/bounded-context.js";
16
16
  export { screensTransport } from "./entrypoint/screens.js";
17
17
  export { processListeners } from "./infrastructure/listeners.js";
@@ -0,0 +1,57 @@
1
+ import type { Execution } from "../../context/domain/execution.js";
2
+ import type { ContextValues } from "../../context/domain/store.js";
3
+ import type { EventKey } from "../domain/consumers.js";
4
+ import { type Executable } from "../domain/dto.js";
5
+ import type { Cause, ExecutionFailed, Interceptor } from "../domain/pipeline.js";
6
+ import { type HandledEvent } from "../domain/services.js";
7
+ import { type DtoIdentity } from "./dto-keys.js";
8
+ import { type Announcer } from "./execution.js";
9
+ /** An event handler's class, as it is registered. */
10
+ export type HandlerClass = new () => object;
11
+ /** A registered event handler: its name, its class, the events it handles. */
12
+ export type HandlerRegistration = {
13
+ readonly name: string;
14
+ readonly Handler: HandlerClass;
15
+ readonly events: readonly EventKey[];
16
+ };
17
+ /**
18
+ * What `handler(...)` answers: the function that registers an event handler — called with the
19
+ * class, or applied as a decorator (standard or legacy).
20
+ */
21
+ export type HandlerRegistrar<E extends HandledEvent> = <S extends new () => {
22
+ handle: (event: NoInfer<E>) => unknown;
23
+ }>(Handler: S, decorator?: ClassDecoratorContext<S>) => S;
24
+ /**
25
+ * The events a handler is registered for — one or N —, each an event's class or a generated
26
+ * event's entry, with a valid wire name, none twice.
27
+ */
28
+ export declare function eventKeysOf(events: EventKey | readonly EventKey[]): readonly EventKey[];
29
+ /**
30
+ * Registers `Handler` with `register`, at once or — applied as a standard decorator — once its
31
+ * class is defined; its name is the class's as the code wrote it (a decorator's `context.name`,
32
+ * untouched by a minifier), else its `name`.
33
+ */
34
+ export declare function handlerRegistrar<E extends HandledEvent>(register: (Handler: HandlerClass, name: string) => void): HandlerRegistrar<E>;
35
+ /** Whether a handler registered for `key` handles the event `known` identifies. */
36
+ export declare function handles(key: EventKey, known: DtoIdentity): boolean;
37
+ /** What a run of an event handler needs besides the handler and the event. */
38
+ export type HandlerRun = {
39
+ readonly owner: string;
40
+ readonly name: string;
41
+ readonly dependencies: ReadonlyMap<string, unknown>;
42
+ readonly context: () => ContextValues;
43
+ readonly cause?: Cause;
44
+ readonly boundedContextOf?: (execution: Execution) => object;
45
+ readonly expected: (error: unknown) => boolean;
46
+ readonly interceptors: readonly Interceptor[];
47
+ readonly announce: Announcer;
48
+ /** Told once when a failure escapes the handler. */
49
+ readonly failed: (heard: ExecutionFailed) => void;
50
+ };
51
+ /**
52
+ * Runs an event handler in the pipeline of every use case, in its own layer (`event_handler`):
53
+ * its span `<owner>/<Handler>`, continuing the message's flow and trace; a failure is observed
54
+ * there, told once (`failed`) and thrown — a handler has no error handlers: what it executes
55
+ * answers in its own bounded context.
56
+ */
57
+ export declare function runHandler(instance: object, event: Executable, run: HandlerRun): Promise<unknown>;
@@ -0,0 +1,114 @@
1
+ import { EVENT_NAME } from "../domain/dto.js";
2
+ import { EventHandler, } from "../domain/services.js";
3
+ import { isEventClass, isEventDescriptor, keyIdentity, } from "./dto-keys.js";
4
+ import { executeService, failedAt, } from "./execution.js";
5
+ import { observabilityNow } from "../../observability/infrastructure/registry.js";
6
+ /**
7
+ * The events a handler is registered for — one or N —, each an event's class or a generated
8
+ * event's entry, with a valid wire name, none twice.
9
+ */
10
+ export function eventKeysOf(events) {
11
+ const keys = Array.isArray(events) ? events : [events];
12
+ if (keys.length === 0)
13
+ throw new TypeError("An event handler handles one event at least");
14
+ const wires = new Set();
15
+ for (const key of keys) {
16
+ if (!isEventClass(key) && !isEventDescriptor(key)) {
17
+ throw new TypeError("An event handler is registered for events: a DomainEvent's class, or a generated event's entry");
18
+ }
19
+ const wire = keyIdentity(key).wire ?? "";
20
+ if (!EVENT_NAME.test(wire)) {
21
+ throw new Error(`${wire || "An event"} is not an event's name: <context>.<aggregate>.vN.<fact>`);
22
+ }
23
+ if (wires.has(wire))
24
+ throw new Error(`The handler lists ${wire} twice`);
25
+ wires.add(wire);
26
+ }
27
+ return keys;
28
+ }
29
+ /**
30
+ * Registers `Handler` with `register`, at once or — applied as a standard decorator — once its
31
+ * class is defined; its name is the class's as the code wrote it (a decorator's `context.name`,
32
+ * untouched by a minifier), else its `name`.
33
+ */
34
+ export function handlerRegistrar(register) {
35
+ return (Handler, decorator) => {
36
+ const take = () => {
37
+ if (!(Handler.prototype instanceof EventHandler)) {
38
+ throw new TypeError("An event handler extends EventHandler");
39
+ }
40
+ const name = decorator?.name ?? Handler.name;
41
+ if (typeof name !== "string" || name.trim() === "") {
42
+ throw new Error("An event handler is a named class: its name is said in spans and logs");
43
+ }
44
+ register(Handler, name);
45
+ };
46
+ if (decorator)
47
+ decorator.addInitializer(take);
48
+ else
49
+ take();
50
+ return Handler;
51
+ };
52
+ }
53
+ /** Whether a handler registered for `key` handles the event `known` identifies. */
54
+ export function handles(key, known) {
55
+ if (known.type !== undefined)
56
+ return key === known.type;
57
+ return isEventDescriptor(key) && key.name === known.wire;
58
+ }
59
+ /**
60
+ * Runs an event handler in the pipeline of every use case, in its own layer (`event_handler`):
61
+ * its span `<owner>/<Handler>`, continuing the message's flow and trace; a failure is observed
62
+ * there, told once (`failed`) and thrown — a handler has no error handlers: what it executes
63
+ * answers in its own bounded context.
64
+ */
65
+ export async function runHandler(instance, event, run) {
66
+ const wire = keyIdentityOf(event);
67
+ try {
68
+ return await executeService(instance, event, {
69
+ boundedContext: run.owner,
70
+ name: run.name,
71
+ layer: "event_handler",
72
+ attributes: wire ? { "sincpro.event": wire } : {},
73
+ dependencies: run.dependencies,
74
+ context: run.context,
75
+ ...(run.cause ? { cause: run.cause } : {}),
76
+ featureBus: () => ({}),
77
+ ...(run.boundedContextOf ? { boundedContextOf: run.boundedContextOf } : {}),
78
+ expected: run.expected,
79
+ handlers: [],
80
+ interceptors: run.interceptors,
81
+ announce: run.announce,
82
+ });
83
+ }
84
+ catch (error) {
85
+ const at = failedAt(error);
86
+ let outcome = "failed";
87
+ try {
88
+ outcome =
89
+ at?.outcome ??
90
+ (run.expected(error) ? "refused" : observabilityNow().outcomeOf(error));
91
+ }
92
+ catch {
93
+ // An outcome that cannot be told is a failure.
94
+ }
95
+ try {
96
+ run.failed({
97
+ executable: at?.executable ?? event,
98
+ execution: at?.execution,
99
+ layer: at?.layer,
100
+ error,
101
+ outcome,
102
+ });
103
+ }
104
+ catch {
105
+ // Telling a listener never changes the failure.
106
+ }
107
+ throw error;
108
+ }
109
+ }
110
+ /** An event's wire name, for its span. */
111
+ function keyIdentityOf(event) {
112
+ const name = event.name;
113
+ return typeof name === "string" ? name : undefined;
114
+ }
@@ -40,6 +40,11 @@ export interface ExecutionOptions {
40
40
  /** What cancels a root run; a child inherits its parent's. */
41
41
  readonly signal?: AbortSignal;
42
42
  readonly featureBus: (execution: Execution) => object;
43
+ /**
44
+ * The bounded context an event handler of it reaches as `this.boundedContext`, bound to the
45
+ * handler's run; none for a Feature, nor for a `Subscriber`'s handler.
46
+ */
47
+ readonly boundedContextOf?: (execution: Execution) => object;
43
48
  /** What runs around the service, outermost first. */
44
49
  readonly interceptors: readonly Interceptor[];
45
50
  /** Who hears it start and answer. */
@@ -50,7 +55,7 @@ export interface ExecutionOptions {
50
55
  readonly handlers: readonly ErrorHandler[];
51
56
  }
52
57
  /**
53
- * One pipeline for every registered Feature and ApplicationService.
58
+ * One pipeline for every registered Feature, ApplicationService and event handler.
54
59
  *
55
60
  * 1. A span `<bounded context>/<Service>`, a child of the run above it when there is one (its
56
61
  * parent, or the caller from outside), and the execution every dependency, `this.logger` and
@@ -53,6 +53,7 @@ function serviceView(target, options, execution) {
53
53
  const dependencies = new Map();
54
54
  const logger = executionLogger(options.layer, execution);
55
55
  let features;
56
+ let own;
56
57
  return new Proxy(target, {
57
58
  get(held, property, receiver) {
58
59
  if (property === "context")
@@ -68,6 +69,9 @@ function serviceView(target, options, execution) {
68
69
  if (property === "featureBus" && options.layer === "application_service") {
69
70
  return (features ??= options.featureBus(execution));
70
71
  }
72
+ if (property === "boundedContext" && options.boundedContextOf) {
73
+ return (own ??= options.boundedContextOf(execution));
74
+ }
71
75
  if (typeof property === "string" && options.dependencies.has(property)) {
72
76
  if (!dependencies.has(property)) {
73
77
  dependencies.set(property, bindDependency(options.dependencies.get(property), execution));
@@ -88,6 +92,7 @@ function serviceView(target, options, execution) {
88
92
  property === "signal" ||
89
93
  property === "execution" ||
90
94
  property === "featureBus" ||
95
+ property === "boundedContext" ||
91
96
  (typeof property === "string" && options.dependencies.has(property))) {
92
97
  throw new Error(`Execution dependencies and context are read-only: ${String(property)}`);
93
98
  }
@@ -95,8 +100,12 @@ function serviceView(target, options, execution) {
95
100
  },
96
101
  });
97
102
  }
103
+ /** What a run calls on its service: `handle` for an event handler, `execute` for a use case. */
104
+ function entryOf(layer) {
105
+ return layer === "event_handler" ? "handle" : "execute";
106
+ }
98
107
  /**
99
- * One pipeline for every registered Feature and ApplicationService.
108
+ * One pipeline for every registered Feature, ApplicationService and event handler.
100
109
  *
101
110
  * 1. A span `<bounded context>/<Service>`, a child of the run above it when there is one (its
102
111
  * parent, or the caller from outside), and the execution every dependency, `this.logger` and
@@ -193,7 +202,7 @@ export async function executeService(target, command, options) {
193
202
  return outcome;
194
203
  };
195
204
  const view = serviceView(target, options, execution);
196
- const execute = Reflect.get(target, "execute");
205
+ const execute = Reflect.get(target, entryOf(options.layer));
197
206
  const service = (current) => Promise.resolve(Reflect.apply(execute, view, [current]));
198
207
  let answer;
199
208
  try {
@@ -1,20 +1,28 @@
1
- import type { AnyCommand, CommandClass, CommandDescriptor, DomainEvent, DtoKey, EventClass, EventDescriptor, Executable, RemoteEvent } from "../../core/domain/dto.js";
1
+ import type { EventConsumer, EventKey } from "../../core/domain/consumers.js";
2
+ import type { AnyCommand, CommandClass, CommandDescriptor, DomainEvent, DtoKey, EventClass, EventDescriptor, Executable, ExecutableOf, RemoteEvent } from "../../core/domain/dto.js";
2
3
  import type { Cause, ExecuteOptions } from "../../core/domain/pipeline.js";
4
+ import { type HandledEvent } from "../../core/domain/services.js";
5
+ import { type HandlerRegistrar } from "../../core/services/event-handlers.js";
3
6
  import type { Envelope } from "../domain/envelope.js";
4
7
  import type { BinaryMessage, Message } from "../domain/messages.js";
5
8
  import type { CommandType, EventType, Handled, Subscribes } from "../domain/queue.js";
6
- /** What the subscriber needs of a bounded context: what it registered, and running it. */
9
+ /**
10
+ * What a subscriber needs of a bounded context — a bus it delivers to: what it registered, who
11
+ * consumes an event there, and running it. A `BoundedContext` is one.
12
+ */
7
13
  export type HearingContext = {
8
14
  readonly name: string;
9
15
  handlerOf(dto: DtoKey): unknown;
10
16
  eventTypeOf(name: string): EventType | undefined;
11
17
  commandTypeOf(identity: string): CommandType | undefined;
12
18
  execute(executable: Executable, options?: ExecuteOptions | Cause): Promise<unknown>;
19
+ /** Who consumes the event there: its use case and its event handlers. */
20
+ consumersOf?(event: DomainEvent | RemoteEvent): readonly EventConsumer[];
13
21
  };
14
- /** Which bounded contexts it hands messages to, and what it takes from the queue. */
22
+ /** Which bounded contexts it delivers to, and what it takes from the queue. */
15
23
  export type SubscriberOptions = {
16
24
  readonly boundedContexts: readonly HearingContext[];
17
- /** The events it hears; every event the bounded contexts registered when none is named. */
25
+ /** The events it hears; every event its consumers registered when none is named. */
18
26
  readonly events?: readonly (EventClass<DomainEvent> | EventDescriptor)[];
19
27
  /**
20
28
  * The Commands it consumes from the queue — none unless named, as the backend's
@@ -22,6 +30,8 @@ export type SubscriberOptions = {
22
30
  */
23
31
  readonly commands?: readonly (CommandClass<AnyCommand> | CommandDescriptor)[];
24
32
  };
33
+ /** What a named subscriber takes besides its name. */
34
+ export type NamedSubscriberOptions = Omit<SubscriberOptions, "boundedContexts">;
25
35
  /** A Command the queue carried that this subscriber was not told to consume. */
26
36
  export declare class CommandNotConsumed extends Error {
27
37
  readonly type: string;
@@ -30,52 +40,96 @@ export declare class CommandNotConsumed extends Error {
30
40
  constructor(type: string);
31
41
  }
32
42
  /**
33
- * The queue's entrypoint — the backend's `Subscriber(*buses)` and `QueueGateway`: what arrives is
34
- * recognized, rebuilt and executed on the bus that registered it.
43
+ * The queue's entrypoint — the backend's `Subscriber(*buses)` and `QueueGateway`, composed: it
44
+ * pulls what the queue delivers, rebuilds it and hands it to every consumer subscribed to it —
45
+ * its own event handlers, and the buses added to it, each with its use case and its handlers.
46
+ *
47
+ * // entrypoints/queue/framework.ts — once, like a bounded context's framework.ts
48
+ * export const { EventHandler } = handlersWith<AppSubscriberDependencies>();
49
+ * export const appSubscriber = new Subscriber<AppSubscriberDependencies>("app");
50
+ * appSubscriber.addDependency("invoicingBoundedContext", invoicingBoundedContext); // to call it
51
+ * appSubscriber.addDependency("notifier", deviceNotifier);
52
+ * appSubscriber.addBus(salesBoundedContext); // to deliver to its use cases and handlers
53
+ *
54
+ * // entrypoints/queue/sale_paid.handler.ts — events → handler
55
+ * @appSubscriber.handler([SalePaid])
56
+ * export class NotifySalePaid extends EventHandler<SalePaid> { async handle(event) { … } }
35
57
  *
36
- * new Subscriber(billingBoundedContext, accountingBoundedContext) // every event they registered
37
- * new Subscriber({
38
- * boundedContexts: [billingBoundedContext],
39
- * events: [OrderPaid, events.IssueClosed], // only these
40
- * commands: [CommandIssueInvoice], // consumed: declared
41
- * })
42
- * await subscriber.receive(message); // what each one answered
58
+ * storedQueue({ store, subscriber: appSubscriber });
43
59
  *
44
- * Context: one per queue, never one per event — registering a use case for an event is the
45
- * subscription. An event is a fact N buses hear, by its wire name; a Command is a request to one
46
- * bus, by its identity, and only when it was declared here. Several hearing one event is several
47
- * executions, one each, in the order named; one that fails does not stop the others, and each is
48
- * said under its bounded context's name — which a stored queue keeps, so a redelivery never runs
49
- * one again. Two never share a name.
60
+ * Context: one per queue, never one per handler. Two levels, never mixed: a dependency — a bus
61
+ * to call included — is what its handlers find on `this` (`addDependency`, by name); a bus added
62
+ * (`addBus`, by its own namespace) is one it delivers to. Adding the same bus again changes
63
+ * nothing; another bus of the same name is delivered to as well (`sales#2`). Every consumer is
64
+ * acknowledged apart — `app/NotifySalePaid`, `sales`, `sales/OnSalePaid` —, which a stored queue
65
+ * keeps, so a redelivery runs only who does not have it yet. A Command is a request to one bus,
66
+ * by its identity, and only when it was declared here.
50
67
  */
51
- export declare class Subscriber implements Subscribes {
52
- private readonly contexts;
68
+ export declare class Subscriber<D extends object = Record<never, never>> implements Subscribes {
69
+ /** Its namespace: its own handlers are said `<name>/<Handler>`. */
70
+ readonly name: string;
71
+ private readonly buses;
72
+ private readonly dependencyValues;
73
+ private readonly handlers;
74
+ private readonly instances;
53
75
  private readonly events;
54
76
  private readonly commands;
77
+ constructor(name: string, options?: NamedSubscriberOptions);
55
78
  constructor(options: SubscriberOptions);
56
79
  constructor(...boundedContexts: HearingContext[]);
80
+ /**
81
+ * What its handlers find on `this` — a bus they call, a notifier, a repository —, by name; a
82
+ * dependency carrying `BIND` (a bounded context, a publisher) is bound to the handler's run.
83
+ */
84
+ addDependency<K extends keyof D & string>(name: K, dependency: D[K], options?: {
85
+ replaces: D[K];
86
+ }): this;
87
+ /**
88
+ * A bus it delivers to: the events its use cases and handlers are registered for reach them
89
+ * through this subscriber. By its namespace — no name to write —; the same bus again changes
90
+ * nothing, another of the same name is delivered to as well. It is not a dependency: a
91
+ * handler that calls a bus has it as one (`addDependency`).
92
+ */
93
+ addBus(boundedContext: HearingContext): this;
94
+ /**
95
+ * Registers an event handler of this subscriber for one event or N — as a decorator, or
96
+ * called with the class:
97
+ *
98
+ * @appSubscriber.handler([SalePaid, SaleCancelled])
99
+ * export class OnSaleChanged extends EventHandler<SalePaid | SaleCancelled> { … }
100
+ *
101
+ * appSubscriber.handler([SalePaid, SaleCancelled])(OnSaleChanged);
102
+ */
103
+ handler<const K extends readonly EventKey[]>(events: K): HandlerRegistrar<ExecutableOf<K[number]> & HandledEvent>;
104
+ handler<E extends DomainEvent>(event: EventClass<E>): HandlerRegistrar<E>;
105
+ handler<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor): HandlerRegistrar<E>;
57
106
  /** What an event of that wire name is rebuilt as, or `undefined` when nobody here hears it. */
58
107
  eventTypeOf(name: string): EventType | undefined;
59
108
  /** What a consumed Command of that identity is rebuilt as, or `undefined` when it is not consumed here. */
60
109
  commandTypeOf(identity: string): CommandType | undefined;
61
110
  /**
62
- * 1. Every bounded context that registered the event — its class exactly, or its wire name for
63
- * a generated one —, in the order named, but those `skip` names, which already have it.
64
- * 2. Each executes it — continuing the envelope's flow when there is one —, and its answer or
65
- * failure is kept; a failure does not stop the next.
66
- * Final: what each answered, or failed with; nothing when this subscriber does not hear it.
111
+ * 1. Who consumes the event here: its own handlers, then each bus added, in the order added —
112
+ * the bus's use case, then its handlers —; none when this subscriber does not hear it.
113
+ * 2. Those `skip` names already have it; each other one consumes it — continuing the
114
+ * envelope's flow and trace when there is one —, and its answer or failure is kept: a
115
+ * failure does not stop the next.
116
+ * Final: what each consumer answered, or failed with, under its key.
67
117
  */
68
118
  handle(event: DomainEvent | RemoteEvent, envelope?: Envelope, skip?: readonly string[]): Promise<Handled[]>;
69
119
  /**
70
120
  * What a queue delivered — CloudEvents, structured or in a broker's binary mode —, executed:
71
121
  *
72
122
  * 1. An event this subscriber hears (by its `type`, the event's name): rebuilt as what it is
73
- * known by here and handed to every bounded context that registered it (`handle`).
123
+ * known by here and handed to every consumer subscribed to it (`handle`).
74
124
  * 2. A Command (its `type`, its identity): only when declared — `CommandNotConsumed` when a bus
75
125
  * registered it but this subscriber does not consume it —, rebuilt and executed by the one
76
- * bounded context that registered it.
126
+ * bus that registered it.
77
127
  * 3. Either continues the message's flow and trace.
78
128
  * Final: what each answered, or failed with; nothing when nobody here knows it.
79
129
  */
80
130
  receive(arrived: Message | BinaryMessage, skip?: readonly string[]): Promise<Handled[]>;
131
+ /** Every consumer of `event`, each under a key no other one has. */
132
+ private consumersOf;
133
+ /** One of its own handlers, as a consumer: its run, with this subscriber's dependencies. */
134
+ private consumerOf;
81
135
  }