@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.
- package/README.md +71 -14
- package/dist/agent/degraded-ingest.protocol.d.ts +2 -8
- package/dist/agent/degraded-ingest.protocol.js +2 -8
- package/dist/agent/detached-observe-worker.assembly.d.ts +2 -0
- package/dist/agent/detached-observe-worker.assembly.js +3 -0
- package/dist/agent/detached-observe-worker.d.ts +8 -0
- package/dist/agent/detached-observe-worker.js +20 -2
- package/dist/agent/observe-agent.shared-buffer.d.ts +48 -22
- package/dist/agent/observe-agent.shared-buffer.js +94 -34
- package/dist/agent/observe-agent.worker.d.ts +16 -21
- package/dist/agent/observe-agent.worker.js +67 -74
- 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 +67 -13
- package/dist/observe.constants.d.ts +7 -0
- package/dist/observe.constants.js +7 -0
- package/dist/observe.module.js +50 -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 +6 -4
- package/dist/outgoing/http.integration.js +3 -3
- package/dist/outgoing/outgoing-observe-agent.service.d.ts +2 -2
- package/dist/outgoing/outgoing-observe-agent.service.js +1 -1
- 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 +28 -21
- 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 +29 -1
- package/dist/services/operation-trace.registry.js +46 -5
- package/dist/utils/default-trace-id-generator.util.js +6 -2
- package/dist/utils/opentelemetry.util.d.ts +26 -0
- package/dist/utils/opentelemetry.util.js +48 -0
- package/dist/utils/trace-handoff.util.d.ts +45 -0
- package/dist/utils/trace-handoff.util.js +90 -0
- package/package.json +13 -12
|
@@ -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 };
|
|
@@ -28,8 +28,10 @@ export interface OutgoingHttpOptions {
|
|
|
28
28
|
* same process: its instrumentations write the header on the calls they
|
|
29
29
|
* cover, and a request takes only one.
|
|
30
30
|
*
|
|
31
|
-
* Only with `openTelemetry` on, and only
|
|
32
|
-
*
|
|
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.
|
|
33
35
|
* @default true, with `openTelemetry` on
|
|
34
36
|
*/
|
|
35
37
|
traceContext?: boolean;
|
|
@@ -61,7 +63,7 @@ export declare function subscribeOutgoingHttp(recorder: OutgoingSpanRecorder, cu
|
|
|
61
63
|
getRedactor?: () => LogRedactor | null,
|
|
62
64
|
/**
|
|
63
65
|
* Whether calls carry W3C Trace Context now: with `openTelemetry` on and
|
|
64
|
-
* `traceContext` not off, while the
|
|
65
|
-
* Off unless given.
|
|
66
|
+
* `traceContext` not off, while the agent reports to NestJS Observe (see
|
|
67
|
+
* `ObserveAgentSharedBuffer.isIngesting`). Off unless given.
|
|
66
68
|
*/
|
|
67
69
|
traceContextOn?: () => boolean): () => void;
|
|
@@ -27,8 +27,8 @@ export function subscribeOutgoingHttp(recorder, currentTrace, options = {},
|
|
|
27
27
|
getRedactor = () => null,
|
|
28
28
|
/**
|
|
29
29
|
* Whether calls carry W3C Trace Context now: with `openTelemetry` on and
|
|
30
|
-
* `traceContext` not off, while the
|
|
31
|
-
* Off unless given.
|
|
30
|
+
* `traceContext` not off, while the agent reports to NestJS Observe (see
|
|
31
|
+
* `ObserveAgentSharedBuffer.isIngesting`). Off unless given.
|
|
32
32
|
*/
|
|
33
33
|
traceContextOn = () => false) {
|
|
34
34
|
const spans = new WeakMap();
|
|
@@ -58,7 +58,7 @@ traceContextOn = () => false) {
|
|
|
58
58
|
// Only while `traceContextOn` says so, and then left to an OpenTelemetry
|
|
59
59
|
// SDK in this process when it propagates W3C Trace Context - see
|
|
60
60
|
// `openTelemetryWritesTraceparent`. Both asked per call: interop pauses
|
|
61
|
-
// while the collector
|
|
61
|
+
// while the collector refuses the app's credentials, and an SDK may be
|
|
62
62
|
// registered after the application starts.
|
|
63
63
|
const sendsTraceContext = () => traceContextOn() && !openTelemetryWritesTraceparent();
|
|
64
64
|
const open = (request, method, url, host, presetSpanId) => {
|
|
@@ -6,7 +6,7 @@ import { OperationTraceRegistry } from "../services/operation-trace.registry.js"
|
|
|
6
6
|
export declare class OutgoingObserveAgentService implements OnApplicationShutdown {
|
|
7
7
|
private readonly options;
|
|
8
8
|
/**
|
|
9
|
-
* Says whether the
|
|
9
|
+
* Says whether the agent reports to NestJS Observe, which W3C Trace
|
|
10
10
|
* Context waits on. Absent only where a test builds the service by hand,
|
|
11
11
|
* and interop then stays off.
|
|
12
12
|
*/
|
|
@@ -16,7 +16,7 @@ export declare class OutgoingObserveAgentService implements OnApplicationShutdow
|
|
|
16
16
|
private deactivateLlm?;
|
|
17
17
|
constructor(options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<any, any>>,
|
|
18
18
|
/**
|
|
19
|
-
* Says whether the
|
|
19
|
+
* Says whether the agent reports to NestJS Observe, which W3C Trace
|
|
20
20
|
* Context waits on. Absent only where a test builds the service by hand,
|
|
21
21
|
* and interop then stays off.
|
|
22
22
|
*/
|
|
@@ -126,7 +126,7 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
|
|
|
126
126
|
return { traceId, traceContext };
|
|
127
127
|
}, http, () => operationTraceRegistry.getRedactor(),
|
|
128
128
|
// W3C Trace Context goes out only with `openTelemetry` on, and only
|
|
129
|
-
// while the
|
|
129
|
+
// while the agent reports to NestJS Observe - see
|
|
130
130
|
// `ObserveAgentSharedBuffer.isIngesting`.
|
|
131
131
|
() => this.options.openTelemetry === true &&
|
|
132
132
|
http.traceContext !== false &&
|
|
@@ -5,8 +5,8 @@ const MAX_IDENTIFIER_LENGTH = 64;
|
|
|
5
5
|
* falls through to the verb alone - a wrong table is worse than none.
|
|
6
6
|
*/
|
|
7
7
|
const TABLE_AFTER = {
|
|
8
|
-
SELECT: /\bFROM\s+([\w."`[\]]+)/i,
|
|
9
|
-
DELETE: /\bFROM\s+([\w."`[\]]+)/i,
|
|
8
|
+
SELECT: /\bFROM\s+(?:ONLY\s+)?([\w."`[\]]+)/i,
|
|
9
|
+
DELETE: /\bFROM\s+(?:ONLY\s+)?([\w."`[\]]+)/i,
|
|
10
10
|
INSERT: /\bINTO\s+([\w."`[\]]+)/i,
|
|
11
11
|
REPLACE: /\bINTO\s+([\w."`[\]]+)/i,
|
|
12
12
|
UPDATE: /^\s*UPDATE\s+(?:ONLY\s+)?([\w."`[\]]+)/i,
|
|
@@ -69,14 +69,7 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
|
|
|
69
69
|
* to, so the HTTP side stands aside and everything else is still reported.
|
|
70
70
|
*/
|
|
71
71
|
private hasRequestHooks;
|
|
72
|
-
/**
|
|
73
|
-
* A CORS preflight, when `http.tracePreflights` has not asked for them.
|
|
74
|
-
*
|
|
75
|
-
* Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
|
|
76
|
-
* with an `Access-Control-Request-Method` header - rather than by the
|
|
77
|
-
* method alone, so an application's own `OPTIONS` handler is still traced.
|
|
78
|
-
* Every adapter lower-cases header names.
|
|
79
|
-
*/
|
|
72
|
+
/** A CORS preflight, when `http.tracePreflights` has not asked for them. */
|
|
80
73
|
private isUntracedPreflight;
|
|
81
74
|
private shouldIgnoreRequest;
|
|
82
75
|
}
|
|
@@ -109,9 +109,9 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
|
|
|
109
109
|
// identical object, one lookup fewer, and it is known to exist.
|
|
110
110
|
const store = new Map();
|
|
111
111
|
this.asyncLocalStorage.run(store, () => {
|
|
112
|
-
// OpenTelemetry interop runs only
|
|
113
|
-
//
|
|
114
|
-
//
|
|
112
|
+
// OpenTelemetry interop runs only beside reporting to NestJS Observe -
|
|
113
|
+
// see `ObserveAgentSharedBuffer.isIngesting`. Asked once per request,
|
|
114
|
+
// so a request is named and carried on one way throughout.
|
|
115
115
|
const openTelemetry = this.options.openTelemetry === true &&
|
|
116
116
|
this.observeAgentSharedBuffer.isIngesting();
|
|
117
117
|
const traceId = generateTraceIdSafely(openTelemetry && usesDefaultTraceIdGenerator(this.options)
|
|
@@ -131,12 +131,13 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
|
|
|
131
131
|
// outbound calls carry that one on either way - for an unrecorded
|
|
132
132
|
// request too, so the trace does not break here. An OpenTelemetry SDK
|
|
133
133
|
// in this process has the say on which trace that is, when one runs -
|
|
134
|
-
// see `inboundTraceContext`.
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
134
|
+
// see `inboundTraceContext`. The registry keeps it beside the
|
|
135
|
+
// snapshot too, for `otlp`, which puts the operation's span under it.
|
|
136
|
+
const traceContext = openTelemetry
|
|
137
|
+
? inboundTraceContext(req.headers)
|
|
138
|
+
: undefined;
|
|
139
|
+
if (traceContext) {
|
|
140
|
+
store.set(TRACE_CONTEXT_KEY, traceContext);
|
|
140
141
|
}
|
|
141
142
|
setAttributesSafely(this.options.http?.setAttributes, [req], this.options.http, store, this.logger, "http");
|
|
142
143
|
if (this.shouldIgnoreRequest(req) || this.isUntracedPreflight(req)) {
|
|
@@ -166,7 +167,12 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
|
|
|
166
167
|
method: req.method,
|
|
167
168
|
originalUrl,
|
|
168
169
|
},
|
|
169
|
-
}, traceId);
|
|
170
|
+
}, traceId, traceContext);
|
|
171
|
+
// Answered by the CORS layer before any route, and on Fastify before
|
|
172
|
+
// any middleware too: a preflight asked for has no span to keep it.
|
|
173
|
+
if (isPreflight(req)) {
|
|
174
|
+
this.operationTraceRegistry.keepWithoutSpans(registryKey);
|
|
175
|
+
}
|
|
170
176
|
this.evictTraceOnClientAbort(res, registryKey);
|
|
171
177
|
done();
|
|
172
178
|
});
|
|
@@ -253,18 +259,9 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
|
|
|
253
259
|
}
|
|
254
260
|
return false;
|
|
255
261
|
}
|
|
256
|
-
/**
|
|
257
|
-
* A CORS preflight, when `http.tracePreflights` has not asked for them.
|
|
258
|
-
*
|
|
259
|
-
* Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
|
|
260
|
-
* with an `Access-Control-Request-Method` header - rather than by the
|
|
261
|
-
* method alone, so an application's own `OPTIONS` handler is still traced.
|
|
262
|
-
* Every adapter lower-cases header names.
|
|
263
|
-
*/
|
|
262
|
+
/** A CORS preflight, when `http.tracePreflights` has not asked for them. */
|
|
264
263
|
isUntracedPreflight(req) {
|
|
265
|
-
return
|
|
266
|
-
req.method === "OPTIONS" &&
|
|
267
|
-
req.headers?.["access-control-request-method"] !== undefined);
|
|
264
|
+
return !this.options.http?.tracePreflights && isPreflight(req);
|
|
268
265
|
}
|
|
269
266
|
shouldIgnoreRequest(req) {
|
|
270
267
|
if (typeof this.options.http?.ignore === "function") {
|
|
@@ -322,3 +319,13 @@ function toGlobalRegExp(pattern) {
|
|
|
322
319
|
}
|
|
323
320
|
return new RegExp(pattern.source, pattern.flags + "g");
|
|
324
321
|
}
|
|
322
|
+
/**
|
|
323
|
+
* A CORS preflight: what the CORS spec defines one to be - `OPTIONS` with an
|
|
324
|
+
* `Access-Control-Request-Method` header - rather than the method alone, so
|
|
325
|
+
* an application's own `OPTIONS` handler is still traced as a request. Every
|
|
326
|
+
* adapter lower-cases header names.
|
|
327
|
+
*/
|
|
328
|
+
function isPreflight(req) {
|
|
329
|
+
return (req.method === "OPTIONS" &&
|
|
330
|
+
req.headers?.["access-control-request-method"] !== undefined);
|
|
331
|
+
}
|