@sincpro/client-framework 1.2.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.
Files changed (55) hide show
  1. package/AGENTS.md +57 -27
  2. package/MANIFESTO.md +5 -4
  3. package/README.md +225 -157
  4. package/dist/client/services/propagation.js +4 -3
  5. package/dist/codegen/services/scaffold.d.ts +12 -10
  6. package/dist/codegen/services/scaffold.js +23 -40
  7. package/dist/core/domain/bus.d.ts +5 -3
  8. package/dist/core/domain/bus.js +8 -1
  9. package/dist/core/domain/consumers.d.ts +19 -0
  10. package/dist/core/domain/consumers.js +1 -0
  11. package/dist/core/domain/dto.d.ts +68 -6
  12. package/dist/core/domain/dto.js +22 -2
  13. package/dist/core/domain/pipeline.d.ts +7 -3
  14. package/dist/core/domain/services.d.ts +97 -14
  15. package/dist/core/domain/services.js +65 -6
  16. package/dist/core/entrypoint/bounded-context.d.ts +86 -35
  17. package/dist/core/entrypoint/bounded-context.js +224 -71
  18. package/dist/core/entrypoint/screens.js +0 -5
  19. package/dist/core/index.d.ts +6 -3
  20. package/dist/core/index.js +4 -3
  21. package/dist/core/infrastructure/listeners.d.ts +5 -4
  22. package/dist/core/infrastructure/listeners.js +1 -1
  23. package/dist/core/services/dto-keys.d.ts +44 -0
  24. package/dist/core/services/dto-keys.js +97 -0
  25. package/dist/core/services/event-handlers.d.ts +57 -0
  26. package/dist/core/services/event-handlers.js +114 -0
  27. package/dist/core/services/execution.d.ts +15 -21
  28. package/dist/core/services/execution.js +38 -32
  29. package/dist/core/services/interceptors.d.ts +2 -2
  30. package/dist/core/services/interceptors.js +5 -5
  31. package/dist/core/services/listening.d.ts +6 -8
  32. package/dist/core/services/listening.js +3 -2
  33. package/dist/event_driven/adapters/stored-queue.d.ts +5 -5
  34. package/dist/event_driven/adapters/stored-queue.js +5 -10
  35. package/dist/event_driven/domain/envelope.d.ts +2 -2
  36. package/dist/event_driven/domain/envelope.js +7 -1
  37. package/dist/event_driven/domain/messages.d.ts +34 -0
  38. package/dist/event_driven/domain/messages.js +1 -0
  39. package/dist/event_driven/domain/queue.d.ts +9 -5
  40. package/dist/event_driven/entrypoint/publisher.d.ts +2 -2
  41. package/dist/event_driven/entrypoint/publisher.js +4 -0
  42. package/dist/event_driven/entrypoint/subscriber.d.ts +122 -29
  43. package/dist/event_driven/entrypoint/subscriber.js +277 -33
  44. package/dist/event_driven/index.d.ts +11 -10
  45. package/dist/event_driven/index.js +9 -9
  46. package/dist/event_driven/services/messages.d.ts +41 -0
  47. package/dist/event_driven/services/messages.js +147 -0
  48. package/dist/observability/domain/logging.d.ts +4 -8
  49. package/dist/observability/services/logging.d.ts +3 -3
  50. package/dist/observability/services/logging.js +1 -1
  51. package/dist/observability/services/trace-context.d.ts +10 -0
  52. package/dist/observability/services/trace-context.js +29 -0
  53. package/package.json +2 -2
  54. package/dist/event_driven/entrypoint/subscriptions.d.ts +0 -110
  55. package/dist/event_driven/entrypoint/subscriptions.js +0 -184
@@ -63,21 +63,18 @@ class Send extends Command {
63
63
  }
64
64
  }
65
65
  class EntityList extends Feature {
66
- static serviceName = "EntityReads.list";
67
66
  execute(dto) {
68
67
  this.span.set({ "http.route": dto.route });
69
68
  return this.transport.list(dto.route, dto.criteria, dto.signal, dto.options);
70
69
  }
71
70
  }
72
71
  class EntityGet extends Feature {
73
- static serviceName = "EntityReads.one";
74
72
  execute(dto) {
75
73
  this.span.set({ "http.route": dto.route });
76
74
  return this.transport.one(dto.route, dto.signal, dto.options);
77
75
  }
78
76
  }
79
77
  class EntityRead extends Feature {
80
- static serviceName = "EntityReads.read";
81
78
  execute(dto) {
82
79
  this.span.set({ "http.route": dto.route });
83
80
  const transport = this.transport;
@@ -88,7 +85,6 @@ class EntityRead extends Feature {
88
85
  }
89
86
  }
90
87
  class EntityExport extends Feature {
91
- static serviceName = "EntityReads.download";
92
88
  execute(dto) {
93
89
  this.span.set({ "http.route": dto.route });
94
90
  const transport = this.transport;
@@ -99,7 +95,6 @@ class EntityExport extends Feature {
99
95
  }
100
96
  }
101
97
  class EntitySend extends Feature {
102
- static serviceName = "EntityWrites.send";
103
98
  execute(dto) {
104
99
  this.span.set({ "http.method": dto.method, "http.route": dto.route });
105
100
  return this.transport.send(dto.method, dto.route, dto.body, dto.signal, dto.options);
@@ -3,17 +3,20 @@
3
3
  * Responses, Features and ApplicationServices, a bounded context that is their bus, its error
4
4
  * handlers — and the process they run in.
5
5
  *
6
- * domain/ DTOs, the bus, the service bases, the error-handler contract
6
+ * domain/ DTOs (classes, and generated ones the bus recognizes), the bus, the service
7
+ * bases (`servicesWith`: typed with a context's dependencies), the error handlers
7
8
  * services/ the execution pipeline, dependency binding, the handler chain
8
9
  * entrypoint/ `BoundedContext`, `screensTransport`
9
10
  * infrastructure/ `configureProcess`, `configureLogger`
10
11
  */
11
12
  export { type CommandBus, FeatureBus } from "./domain/bus.js";
12
- export { Command, DataTransferObject, DomainEvent, type EventClass, Response, } from "./domain/dto.js";
13
+ export type { EventConsumer, EventKey, } from "./domain/consumers.js";
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";
13
15
  export type { ErrorClass, ErrorHandler } from "./domain/errors.js";
14
16
  export type { CallNext, Cause, ExecuteOptions, ExecutionCompleted, ExecutionFailed, ExecutionStarted, Extension, InterceptedRun, Interceptor, Listener, PipelineLayer, } from "./domain/pipeline.js";
15
- export { ApplicationService, Feature } 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";
16
18
  export { BoundedContext, type Registrar, type RegistrationOptions, } from "./entrypoint/bounded-context.js";
17
19
  export { screensTransport } from "./entrypoint/screens.js";
18
20
  export { processListeners } from "./infrastructure/listeners.js";
19
21
  export { configureLogger, configureProcess, type LoggerConfiguration, type ProcessOptions, } from "./infrastructure/process.js";
22
+ export type { HandlerRegistrar } from "./services/event-handlers.js";
@@ -3,14 +3,15 @@
3
3
  * Responses, Features and ApplicationServices, a bounded context that is their bus, its error
4
4
  * handlers — and the process they run in.
5
5
  *
6
- * domain/ DTOs, the bus, the service bases, the error-handler contract
6
+ * domain/ DTOs (classes, and generated ones the bus recognizes), the bus, the service
7
+ * bases (`servicesWith`: typed with a context's dependencies), the error handlers
7
8
  * services/ the execution pipeline, dependency binding, the handler chain
8
9
  * entrypoint/ `BoundedContext`, `screensTransport`
9
10
  * infrastructure/ `configureProcess`, `configureLogger`
10
11
  */
11
12
  export { FeatureBus } from "./domain/bus.js";
12
- export { Command, DataTransferObject, DomainEvent, Response, } from "./domain/dto.js";
13
- export { ApplicationService, Feature } from "./domain/services.js";
13
+ export { Command, COMMAND_IDENTITY, commandOf, DataTransferObject, DomainEvent, Response, } from "./domain/dto.js";
14
+ export { ApplicationService, EventHandler, Feature, handlersWith, servicesWith, } from "./domain/services.js";
14
15
  export { BoundedContext, } from "./entrypoint/bounded-context.js";
15
16
  export { screensTransport } from "./entrypoint/screens.js";
16
17
  export { processListeners } from "./infrastructure/listeners.js";
@@ -1,5 +1,6 @@
1
+ import type { DtoKey } from "../domain/dto.js";
1
2
  import type { ExecutionCompleted, ExecutionFailed, ExecutionStarted, Listener } from "../domain/pipeline.js";
2
- import { type ExecutableClass, type Hearing } from "../services/listening.js";
3
+ import { type Hearing } from "../services/listening.js";
3
4
  /**
4
5
  * Who hears every bounded context of this process — the backend's process listeners: an
5
6
  * activity indicator, a toast, an audit that must not be wired into each context.
@@ -19,10 +20,10 @@ declare const hearing: {
19
20
  export declare function processHearing(): typeof hearing;
20
21
  export declare const processListeners: {
21
22
  /** Hears every run of every bounded context begin. Answers how to stop. */
22
- onStart(listener: Listener<ExecutionStarted>, ...dtos: ExecutableClass[]): () => void;
23
+ onStart(listener: Listener<ExecutionStarted>, ...dtos: DtoKey[]): () => void;
23
24
  /** Hears every service that answered, in every bounded context. */
24
- onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: ExecutableClass[]): () => void;
25
+ onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: DtoKey[]): () => void;
25
26
  /** Hears every failure that escapes a call, once, where it failed. */
26
- onFailure(listener: Listener<ExecutionFailed>, ...dtos: ExecutableClass[]): () => void;
27
+ onFailure(listener: Listener<ExecutionFailed>, ...dtos: DtoKey[]): () => void;
27
28
  };
28
29
  export {};
@@ -1,4 +1,4 @@
1
- import { listenIn, } from "../services/listening.js";
1
+ import { listenIn } from "../services/listening.js";
2
2
  /**
3
3
  * Who hears every bounded context of this process — the backend's process listeners: an
4
4
  * activity indicator, a toast, an audit that must not be wired into each context.
@@ -0,0 +1,44 @@
1
+ import { type AnyCommand, type CommandClass, type CommandDescriptor, DomainEvent, type DtoKey, type EventClass, type EventDescriptor, type Executable } from "../domain/dto.js";
2
+ /** How a DTO travels: a Command to one bus, by its identity; an event to N, by its wire name. */
3
+ export type DtoKind = "command" | "event";
4
+ /** What a DTO is known by: its kind, its class when it has one, and its wire identity when it has one. */
5
+ export type DtoIdentity = {
6
+ readonly kind: DtoKind;
7
+ /** The class it is an instance of; `undefined` for a generated DTO, which is data. */
8
+ readonly type: (abstract new (...args: never[]) => object) | undefined;
9
+ /** A Command's identity (`<context>.<Command>`), an event's wire name; `undefined` when none is declared. */
10
+ readonly wire: string | undefined;
11
+ };
12
+ export declare function isEventClass(key: unknown): key is EventClass<DomainEvent>;
13
+ export declare function isCommandClass(key: unknown): key is CommandClass<AnyCommand>;
14
+ export declare function isCommandDescriptor(key: unknown): key is CommandDescriptor;
15
+ export declare function isEventDescriptor(key: unknown): key is EventDescriptor;
16
+ /** Whether `key` is something a service can be registered for. */
17
+ export declare function isDtoKey(key: unknown): key is DtoKey;
18
+ /**
19
+ * What a registration key names:
20
+ *
21
+ * keyIdentity(CommandIssueInvoice) -> { kind: "command", type: CommandIssueInvoice, wire: "billing.CommandIssueInvoice" }
22
+ * keyIdentity(OrderPaid) -> { kind: "event", type: OrderPaid, wire: "shop.order.v1.paid" }
23
+ * keyIdentity(operations.CommandSendIssue) -> { kind: "command", type: undefined, wire: "project.CommandSendIssue" }
24
+ * keyIdentity(events.IssueClosed) -> { kind: "event", type: undefined, wire: "project.issue.v1.closed" }
25
+ */
26
+ export declare function keyIdentity(key: DtoKey): DtoIdentity;
27
+ /**
28
+ * What a value being executed is:
29
+ *
30
+ * 1. An instance of a Command or a domain event: its class, and the identity the class declares.
31
+ * 2. A generated Command (`commandOf`): the identity it carries.
32
+ * 3. A generated event: the wire name in its data.
33
+ * Final: `undefined` for anything else — nothing a bus executes.
34
+ */
35
+ export declare function identityOf(executable: unknown): DtoIdentity | undefined;
36
+ /**
37
+ * Whether `key` is what `executable` was registered under: the same class — exactly, a subclass
38
+ * is another DTO — or, for a generated DTO, the same kind and wire identity.
39
+ */
40
+ export declare function matches(key: DtoKey, executable: Executable): boolean;
41
+ /** Whether two values being executed are the same DTO: an interceptor passes on only that. */
42
+ export declare function sameDto(left: unknown, right: unknown): boolean;
43
+ /** A DTO's name for a message: its wire identity, or its class's name. */
44
+ export declare function describeDto(executable: unknown): string;
@@ -0,0 +1,97 @@
1
+ import { Command, COMMAND_IDENTITY, DomainEvent, } from "../domain/dto.js";
2
+ export function isEventClass(key) {
3
+ return typeof key === "function" && key.prototype instanceof DomainEvent;
4
+ }
5
+ export function isCommandClass(key) {
6
+ return typeof key === "function" && key.prototype instanceof Command;
7
+ }
8
+ export function isCommandDescriptor(key) {
9
+ return (key !== null &&
10
+ typeof key === "object" &&
11
+ typeof key.identity === "string");
12
+ }
13
+ export function isEventDescriptor(key) {
14
+ return (key !== null &&
15
+ typeof key === "object" &&
16
+ !isCommandDescriptor(key) &&
17
+ typeof key.name === "string");
18
+ }
19
+ /** Whether `key` is something a service can be registered for. */
20
+ export function isDtoKey(key) {
21
+ return (isCommandClass(key) ||
22
+ isEventClass(key) ||
23
+ isCommandDescriptor(key) ||
24
+ isEventDescriptor(key));
25
+ }
26
+ /**
27
+ * What a registration key names:
28
+ *
29
+ * keyIdentity(CommandIssueInvoice) -> { kind: "command", type: CommandIssueInvoice, wire: "billing.CommandIssueInvoice" }
30
+ * keyIdentity(OrderPaid) -> { kind: "event", type: OrderPaid, wire: "shop.order.v1.paid" }
31
+ * keyIdentity(operations.CommandSendIssue) -> { kind: "command", type: undefined, wire: "project.CommandSendIssue" }
32
+ * keyIdentity(events.IssueClosed) -> { kind: "event", type: undefined, wire: "project.issue.v1.closed" }
33
+ */
34
+ export function keyIdentity(key) {
35
+ if (isEventClass(key))
36
+ return { kind: "event", type: key, wire: key.eventName };
37
+ if (isCommandClass(key))
38
+ return { kind: "command", type: key, wire: key.commandName };
39
+ if (isCommandDescriptor(key))
40
+ return { kind: "command", type: undefined, wire: key.identity };
41
+ return { kind: "event", type: undefined, wire: key.name };
42
+ }
43
+ /**
44
+ * What a value being executed is:
45
+ *
46
+ * 1. An instance of a Command or a domain event: its class, and the identity the class declares.
47
+ * 2. A generated Command (`commandOf`): the identity it carries.
48
+ * 3. A generated event: the wire name in its data.
49
+ * Final: `undefined` for anything else — nothing a bus executes.
50
+ */
51
+ export function identityOf(executable) {
52
+ if (executable instanceof DomainEvent) {
53
+ const type = Object.getPrototypeOf(executable)?.constructor;
54
+ return { kind: "event", type, wire: executable.name || undefined };
55
+ }
56
+ if (executable instanceof Command) {
57
+ const type = Object.getPrototypeOf(executable)?.constructor;
58
+ return { kind: "command", type, wire: type.commandName };
59
+ }
60
+ if (executable === null || typeof executable !== "object")
61
+ return undefined;
62
+ const carried = executable[COMMAND_IDENTITY];
63
+ if (typeof carried === "string")
64
+ return { kind: "command", type: undefined, wire: carried };
65
+ const name = executable.name;
66
+ if (typeof name === "string" && name !== "")
67
+ return { kind: "event", type: undefined, wire: name };
68
+ return undefined;
69
+ }
70
+ /**
71
+ * Whether `key` is what `executable` was registered under: the same class — exactly, a subclass
72
+ * is another DTO — or, for a generated DTO, the same kind and wire identity.
73
+ */
74
+ export function matches(key, executable) {
75
+ const known = identityOf(executable);
76
+ if (known === undefined)
77
+ return false;
78
+ const wanted = keyIdentity(key);
79
+ if (wanted.type !== undefined)
80
+ return known.type === wanted.type;
81
+ return known.type === undefined && known.kind === wanted.kind && known.wire === wanted.wire;
82
+ }
83
+ /** Whether two values being executed are the same DTO: an interceptor passes on only that. */
84
+ export function sameDto(left, right) {
85
+ const one = identityOf(left);
86
+ const other = identityOf(right);
87
+ if (one === undefined || other === undefined)
88
+ return false;
89
+ if (one.type !== undefined || other.type !== undefined)
90
+ return one.type === other.type;
91
+ return one.kind === other.kind && one.wire === other.wire;
92
+ }
93
+ /** A DTO's name for a message: its wire identity, or its class's name. */
94
+ export function describeDto(executable) {
95
+ const known = identityOf(executable);
96
+ return known?.wire ?? known?.type?.name ?? typeof executable;
97
+ }
@@ -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
+ }
@@ -4,12 +4,7 @@ import type { Executable } from "../domain/dto.js";
4
4
  import type { ErrorHandler } from "../domain/errors.js";
5
5
  import type { Cause, ExecutionCompleted, ExecutionStarted, Interceptor, PipelineLayer } from "../domain/pipeline.js";
6
6
  import { type Attributes, type Outcome } from "../../observability/domain/tracing.js";
7
- /**
8
- * Where a run sits: a use case's layer (`PipelineLayer`), or an entrypoint that calls use cases —
9
- * an `EventSubscriber`. Interceptors wrap and listeners hear use cases only.
10
- */
11
- export type RunLayer = PipelineLayer | "entrypoint";
12
- type Layer = RunLayer;
7
+ type Layer = PipelineLayer;
13
8
  /** Where a failure first happened: the run, its executable, its layer and how it ended. */
14
9
  export type FailedAt = {
15
10
  readonly execution: Execution;
@@ -25,20 +20,17 @@ export interface Announcer {
25
20
  completed(heard: ExecutionCompleted): void;
26
21
  }
27
22
  export interface ExecutionOptions {
28
- /** Its bounded context — or, for an entrypoint's run, the registry it belongs to. */
29
23
  readonly boundedContext: string;
30
24
  readonly name: string;
31
25
  readonly layer: Layer;
32
- /** The method that runs it: a use case's `execute`, an entrypoint's `handle`. */
33
- readonly method?: "execute" | "handle";
34
26
  /** What else its span says: the event it executes, the service it replaced. */
35
27
  readonly attributes?: Attributes;
36
28
  readonly dependencies: ReadonlyMap<string, unknown>;
37
29
  readonly context: () => ContextValues;
38
30
  readonly parent?: Execution;
39
31
  /**
40
- * The run that called this root from outside its bounded context — an `EventSubscriber`, a
41
- * Feature of another bounded context — through a bounded context bound to it (`BIND`): its span
32
+ * The run that called this root from outside its bounded context — a Feature of another
33
+ * bounded context — through a bounded context bound to it (`BIND`): its span
42
34
  * is the parent, its flow continues, it is the cause and its signal cancels this one; the
43
35
  * context, dependencies and handlers stay this bounded context's.
44
36
  */
@@ -47,28 +39,30 @@ export interface ExecutionOptions {
47
39
  readonly cause?: Cause;
48
40
  /** What cancels a root run; a child inherits its parent's. */
49
41
  readonly signal?: AbortSignal;
50
- /** An ApplicationService's Features; no other layer has them. */
51
- readonly featureBus?: (execution: Execution) => object;
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;
52
48
  /** What runs around the service, outermost first. */
53
49
  readonly interceptors: readonly Interceptor[];
54
- /** Who hears a use case start and answer; an entrypoint's run is not announced. */
55
- readonly announce?: Announcer;
50
+ /** Who hears it start and answer. */
51
+ readonly announce: Announcer;
56
52
  /** The bounded context's expected errors: they end `refused`, never reported. */
57
53
  readonly expected: (error: unknown) => boolean;
58
54
  /** The bounded context's handlers for this layer: what answers a failure instead of raising it. */
59
55
  readonly handlers: readonly ErrorHandler[];
60
56
  }
61
57
  /**
62
- * One pipeline for every registered Feature and ApplicationService — and for every entrypoint's
63
- * run that calls them (an `EventSubscriber`).
58
+ * One pipeline for every registered Feature, ApplicationService and event handler.
64
59
  *
65
- * 1. A span `<bounded context>/<serviceName>`, a child of the run above it when there is one (its
60
+ * 1. A span `<bounded context>/<Service>`, a child of the run above it when there is one (its
66
61
  * parent, or the caller from outside), and the execution every dependency, `this.logger` and
67
62
  * child Feature are bound to. Its chain: the run above's correlation (or the cause's, or its
68
63
  * own id for a root), caused by the run above or the delivered event.
69
- * 2. A use case's start is announced; the interceptors run around the service, which sees the
70
- * execution through its own view of the instance. An entrypoint's run is neither announced
71
- * nor intercepted.
64
+ * 2. Its start is announced; the interceptors run around the service, which sees the
65
+ * execution through its own view of the instance.
72
66
  * 3. A failure is observed where it happened: its outcome (expected by the bounded context →
73
67
  * `refused`; else the outcome it already had where it first failed — another bounded
74
68
  * context's rules —; else the process's `outcomeOf`), the span closed with it, its log line,
@@ -6,6 +6,7 @@ import { NO_TRACER, } from "../../observability/domain/tracing.js";
6
6
  import { observabilityNow } from "../../observability/infrastructure/registry.js";
7
7
  import { executionLogger, logExecution, logHandled, } from "../../observability/services/logging.js";
8
8
  import { firstReport } from "../../observability/services/reporting.js";
9
+ import { remoteSpan } from "../../observability/services/trace-context.js";
9
10
  const FAILED_AT = new WeakMap();
10
11
  /** Where `error` first failed, when it is an object a run threw; `undefined` otherwise. */
11
12
  export function failedAt(error) {
@@ -52,6 +53,7 @@ function serviceView(target, options, execution) {
52
53
  const dependencies = new Map();
53
54
  const logger = executionLogger(options.layer, execution);
54
55
  let features;
56
+ let own;
55
57
  return new Proxy(target, {
56
58
  get(held, property, receiver) {
57
59
  if (property === "context")
@@ -64,11 +66,12 @@ function serviceView(target, options, execution) {
64
66
  return execution.signal;
65
67
  if (property === "execution")
66
68
  return execution;
67
- if (property === "featureBus" &&
68
- options.layer === "application_service" &&
69
- options.featureBus) {
69
+ if (property === "featureBus" && options.layer === "application_service") {
70
70
  return (features ??= options.featureBus(execution));
71
71
  }
72
+ if (property === "boundedContext" && options.boundedContextOf) {
73
+ return (own ??= options.boundedContextOf(execution));
74
+ }
72
75
  if (typeof property === "string" && options.dependencies.has(property)) {
73
76
  if (!dependencies.has(property)) {
74
77
  dependencies.set(property, bindDependency(options.dependencies.get(property), execution));
@@ -89,6 +92,7 @@ function serviceView(target, options, execution) {
89
92
  property === "signal" ||
90
93
  property === "execution" ||
91
94
  property === "featureBus" ||
95
+ property === "boundedContext" ||
92
96
  (typeof property === "string" && options.dependencies.has(property))) {
93
97
  throw new Error(`Execution dependencies and context are read-only: ${String(property)}`);
94
98
  }
@@ -96,17 +100,19 @@ function serviceView(target, options, execution) {
96
100
  },
97
101
  });
98
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
+ }
99
107
  /**
100
- * One pipeline for every registered Feature and ApplicationService — and for every entrypoint's
101
- * run that calls them (an `EventSubscriber`).
108
+ * One pipeline for every registered Feature, ApplicationService and event handler.
102
109
  *
103
- * 1. A span `<bounded context>/<serviceName>`, a child of the run above it when there is one (its
110
+ * 1. A span `<bounded context>/<Service>`, a child of the run above it when there is one (its
104
111
  * parent, or the caller from outside), and the execution every dependency, `this.logger` and
105
112
  * child Feature are bound to. Its chain: the run above's correlation (or the cause's, or its
106
113
  * own id for a root), caused by the run above or the delivered event.
107
- * 2. A use case's start is announced; the interceptors run around the service, which sees the
108
- * execution through its own view of the instance. An entrypoint's run is neither announced
109
- * nor intercepted.
114
+ * 2. Its start is announced; the interceptors run around the service, which sees the
115
+ * execution through its own view of the instance.
110
116
  * 3. A failure is observed where it happened: its outcome (expected by the bounded context →
111
117
  * `refused`; else the outcome it already had where it first failed — another bounded
112
118
  * context's rules —; else the process's `outcomeOf`), the span closed with it, its log line,
@@ -127,7 +133,6 @@ export async function executeService(target, command, options) {
127
133
  const correlationId = above?.correlationId ?? options.cause?.correlationId ?? id;
128
134
  const causationId = above?.id ?? options.cause?.id;
129
135
  const layer = options.layer;
130
- const useCaseLayer = layer === "entrypoint" ? undefined : layer;
131
136
  const attributes = {
132
137
  "sincpro.use_case": useCase,
133
138
  "sincpro.layer": options.layer,
@@ -137,8 +142,13 @@ export async function executeService(target, command, options) {
137
142
  ...(causationId ? { "sincpro.causation_id": causationId } : {}),
138
143
  ...options.attributes,
139
144
  };
145
+ // A delivered message from another process continues its trace: its span is the parent.
146
+ const parentSpan = above?.span ??
147
+ (options.cause?.traceparent
148
+ ? remoteSpan(options.cause.traceparent, options.cause.tracestate)
149
+ : undefined);
140
150
  const span = observe(() => ports.tracer.start(`${options.boundedContext}/${options.name}`, {
141
- ...(above ? { parent: above.span } : {}),
151
+ ...(parentSpan ? { parent: parentSpan } : {}),
142
152
  attributes,
143
153
  }), NO_TRACER.start(useCase, {}));
144
154
  const execution = {
@@ -157,8 +167,7 @@ export async function executeService(target, command, options) {
157
167
  : new Set();
158
168
  REPORTED_BY_EXECUTION.set(execution, reported);
159
169
  logExecution(layer, execution);
160
- if (useCaseLayer)
161
- observe(() => options.announce?.started({ executable: command, execution, layer: useCaseLayer }), undefined);
170
+ observe(() => options.announce.started({ executable: command, execution, layer }), undefined);
162
171
  const finish = (error) => {
163
172
  const outcome = error
164
173
  ? observe(() => options.expected(error.value)
@@ -193,22 +202,20 @@ export async function executeService(target, command, options) {
193
202
  return outcome;
194
203
  };
195
204
  const view = serviceView(target, options, execution);
196
- const method = Reflect.get(target, options.method ?? "execute");
197
- const service = (current) => Promise.resolve(Reflect.apply(method, view, [current]));
205
+ const execute = Reflect.get(target, entryOf(options.layer));
206
+ const service = (current) => Promise.resolve(Reflect.apply(execute, view, [current]));
198
207
  let answer;
199
208
  try {
200
209
  const signal = execution.signal;
201
210
  if (signal?.aborted)
202
211
  throw abortedBy(signal);
203
- const running = useCaseLayer
204
- ? runAround(options.interceptors, service, command, {
205
- boundedContext: options.boundedContext,
206
- useCase,
207
- layer: useCaseLayer,
208
- execution,
209
- logger: executionLogger(useCaseLayer, execution),
210
- })
211
- : service(command);
212
+ const running = runAround(options.interceptors, service, command, {
213
+ boundedContext: options.boundedContext,
214
+ useCase,
215
+ layer,
216
+ execution,
217
+ logger: executionLogger(layer, execution),
218
+ });
212
219
  answer = signal === undefined ? await running : await untilAborted(running, signal);
213
220
  }
214
221
  catch (error) {
@@ -220,13 +227,12 @@ export async function executeService(target, command, options) {
220
227
  return recovered;
221
228
  }
222
229
  finish();
223
- if (useCaseLayer)
224
- observe(() => options.announce?.completed({
225
- executable: command,
226
- execution,
227
- layer: useCaseLayer,
228
- answer,
229
- durationMs: Math.max(0, Date.now() - startedAt),
230
- }), undefined);
230
+ observe(() => options.announce.completed({
231
+ executable: command,
232
+ execution,
233
+ layer,
234
+ answer,
235
+ durationMs: Math.max(0, Date.now() - startedAt),
236
+ }), undefined);
231
237
  return answer;
232
238
  }