@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
@@ -5,8 +5,10 @@ import { FeatureBus, optionsOf, } from "../domain/bus.js";
5
5
  import { EVENT_NAME, } from "../domain/dto.js";
6
6
  import { ApplicationService, Feature, RESERVED_MEMBERS, } from "../domain/services.js";
7
7
  import { processHearing } from "../infrastructure/listeners.js";
8
+ import { bindDependency } from "../services/binding.js";
8
9
  import { describeDto, identityOf, isCommandClass, isCommandDescriptor, isDtoKey, keyIdentity, } from "../services/dto-keys.js";
9
10
  import { handled } from "../services/error-handlers.js";
11
+ import { eventKeysOf, handlerRegistrar, handles, runHandler, } from "../services/event-handlers.js";
10
12
  import { executeService, failedAt } from "../services/execution.js";
11
13
  import { announceTo, concerns, listenIn, } from "../services/listening.js";
12
14
  import { observabilityNow } from "../../observability/infrastructure/registry.js";
@@ -50,6 +52,7 @@ export class BoundedContext {
50
52
  /** Its own logger, named after it: for what it does outside a use case. */
51
53
  logger;
52
54
  registrations = new Map();
55
+ eventHandlers = [];
53
56
  dependencyValues = new Map();
54
57
  handlers = {
55
58
  global: [],
@@ -118,6 +121,10 @@ export class BoundedContext {
118
121
  appService(dto, options) {
119
122
  return this.registrar(dto, "application_service", options);
120
123
  }
124
+ handler(events) {
125
+ const keys = eventKeysOf(events);
126
+ return handlerRegistrar((Handler, name) => this.registerHandler(Handler, name, keys));
127
+ }
121
128
  /** The service registered now for a DTO — what a `replaces` names. */
122
129
  handlerOf(dto) {
123
130
  return this.registrations.get(dto)?.Service;
@@ -133,8 +140,21 @@ export class BoundedContext {
133
140
  if (known.kind === "event" && known.wire === name)
134
141
  return dto;
135
142
  }
143
+ for (const registration of this.eventHandlers) {
144
+ for (const key of registration.events) {
145
+ if (keyIdentity(key).wire === name)
146
+ return key;
147
+ }
148
+ }
136
149
  return undefined;
137
150
  }
151
+ /**
152
+ * @internal — who consumes `event` here, for the `Subscriber` that delivers it: its use case
153
+ * (keyed by this context's name) and each of its event handlers (`<context>/<Handler>`).
154
+ */
155
+ consumersOf(event) {
156
+ return this.generation().consumersOf(event);
157
+ }
138
158
  /**
139
159
  * What a Command of that identity (`<context>.<Command>`) is rebuilt as here — its class, or
140
160
  * the generated entry it was registered with —, or `undefined` when nothing here executes it.
@@ -261,6 +281,7 @@ export class BoundedContext {
261
281
  for (const [name, dependency] of this.dependencyValues) {
262
282
  fresh.dependencyValues.set(name, dependency);
263
283
  }
284
+ fresh.eventHandlers.push(...this.eventHandlers);
264
285
  for (const where of ["global", "feature", "application_service"]) {
265
286
  fresh.handlers[where].push(...this.handlers[where]);
266
287
  }
@@ -384,6 +405,9 @@ export class BoundedContext {
384
405
  if (typeof name !== "string" || name.trim() === "") {
385
406
  throw new Error("A service is a named class: its name is its use case in spans and logs");
386
407
  }
408
+ if (this.eventHandlers.some((one) => one.name === name)) {
409
+ throw new Error(`Service name already registered: ${name}`);
410
+ }
387
411
  for (const [other, registration] of this.registrations) {
388
412
  if (registration !== current &&
389
413
  registration.Service !== Service &&
@@ -407,6 +431,22 @@ export class BoundedContext {
407
431
  });
408
432
  this.revision++;
409
433
  }
434
+ /**
435
+ * 1. A class registered once, for the events listed: register it for N in one call.
436
+ * 2. Its name is no other handler's or service's here: both are said `<context>/<Name>`.
437
+ * Final: registered; the next delivery reaches it.
438
+ */
439
+ registerHandler(Handler, name, events) {
440
+ if (this.eventHandlers.some((one) => one.Handler === Handler)) {
441
+ throw new Error(`Event handler already registered: ${name} — list all its events once`);
442
+ }
443
+ const taken = this.eventHandlers.some((one) => one.name === name) ||
444
+ [...this.registrations.values()].some((one) => one.name === name);
445
+ if (taken)
446
+ throw new Error(`Service name already registered: ${name}`);
447
+ this.eventHandlers.push({ name, Handler, events });
448
+ this.revision++;
449
+ }
410
450
  generation() {
411
451
  if (this.built && this.builtRevision === this.revision)
412
452
  return this.built;
@@ -499,27 +539,72 @@ export class BoundedContext {
499
539
  announce,
500
540
  });
501
541
  };
502
- return {
503
- root: async (executable, scope, options) => {
504
- try {
505
- return await dispatch(executable, undefined, false, scope, options);
506
- }
507
- catch (error) {
508
- let escaping = error;
509
- if (handlers.global.length > 0) {
510
- try {
511
- const answer = await handled(handlers.global, error);
512
- logHandled("bounded_context", { boundedContext: this.name });
513
- return answer;
514
- }
515
- catch (thrown) {
516
- escaping = thrown;
517
- }
542
+ const root = async (executable, scope, options) => {
543
+ try {
544
+ return await dispatch(executable, undefined, false, scope, options);
545
+ }
546
+ catch (error) {
547
+ let escaping = error;
548
+ if (handlers.global.length > 0) {
549
+ try {
550
+ const answer = await handled(handlers.global, error);
551
+ logHandled("bounded_context", { boundedContext: this.name });
552
+ return answer;
553
+ }
554
+ catch (thrown) {
555
+ escaping = thrown;
518
556
  }
519
- this.escaped(executable, escaping, expected);
520
- throw escaping;
521
557
  }
522
- },
558
+ this.escaped(executable, escaping, expected);
559
+ throw escaping;
560
+ }
561
+ };
562
+ // The event handlers of this generation: one instance each, a singleton like a service.
563
+ const eventHandlers = this.eventHandlers.map((registration) => ({
564
+ registration,
565
+ instance: new registration.Handler(),
566
+ }));
567
+ const context = () => ({ ...processContext.values, ...this.context.values });
568
+ const consumersOf = (event) => {
569
+ const known = identityOf(event);
570
+ if (known?.kind !== "event")
571
+ return [];
572
+ const consumers = [];
573
+ const useCase = known.type !== undefined
574
+ ? registrations.get(known.type)
575
+ : generated.get(`event:${known.wire}`);
576
+ if (useCase) {
577
+ consumers.push({
578
+ key: this.name,
579
+ consume: (heard, cause) => root(heard, {}, cause ? { cause } : {}),
580
+ });
581
+ }
582
+ for (const { registration, instance } of eventHandlers) {
583
+ if (!registration.events.some((key) => handles(key, known)))
584
+ continue;
585
+ consumers.push({
586
+ key: `${this.name}/${registration.name}`,
587
+ consume: (heard, cause) => runHandler(instance, heard, {
588
+ owner: this.name,
589
+ name: registration.name,
590
+ dependencies,
591
+ context,
592
+ ...(cause ? { cause } : {}),
593
+ boundedContextOf: (execution) => bindDependency(this, execution),
594
+ expected,
595
+ interceptors: interceptors
596
+ .filter((one) => concerns(one.dtos, heard))
597
+ .map((one) => one.what),
598
+ announce,
599
+ failed: (failure) => {
600
+ announceTo(this.listeners.failed, failure);
601
+ announceTo(everyContext.failed, failure);
602
+ },
603
+ }),
604
+ });
605
+ }
606
+ return consumers;
523
607
  };
608
+ return { root, consumersOf };
524
609
  }
525
610
  }
@@ -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
- export { configureLogger, configureProcess, type LoggerConfiguration, type ProcessOptions, } from "./infrastructure/process.js";
21
+ export { configureLogger, configureProcess, type LoggerConfiguration, processIdentity, type ProcessOptions, } from "./infrastructure/process.js";
22
+ export type { HandlerRegistrar } from "./services/event-handlers.js";
@@ -11,8 +11,8 @@
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";
18
- export { configureLogger, configureProcess, } from "./infrastructure/process.js";
18
+ export { configureLogger, configureProcess, processIdentity, } from "./infrastructure/process.js";
@@ -1,6 +1,7 @@
1
1
  import type { ContextStore } from "../../context/domain/store.js";
2
2
  import { type ConsoleLoggerOptions } from "../../observability/adapters/console.js";
3
3
  import type { ErrorReporter } from "../../observability/domain/errors.js";
4
+ import { type ProcessIdentity } from "../../observability/domain/identity.js";
4
5
  import type { Logger } from "../../observability/domain/logging.js";
5
6
  import { type Outcome, type Tracer } from "../../observability/domain/tracing.js";
6
7
  /**
@@ -24,6 +25,7 @@ export type LoggerConfiguration = Partial<ConsoleLoggerOptions> & {
24
25
  *
25
26
  * // entrypoints/main.tsx — the platform's pieces, built from the application's settings
26
27
  * configureProcess({
28
+ * identity: { release: "forge-web:1.4.0" }, // + tenant, when the deployment serves one
27
29
  * tracer: browserTracer({ endpoint: settings.otlp, service: "forge-web" }),
28
30
  * reporter: glitchtipReporter({ dsn: settings.glitchtip }),
29
31
  * logger: { mode: settings.production ? "production" : "development" },
@@ -40,6 +42,15 @@ export type LoggerConfiguration = Partial<ConsoleLoggerOptions> & {
40
42
  * with its own tracer and starts from a clean context.
41
43
  */
42
44
  export type ProcessOptions = {
45
+ /**
46
+ * Who is running — the backend's `APP_RELEASE` (`<name>:<version>`) and `TENANT`. Every span,
47
+ * log line and report says its `release` and, when there is one, its `tenant` (the run's
48
+ * context's, else this one); `service.name` and `service.version` are read out of the release.
49
+ */
50
+ identity?: {
51
+ release: string;
52
+ tenant?: string;
53
+ };
43
54
  /** The platform's (OpenTelemetry in a browser, a queue on a phone, memory in a test). */
44
55
  tracer?: Tracer;
45
56
  /** The platform's (GlitchTip, Sentry, memory in a test). Only what nobody expected reaches it. */
@@ -52,5 +63,10 @@ export type ProcessOptions = {
52
63
  outcomeOf?: (error: unknown) => Outcome;
53
64
  };
54
65
  export declare function configureProcess(options?: ProcessOptions): void;
66
+ /**
67
+ * Who the process is running as (`configureProcess({ identity })`): what a platform's tracer puts
68
+ * on its resource and its log shipping on its labels, so no adapter invents a key of its own.
69
+ */
70
+ export declare function processIdentity(): ProcessIdentity | undefined;
55
71
  /** Replace logging only; tracing, reporting and the context stay as they are. */
56
72
  export declare function configureLogger(options?: LoggerConfiguration): void;
@@ -1,8 +1,9 @@
1
1
  import { memoryContexts } from "../../context/adapters/memory.js";
2
2
  import { replaceProcessStore } from "../../context/infrastructure/process.js";
3
3
  import { consoleLogger, } from "../../observability/adapters/console.js";
4
+ import { identityOf, } from "../../observability/domain/identity.js";
4
5
  import { NO_TRACER, } from "../../observability/domain/tracing.js";
5
- import { replaceObservability } from "../../observability/infrastructure/registry.js";
6
+ import { observabilityNow, replaceObservability, } from "../../observability/infrastructure/registry.js";
6
7
  import { outcomeOf } from "../../observability/services/outcome.js";
7
8
  function loggingEngine(options) {
8
9
  if (options.engine === false)
@@ -22,6 +23,9 @@ function loggingEngine(options) {
22
23
  export function configureProcess(options = {}) {
23
24
  const logger = loggingEngine(options.logger ?? {});
24
25
  replaceObservability({
26
+ identity: options.identity
27
+ ? identityOf(options.identity.release, options.identity.tenant)
28
+ : undefined,
25
29
  tracer: options.tracer ?? NO_TRACER,
26
30
  reporter: options.reporter,
27
31
  logger,
@@ -29,6 +33,13 @@ export function configureProcess(options = {}) {
29
33
  });
30
34
  replaceProcessStore(options.context ?? memoryContexts());
31
35
  }
36
+ /**
37
+ * Who the process is running as (`configureProcess({ identity })`): what a platform's tracer puts
38
+ * on its resource and its log shipping on its labels, so no adapter invents a key of its own.
39
+ */
40
+ export function processIdentity() {
41
+ return observabilityNow().identity;
42
+ }
32
43
  /** Replace logging only; tracing, reporting and the context stay as they are. */
33
44
  export function configureLogger(options = {}) {
34
45
  replaceObservability({ logger: loggingEngine(options) });
@@ -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
@@ -2,6 +2,7 @@ import { newEntityId } from "../../common/ids.js";
2
2
  import { bindDependency } from "./binding.js";
3
3
  import { handled } from "./error-handlers.js";
4
4
  import { runAround } from "./interceptors.js";
5
+ import { tenantOf } from "../../observability/domain/identity.js";
5
6
  import { NO_TRACER, } from "../../observability/domain/tracing.js";
6
7
  import { observabilityNow } from "../../observability/infrastructure/registry.js";
7
8
  import { executionLogger, logExecution, logHandled, } from "../../observability/services/logging.js";
@@ -53,6 +54,7 @@ function serviceView(target, options, execution) {
53
54
  const dependencies = new Map();
54
55
  const logger = executionLogger(options.layer, execution);
55
56
  let features;
57
+ let own;
56
58
  return new Proxy(target, {
57
59
  get(held, property, receiver) {
58
60
  if (property === "context")
@@ -68,6 +70,9 @@ function serviceView(target, options, execution) {
68
70
  if (property === "featureBus" && options.layer === "application_service") {
69
71
  return (features ??= options.featureBus(execution));
70
72
  }
73
+ if (property === "boundedContext" && options.boundedContextOf) {
74
+ return (own ??= options.boundedContextOf(execution));
75
+ }
71
76
  if (typeof property === "string" && options.dependencies.has(property)) {
72
77
  if (!dependencies.has(property)) {
73
78
  dependencies.set(property, bindDependency(options.dependencies.get(property), execution));
@@ -88,6 +93,7 @@ function serviceView(target, options, execution) {
88
93
  property === "signal" ||
89
94
  property === "execution" ||
90
95
  property === "featureBus" ||
96
+ property === "boundedContext" ||
91
97
  (typeof property === "string" && options.dependencies.has(property))) {
92
98
  throw new Error(`Execution dependencies and context are read-only: ${String(property)}`);
93
99
  }
@@ -95,8 +101,12 @@ function serviceView(target, options, execution) {
95
101
  },
96
102
  });
97
103
  }
104
+ /** What a run calls on its service: `handle` for an event handler, `execute` for a use case. */
105
+ function entryOf(layer) {
106
+ return layer === "event_handler" ? "handle" : "execute";
107
+ }
98
108
  /**
99
- * One pipeline for every registered Feature and ApplicationService.
109
+ * One pipeline for every registered Feature, ApplicationService and event handler.
100
110
  *
101
111
  * 1. A span `<bounded context>/<Service>`, a child of the run above it when there is one (its
102
112
  * parent, or the caller from outside), and the execution every dependency, `this.logger` and
@@ -124,7 +134,12 @@ export async function executeService(target, command, options) {
124
134
  const correlationId = above?.correlationId ?? options.cause?.correlationId ?? id;
125
135
  const causationId = above?.id ?? options.cause?.id;
126
136
  const layer = options.layer;
137
+ // Who is running, on the span as on its lines and its report.
138
+ const release = ports.identity?.release;
139
+ const tenant = tenantOf(context, ports.identity);
127
140
  const attributes = {
141
+ ...(release ? { release } : {}),
142
+ ...(tenant ? { tenant } : {}),
128
143
  "sincpro.use_case": useCase,
129
144
  "sincpro.layer": options.layer,
130
145
  "sincpro.context": options.boundedContext,
@@ -179,6 +194,8 @@ export async function executeService(target, command, options) {
179
194
  traceId: span.traceId,
180
195
  executionId: id,
181
196
  context,
197
+ ...(release ? { release } : {}),
198
+ ...(tenant ? { tenant } : {}),
182
199
  }), undefined);
183
200
  }
184
201
  if (error?.value !== null &&
@@ -193,7 +210,7 @@ export async function executeService(target, command, options) {
193
210
  return outcome;
194
211
  };
195
212
  const view = serviceView(target, options, execution);
196
- const execute = Reflect.get(target, "execute");
213
+ const execute = Reflect.get(target, entryOf(options.layer));
197
214
  const service = (current) => Promise.resolve(Reflect.apply(execute, view, [current]));
198
215
  let answer;
199
216
  try {