@macss/modular-api 0.6.1 → 0.7.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.
- package/README.md +19 -0
- package/dist/core/logger/logger.d.ts +39 -1
- package/dist/core/logger/logger.js +29 -10
- package/dist/core/logger/logging_middleware.d.ts +3 -1
- package/dist/core/logger/logging_middleware.js +21 -3
- package/dist/core/modular_api.d.ts +15 -0
- package/dist/core/modular_api.js +61 -2
- package/dist/core/module_builder.d.ts +2 -2
- package/dist/core/schema/field.d.ts +1 -1
- package/dist/core/tracing/cloudTracePropagator.d.ts +33 -0
- package/dist/core/tracing/cloudTracePropagator.js +103 -0
- package/dist/core/tracing/compositePropagator.d.ts +23 -0
- package/dist/core/tracing/compositePropagator.js +52 -0
- package/dist/core/tracing/propagationPolicy.d.ts +65 -0
- package/dist/core/tracing/propagationPolicy.js +94 -0
- package/dist/core/tracing/serverSpan.d.ts +40 -0
- package/dist/core/tracing/serverSpan.js +64 -0
- package/dist/core/tracing/tracingMiddleware.d.ts +42 -0
- package/dist/core/tracing/tracingMiddleware.js +76 -0
- package/dist/core/tracing/tracingOptions.d.ts +76 -0
- package/dist/core/tracing/tracingOptions.js +44 -0
- package/dist/core/tracing/w3cTraceContextPropagator.d.ts +31 -0
- package/dist/core/tracing/w3cTraceContextPropagator.js +117 -0
- package/dist/core/usecase.d.ts +1 -1
- package/dist/core/usecase_handler.d.ts +1 -1
- package/dist/index.d.ts +8 -0
- package/dist/index.js +21 -2
- package/package.json +7 -3
package/README.md
CHANGED
|
@@ -42,6 +42,25 @@ curl -X POST http://localhost:8080/api/greetings/hello \
|
|
|
42
42
|
|
|
43
43
|
See `example/example.ts` for the full implementation including Input, Output, UseCase with `validate()`, and the builder.
|
|
44
44
|
|
|
45
|
+
### JSON body limit
|
|
46
|
+
|
|
47
|
+
Set `jsonBodyLimit` in `ModularApiOptions` to configure the JSON parser installed by
|
|
48
|
+
`serve()`. It accepts a size string such as `'1mb'` or a number of bytes:
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
const api = new ModularApi({
|
|
52
|
+
basePath: '/api',
|
|
53
|
+
jsonBodyLimit: '1mb', // Equivalent to 1_048_576 bytes.
|
|
54
|
+
});
|
|
55
|
+
api.module('greetings', buildGreetingsModule);
|
|
56
|
+
await api.serve({ port: 8080 });
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Omitting the option or passing `undefined` keeps the default `'100kb'` (102,400
|
|
60
|
+
bytes). The limit measures UTF-8 body bytes, applies only to bodies handled by the
|
|
61
|
+
JSON parser, and is independent for each `ModularApi` instance. Oversized bodies
|
|
62
|
+
keep the existing error response.
|
|
63
|
+
|
|
45
64
|
---
|
|
46
65
|
|
|
47
66
|
## Features
|
|
@@ -43,12 +43,50 @@ export type WriteFn = (line: string) => void;
|
|
|
43
43
|
* Accepts an optional `writeFn` for output — defaults to `console.log`.
|
|
44
44
|
* In tests, pass a capturing function to inspect output without side-effects.
|
|
45
45
|
*/
|
|
46
|
+
/**
|
|
47
|
+
* Builds platform-specific correlation fields from the ids the framework resolved.
|
|
48
|
+
*
|
|
49
|
+
* The framework emits open formats and nothing vendor-specific (roadmap invariant 7), so
|
|
50
|
+
* a field like Google's `logging.googleapis.com/trace` — which needs a project id the
|
|
51
|
+
* framework has no business knowing — is produced by the application.
|
|
52
|
+
*/
|
|
53
|
+
export type TraceFieldFormatter = (traceId: string, spanId: string | undefined) => Record<string, unknown>;
|
|
46
54
|
export declare class RequestScopedLogger implements ModularLogger {
|
|
47
55
|
readonly traceId: string;
|
|
48
56
|
readonly logLevel: LogLevel;
|
|
49
57
|
readonly serviceName: string;
|
|
50
58
|
private readonly writeFn;
|
|
51
|
-
|
|
59
|
+
/**
|
|
60
|
+
* The caller's `X-Request-ID`, when it sent one. Preserved beside {@link traceId}
|
|
61
|
+
* rather than promoted into it (runbook D6).
|
|
62
|
+
*/
|
|
63
|
+
readonly requestId?: string | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* The active server span's id, when tracing is configured.
|
|
66
|
+
*
|
|
67
|
+
* Known at construction because the tracing middleware is **outermost** (runbook D12
|
|
68
|
+
* as reversed): the span already exists when `loggingMiddleware` creates this logger,
|
|
69
|
+
* so nothing needs mutating afterwards.
|
|
70
|
+
*/
|
|
71
|
+
readonly spanId?: string | undefined;
|
|
72
|
+
/** Builds platform correlation fields. Undefined means none are emitted. */
|
|
73
|
+
private readonly traceFieldFormatter?;
|
|
74
|
+
constructor(traceId: string, logLevel: LogLevel, serviceName: string, writeFn?: WriteFn,
|
|
75
|
+
/**
|
|
76
|
+
* The caller's `X-Request-ID`, when it sent one. Preserved beside {@link traceId}
|
|
77
|
+
* rather than promoted into it (runbook D6).
|
|
78
|
+
*/
|
|
79
|
+
requestId?: string | undefined,
|
|
80
|
+
/**
|
|
81
|
+
* The active server span's id, when tracing is configured.
|
|
82
|
+
*
|
|
83
|
+
* Known at construction because the tracing middleware is **outermost** (runbook D12
|
|
84
|
+
* as reversed): the span already exists when `loggingMiddleware` creates this logger,
|
|
85
|
+
* so nothing needs mutating afterwards.
|
|
86
|
+
*/
|
|
87
|
+
spanId?: string | undefined,
|
|
88
|
+
/** Builds platform correlation fields. Undefined means none are emitted. */
|
|
89
|
+
traceFieldFormatter?: TraceFieldFormatter | undefined);
|
|
52
90
|
emergency(msg: string, fields?: Record<string, unknown>): void;
|
|
53
91
|
alert(msg: string, fields?: Record<string, unknown>): void;
|
|
54
92
|
critical(msg: string, fields?: Record<string, unknown>): void;
|
|
@@ -34,25 +34,37 @@ const LEVEL_NAME = {
|
|
|
34
34
|
[LogLevel.info]: 'info',
|
|
35
35
|
[LogLevel.debug]: 'debug',
|
|
36
36
|
};
|
|
37
|
-
/**
|
|
38
|
-
* Per-request logger that carries `traceId` and respects `logLevel` filtering.
|
|
39
|
-
*
|
|
40
|
-
* Created by `loggingMiddleware` for each incoming HTTP request and injected
|
|
41
|
-
* into the UseCase via the `logger` property.
|
|
42
|
-
*
|
|
43
|
-
* Accepts an optional `writeFn` for output — defaults to `console.log`.
|
|
44
|
-
* In tests, pass a capturing function to inspect output without side-effects.
|
|
45
|
-
*/
|
|
46
37
|
class RequestScopedLogger {
|
|
47
38
|
traceId;
|
|
48
39
|
logLevel;
|
|
49
40
|
serviceName;
|
|
50
41
|
writeFn;
|
|
51
|
-
|
|
42
|
+
requestId;
|
|
43
|
+
spanId;
|
|
44
|
+
traceFieldFormatter;
|
|
45
|
+
constructor(traceId, logLevel, serviceName, writeFn = (line) => process.stdout.write(line + '\n'),
|
|
46
|
+
/**
|
|
47
|
+
* The caller's `X-Request-ID`, when it sent one. Preserved beside {@link traceId}
|
|
48
|
+
* rather than promoted into it (runbook D6).
|
|
49
|
+
*/
|
|
50
|
+
requestId,
|
|
51
|
+
/**
|
|
52
|
+
* The active server span's id, when tracing is configured.
|
|
53
|
+
*
|
|
54
|
+
* Known at construction because the tracing middleware is **outermost** (runbook D12
|
|
55
|
+
* as reversed): the span already exists when `loggingMiddleware` creates this logger,
|
|
56
|
+
* so nothing needs mutating afterwards.
|
|
57
|
+
*/
|
|
58
|
+
spanId,
|
|
59
|
+
/** Builds platform correlation fields. Undefined means none are emitted. */
|
|
60
|
+
traceFieldFormatter) {
|
|
52
61
|
this.traceId = traceId;
|
|
53
62
|
this.logLevel = logLevel;
|
|
54
63
|
this.serviceName = serviceName;
|
|
55
64
|
this.writeFn = writeFn;
|
|
65
|
+
this.requestId = requestId;
|
|
66
|
+
this.spanId = spanId;
|
|
67
|
+
this.traceFieldFormatter = traceFieldFormatter;
|
|
56
68
|
}
|
|
57
69
|
// ─── Public API (8 RFC 5424 levels) ──────────────────────────────
|
|
58
70
|
emergency(msg, fields) {
|
|
@@ -116,7 +128,14 @@ class RequestScopedLogger {
|
|
|
116
128
|
msg,
|
|
117
129
|
service: this.serviceName,
|
|
118
130
|
trace_id: this.traceId,
|
|
131
|
+
...(this.spanId === undefined ? {} : { span_id: this.spanId }),
|
|
132
|
+
...(this.requestId === undefined ? {} : { request_id: this.requestId }),
|
|
119
133
|
};
|
|
134
|
+
// Only when there is trace context to point at. A platform field naming a trace
|
|
135
|
+
// that does not exist is worse than no field.
|
|
136
|
+
if (this.traceFieldFormatter !== undefined && this.spanId !== undefined) {
|
|
137
|
+
Object.assign(entry, this.traceFieldFormatter(this.traceId, this.spanId));
|
|
138
|
+
}
|
|
120
139
|
if (opts.extra)
|
|
121
140
|
Object.assign(entry, opts.extra);
|
|
122
141
|
if (opts.fields)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { RequestHandler } from 'express';
|
|
2
|
-
import { LogLevel } from './logger';
|
|
2
|
+
import { LogLevel, type TraceFieldFormatter } from './logger';
|
|
3
3
|
import type { WriteFn } from './logger';
|
|
4
4
|
/** Key used in `res.locals` to propagate the logger to downstream handlers. */
|
|
5
5
|
export declare const LOGGER_LOCALS_KEY = "modularLogger";
|
|
@@ -9,6 +9,8 @@ export interface LoggingMiddlewareOptions {
|
|
|
9
9
|
excludedRoutes?: string[];
|
|
10
10
|
/** Override output for testing. Defaults to stdout. */
|
|
11
11
|
writeFn?: WriteFn;
|
|
12
|
+
/** Builds platform correlation fields. Undefined means none are emitted. */
|
|
13
|
+
traceFieldFormatter?: TraceFieldFormatter;
|
|
12
14
|
}
|
|
13
15
|
/**
|
|
14
16
|
* Creates an Express middleware that:
|
|
@@ -8,6 +8,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
8
8
|
exports.LOGGER_LOCALS_KEY = void 0;
|
|
9
9
|
exports.loggingMiddleware = loggingMiddleware;
|
|
10
10
|
const node_crypto_1 = require("node:crypto");
|
|
11
|
+
const api_1 = require("@opentelemetry/api");
|
|
11
12
|
const logger_1 = require("./logger");
|
|
12
13
|
const request_pipeline_audit_1 = require("../request_pipeline_audit");
|
|
13
14
|
/** Key used in `res.locals` to propagate the logger to downstream handlers. */
|
|
@@ -32,11 +33,28 @@ function loggingMiddleware(opts) {
|
|
|
32
33
|
if (excludedSet.has(path)) {
|
|
33
34
|
return next();
|
|
34
35
|
}
|
|
35
|
-
// 1. Resolve
|
|
36
|
+
// 1. Resolve the ids from the ambient span.
|
|
37
|
+
//
|
|
38
|
+
// The tracing middleware is outermost (D12 as reversed), so when tracing is
|
|
39
|
+
// configured a recording span is already active here — and it stays active for
|
|
40
|
+
// `request completed` too. That is what lets both lines carry the same ids with
|
|
41
|
+
// nothing mutated afterwards.
|
|
42
|
+
//
|
|
43
|
+
// With no recording span this is byte-for-byte the behaviour it always had: the
|
|
44
|
+
// caller's X-Request-ID or a fresh UUID. D5b's compatibility guarantee is therefore
|
|
45
|
+
// structural rather than conditional — there is no tracing flag to consult, only
|
|
46
|
+
// whether a span exists.
|
|
47
|
+
const activeSpan = api_1.trace.getSpan(api_1.context.active());
|
|
48
|
+
const activeSpanContext = activeSpan?.spanContext();
|
|
49
|
+
const tracingActive = activeSpanContext !== undefined && api_1.trace.isSpanContextValid(activeSpanContext);
|
|
36
50
|
const headerValue = req.headers['x-request-id'];
|
|
37
|
-
const
|
|
51
|
+
const callerRequestId = typeof headerValue === 'string' && headerValue.length > 0 ? headerValue : undefined;
|
|
52
|
+
const traceId = tracingActive ? activeSpanContext.traceId : (callerRequestId ?? (0, node_crypto_1.randomUUID)());
|
|
53
|
+
const spanId = tracingActive ? activeSpanContext.spanId : undefined;
|
|
54
|
+
// Preserved beside the trace id rather than promoted into it (D6).
|
|
55
|
+
const requestId = tracingActive ? callerRequestId : undefined;
|
|
38
56
|
// 2. Create per-request logger
|
|
39
|
-
const logger = new logger_1.RequestScopedLogger(traceId, opts.logLevel, opts.serviceName, opts.writeFn);
|
|
57
|
+
const logger = new logger_1.RequestScopedLogger(traceId, opts.logLevel, opts.serviceName, opts.writeFn, requestId, spanId, opts.traceFieldFormatter);
|
|
40
58
|
const method = req.method.toUpperCase();
|
|
41
59
|
const route = path;
|
|
42
60
|
// 3. "request received"
|
|
@@ -2,12 +2,18 @@ import { type RequestHandler } from 'express';
|
|
|
2
2
|
import { ModuleBuilder } from './module_builder';
|
|
3
3
|
import type { HealthCheck } from './health/health_check';
|
|
4
4
|
import { MetricsRegistrar } from './metrics/metric_registry';
|
|
5
|
+
import { TracingOptions } from './tracing/tracingOptions';
|
|
5
6
|
import { LogLevel } from './logger/logger';
|
|
6
7
|
import { type Plugin } from './plugin';
|
|
7
8
|
import type { GraphqlOptions } from '../graphql/runtime/graphql_runtime_options';
|
|
8
9
|
export interface ModularApiOptions {
|
|
9
10
|
/** Base path prefix for all module routes. Default: '/api' */
|
|
10
11
|
basePath?: string;
|
|
12
|
+
/**
|
|
13
|
+
* Maximum JSON request body size. Number in bytes or a size string (e.g. '1mb').
|
|
14
|
+
* Default: '100kb' (102400 bytes), matching Express/body-parser.
|
|
15
|
+
*/
|
|
16
|
+
jsonBodyLimit?: string | number;
|
|
11
17
|
/** API title shown in Swagger UI. Default: 'API' */
|
|
12
18
|
title?: string;
|
|
13
19
|
/** API version string (e.g. '1.0.0'). Used in health check response. Default: '0.0.0' */
|
|
@@ -28,6 +34,12 @@ export interface ModularApiOptions {
|
|
|
28
34
|
* Default: LogLevel.info (emits emergency..info, suppresses debug).
|
|
29
35
|
*/
|
|
30
36
|
logLevel?: LogLevel;
|
|
37
|
+
/**
|
|
38
|
+
* Opt-in distributed tracing. Absent means off and costs nothing: no tracing
|
|
39
|
+
* middleware is installed and no span is ever created. The application supplies
|
|
40
|
+
* the tracer provider; the framework depends on `@opentelemetry/api` only.
|
|
41
|
+
*/
|
|
42
|
+
tracing?: TracingOptions;
|
|
31
43
|
/**
|
|
32
44
|
* OpenAPI `servers` list. Each entry has a `url` and optional `description`.
|
|
33
45
|
* When omitted, `serve()` generates `[{url: 'http://localhost:{port}'}]`.
|
|
@@ -64,6 +76,7 @@ export declare class ModularApi {
|
|
|
64
76
|
private readonly app;
|
|
65
77
|
private readonly rootRouter;
|
|
66
78
|
private readonly basePath;
|
|
79
|
+
private readonly jsonBodyLimit;
|
|
67
80
|
private readonly title;
|
|
68
81
|
private readonly version;
|
|
69
82
|
private readonly middlewares;
|
|
@@ -78,6 +91,8 @@ export declare class ModularApi {
|
|
|
78
91
|
private readonly httpRequestsInFlight?;
|
|
79
92
|
private readonly httpRequestDuration?;
|
|
80
93
|
private readonly logLevel;
|
|
94
|
+
/** Distributed tracing options, or undefined when tracing is off (ADR-0005). */
|
|
95
|
+
private readonly tracing?;
|
|
81
96
|
private readonly servers?;
|
|
82
97
|
private readonly graphql?;
|
|
83
98
|
/** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
|
package/dist/core/modular_api.js
CHANGED
|
@@ -14,6 +14,9 @@ const module_builder_1 = require("./module_builder");
|
|
|
14
14
|
const health_service_1 = require("./health/health_service");
|
|
15
15
|
const metric_registry_1 = require("./metrics/metric_registry");
|
|
16
16
|
const logging_middleware_1 = require("./logger/logging_middleware");
|
|
17
|
+
const api_1 = require("@opentelemetry/api");
|
|
18
|
+
const compositePropagator_1 = require("./tracing/compositePropagator");
|
|
19
|
+
const tracingMiddleware_1 = require("./tracing/tracingMiddleware");
|
|
17
20
|
const logger_1 = require("./logger/logger");
|
|
18
21
|
const body_parser_error_handler_1 = require("./body_parser_error_handler");
|
|
19
22
|
const unhandled_request_error_handler_1 = require("./unhandled_request_error_handler");
|
|
@@ -44,6 +47,7 @@ class ModularApi {
|
|
|
44
47
|
app;
|
|
45
48
|
rootRouter;
|
|
46
49
|
basePath;
|
|
50
|
+
jsonBodyLimit;
|
|
47
51
|
title;
|
|
48
52
|
version;
|
|
49
53
|
middlewares = [];
|
|
@@ -60,6 +64,8 @@ class ModularApi {
|
|
|
60
64
|
httpRequestDuration;
|
|
61
65
|
// Logging
|
|
62
66
|
logLevel;
|
|
67
|
+
/** Distributed tracing options, or undefined when tracing is off (ADR-0005). */
|
|
68
|
+
tracing;
|
|
63
69
|
// OpenAPI
|
|
64
70
|
servers;
|
|
65
71
|
graphql;
|
|
@@ -69,6 +75,7 @@ class ModularApi {
|
|
|
69
75
|
}
|
|
70
76
|
constructor(options = {}) {
|
|
71
77
|
this.basePath = options.basePath ?? '/api';
|
|
78
|
+
this.jsonBodyLimit = options.jsonBodyLimit ?? '100kb';
|
|
72
79
|
this.title = options.title ?? 'Modular API';
|
|
73
80
|
this.version = options.version ?? 'x.y.z';
|
|
74
81
|
this.healthService = new health_service_1.HealthService({
|
|
@@ -81,6 +88,7 @@ class ModularApi {
|
|
|
81
88
|
this.excludedMetricsRoutes = options.excludedMetricsRoutes ?? ['/metrics', '/health', '/docs'];
|
|
82
89
|
// Logging
|
|
83
90
|
this.logLevel = options.logLevel ?? logger_1.LogLevel.info;
|
|
91
|
+
this.tracing = options.tracing;
|
|
84
92
|
// OpenAPI servers
|
|
85
93
|
this.servers = options.servers;
|
|
86
94
|
this.graphql = options.graphql;
|
|
@@ -234,13 +242,46 @@ class ModularApi {
|
|
|
234
242
|
operationalPaths.openApiYamlPath,
|
|
235
243
|
...(operationalPaths.metricsPath ? [operationalPaths.metricsPath] : []),
|
|
236
244
|
];
|
|
245
|
+
// Tracing is the OUTERMOST middleware, with logging inside it (runbook D12 as
|
|
246
|
+
// reversed). The logger then runs within the span's active scope and reads
|
|
247
|
+
// `trace_id` and `span_id` from the ambient span on every line. An earlier design
|
|
248
|
+
// had this after logging, which forced the logger to own the trace id and the span
|
|
249
|
+
// to adopt it — and here that meant seeding a parent, whose trace flags made the
|
|
250
|
+
// default ParentBased sampler drop the span entirely.
|
|
251
|
+
//
|
|
252
|
+
// Absent options install nothing, which is what makes tracing free when it is off
|
|
253
|
+
// (gate G3).
|
|
254
|
+
const tracing = this.tracing;
|
|
255
|
+
if (tracing !== undefined) {
|
|
256
|
+
// Publish the chain as the global propagator, which is how satellite packages
|
|
257
|
+
// inject it. @macss/modular-api-rest-client does not depend on this package (D21),
|
|
258
|
+
// so it cannot reach our W3C propagator — and per the OpenTelemetry API's guidance
|
|
259
|
+
// it should not: instrumentation libraries read the global, the host sets it.
|
|
260
|
+
//
|
|
261
|
+
// That indirection also means whatever chain the application configured is honoured
|
|
262
|
+
// on outbound calls, including a Cloud Trace propagator it appended.
|
|
263
|
+
const propagators = tracing.policy.propagators;
|
|
264
|
+
if (propagators.length > 0) {
|
|
265
|
+
api_1.propagation.setGlobalPropagator(propagators.length === 1
|
|
266
|
+
? propagators[0]
|
|
267
|
+
: new compositePropagator_1.CompositeTextMapPropagator(propagators));
|
|
268
|
+
}
|
|
269
|
+
this.app.use((0, tracingMiddleware_1.tracingMiddleware)({
|
|
270
|
+
tracer: tracing.tracer,
|
|
271
|
+
policy: tracing.policy,
|
|
272
|
+
excludedRoutes: excludedLogRoutes,
|
|
273
|
+
}));
|
|
274
|
+
}
|
|
237
275
|
this.app.use((0, logging_middleware_1.loggingMiddleware)({
|
|
238
276
|
logLevel: this.logLevel,
|
|
239
277
|
serviceName: this.title,
|
|
240
278
|
excludedRoutes: excludedLogRoutes,
|
|
279
|
+
...(this.tracing?.traceFieldFormatter === undefined
|
|
280
|
+
? {}
|
|
281
|
+
: { traceFieldFormatter: this.tracing.traceFieldFormatter }),
|
|
241
282
|
}));
|
|
242
283
|
// Body parsing AFTER loggingMiddleware — SyntaxErrors now have trace_id.
|
|
243
|
-
this.app.use(express_1.default.json());
|
|
284
|
+
this.app.use(express_1.default.json({ limit: this.jsonBodyLimit }));
|
|
244
285
|
this.app.use(body_parser_error_handler_1.bodyParserErrorHandler);
|
|
245
286
|
pluginHost.applyMiddlewares('preRouting', this.app);
|
|
246
287
|
// Register middlewares before routes
|
|
@@ -266,7 +307,25 @@ class ModularApi {
|
|
|
266
307
|
resolve(server);
|
|
267
308
|
});
|
|
268
309
|
server.on('close', () => {
|
|
269
|
-
|
|
310
|
+
// Tracing's shutdown callback runs alongside the plugin host's, not as a plugin.
|
|
311
|
+
// There is deliberately no tracing plugin: every responsibility ADR-0005 decision
|
|
312
|
+
// 4 gave one was reassigned by a later decision, and what remained was a plugin
|
|
313
|
+
// whose setup() did nothing (see ADR-0005 A7).
|
|
314
|
+
//
|
|
315
|
+
// The framework owns the timing; the application owns the provider. A callback
|
|
316
|
+
// that rejects is swallowed — losing telemetry is bad, failing to stop is worse.
|
|
317
|
+
const onShutdown = this.tracing?.onShutdown;
|
|
318
|
+
void (async () => {
|
|
319
|
+
if (onShutdown !== undefined) {
|
|
320
|
+
try {
|
|
321
|
+
await onShutdown();
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
// Intentionally ignored.
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
await pluginHost.shutdown();
|
|
328
|
+
})();
|
|
270
329
|
});
|
|
271
330
|
});
|
|
272
331
|
}
|
|
@@ -11,9 +11,9 @@ export interface UseCaseOptions {
|
|
|
11
11
|
/** Override output schema for OpenAPI (if fromJson fails with empty data) */
|
|
12
12
|
outputSchema?: Record<string, unknown>;
|
|
13
13
|
/** Input class for pre-validation and schema extraction (enables strict fromJson). */
|
|
14
|
-
inputClass: abstract new (...args:
|
|
14
|
+
inputClass: abstract new (...args: never[]) => Input;
|
|
15
15
|
/** Output class for schema extraction. */
|
|
16
|
-
outputClass: abstract new (...args:
|
|
16
|
+
outputClass: abstract new (...args: never[]) => Output;
|
|
17
17
|
}
|
|
18
18
|
/**
|
|
19
19
|
* Fluent builder that registers use cases on a module-scoped Express Router.
|
|
@@ -57,5 +57,5 @@ export declare const Field: {
|
|
|
57
57
|
* Retrieves the `@Field` metadata registered on a class.
|
|
58
58
|
* Returns an empty array if the class has no decorated fields.
|
|
59
59
|
*/
|
|
60
|
-
export declare function getFieldMetadata(target: abstract new (...args:
|
|
60
|
+
export declare function getFieldMetadata(target: abstract new (...args: never[]) => unknown): FieldMeta[];
|
|
61
61
|
export {};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type Context, type TextMapGetter, type TextMapPropagator, type TextMapSetter } from '@opentelemetry/api';
|
|
2
|
+
/** The carrier key this propagator reads and writes. */
|
|
3
|
+
export declare const CLOUD_TRACE_CONTEXT_HEADER = "x-cloud-trace-context";
|
|
4
|
+
/**
|
|
5
|
+
* Propagates Google Cloud's legacy `X-Cloud-Trace-Context` header.
|
|
6
|
+
*
|
|
7
|
+
* The OTel API ships W3C `traceparent` and Baggage propagators but no Google
|
|
8
|
+
* Cloud propagator, so this one is ours. Cloud Run injects both headers; W3C is
|
|
9
|
+
* preferred and this is the documented fallback, which is why the precedence
|
|
10
|
+
* policy consults it second.
|
|
11
|
+
*
|
|
12
|
+
* Format: `TRACE_ID/SPAN_ID;o=OPTIONS`, where
|
|
13
|
+
*
|
|
14
|
+
* - `TRACE_ID` is 32 hex characters, case-insensitive per Google's docs;
|
|
15
|
+
* - **`SPAN_ID` is the decimal representation of an unsigned 64-bit integer** —
|
|
16
|
+
* not hex. Reading it as hex yields a wrong parent and a silently broken
|
|
17
|
+
* waterfall, which is the most likely defect in this file. JavaScript's Number
|
|
18
|
+
* cannot hold 2^64-1 either, so the conversion goes through BigInt.
|
|
19
|
+
* - `OPTIONS` carries `o=1` (parent sampled) or `o=0` (not sampled).
|
|
20
|
+
*
|
|
21
|
+
* Header-name casing is deliberately not this class's concern. HTTP header
|
|
22
|
+
* semantics belong to the carrier, so {@link fields} returns the lowercase
|
|
23
|
+
* canonical name and lookup goes through the supplied getter.
|
|
24
|
+
*
|
|
25
|
+
* The Dart counterpart is `lib/src/core/tracing/cloud_trace_propagator.dart`.
|
|
26
|
+
* Same behaviour; this version leans on `isValidTraceId` / `isValidSpanId`, which
|
|
27
|
+
* the JavaScript API provides and the Dart API does not.
|
|
28
|
+
*/
|
|
29
|
+
export declare class CloudTraceContextPropagator implements TextMapPropagator<unknown> {
|
|
30
|
+
fields(): string[];
|
|
31
|
+
inject(context: Context, carrier: unknown, setter: TextMapSetter<unknown>): void;
|
|
32
|
+
extract(context: Context, carrier: unknown, getter: TextMapGetter<unknown>): Context;
|
|
33
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CloudTraceContextPropagator = exports.CLOUD_TRACE_CONTEXT_HEADER = void 0;
|
|
4
|
+
const api_1 = require("@opentelemetry/api");
|
|
5
|
+
/** The carrier key this propagator reads and writes. */
|
|
6
|
+
exports.CLOUD_TRACE_CONTEXT_HEADER = 'x-cloud-trace-context';
|
|
7
|
+
const TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;
|
|
8
|
+
const DECIMAL_PATTERN = /^[0-9]+$/;
|
|
9
|
+
/** 2^64-1 — the span id is an unsigned 64-bit integer, so the bound is a BigInt. */
|
|
10
|
+
const MAX_UNSIGNED_64 = BigInt('0xffffffffffffffff');
|
|
11
|
+
/**
|
|
12
|
+
* Propagates Google Cloud's legacy `X-Cloud-Trace-Context` header.
|
|
13
|
+
*
|
|
14
|
+
* The OTel API ships W3C `traceparent` and Baggage propagators but no Google
|
|
15
|
+
* Cloud propagator, so this one is ours. Cloud Run injects both headers; W3C is
|
|
16
|
+
* preferred and this is the documented fallback, which is why the precedence
|
|
17
|
+
* policy consults it second.
|
|
18
|
+
*
|
|
19
|
+
* Format: `TRACE_ID/SPAN_ID;o=OPTIONS`, where
|
|
20
|
+
*
|
|
21
|
+
* - `TRACE_ID` is 32 hex characters, case-insensitive per Google's docs;
|
|
22
|
+
* - **`SPAN_ID` is the decimal representation of an unsigned 64-bit integer** —
|
|
23
|
+
* not hex. Reading it as hex yields a wrong parent and a silently broken
|
|
24
|
+
* waterfall, which is the most likely defect in this file. JavaScript's Number
|
|
25
|
+
* cannot hold 2^64-1 either, so the conversion goes through BigInt.
|
|
26
|
+
* - `OPTIONS` carries `o=1` (parent sampled) or `o=0` (not sampled).
|
|
27
|
+
*
|
|
28
|
+
* Header-name casing is deliberately not this class's concern. HTTP header
|
|
29
|
+
* semantics belong to the carrier, so {@link fields} returns the lowercase
|
|
30
|
+
* canonical name and lookup goes through the supplied getter.
|
|
31
|
+
*
|
|
32
|
+
* The Dart counterpart is `lib/src/core/tracing/cloud_trace_propagator.dart`.
|
|
33
|
+
* Same behaviour; this version leans on `isValidTraceId` / `isValidSpanId`, which
|
|
34
|
+
* the JavaScript API provides and the Dart API does not.
|
|
35
|
+
*/
|
|
36
|
+
class CloudTraceContextPropagator {
|
|
37
|
+
fields() {
|
|
38
|
+
return [exports.CLOUD_TRACE_CONTEXT_HEADER];
|
|
39
|
+
}
|
|
40
|
+
inject(context, carrier, setter) {
|
|
41
|
+
const spanContext = api_1.trace.getSpanContext(context);
|
|
42
|
+
if (spanContext === undefined)
|
|
43
|
+
return;
|
|
44
|
+
if (!(0, api_1.isValidTraceId)(spanContext.traceId) || !(0, api_1.isValidSpanId)(spanContext.spanId))
|
|
45
|
+
return;
|
|
46
|
+
// Back to decimal, which is what makes this header Google's and not W3C's.
|
|
47
|
+
const spanId = BigInt(`0x${spanContext.spanId}`).toString();
|
|
48
|
+
const option = (spanContext.traceFlags & api_1.TraceFlags.SAMPLED) === api_1.TraceFlags.SAMPLED ? '1' : '0';
|
|
49
|
+
setter.set(carrier, exports.CLOUD_TRACE_CONTEXT_HEADER, `${spanContext.traceId}/${spanId};o=${option}`);
|
|
50
|
+
}
|
|
51
|
+
extract(context, carrier, getter) {
|
|
52
|
+
// A malformed upstream header must never fail a request, so every exit
|
|
53
|
+
// returns the untouched context and the whole body is guarded.
|
|
54
|
+
try {
|
|
55
|
+
const raw = getter.get(carrier, exports.CLOUD_TRACE_CONTEXT_HEADER);
|
|
56
|
+
const value = Array.isArray(raw) ? raw[0] : raw;
|
|
57
|
+
if (typeof value !== 'string' || value.length === 0)
|
|
58
|
+
return context;
|
|
59
|
+
const separator = value.indexOf('/');
|
|
60
|
+
if (separator <= 0)
|
|
61
|
+
return context;
|
|
62
|
+
// Google documents the trace id as case-insensitive hex; W3C requires
|
|
63
|
+
// lowercase. Normalising here is the deliberate asymmetry.
|
|
64
|
+
const traceId = value.slice(0, separator).toLowerCase();
|
|
65
|
+
if (!TRACE_ID_PATTERN.test(traceId) || !(0, api_1.isValidTraceId)(traceId))
|
|
66
|
+
return context;
|
|
67
|
+
let remainder = value.slice(separator + 1);
|
|
68
|
+
let sampled = false;
|
|
69
|
+
const optionsAt = remainder.indexOf(';');
|
|
70
|
+
if (optionsAt >= 0) {
|
|
71
|
+
sampled = isSampled(remainder.slice(optionsAt + 1));
|
|
72
|
+
remainder = remainder.slice(0, optionsAt);
|
|
73
|
+
}
|
|
74
|
+
if (!DECIMAL_PATTERN.test(remainder))
|
|
75
|
+
return context;
|
|
76
|
+
const spanIdValue = BigInt(remainder);
|
|
77
|
+
if (spanIdValue <= 0n || spanIdValue > MAX_UNSIGNED_64)
|
|
78
|
+
return context;
|
|
79
|
+
const spanId = spanIdValue.toString(16).padStart(16, '0');
|
|
80
|
+
if (!(0, api_1.isValidSpanId)(spanId))
|
|
81
|
+
return context;
|
|
82
|
+
return api_1.trace.setSpanContext(context, {
|
|
83
|
+
traceId,
|
|
84
|
+
spanId,
|
|
85
|
+
traceFlags: sampled ? api_1.TraceFlags.SAMPLED : api_1.TraceFlags.NONE,
|
|
86
|
+
isRemote: true,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return context;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
exports.CloudTraceContextPropagator = CloudTraceContextPropagator;
|
|
95
|
+
/** Reads the `o=` option, tolerating other options alongside it. */
|
|
96
|
+
function isSampled(options) {
|
|
97
|
+
for (const option of options.split(';')) {
|
|
98
|
+
const trimmed = option.trim();
|
|
99
|
+
if (trimmed.startsWith('o='))
|
|
100
|
+
return trimmed.slice(2) === '1';
|
|
101
|
+
}
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Context, TextMapGetter, TextMapPropagator, TextMapSetter } from '@opentelemetry/api';
|
|
2
|
+
/**
|
|
3
|
+
* Combines several propagators into one, for publishing as the global propagator.
|
|
4
|
+
*
|
|
5
|
+
* `@opentelemetry/core` ships a `CompositePropagator`, and this exists because core may not
|
|
6
|
+
* depend on it: that package is past the API boundary ADR-0005 A2 draws, and the Stage 1b
|
|
7
|
+
* dependency guard names it explicitly. Dart needs no equivalent — its OpenTelemetry API
|
|
8
|
+
* provides `OTelAPI.compositePropagator` directly, one of several places where the Dart API
|
|
9
|
+
* is the richer of the three.
|
|
10
|
+
*
|
|
11
|
+
* Injection runs every propagator, so an outbound call can carry both `traceparent` and a
|
|
12
|
+
* vendor header when the application asked for that. Extraction stops at the first
|
|
13
|
+
* propagator that yields a valid span context, which is the precedence
|
|
14
|
+
* {@link PropagationPolicy} defines — and why extraction here is a fallback rather than the
|
|
15
|
+
* main path: the host resolves inbound context through the policy, not through this.
|
|
16
|
+
*/
|
|
17
|
+
export declare class CompositeTextMapPropagator implements TextMapPropagator<unknown> {
|
|
18
|
+
private readonly propagators;
|
|
19
|
+
constructor(propagators: readonly TextMapPropagator<unknown>[]);
|
|
20
|
+
fields(): string[];
|
|
21
|
+
inject(context: Context, carrier: unknown, setter: TextMapSetter<unknown>): void;
|
|
22
|
+
extract(context: Context, carrier: unknown, getter: TextMapGetter<unknown>): Context;
|
|
23
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CompositeTextMapPropagator = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Combines several propagators into one, for publishing as the global propagator.
|
|
6
|
+
*
|
|
7
|
+
* `@opentelemetry/core` ships a `CompositePropagator`, and this exists because core may not
|
|
8
|
+
* depend on it: that package is past the API boundary ADR-0005 A2 draws, and the Stage 1b
|
|
9
|
+
* dependency guard names it explicitly. Dart needs no equivalent — its OpenTelemetry API
|
|
10
|
+
* provides `OTelAPI.compositePropagator` directly, one of several places where the Dart API
|
|
11
|
+
* is the richer of the three.
|
|
12
|
+
*
|
|
13
|
+
* Injection runs every propagator, so an outbound call can carry both `traceparent` and a
|
|
14
|
+
* vendor header when the application asked for that. Extraction stops at the first
|
|
15
|
+
* propagator that yields a valid span context, which is the precedence
|
|
16
|
+
* {@link PropagationPolicy} defines — and why extraction here is a fallback rather than the
|
|
17
|
+
* main path: the host resolves inbound context through the policy, not through this.
|
|
18
|
+
*/
|
|
19
|
+
class CompositeTextMapPropagator {
|
|
20
|
+
propagators;
|
|
21
|
+
constructor(propagators) {
|
|
22
|
+
this.propagators = propagators;
|
|
23
|
+
}
|
|
24
|
+
fields() {
|
|
25
|
+
return [...new Set(this.propagators.flatMap((propagator) => propagator.fields()))];
|
|
26
|
+
}
|
|
27
|
+
inject(context, carrier, setter) {
|
|
28
|
+
for (const propagator of this.propagators) {
|
|
29
|
+
try {
|
|
30
|
+
propagator.inject(context, carrier, setter);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// A third-party propagator is not our code. One misbehaving entry must not fail an
|
|
34
|
+
// outbound request; the rest still get their headers on.
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
extract(context, carrier, getter) {
|
|
39
|
+
for (const propagator of this.propagators) {
|
|
40
|
+
try {
|
|
41
|
+
const extracted = propagator.extract(context, carrier, getter);
|
|
42
|
+
if (extracted !== context)
|
|
43
|
+
return extracted;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return context;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
exports.CompositeTextMapPropagator = CompositeTextMapPropagator;
|