@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.
@@ -1,4 +1,9 @@
1
+ import { processContext } from "../../context/infrastructure/process.js";
2
+ import { RESERVED_MEMBERS, } from "../../core/domain/services.js";
3
+ import { processHearing } from "../../core/infrastructure/listeners.js";
1
4
  import { identityOf, keyIdentity } from "../../core/services/dto-keys.js";
5
+ import { eventKeysOf, handlerRegistrar, handles, runHandler, } from "../../core/services/event-handlers.js";
6
+ import { announceTo } from "../../core/services/listening.js";
2
7
  import { causeOf, commandFrom, envelopeFrom, eventFrom, readMessage, } from "../services/messages.js";
3
8
  /** A Command the queue carried that this subscriber was not told to consume. */
4
9
  export class CommandNotConsumed extends Error {
@@ -28,50 +33,148 @@ function wireNames(keys) {
28
33
  }
29
34
  return names;
30
35
  }
36
+ /** The consumers of a bus: what it says, or — a bus that says nothing — its one use case. */
37
+ function consumersIn(bus, event) {
38
+ const { context, key } = bus;
39
+ let consumers;
40
+ if (context.consumersOf)
41
+ consumers = context.consumersOf(event);
42
+ else {
43
+ const known = identityOf(event);
44
+ const hears = known?.type !== undefined
45
+ ? context.handlerOf(known.type) !== undefined
46
+ : context.eventTypeOf(known?.wire ?? "") !== undefined;
47
+ consumers = hears
48
+ ? [{ key: context.name, consume: (heard, cause) => context.execute(heard, cause) }]
49
+ : [];
50
+ }
51
+ if (key === context.name)
52
+ return consumers;
53
+ // Another bus of the same name: its consumers are acknowledged under its own key.
54
+ return consumers.map((one) => ({
55
+ key: one.key === context.name ? key : `${key}${one.key.slice(context.name.length)}`,
56
+ consume: one.consume,
57
+ }));
58
+ }
31
59
  /**
32
- * The queue's entrypoint — the backend's `Subscriber(*buses)` and `QueueGateway`: what arrives is
33
- * recognized, rebuilt and executed on the bus that registered it.
60
+ * The queue's entrypoint — the backend's `Subscriber(*buses)` and `QueueGateway`, composed: it
61
+ * pulls what the queue delivers, rebuilds it and hands it to every consumer subscribed to it —
62
+ * its own event handlers, and the buses added to it, each with its use case and its handlers.
63
+ *
64
+ * // entrypoints/queue/framework.ts — once, like a bounded context's framework.ts
65
+ * export const { EventHandler } = handlersWith<AppSubscriberDependencies>();
66
+ * export const appSubscriber = new Subscriber<AppSubscriberDependencies>("app");
67
+ * appSubscriber.addDependency("invoicingBoundedContext", invoicingBoundedContext); // to call it
68
+ * appSubscriber.addDependency("notifier", deviceNotifier);
69
+ * appSubscriber.addBus(salesBoundedContext); // to deliver to its use cases and handlers
70
+ *
71
+ * // entrypoints/queue/sale_paid.handler.ts — events → handler
72
+ * @appSubscriber.handler([SalePaid])
73
+ * export class NotifySalePaid extends EventHandler<SalePaid> { async handle(event) { … } }
34
74
  *
35
- * new Subscriber(billingBoundedContext, accountingBoundedContext) // every event they registered
36
- * new Subscriber({
37
- * boundedContexts: [billingBoundedContext],
38
- * events: [OrderPaid, events.IssueClosed], // only these
39
- * commands: [CommandIssueInvoice], // consumed: declared
40
- * })
41
- * await subscriber.receive(message); // what each one answered
75
+ * storedQueue({ store, subscriber: appSubscriber });
42
76
  *
43
- * Context: one per queue, never one per event — registering a use case for an event is the
44
- * subscription. An event is a fact N buses hear, by its wire name; a Command is a request to one
45
- * bus, by its identity, and only when it was declared here. Several hearing one event is several
46
- * executions, one each, in the order named; one that fails does not stop the others, and each is
47
- * said under its bounded context's name — which a stored queue keeps, so a redelivery never runs
48
- * one again. Two never share a name.
77
+ * Context: one per queue, never one per handler. Two levels, never mixed: a dependency — a bus
78
+ * to call included — is what its handlers find on `this` (`addDependency`, by name); a bus added
79
+ * (`addBus`, by its own namespace) is one it delivers to. Adding the same bus again changes
80
+ * nothing; another bus of the same name is delivered to as well (`sales#2`). Every consumer is
81
+ * acknowledged apart — `app/NotifySalePaid`, `sales`, `sales/OnSalePaid` —, which a stored queue
82
+ * keeps, so a redelivery runs only who does not have it yet. A Command is a request to one bus,
83
+ * by its identity, and only when it was declared here.
49
84
  */
50
85
  export class Subscriber {
51
- contexts;
86
+ /** Its namespace: its own handlers are said `<name>/<Handler>`. */
87
+ name;
88
+ buses = [];
89
+ dependencyValues = new Map();
90
+ handlers = [];
91
+ instances = new Map();
52
92
  events;
53
93
  commands;
54
94
  constructor(...given) {
55
- const options = given.length === 1 && isOptions(given[0])
56
- ? given[0]
57
- : { boundedContexts: given };
58
- const names = new Set();
59
- for (const context of options.boundedContexts) {
60
- if (names.has(context.name)) {
61
- throw new Error(`Two bounded contexts are named ${context.name}: the queue keeps who heard a message by its name`);
95
+ let options;
96
+ let boundedContexts = [];
97
+ if (typeof given[0] === "string") {
98
+ const name = given[0];
99
+ if (name.trim() === "" || name.includes("/")) {
100
+ throw new TypeError("A subscriber needs a nonempty name without '/'");
62
101
  }
63
- names.add(context.name);
102
+ this.name = name;
103
+ options = given[1] ?? {};
104
+ }
105
+ else {
106
+ this.name = "";
107
+ const all = given.length === 1 && isOptions(given[0])
108
+ ? given[0]
109
+ : { boundedContexts: given };
110
+ options = all;
111
+ boundedContexts = all.boundedContexts;
64
112
  }
65
- this.contexts = options.boundedContexts;
66
113
  this.events = wireNames(options.events);
67
114
  this.commands = wireNames(options.commands) ?? new Set();
115
+ for (const boundedContext of boundedContexts)
116
+ this.addBus(boundedContext);
117
+ }
118
+ /**
119
+ * What its handlers find on `this` — a bus they call, a notifier, a repository —, by name; a
120
+ * dependency carrying `BIND` (a bounded context, a publisher) is bound to the handler's run.
121
+ */
122
+ addDependency(name, dependency, options) {
123
+ if (RESERVED_MEMBERS.has(name))
124
+ throw new Error(`Reserved dependency name: ${name}`);
125
+ const registered = this.dependencyValues.has(name);
126
+ if (registered && options === undefined) {
127
+ throw new Error(`Dependency already registered: ${name}`);
128
+ }
129
+ if (options && (!registered || this.dependencyValues.get(name) !== options.replaces)) {
130
+ throw new Error(`Replacement does not match the dependency: ${name}`);
131
+ }
132
+ this.dependencyValues.set(name, dependency);
133
+ return this;
134
+ }
135
+ /**
136
+ * A bus it delivers to: the events its use cases and handlers are registered for reach them
137
+ * through this subscriber. By its namespace — no name to write —; the same bus again changes
138
+ * nothing, another of the same name is delivered to as well. It is not a dependency: a
139
+ * handler that calls a bus has it as one (`addDependency`).
140
+ */
141
+ addBus(boundedContext) {
142
+ if (this.buses.some((one) => one.context === boundedContext))
143
+ return this;
144
+ const sameName = this.buses.filter((one) => one.context.name === boundedContext.name);
145
+ const key = sameName.length === 0
146
+ ? boundedContext.name
147
+ : `${boundedContext.name}#${sameName.length + 1}`;
148
+ this.buses.push({ context: boundedContext, key });
149
+ return this;
150
+ }
151
+ handler(events) {
152
+ const keys = eventKeysOf(events);
153
+ return handlerRegistrar((Handler, name) => {
154
+ if (this.name === "") {
155
+ throw new Error("A subscriber with event handlers has a name: new Subscriber(name)");
156
+ }
157
+ if (this.handlers.some((one) => one.Handler === Handler)) {
158
+ throw new Error(`Event handler already registered: ${name} — list all its events once`);
159
+ }
160
+ if (this.handlers.some((one) => one.name === name)) {
161
+ throw new Error(`Event handler name already registered: ${name}`);
162
+ }
163
+ this.handlers.push({ name, Handler, events: keys });
164
+ });
68
165
  }
69
166
  /** What an event of that wire name is rebuilt as, or `undefined` when nobody here hears it. */
70
167
  eventTypeOf(name) {
71
168
  if (this.events !== undefined && !this.events.has(name))
72
169
  return undefined;
73
- for (const context of this.contexts) {
74
- const found = context.eventTypeOf(name);
170
+ for (const registration of this.handlers) {
171
+ for (const key of registration.events) {
172
+ if (keyIdentity(key).wire === name)
173
+ return key;
174
+ }
175
+ }
176
+ for (const bus of this.buses) {
177
+ const found = bus.context.eventTypeOf(name);
75
178
  if (found)
76
179
  return found;
77
180
  }
@@ -81,41 +184,34 @@ export class Subscriber {
81
184
  commandTypeOf(identity) {
82
185
  if (!this.commands.has(identity))
83
186
  return undefined;
84
- for (const context of this.contexts) {
85
- const found = context.commandTypeOf(identity);
187
+ for (const bus of this.buses) {
188
+ const found = bus.context.commandTypeOf(identity);
86
189
  if (found)
87
190
  return found;
88
191
  }
89
192
  return undefined;
90
193
  }
91
194
  /**
92
- * 1. Every bounded context that registered the event — its class exactly, or its wire name for
93
- * a generated one —, in the order named, but those `skip` names, which already have it.
94
- * 2. Each executes it — continuing the envelope's flow when there is one —, and its answer or
95
- * failure is kept; a failure does not stop the next.
96
- * Final: what each answered, or failed with; nothing when this subscriber does not hear it.
195
+ * 1. Who consumes the event here: its own handlers, then each bus added, in the order added —
196
+ * the bus's use case, then its handlers —; none when this subscriber does not hear it.
197
+ * 2. Those `skip` names already have it; each other one consumes it — continuing the
198
+ * envelope's flow and trace when there is one —, and its answer or failure is kept: a
199
+ * failure does not stop the next.
200
+ * Final: what each consumer answered, or failed with, under its key.
97
201
  */
98
202
  async handle(event, envelope, skip = []) {
99
- const known = identityOf(event);
100
- if (known?.kind !== "event")
101
- return [];
102
- if (this.events !== undefined && !this.events.has(known.wire ?? ""))
103
- return [];
104
203
  const handled = [];
105
- for (const context of this.contexts) {
106
- const hears = known.type !== undefined
107
- ? context.handlerOf(known.type) !== undefined
108
- : context.eventTypeOf(known.wire ?? "") !== undefined;
109
- if (!hears || skip.includes(context.name))
204
+ for (const consumer of this.consumersOf(event)) {
205
+ if (skip.includes(consumer.key))
110
206
  continue;
111
207
  try {
112
208
  handled.push({
113
- boundedContext: context.name,
114
- answer: await context.execute(event, envelope),
209
+ boundedContext: consumer.key,
210
+ answer: await consumer.consume(event, envelope),
115
211
  });
116
212
  }
117
213
  catch (error) {
118
- handled.push({ boundedContext: context.name, error });
214
+ handled.push({ boundedContext: consumer.key, error });
119
215
  }
120
216
  }
121
217
  return handled;
@@ -124,10 +220,10 @@ export class Subscriber {
124
220
  * What a queue delivered — CloudEvents, structured or in a broker's binary mode —, executed:
125
221
  *
126
222
  * 1. An event this subscriber hears (by its `type`, the event's name): rebuilt as what it is
127
- * known by here and handed to every bounded context that registered it (`handle`).
223
+ * known by here and handed to every consumer subscribed to it (`handle`).
128
224
  * 2. A Command (its `type`, its identity): only when declared — `CommandNotConsumed` when a bus
129
225
  * registered it but this subscriber does not consume it —, rebuilt and executed by the one
130
- * bounded context that registered it.
226
+ * bus that registered it.
131
227
  * 3. Either continues the message's flow and trace.
132
228
  * Final: what each answered, or failed with; nothing when nobody here knows it.
133
229
  */
@@ -138,21 +234,73 @@ export class Subscriber {
138
234
  return this.handle(eventFrom(eventType, message.data), envelopeFrom(message), skip);
139
235
  const commandType = this.commandTypeOf(message.type);
140
236
  if (commandType === undefined) {
141
- if (this.contexts.some((one) => one.commandTypeOf(message.type) !== undefined))
237
+ if (this.buses.some((one) => one.context.commandTypeOf(message.type) !== undefined))
142
238
  throw new CommandNotConsumed(message.type);
143
239
  return [];
144
240
  }
145
- const context = this.contexts.find((one) => one.commandTypeOf(message.type) !== undefined);
146
- if (context === undefined || skip.includes(context.name))
241
+ const bus = this.buses.find((one) => one.context.commandTypeOf(message.type) !== undefined);
242
+ if (bus === undefined || skip.includes(bus.key))
147
243
  return [];
148
244
  try {
149
- const answer = await context.execute(commandFrom(commandType, message.data), {
245
+ const answer = await bus.context.execute(commandFrom(commandType, message.data), {
150
246
  cause: causeOf(message),
151
247
  });
152
- return [{ boundedContext: context.name, answer }];
248
+ return [{ boundedContext: bus.key, answer }];
153
249
  }
154
250
  catch (error) {
155
- return [{ boundedContext: context.name, error }];
251
+ return [{ boundedContext: bus.key, error }];
252
+ }
253
+ }
254
+ /** Every consumer of `event`, each under a key no other one has. */
255
+ consumersOf(event) {
256
+ const known = identityOf(event);
257
+ if (known?.kind !== "event")
258
+ return [];
259
+ if (this.events !== undefined && !this.events.has(known.wire ?? ""))
260
+ return [];
261
+ const consumers = [];
262
+ for (const registration of this.handlers) {
263
+ if (!registration.events.some((key) => handles(key, known)))
264
+ continue;
265
+ consumers.push(this.consumerOf(registration));
156
266
  }
267
+ for (const bus of this.buses)
268
+ consumers.push(...consumersIn(bus, event));
269
+ const keys = new Set();
270
+ for (const consumer of consumers) {
271
+ if (keys.has(consumer.key)) {
272
+ throw new Error(`Two consumers are ${consumer.key}: the queue keeps who has a message by it`);
273
+ }
274
+ keys.add(consumer.key);
275
+ }
276
+ return consumers;
277
+ }
278
+ /** One of its own handlers, as a consumer: its run, with this subscriber's dependencies. */
279
+ consumerOf(registration) {
280
+ const everyContext = processHearing();
281
+ return {
282
+ key: `${this.name}/${registration.name}`,
283
+ consume: (event, cause) => {
284
+ let instance = this.instances.get(registration.Handler);
285
+ if (instance === undefined) {
286
+ instance = new registration.Handler();
287
+ this.instances.set(registration.Handler, instance);
288
+ }
289
+ return runHandler(instance, event, {
290
+ owner: this.name,
291
+ name: registration.name,
292
+ dependencies: this.dependencyValues,
293
+ context: () => ({ ...processContext.values }),
294
+ ...(cause ? { cause } : {}),
295
+ expected: () => false,
296
+ interceptors: [],
297
+ announce: {
298
+ started: (heard) => announceTo(everyContext.started, heard),
299
+ completed: (heard) => announceTo(everyContext.completed, heard),
300
+ },
301
+ failed: (heard) => announceTo(everyContext.failed, heard),
302
+ });
303
+ },
304
+ };
157
305
  }
158
306
  }
@@ -19,5 +19,5 @@ export type { BinaryMessage, Message, } from "./domain/messages.js";
19
19
  export type { CommandType, EventQueue, EventType, Handled, Subscribes, } from "./domain/queue.js";
20
20
  export type { DeliveryFailure, EventStore, StoredEvent, StoredState, } from "./domain/store.js";
21
21
  export { Publisher } from "./entrypoint/publisher.js";
22
- export { CommandNotConsumed, type HearingContext, Subscriber, type SubscriberOptions, } from "./entrypoint/subscriber.js";
22
+ export { CommandNotConsumed, type HearingContext, type NamedSubscriberOptions, Subscriber, type SubscriberOptions, } from "./entrypoint/subscriber.js";
23
23
  export { causeOf, commandFrom, commandMessageOf, envelopeFrom, eventFrom, eventMessageOf, type MessageOptions, readMessage, } from "./services/messages.js";
@@ -12,7 +12,7 @@ import type { Attributes, Outcome } from "./tracing.js";
12
12
  */
13
13
  export type LogLevel = "debug" | "info" | "warn" | "error";
14
14
  /** The layer a line comes from. */
15
- export type LogLayer = "infrastructure" | "adapter" | "bounded_context" | "application_service" | "feature";
15
+ export type LogLayer = "infrastructure" | "adapter" | "bounded_context" | "event_handler" | "application_service" | "feature";
16
16
  /** Structured logging never implicitly includes a DTO, response, error body or session context. */
17
17
  export type LogRecord = {
18
18
  readonly timestamp: string;
@@ -7,8 +7,8 @@ export declare const logger: LayerLogger;
7
7
  export declare const loggerAdapter: LayerLogger;
8
8
  /** @internal — a bounded context's own logger (`projectBoundedContext.logger`). */
9
9
  export declare function boundedContextLogger(name: string): LayerLogger;
10
- /** A run's layer: a Feature's or an ApplicationService's. */
11
- type RunLogLayer = Extract<LogLayer, "feature" | "application_service">;
10
+ /** A run's layer: a Feature's, an ApplicationService's or an event handler's. */
11
+ type RunLogLayer = Extract<LogLayer, "feature" | "application_service" | "event_handler">;
12
12
  /** @internal — what a Feature or ApplicationService finds as `this.logger` while it runs. */
13
13
  export declare function executionLogger(layer: RunLogLayer, execution: Execution): LayerLogger;
14
14
  /** Each destination keeps its own policy; one failing sink does not hold back the others. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/client-framework",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "The client side of sincpro_framework, for every platform: Feature and ApplicationService traced and reported by default, applications made of domains, and the typed client generated from a service's contract. No React, no DOM.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",