@sincpro/client-framework 1.5.0 → 1.6.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.
package/AGENTS.md CHANGED
@@ -204,8 +204,22 @@ options)`: no route, no verb, no RPC method. The contract's bindings (`rest`, `r
204
204
  `loggerAdapter` are predefined; injected as a dependency they bind to the run (`BIND`), imported
205
205
  at module level they do not. No logger is predefined for an application layer. Console is the
206
206
  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.
207
+ `LoggerConfiguration`. The host chooses production explicitly. Never log DTOs, results or the
208
+ full session context automatically.
209
+ - **A failure is described once, as sincpro_framework's failure line** (`PRD_03 §6`,
210
+ `observability/failure.py`). The run where it was raised writes its type, kind, fault and —
211
+ when nobody expected it — its message, the use case's own line (`at`) and its stack; a run it
212
+ crosses says only `failedIn`. Its span records the exception; the spans it crosses take the
213
+ error status. An expected failure is information: type and kind, never its message (it may
214
+ carry the caller's data) nor a stack. `sincpro.outcome` is `ok` or the failure's kind, beside
215
+ `sincpro.fault` and `error.type`, on the span and in GlitchTip.
216
+ - **Who is running is on every signal** (`configureProcess({ identity })`, `PRD_03 §4.10`):
217
+ `release`, the run's `tenant` and `user_id`. Tenant and user are optional, and so are their
218
+ keys — `identity.keys` names the context keys an application uses (`company_id`, `tenant_ids`);
219
+ nothing is sent when its context says none. Nothing else of the context is copied.
220
+ - **Observability never fails a use case.** Every tracer, logger and reporter call is shielded:
221
+ a collector down, Loki unreachable or no network leave the run's own answer — or its own error —
222
+ untouched.
209
223
 
210
224
  - **Only what is transversal comes here.** A value's wire form (a decimal as text, a day never
211
225
  an instant, a money with its currency) is the backend's contract, the same on every platform,
@@ -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,
@@ -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 &&
@@ -29,7 +29,15 @@ export function consoleLogger(options) {
29
29
  : record.level === "error"
30
30
  ? console.error
31
31
  : console.log;
32
- method.call(console, prefix, record.message, record);
32
+ // An unexpected failure's stack prints as a stack, readable, after its line — not escaped
33
+ // inside the record.
34
+ const stack = record.failure?.stack;
35
+ if (!stack) {
36
+ method.call(console, prefix, record.message, record);
37
+ return;
38
+ }
39
+ const { stack: _printedBelow, ...failure } = record.failure ?? {};
40
+ method.call(console, prefix, record.message, { ...record, failure }, `\n${stack}`);
33
41
  },
34
42
  };
35
43
  }
@@ -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.0",
4
4
  "description": "The client side of sincpro_framework, for every platform: Feature and ApplicationService traced and reported by default, applications made of domains, and the typed client generated from a service's contract. No React, no DOM.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",