@nestjs/observe 0.3.21 → 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.
- package/README.md +100 -14
- package/dist/agent/degraded-ingest.protocol.d.ts +14 -0
- package/dist/agent/degraded-ingest.protocol.js +19 -0
- package/dist/agent/detached-observe-worker.assembly.d.ts +2 -0
- package/dist/agent/detached-observe-worker.assembly.js +5 -1
- package/dist/agent/detached-observe-worker.d.ts +10 -0
- package/dist/agent/detached-observe-worker.js +27 -2
- package/dist/agent/observe-agent.shared-buffer.d.ts +63 -1
- package/dist/agent/observe-agent.shared-buffer.js +117 -2
- package/dist/agent/observe-agent.worker.d.ts +27 -20
- package/dist/agent/observe-agent.worker.js +109 -62
- package/dist/agent/observe-reporting.util.d.ts +35 -0
- package/dist/agent/observe-reporting.util.js +69 -0
- package/dist/interfaces/observe-options.interface.d.ts +100 -8
- package/dist/observe.constants.d.ts +17 -0
- package/dist/observe.constants.js +17 -0
- package/dist/observe.module.js +53 -4
- package/dist/otlp/otlp-encoders.d.ts +26 -0
- package/dist/otlp/otlp-encoders.js +296 -0
- package/dist/otlp/otlp-export-grant.d.ts +34 -0
- package/dist/otlp/otlp-export-grant.js +22 -0
- package/dist/otlp/otlp-options.interface.d.ts +59 -0
- package/dist/otlp/otlp-options.interface.js +1 -0
- package/dist/otlp/otlp-settings.util.d.ts +38 -0
- package/dist/otlp/otlp-settings.util.js +154 -0
- package/dist/otlp/otlp-span.mapper.d.ts +73 -0
- package/dist/otlp/otlp-span.mapper.js +345 -0
- package/dist/otlp/otlp-trace-exporter.service.d.ts +130 -0
- package/dist/otlp/otlp-trace-exporter.service.js +497 -0
- package/dist/outgoing/http.integration.d.ts +36 -3
- package/dist/outgoing/http.integration.js +84 -17
- package/dist/outgoing/outgoing-observe-agent.service.d.ts +14 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +24 -9
- package/dist/outgoing/outgoing-span.recorder.d.ts +11 -1
- package/dist/outgoing/outgoing-span.recorder.js +8 -2
- package/dist/outgoing/sql-statement.util.js +2 -2
- package/dist/protocols/http-observe-agent.service.d.ts +1 -8
- package/dist/protocols/http-observe-agent.service.js +44 -14
- package/dist/protocols/job-trace-runner.d.ts +11 -0
- package/dist/protocols/job-trace-runner.js +42 -8
- package/dist/protocols/rpc-observe-agent.service.d.ts +5 -0
- package/dist/protocols/rpc-observe-agent.service.js +43 -3
- package/dist/services/operation-trace.registry.d.ts +46 -3
- package/dist/services/operation-trace.registry.js +69 -13
- package/dist/services/tracer.service.d.ts +6 -0
- package/dist/services/tracer.service.js +11 -2
- package/dist/utils/default-trace-id-generator.util.d.ts +18 -0
- package/dist/utils/default-trace-id-generator.util.js +39 -2
- package/dist/utils/opentelemetry.util.d.ts +57 -0
- package/dist/utils/opentelemetry.util.js +100 -0
- package/dist/utils/trace-context.util.d.ts +91 -0
- package/dist/utils/trace-context.util.js +219 -0
- package/dist/utils/trace-handoff.util.d.ts +45 -0
- package/dist/utils/trace-handoff.util.js +90 -0
- package/dist/utils/trace-id-generator-origin.util.d.ts +11 -0
- package/dist/utils/trace-id-generator-origin.util.js +26 -0
- package/package.json +26 -13
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
var OtlpTraceExporter_1;
|
|
14
|
+
import { Inject, Injectable, Logger, } from "@nestjs/common";
|
|
15
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
16
|
+
import * as http from "http";
|
|
17
|
+
import * as https from "https";
|
|
18
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
19
|
+
import { promisify } from "util";
|
|
20
|
+
import { gzip } from "zlib";
|
|
21
|
+
import { sendsToObserve } from "../agent/observe-reporting.util.js";
|
|
22
|
+
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
23
|
+
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
24
|
+
import { readSdkVersion } from "../utils/sdk-version.util.js";
|
|
25
|
+
import { encodeOtlpJson, encodeOtlpProtobuf, } from "./otlp-encoders.js";
|
|
26
|
+
import { resolveOtlpSettings, } from "./otlp-settings.util.js";
|
|
27
|
+
import { jobSnapshotSpans, requestSnapshotSpans, toAttributes, } from "./otlp-span.mapper.js";
|
|
28
|
+
const gzipAsync = promisify(gzip);
|
|
29
|
+
/**
|
|
30
|
+
* The most spans waiting to be exported. Past it, a finished operation's
|
|
31
|
+
* spans are dropped whole - never part of a tree - and counted.
|
|
32
|
+
*
|
|
33
|
+
* What bounds the process when the receiver is slow or down: spans wait
|
|
34
|
+
* here while an export is retried, and a receiver that never comes back
|
|
35
|
+
* must cost telemetry, not memory.
|
|
36
|
+
*/
|
|
37
|
+
const MAX_QUEUED_SPANS = 10_000;
|
|
38
|
+
/**
|
|
39
|
+
* The most spans one export carries. A full batch is sent at once rather
|
|
40
|
+
* than at the next interval, so a busy service exports in step with what it
|
|
41
|
+
* records instead of building up a backlog between ticks.
|
|
42
|
+
*/
|
|
43
|
+
const MAX_BATCH_SPANS = 1_000;
|
|
44
|
+
const DEFAULT_FLUSH_INTERVAL_MS = 5_000;
|
|
45
|
+
const MIN_FLUSH_INTERVAL_MS = 1_000;
|
|
46
|
+
const DEFAULT_SHUTDOWN_FLUSH_TIMEOUT_MS = 2_000;
|
|
47
|
+
/**
|
|
48
|
+
* The statuses OTLP/HTTP says a client should retry after - the receiver is
|
|
49
|
+
* overloaded or briefly away. Anything else is an answer about the batch or
|
|
50
|
+
* the credentials, which sending the batch again would not change.
|
|
51
|
+
*/
|
|
52
|
+
const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
|
|
53
|
+
/** The first wait before an export is retried; it doubles to the ceiling. */
|
|
54
|
+
const RETRY_BASE_MS = 1_000;
|
|
55
|
+
const RETRY_MAX_MS = 60_000;
|
|
56
|
+
/** The longest a receiver's own `Retry-After` is obeyed for. */
|
|
57
|
+
const RETRY_AFTER_MAX_MS = 5 * 60_000;
|
|
58
|
+
/** How long an idle connection to the receiver is kept for the next batch. */
|
|
59
|
+
const KEEP_ALIVE_IDLE_MS = 30_000;
|
|
60
|
+
/**
|
|
61
|
+
* Exports what the agent records as OpenTelemetry traces, over OTLP/HTTP, to
|
|
62
|
+
* whatever receiver `otlp` names - a collector, Jaeger, Tempo, Honeycomb, a
|
|
63
|
+
* vendor's agent - beside what goes to Observe, never instead of it: an agent
|
|
64
|
+
* that sends Observe nothing (see `sendsToObserve`) exports nothing either.
|
|
65
|
+
* Part of OpenTelemetry interop, so it also takes `openTelemetry: true`: the
|
|
66
|
+
* `traceparent` the spans nest under is read only with that on.
|
|
67
|
+
*
|
|
68
|
+
* Fed finished operations by the shared buffer, which decides what to hand
|
|
69
|
+
* over: nothing until the collector takes the app's telemetry and its reply
|
|
70
|
+
* grants export for the account's plan, and then - see `OtlpExportGrant` -
|
|
71
|
+
* either everything, before anything the Observe side decides about it, or
|
|
72
|
+
* only what NestJS Observe keeps. What it is fed has already been through
|
|
73
|
+
* `tracesSampleRate`, `skipSpans` and `spanCollapse`, and through redaction.
|
|
74
|
+
*
|
|
75
|
+
* Runs on the application's thread, unlike the Observe worker: an export is
|
|
76
|
+
* a small encode and an asynchronous request, compression runs on libuv's
|
|
77
|
+
* pool, and none of it sits on a request's path. Every send runs outside the
|
|
78
|
+
* agent's async context, so the agent never traces - or puts trace headers
|
|
79
|
+
* on - its own exports.
|
|
80
|
+
*/
|
|
81
|
+
let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
|
|
82
|
+
options;
|
|
83
|
+
operationTraceRegistry;
|
|
84
|
+
asyncLocalStorage;
|
|
85
|
+
logger = new Logger(OtlpTraceExporter_1.name);
|
|
86
|
+
settings;
|
|
87
|
+
resource = [];
|
|
88
|
+
/** Its version is read only once export is known to be on. */
|
|
89
|
+
scope = { name: "@nestjs/observe", version: "" };
|
|
90
|
+
agent;
|
|
91
|
+
queue = [];
|
|
92
|
+
sending = null;
|
|
93
|
+
flushTimer = null;
|
|
94
|
+
shutdownPromise = null;
|
|
95
|
+
/**
|
|
96
|
+
* Set once shutdown has let go of the connection. An export still open
|
|
97
|
+
* then fails as its socket goes, which is the shutdown, not the receiver,
|
|
98
|
+
* and nothing will retry it.
|
|
99
|
+
*/
|
|
100
|
+
closed = false;
|
|
101
|
+
/** No export starts before this (epoch ms): a retry is waiting. */
|
|
102
|
+
retryNotBefore = 0;
|
|
103
|
+
retryDelayMs = 0;
|
|
104
|
+
/** Whether the last export failed - the final flush does not retry it. */
|
|
105
|
+
lastSendFailed = false;
|
|
106
|
+
/**
|
|
107
|
+
* What the last failure was, while exports are failing: said once when it
|
|
108
|
+
* starts or changes, and again when exports recover. Null while healthy.
|
|
109
|
+
*/
|
|
110
|
+
failure = null;
|
|
111
|
+
/** Spans dropped since the last report of it. */
|
|
112
|
+
droppedSpans = 0;
|
|
113
|
+
reportedDrop = false;
|
|
114
|
+
reportedMappingFailure = false;
|
|
115
|
+
/**
|
|
116
|
+
* Why `otlp` is set and export still cannot run, said once at start-up;
|
|
117
|
+
* null when it can, or when `otlp` is not set at all.
|
|
118
|
+
*/
|
|
119
|
+
offReason = null;
|
|
120
|
+
constructor(options, operationTraceRegistry, asyncLocalStorage) {
|
|
121
|
+
this.options = options;
|
|
122
|
+
this.operationTraceRegistry = operationTraceRegistry;
|
|
123
|
+
this.asyncLocalStorage = asyncLocalStorage;
|
|
124
|
+
if (!options.otlp) {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
// Off with the agent, which says so itself and records nothing.
|
|
128
|
+
if (options.enabled === false) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (options.openTelemetry !== true) {
|
|
132
|
+
this.offReason =
|
|
133
|
+
"OTLP export is off: `otlp` takes `openTelemetry: true` as well, which reads the `traceparent` " +
|
|
134
|
+
"the exported spans nest under and sends one on every call out.";
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (!sendsToObserve(options)) {
|
|
138
|
+
this.offReason =
|
|
139
|
+
"OTLP export is off: it runs beside reporting to NestJS Observe, never instead of it, " +
|
|
140
|
+
"and this agent reports nothing to it - it has no credentials for the hosted collector, or still has `nest new`'s placeholders.";
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const { settings, warnings } = resolveOtlpSettings(options.otlp, {
|
|
144
|
+
serviceId: options.serviceId,
|
|
145
|
+
serviceVersion: options.serviceVersion,
|
|
146
|
+
});
|
|
147
|
+
for (const warning of warnings) {
|
|
148
|
+
this.logger.warn(warning);
|
|
149
|
+
}
|
|
150
|
+
if (!settings) {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
this.settings = settings;
|
|
154
|
+
this.resource = toAttributes(settings.resource).attributes;
|
|
155
|
+
this.scope = { name: "@nestjs/observe", version: readSdkVersion() };
|
|
156
|
+
const transport = settings.url.startsWith("https:") ? https : http;
|
|
157
|
+
this.agent = new transport.Agent({
|
|
158
|
+
keepAlive: true,
|
|
159
|
+
timeout: KEEP_ALIVE_IDLE_MS,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Whether `otlp` is set up and export can run once the collector grants
|
|
164
|
+
* it - `openTelemetry` on, reporting to NestJS Observe, a usable endpoint.
|
|
165
|
+
*/
|
|
166
|
+
get enabled() {
|
|
167
|
+
return this.settings !== undefined;
|
|
168
|
+
}
|
|
169
|
+
/** Where export goes, once it is enabled. */
|
|
170
|
+
get url() {
|
|
171
|
+
return this.settings?.url;
|
|
172
|
+
}
|
|
173
|
+
onModuleInit() {
|
|
174
|
+
if (this.offReason) {
|
|
175
|
+
this.logger.warn(this.offReason);
|
|
176
|
+
}
|
|
177
|
+
if (!this.settings) {
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const interval = Math.max(this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL_MS, MIN_FLUSH_INTERVAL_MS);
|
|
181
|
+
this.flushTimer = setInterval(() => this.flush(), interval);
|
|
182
|
+
this.flushTimer.unref();
|
|
183
|
+
this.logger.log(`OTLP export to ${this.settings.url} (${this.settings.protocol}) starts once NestJS Observe ` +
|
|
184
|
+
"accepts this app's first batch and says what its plan includes.");
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Queues a finished request's spans - its own span, and with `withTree` the
|
|
188
|
+
* spans under it. Never throws into the caller.
|
|
189
|
+
*
|
|
190
|
+
* Left out when the request arrived in a trace its caller sampled out
|
|
191
|
+
* (`traceparent` flags 00), as an OpenTelemetry SDK sampling by its parent
|
|
192
|
+
* would leave it out: the caller exports none of that trace, so these
|
|
193
|
+
* spans would only hang in the backend under a parent it never gets.
|
|
194
|
+
*/
|
|
195
|
+
exportRequestSnapshot(snapshot, withTree = true) {
|
|
196
|
+
if (!this.settings) {
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
const context = this.operationTraceRegistry.traceContextOf(snapshot);
|
|
201
|
+
if (context && !context.sampled) {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
this.enqueue(requestSnapshotSpans(snapshot, context, withTree));
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
this.reportMappingFailure(error);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Queues a finished job's spans - its own span, and with `withTree` the
|
|
212
|
+
* spans under it. Never throws into the caller.
|
|
213
|
+
*/
|
|
214
|
+
exportJobSnapshot(snapshot, withTree = true) {
|
|
215
|
+
if (!this.settings) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
try {
|
|
219
|
+
this.enqueue(jobSnapshotSpans(snapshot, withTree));
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
this.reportMappingFailure(error);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Starts an export of what is queued, unless one is already under way, a
|
|
227
|
+
* retry is waiting out its delay, or there is nothing to send.
|
|
228
|
+
*/
|
|
229
|
+
flush() {
|
|
230
|
+
if (!this.settings ||
|
|
231
|
+
this.sending ||
|
|
232
|
+
this.queue.length === 0 ||
|
|
233
|
+
Date.now() < this.retryNotBefore) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const batch = this.queue.splice(0, MAX_BATCH_SPANS);
|
|
237
|
+
this.sending = this.send(batch).finally(() => {
|
|
238
|
+
this.sending = null;
|
|
239
|
+
// A backlog left behind a full batch goes straight out after it.
|
|
240
|
+
if (this.queue.length >= MAX_BATCH_SPANS && !this.shutdownPromise) {
|
|
241
|
+
this.flush();
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
onApplicationShutdown() {
|
|
246
|
+
this.shutdownPromise ??= this.shutDown();
|
|
247
|
+
return this.shutdownPromise;
|
|
248
|
+
}
|
|
249
|
+
enqueue(spans) {
|
|
250
|
+
if (this.queue.length + spans.length > MAX_QUEUED_SPANS) {
|
|
251
|
+
this.droppedSpans += spans.length;
|
|
252
|
+
if (!this.reportedDrop) {
|
|
253
|
+
this.reportedDrop = true;
|
|
254
|
+
this.logger.warn(`OTLP export is falling behind: more than ${MAX_QUEUED_SPANS} spans are waiting for ${this.settings?.url}, so newer traces are dropped until it catches up. Dropped spans are counted and reported when it does.`);
|
|
255
|
+
}
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
for (const span of spans) {
|
|
259
|
+
this.queue.push(span);
|
|
260
|
+
}
|
|
261
|
+
if (this.queue.length >= MAX_BATCH_SPANS) {
|
|
262
|
+
this.flush();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* One export. Resolves whatever happens: a failure is reported and either
|
|
267
|
+
* put back for a retry or dropped, never thrown.
|
|
268
|
+
*/
|
|
269
|
+
async send(batch) {
|
|
270
|
+
const settings = this.settings;
|
|
271
|
+
let body;
|
|
272
|
+
try {
|
|
273
|
+
const encoded = settings.protocol === "http/json"
|
|
274
|
+
? Buffer.from(encodeOtlpJson(this.resource, this.scope, batch))
|
|
275
|
+
: encodeOtlpProtobuf(this.resource, this.scope, batch);
|
|
276
|
+
body =
|
|
277
|
+
settings.compression === "gzip" ? await gzipAsync(encoded) : encoded;
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
// Nothing a retry would change: the batch is lost, and said so.
|
|
281
|
+
this.lastSendFailed = true;
|
|
282
|
+
this.reportFailure(`the batch could not be encoded (${String(error)})`, false);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
let reply;
|
|
286
|
+
try {
|
|
287
|
+
// Outside the agent's context: the request below would otherwise be
|
|
288
|
+
// traced, and given trace headers, as part of whatever operation's
|
|
289
|
+
// completion happened to start this export.
|
|
290
|
+
reply = await this.asyncLocalStorage.exit(() => this.post(body));
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
if (this.closed) {
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
const code = error.code;
|
|
297
|
+
this.retryLater(batch, undefined);
|
|
298
|
+
this.reportFailure(`the receiver could not be reached (${code ?? String(error)})`, true);
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
if (reply.status >= 200 && reply.status < 300) {
|
|
302
|
+
this.recovered(batch.length);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
const retryable = RETRYABLE_STATUSES.has(reply.status);
|
|
306
|
+
if (retryable) {
|
|
307
|
+
this.retryLater(batch, reply.retryAfter);
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
this.lastSendFailed = true;
|
|
311
|
+
}
|
|
312
|
+
const detail = reply.body && /json|text/.test(reply.contentType ?? "")
|
|
313
|
+
? ` - ${reply.body.slice(0, 300)}`
|
|
314
|
+
: "";
|
|
315
|
+
this.reportFailure(`it answered ${reply.status}${detail}`, retryable);
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Puts a batch back at the front of the queue, if it still fits, and holds
|
|
319
|
+
* exports back for the receiver's `Retry-After` or the next backoff step.
|
|
320
|
+
*/
|
|
321
|
+
retryLater(batch, retryAfter) {
|
|
322
|
+
this.lastSendFailed = true;
|
|
323
|
+
if (this.queue.length + batch.length <= MAX_QUEUED_SPANS) {
|
|
324
|
+
this.queue.unshift(...batch);
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
this.droppedSpans += batch.length;
|
|
328
|
+
}
|
|
329
|
+
this.retryDelayMs =
|
|
330
|
+
this.retryDelayMs === 0
|
|
331
|
+
? RETRY_BASE_MS
|
|
332
|
+
: Math.min(this.retryDelayMs * 2, RETRY_MAX_MS);
|
|
333
|
+
const asked = Number(retryAfter);
|
|
334
|
+
const delay = Number.isFinite(asked) && asked > 0
|
|
335
|
+
? Math.min(asked * 1000, RETRY_AFTER_MAX_MS)
|
|
336
|
+
: this.retryDelayMs;
|
|
337
|
+
this.retryNotBefore = Date.now() + delay;
|
|
338
|
+
}
|
|
339
|
+
/** Clears the failure state after an accepted export, and says so. */
|
|
340
|
+
recovered(exported) {
|
|
341
|
+
this.lastSendFailed = false;
|
|
342
|
+
this.retryDelayMs = 0;
|
|
343
|
+
this.retryNotBefore = 0;
|
|
344
|
+
if (this.failure !== null || this.droppedSpans > 0) {
|
|
345
|
+
const dropped = this.droppedSpans > 0
|
|
346
|
+
? `; ${this.droppedSpans} spans were dropped in the meantime`
|
|
347
|
+
: "";
|
|
348
|
+
this.logger.log(`OTLP export to ${this.settings?.url} is working again${dropped}.`);
|
|
349
|
+
}
|
|
350
|
+
this.failure = null;
|
|
351
|
+
this.droppedSpans = 0;
|
|
352
|
+
this.reportedDrop = false;
|
|
353
|
+
if (this.options.debug) {
|
|
354
|
+
this.logger.debug(`Exported ${exported} spans over OTLP.`);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Says that exports are failing, once when it starts and again only when
|
|
359
|
+
* the reason changes: a receiver that is down for an hour is one line, not
|
|
360
|
+
* one per flush.
|
|
361
|
+
*/
|
|
362
|
+
reportFailure(reason, retrying) {
|
|
363
|
+
if (this.failure === reason) {
|
|
364
|
+
if (this.options.debug) {
|
|
365
|
+
this.logger.debug(`OTLP export failed again: ${reason}.`);
|
|
366
|
+
}
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
this.failure = reason;
|
|
370
|
+
this.logger.warn(`OTLP export to ${this.settings?.url} failed: ${reason}. ` +
|
|
371
|
+
(retrying
|
|
372
|
+
? "Retrying with backoff; spans wait meanwhile, up to a limit."
|
|
373
|
+
: "That batch was dropped.") +
|
|
374
|
+
" Said again only if the reason changes.");
|
|
375
|
+
}
|
|
376
|
+
reportMappingFailure(error) {
|
|
377
|
+
if (this.reportedMappingFailure) {
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
this.reportedMappingFailure = true;
|
|
381
|
+
this.logger.warn(`An operation could not be converted to OTLP spans and was left out of the export; later ones are not reported: ${String(error)}`);
|
|
382
|
+
}
|
|
383
|
+
post(body) {
|
|
384
|
+
const settings = this.settings;
|
|
385
|
+
const transport = settings.url.startsWith("https:") ? https : http;
|
|
386
|
+
return new Promise((resolve, reject) => {
|
|
387
|
+
const request = transport.request(settings.url, {
|
|
388
|
+
method: "POST",
|
|
389
|
+
agent: this.agent,
|
|
390
|
+
headers: {
|
|
391
|
+
...settings.headers,
|
|
392
|
+
"Content-Type": settings.protocol === "http/json"
|
|
393
|
+
? "application/json"
|
|
394
|
+
: "application/x-protobuf",
|
|
395
|
+
...(settings.compression === "gzip"
|
|
396
|
+
? { "Content-Encoding": "gzip" }
|
|
397
|
+
: {}),
|
|
398
|
+
"Content-Length": body.length,
|
|
399
|
+
"User-Agent": `nestjs-observe/${this.scope.version}`,
|
|
400
|
+
},
|
|
401
|
+
}, (response) => {
|
|
402
|
+
const chunks = [];
|
|
403
|
+
response.on("data", (chunk) => chunks.push(chunk));
|
|
404
|
+
response.on("error", reject);
|
|
405
|
+
response.on("end", () => {
|
|
406
|
+
const retryAfter = response.headers["retry-after"];
|
|
407
|
+
resolve({
|
|
408
|
+
status: response.statusCode ?? 0,
|
|
409
|
+
retryAfter: Array.isArray(retryAfter)
|
|
410
|
+
? retryAfter[0]
|
|
411
|
+
: retryAfter,
|
|
412
|
+
contentType: response.headers["content-type"],
|
|
413
|
+
body: Buffer.concat(chunks).toString("utf8"),
|
|
414
|
+
});
|
|
415
|
+
});
|
|
416
|
+
});
|
|
417
|
+
request.on("error", reject);
|
|
418
|
+
request.setTimeout(settings.timeoutMs, () => request.destroy(Object.assign(new Error(`no answer within ${settings.timeoutMs} ms`), { code: "ETIMEDOUT" })));
|
|
419
|
+
request.end(body);
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Exports what is still queued, for at most `shutdownFlushTimeout`, then
|
|
424
|
+
* lets go of the connection.
|
|
425
|
+
*
|
|
426
|
+
* Operations finish their traces a tick after their response, and one
|
|
427
|
+
* whose spans were still open waits a further second in the registry, so
|
|
428
|
+
* the drain waits for both before deciding it is done - as the Observe
|
|
429
|
+
* worker's final flush does. A receiver that fails the final export is not
|
|
430
|
+
* retried: shutdown is not the time to wait out a backoff.
|
|
431
|
+
*/
|
|
432
|
+
async shutDown() {
|
|
433
|
+
if (this.flushTimer) {
|
|
434
|
+
clearInterval(this.flushTimer);
|
|
435
|
+
this.flushTimer = null;
|
|
436
|
+
}
|
|
437
|
+
if (!this.settings) {
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
const timeoutMs = this.options.shutdownFlushTimeout ?? DEFAULT_SHUTDOWN_FLUSH_TIMEOUT_MS;
|
|
441
|
+
try {
|
|
442
|
+
if (timeoutMs > 0) {
|
|
443
|
+
await this.drain(timeoutMs);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
catch (error) {
|
|
447
|
+
if (this.options.debug) {
|
|
448
|
+
this.logger.debug(`Final OTLP export failed: ${String(error)}`);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
finally {
|
|
452
|
+
this.closed = true;
|
|
453
|
+
this.agent?.destroy();
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
async drain(timeoutMs) {
|
|
457
|
+
const deadline = process.uptime() * 1000 + timeoutMs;
|
|
458
|
+
await sleep(0);
|
|
459
|
+
for (;;) {
|
|
460
|
+
const remaining = deadline - process.uptime() * 1000;
|
|
461
|
+
if (remaining <= 0) {
|
|
462
|
+
if (this.options.debug && this.queue.length > 0) {
|
|
463
|
+
this.logger.debug(`Final OTLP export did not finish within ${timeoutMs}ms; ${this.queue.length} spans were not exported.`);
|
|
464
|
+
}
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
if (this.sending) {
|
|
468
|
+
const timeout = new AbortController();
|
|
469
|
+
await Promise.race([
|
|
470
|
+
this.sending,
|
|
471
|
+
sleep(remaining, undefined, { signal: timeout.signal }).catch(() => undefined),
|
|
472
|
+
]);
|
|
473
|
+
timeout.abort();
|
|
474
|
+
if (this.lastSendFailed) {
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
if (this.operationTraceRegistry.hasSnapshotsAwaitingCompletion()) {
|
|
480
|
+
await sleep(Math.min(10, remaining));
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
if (this.queue.length === 0) {
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
this.retryNotBefore = 0;
|
|
487
|
+
this.flush();
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
OtlpTraceExporter = OtlpTraceExporter_1 = __decorate([
|
|
492
|
+
Injectable(),
|
|
493
|
+
__param(0, Inject(OBSERVE_OPTIONS)),
|
|
494
|
+
__metadata("design:paramtypes", [Object, OperationTraceRegistry,
|
|
495
|
+
AsyncLocalStorage])
|
|
496
|
+
], OtlpTraceExporter);
|
|
497
|
+
export { OtlpTraceExporter };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { LogRedactor } from "../utils/log-redactor.js";
|
|
2
|
+
import { TraceContext } from "../utils/trace-context.util.js";
|
|
2
3
|
import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
|
|
3
4
|
export interface OutgoingHttpOptions {
|
|
4
5
|
/**
|
|
@@ -11,10 +12,36 @@ export interface OutgoingHttpOptions {
|
|
|
11
12
|
* carries one. It is what a downstream service running `@nestjs/observe`
|
|
12
13
|
* adopts as its own trace id, which makes HTTP-to-HTTP calls one trace with
|
|
13
14
|
* no application code. A function narrows it to the URLs it returns true
|
|
14
|
-
* for - your own services, say, and not third parties.
|
|
15
|
+
* for - your own services, say, and not third parties. It narrows
|
|
16
|
+
* `traceContext` too.
|
|
15
17
|
* @default true
|
|
16
18
|
*/
|
|
17
19
|
propagateTraceId?: boolean | ((url: string) => boolean);
|
|
20
|
+
/**
|
|
21
|
+
* Send W3C Trace Context beside `x-request-id`: a `traceparent` naming the
|
|
22
|
+
* trace and this call's span, and the `tracestate` the operation arrived
|
|
23
|
+
* with, if any. It is what a service instrumented with OpenTelemetry - in
|
|
24
|
+
* any language - reads, so the call stays one trace through it. The trace
|
|
25
|
+
* is the one the operation's own `traceparent` named, when it arrived with
|
|
26
|
+
* one. Never added to a request that already carries a `traceparent`, nor
|
|
27
|
+
* while an OpenTelemetry SDK that propagates W3C Trace Context runs in the
|
|
28
|
+
* same process: its instrumentations write the header on the calls they
|
|
29
|
+
* cover, and a request takes only one.
|
|
30
|
+
*
|
|
31
|
+
* Only with `openTelemetry` on, and only beside reporting to NestJS
|
|
32
|
+
* Observe - from the first batch the collector accepts, through outages,
|
|
33
|
+
* until it refuses the app's credentials; otherwise no `traceparent` is
|
|
34
|
+
* sent.
|
|
35
|
+
* @default true, with `openTelemetry` on
|
|
36
|
+
*/
|
|
37
|
+
traceContext?: boolean;
|
|
38
|
+
}
|
|
39
|
+
/** What an outbound call is told about the operation making it. */
|
|
40
|
+
export interface OutgoingTrace {
|
|
41
|
+
/** The operation's trace id, as `x-request-id` carries it. */
|
|
42
|
+
traceId: string;
|
|
43
|
+
/** The `traceparent` the operation arrived with, when it had one. */
|
|
44
|
+
traceContext?: TraceContext;
|
|
18
45
|
}
|
|
19
46
|
/**
|
|
20
47
|
* Spans for outbound HTTP, from the diagnostics channels Node publishes on its
|
|
@@ -28,9 +55,15 @@ export interface OutgoingHttpOptions {
|
|
|
28
55
|
*
|
|
29
56
|
* Returns the function that removes every subscription.
|
|
30
57
|
*/
|
|
31
|
-
export declare function subscribeOutgoingHttp(recorder: OutgoingSpanRecorder,
|
|
58
|
+
export declare function subscribeOutgoingHttp(recorder: OutgoingSpanRecorder, currentTrace: () => OutgoingTrace | undefined, options?: OutgoingHttpOptions,
|
|
32
59
|
/**
|
|
33
60
|
* Read per request rather than passed once: the redactor is configured
|
|
34
61
|
* after the module's options resolve, which can be after this subscribes.
|
|
35
62
|
*/
|
|
36
|
-
getRedactor?: () => LogRedactor | null
|
|
63
|
+
getRedactor?: () => LogRedactor | null,
|
|
64
|
+
/**
|
|
65
|
+
* Whether calls carry W3C Trace Context now: with `openTelemetry` on and
|
|
66
|
+
* `traceContext` not off, while the agent reports to NestJS Observe (see
|
|
67
|
+
* `ObserveAgentSharedBuffer.isIngesting`). Off unless given.
|
|
68
|
+
*/
|
|
69
|
+
traceContextOn?: () => boolean): () => void;
|