@nestjs/observe 0.3.22 → 0.3.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +71 -14
  2. package/dist/agent/degraded-ingest.protocol.d.ts +2 -8
  3. package/dist/agent/degraded-ingest.protocol.js +2 -8
  4. package/dist/agent/detached-observe-worker.assembly.d.ts +2 -0
  5. package/dist/agent/detached-observe-worker.assembly.js +3 -0
  6. package/dist/agent/detached-observe-worker.d.ts +8 -0
  7. package/dist/agent/detached-observe-worker.js +20 -2
  8. package/dist/agent/observe-agent.shared-buffer.d.ts +48 -22
  9. package/dist/agent/observe-agent.shared-buffer.js +94 -34
  10. package/dist/agent/observe-agent.worker.d.ts +16 -21
  11. package/dist/agent/observe-agent.worker.js +67 -74
  12. package/dist/agent/observe-reporting.util.d.ts +35 -0
  13. package/dist/agent/observe-reporting.util.js +69 -0
  14. package/dist/interfaces/observe-options.interface.d.ts +67 -13
  15. package/dist/observe.constants.d.ts +7 -0
  16. package/dist/observe.constants.js +7 -0
  17. package/dist/observe.module.js +50 -4
  18. package/dist/otlp/otlp-encoders.d.ts +26 -0
  19. package/dist/otlp/otlp-encoders.js +296 -0
  20. package/dist/otlp/otlp-export-grant.d.ts +34 -0
  21. package/dist/otlp/otlp-export-grant.js +22 -0
  22. package/dist/otlp/otlp-options.interface.d.ts +59 -0
  23. package/dist/otlp/otlp-options.interface.js +1 -0
  24. package/dist/otlp/otlp-settings.util.d.ts +38 -0
  25. package/dist/otlp/otlp-settings.util.js +154 -0
  26. package/dist/otlp/otlp-span.mapper.d.ts +73 -0
  27. package/dist/otlp/otlp-span.mapper.js +345 -0
  28. package/dist/otlp/otlp-trace-exporter.service.d.ts +130 -0
  29. package/dist/otlp/otlp-trace-exporter.service.js +497 -0
  30. package/dist/outgoing/http.integration.d.ts +6 -4
  31. package/dist/outgoing/http.integration.js +3 -3
  32. package/dist/outgoing/outgoing-observe-agent.service.d.ts +2 -2
  33. package/dist/outgoing/outgoing-observe-agent.service.js +1 -1
  34. package/dist/outgoing/sql-statement.util.js +2 -2
  35. package/dist/protocols/http-observe-agent.service.d.ts +1 -8
  36. package/dist/protocols/http-observe-agent.service.js +28 -21
  37. package/dist/protocols/job-trace-runner.d.ts +11 -0
  38. package/dist/protocols/job-trace-runner.js +42 -8
  39. package/dist/protocols/rpc-observe-agent.service.d.ts +5 -0
  40. package/dist/protocols/rpc-observe-agent.service.js +43 -3
  41. package/dist/services/operation-trace.registry.d.ts +29 -1
  42. package/dist/services/operation-trace.registry.js +46 -5
  43. package/dist/utils/default-trace-id-generator.util.js +6 -2
  44. package/dist/utils/opentelemetry.util.d.ts +26 -0
  45. package/dist/utils/opentelemetry.util.js +48 -0
  46. package/dist/utils/trace-handoff.util.d.ts +45 -0
  47. package/dist/utils/trace-handoff.util.js +90 -0
  48. package/package.json +13 -12
@@ -0,0 +1,34 @@
1
+ /**
2
+ * What the collector says an app's plan allows `otlp` to export - read off
3
+ * the reply to an accepted batch, so the plans live where they are sold and
4
+ * this agent names none of them:
5
+ *
6
+ * - `full`: every operation the agent records, with its whole tree, ahead of
7
+ * anything the collector's answers make it hold back from NestJS Observe -
8
+ * an account paused for its overage still exports every trace.
9
+ * - `capped`: what NestJS Observe keeps of it and nothing more. Whatever this
10
+ * agent leaves out of a batch is left out of the export, and an operation
11
+ * it sends without its spans - a day past Free's daily pacing, an account
12
+ * past its monthly allowance - is exported as the operation's own span,
13
+ * without the tree under it.
14
+ * - `off`: nothing. What a reply carrying no grant means, which is every
15
+ * reply from a collector that predates export, so an agent released before
16
+ * the collector learnt to answer exports nothing.
17
+ */
18
+ export type OtlpExportGrant = "full" | "capped" | "off";
19
+ /**
20
+ * The token an agent with `otlp` set adds to `x-observe-ingest-modes`, the
21
+ * header in which it lists the answers it can read. The collector answers
22
+ * `otlpExport` only to a batch that lists it, so the replies every other
23
+ * agent gets stay what they were, byte for byte.
24
+ */
25
+ export declare const OTLP_EXPORT_INGEST_MODE = "otlp-export";
26
+ /**
27
+ * How the detached worker tells the main thread what the collector granted:
28
+ * this prefix, then `full`, `capped` or `off`. Posted for every accepted
29
+ * batch, ahead of the degraded verdict for the same batch, and only by a
30
+ * worker that listed `OTLP_EXPORT_INGEST_MODE`.
31
+ */
32
+ export declare const OTLP_EXPORT_MESSAGE_PREFIX = "observe:otlp-export=";
33
+ /** The grant a worker's line carries, or null if this is not that line. */
34
+ export declare function parseOtlpExportMessage(msg: string): OtlpExportGrant | null;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The token an agent with `otlp` set adds to `x-observe-ingest-modes`, the
3
+ * header in which it lists the answers it can read. The collector answers
4
+ * `otlpExport` only to a batch that lists it, so the replies every other
5
+ * agent gets stay what they were, byte for byte.
6
+ */
7
+ export const OTLP_EXPORT_INGEST_MODE = "otlp-export";
8
+ /**
9
+ * How the detached worker tells the main thread what the collector granted:
10
+ * this prefix, then `full`, `capped` or `off`. Posted for every accepted
11
+ * batch, ahead of the degraded verdict for the same batch, and only by a
12
+ * worker that listed `OTLP_EXPORT_INGEST_MODE`.
13
+ */
14
+ export const OTLP_EXPORT_MESSAGE_PREFIX = "observe:otlp-export=";
15
+ /** The grant a worker's line carries, or null if this is not that line. */
16
+ export function parseOtlpExportMessage(msg) {
17
+ if (!msg.startsWith(OTLP_EXPORT_MESSAGE_PREFIX)) {
18
+ return null;
19
+ }
20
+ const value = msg.slice(OTLP_EXPORT_MESSAGE_PREFIX.length);
21
+ return value === "full" || value === "capped" ? value : "off";
22
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Where, and how, `otlp` exports traces. Every field falls back to the
3
+ * standard OpenTelemetry environment variable named beside it, then to the
4
+ * OpenTelemetry default - so `otlp: true` alone exports wherever the
5
+ * environment says, as any OpenTelemetry SDK would.
6
+ */
7
+ export interface OtlpExportOptions {
8
+ /**
9
+ * The OTLP/HTTP receiver: a collector, an agent, or a vendor's endpoint.
10
+ * Given as the base URL, the way `OTEL_EXPORTER_OTLP_ENDPOINT` takes it -
11
+ * `/v1/traces` is appended unless the URL already ends with it.
12
+ *
13
+ * Falls back to `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` (used as given), then
14
+ * `OTEL_EXPORTER_OTLP_ENDPOINT`.
15
+ * @default 'http://localhost:4318'
16
+ */
17
+ endpoint?: string;
18
+ /**
19
+ * Headers sent with every export - a vendor's API key, usually. Merged
20
+ * over `OTEL_EXPORTER_OTLP_HEADERS` and `OTEL_EXPORTER_OTLP_TRACES_HEADERS`
21
+ * (`key=value,key2=value2`), which keep any key this does not set.
22
+ */
23
+ headers?: Record<string, string>;
24
+ /**
25
+ * The OTLP/HTTP encoding. gRPC is not supported: point at the receiver's
26
+ * HTTP port (4318 by convention) instead.
27
+ *
28
+ * Falls back to `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL`, then
29
+ * `OTEL_EXPORTER_OTLP_PROTOCOL`.
30
+ * @default 'http/protobuf'
31
+ */
32
+ protocol?: "http/protobuf" | "http/json";
33
+ /**
34
+ * Falls back to `OTEL_EXPORTER_OTLP_TRACES_COMPRESSION`, then
35
+ * `OTEL_EXPORTER_OTLP_COMPRESSION`.
36
+ * @default 'gzip'
37
+ */
38
+ compression?: "gzip" | "none";
39
+ /**
40
+ * Milliseconds one export may take before it is abandoned and retried.
41
+ *
42
+ * Falls back to `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT`, then
43
+ * `OTEL_EXPORTER_OTLP_TIMEOUT`.
44
+ * @default 10000
45
+ */
46
+ timeoutMillis?: number;
47
+ /**
48
+ * The `service.name` the spans are reported under.
49
+ * Falls back to `OTEL_SERVICE_NAME`, then `serviceId`.
50
+ */
51
+ serviceName?: string;
52
+ /**
53
+ * Resource attributes on every span - `deployment.environment.name`,
54
+ * `service.namespace` and the like. Merged over `OTEL_RESOURCE_ATTRIBUTES`
55
+ * and the ones the agent sets itself (`service.version`, `host.name`,
56
+ * `process.pid`, ...).
57
+ */
58
+ resourceAttributes?: Record<string, string | number | boolean>;
59
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,38 @@
1
+ import type { OtlpExportOptions } from "./otlp-options.interface.js";
2
+ export type OtlpAttributeValue = string | number | boolean;
3
+ /** `otlp`, resolved against the environment once, when the agent starts. */
4
+ export interface OtlpExportSettings {
5
+ /** The full traces URL the batches are posted to. */
6
+ url: string;
7
+ headers: Record<string, string>;
8
+ protocol: "http/protobuf" | "http/json";
9
+ compression: "gzip" | "none";
10
+ timeoutMs: number;
11
+ /** Attributes of the resource every exported span belongs to. */
12
+ resource: Record<string, OtlpAttributeValue>;
13
+ }
14
+ export interface ResolvedOtlpSettings {
15
+ /** Undefined when export is off. */
16
+ settings: OtlpExportSettings | undefined;
17
+ /** What was wrong with the configuration, to be said once at start-up. */
18
+ warnings: string[];
19
+ }
20
+ /**
21
+ * Resolves `otlp` into what the exporter needs, with no settings when export
22
+ * is off - not asked for, or pointed at something that is not a URL.
23
+ *
24
+ * The environment only fills in what the options leave out; it never turns
25
+ * export on by itself. An application that also runs an OpenTelemetry SDK
26
+ * has these variables set for that SDK, and exporting from here too would
27
+ * send every trace twice.
28
+ */
29
+ export declare function resolveOtlpSettings(otlp: boolean | OtlpExportOptions | undefined, service: {
30
+ serviceId: string;
31
+ serviceVersion?: string | false;
32
+ }, env?: NodeJS.ProcessEnv): ResolvedOtlpSettings;
33
+ /**
34
+ * `key=value,key2=value2`, as `OTEL_EXPORTER_OTLP_HEADERS` and
35
+ * `OTEL_RESOURCE_ATTRIBUTES` spell them, values percent-decoded. A member
36
+ * without a key or an `=` is skipped rather than failing the whole list.
37
+ */
38
+ export declare function parseKeyValueList(value: string | undefined): Record<string, string>;
@@ -0,0 +1,154 @@
1
+ import { randomUUID } from "crypto";
2
+ import { hostname } from "os";
3
+ import { readSdkVersion } from "../utils/sdk-version.util.js";
4
+ const DEFAULT_ENDPOINT = "http://localhost:4318";
5
+ const TRACES_PATH = "/v1/traces";
6
+ const DEFAULT_TIMEOUT_MS = 10_000;
7
+ /**
8
+ * Resolves `otlp` into what the exporter needs, with no settings when export
9
+ * is off - not asked for, or pointed at something that is not a URL.
10
+ *
11
+ * The environment only fills in what the options leave out; it never turns
12
+ * export on by itself. An application that also runs an OpenTelemetry SDK
13
+ * has these variables set for that SDK, and exporting from here too would
14
+ * send every trace twice.
15
+ */
16
+ export function resolveOtlpSettings(otlp, service, env = process.env) {
17
+ if (!otlp) {
18
+ return { settings: undefined, warnings: [] };
19
+ }
20
+ const options = otlp === true ? {} : otlp;
21
+ const warnings = [];
22
+ const signalEndpoint = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim();
23
+ const baseEndpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim();
24
+ const url = options.endpoint
25
+ ? toTracesUrl(options.endpoint)
26
+ : signalEndpoint ||
27
+ // The spec's own rule: the signal-specific variable is the whole URL,
28
+ // the generic one a base the signal's path is added to.
29
+ toTracesUrl(baseEndpoint || DEFAULT_ENDPOINT);
30
+ let normalizedUrl;
31
+ try {
32
+ const parsed = new URL(url);
33
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
34
+ throw new Error(parsed.protocol);
35
+ }
36
+ // Scheme and host lower-cased: the exporter picks its transport off
37
+ // the scheme, and `HTTPS://` is still https.
38
+ normalizedUrl = parsed.toString();
39
+ }
40
+ catch {
41
+ warnings.push(`OTLP export is off: the endpoint ${JSON.stringify(url)} is not an http(s) URL.`);
42
+ return { settings: undefined, warnings };
43
+ }
44
+ const protocolSetting = options.protocol ??
45
+ env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?.trim() ??
46
+ env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim();
47
+ let protocol = "http/protobuf";
48
+ if (protocolSetting === "http/json") {
49
+ protocol = "http/json";
50
+ }
51
+ else if (protocolSetting === "grpc") {
52
+ warnings.push(`OTLP over gRPC is not supported, so traces go to ${url} as http/protobuf. ` +
53
+ "If that is the receiver's gRPC port (4317 by convention), point the endpoint at its HTTP port (4318) instead.");
54
+ }
55
+ else if (protocolSetting && protocolSetting !== "http/protobuf") {
56
+ warnings.push(`Unknown OTLP protocol ${JSON.stringify(protocolSetting)}; exporting http/protobuf.`);
57
+ }
58
+ const compressionSetting = options.compression ??
59
+ env.OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?.trim() ??
60
+ env.OTEL_EXPORTER_OTLP_COMPRESSION?.trim();
61
+ let compression = "gzip";
62
+ if (compressionSetting === "none") {
63
+ compression = "none";
64
+ }
65
+ else if (compressionSetting && compressionSetting !== "gzip") {
66
+ warnings.push(`Unknown OTLP compression ${JSON.stringify(compressionSetting)}; exporting gzip.`);
67
+ }
68
+ const timeoutMs = positive(options.timeoutMillis) ??
69
+ positive(Number(env.OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)) ??
70
+ positive(Number(env.OTEL_EXPORTER_OTLP_TIMEOUT)) ??
71
+ DEFAULT_TIMEOUT_MS;
72
+ const headers = {
73
+ ...parseKeyValueList(env.OTEL_EXPORTER_OTLP_HEADERS),
74
+ ...parseKeyValueList(env.OTEL_EXPORTER_OTLP_TRACES_HEADERS),
75
+ ...options.headers,
76
+ };
77
+ // Lowest precedence first: what the agent knows, then the environment's
78
+ // resource attributes, its service name - which the spec puts above them
79
+ // - and last what the application passed in code.
80
+ const resource = {
81
+ "service.name": service.serviceId,
82
+ "service.instance.id": randomUUID(),
83
+ "host.name": hostname(),
84
+ "process.pid": process.pid,
85
+ "process.runtime.name": "nodejs",
86
+ "process.runtime.version": process.versions.node,
87
+ "telemetry.sdk.name": "@nestjs/observe",
88
+ "telemetry.sdk.language": "nodejs",
89
+ "telemetry.sdk.version": readSdkVersion(),
90
+ };
91
+ if (typeof service.serviceVersion === "string" && service.serviceVersion) {
92
+ resource["service.version"] = service.serviceVersion;
93
+ }
94
+ Object.assign(resource, parseKeyValueList(env.OTEL_RESOURCE_ATTRIBUTES));
95
+ const envServiceName = env.OTEL_SERVICE_NAME?.trim();
96
+ if (envServiceName) {
97
+ resource["service.name"] = envServiceName;
98
+ }
99
+ Object.assign(resource, options.resourceAttributes);
100
+ if (options.serviceName) {
101
+ resource["service.name"] = options.serviceName;
102
+ }
103
+ return {
104
+ settings: {
105
+ url: normalizedUrl,
106
+ headers,
107
+ protocol,
108
+ compression,
109
+ timeoutMs,
110
+ resource,
111
+ },
112
+ warnings,
113
+ };
114
+ }
115
+ /**
116
+ * The traces URL for a base endpoint: `/v1/traces` appended, unless it is
117
+ * already there - so the full URL a vendor's docs give works as well as the
118
+ * base the environment variable takes.
119
+ */
120
+ function toTracesUrl(endpoint) {
121
+ const trimmed = endpoint.trim().replace(/\/+$/, "");
122
+ return trimmed.endsWith(TRACES_PATH) ? trimmed : `${trimmed}${TRACES_PATH}`;
123
+ }
124
+ /**
125
+ * `key=value,key2=value2`, as `OTEL_EXPORTER_OTLP_HEADERS` and
126
+ * `OTEL_RESOURCE_ATTRIBUTES` spell them, values percent-decoded. A member
127
+ * without a key or an `=` is skipped rather than failing the whole list.
128
+ */
129
+ export function parseKeyValueList(value) {
130
+ const parsed = {};
131
+ for (const member of value?.split(",") ?? []) {
132
+ const separator = member.indexOf("=");
133
+ if (separator <= 0) {
134
+ continue;
135
+ }
136
+ const key = member.slice(0, separator).trim();
137
+ const raw = member.slice(separator + 1).trim();
138
+ if (!key) {
139
+ continue;
140
+ }
141
+ try {
142
+ parsed[key] = decodeURIComponent(raw);
143
+ }
144
+ catch {
145
+ parsed[key] = raw;
146
+ }
147
+ }
148
+ return parsed;
149
+ }
150
+ function positive(value) {
151
+ return typeof value === "number" && Number.isFinite(value) && value > 0
152
+ ? value
153
+ : undefined;
154
+ }
@@ -0,0 +1,73 @@
1
+ import type { JobSnapshot } from "../interfaces/job-snapshot.interface.js";
2
+ import type { RequestSnapshot } from "../interfaces/request-snapshot.interface.js";
3
+ import { TraceContext } from "../utils/trace-context.util.js";
4
+ import type { OtlpAttributeValue } from "./otlp-settings.util.js";
5
+ /** OTLP's `Span.SpanKind`. */
6
+ export declare const SpanKind: {
7
+ readonly INTERNAL: 1;
8
+ readonly SERVER: 2;
9
+ readonly CLIENT: 3;
10
+ readonly CONSUMER: 5;
11
+ };
12
+ /** OTLP's `Status.StatusCode`. Only errors are ever set. */
13
+ export declare const STATUS_CODE_ERROR = 2;
14
+ export interface OtlpAttribute {
15
+ key: string;
16
+ value: OtlpAttributeValue;
17
+ }
18
+ export interface OtlpEvent {
19
+ timeUnixNano: bigint;
20
+ name: string;
21
+ attributes: OtlpAttribute[];
22
+ }
23
+ /** One span, ready for either encoder. Ids are lowercase hex. */
24
+ export interface OtlpSpan {
25
+ traceId: string;
26
+ spanId: string;
27
+ parentSpanId?: string;
28
+ traceState?: string;
29
+ name: string;
30
+ kind: (typeof SpanKind)[keyof typeof SpanKind];
31
+ startTimeUnixNano: bigint;
32
+ endTimeUnixNano: bigint;
33
+ attributes: OtlpAttribute[];
34
+ droppedAttributesCount: number;
35
+ events: OtlpEvent[];
36
+ status?: {
37
+ code: typeof STATUS_CODE_ERROR;
38
+ message?: string;
39
+ };
40
+ flags: number;
41
+ }
42
+ /**
43
+ * A request, a GraphQL operation, an RPC message or a gateway message as
44
+ * OTLP spans: one SERVER span for the operation, and under it a span for
45
+ * every node of its tree.
46
+ *
47
+ * The SERVER span is what the agent's own snapshot has no node for - the
48
+ * operation itself, with its route, status and user - and gets an id of its
49
+ * own, minted here: several requests can share a trace id (a caller that
50
+ * fans out), and anything derived from it would give them all one span. It
51
+ * goes under the caller's span when the request arrived with a
52
+ * `traceparent`, which is what joins it to the trace upstream.
53
+ *
54
+ * Without `withTree`, the SERVER span alone: what NestJS Observe keeps of an
55
+ * operation whose spans it holds back - see `OtlpExportGrant`.
56
+ */
57
+ export declare function requestSnapshotSpans(snapshot: RequestSnapshot, context: TraceContext | undefined, withTree?: boolean): OtlpSpan[];
58
+ /**
59
+ * A queue job or a scheduled run as OTLP spans: a CONSUMER span for the run
60
+ * - INTERNAL for a scheduled one, which nothing sent - and its tree under
61
+ * it. A job reports under the trace id of the operation that enqueued it,
62
+ * so it lands in that trace; nothing records which span enqueued it, so it
63
+ * has no parent there. Without `withTree`, the run's span alone.
64
+ */
65
+ export declare function jobSnapshotSpans(snapshot: JobSnapshot, withTree?: boolean): OtlpSpan[];
66
+ /**
67
+ * Attributes from a flat record, in its order, without the keys that hold
68
+ * nothing - and at most `MAX_ATTRIBUTES_PER_SPAN` of them, the rest counted.
69
+ */
70
+ export declare function toAttributes(record: Record<string, OtlpAttributeValue | undefined | null>): {
71
+ attributes: OtlpAttribute[];
72
+ droppedAttributesCount: number;
73
+ };