@sincpro/client-framework 1.5.0 → 1.6.1

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 +28 -4
  2. package/README.md +6 -3
  3. package/dist/client/adapters/json-rpc.js +3 -2
  4. package/dist/client/adapters/memory.js +3 -2
  5. package/dist/client/adapters/rest-operations.js +3 -2
  6. package/dist/client/adapters/rest.js +3 -2
  7. package/dist/client/index.d.ts +1 -1
  8. package/dist/client/index.js +1 -1
  9. package/dist/client/services/guarded.js +4 -3
  10. package/dist/client/services/propagation.d.ts +21 -9
  11. package/dist/client/services/propagation.js +60 -3
  12. package/dist/core/entrypoint/screens.js +2 -1
  13. package/dist/core/infrastructure/process.d.ts +6 -2
  14. package/dist/core/infrastructure/process.js +1 -1
  15. package/dist/core/services/binding.d.ts +5 -2
  16. package/dist/core/services/binding.js +5 -8
  17. package/dist/core/services/execution.js +27 -2
  18. package/dist/observability/adapters/console.d.ts +0 -4
  19. package/dist/observability/adapters/console.js +17 -1
  20. package/dist/observability/adapters/opentelemetry.js +5 -4
  21. package/dist/observability/adapters/sentry.d.ts +3 -0
  22. package/dist/observability/adapters/sentry.js +25 -0
  23. package/dist/observability/domain/errors.d.ts +12 -0
  24. package/dist/observability/domain/identity.d.ts +25 -4
  25. package/dist/observability/domain/identity.js +28 -6
  26. package/dist/observability/domain/logging.d.ts +25 -0
  27. package/dist/observability/index.d.ts +3 -2
  28. package/dist/observability/index.js +2 -1
  29. package/dist/observability/services/failure.d.ts +21 -0
  30. package/dist/observability/services/failure.js +73 -0
  31. package/dist/observability/services/logging.d.ts +2 -1
  32. package/dist/observability/services/logging.js +19 -10
  33. package/dist/observability/services/reporting.js +16 -3
  34. package/package.json +1 -1
package/AGENTS.md CHANGED
@@ -158,9 +158,19 @@ module has only the layers it needs, and says what it offers in its own `index.t
158
158
  - **Decorators are optional.** Function registration must work without any decorator
159
159
  transform. Standard and legacy (`experimentalDecorators`) fixtures are compiled explicitly in
160
160
  tests; do not claim Metro (Babel) or web bundler support without testing those configurations.
161
+ - **A run binds what says it can be bound, never what looks like a transport.** A dependency is
162
+ bound only when it carries `BIND`: a generated client, `restOperations`, `jsonRpcOperations`,
163
+ `restTransport`, `memoryTransport`, `guardedTransport`, `screensTransport`, and what a
164
+ platform marks with `bindableOperations(…)` / `bindableTransport(…)`. Nothing else — not an
165
+ object with `list`/`one`/`send`, not one with a `call` — is ever wrapped: an application's
166
+ abstraction reaches its use cases as it is.
167
+ An object is never taken for an `OperationTransport` because it has a `call`: an Odoo client's
168
+ is `call(service, method, args)`, and binding it hid `setServer` and rewrote its `args` — only
169
+ with a trace to carry, so never in a test without a tracer. Binding wraps only the wire's
170
+ methods; the dependency's state, methods and getters stay its own (`keeping`).
161
171
  - **The trace reaches the wire through the dependencies.** A dependency is bound to the run when it
162
- is a `Transport` or carries `BIND` (every generated client does, through `bindable`); anything
163
- else is handed as it is. A client built elsewhere and closed over sends no trace.
172
+ carries `BIND` (every generated client does, through `bindable`; the framework's transports do);
173
+ anything else is handed as it is. A client built elsewhere and closed over sends no trace.
164
174
  - **The process is read on every call, never at import.** `project` is defined when its module
165
175
  loads, before `main` runs `configureProcess`; nothing may capture the tracer, the reporter or the
166
176
  store at definition time. `configureProcess` replaces everything at once — a test calls it in
@@ -204,8 +214,22 @@ options)`: no route, no verb, no RPC method. The contract's bindings (`rest`, `r
204
214
  `loggerAdapter` are predefined; injected as a dependency they bind to the run (`BIND`), imported
205
215
  at module level they do not. No logger is predefined for an application layer. Console is the
206
216
  default engine; `configureProcess({ logger })` and `configureLogger(...)` take the same
207
- `LoggerConfiguration`. The host chooses production explicitly. Never log DTOs, results, full
208
- session context or raw errors automatically.
217
+ `LoggerConfiguration`. The host chooses production explicitly. Never log DTOs, results or the
218
+ full session context automatically.
219
+ - **A failure is described once, as sincpro_framework's failure line** (`PRD_03 §6`,
220
+ `observability/failure.py`). The run where it was raised writes its type, kind, fault and —
221
+ when nobody expected it — its message, the use case's own line (`at`) and its stack; a run it
222
+ crosses says only `failedIn`. Its span records the exception; the spans it crosses take the
223
+ error status. An expected failure is information: type and kind, never its message (it may
224
+ carry the caller's data) nor a stack. `sincpro.outcome` is `ok` or the failure's kind, beside
225
+ `sincpro.fault` and `error.type`, on the span and in GlitchTip.
226
+ - **Who is running is on every signal** (`configureProcess({ identity })`, `PRD_03 §4.10`):
227
+ `release`, the run's `tenant` and `user_id`. Tenant and user are optional, and so are their
228
+ keys — `identity.keys` names the context keys an application uses (`company_id`, `tenant_ids`);
229
+ nothing is sent when its context says none. Nothing else of the context is copied.
230
+ - **Observability never fails a use case.** Every tracer, logger and reporter call is shielded:
231
+ a collector down, Loki unreachable or no network leave the run's own answer — or its own error —
232
+ untouched.
209
233
 
210
234
  - **Only what is transversal comes here.** A value's wire form (a decimal as text, a day never
211
235
  an instant, a money with its currency) is the backend's contract, the same on every platform,
package/README.md CHANGED
@@ -506,9 +506,12 @@ are its children, on the same trace. Each span, log record and report says who w
506
506
  sincpro_framework's keys: `release` (`<name>:<version>`, the backend's `APP_RELEASE`) and, when
507
507
  there is one, `tenant` — the run's context's, else the deployment's. `processIdentity()` gives
508
508
  `release`, `serviceName` and `serviceVersion` (read out of the release with the backend's rules)
509
- to a platform's tracer resource and log labels; nothing else of the context is copied. A dependency that is a `Transport` or a generated client is
510
- bound to the run, so each request carries `traceparent` (and `tracestate`) and
511
- `sincpro-context` — the backend continues the trace. A tracer, reporter or logger that fails is
509
+ to a platform's tracer resource and log labels; nothing else of the context is copied. A dependency that says it can be bound — a generated
510
+ client, or one of the framework's transports (`restTransport`, `restOperations`,
511
+ `jsonRpcOperations`, `guardedTransport`; `bindableTransport`/`bindableOperations` for a
512
+ platform's own) — is bound to the run, so each request carries `traceparent` (and `tracestate`)
513
+ and `sincpro-context` — the backend continues the trace. Nothing is guessed from a method's
514
+ name: an application's own object (an Odoo client with a `call`) reaches its use cases as it is. A tracer, reporter or logger that fails is
512
515
  ignored: telling about a use case never changes its answer.
513
516
 
514
517
  The vendor entries wrap what the application built — they initialize nothing, read no
@@ -1,4 +1,5 @@
1
1
  import { OperationNotPublished, } from "../domain/operation.js";
2
+ import { bindableOperations } from "../services/propagation.js";
2
3
  import { kindOfJsonRpcCode } from "../../common/failures.js";
3
4
  import { readProblem } from "@sincpro/criteria";
4
5
  /**
@@ -49,7 +50,7 @@ let next = 0;
49
50
  export function jsonRpcOperations(options) {
50
51
  const send = options.fetch ?? ((...args) => fetch(...args));
51
52
  const own = () => typeof options.headers === "function" ? options.headers() : options.headers;
52
- return {
53
+ return bindableOperations({
53
54
  async call(operation, input, call = {}) {
54
55
  const method = operation.rpc?.method;
55
56
  if (method === undefined)
@@ -93,5 +94,5 @@ export function jsonRpcOperations(options) {
93
94
  }
94
95
  return answer.result;
95
96
  },
96
- };
97
+ });
97
98
  }
@@ -1,4 +1,5 @@
1
1
  import { TransportError, } from "../domain/transport.js";
2
+ import { bindableTransport } from "../services/propagation.js";
2
3
  import { pack, readValues } from "../../common/serialization.js";
3
4
  import { answer, answerGroups } from "@sincpro/criteria/engine";
4
5
  /**
@@ -44,7 +45,7 @@ export function memoryTransport(tables, options = {}) {
44
45
  });
45
46
  return table;
46
47
  }
47
- return {
48
+ return bindableTransport({
48
49
  async list(route, criteria, signal) {
49
50
  options.observe?.(route, criteria);
50
51
  await check(route, signal);
@@ -116,5 +117,5 @@ export function memoryTransport(tables, options = {}) {
116
117
  return copyOf(await options.read(route));
117
118
  },
118
119
  }),
119
- };
120
+ });
120
121
  }
@@ -1,5 +1,6 @@
1
1
  import { OperationNotPublished, } from "../domain/operation.js";
2
2
  import { downloadRoute, readRoute, } from "../domain/transport.js";
3
+ import { bindableOperations } from "../services/propagation.js";
3
4
  const PATH_KEY = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
4
5
  /** What a value is in a query string: text as it is, anything else as JSON (`criteria`). */
5
6
  function queryValue(value) {
@@ -41,7 +42,7 @@ function withQuery(route, fields) {
41
42
  * Final: the operation's answer, as the contract describes it.
42
43
  */
43
44
  export function restOperations(transport) {
44
- return {
45
+ return bindableOperations({
45
46
  call(operation, input, options = {}) {
46
47
  const rest = operation.rest;
47
48
  if (rest === undefined)
@@ -62,5 +63,5 @@ export function restOperations(transport) {
62
63
  return Promise.reject(error);
63
64
  }
64
65
  },
65
- };
66
+ });
66
67
  }
@@ -1,5 +1,6 @@
1
1
  import { TransportError, } from "../domain/transport.js";
2
2
  import { definitionOf, modelAt, } from "../services/discovery.js";
3
+ import { bindableTransport } from "../services/propagation.js";
3
4
  import { readProblem } from "@sincpro/criteria";
4
5
  import { RestError, restSource } from "@sincpro/criteria/rest";
5
6
  /** The keys of an answer that are not the record: what is left is the record's own field. */
@@ -130,7 +131,7 @@ export function restTransport(options = {}) {
130
131
  throw new TransportError(route, response.status, readProblem(text), undefined);
131
132
  return text ? JSON.parse(text) : null;
132
133
  }
133
- return {
134
+ return bindableTransport({
134
135
  async list(route, criteria, signal, call) {
135
136
  const source = restSource(`${base}${route}`, {
136
137
  // Only a page may come in another format: the decoders are said here, and nowhere else.
@@ -184,5 +185,5 @@ export function restTransport(options = {}) {
184
185
  async send(method, route, body, signal, sending) {
185
186
  return (await get(route, urlOf(base, route), signal, { method, body, key: sending?.idempotencyKey }, sending));
186
187
  },
187
- };
188
+ });
188
189
  }
@@ -16,5 +16,5 @@ export { bodyFor, type CommandAnswers, type CommandBodies, type CommandRoute, ty
16
16
  export { OperationNotPublished, type OperationOptions, type OperationTransport, type RemoteOperation, } from "./domain/operation.js";
17
17
  export { type CallOptions, type Decoder, type Download, downloadRoute, type Draft, type Method, type One, readRoute, type SendOptions, type Transport, TransportError, } from "./domain/transport.js";
18
18
  export { guardedTransport } from "./services/guarded.js";
19
- export { bindable, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
19
+ export { bindable, bindableOperations, bindableTransport, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
20
20
  export { type RetryKeys, retryKeys, unanswered, } from "./services/retry.js";
@@ -16,5 +16,5 @@ export { bodyFor, entity, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM
16
16
  export { OperationNotPublished, } from "./domain/operation.js";
17
17
  export { downloadRoute, readRoute, TransportError, } from "./domain/transport.js";
18
18
  export { guardedTransport } from "./services/guarded.js";
19
- export { bindable, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
19
+ export { bindable, bindableOperations, bindableTransport, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
20
20
  export { retryKeys, unanswered, } from "./services/retry.js";
@@ -1,9 +1,10 @@
1
1
  import { isOperationTransport, } from "../domain/operation.js";
2
+ import { bindableOperations, bindableTransport, } from "./propagation.js";
2
3
  export function guardedTransport(transport, breaker) {
3
4
  if (isOperationTransport(transport))
4
- return {
5
+ return bindableOperations({
5
6
  call: (operation, input, options) => breaker.call(() => transport.call(operation, input, options)),
6
- };
7
+ });
7
8
  const guarded = {
8
9
  list: (route, criteria, signal, options) => breaker.call(() => transport.list(route, criteria, signal, options)),
9
10
  one: (route, signal, options) => breaker.call(() => transport.one(route, signal, options)),
@@ -15,5 +16,5 @@ export function guardedTransport(transport, breaker) {
15
16
  const download = transport.download;
16
17
  if (download !== undefined)
17
18
  guarded.download = (route, signal, options) => breaker.call(() => download.call(transport, route, signal, options));
18
- return guarded;
19
+ return bindableTransport(guarded);
19
20
  }
@@ -9,15 +9,6 @@ export declare function isTransport(value: unknown): value is Transport;
9
9
  * Nothing when there is no trace and no context that travels.
10
10
  */
11
11
  export declare function headersOf(execution: Execution): Record<string, string>;
12
- /**
13
- * The transport, writing the execution's headers on every call — the caller's own headers of a
14
- * call still win.
15
- *
16
- * Context: the transport's own headers (`restTransport({ headers })`) are the session's — the
17
- * token, the tenant — the same for every call; these are the use case's, different for two use
18
- * cases running at once, so they travel per call (`CallOptions`). A call that gives no signal of
19
- * its own is cancelled with the run.
20
- */
21
12
  export declare function bindTransport(transport: Transport, execution: Execution): Transport;
22
13
  /**
23
14
  * The operation transport, calling as `execution`: every call carries the run's trace and
@@ -25,6 +16,27 @@ export declare function bindTransport(transport: Transport, execution: Execution
25
16
  * win.
26
17
  */
27
18
  export declare function bindOperations(transport: OperationTransport, execution: Execution): OperationTransport;
19
+ /**
20
+ * A REST `Transport` a run binds to itself when it is a dependency: its requests carry the run's
21
+ * trace, context and signal. `restTransport`, `memoryTransport`, `guardedTransport` and
22
+ * `screensTransport` answer one; a platform's own marks itself with it.
23
+ *
24
+ * Context: a run binds only what says it can be bound — never an object because it has `list`,
25
+ * `one` and `send`: an application's own object with those names is the application's.
26
+ */
27
+ export declare function bindableTransport<T extends Transport>(transport: T): T;
28
+ /**
29
+ * An `OperationTransport` a run binds to itself when it is a dependency: its `call` carries the
30
+ * run's trace, context and signal. `restOperations`, `jsonRpcOperations` and `guardedTransport`
31
+ * answer one; a platform's own (gRPC) marks itself with it.
32
+ *
33
+ * boundedContext.addDependency("operations", bindableOperations(grpcOperations(channel)));
34
+ *
35
+ * Context: an object is not taken for a transport because it has a `call` — an Odoo client's is
36
+ * `call(service, method, args)`, and binding it rewrote its arguments and hid its other methods.
37
+ * A run binds what says it can be bound (`BIND`) and a REST `Transport`; nothing else.
38
+ */
39
+ export declare function bindableOperations<T extends OperationTransport>(transport: T): T;
28
40
  /** A transport of either kind, bound to `execution`. */
29
41
  export declare function bound<W extends Transport | OperationTransport>(wire: W, execution: Execution): W;
30
42
  /**
@@ -39,6 +39,28 @@ export function headersOf(execution) {
39
39
  * cases running at once, so they travel per call (`CallOptions`). A call that gives no signal of
40
40
  * its own is cancelled with the run.
41
41
  */
42
+ /**
43
+ * The dependency as it is — its state, its own methods, its getters —, with only its wire's
44
+ * methods carrying the run. Binding a transport never takes away what the dependency is: an
45
+ * Odoo client that happens to have a `call` is still the Odoo client, and `setServer` still sets
46
+ * the server of the one the app holds.
47
+ *
48
+ * Context: it used to answer a new object with only the wire's methods, and only when the run had
49
+ * something to carry (a trace, a context, a signal): with tracing on, every other method vanished
50
+ * — `this.odoo.setServer is not a function` on a phone, never in a test without a tracer.
51
+ */
52
+ function keeping(original, wire) {
53
+ return new Proxy(original, {
54
+ get(target, property) {
55
+ if (Object.hasOwn(wire, property))
56
+ return wire[property];
57
+ const value = Reflect.get(target, property, target);
58
+ return typeof value === "function" ? value.bind(target) : value;
59
+ },
60
+ set: (target, property, value) => Reflect.set(target, property, value, target),
61
+ has: (target, property) => Object.hasOwn(wire, property) || property in target,
62
+ });
63
+ }
42
64
  export function bindTransport(transport, execution) {
43
65
  const own = headersOf(execution);
44
66
  const cancels = execution.signal;
@@ -56,7 +78,7 @@ export function bindTransport(transport, execution) {
56
78
  const download = transport.download;
57
79
  if (download !== undefined)
58
80
  bound.download = (route, signal, options) => download.call(transport, route, signal ?? cancels, call(options));
59
- return bound;
81
+ return keeping(transport, bound);
60
82
  }
61
83
  /**
62
84
  * The operation transport, calling as `execution`: every call carries the run's trace and
@@ -68,13 +90,48 @@ export function bindOperations(transport, execution) {
68
90
  const cancels = execution.signal;
69
91
  if (Object.keys(own).length === 0 && cancels === undefined)
70
92
  return transport;
71
- return {
93
+ return keeping(transport, {
72
94
  call: (operation, input, options) => transport.call(operation, input, {
73
95
  ...options,
74
96
  headers: { ...own, ...options?.headers },
75
97
  ...((options?.signal ?? cancels) ? { signal: options?.signal ?? cancels } : {}),
76
98
  }),
77
- };
99
+ });
100
+ }
101
+ /**
102
+ * A REST `Transport` a run binds to itself when it is a dependency: its requests carry the run's
103
+ * trace, context and signal. `restTransport`, `memoryTransport`, `guardedTransport` and
104
+ * `screensTransport` answer one; a platform's own marks itself with it.
105
+ *
106
+ * Context: a run binds only what says it can be bound — never an object because it has `list`,
107
+ * `one` and `send`: an application's own object with those names is the application's.
108
+ */
109
+ export function bindableTransport(transport) {
110
+ Object.defineProperty(transport, BIND, {
111
+ value: (execution) => bindTransport(transport, execution),
112
+ enumerable: false,
113
+ configurable: true,
114
+ });
115
+ return transport;
116
+ }
117
+ /**
118
+ * An `OperationTransport` a run binds to itself when it is a dependency: its `call` carries the
119
+ * run's trace, context and signal. `restOperations`, `jsonRpcOperations` and `guardedTransport`
120
+ * answer one; a platform's own (gRPC) marks itself with it.
121
+ *
122
+ * boundedContext.addDependency("operations", bindableOperations(grpcOperations(channel)));
123
+ *
124
+ * Context: an object is not taken for a transport because it has a `call` — an Odoo client's is
125
+ * `call(service, method, args)`, and binding it rewrote its arguments and hid its other methods.
126
+ * A run binds what says it can be bound (`BIND`) and a REST `Transport`; nothing else.
127
+ */
128
+ export function bindableOperations(transport) {
129
+ Object.defineProperty(transport, BIND, {
130
+ value: (execution) => bindOperations(transport, execution),
131
+ enumerable: false,
132
+ configurable: true,
133
+ });
134
+ return transport;
78
135
  }
79
136
  /** A transport of either kind, bound to `execution`. */
80
137
  export function bound(wire, execution) {
@@ -1,3 +1,4 @@
1
+ import { bindableTransport } from "../../client/services/propagation.js";
1
2
  import { Command } from "../domain/dto.js";
2
3
  import { Feature } from "../domain/services.js";
3
4
  import { BoundedContext } from "./bounded-context.js";
@@ -127,5 +128,5 @@ export function screensTransport(transport, name = "screens") {
127
128
  through.download = (route, signal, options) => screens.execute(new Export(route, signal, options));
128
129
  }
129
130
  MADE.add(through);
130
- return through;
131
+ return bindableTransport(through);
131
132
  }
@@ -1,7 +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
+ import { type IdentityKeys, type ProcessIdentity } from "../../observability/domain/identity.js";
5
5
  import type { Logger } from "../../observability/domain/logging.js";
6
6
  import { type Outcome, type Tracer } from "../../observability/domain/tracing.js";
7
7
  /**
@@ -45,11 +45,15 @@ export type ProcessOptions = {
45
45
  /**
46
46
  * Who is running — the backend's `APP_RELEASE` (`<name>:<version>`) and `TENANT`. Every span,
47
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.
48
+ * context's, else this one) and its `user_id`; `service.name` and `service.version` are read
49
+ * out of the release. Tenant and user are optional, and so are their keys: `keys` names the
50
+ * context keys they are read from (`tenant`/`tenant_id` and `user_id` by default) — an
51
+ * application whose tenant is its company says `keys: { tenant: "company_id" }`.
49
52
  */
50
53
  identity?: {
51
54
  release: string;
52
55
  tenant?: string;
56
+ keys?: IdentityKeys;
53
57
  };
54
58
  /** The platform's (OpenTelemetry in a browser, a queue on a phone, memory in a test). */
55
59
  tracer?: Tracer;
@@ -24,7 +24,7 @@ export function configureProcess(options = {}) {
24
24
  const logger = loggingEngine(options.logger ?? {});
25
25
  replaceObservability({
26
26
  identity: options.identity
27
- ? identityOf(options.identity.release, options.identity.tenant)
27
+ ? identityOf(options.identity.release, options.identity.tenant, options.identity.keys)
28
28
  : undefined,
29
29
  tracer: options.tracer ?? NO_TRACER,
30
30
  reporter: options.reporter,
@@ -1,6 +1,9 @@
1
1
  import { type Execution } from "../../context/domain/execution.js";
2
2
  /**
3
- * A dependency as the execution should see it: bound when it can be (`BIND`, a `Transport`, an
4
- * `OperationTransport`), as it is otherwise.
3
+ * A dependency as the execution should see it: bound when it says it can be (`BIND` — a
4
+ * generated client, `restOperations`, `jsonRpcOperations`, `restTransport`, `memoryTransport`,
5
+ * `guardedTransport`, `bindableOperations(…)`, `bindableTransport(…)`); as it is otherwise.
6
+ * Never guessed from a method's name: an application's object — an Odoo client with a `call`,
7
+ * a repository with a `list` — is the application's, untouched.
5
8
  */
6
9
  export declare function bindDependency<T>(value: T, execution: Execution): T;
@@ -1,16 +1,13 @@
1
- import { isOperationTransport } from "../../client/domain/operation.js";
2
- import { bindOperations, bindTransport, isTransport, } from "../../client/services/propagation.js";
3
1
  import { BIND, isBindable, } from "../../context/domain/execution.js";
4
2
  /**
5
- * A dependency as the execution should see it: bound when it can be (`BIND`, a `Transport`, an
6
- * `OperationTransport`), as it is otherwise.
3
+ * A dependency as the execution should see it: bound when it says it can be (`BIND` — a
4
+ * generated client, `restOperations`, `jsonRpcOperations`, `restTransport`, `memoryTransport`,
5
+ * `guardedTransport`, `bindableOperations(…)`, `bindableTransport(…)`); as it is otherwise.
6
+ * Never guessed from a method's name: an application's object — an Odoo client with a `call`,
7
+ * a repository with a `list` — is the application's, untouched.
7
8
  */
8
9
  export function bindDependency(value, execution) {
9
10
  if (isBindable(value))
10
11
  return value[BIND](execution);
11
- if (isTransport(value))
12
- return bindTransport(value, execution);
13
- if (isOperationTransport(value))
14
- return bindOperations(value, execution);
15
12
  return value;
16
13
  }
@@ -2,9 +2,10 @@ 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
+ import { tenantOf, userOf } from "../../observability/domain/identity.js";
6
6
  import { NO_TRACER, } from "../../observability/domain/tracing.js";
7
7
  import { observabilityNow } from "../../observability/infrastructure/registry.js";
8
+ import { describeFailure } from "../../observability/services/failure.js";
8
9
  import { executionLogger, logExecution, logHandled, } from "../../observability/services/logging.js";
9
10
  import { firstReport } from "../../observability/services/reporting.js";
10
11
  import { remoteSpan } from "../../observability/services/trace-context.js";
@@ -137,9 +138,11 @@ export async function executeService(target, command, options) {
137
138
  // Who is running, on the span as on its lines and its report.
138
139
  const release = ports.identity?.release;
139
140
  const tenant = tenantOf(context, ports.identity);
141
+ const userId = userOf(context, ports.identity);
140
142
  const attributes = {
141
143
  ...(release ? { release } : {}),
142
144
  ...(tenant ? { tenant } : {}),
145
+ ...(userId ? { user_id: userId } : {}),
143
146
  "sincpro.use_case": useCase,
144
147
  "sincpro.layer": options.layer,
145
148
  "sincpro.context": options.boundedContext,
@@ -180,10 +183,21 @@ export async function executeService(target, command, options) {
180
183
  ? "refused"
181
184
  : (failedAt(error.value)?.outcome ?? ports.outcomeOf(error.value)), "failed")
182
185
  : "ok";
183
- observe(() => span.end(outcome, error?.value), undefined);
186
+ // A failure is described once, by the run where it was raised; a run it crosses on the way
187
+ // out says only where it failed, and its span takes the error status, not the exception.
188
+ const origin = error ? failedAt(error.value) : undefined;
189
+ const failure = error
190
+ ? observe(() => describeFailure(error.value, outcome, origin?.execution.useCase), undefined)
191
+ : undefined;
192
+ observe(() => span.set({
193
+ "sincpro.outcome": failure ? failure.kind : "ok",
194
+ ...(failure ? { "sincpro.fault": failure.fault, "error.type": failure.type } : {}),
195
+ }), undefined);
196
+ observe(() => span.end(outcome, origin ? undefined : error?.value), undefined);
184
197
  logExecution(layer, execution, {
185
198
  outcome,
186
199
  durationMs: Math.max(0, Date.now() - startedAt),
200
+ ...(failure ? { failure } : {}),
187
201
  });
188
202
  if (outcome === "failed" && error && ports.reporter && !reported.has(error.value)) {
189
203
  reported.add(error.value);
@@ -195,7 +209,18 @@ export async function executeService(target, command, options) {
195
209
  executionId: id,
196
210
  context,
197
211
  ...(release ? { release } : {}),
212
+ ...(ports.identity
213
+ ? {
214
+ serviceName: ports.identity.serviceName,
215
+ serviceVersion: ports.identity.serviceVersion,
216
+ }
217
+ : {}),
198
218
  ...(tenant ? { tenant } : {}),
219
+ ...(userId ? { userId } : {}),
220
+ boundedContext: options.boundedContext,
221
+ layer,
222
+ ...(span.spanId ? { spanId: span.spanId } : {}),
223
+ ...(failure ? { errorType: failure.type, kind: failure.kind } : {}),
199
224
  }), undefined);
200
225
  }
201
226
  if (error?.value !== null &&
@@ -5,8 +5,4 @@ export type ConsoleLoggerOptions = {
5
5
  level?: LogLevel;
6
6
  layers?: Partial<Record<LogLayer, boolean>>;
7
7
  };
8
- /**
9
- * Built-in console engine: silent in production, configurable
10
- * development layers, and WARN/ERROR preserved. Other sinks are filtered independently.
11
- */
12
8
  export declare function consoleLogger(options: ConsoleLoggerOptions): Logger;
@@ -3,6 +3,13 @@ const RANK = { debug: 0, info: 1, warn: 2, error: 3 };
3
3
  * Built-in console engine: silent in production, configurable
4
4
  * development layers, and WARN/ERROR preserved. Other sinks are filtered independently.
5
5
  */
6
+ /** The failure as an Error to print: its type as its name, its message, its stack. */
7
+ function errorOf(stack, failure) {
8
+ const shown = new Error(failure.message ?? failure.type ?? "");
9
+ shown.name = failure.type ?? "Error";
10
+ shown.stack = stack;
11
+ return shown;
12
+ }
6
13
  export function consoleLogger(options) {
7
14
  const mode = options.mode;
8
15
  if (mode !== "development" && mode !== "production") {
@@ -29,7 +36,16 @@ export function consoleLogger(options) {
29
36
  : record.level === "error"
30
37
  ? console.error
31
38
  : console.log;
32
- method.call(console, prefix, record.message, record);
39
+ const stack = record.failure?.stack;
40
+ if (!stack) {
41
+ method.call(console, prefix, record.message, record);
42
+ return;
43
+ }
44
+ // An unexpected failure goes as an Error — its name, its message, its stack —: what React
45
+ // Native's LogBox, Expo's terminal and a browser print as a failure, with its code frame.
46
+ // A bare stack string read as one printed `ERROR null null`.
47
+ const { stack: _shownBelow, ...failure } = record.failure ?? {};
48
+ method.call(console, `${prefix} ${record.message}`, { ...record, failure }, errorOf(stack, failure));
33
49
  },
34
50
  };
35
51
  }
@@ -48,12 +48,13 @@ export function openTelemetryTracer(tracer) {
48
48
  };
49
49
  }
50
50
  /**
51
- * How the use case ended, said the way OpenTelemetry reads it: `failed` is an error with its
52
- * exception; `refused` and `aborted` are expected answers — said in `sincpro.outcome`, never as
53
- * an error, the way the backend leaves a refusal out of its error rate.
51
+ * How the use case ended, said the way OpenTelemetry reads it: `failed` is an error — with its
52
+ * exception on the span where it was raised, the only one handed it —; `refused` and `aborted`
53
+ * are expected answers, never an error, the way the backend leaves a refusal out of its error
54
+ * rate. `sincpro.outcome` (`ok` or the failure's kind), `sincpro.fault` and `error.type` are set
55
+ * by the run before it ends.
54
56
  */
55
57
  function close(span, outcome, error) {
56
- span.setAttribute("sincpro.outcome", outcome);
57
58
  if (outcome === "failed") {
58
59
  if (error instanceof Error)
59
60
  span.recordException(error);
@@ -7,6 +7,9 @@ export type ExceptionClient = {
7
7
  captureException(error: unknown, hint?: {
8
8
  captureContext?: {
9
9
  tags?: Record<string, string>;
10
+ user?: {
11
+ id: string;
12
+ };
10
13
  contexts?: Record<string, Record<string, unknown>>;
11
14
  };
12
15
  }): unknown;
@@ -17,13 +17,38 @@ export function sentryReporter(client) {
17
17
  report(error, about) {
18
18
  client.captureException(error, {
19
19
  captureContext: {
20
+ // sincpro_framework's keys (PRD_03 §5, §4.10): the same text as the log line and the span.
20
21
  tags: {
21
22
  "sincpro.use_case": about.useCase,
23
+ ...(about.boundedContext ? { "sincpro.context": about.boundedContext } : {}),
24
+ ...(about.layer ? { "sincpro.layer": about.layer } : {}),
25
+ ...(about.kind
26
+ ? { "sincpro.outcome": about.kind, "sincpro.kind": about.kind }
27
+ : {}),
28
+ ...(about.errorType ? { "error.type": about.errorType } : {}),
22
29
  ...(about.release ? { release: about.release } : {}),
30
+ ...(about.serviceName ? { service_name: about.serviceName } : {}),
31
+ ...(about.serviceVersion
32
+ ? {
33
+ service_version: about.serviceVersion,
34
+ "sincpro.version": about.serviceVersion,
35
+ }
36
+ : {}),
23
37
  ...(about.tenant ? { tenant: about.tenant } : {}),
38
+ ...(about.userId ? { user_id: about.userId } : {}),
24
39
  ...(about.traceId === "" ? {} : { trace_id: about.traceId }),
25
40
  },
41
+ // The issue opens its trace, and says how many users it hit.
42
+ ...(about.userId ? { user: { id: about.userId } } : {}),
26
43
  contexts: {
44
+ ...(about.traceId === ""
45
+ ? {}
46
+ : {
47
+ trace: {
48
+ trace_id: about.traceId,
49
+ ...(about.spanId ? { span_id: about.spanId } : {}),
50
+ },
51
+ }),
27
52
  sincpro: {
28
53
  use_case: about.useCase,
29
54
  execution_id: about.executionId,
@@ -20,6 +20,18 @@ export type ErrorAbout = {
20
20
  release?: string;
21
21
  /** The run's tenant — its context's, else the deployment's —, when there is one. */
22
22
  tenant?: string;
23
+ /** The run's user — its context's `user_id` —: the event's user. */
24
+ userId?: string;
25
+ /** The name and version out of the release (`identityOf`). */
26
+ serviceName?: string;
27
+ serviceVersion?: string;
28
+ /** Where it ran: its bounded context, its layer and its span. */
29
+ boundedContext?: string;
30
+ layer?: string;
31
+ spanId?: string;
32
+ /** The class's name (`error.type`) and the backend's failure kind. */
33
+ errorType?: string;
34
+ kind?: string;
23
35
  };
24
36
  /** Reports what nobody expected. One per platform; none when nothing reports. */
25
37
  export interface ErrorReporter {
@@ -23,15 +23,36 @@ export type ProcessIdentity = {
23
23
  readonly serviceVersion: string;
24
24
  /** The tenant the deployment serves, when it serves one. */
25
25
  readonly tenant?: string;
26
+ /** The context keys a run's tenant is read from, first found wins: `tenant`, `tenant_id`. */
27
+ readonly tenantKeys: readonly string[];
28
+ /** The context keys a run's user is read from: `user_id`. */
29
+ readonly userKeys: readonly string[];
30
+ };
31
+ /**
32
+ * Which keys of a run's context say its tenant and its user — optional both: an application
33
+ * that calls its tenant `company_id` names it here, one without tenants or users names nothing
34
+ * and nothing is sent.
35
+ */
36
+ export type IdentityKeys = {
37
+ readonly tenant?: string | readonly string[];
38
+ readonly user?: string | readonly string[];
26
39
  };
27
40
  /** The key the release goes by on a span, a log line and a report. */
28
41
  export declare const RELEASE = "release";
29
42
  /** The key the tenant goes by on a span, a log line and a report. */
30
43
  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;
44
+ /** The key the user goes by on a span, a log line and a report — GlitchTip's user. */
45
+ export declare const USER_ID = "user_id";
46
+ /**
47
+ * Who is running, out of its release — the deployment's tenant, when there is one, and the
48
+ * context keys its runs say their tenant and user under.
49
+ */
50
+ export declare function identityOf(release: string, tenant?: string, keys?: IdentityKeys): ProcessIdentity;
33
51
  /**
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.
52
+ * The tenant of a run: its context's, under the keys the application named (`tenant`, else
53
+ * `tenant_id`, by default), else the deployment's. Undefined when neither says one — most phones
54
+ * serve whoever opens the app.
36
55
  */
37
56
  export declare function tenantOf(context: Readonly<Record<string, unknown>>, identity: ProcessIdentity | undefined): string | undefined;
57
+ /** The user of a run: its context's, under the keys the application named (`user_id`). */
58
+ export declare function userOf(context: Readonly<Record<string, unknown>>, identity?: ProcessIdentity): string | undefined;
@@ -2,8 +2,17 @@
2
2
  export const RELEASE = "release";
3
3
  /** The key the tenant goes by on a span, a log line and a report. */
4
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) {
5
+ /** The key the user goes by on a span, a log line and a report — GlitchTip's user. */
6
+ export const USER_ID = "user_id";
7
+ /** Where a run's tenant and user are read from when the application names no keys. */
8
+ const DEFAULT_TENANT_KEYS = [TENANT, "tenant_id"];
9
+ const DEFAULT_USER_KEYS = [USER_ID];
10
+ const keysOf = (named, fallback) => (named === undefined ? fallback : typeof named === "string" ? [named] : [...named]);
11
+ /**
12
+ * Who is running, out of its release — the deployment's tenant, when there is one, and the
13
+ * context keys its runs say their tenant and user under.
14
+ */
15
+ export function identityOf(release, tenant, keys = {}) {
7
16
  const verbatim = release.trim();
8
17
  const [artifact, version] = split(verbatim);
9
18
  const deployed = tenant?.trim();
@@ -12,21 +21,34 @@ export function identityOf(release, tenant) {
12
21
  serviceName: artifact.slice(artifact.lastIndexOf("/") + 1),
13
22
  serviceVersion: version,
14
23
  ...(deployed ? { tenant: deployed } : {}),
24
+ tenantKeys: keysOf(keys.tenant, DEFAULT_TENANT_KEYS),
25
+ userKeys: keysOf(keys.user, DEFAULT_USER_KEYS),
15
26
  };
16
27
  }
17
28
  /**
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.
29
+ * The tenant of a run: its context's, under the keys the application named (`tenant`, else
30
+ * `tenant_id`, by default), else the deployment's. Undefined when neither says one — most phones
31
+ * serve whoever opens the app.
20
32
  */
21
33
  export function tenantOf(context, identity) {
22
- for (const key of [TENANT, "tenant_id"]) {
34
+ return valueOf(context, identity?.tenantKeys ?? DEFAULT_TENANT_KEYS) ?? identity?.tenant;
35
+ }
36
+ /** The user of a run: its context's, under the keys the application named (`user_id`). */
37
+ export function userOf(context, identity) {
38
+ return valueOf(context, identity?.userKeys ?? DEFAULT_USER_KEYS);
39
+ }
40
+ /** The first key the context says, as text; a list of them (`tenant_ids`) is said as one. */
41
+ function valueOf(context, keys) {
42
+ for (const key of keys) {
23
43
  const value = context[key];
24
44
  if (typeof value === "string" && value !== "")
25
45
  return value;
26
46
  if (typeof value === "number")
27
47
  return String(value);
48
+ if (Array.isArray(value) && value.length > 0)
49
+ return value.map(String).join(",");
28
50
  }
29
- return identity?.tenant;
51
+ return undefined;
30
52
  }
31
53
  /**
32
54
  * Name and version out of a release, read as an image reference or `name@version`:
@@ -14,6 +14,27 @@ export type LogLevel = "debug" | "info" | "warn" | "error";
14
14
  /** The layer a line comes from. */
15
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
+ /**
18
+ * What a failure says — sincpro_framework's failure line: its type (`error.type`), its kind, its
19
+ * fault and, when nobody expected it, its message, where it was raised and its stack. Told once,
20
+ * by the run where it was raised; a run it crosses says only where it failed (`failedIn`).
21
+ */
22
+ export type FailureDescription = {
23
+ /** The class's name: `TypeError`, `TransportError`. */
24
+ readonly type: string;
25
+ /** The backend's failure kind (`invalid` … `internal`), or `aborted`. */
26
+ readonly kind: string;
27
+ /** The system's problem, not an answer to the caller. */
28
+ readonly fault: boolean;
29
+ /** An unexpected failure's message, cut at 500 characters. */
30
+ readonly message?: string;
31
+ /** The first frame outside the framework: the use case's own line. */
32
+ readonly at?: string;
33
+ /** An unexpected failure's stack — on the run where it was raised only. */
34
+ readonly stack?: string;
35
+ /** The use case it was raised in, when that is another run's. */
36
+ readonly failedIn?: string;
37
+ };
17
38
  export type LogRecord = {
18
39
  readonly timestamp: string;
19
40
  readonly level: LogLevel;
@@ -34,6 +55,10 @@ export type LogRecord = {
34
55
  readonly release?: string;
35
56
  /** The run's tenant — its context's, else the deployment's —, when there is one. */
36
57
  readonly tenant?: string;
58
+ /** The run's user — its context's `user_id` —, when there is one. */
59
+ readonly userId?: string;
60
+ /** How the run failed, on its `execution.finished` line. */
61
+ readonly failure?: FailureDescription;
37
62
  };
38
63
  /** A sink owns filtering and delivery. Logging is best-effort and never awaited by business work. */
39
64
  export interface Logger {
@@ -9,9 +9,10 @@
9
9
  * services/ the loggers, `reportError`, the default `outcomeOf`
10
10
  */
11
11
  export type { ErrorAbout, ErrorReporter, } from "./domain/errors.js";
12
- export { identityOf, type ProcessIdentity, RELEASE, TENANT, tenantOf, } from "./domain/identity.js";
13
- export type { LayerLogger, Logger, LogLayer, LogLevel, LogRecord, } from "./domain/logging.js";
12
+ export { type IdentityKeys, identityOf, type ProcessIdentity, RELEASE, TENANT, tenantOf, USER_ID, userOf, } from "./domain/identity.js";
13
+ export type { FailureDescription, LayerLogger, Logger, LogLayer, LogLevel, LogRecord, } from "./domain/logging.js";
14
14
  export { type Attributes, NO_TRACER, type Outcome, type Span, type Tracer, } from "./domain/tracing.js";
15
+ export { describeFailure } from "./services/failure.js";
15
16
  export { combineLoggers, logger, loggerAdapter, } from "./services/logging.js";
16
17
  export { outcomeOf } from "./services/outcome.js";
17
18
  export { reportError } from "./services/reporting.js";
@@ -1,5 +1,6 @@
1
- export { identityOf, RELEASE, TENANT, tenantOf, } from "./domain/identity.js";
1
+ export { identityOf, RELEASE, TENANT, tenantOf, USER_ID, userOf, } from "./domain/identity.js";
2
2
  export { NO_TRACER, } from "./domain/tracing.js";
3
+ export { describeFailure } from "./services/failure.js";
3
4
  export { combineLoggers, logger, loggerAdapter, } from "./services/logging.js";
4
5
  export { outcomeOf } from "./services/outcome.js";
5
6
  export { reportError } from "./services/reporting.js";
@@ -0,0 +1,21 @@
1
+ import type { FailureDescription } from "../domain/logging.js";
2
+ import type { Outcome } from "../domain/tracing.js";
3
+ /**
4
+ * What a failure says on its log line, its span and its report — sincpro_framework's failure
5
+ * (`observability/failure.py`): its type, its kind, whether it is a fault, its message, where it
6
+ * was raised and, when nobody expected it, its stack.
7
+ *
8
+ * describeFailure(new TypeError("x is undefined"), "failed")
9
+ * → { type: "TypeError", kind: "internal", fault: true, message: "x is undefined",
10
+ * at: "SaveServer.execute (save_server.feature.ts:20:5)", stack: "TypeError: …" }
11
+ * describeFailure(new TransportError("/x", 409, null), "refused")
12
+ * → { type: "TransportError", kind: "conflict", fault: false } // expected: no message, no stack
13
+ * describeFailure(error, "failed", "odoo.SaveServer")
14
+ * → { type, kind, fault, message, failedIn: "odoo.SaveServer" } // told once, where it failed
15
+ *
16
+ * Context: a failure is described once — by the run where it was raised —; a run it crosses on
17
+ * the way out says only its type and where it failed (`failedIn`). An expected one (`refused`,
18
+ * `aborted`) is the business answering or the caller leaving: its type and kind, never its
19
+ * message, which may carry the caller's data. Never the DTO, the result or the context.
20
+ */
21
+ export declare function describeFailure(error: unknown, outcome: Outcome, failedIn?: string): FailureDescription;
@@ -0,0 +1,73 @@
1
+ import { failureOf } from "../../common/failures.js";
2
+ /** A message is cut here: a line is a description, not a dump. */
3
+ const MAX_MESSAGE = 500;
4
+ /**
5
+ * Frames of the framework itself — the installed package, or its own sources —: where a failure
6
+ * was raised is the first frame outside them.
7
+ */
8
+ const FRAMEWORK_FRAME = /@sincpro\/client-framework\/|sincpro_client_framework\/src\/|node:internal/;
9
+ /**
10
+ * What a failure says on its log line, its span and its report — sincpro_framework's failure
11
+ * (`observability/failure.py`): its type, its kind, whether it is a fault, its message, where it
12
+ * was raised and, when nobody expected it, its stack.
13
+ *
14
+ * describeFailure(new TypeError("x is undefined"), "failed")
15
+ * → { type: "TypeError", kind: "internal", fault: true, message: "x is undefined",
16
+ * at: "SaveServer.execute (save_server.feature.ts:20:5)", stack: "TypeError: …" }
17
+ * describeFailure(new TransportError("/x", 409, null), "refused")
18
+ * → { type: "TransportError", kind: "conflict", fault: false } // expected: no message, no stack
19
+ * describeFailure(error, "failed", "odoo.SaveServer")
20
+ * → { type, kind, fault, message, failedIn: "odoo.SaveServer" } // told once, where it failed
21
+ *
22
+ * Context: a failure is described once — by the run where it was raised —; a run it crosses on
23
+ * the way out says only its type and where it failed (`failedIn`). An expected one (`refused`,
24
+ * `aborted`) is the business answering or the caller leaving: its type and kind, never its
25
+ * message, which may carry the caller's data. Never the DTO, the result or the context.
26
+ */
27
+ export function describeFailure(error, outcome, failedIn) {
28
+ const failure = failureOf(error);
29
+ const type = typeOf(error);
30
+ const base = {
31
+ type,
32
+ kind: failure.aborted ? "aborted" : failure.kind,
33
+ fault: failure.fault,
34
+ };
35
+ if (outcome !== "failed")
36
+ return base;
37
+ const message = messageOf(error);
38
+ if (failedIn)
39
+ return { ...base, ...(message ? { message } : {}), failedIn };
40
+ const stack = error instanceof Error ? error.stack : undefined;
41
+ const at = stack ? raisedAt(stack) : undefined;
42
+ return {
43
+ ...base,
44
+ ...(message ? { message } : {}),
45
+ ...(at ? { at } : {}),
46
+ ...(stack ? { stack } : {}),
47
+ };
48
+ }
49
+ /** The class's name, as every signal spells it (`error.type`). */
50
+ function typeOf(error) {
51
+ if (error instanceof Error) {
52
+ const named = error.constructor?.name;
53
+ return named && named !== "Object" ? named : error.name || "Error";
54
+ }
55
+ return error === null ? "null" : typeof error;
56
+ }
57
+ function messageOf(error) {
58
+ const text = error instanceof Error ? error.message : String(error);
59
+ return text.length > MAX_MESSAGE ? `${text.slice(0, MAX_MESSAGE)}…` : text;
60
+ }
61
+ /**
62
+ * Where it was raised: the first frame of the stack outside the framework — the use case's own
63
+ * code (`SaveServer.execute (save_server.feature.ts:20:5)`), V8's `at …` or JavaScriptCore's
64
+ * `name@file:line`.
65
+ */
66
+ function raisedAt(stack) {
67
+ for (const line of stack.split("\n").slice(1)) {
68
+ const frame = line.trim().replace(/^at /, "");
69
+ if (frame && !FRAMEWORK_FRAME.test(frame))
70
+ return frame;
71
+ }
72
+ return undefined;
73
+ }
@@ -1,5 +1,5 @@
1
1
  import { type Execution } from "../../context/domain/execution.js";
2
- import type { LayerLogger, Logger, LogLayer } from "../domain/logging.js";
2
+ import type { FailureDescription, LayerLogger, Logger, LogLayer } from "../domain/logging.js";
3
3
  import type { Outcome } from "../domain/tracing.js";
4
4
  /** The infrastructure's logger — the global one: the code that starts and holds the application. */
5
5
  export declare const logger: LayerLogger;
@@ -17,6 +17,7 @@ export declare function combineLoggers(...loggers: readonly Logger[]): Logger;
17
17
  export declare function logExecution(layer: RunLogLayer, execution: Execution, completed?: {
18
18
  outcome: Outcome;
19
19
  durationMs: number;
20
+ failure?: FailureDescription;
20
21
  }): void;
21
22
  /**
22
23
  * @internal — an error a handler of the bounded context answered instead of raising: said once,
@@ -1,5 +1,5 @@
1
1
  import { BIND } from "../../context/domain/execution.js";
2
- import { tenantOf } from "../domain/identity.js";
2
+ import { tenantOf, userOf } from "../domain/identity.js";
3
3
  import { observabilityNow } from "../infrastructure/registry.js";
4
4
  const processSink = () => observabilityNow().logger;
5
5
  /** Sink failures cannot replace a business outcome or cause unhandled async rejections. */
@@ -23,11 +23,13 @@ function recordOf(fields, correlation) {
23
23
  const { runContext, ...where } = correlation;
24
24
  const identity = observabilityNow().identity;
25
25
  const tenant = tenantOf(runContext ?? {}, identity);
26
+ const userId = userOf(runContext ?? {}, identity);
26
27
  return {
27
28
  ...fields,
28
29
  ...where,
29
30
  ...(identity ? { release: identity.release } : {}),
30
31
  ...(tenant ? { tenant } : {}),
32
+ ...(userId ? { userId } : {}),
31
33
  };
32
34
  }
33
35
  function correlationOf(execution) {
@@ -87,22 +89,28 @@ export function combineLoggers(...loggers) {
87
89
  /** @internal — lifecycle records contain correlation and outcome, never business payloads. */
88
90
  export function logExecution(layer, execution, completed) {
89
91
  const outcome = completed?.outcome;
90
- const level = outcome === "failed"
91
- ? "error"
92
- : outcome === "refused"
93
- ? "warn"
94
- : completed
95
- ? "info"
96
- : "debug";
92
+ // As sincpro_framework: an unexpected failure is an error; an expected one — a refusal, the
93
+ // caller leaving — is information, without a stack.
94
+ const level = outcome === "failed" ? "error" : completed ? "info" : "debug";
95
+ const failure = completed?.failure;
97
96
  deliver(processSink(), recordOf({
98
97
  timestamp: new Date().toISOString(),
99
98
  level,
100
99
  layer,
101
100
  event: completed ? "execution.finished" : "execution.started",
102
- message: completed ? `Execution ${completed.outcome}` : "Execution started",
101
+ message: completed
102
+ ? `Execution ${completed.outcome}${failure ? `: ${summaryOf(failure)}` : ""}`
103
+ : "Execution started",
103
104
  ...(completed ? completed : {}),
104
105
  }, correlationOf(execution)));
105
106
  }
107
+ /** `TypeError: x is undefined at SaveServer.execute (…)`, or where it failed when it was another run. */
108
+ function summaryOf(failure) {
109
+ const what = failure.message ? `${failure.type}: ${failure.message}` : failure.type;
110
+ if (failure.failedIn)
111
+ return `${what} (in ${failure.failedIn})`;
112
+ return failure.at ? `${what} at ${failure.at}` : what;
113
+ }
106
114
  /**
107
115
  * @internal — an error a handler of the bounded context answered instead of raising: said once,
108
116
  * with where it was handled, never with the error itself.
@@ -110,7 +118,8 @@ export function logExecution(layer, execution, completed) {
110
118
  export function logHandled(layer, correlation) {
111
119
  deliver(processSink(), recordOf({
112
120
  timestamp: new Date().toISOString(),
113
- level: "info",
121
+ // As sincpro_framework: an error a handler answered is a warning.
122
+ level: "warn",
114
123
  layer,
115
124
  event: "error.handled",
116
125
  message: "Error handled",
@@ -1,7 +1,8 @@
1
1
  import { newEntityId } from "../../common/ids.js";
2
2
  import { processContext } from "../../context/infrastructure/process.js";
3
- import { tenantOf } from "../domain/identity.js";
3
+ import { tenantOf, userOf } from "../domain/identity.js";
4
4
  import { observabilityNow } from "../infrastructure/registry.js";
5
+ import { describeFailure } from "./failure.js";
5
6
  /**
6
7
  * Whether this is the first time this error is reported. A Feature that fails inside an
7
8
  * ApplicationService throws through it, and a screen that draws the failure may break on it:
@@ -43,14 +44,26 @@ export function reportError(error, where) {
43
44
  return;
44
45
  try {
45
46
  const context = processContext.values;
46
- const tenant = tenantOf(context, settings.identity);
47
+ const identity = settings.identity;
48
+ const tenant = tenantOf(context, identity);
49
+ const userId = userOf(context, identity);
50
+ const failure = describeFailure(error, "failed");
47
51
  settings.reporter?.report(error, {
48
52
  useCase: where,
49
53
  traceId: "",
50
54
  executionId: newEntityId(),
51
55
  context,
52
- ...(settings.identity ? { release: settings.identity.release } : {}),
56
+ ...(identity
57
+ ? {
58
+ release: identity.release,
59
+ serviceName: identity.serviceName,
60
+ serviceVersion: identity.serviceVersion,
61
+ }
62
+ : {}),
53
63
  ...(tenant ? { tenant } : {}),
64
+ ...(userId ? { userId } : {}),
65
+ errorType: failure.type,
66
+ kind: failure.kind,
54
67
  });
55
68
  }
56
69
  catch {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/client-framework",
3
- "version": "1.5.0",
3
+ "version": "1.6.1",
4
4
  "description": "The client side of sincpro_framework, for every platform: Feature and ApplicationService traced and reported by default, applications made of domains, and the typed client generated from a service's contract. No React, no DOM.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",