@leoribeiroweb/nest-tracing 0.0.0-stage → 0.0.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/README.md +102 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.js +16 -0
- package/dist/sdk-options.d.ts +29 -0
- package/dist/sdk-options.js +104 -0
- package/dist/start-tracing.d.ts +49 -0
- package/dist/start-tracing.js +76 -0
- package/dist/tracing-config.d.ts +40 -0
- package/dist/tracing-config.js +40 -0
- package/dist/tracing-env.d.ts +19 -0
- package/dist/tracing-env.js +18 -0
- package/package.json +53 -4
package/README.md
CHANGED
|
@@ -1,3 +1,103 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @leoribeiroweb/nest-tracing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The OpenTelemetry SDK bootstrap every NestJS service of the platform ran from its own copy of
|
|
4
|
+
`src/instrumentation.ts`: traces only, OTLP over HTTP through the core package's
|
|
5
|
+
`RedactingSpanExporter`, parent-based ratio sampling, probe and scrape paths ignored, and
|
|
6
|
+
database, cache and outbound spans recorded only under a parent.
|
|
7
|
+
|
|
8
|
+
This package is part of the shared framework behind my own services. It is published publicly
|
|
9
|
+
so builds need no registry credentials, but it is **not an open-source project**: there is no
|
|
10
|
+
support commitment, and the API changes to suit the services that consume it. Pin a major
|
|
11
|
+
version.
|
|
12
|
+
|
|
13
|
+
## Requirements
|
|
14
|
+
|
|
15
|
+
Peers, never dependencies. A second copy of the core package would split the tracing registry,
|
|
16
|
+
so the SDK started here would be registered where `TracingShutdownService` never looks; a
|
|
17
|
+
second copy of an OpenTelemetry package would split the global tracer provider.
|
|
18
|
+
|
|
19
|
+
| Peer | Range |
|
|
20
|
+
| --- | --- |
|
|
21
|
+
| `@leoribeiroweb/nest-core` | `>=0.9.0 <1.0.0` (0.9.0 is the first release with the `./tracing` subpath) |
|
|
22
|
+
| `@opentelemetry/sdk-node` | `^0.222.0` |
|
|
23
|
+
| `@opentelemetry/auto-instrumentations-node` | `^0.80.0` |
|
|
24
|
+
| `@opentelemetry/exporter-trace-otlp-proto` | `^0.222.0` |
|
|
25
|
+
| `@opentelemetry/sdk-trace-base` | `^2.11.0` |
|
|
26
|
+
| `@opentelemetry/resources` | `^2.11.0` |
|
|
27
|
+
| `@opentelemetry/semantic-conventions` | `^1.43.0` |
|
|
28
|
+
|
|
29
|
+
## Use
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
// src/instrumentation.ts — the first import of main.ts
|
|
33
|
+
import { startTracing } from '@leoribeiroweb/nest-tracing';
|
|
34
|
+
|
|
35
|
+
startTracing({ serviceName: 'affiliate-api' });
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
// src/main.ts
|
|
40
|
+
import './instrumentation';
|
|
41
|
+
// ...everything else
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The first import matters: auto-instrumentation patches `http`, `mongodb`/`mongoose` and
|
|
45
|
+
`ioredis` only if they are required after `startTracing()` runs. Importing this package loads
|
|
46
|
+
neither `http` nor `axios` nor any SDK package (`src/import-closure.spec.ts`): it reaches the
|
|
47
|
+
core only through `@leoribeiroweb/nest-core/tracing`, and requires the SDK packages inside
|
|
48
|
+
`startTracing`, only when tracing is on.
|
|
49
|
+
|
|
50
|
+
`startTracing` makes both registrations of the core package, so `instrumentation.ts` needs no
|
|
51
|
+
other line:
|
|
52
|
+
|
|
53
|
+
- `registerTracingServiceName(OTEL_SERVICE_NAME ?? serviceName)`, always, before the SDK, so
|
|
54
|
+
`runInRootSpan` names its tracer `<service>.background-jobs` on the tracing-off paths too.
|
|
55
|
+
- `registerTracingSdk(sdk)`, with `null` when tracing is off, so `TracingShutdownService`
|
|
56
|
+
flushes the last spans during the graceful shutdown.
|
|
57
|
+
|
|
58
|
+
It returns the started `NodeSDK`, or `null`.
|
|
59
|
+
|
|
60
|
+
## Options
|
|
61
|
+
|
|
62
|
+
| Option | Default | Effect |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| `serviceName` | required | `service.name` of the spans, unless `OTEL_SERVICE_NAME` is set |
|
|
65
|
+
| `env` | `readTracingEnv()` (`process.env`) | The variables below |
|
|
66
|
+
| `ignoredPaths` | `DEFAULT_IGNORED_PATHS`: `/metrics`, `/health`, `/health/ready`, `/health/live` | Inbound paths never traced, query string ignored. Replaces the default; spread `DEFAULT_IGNORED_PATHS` to extend it |
|
|
67
|
+
| `instrumentations` | none | Per-instrumentation overrides for `getNodeAutoInstrumentations`, merged field by field over the defaults below |
|
|
68
|
+
|
|
69
|
+
## Environment
|
|
70
|
+
|
|
71
|
+
| Variable | Effect |
|
|
72
|
+
| --- | --- |
|
|
73
|
+
| `OTEL_EXPORTER_OTLP_ENDPOINT` | Collector base URL; spans go to `<endpoint>/v1/traces`. Unset or empty: tracing off (local dev, tests, CronJob pods) |
|
|
74
|
+
| `OTEL_SDK_DISABLED` | `true` turns tracing off even with an endpoint |
|
|
75
|
+
| `OTEL_TRACES_SAMPLER_ARG` | Root sampling ratio in `[0, 1]`; anything else samples everything |
|
|
76
|
+
| `OTEL_SERVICE_NAME` | Overrides `serviceName` |
|
|
77
|
+
|
|
78
|
+
## What the SDK is given
|
|
79
|
+
|
|
80
|
+
- **Traces only.** `metricReaders: []` and `logRecordProcessors: []`: left out, `NodeSDK` falls
|
|
81
|
+
back to an OTLP metric reader and a logs pipeline.
|
|
82
|
+
- **Exporter:** `new RedactingSpanExporter(new OTLPTraceExporter({ url }))` from the core
|
|
83
|
+
package, which masks URL secrets and personal identifiers on every span.
|
|
84
|
+
- **Sampler:** `ParentBasedSampler` with a `TraceIdRatioBasedSampler` root.
|
|
85
|
+
- **Auto-instrumentations** (`defaultInstrumentationConfig(ignoredPaths)`):
|
|
86
|
+
- off: `fs`, `dns`, `net`, `runtime-node`, `winston`, `pino`, `bunyan`;
|
|
87
|
+
- parent required: `mongodb` (with `enhancedDatabaseReporting: false`, so filter values are
|
|
88
|
+
never exported), `mongoose`, `ioredis` (statement reduced to the command name), `undici`,
|
|
89
|
+
outbound `http`;
|
|
90
|
+
- `http` ignores the inbound requests on `ignoredPaths`.
|
|
91
|
+
|
|
92
|
+
## Lower-level functions
|
|
93
|
+
|
|
94
|
+
For a consumer that needs one step on its own, and for tests:
|
|
95
|
+
|
|
96
|
+
- `readTracingEnv()` reads the four variables.
|
|
97
|
+
- `buildTracingConfig(env, { serviceName, ignoredPaths?, instrumentations? })` returns the
|
|
98
|
+
configuration, or `null` when tracing is off.
|
|
99
|
+
- `buildSdkOptions(config, deps)` returns the `NodeSDK` options. `deps` are the OTel
|
|
100
|
+
constructors (`TracingSdkDeps`), so it runs with fakes.
|
|
101
|
+
- `loadSdkPackages()` requires the real SDK packages; `startTracing(options, loadSdk?)` takes a
|
|
102
|
+
replacement for tests.
|
|
103
|
+
- `mergeInstrumentationConfig(defaults, overrides)` is the merge `instrumentations` goes through.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { readTracingEnv, type TracingEnv } from './tracing-env';
|
|
2
|
+
export { DEFAULT_IGNORED_PATHS, buildTracingConfig, resolveServiceName, type TracingConfig, type TracingOptions, } from './tracing-config';
|
|
3
|
+
export { buildSdkOptions, defaultInstrumentationConfig, mergeInstrumentationConfig, type TracingSdkDeps, } from './sdk-options';
|
|
4
|
+
export { loadSdkPackages, startTracing, type StartTracingOptions, type TracingSdkPackages, } from './start-tracing';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.startTracing = exports.loadSdkPackages = exports.mergeInstrumentationConfig = exports.defaultInstrumentationConfig = exports.buildSdkOptions = exports.resolveServiceName = exports.buildTracingConfig = exports.DEFAULT_IGNORED_PATHS = exports.readTracingEnv = void 0;
|
|
4
|
+
var tracing_env_1 = require("./tracing-env");
|
|
5
|
+
Object.defineProperty(exports, "readTracingEnv", { enumerable: true, get: function () { return tracing_env_1.readTracingEnv; } });
|
|
6
|
+
var tracing_config_1 = require("./tracing-config");
|
|
7
|
+
Object.defineProperty(exports, "DEFAULT_IGNORED_PATHS", { enumerable: true, get: function () { return tracing_config_1.DEFAULT_IGNORED_PATHS; } });
|
|
8
|
+
Object.defineProperty(exports, "buildTracingConfig", { enumerable: true, get: function () { return tracing_config_1.buildTracingConfig; } });
|
|
9
|
+
Object.defineProperty(exports, "resolveServiceName", { enumerable: true, get: function () { return tracing_config_1.resolveServiceName; } });
|
|
10
|
+
var sdk_options_1 = require("./sdk-options");
|
|
11
|
+
Object.defineProperty(exports, "buildSdkOptions", { enumerable: true, get: function () { return sdk_options_1.buildSdkOptions; } });
|
|
12
|
+
Object.defineProperty(exports, "defaultInstrumentationConfig", { enumerable: true, get: function () { return sdk_options_1.defaultInstrumentationConfig; } });
|
|
13
|
+
Object.defineProperty(exports, "mergeInstrumentationConfig", { enumerable: true, get: function () { return sdk_options_1.mergeInstrumentationConfig; } });
|
|
14
|
+
var start_tracing_1 = require("./start-tracing");
|
|
15
|
+
Object.defineProperty(exports, "loadSdkPackages", { enumerable: true, get: function () { return start_tracing_1.loadSdkPackages; } });
|
|
16
|
+
Object.defineProperty(exports, "startTracing", { enumerable: true, get: function () { return start_tracing_1.startTracing; } });
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { InstrumentationConfigMap } from '@opentelemetry/auto-instrumentations-node';
|
|
2
|
+
import type { NodeSDKConfiguration } from '@opentelemetry/sdk-node';
|
|
3
|
+
import type { TracingConfig } from './tracing-config';
|
|
4
|
+
/**
|
|
5
|
+
* The OTel values `buildSdkOptions` needs, passed in rather than imported at
|
|
6
|
+
* the top of this module: `startTracing` requires the SDK packages only once
|
|
7
|
+
* it knows tracing is on, and `buildSdkOptions` stays a pure function
|
|
8
|
+
* testable with plain fakes.
|
|
9
|
+
*/
|
|
10
|
+
export interface TracingSdkDeps {
|
|
11
|
+
getNodeAutoInstrumentations: typeof import('@opentelemetry/auto-instrumentations-node').getNodeAutoInstrumentations;
|
|
12
|
+
OTLPTraceExporter: typeof import('@opentelemetry/exporter-trace-otlp-proto').OTLPTraceExporter;
|
|
13
|
+
ParentBasedSampler: typeof import('@opentelemetry/sdk-trace-base').ParentBasedSampler;
|
|
14
|
+
TraceIdRatioBasedSampler: typeof import('@opentelemetry/sdk-trace-base').TraceIdRatioBasedSampler;
|
|
15
|
+
resourceFromAttributes: typeof import('@opentelemetry/resources').resourceFromAttributes;
|
|
16
|
+
ATTR_SERVICE_NAME: typeof import('@opentelemetry/semantic-conventions').ATTR_SERVICE_NAME;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The auto-instrumentation settings of the three service copies, identical in
|
|
20
|
+
* all three. `ignoredPaths` feeds the inbound HTTP hook.
|
|
21
|
+
*/
|
|
22
|
+
export declare function defaultInstrumentationConfig(ignoredPaths: readonly string[]): InstrumentationConfigMap;
|
|
23
|
+
/**
|
|
24
|
+
* The defaults with the consumer's overrides merged key by key: an override
|
|
25
|
+
* replaces only the fields it names, and a key absent from the defaults is
|
|
26
|
+
* added as given.
|
|
27
|
+
*/
|
|
28
|
+
export declare function mergeInstrumentationConfig(defaults: InstrumentationConfigMap, overrides: InstrumentationConfigMap): InstrumentationConfigMap;
|
|
29
|
+
export declare function buildSdkOptions(config: TracingConfig, deps: TracingSdkDeps): Partial<NodeSDKConfiguration>;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.defaultInstrumentationConfig = defaultInstrumentationConfig;
|
|
4
|
+
exports.mergeInstrumentationConfig = mergeInstrumentationConfig;
|
|
5
|
+
exports.buildSdkOptions = buildSdkOptions;
|
|
6
|
+
const tracing_1 = require("@leoribeiroweb/nest-core/tracing");
|
|
7
|
+
/**
|
|
8
|
+
* The auto-instrumentation settings of the three service copies, identical in
|
|
9
|
+
* all three. `ignoredPaths` feeds the inbound HTTP hook.
|
|
10
|
+
*/
|
|
11
|
+
function defaultInstrumentationConfig(ignoredPaths) {
|
|
12
|
+
return {
|
|
13
|
+
// fs and dns spans are noise at our volume and cost Tempo bytes.
|
|
14
|
+
'@opentelemetry/instrumentation-fs': { enabled: false },
|
|
15
|
+
'@opentelemetry/instrumentation-dns': { enabled: false },
|
|
16
|
+
'@opentelemetry/instrumentation-net': { enabled: false },
|
|
17
|
+
// Bundled runtime metrics (event loop lag, GC, heap). The SDK is
|
|
18
|
+
// traces-only — `metricReaders` is empty — so nothing would report them.
|
|
19
|
+
'@opentelemetry/instrumentation-runtime-node': { enabled: false },
|
|
20
|
+
// The log format is frozen (logfmt via the core package's structured
|
|
21
|
+
// logger). No service uses winston, pino or bunyan; their log-correlation
|
|
22
|
+
// injection is disabled so a future transitive dependency on one of them
|
|
23
|
+
// can never silently alter log output.
|
|
24
|
+
'@opentelemetry/instrumentation-winston': { enabled: false },
|
|
25
|
+
'@opentelemetry/instrumentation-pino': { enabled: false },
|
|
26
|
+
'@opentelemetry/instrumentation-bunyan': { enabled: false },
|
|
27
|
+
// Root spans come only from inbound HTTP requests and from the background
|
|
28
|
+
// jobs wrapped in the core package's `runInRootSpan`. Without a parent
|
|
29
|
+
// requirement, every @Interval/@Cron tick and BullMQ worker poll would
|
|
30
|
+
// export its Mongo queries, Redis commands and outbound calls as a
|
|
31
|
+
// stand-alone root trace — most of the trace volume, none of it attached
|
|
32
|
+
// to a request. mongodb and ioredis already default to true; it is pinned
|
|
33
|
+
// so an upstream default change cannot silently undo it.
|
|
34
|
+
//
|
|
35
|
+
// `enhancedDatabaseReporting` off (also the default, pinned): with it on,
|
|
36
|
+
// `db.query.text` carries filter and update VALUES — a taker's document or
|
|
37
|
+
// e-mail in an NFS-e query. Off, the default serializer replaces every
|
|
38
|
+
// value with `?`. No `dbStatementSerializer` is set on mongodb or mongoose,
|
|
39
|
+
// for the same reason.
|
|
40
|
+
'@opentelemetry/instrumentation-mongodb': {
|
|
41
|
+
requireParentSpan: true,
|
|
42
|
+
enhancedDatabaseReporting: false,
|
|
43
|
+
},
|
|
44
|
+
'@opentelemetry/instrumentation-mongoose': { requireParentSpan: true },
|
|
45
|
+
// Command name only. The default serializer writes every argument of
|
|
46
|
+
// EVAL/EVALSHA and the key of most commands, so Lua script calls would
|
|
47
|
+
// export their payloads: prompt text, BullMQ job data and job ids that
|
|
48
|
+
// embed personal identifiers.
|
|
49
|
+
'@opentelemetry/instrumentation-ioredis': {
|
|
50
|
+
requireParentSpan: true,
|
|
51
|
+
dbStatementSerializer: (cmdName) => cmdName,
|
|
52
|
+
},
|
|
53
|
+
'@opentelemetry/instrumentation-undici': {
|
|
54
|
+
requireParentforSpans: true,
|
|
55
|
+
},
|
|
56
|
+
'@opentelemetry/instrumentation-http': {
|
|
57
|
+
requireParentforOutgoingSpans: true,
|
|
58
|
+
// An ignored request runs its handler under a suppressed tracing context
|
|
59
|
+
// (instrumentation-http `http.js:309-314`), so the Mongo queries a
|
|
60
|
+
// /metrics collector runs are not traced either.
|
|
61
|
+
ignoreIncomingRequestHook: (req) => ignoredPaths.includes((req.url ?? '').split('?')[0]),
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The defaults with the consumer's overrides merged key by key: an override
|
|
67
|
+
* replaces only the fields it names, and a key absent from the defaults is
|
|
68
|
+
* added as given.
|
|
69
|
+
*/
|
|
70
|
+
function mergeInstrumentationConfig(defaults, overrides) {
|
|
71
|
+
const merged = { ...defaults };
|
|
72
|
+
for (const [name, override] of Object.entries(overrides)) {
|
|
73
|
+
if (override === undefined)
|
|
74
|
+
continue;
|
|
75
|
+
merged[name] = { ...(merged[name] ?? {}), ...override };
|
|
76
|
+
}
|
|
77
|
+
return merged;
|
|
78
|
+
}
|
|
79
|
+
function buildSdkOptions(config, deps) {
|
|
80
|
+
return {
|
|
81
|
+
resource: deps.resourceFromAttributes({
|
|
82
|
+
[deps.ATTR_SERVICE_NAME]: config.serviceName,
|
|
83
|
+
}),
|
|
84
|
+
// Every span leaves the process through this wrapper, which masks URL
|
|
85
|
+
// secrets and personal identifiers (see the core package's
|
|
86
|
+
// redacting-span-exporter.ts).
|
|
87
|
+
traceExporter: new tracing_1.RedactingSpanExporter(new deps.OTLPTraceExporter({
|
|
88
|
+
url: `${config.endpoint}/v1/traces`,
|
|
89
|
+
})),
|
|
90
|
+
sampler: new deps.ParentBasedSampler({
|
|
91
|
+
root: new deps.TraceIdRatioBasedSampler(config.sampleRatio),
|
|
92
|
+
}),
|
|
93
|
+
// Traces only. Without these two, NodeSDK falls back to its own defaults
|
|
94
|
+
// — an OTLP metric reader and a logs pipeline — whenever no explicit
|
|
95
|
+
// override is given: every pod would push runtime, http and mongodb-pool
|
|
96
|
+
// metric series every 60s and stand up a global LoggerProvider. Empty
|
|
97
|
+
// arrays, not omitted keys: omission is what re-enables the defaults.
|
|
98
|
+
metricReaders: [],
|
|
99
|
+
logRecordProcessors: [],
|
|
100
|
+
instrumentations: [
|
|
101
|
+
deps.getNodeAutoInstrumentations(mergeInstrumentationConfig(defaultInstrumentationConfig(config.ignoredPaths), config.instrumentations)),
|
|
102
|
+
],
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { NodeSDK } from '@opentelemetry/sdk-node';
|
|
2
|
+
import { type TracingSdkDeps } from './sdk-options';
|
|
3
|
+
import { type TracingOptions } from './tracing-config';
|
|
4
|
+
import { type TracingEnv } from './tracing-env';
|
|
5
|
+
export interface StartTracingOptions extends TracingOptions {
|
|
6
|
+
/** The variables to read. Unset: {@link readTracingEnv}, that is `process.env`. */
|
|
7
|
+
env?: TracingEnv;
|
|
8
|
+
}
|
|
9
|
+
/** The SDK packages, required only once tracing is known to be on. */
|
|
10
|
+
export interface TracingSdkPackages extends TracingSdkDeps {
|
|
11
|
+
NodeSDK: typeof NodeSDK;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Requires the six OpenTelemetry packages. Lazily, from inside a function, so
|
|
15
|
+
* that importing this package — which an `instrumentation.ts` does before the
|
|
16
|
+
* SDK patches anything — never loads `@opentelemetry/auto-instrumentations-node`
|
|
17
|
+
* and its dependency graph where tracing is off (tests, local dev, CronJobs).
|
|
18
|
+
* One of its bundled instrumentations (`instrumentation-amqplib`) ships a
|
|
19
|
+
* compiled `require('../src/semconv-obsolete')` that collides with an
|
|
20
|
+
* unanchored `"src/(.*)"` jest `moduleNameMapper`, which every service has.
|
|
21
|
+
*/
|
|
22
|
+
export declare function loadSdkPackages(): TracingSdkPackages;
|
|
23
|
+
/**
|
|
24
|
+
* Starts the OpenTelemetry SDK when `OTEL_EXPORTER_OTLP_ENDPOINT` is set and
|
|
25
|
+
* `OTEL_SDK_DISABLED` is not `'true'`; returns the started SDK, or `null`.
|
|
26
|
+
*
|
|
27
|
+
* Call it from the service's `instrumentation.ts`, the first import of
|
|
28
|
+
* `main.ts`, so auto-instrumentation patches `http`, `mongodb`/`mongoose` and
|
|
29
|
+
* `ioredis` before anything else requires them:
|
|
30
|
+
*
|
|
31
|
+
* ```ts
|
|
32
|
+
* // src/instrumentation.ts
|
|
33
|
+
* import { startTracing } from '@leoribeiroweb/nest-tracing';
|
|
34
|
+
* startTracing({ serviceName: 'affiliate-api' });
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* Both registrations of the core package happen here, so the consumer makes
|
|
38
|
+
* neither:
|
|
39
|
+
*
|
|
40
|
+
* - `registerTracingServiceName` — always, before the SDK, with
|
|
41
|
+
* `OTEL_SERVICE_NAME` or `serviceName`. `runInRootSpan` names its tracer
|
|
42
|
+
* `<service>.background-jobs` on every path, the tracing-off ones included.
|
|
43
|
+
* - `registerTracingSdk` — with the SDK, or `null` when tracing is off, so
|
|
44
|
+
* `TracingShutdownService` flushes the spans ended since the last export
|
|
45
|
+
* during the graceful shutdown.
|
|
46
|
+
*
|
|
47
|
+
* `loadSdk` is a test seam: the default requires the real packages.
|
|
48
|
+
*/
|
|
49
|
+
export declare function startTracing(options: StartTracingOptions, loadSdk?: () => TracingSdkPackages): NodeSDK | null;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.loadSdkPackages = loadSdkPackages;
|
|
4
|
+
exports.startTracing = startTracing;
|
|
5
|
+
const tracing_1 = require("@leoribeiroweb/nest-core/tracing");
|
|
6
|
+
const sdk_options_1 = require("./sdk-options");
|
|
7
|
+
const tracing_config_1 = require("./tracing-config");
|
|
8
|
+
const tracing_env_1 = require("./tracing-env");
|
|
9
|
+
/**
|
|
10
|
+
* Requires the six OpenTelemetry packages. Lazily, from inside a function, so
|
|
11
|
+
* that importing this package — which an `instrumentation.ts` does before the
|
|
12
|
+
* SDK patches anything — never loads `@opentelemetry/auto-instrumentations-node`
|
|
13
|
+
* and its dependency graph where tracing is off (tests, local dev, CronJobs).
|
|
14
|
+
* One of its bundled instrumentations (`instrumentation-amqplib`) ships a
|
|
15
|
+
* compiled `require('../src/semconv-obsolete')` that collides with an
|
|
16
|
+
* unanchored `"src/(.*)"` jest `moduleNameMapper`, which every service has.
|
|
17
|
+
*/
|
|
18
|
+
function loadSdkPackages() {
|
|
19
|
+
/* eslint-disable @typescript-eslint/no-require-imports */
|
|
20
|
+
const { NodeSDK: NodeSDKCtor } = require('@opentelemetry/sdk-node');
|
|
21
|
+
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
|
|
22
|
+
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-proto');
|
|
23
|
+
const { ParentBasedSampler, TraceIdRatioBasedSampler } = require('@opentelemetry/sdk-trace-base');
|
|
24
|
+
const { resourceFromAttributes } = require('@opentelemetry/resources');
|
|
25
|
+
const { ATTR_SERVICE_NAME } = require('@opentelemetry/semantic-conventions');
|
|
26
|
+
/* eslint-enable @typescript-eslint/no-require-imports */
|
|
27
|
+
return {
|
|
28
|
+
NodeSDK: NodeSDKCtor,
|
|
29
|
+
getNodeAutoInstrumentations,
|
|
30
|
+
OTLPTraceExporter,
|
|
31
|
+
ParentBasedSampler,
|
|
32
|
+
TraceIdRatioBasedSampler,
|
|
33
|
+
resourceFromAttributes,
|
|
34
|
+
ATTR_SERVICE_NAME,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Starts the OpenTelemetry SDK when `OTEL_EXPORTER_OTLP_ENDPOINT` is set and
|
|
39
|
+
* `OTEL_SDK_DISABLED` is not `'true'`; returns the started SDK, or `null`.
|
|
40
|
+
*
|
|
41
|
+
* Call it from the service's `instrumentation.ts`, the first import of
|
|
42
|
+
* `main.ts`, so auto-instrumentation patches `http`, `mongodb`/`mongoose` and
|
|
43
|
+
* `ioredis` before anything else requires them:
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* // src/instrumentation.ts
|
|
47
|
+
* import { startTracing } from '@leoribeiroweb/nest-tracing';
|
|
48
|
+
* startTracing({ serviceName: 'affiliate-api' });
|
|
49
|
+
* ```
|
|
50
|
+
*
|
|
51
|
+
* Both registrations of the core package happen here, so the consumer makes
|
|
52
|
+
* neither:
|
|
53
|
+
*
|
|
54
|
+
* - `registerTracingServiceName` — always, before the SDK, with
|
|
55
|
+
* `OTEL_SERVICE_NAME` or `serviceName`. `runInRootSpan` names its tracer
|
|
56
|
+
* `<service>.background-jobs` on every path, the tracing-off ones included.
|
|
57
|
+
* - `registerTracingSdk` — with the SDK, or `null` when tracing is off, so
|
|
58
|
+
* `TracingShutdownService` flushes the spans ended since the last export
|
|
59
|
+
* during the graceful shutdown.
|
|
60
|
+
*
|
|
61
|
+
* `loadSdk` is a test seam: the default requires the real packages.
|
|
62
|
+
*/
|
|
63
|
+
function startTracing(options, loadSdk = loadSdkPackages) {
|
|
64
|
+
const env = options.env ?? (0, tracing_env_1.readTracingEnv)();
|
|
65
|
+
(0, tracing_1.registerTracingServiceName)((0, tracing_config_1.resolveServiceName)(env, options.serviceName));
|
|
66
|
+
const config = (0, tracing_config_1.buildTracingConfig)(env, options);
|
|
67
|
+
if (!config) {
|
|
68
|
+
(0, tracing_1.registerTracingSdk)(null);
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
const { NodeSDK: NodeSDKCtor, ...deps } = loadSdk();
|
|
72
|
+
const sdk = new NodeSDKCtor((0, sdk_options_1.buildSdkOptions)(config, deps));
|
|
73
|
+
sdk.start();
|
|
74
|
+
(0, tracing_1.registerTracingSdk)(sdk);
|
|
75
|
+
return sdk;
|
|
76
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { InstrumentationConfigMap } from '@opentelemetry/auto-instrumentations-node';
|
|
2
|
+
import type { TracingEnv } from './tracing-env';
|
|
3
|
+
/**
|
|
4
|
+
* Probe and scrape traffic is noise: it never carries a user request and
|
|
5
|
+
* would otherwise be billed as App O11y host-hours on every health check and
|
|
6
|
+
* Prometheus scrape. The list every service used.
|
|
7
|
+
*/
|
|
8
|
+
export declare const DEFAULT_IGNORED_PATHS: readonly string[];
|
|
9
|
+
/** What the consumer says about itself; everything else comes from the environment. */
|
|
10
|
+
export interface TracingOptions {
|
|
11
|
+
/** The span resource's `service.name`, unless `OTEL_SERVICE_NAME` is set. */
|
|
12
|
+
serviceName: string;
|
|
13
|
+
/**
|
|
14
|
+
* Inbound request paths never traced (query string ignored). Replaces
|
|
15
|
+
* {@link DEFAULT_IGNORED_PATHS}; spread that constant to extend it.
|
|
16
|
+
*/
|
|
17
|
+
ignoredPaths?: readonly string[];
|
|
18
|
+
/**
|
|
19
|
+
* Per-instrumentation overrides for `getNodeAutoInstrumentations`, merged
|
|
20
|
+
* key by key over the defaults (see `buildSdkOptions`): a key given here
|
|
21
|
+
* replaces only the fields it names. Unset: the defaults alone.
|
|
22
|
+
*/
|
|
23
|
+
instrumentations?: InstrumentationConfigMap;
|
|
24
|
+
}
|
|
25
|
+
export interface TracingConfig {
|
|
26
|
+
serviceName: string;
|
|
27
|
+
endpoint: string;
|
|
28
|
+
sampleRatio: number;
|
|
29
|
+
ignoredPaths: readonly string[];
|
|
30
|
+
instrumentations: InstrumentationConfigMap;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The tracing configuration, or `null` when tracing is off.
|
|
34
|
+
*
|
|
35
|
+
* No endpoint means local dev, a test run or a CronJob pod (CronJobs never
|
|
36
|
+
* emit traces: a short-lived pod would bill as a full App O11y host per run).
|
|
37
|
+
*/
|
|
38
|
+
export declare function buildTracingConfig(env: TracingEnv, options: TracingOptions): TracingConfig | null;
|
|
39
|
+
/** `OTEL_SERVICE_NAME` when set, the consumer's name otherwise — the rule of all three copies. */
|
|
40
|
+
export declare function resolveServiceName(env: TracingEnv, serviceName: string): string;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_IGNORED_PATHS = void 0;
|
|
4
|
+
exports.buildTracingConfig = buildTracingConfig;
|
|
5
|
+
exports.resolveServiceName = resolveServiceName;
|
|
6
|
+
/**
|
|
7
|
+
* Probe and scrape traffic is noise: it never carries a user request and
|
|
8
|
+
* would otherwise be billed as App O11y host-hours on every health check and
|
|
9
|
+
* Prometheus scrape. The list every service used.
|
|
10
|
+
*/
|
|
11
|
+
exports.DEFAULT_IGNORED_PATHS = Object.freeze([
|
|
12
|
+
'/metrics',
|
|
13
|
+
'/health',
|
|
14
|
+
'/health/ready',
|
|
15
|
+
'/health/live',
|
|
16
|
+
]);
|
|
17
|
+
/**
|
|
18
|
+
* The tracing configuration, or `null` when tracing is off.
|
|
19
|
+
*
|
|
20
|
+
* No endpoint means local dev, a test run or a CronJob pod (CronJobs never
|
|
21
|
+
* emit traces: a short-lived pod would bill as a full App O11y host per run).
|
|
22
|
+
*/
|
|
23
|
+
function buildTracingConfig(env, options) {
|
|
24
|
+
const endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
|
25
|
+
if (!endpoint || env.OTEL_SDK_DISABLED === 'true')
|
|
26
|
+
return null;
|
|
27
|
+
const parsed = Number(env.OTEL_TRACES_SAMPLER_ARG);
|
|
28
|
+
const sampleRatio = Number.isFinite(parsed) && parsed >= 0 && parsed <= 1 ? parsed : 1;
|
|
29
|
+
return {
|
|
30
|
+
serviceName: resolveServiceName(env, options.serviceName),
|
|
31
|
+
endpoint,
|
|
32
|
+
sampleRatio,
|
|
33
|
+
ignoredPaths: options.ignoredPaths ?? exports.DEFAULT_IGNORED_PATHS,
|
|
34
|
+
instrumentations: options.instrumentations ?? {},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** `OTEL_SERVICE_NAME` when set, the consumer's name otherwise — the rule of all three copies. */
|
|
38
|
+
function resolveServiceName(env, serviceName) {
|
|
39
|
+
return env.OTEL_SERVICE_NAME ?? serviceName;
|
|
40
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The only environment variables the tracing bootstrap reads. */
|
|
2
|
+
export interface TracingEnv {
|
|
3
|
+
/** The OTLP/HTTP collector base URL; `/v1/traces` is appended. Unset: tracing off. */
|
|
4
|
+
OTEL_EXPORTER_OTLP_ENDPOINT?: string;
|
|
5
|
+
/** `'true'` turns tracing off even with an endpoint. */
|
|
6
|
+
OTEL_SDK_DISABLED?: string;
|
|
7
|
+
/** Root sampling ratio in `[0, 1]`; anything else samples everything. */
|
|
8
|
+
OTEL_TRACES_SAMPLER_ARG?: string;
|
|
9
|
+
/** Overrides the `serviceName` the consumer passes. */
|
|
10
|
+
OTEL_SERVICE_NAME?: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Reads the four variables of {@link TracingEnv} from `process.env`.
|
|
14
|
+
*
|
|
15
|
+
* Spelled as one literal `process.env.X` read per variable, as the service
|
|
16
|
+
* copies were, so a reader of this file sees the whole surface at once.
|
|
17
|
+
* `buildTracingConfig` takes the object, so tests never touch `process.env`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function readTracingEnv(): TracingEnv;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readTracingEnv = readTracingEnv;
|
|
4
|
+
/**
|
|
5
|
+
* Reads the four variables of {@link TracingEnv} from `process.env`.
|
|
6
|
+
*
|
|
7
|
+
* Spelled as one literal `process.env.X` read per variable, as the service
|
|
8
|
+
* copies were, so a reader of this file sees the whole surface at once.
|
|
9
|
+
* `buildTracingConfig` takes the object, so tests never touch `process.env`.
|
|
10
|
+
*/
|
|
11
|
+
function readTracingEnv() {
|
|
12
|
+
return {
|
|
13
|
+
OTEL_EXPORTER_OTLP_ENDPOINT: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
|
|
14
|
+
OTEL_SDK_DISABLED: process.env.OTEL_SDK_DISABLED,
|
|
15
|
+
OTEL_TRACES_SAMPLER_ARG: process.env.OTEL_TRACES_SAMPLER_ARG,
|
|
16
|
+
OTEL_SERVICE_NAME: process.env.OTEL_SERVICE_NAME,
|
|
17
|
+
};
|
|
18
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leoribeiroweb/nest-tracing",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "The OpenTelemetry SDK bootstrap of the NestJS services: traces only, OTLP over HTTP through the core package's RedactingSpanExporter, parent-based ratio sampling, probe and scrape paths ignored, and database, cache and outbound spans only under a parent.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/leoribeiro2/nest-core.git",
|
|
9
|
+
"directory": "packages/nest-tracing"
|
|
10
|
+
},
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/leoribeiro2/nest-core/issues"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/leoribeiro2/nest-core#readme",
|
|
15
|
+
"main": "dist/index.js",
|
|
16
|
+
"types": "dist/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=20.11.0"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsc -p tsconfig.build.json",
|
|
35
|
+
"prepublishOnly": "npm run build"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@leoribeiroweb/nest-core": ">=0.9.0 <1.0.0",
|
|
39
|
+
"@opentelemetry/auto-instrumentations-node": "^0.80.0",
|
|
40
|
+
"@opentelemetry/exporter-trace-otlp-proto": "^0.222.0",
|
|
41
|
+
"@opentelemetry/resources": "^2.11.0",
|
|
42
|
+
"@opentelemetry/sdk-node": "^0.222.0",
|
|
43
|
+
"@opentelemetry/sdk-trace-base": "^2.11.0",
|
|
44
|
+
"@opentelemetry/semantic-conventions": "^1.43.0"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@leoribeiroweb/nest-core": "*",
|
|
48
|
+
"@opentelemetry/auto-instrumentations-node": "^0.80.0",
|
|
49
|
+
"@opentelemetry/exporter-trace-otlp-proto": "^0.222.0",
|
|
50
|
+
"@opentelemetry/resources": "^2.11.0",
|
|
51
|
+
"@opentelemetry/sdk-node": "^0.222.0",
|
|
52
|
+
"@opentelemetry/sdk-trace-base": "^2.11.0",
|
|
53
|
+
"@opentelemetry/semantic-conventions": "^1.43.0"
|
|
54
|
+
}
|
|
55
|
+
}
|