@nestjs/observe 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +135 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/agent/detached-observe-worker.d.ts +1 -0
  5. package/dist/agent/detached-observe-worker.js +104 -0
  6. package/dist/agent/observe-agent.shared-buffer.d.ts +42 -0
  7. package/dist/agent/observe-agent.shared-buffer.js +211 -0
  8. package/dist/agent/observe-agent.worker.d.ts +25 -0
  9. package/dist/agent/observe-agent.worker.js +213 -0
  10. package/dist/custom-metrics/counter.d.ts +39 -0
  11. package/dist/custom-metrics/counter.js +128 -0
  12. package/dist/custom-metrics/gauge.d.ts +40 -0
  13. package/dist/custom-metrics/gauge.js +134 -0
  14. package/dist/custom-metrics/index.d.ts +3 -0
  15. package/dist/custom-metrics/index.js +3 -0
  16. package/dist/custom-metrics/summary.d.ts +38 -0
  17. package/dist/custom-metrics/summary.js +106 -0
  18. package/dist/encoders/custom-metrics.encoder.d.ts +25 -0
  19. package/dist/encoders/custom-metrics.encoder.js +50 -0
  20. package/dist/encoders/job-snapshot.encoder.d.ts +28 -0
  21. package/dist/encoders/job-snapshot.encoder.js +28 -0
  22. package/dist/encoders/remap-keys.util.d.ts +1 -0
  23. package/dist/encoders/remap-keys.util.js +10 -0
  24. package/dist/encoders/request-snapshot.encoder.d.ts +33 -0
  25. package/dist/encoders/request-snapshot.encoder.js +32 -0
  26. package/dist/encoders/runtime-metrics.encoder.d.ts +63 -0
  27. package/dist/encoders/runtime-metrics.encoder.js +55 -0
  28. package/dist/encoders/trace.encoder.d.ts +19 -0
  29. package/dist/encoders/trace.encoder.js +20 -0
  30. package/dist/index.d.ts +10 -0
  31. package/dist/index.js +10 -0
  32. package/dist/instrument/create-instance-decorator.instrument.d.ts +7 -0
  33. package/dist/instrument/create-instance-decorator.instrument.js +165 -0
  34. package/dist/interfaces/custom-metric.interface.d.ts +18 -0
  35. package/dist/interfaces/custom-metric.interface.js +1 -0
  36. package/dist/interfaces/graphql.interfaces.d.ts +12 -0
  37. package/dist/interfaces/graphql.interfaces.js +1 -0
  38. package/dist/interfaces/index.d.ts +7 -0
  39. package/dist/interfaces/index.js +7 -0
  40. package/dist/interfaces/job-snapshot.interface.d.ts +23 -0
  41. package/dist/interfaces/job-snapshot.interface.js +1 -0
  42. package/dist/interfaces/node-runtime-metrics.interface.d.ts +37 -0
  43. package/dist/interfaces/node-runtime-metrics.interface.js +1 -0
  44. package/dist/interfaces/observe-options.interface.d.ts +93 -0
  45. package/dist/interfaces/observe-options.interface.js +1 -0
  46. package/dist/interfaces/request-snapshot.interface.d.ts +23 -0
  47. package/dist/interfaces/request-snapshot.interface.js +1 -0
  48. package/dist/interfaces/trace-events.interfaces.d.ts +17 -0
  49. package/dist/interfaces/trace-events.interfaces.js +1 -0
  50. package/dist/interfaces/trace-span.interface.d.ts +12 -0
  51. package/dist/interfaces/trace-span.interface.js +1 -0
  52. package/dist/observe.constants.d.ts +2 -0
  53. package/dist/observe.constants.js +2 -0
  54. package/dist/observe.module.d.ts +20 -0
  55. package/dist/observe.module.js +181 -0
  56. package/dist/profiling/cpu-profiler.service.d.ts +45 -0
  57. package/dist/profiling/cpu-profiler.service.js +146 -0
  58. package/dist/profiling/fold-profile.util.d.ts +28 -0
  59. package/dist/profiling/fold-profile.util.js +0 -0
  60. package/dist/profiling/profile-uploader.d.ts +19 -0
  61. package/dist/profiling/profile-uploader.js +88 -0
  62. package/dist/profiling/span-slice-recorder.d.ts +18 -0
  63. package/dist/profiling/span-slice-recorder.js +78 -0
  64. package/dist/protocols/graphql-observe-agent.service.d.ts +58 -0
  65. package/dist/protocols/graphql-observe-agent.service.js +261 -0
  66. package/dist/protocols/graphql-operation-parser.d.ts +10 -0
  67. package/dist/protocols/graphql-operation-parser.js +174 -0
  68. package/dist/protocols/http-observe-agent.service.d.ts +31 -0
  69. package/dist/protocols/http-observe-agent.service.js +186 -0
  70. package/dist/protocols/queue-observe-agent.service.d.ts +15 -0
  71. package/dist/protocols/queue-observe-agent.service.js +132 -0
  72. package/dist/protocols/rpc-observe-agent.service.d.ts +33 -0
  73. package/dist/protocols/rpc-observe-agent.service.js +183 -0
  74. package/dist/services/index.d.ts +1 -0
  75. package/dist/services/index.js +1 -0
  76. package/dist/services/logger-patcher.service.d.ts +12 -0
  77. package/dist/services/logger-patcher.service.js +76 -0
  78. package/dist/services/node-runtime-metrics.service.d.ts +23 -0
  79. package/dist/services/node-runtime-metrics.service.js +156 -0
  80. package/dist/services/operation-trace.registry.d.ts +49 -0
  81. package/dist/services/operation-trace.registry.js +364 -0
  82. package/dist/services/stdout-forwarder.service.d.ts +21 -0
  83. package/dist/services/stdout-forwarder.service.js +128 -0
  84. package/dist/services/trace-sampler.service.d.ts +19 -0
  85. package/dist/services/trace-sampler.service.js +38 -0
  86. package/dist/services/tracer.service.d.ts +48 -0
  87. package/dist/services/tracer.service.js +186 -0
  88. package/dist/trace-span.delegate.d.ts +10 -0
  89. package/dist/trace-span.delegate.js +24 -0
  90. package/dist/types/key-of.type.d.ts +1 -0
  91. package/dist/types/key-of.type.js +1 -0
  92. package/dist/types/path-value.type.d.ts +6 -0
  93. package/dist/types/path-value.type.js +1 -0
  94. package/dist/utils/assert-module-options.util.d.ts +2 -0
  95. package/dist/utils/assert-module-options.util.js +8 -0
  96. package/dist/utils/default-trace-id-generator.util.d.ts +1 -0
  97. package/dist/utils/default-trace-id-generator.util.js +11 -0
  98. package/dist/utils/log-line.parser.d.ts +9 -0
  99. package/dist/utils/log-line.parser.js +59 -0
  100. package/dist/utils/log-redactor.d.ts +11 -0
  101. package/dist/utils/log-redactor.js +150 -0
  102. package/dist/utils/redact-url-query.d.ts +2 -0
  103. package/dist/utils/redact-url-query.js +51 -0
  104. package/dist/utils/source-context.util.d.ts +11 -0
  105. package/dist/utils/source-context.util.js +130 -0
  106. package/dist/utils/source-map-resolver.util.d.ts +7 -0
  107. package/dist/utils/source-map-resolver.util.js +107 -0
  108. package/package.json +129 -0
@@ -0,0 +1,364 @@
1
+ import { IntrinsicException, Logger } from "@nestjs/common";
2
+ import { activeSliceRecorder } from "../profiling/span-slice-recorder.js";
3
+ import { randomUUID } from "crypto";
4
+ import { TraceSpanDelegate } from "../trace-span.delegate.js";
5
+ import { collectCodeFrames } from "../utils/source-context.util.js";
6
+ import { CALLER_METADATA_KEY } from "../observe.constants.js";
7
+ const SNAPSHOT_COMPLETION_TIMEOUT_MS = 1000;
8
+ const UNHANDLED_ERROR_STATUS_CODE = 500;
9
+ const HANDLED_ERROR_STATUS_CODE = 400;
10
+ export class OperationTraceRegistry {
11
+ als;
12
+ sourceContext;
13
+ traceSnapshots = new Map();
14
+ callerIdsByTraceId = new Map();
15
+ logger = new Logger(OperationTraceRegistry.name);
16
+ hasReportedMissingInstrumentation = false;
17
+ constructor(als, sourceContext = true) {
18
+ this.als = als;
19
+ this.sourceContext = sourceContext;
20
+ }
21
+ toErrorPayload(error) {
22
+ const payload = error instanceof Error
23
+ ? { message: error.message, stack: error.stack }
24
+ : { message: String(error), stack: undefined };
25
+ const result = payload;
26
+ if (typeof error?.constructor === "function") {
27
+ result.cls = error.constructor.name;
28
+ }
29
+ if (this.sourceContext !== false) {
30
+ const settings = this.sourceContext === true ? {} : this.sourceContext;
31
+ const codeFrames = collectCodeFrames(payload.stack, settings ?? {});
32
+ if (codeFrames) {
33
+ result.codeFrames = codeFrames;
34
+ }
35
+ }
36
+ return result;
37
+ }
38
+ startTrace(traceId, data) {
39
+ if (this.traceSnapshots.has(traceId)) {
40
+ this.logger.warn(`Trace already started for traceId: "${traceId}". Overwriting existing trace.`);
41
+ this.traceSnapshots.delete(traceId);
42
+ this.callerIdsByTraceId.delete(traceId);
43
+ }
44
+ const snapshot = {
45
+ ...data,
46
+ traceId,
47
+ calledAt: new Date().toISOString(),
48
+ startTimestamp: performance.now(),
49
+ traces: [],
50
+ refsCounter: 0,
51
+ refsMarkedAsComplete: 0,
52
+ };
53
+ this.traceSnapshots.set(traceId, snapshot);
54
+ }
55
+ endTrace(traceId, opts = {}) {
56
+ const snapshot = this.traceSnapshots.get(traceId);
57
+ if (!snapshot) {
58
+ return;
59
+ }
60
+ if (snapshot.traces.length === 0) {
61
+ if ("operationId" in snapshot) {
62
+ this.reportMissingInstrumentation(snapshot);
63
+ this.traceSnapshots.delete(traceId);
64
+ return;
65
+ }
66
+ this.traceSnapshots.delete(traceId);
67
+ return;
68
+ }
69
+ const startTimestamp = snapshot.startTimestamp ?? performance.now();
70
+ snapshot.duration = performance.now() - startTimestamp;
71
+ const reportedStatusCode = "statusCode" in opts && typeof opts.statusCode === "number"
72
+ ? opts.statusCode
73
+ : undefined;
74
+ const errorStatusCode = "protocol" in snapshot ? snapshot.errorStatusCode : undefined;
75
+ const statusCode = errorStatusCode !== undefined &&
76
+ (reportedStatusCode === undefined || reportedStatusCode < 400)
77
+ ? errorStatusCode
78
+ : reportedStatusCode;
79
+ if (typeof statusCode === "number") {
80
+ this.setStatusCode(snapshot, statusCode);
81
+ }
82
+ if ("status" in opts && typeof opts.status === "string") {
83
+ const jobSnapshot = snapshot;
84
+ jobSnapshot.status = opts.status;
85
+ }
86
+ if ("userId" in opts && typeof opts.userId !== "undefined") {
87
+ const requestSnapshot = snapshot;
88
+ requestSnapshot.userId = String(opts.userId);
89
+ }
90
+ delete snapshot.startTimestamp;
91
+ if (snapshot.traces && snapshot.traces.length > 0) {
92
+ for (const trace of snapshot.traces) {
93
+ if ("error" in trace && trace.error) {
94
+ if (typeof trace.error === "object") {
95
+ snapshot.error = trace.error;
96
+ }
97
+ break;
98
+ }
99
+ }
100
+ }
101
+ }
102
+ reportMissingInstrumentation(snapshot) {
103
+ const method = snapshot.attributes?.method;
104
+ const operation = method
105
+ ? `${method} ${snapshot.operationId}`
106
+ : snapshot.operationId;
107
+ if (this.hasReportedMissingInstrumentation) {
108
+ this.logger.error(`Operation "${operation}" produced no spans - the "instrument" option is still missing from NestFactory (traceId: "${snapshot.traceId}").`);
109
+ return;
110
+ }
111
+ this.hasReportedMissingInstrumentation = true;
112
+ this.logger.error([
113
+ `Operation "${operation}" produced no spans, so this request is missing from your traces (traceId: "${snapshot.traceId}").`,
114
+ `The handler ran, but none of its providers were instrumented - which happens when the "instrument" option never reaches NestFactory.`,
115
+ ``,
116
+ `Pass the instrument that createObserveModule() returns next to the module it belongs to:`,
117
+ ``,
118
+ ` // app.module.ts`,
119
+ ` export const { ObserveModule, ObserveInstrument } = createObserveModule();`,
120
+ ``,
121
+ ` // main.ts`,
122
+ ` const app = await NestFactory.create(AppModule, {`,
123
+ ` instrument: ObserveInstrument,`,
124
+ ` });`,
125
+ ``,
126
+ `NestFactory.createMicroservice() accepts the same option. Later occurrences of this error are logged on a single line.`,
127
+ ].join("\n"));
128
+ }
129
+ toErrorStatusCode(error) {
130
+ if (!(error instanceof IntrinsicException)) {
131
+ return UNHANDLED_ERROR_STATUS_CODE;
132
+ }
133
+ const status = error.getStatus?.();
134
+ if (typeof status === "number" && status >= 400 && status < 500) {
135
+ return status;
136
+ }
137
+ return HANDLED_ERROR_STATUS_CODE;
138
+ }
139
+ setStatusCode(snapshot, statusCode) {
140
+ const requestSnapshot = snapshot;
141
+ if (!requestSnapshot.attributes) {
142
+ requestSnapshot.attributes = {};
143
+ }
144
+ requestSnapshot.attributes.statusCode = statusCode;
145
+ }
146
+ internalStartTraceStep(traceId, className, methodKey, callerId) {
147
+ const snapshot = this.traceSnapshots.get(traceId);
148
+ if (!snapshot) {
149
+ return undefined;
150
+ }
151
+ snapshot.refsCounter += 1;
152
+ const newNodeId = randomUUID();
153
+ const startTime = performance.now();
154
+ activeSliceRecorder()?.enter(traceId, newNodeId, startTime);
155
+ const newNode = {
156
+ origin: "auto",
157
+ type: "start",
158
+ className,
159
+ methodKey,
160
+ startTime,
161
+ startOffset: this.toStartOffset(snapshot, startTime),
162
+ children: [],
163
+ spanId: newNodeId,
164
+ };
165
+ let refsByCaller = this.callerIdsByTraceId.get(traceId);
166
+ if (callerId) {
167
+ const caller = refsByCaller.get(callerId);
168
+ caller.children.push(newNode);
169
+ newNode.parent = caller;
170
+ }
171
+ else {
172
+ snapshot.traces.push(newNode);
173
+ }
174
+ if (!refsByCaller) {
175
+ refsByCaller = new Map();
176
+ this.callerIdsByTraceId.set(traceId, refsByCaller);
177
+ }
178
+ refsByCaller.set(newNodeId, newNode);
179
+ return newNodeId;
180
+ }
181
+ internalEndTraceStep(traceId, spanId, className, methodKey, callerId, error) {
182
+ const snapshot = this.traceSnapshots.get(traceId);
183
+ if (!snapshot) {
184
+ this.logger.error(`No snapshot found for traceId: "${traceId}". Cannot end trace step for "${className}#${methodKey}".`);
185
+ return;
186
+ }
187
+ snapshot.refsMarkedAsComplete += 1;
188
+ activeSliceRecorder()?.exit(callerId);
189
+ const refsByCaller = this.callerIdsByTraceId.get(traceId);
190
+ if (!refsByCaller) {
191
+ this.logger.warn(`No ongoing ref map found for the "${spanId}" span. Some of your async operations were not awaited and the outer span ended before the inner one. Check your "${className}#${methodKey}" method. Ignore if this is the desired behavior.`);
192
+ return;
193
+ }
194
+ const cursor = refsByCaller.get(callerId);
195
+ if (!cursor) {
196
+ this.logger.warn(`No ongoing trace found for the "${spanId}" span. Some of your async operations were not awaited and the outer span ended before the inner one. Check your "${className}#${methodKey}" method. Ignore if this is the desired behavior.`);
197
+ return;
198
+ }
199
+ const duration = performance.now() - cursor.startTime;
200
+ const completing = cursor;
201
+ delete completing.type;
202
+ delete completing.startTime;
203
+ const parent = cursor.parent;
204
+ delete completing.parent;
205
+ if (Object.keys(cursor.tags || {}).length === 0) {
206
+ delete completing.tags;
207
+ }
208
+ if (cursor.children.length === 0) {
209
+ delete completing.children;
210
+ }
211
+ const activeTrace = cursor;
212
+ activeTrace.duration = duration;
213
+ if (error && !activeTrace.error) {
214
+ const isRootSpan = !parent;
215
+ if (isRootSpan) {
216
+ snapshot.errorStatusCode = this.toErrorStatusCode(error);
217
+ if (typeof error === "object") {
218
+ activeTrace.error = this.toErrorPayload(error);
219
+ }
220
+ else {
221
+ activeTrace.error = true;
222
+ }
223
+ }
224
+ else {
225
+ activeTrace.error = true;
226
+ }
227
+ }
228
+ }
229
+ addRouteMetadataToTrace(requestId, requestMethod, path) {
230
+ const snapshot = this.traceSnapshots.get(requestId);
231
+ if (!snapshot) {
232
+ return;
233
+ }
234
+ snapshot.operationId = path;
235
+ }
236
+ addGraphQLMetadataToTrace(traceId, metadata) {
237
+ const snapshot = this.traceSnapshots.get(traceId);
238
+ if (!snapshot) {
239
+ return;
240
+ }
241
+ snapshot.operationId ??= metadata.operationId;
242
+ if (metadata.tags) {
243
+ snapshot.tags = { ...snapshot.tags, ...metadata.tags };
244
+ }
245
+ if (metadata.attributes) {
246
+ snapshot.attributes = { ...snapshot.attributes, ...metadata.attributes };
247
+ }
248
+ }
249
+ toStartOffset(snapshot, startTime) {
250
+ if (typeof snapshot?.startTimestamp !== "number") {
251
+ return undefined;
252
+ }
253
+ return startTime - snapshot.startTimestamp;
254
+ }
255
+ captureError(traceId, callerId, error, tags) {
256
+ const snapshot = this.traceSnapshots.get(traceId);
257
+ if (!snapshot) {
258
+ this.logger.warn(`No request snapshot found for traceId: "${traceId}". Cannot capture error.`);
259
+ return;
260
+ }
261
+ if (!snapshot.traces || snapshot.traces.length === 0) {
262
+ this.logger.warn(`No traces found for traceId: "${traceId}". Cannot capture error.`);
263
+ return;
264
+ }
265
+ const refsByCaller = this.callerIdsByTraceId.get(traceId);
266
+ const targetSpan = refsByCaller?.get(callerId);
267
+ if (!targetSpan) {
268
+ this.logger.warn(`No active span found for traceId: "${traceId}". Cannot capture error.`);
269
+ return;
270
+ }
271
+ if (!targetSpan.tags) {
272
+ targetSpan.tags = {};
273
+ }
274
+ Object.assign(targetSpan.tags, tags);
275
+ targetSpan.error = this.toErrorPayload(error);
276
+ }
277
+ abandonTrace(traceId) {
278
+ this.callerIdsByTraceId.delete(traceId);
279
+ this.traceSnapshots.delete(traceId);
280
+ }
281
+ async pluckSnapshot(traceId) {
282
+ const snapshot = this.traceSnapshots.get(traceId);
283
+ if (snapshot) {
284
+ const cleanup = () => {
285
+ this.callerIdsByTraceId.delete(traceId);
286
+ this.traceSnapshots.delete(traceId);
287
+ };
288
+ if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
289
+ await new Promise((resolve) => setTimeout(resolve, SNAPSHOT_COMPLETION_TIMEOUT_MS));
290
+ if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
291
+ cleanup();
292
+ return undefined;
293
+ }
294
+ }
295
+ cleanup();
296
+ const bookkeeping = snapshot;
297
+ delete bookkeeping.refsCounter;
298
+ delete bookkeeping.refsMarkedAsComplete;
299
+ delete bookkeeping.errorStatusCode;
300
+ return snapshot;
301
+ }
302
+ return undefined;
303
+ }
304
+ getActiveSpan(traceId, callerId) {
305
+ const refsByCaller = this.callerIdsByTraceId.get(traceId);
306
+ if (!refsByCaller) {
307
+ return undefined;
308
+ }
309
+ const activeSpan = refsByCaller.get(callerId);
310
+ return activeSpan;
311
+ }
312
+ async createManualSpan(traceId, callerId, name, spanFunction) {
313
+ const activeSpan = this.getActiveSpan(traceId, callerId);
314
+ if (!activeSpan) {
315
+ return spanFunction(new TraceSpanDelegate("", name, {}));
316
+ }
317
+ const snapshot = this.traceSnapshots.get(traceId);
318
+ if (snapshot) {
319
+ snapshot.refsCounter += 1;
320
+ }
321
+ const newNodeId = randomUUID();
322
+ const startTime = performance.now();
323
+ activeSliceRecorder()?.enter(traceId, newNodeId, startTime);
324
+ const manualSpan = {
325
+ spanId: newNodeId,
326
+ name,
327
+ origin: "manual",
328
+ type: "start",
329
+ className: activeSpan.className,
330
+ methodKey: activeSpan.methodKey,
331
+ startTime,
332
+ startOffset: this.toStartOffset(snapshot, startTime),
333
+ children: [],
334
+ parent: activeSpan,
335
+ };
336
+ activeSpan.children.push(manualSpan);
337
+ this.callerIdsByTraceId.get(traceId)?.set(newNodeId, manualSpan);
338
+ const onResponse = (res) => {
339
+ this.internalEndTraceStep(traceId, newNodeId, manualSpan.className, manualSpan.methodKey, newNodeId);
340
+ return res;
341
+ };
342
+ const onError = (err) => {
343
+ this.internalEndTraceStep(traceId, newNodeId, manualSpan.className, manualSpan.methodKey, newNodeId, err);
344
+ throw err;
345
+ };
346
+ const tags = {};
347
+ const delegate = new TraceSpanDelegate(newNodeId, manualSpan.name, tags);
348
+ manualSpan.tags = tags;
349
+ const store = this.als.getStore();
350
+ return this.als.run(new Map([...(store?.entries() ?? []), [CALLER_METADATA_KEY, newNodeId]]), () => {
351
+ try {
352
+ const result = spanFunction(delegate);
353
+ if (result instanceof Promise) {
354
+ return result.then(onResponse).catch(onError);
355
+ }
356
+ return onResponse(result);
357
+ }
358
+ catch (err) {
359
+ onError(err);
360
+ throw err;
361
+ }
362
+ });
363
+ }
364
+ }
@@ -0,0 +1,21 @@
1
+ import { OnModuleDestroy, OnModuleInit } from "@nestjs/common";
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
4
+ import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
5
+ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDestroy {
6
+ private readonly options;
7
+ private readonly observeAgentSharedBuffer;
8
+ private readonly als;
9
+ private readonly logger;
10
+ private partialLine;
11
+ private originalWrite;
12
+ private readonly redactor;
13
+ constructor(options: ObserveModuleOptionsWithDefaults, observeAgentSharedBuffer: ObserveAgentSharedBuffer, als: AsyncLocalStorage<Map<string, any>>);
14
+ onModuleInit(): void;
15
+ onModuleDestroy(): void;
16
+ start(): void;
17
+ private restore;
18
+ private consume;
19
+ private flushPartial;
20
+ private toLogEntry;
21
+ }
@@ -0,0 +1,128 @@
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 StdoutForwarderService_1;
14
+ import { Inject, Injectable, Logger, } from "@nestjs/common";
15
+ import { AsyncLocalStorage } from "async_hooks";
16
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
17
+ import { parseLogLine } from "../utils/log-line.parser.js";
18
+ import { LogRedactor } from "../utils/log-redactor.js";
19
+ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
20
+ const MAX_PARTIAL_LINE_LENGTH = 8 * 1024;
21
+ const MAX_PARSED_LINE_LENGTH = 16 * 1024;
22
+ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderService {
23
+ options;
24
+ observeAgentSharedBuffer;
25
+ als;
26
+ logger = new Logger(StdoutForwarderService_1.name);
27
+ partialLine = "";
28
+ originalWrite = null;
29
+ redactor;
30
+ constructor(options, observeAgentSharedBuffer, als) {
31
+ this.options = options;
32
+ this.observeAgentSharedBuffer = observeAgentSharedBuffer;
33
+ this.als = als;
34
+ this.redactor =
35
+ this.options.redaction?.enabled === false
36
+ ? null
37
+ : new LogRedactor(this.options.redaction);
38
+ if (this.options.forwardLogs) {
39
+ this.start();
40
+ }
41
+ }
42
+ onModuleInit() {
43
+ if (this.options.debug) {
44
+ this.logger.debug("Forwarding logs to stdout is enabled.");
45
+ }
46
+ }
47
+ onModuleDestroy() {
48
+ this.restore();
49
+ }
50
+ start() {
51
+ if (this.originalWrite) {
52
+ return;
53
+ }
54
+ this.originalWrite = process.stdout.write;
55
+ const originalWrite = process.stdout.write.bind(process.stdout);
56
+ process.stdout.write = ((chunk, encoding, callback) => {
57
+ if (typeof chunk === "string") {
58
+ try {
59
+ this.consume(chunk);
60
+ }
61
+ catch {
62
+ }
63
+ }
64
+ return originalWrite(chunk, encoding, callback);
65
+ });
66
+ }
67
+ restore() {
68
+ if (!this.originalWrite) {
69
+ return;
70
+ }
71
+ this.flushPartial();
72
+ process.stdout.write = this.originalWrite;
73
+ this.originalWrite = null;
74
+ }
75
+ consume(chunk) {
76
+ const combined = this.partialLine + chunk;
77
+ const segments = combined.split("\n");
78
+ this.partialLine = segments.pop() ?? "";
79
+ const entries = segments
80
+ .filter((line) => line.trim().length > 0)
81
+ .map((line) => this.toLogEntry(line));
82
+ if (entries.length > 0) {
83
+ this.observeAgentSharedBuffer.pushLogs(entries);
84
+ }
85
+ if (this.partialLine.length > MAX_PARTIAL_LINE_LENGTH) {
86
+ this.flushPartial();
87
+ }
88
+ }
89
+ flushPartial() {
90
+ if (this.partialLine.trim().length === 0) {
91
+ this.partialLine = "";
92
+ return;
93
+ }
94
+ this.observeAgentSharedBuffer.pushLogs([this.toLogEntry(this.partialLine)]);
95
+ this.partialLine = "";
96
+ }
97
+ toLogEntry(rawLine) {
98
+ const line = rawLine.length > MAX_PARSED_LINE_LENGTH
99
+ ? rawLine.slice(0, MAX_PARSED_LINE_LENGTH)
100
+ : rawLine;
101
+ const parsed = parseLogLine(line);
102
+ const store = this.als.getStore();
103
+ const contextTraceId = store?.get(this.options.traceIdKey);
104
+ const traceId = parsed.traceId ?? contextTraceId;
105
+ return {
106
+ timestamp: Date.now(),
107
+ traceId,
108
+ spanId: traceId === contextTraceId
109
+ ? store?.get(CALLER_METADATA_KEY)
110
+ : undefined,
111
+ level: parsed.level,
112
+ context: parsed.context,
113
+ attributes: this.redactor
114
+ ? this.redactor.redactAttributes(parsed.attributes)
115
+ : parsed.attributes,
116
+ text: this.redactor
117
+ ? this.redactor.redactMessage(parsed.message)
118
+ : parsed.message,
119
+ };
120
+ }
121
+ };
122
+ StdoutForwarderService = StdoutForwarderService_1 = __decorate([
123
+ Injectable(),
124
+ __param(0, Inject(OBSERVE_OPTIONS)),
125
+ __metadata("design:paramtypes", [Object, ObserveAgentSharedBuffer,
126
+ AsyncLocalStorage])
127
+ ], StdoutForwarderService);
128
+ export { StdoutForwarderService };
@@ -0,0 +1,19 @@
1
+ import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
2
+ export declare class TraceSamplerService {
3
+ private readonly options;
4
+ constructor(options: ObserveModuleOptionsWithDefaults);
5
+ shouldCapture(protocol: "http", attributes: {
6
+ url: string;
7
+ method: string;
8
+ }): boolean;
9
+ shouldCapture(protocol: "rpc", attributes: {
10
+ transport: string;
11
+ ctx: Record<string, any>;
12
+ }): boolean;
13
+ shouldCapture(protocol: "grpc", attributes: {
14
+ call: Record<string, any>;
15
+ }): boolean;
16
+ shouldCapture(protocol: "graphql", attributes: {
17
+ operationId: string;
18
+ }): boolean;
19
+ }
@@ -0,0 +1,38 @@
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
+ import { Inject, Injectable } from "@nestjs/common";
14
+ import { OBSERVE_OPTIONS } from "../observe.constants.js";
15
+ let TraceSamplerService = class TraceSamplerService {
16
+ options;
17
+ constructor(options) {
18
+ this.options = options;
19
+ }
20
+ shouldCapture(protocol, attributes) {
21
+ if (!this.options.tracesSampleRate) {
22
+ return true;
23
+ }
24
+ if (typeof this.options.tracesSampleRate === "number") {
25
+ if (this.options.tracesSampleRate >= 1) {
26
+ return true;
27
+ }
28
+ return Math.random() < this.options.tracesSampleRate;
29
+ }
30
+ return this.options.tracesSampleRate(protocol, attributes);
31
+ }
32
+ };
33
+ TraceSamplerService = __decorate([
34
+ Injectable(),
35
+ __param(0, Inject(OBSERVE_OPTIONS)),
36
+ __metadata("design:paramtypes", [Object])
37
+ ], TraceSamplerService);
38
+ export { TraceSamplerService };
@@ -0,0 +1,48 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
2
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
3
+ import { Gauge, GaugeKind, Summary } from "../custom-metrics/index.js";
4
+ import { Counter } from "../custom-metrics/counter.js";
5
+ import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
6
+ import { TraceSpanDelegate } from "../trace-span.delegate.js";
7
+ import { KeyOf } from "../types/key-of.type.js";
8
+ import { Path, PathValue } from "../types/path-value.type.js";
9
+ import { OperationTraceRegistry } from "./operation-trace.registry.js";
10
+ export declare class TracerService<Store extends Record<string | symbol, unknown> = Record<string | symbol, unknown>, TraceKey extends string = "traceId"> {
11
+ private readonly operationTraceRegistry;
12
+ private readonly als;
13
+ private readonly observeAgentSharedBuffer;
14
+ private readonly options;
15
+ private readonly counters;
16
+ private readonly gauges;
17
+ private readonly summaries;
18
+ constructor(operationTraceRegistry: OperationTraceRegistry, als: AsyncLocalStorage<Map<KeyOf<Store> | TraceKey, any>>, observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults);
19
+ createSpan(name: string, callback: (span: TraceSpanDelegate) => unknown | Promise<unknown>): Promise<any>;
20
+ activeSpan(): Promise<TraceSpanDelegate>;
21
+ captureError(error: Error, tags?: Record<string, string | number | boolean>): Promise<void>;
22
+ counter<TLabel extends string = "default">(name: string): Counter<TLabel>;
23
+ counter<TLabel extends string = "default">(name: string, attributes: {
24
+ description?: string;
25
+ initialValue?: number;
26
+ labels?: TLabel[];
27
+ }): Counter<TLabel>;
28
+ gauge<TLabel extends string = "default">(name: string): Gauge<TLabel>;
29
+ gauge<TLabel extends string = "default">(name: string, attributes: {
30
+ description?: string;
31
+ initialValue?: number;
32
+ labels?: TLabel[];
33
+ kind?: GaugeKind;
34
+ }): Gauge<TLabel>;
35
+ summary<TLabel extends string = "default">(name: string): Summary<TLabel>;
36
+ summary<TLabel extends string = "default">(name: string, attributes: {
37
+ description?: string;
38
+ labels?: TLabel[];
39
+ sampleSize?: number;
40
+ }): Summary<TLabel>;
41
+ currentTraceId(): string | null;
42
+ setAttribute<P extends Path<Store>>(key: P, value: PathValue<Store, P>): void;
43
+ getAttribute<P extends Path<Store>>(key: P): PathValue<Store, P> | undefined;
44
+ private requireTraceId;
45
+ private registerCounterChangeHandler;
46
+ private registerGaugeChangeHandler;
47
+ private registerSummaryChangeHandler;
48
+ }