@sincpro/client-framework 1.3.0 → 1.5.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.
Files changed (34) hide show
  1. package/AGENTS.md +26 -13
  2. package/MANIFESTO.md +2 -1
  3. package/README.md +67 -19
  4. package/dist/core/domain/consumers.d.ts +19 -0
  5. package/dist/core/domain/consumers.js +1 -0
  6. package/dist/core/domain/pipeline.d.ts +2 -1
  7. package/dist/core/domain/services.d.ts +59 -2
  8. package/dist/core/domain/services.js +36 -1
  9. package/dist/core/entrypoint/bounded-context.d.ts +32 -0
  10. package/dist/core/entrypoint/bounded-context.js +104 -19
  11. package/dist/core/index.d.ts +4 -2
  12. package/dist/core/index.js +2 -2
  13. package/dist/core/infrastructure/process.d.ts +16 -0
  14. package/dist/core/infrastructure/process.js +12 -1
  15. package/dist/core/services/event-handlers.d.ts +57 -0
  16. package/dist/core/services/event-handlers.js +114 -0
  17. package/dist/core/services/execution.d.ts +6 -1
  18. package/dist/core/services/execution.js +19 -2
  19. package/dist/event_driven/entrypoint/subscriber.d.ts +82 -28
  20. package/dist/event_driven/entrypoint/subscriber.js +203 -55
  21. package/dist/event_driven/index.d.ts +1 -1
  22. package/dist/observability/adapters/sentry.js +2 -0
  23. package/dist/observability/domain/errors.d.ts +4 -0
  24. package/dist/observability/domain/identity.d.ts +37 -0
  25. package/dist/observability/domain/identity.js +51 -0
  26. package/dist/observability/domain/logging.d.ts +5 -1
  27. package/dist/observability/index.d.ts +2 -1
  28. package/dist/observability/index.js +1 -0
  29. package/dist/observability/infrastructure/registry.d.ts +3 -0
  30. package/dist/observability/infrastructure/registry.js +1 -0
  31. package/dist/observability/services/logging.d.ts +2 -2
  32. package/dist/observability/services/logging.js +25 -11
  33. package/dist/observability/services/reporting.js +6 -1
  34. package/package.json +1 -1
@@ -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
  }
@@ -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";
@@ -19,6 +19,8 @@ export function sentryReporter(client) {
19
19
  captureContext: {
20
20
  tags: {
21
21
  "sincpro.use_case": about.useCase,
22
+ ...(about.release ? { release: about.release } : {}),
23
+ ...(about.tenant ? { tenant: about.tenant } : {}),
22
24
  ...(about.traceId === "" ? {} : { trace_id: about.traceId }),
23
25
  },
24
26
  contexts: {
@@ -16,6 +16,10 @@ export type ErrorAbout = {
16
16
  executionId: string;
17
17
  /** What the use case ran with: the process's context, its bounded context's, its scope's. */
18
18
  context: Readonly<Record<string, unknown>>;
19
+ /** Who was running (`configureProcess({ identity })`), when the process says. */
20
+ release?: string;
21
+ /** The run's tenant — its context's, else the deployment's —, when there is one. */
22
+ tenant?: string;
19
23
  };
20
24
  /** Reports what nobody expected. One per platform; none when nothing reports. */
21
25
  export interface ErrorReporter {
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Who is running — sincpro_framework's identity, the same text on every signal: a span, a log
3
+ * line, a report.
4
+ *
5
+ * identityOf("sincpro-mobile-tickets:0.3.0")
6
+ * → { release: "sincpro-mobile-tickets:0.3.0",
7
+ * serviceName: "sincpro-mobile-tickets", serviceVersion: "0.3.0" }
8
+ * identityOf("registry.io/team/app:1.2@sha256:ab…") → serviceName "app", serviceVersion "1.2"
9
+ * identityOf("app@1.2.3") → "app", "1.2.3"
10
+ * identityOf("registry.local:5000/team/app") → "app", "" (a port, no tag)
11
+ *
12
+ * Context: the release is the backend's `APP_RELEASE`, used verbatim; the name and the version
13
+ * are read out of it with the backend's rules (`ObservabilityIdentity._split`), so GlitchTip's
14
+ * release, Tempo's `service.name` and the logs' `service_name` never drift apart. The tenant is
15
+ * the deployment's, when it serves one; a run's own comes from its context (`tenantOf`).
16
+ */
17
+ export type ProcessIdentity = {
18
+ /** `<name>:<version>` as deployed — GlitchTip's release and every signal's `release`. */
19
+ readonly release: string;
20
+ /** The name, without its registry or its version: `service.name`. */
21
+ readonly serviceName: string;
22
+ /** The version out of the release; empty when it names none. */
23
+ readonly serviceVersion: string;
24
+ /** The tenant the deployment serves, when it serves one. */
25
+ readonly tenant?: string;
26
+ };
27
+ /** The key the release goes by on a span, a log line and a report. */
28
+ export declare const RELEASE = "release";
29
+ /** The key the tenant goes by on a span, a log line and a report. */
30
+ export declare const TENANT = "tenant";
31
+ /** Who is running, out of its release — and the deployment's tenant, when there is one. */
32
+ export declare function identityOf(release: string, tenant?: string): ProcessIdentity;
33
+ /**
34
+ * The tenant of a run: its context's (`tenant`, else `tenant_id`), else the deployment's.
35
+ * Undefined when neither says one — most phones serve whoever opens the app.
36
+ */
37
+ export declare function tenantOf(context: Readonly<Record<string, unknown>>, identity: ProcessIdentity | undefined): string | undefined;
@@ -0,0 +1,51 @@
1
+ /** The key the release goes by on a span, a log line and a report. */
2
+ export const RELEASE = "release";
3
+ /** The key the tenant goes by on a span, a log line and a report. */
4
+ export const TENANT = "tenant";
5
+ /** Who is running, out of its release — and the deployment's tenant, when there is one. */
6
+ export function identityOf(release, tenant) {
7
+ const verbatim = release.trim();
8
+ const [artifact, version] = split(verbatim);
9
+ const deployed = tenant?.trim();
10
+ return {
11
+ release: verbatim,
12
+ serviceName: artifact.slice(artifact.lastIndexOf("/") + 1),
13
+ serviceVersion: version,
14
+ ...(deployed ? { tenant: deployed } : {}),
15
+ };
16
+ }
17
+ /**
18
+ * The tenant of a run: its context's (`tenant`, else `tenant_id`), else the deployment's.
19
+ * Undefined when neither says one — most phones serve whoever opens the app.
20
+ */
21
+ export function tenantOf(context, identity) {
22
+ for (const key of [TENANT, "tenant_id"]) {
23
+ const value = context[key];
24
+ if (typeof value === "string" && value !== "")
25
+ return value;
26
+ if (typeof value === "number")
27
+ return String(value);
28
+ }
29
+ return identity?.tenant;
30
+ }
31
+ /**
32
+ * Name and version out of a release, read as an image reference or `name@version`:
33
+ * 1. `@`: a digest (`@sha256:…`) is dropped; anything else after it is the version.
34
+ * 2. `:` after the last `/` is the tag; one before it is a registry's port.
35
+ * Final: no version when neither says one.
36
+ */
37
+ function split(release) {
38
+ let artifact = release;
39
+ const at = artifact.lastIndexOf("@");
40
+ if (at >= 0) {
41
+ const after = artifact.slice(at + 1);
42
+ artifact = artifact.slice(0, at);
43
+ if (!after.includes(":"))
44
+ return [artifact, after];
45
+ }
46
+ const colon = artifact.lastIndexOf(":");
47
+ if (colon > artifact.lastIndexOf("/")) {
48
+ return [artifact.slice(0, colon), artifact.slice(colon + 1)];
49
+ }
50
+ return [artifact, ""];
51
+ }
@@ -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;
@@ -30,6 +30,10 @@ export type LogRecord = {
30
30
  readonly spanId?: string;
31
31
  readonly outcome?: Outcome;
32
32
  readonly durationMs?: number;
33
+ /** Who was running (`configureProcess({ identity })`), when the process says. */
34
+ readonly release?: string;
35
+ /** The run's tenant — its context's, else the deployment's —, when there is one. */
36
+ readonly tenant?: string;
33
37
  };
34
38
  /** A sink owns filtering and delivery. Logging is best-effort and never awaited by business work. */
35
39
  export interface Logger {