@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 @@
1
+ export declare const detachedObserveWorker: () => void;
@@ -0,0 +1,104 @@
1
+ export const detachedObserveWorker = () => {
2
+ const { parentPort, workerData } = require("worker_threads");
3
+ const zlib = require("zlib");
4
+ const { sharedBuffer, config } = workerData;
5
+ const buffer = new Uint8Array(sharedBuffer);
6
+ const lock = new Int32Array(sharedBuffer, 0, 1);
7
+ const view = new DataView(sharedBuffer, 4, 4);
8
+ const decoder = new TextDecoder();
9
+ const telemetryUrl = `${config.endpoint}/applications/telemetry`;
10
+ const headers = {
11
+ "Content-Type": "application/json",
12
+ "Content-Encoding": "gzip",
13
+ };
14
+ if (config.appKey && config.appSecret) {
15
+ headers["x-api-key"] = config.appKey;
16
+ headers["x-api-secret"] = config.appSecret;
17
+ }
18
+ let authRejections = 0;
19
+ const AUTH_REJECTION_REPORT_EVERY = 720;
20
+ const LOCK_WAIT_MS = 100;
21
+ const IDLE_SLEEP_MS = 50;
22
+ const acquireLock = () => Atomics.compareExchange(lock, 0, 0, 1) === 0;
23
+ const waitWhileLocked = () => {
24
+ if (Atomics.load(lock, 0) !== 0) {
25
+ Atomics.wait(lock, 0, 1, LOCK_WAIT_MS);
26
+ }
27
+ };
28
+ const releaseLock = () => {
29
+ Atomics.store(lock, 0, 0);
30
+ Atomics.notify(lock, 0);
31
+ };
32
+ const clearBuffer = () => view.setUint32(0, 0);
33
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
34
+ const sendInstrumentationJsonData = async () => {
35
+ waitWhileLocked();
36
+ if (!acquireLock()) {
37
+ return false;
38
+ }
39
+ try {
40
+ const jsonLength = view.getUint32(0);
41
+ if (jsonLength === 0) {
42
+ return false;
43
+ }
44
+ const jsonBytes = buffer.slice(8, 8 + jsonLength);
45
+ const jsonStr = decoder.decode(jsonBytes);
46
+ const compressed = await new Promise((resolve, reject) => zlib.gzip(jsonStr, (err, compressed) => {
47
+ if (err) {
48
+ reject(err);
49
+ }
50
+ else {
51
+ resolve(compressed);
52
+ }
53
+ }));
54
+ const response = await fetch(telemetryUrl, {
55
+ method: "POST",
56
+ headers,
57
+ body: compressed,
58
+ });
59
+ if (!response.ok) {
60
+ if (response.status === 401 || response.status === 403) {
61
+ authRejections += 1;
62
+ if (authRejections === 1) {
63
+ parentPort.postMessage(`Error: Telemetry rejected (${response.status}). Check that appKey and appSecret are valid; ` +
64
+ `the application is taken from the key. Credentials are read once at start-up, so this ` +
65
+ `will not recover without a restart - further rejections are counted, not logged.`);
66
+ }
67
+ else if (authRejections % AUTH_REJECTION_REPORT_EVERY === 0) {
68
+ parentPort.postMessage(`Error: Telemetry still rejected (${response.status}); ${authRejections} batches dropped since start-up.`);
69
+ }
70
+ return true;
71
+ }
72
+ const errorBody = await response.text().catch(() => "");
73
+ parentPort.postMessage(`Error: Failed to send data. ${response.statusText} (${response.status})` +
74
+ (errorBody ? ` - ${errorBody.slice(0, 500)}` : ""));
75
+ return true;
76
+ }
77
+ parentPort.postMessage("Tracing and instrumentation data sent successfully");
78
+ return true;
79
+ }
80
+ catch (err) {
81
+ const cause = err
82
+ ?.cause;
83
+ const reason = cause?.code ?? cause?.message;
84
+ parentPort.postMessage(`Error: Could not reach the collector at ${telemetryUrl}` +
85
+ (reason ? ` (${reason})` : "") +
86
+ `. Check that it is running and that \`endpoint\` points at it.`);
87
+ return true;
88
+ }
89
+ finally {
90
+ clearBuffer();
91
+ releaseLock();
92
+ }
93
+ };
94
+ const run = async () => {
95
+ parentPort.postMessage("Ready to process instrumentation data");
96
+ for (;;) {
97
+ const sent = await sendInstrumentationJsonData();
98
+ if (!sent) {
99
+ await sleep(IDLE_SLEEP_MS);
100
+ }
101
+ }
102
+ };
103
+ run();
104
+ };
@@ -0,0 +1,42 @@
1
+ import { Counter, Gauge, Summary } from "../custom-metrics/index.js";
2
+ import { JobSnapshot } from "../interfaces/job-snapshot.interface.js";
3
+ import { NodeRuntimeMetrics } from "../interfaces/node-runtime-metrics.interface.js";
4
+ import { RequestSnapshot } from "../interfaces/request-snapshot.interface.js";
5
+ import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
6
+ interface BufferedLogEntry {
7
+ timestamp: number;
8
+ traceId?: string;
9
+ spanId?: string;
10
+ level?: string;
11
+ context?: string;
12
+ attributes?: Record<string, unknown>;
13
+ text: string;
14
+ }
15
+ export declare class ObserveAgentSharedBuffer {
16
+ private readonly options;
17
+ private readonly _sharedBuffer;
18
+ private readonly lock;
19
+ private readonly sharedBytes;
20
+ private readonly encoder;
21
+ private readonly logger;
22
+ private _mainThreadBuffer;
23
+ private readonly _pendingLogs;
24
+ private readonly _awaitingFlushAck;
25
+ get sharedBuffer(): SharedArrayBuffer;
26
+ constructor(options: ObserveModuleOptionsWithDefaults);
27
+ insertRequestSnapshot(snapshot: RequestSnapshot): void;
28
+ insertJobSnapshot(jobSnapshot: JobSnapshot): void;
29
+ isBufferLocked(): boolean;
30
+ isBufferEmpty(): boolean;
31
+ acquireLock(): boolean;
32
+ releaseLock(): void;
33
+ addNodeRuntimeMetrics(runtimeMetrics: NodeRuntimeMetrics | undefined): void;
34
+ upsertCustomMetric(metric: Counter<any> | Gauge<any> | Summary<any>): void;
35
+ pushLogs(logs: Array<BufferedLogEntry>): void;
36
+ drainPendingLogs(): void;
37
+ private truncateLogText;
38
+ encodeAndWrite(): void;
39
+ resetMainThreadBuffer(): void;
40
+ private createEmptyPayload;
41
+ }
42
+ export {};
@@ -0,0 +1,211 @@
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 ObserveAgentSharedBuffer_1;
14
+ import { Inject, Injectable, Logger } from "@nestjs/common";
15
+ import { Counter, Summary } from "../custom-metrics/index.js";
16
+ import { CustomMetricsEncoder, } from "../encoders/custom-metrics.encoder.js";
17
+ import { JobSnapshotEncoder, } from "../encoders/job-snapshot.encoder.js";
18
+ import { RequestSnapshotEncoder, } from "../encoders/request-snapshot.encoder.js";
19
+ import { RuntimeMetricsEncoder, } from "../encoders/runtime-metrics.encoder.js";
20
+ import { OBSERVE_OPTIONS } from "../observe.constants.js";
21
+ const SHARED_BUFFER_SIZE = 1024 * 1024 * 16;
22
+ const DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION = 1000;
23
+ const MAX_LOGS_PER_TRANSACTION = 250;
24
+ const MAX_LOG_ENTRY_LENGTH = 4 * 1024;
25
+ const TRUNCATION_SUFFIX = "... [truncated by observe]";
26
+ const MAX_PENDING_LOGS = 2000;
27
+ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSharedBuffer {
28
+ options;
29
+ _sharedBuffer = new SharedArrayBuffer(SHARED_BUFFER_SIZE);
30
+ lock = new Int32Array(this._sharedBuffer, 0, 1);
31
+ sharedBytes = new Uint8Array(this._sharedBuffer);
32
+ encoder = new TextEncoder();
33
+ logger = new Logger(ObserveAgentSharedBuffer_1.name);
34
+ _mainThreadBuffer = null;
35
+ _pendingLogs = [];
36
+ _awaitingFlushAck = new Set();
37
+ get sharedBuffer() {
38
+ return this._sharedBuffer;
39
+ }
40
+ constructor(options) {
41
+ this.options = options;
42
+ }
43
+ insertRequestSnapshot(snapshot) {
44
+ if (!this._mainThreadBuffer) {
45
+ this._mainThreadBuffer = this.createEmptyPayload();
46
+ }
47
+ const maxPerBatch = this.options.maxTracesPerBatch ?? DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION;
48
+ if (this._mainThreadBuffer.snapshots.length >= maxPerBatch) {
49
+ if (this.options.debug) {
50
+ this.logger.debug(`Max snapshots per transaction reached: ${maxPerBatch}. Ignoring snapshot.`);
51
+ }
52
+ return;
53
+ }
54
+ const encodedSnapshot = RequestSnapshotEncoder.encode(snapshot);
55
+ this._mainThreadBuffer.snapshots.push(encodedSnapshot);
56
+ }
57
+ insertJobSnapshot(jobSnapshot) {
58
+ if (!this._mainThreadBuffer) {
59
+ this._mainThreadBuffer = this.createEmptyPayload();
60
+ }
61
+ if (!this._mainThreadBuffer.jobs) {
62
+ this._mainThreadBuffer.jobs = [];
63
+ }
64
+ const maxPerBatch = this.options.maxTracesPerBatch ?? DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION;
65
+ if (this._mainThreadBuffer.jobs.length >= maxPerBatch) {
66
+ if (this.options.debug) {
67
+ this.logger.debug(`Max job snapshots per transaction reached: ${maxPerBatch}. Ignoring snapshot.`);
68
+ }
69
+ return;
70
+ }
71
+ const encodedJobSnapshot = JobSnapshotEncoder.encode(jobSnapshot);
72
+ this._mainThreadBuffer.jobs.push(encodedJobSnapshot);
73
+ }
74
+ isBufferLocked() {
75
+ return Atomics.load(this.lock, 0) !== 0;
76
+ }
77
+ isBufferEmpty() {
78
+ return !this._mainThreadBuffer;
79
+ }
80
+ acquireLock() {
81
+ if (Atomics.compareExchange(this.lock, 0, 0, 1) !== 0) {
82
+ return false;
83
+ }
84
+ if (this.options.debug) {
85
+ this.logger.debug("Shared buffer lock acquired.");
86
+ }
87
+ return true;
88
+ }
89
+ releaseLock() {
90
+ Atomics.store(this.lock, 0, 0);
91
+ Atomics.notify(this.lock, 0);
92
+ if (this.options.debug) {
93
+ this.logger.debug("Shared buffer lock released.");
94
+ }
95
+ }
96
+ addNodeRuntimeMetrics(runtimeMetrics) {
97
+ if (!runtimeMetrics) {
98
+ return;
99
+ }
100
+ if (!this._mainThreadBuffer) {
101
+ this._mainThreadBuffer = this.createEmptyPayload();
102
+ }
103
+ this._mainThreadBuffer.runtime =
104
+ RuntimeMetricsEncoder.encode(runtimeMetrics);
105
+ }
106
+ upsertCustomMetric(metric) {
107
+ if (!this._mainThreadBuffer) {
108
+ this._mainThreadBuffer = this.createEmptyPayload();
109
+ }
110
+ if (!this._mainThreadBuffer.custom) {
111
+ this._mainThreadBuffer.custom = [];
112
+ }
113
+ if (metric instanceof Counter || metric instanceof Summary) {
114
+ this._awaitingFlushAck.add(metric);
115
+ }
116
+ const existingMetricIndex = this._mainThreadBuffer.custom.findIndex((m) => m.n === metric.name && m.t === metric.type);
117
+ if (existingMetricIndex !== -1) {
118
+ this._mainThreadBuffer.custom[existingMetricIndex] = {
119
+ ...this._mainThreadBuffer.custom[existingMetricIndex],
120
+ ...CustomMetricsEncoder.encode(metric),
121
+ };
122
+ }
123
+ else {
124
+ this._mainThreadBuffer.custom.push(CustomMetricsEncoder.encode(metric));
125
+ }
126
+ }
127
+ pushLogs(logs) {
128
+ if (!this._mainThreadBuffer) {
129
+ this._mainThreadBuffer = this.createEmptyPayload();
130
+ }
131
+ if (!this._mainThreadBuffer.logs) {
132
+ this._mainThreadBuffer.logs = [];
133
+ }
134
+ const buffered = this._mainThreadBuffer.logs;
135
+ for (const log of logs) {
136
+ const entry = log.text.length > MAX_LOG_ENTRY_LENGTH
137
+ ? { ...log, text: this.truncateLogText(log.text) }
138
+ : log;
139
+ if (buffered.length < MAX_LOGS_PER_TRANSACTION) {
140
+ buffered.push(entry);
141
+ continue;
142
+ }
143
+ if (this._pendingLogs.length < MAX_PENDING_LOGS) {
144
+ this._pendingLogs.push(entry);
145
+ continue;
146
+ }
147
+ return;
148
+ }
149
+ }
150
+ drainPendingLogs() {
151
+ if (this._pendingLogs.length === 0) {
152
+ return;
153
+ }
154
+ if (!this._mainThreadBuffer) {
155
+ this._mainThreadBuffer = this.createEmptyPayload();
156
+ }
157
+ if (!this._mainThreadBuffer.logs) {
158
+ this._mainThreadBuffer.logs = [];
159
+ }
160
+ const capacity = MAX_LOGS_PER_TRANSACTION - this._mainThreadBuffer.logs.length;
161
+ if (capacity <= 0) {
162
+ return;
163
+ }
164
+ this._mainThreadBuffer.logs.push(...this._pendingLogs.splice(0, Math.min(capacity, MAX_PENDING_LOGS)));
165
+ }
166
+ truncateLogText(text) {
167
+ return (text.slice(0, MAX_LOG_ENTRY_LENGTH - TRUNCATION_SUFFIX.length) +
168
+ TRUNCATION_SUFFIX);
169
+ }
170
+ encodeAndWrite() {
171
+ if (this.options.debug) {
172
+ if (this._mainThreadBuffer?.snapshots) {
173
+ this.logger.debug(`Encoding and writing ${this._mainThreadBuffer.snapshots.length} snapshots to shared buffer.`);
174
+ this.logger.debug(`Operations in shared buffer: ${this._mainThreadBuffer.snapshots.map((s) => s.op)}`);
175
+ }
176
+ }
177
+ const json = JSON.stringify(this._mainThreadBuffer);
178
+ const jsonBytes = this.encoder.encode(json);
179
+ const jsonLength = jsonBytes.length;
180
+ if (jsonLength > SHARED_BUFFER_SIZE - 8) {
181
+ throw new Error("Payload too large for shared buffer");
182
+ }
183
+ const view = new DataView(this._sharedBuffer, 4, 4);
184
+ view.setUint32(0, jsonLength);
185
+ this.sharedBytes.set(jsonBytes, 8);
186
+ for (const metric of this._awaitingFlushAck) {
187
+ metric.markFlushed();
188
+ }
189
+ this._awaitingFlushAck.clear();
190
+ }
191
+ resetMainThreadBuffer() {
192
+ this._mainThreadBuffer = null;
193
+ }
194
+ createEmptyPayload() {
195
+ const payload = {
196
+ serviceId: this.options.serviceId,
197
+ snapshots: [],
198
+ forwardLogs: Boolean(this.options.forwardLogs),
199
+ };
200
+ if (this.options.serviceVersion) {
201
+ payload.serviceVersion = this.options.serviceVersion;
202
+ }
203
+ return payload;
204
+ }
205
+ };
206
+ ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = __decorate([
207
+ Injectable(),
208
+ __param(0, Inject(OBSERVE_OPTIONS)),
209
+ __metadata("design:paramtypes", [Object])
210
+ ], ObserveAgentSharedBuffer);
211
+ export { ObserveAgentSharedBuffer };
@@ -0,0 +1,25 @@
1
+ import { OnApplicationShutdown, OnModuleInit } from "@nestjs/common";
2
+ import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
3
+ import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
4
+ import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
5
+ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationShutdown {
6
+ private readonly observeAgentSharedBuffer;
7
+ private readonly options;
8
+ private readonly nodeRuntimeMetricsService;
9
+ private readonly logger;
10
+ private worker;
11
+ private flushInterval;
12
+ private runtimeMetricsInterval;
13
+ private cpuProfiler;
14
+ constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, nodeRuntimeMetricsService: NodeRuntimeMetricsService);
15
+ onModuleInit(): void;
16
+ private startRuntimeMetrics;
17
+ private startContinuousProfiling;
18
+ onApplicationShutdown(): Promise<void>;
19
+ private get endpoint();
20
+ private warnIfCredentialsSentInClear;
21
+ initializeWorker(): void;
22
+ handleMessage(msg: string): void;
23
+ handleError(error: Error): void;
24
+ flush(): void;
25
+ }
@@ -0,0 +1,213 @@
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 ObserveAgentWorker_1;
14
+ import { Inject, Injectable, Logger, } from "@nestjs/common";
15
+ import { hostname } from "node:os";
16
+ import { Worker } from "worker_threads";
17
+ import { OBSERVE_OPTIONS } from "../observe.constants.js";
18
+ import { CpuProfilerService } from "../profiling/cpu-profiler.service.js";
19
+ import { ProfileUploader } from "../profiling/profile-uploader.js";
20
+ import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-slice-recorder.js";
21
+ import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
22
+ import { detachedObserveWorker } from "./detached-observe-worker.js";
23
+ import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
24
+ const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000;
25
+ const MIN_RUNTIME_METRICS_INTERVAL = 30000;
26
+ const DEFAULT_FLUSH_INTERVAL = 5000;
27
+ const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? "https://observe-api.nestjs.com";
28
+ const MIN_FLUSH_INTERVAL = 1000;
29
+ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
30
+ observeAgentSharedBuffer;
31
+ options;
32
+ nodeRuntimeMetricsService;
33
+ logger = new Logger(ObserveAgentWorker_1.name);
34
+ worker = null;
35
+ flushInterval;
36
+ runtimeMetricsInterval = null;
37
+ cpuProfiler = null;
38
+ constructor(observeAgentSharedBuffer, options, nodeRuntimeMetricsService) {
39
+ this.observeAgentSharedBuffer = observeAgentSharedBuffer;
40
+ this.options = options;
41
+ this.nodeRuntimeMetricsService = nodeRuntimeMetricsService;
42
+ }
43
+ onModuleInit() {
44
+ this.initializeWorker();
45
+ const flushIntervalTime = this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
46
+ if (flushIntervalTime < MIN_FLUSH_INTERVAL) {
47
+ this.logger.warn(`Flush interval is too short (${flushIntervalTime}ms). Setting to minimum of ${MIN_FLUSH_INTERVAL}ms.`);
48
+ this.options.flushInterval = MIN_FLUSH_INTERVAL;
49
+ }
50
+ this.flushInterval = setInterval(() => this.flush(), flushIntervalTime);
51
+ this.startRuntimeMetrics();
52
+ }
53
+ startRuntimeMetrics() {
54
+ if (!this.options.runtimeMetrics) {
55
+ return;
56
+ }
57
+ let interval = this.options.runtimeMetricsInterval ?? DEFAULT_RUNTIME_METRICS_INTERVAL;
58
+ if (interval < MIN_RUNTIME_METRICS_INTERVAL) {
59
+ this.logger.warn(`Runtime metrics interval is too short (${interval}ms). Setting to minimum of ${MIN_RUNTIME_METRICS_INTERVAL}ms.`);
60
+ interval = MIN_RUNTIME_METRICS_INTERVAL;
61
+ }
62
+ this.runtimeMetricsInterval = setInterval(() => {
63
+ this.observeAgentSharedBuffer.addNodeRuntimeMetrics(this.nodeRuntimeMetricsService.collectNodeRuntimeMetrics());
64
+ }, interval);
65
+ if (this.options.debug) {
66
+ this.logger.debug(`Collecting runtime metrics every ${interval}ms.`);
67
+ }
68
+ }
69
+ startContinuousProfiling() {
70
+ const profiling = this.options.profiling;
71
+ if (!profiling?.enabled) {
72
+ return;
73
+ }
74
+ const slices = new SpanSliceRecorder();
75
+ const uploader = new ProfileUploader({
76
+ endpoint: this.endpoint,
77
+ appKey: this.options.appKey,
78
+ appSecret: this.options.appSecret,
79
+ serviceNode: `${hostname()}:${process.pid}`,
80
+ onError: (message) => this.logger.warn(message),
81
+ });
82
+ this.cpuProfiler = new CpuProfilerService(slices, {
83
+ sampleRateHz: profiling.sampleRateHz,
84
+ windowMs: profiling.windowMs,
85
+ dutyMs: profiling.dutyMs,
86
+ maxCpuPercent: profiling.maxCpuPercent,
87
+ onWindow: (window, sampleRateHz) => uploader.enqueue(window, sampleRateHz),
88
+ onDisabled: (reason) => {
89
+ this.logger.warn(`Continuous profiling stopped - ${reason}`);
90
+ setActiveSliceRecorder(null);
91
+ },
92
+ });
93
+ setActiveSliceRecorder(slices);
94
+ void this.cpuProfiler.start().catch((err) => {
95
+ this.logger.warn(`Continuous profiling failed to start: ${String(err)}`);
96
+ setActiveSliceRecorder(null);
97
+ });
98
+ this.logger.log("Continuous profiling enabled.");
99
+ }
100
+ async onApplicationShutdown() {
101
+ if (this.flushInterval) {
102
+ clearInterval(this.flushInterval);
103
+ }
104
+ if (this.runtimeMetricsInterval) {
105
+ clearInterval(this.runtimeMetricsInterval);
106
+ }
107
+ if (this.cpuProfiler) {
108
+ setActiveSliceRecorder(null);
109
+ await this.cpuProfiler.stop();
110
+ this.cpuProfiler = null;
111
+ }
112
+ if (!this.worker) {
113
+ return;
114
+ }
115
+ await this.worker.terminate();
116
+ if (this.options.debug) {
117
+ this.logger.debug("Worker terminated successfully.");
118
+ }
119
+ this.worker = null;
120
+ }
121
+ get endpoint() {
122
+ return this.options.endpoint ?? DEFAULT_COLLECTOR_ENDPOINT;
123
+ }
124
+ warnIfCredentialsSentInClear() {
125
+ if (!this.options.appKey && !this.options.appSecret) {
126
+ return;
127
+ }
128
+ try {
129
+ const url = new URL(this.endpoint);
130
+ const loopback = url.hostname === "localhost" ||
131
+ url.hostname === "127.0.0.1" ||
132
+ url.hostname === "[::1]" ||
133
+ url.hostname === "::1";
134
+ if (url.protocol === "http:" && !loopback) {
135
+ this.logger.warn(`The collector endpoint "${url.origin}" uses plain HTTP: appKey and appSecret will be sent unencrypted. Use https:// unless the network path is fully trusted.`);
136
+ }
137
+ }
138
+ catch {
139
+ }
140
+ }
141
+ initializeWorker() {
142
+ this.warnIfCredentialsSentInClear();
143
+ this.worker = new Worker(`(${detachedObserveWorker.toString()})()`, {
144
+ eval: true,
145
+ workerData: {
146
+ sharedBuffer: this.observeAgentSharedBuffer.sharedBuffer,
147
+ config: {
148
+ endpoint: this.endpoint,
149
+ appKey: this.options.appKey,
150
+ appSecret: this.options.appSecret,
151
+ },
152
+ },
153
+ });
154
+ this.worker.on("message", (msg) => this.handleMessage(msg));
155
+ this.worker.on("error", (error) => this.handleError(error));
156
+ this.worker.on("exit", (code) => {
157
+ if (code !== 0) {
158
+ this.logger.error(`Worker stopped with exit code ${code}. Restarting worker...`);
159
+ this.initializeWorker();
160
+ }
161
+ else {
162
+ this.logger.debug("Worker exited gracefully.");
163
+ }
164
+ });
165
+ this.logger.log("Observe agent worker initialized.");
166
+ }
167
+ handleMessage(msg) {
168
+ if (msg.includes("Error:")) {
169
+ this.logger.error(msg);
170
+ return;
171
+ }
172
+ if (this.options.debug) {
173
+ this.logger.debug(msg);
174
+ }
175
+ }
176
+ handleError(error) {
177
+ this.logger.error(error);
178
+ }
179
+ flush() {
180
+ this.observeAgentSharedBuffer.drainPendingLogs();
181
+ if (this.observeAgentSharedBuffer.isBufferEmpty()) {
182
+ return;
183
+ }
184
+ if (this.observeAgentSharedBuffer.isBufferLocked()) {
185
+ if (this.options.debug) {
186
+ this.logger.debug("Shared buffer is locked, cannot flush data to worker. Skipping flush for now.");
187
+ }
188
+ return;
189
+ }
190
+ if (!this.observeAgentSharedBuffer.acquireLock()) {
191
+ if (this.options.debug) {
192
+ this.logger.debug("Failed to acquire lock on shared buffer. Skipping flush for now.");
193
+ }
194
+ return;
195
+ }
196
+ try {
197
+ this.observeAgentSharedBuffer.encodeAndWrite();
198
+ }
199
+ catch (error) {
200
+ this.logger.error("Error during flush:", error);
201
+ }
202
+ finally {
203
+ this.observeAgentSharedBuffer.releaseLock();
204
+ this.observeAgentSharedBuffer.resetMainThreadBuffer();
205
+ }
206
+ }
207
+ };
208
+ ObserveAgentWorker = ObserveAgentWorker_1 = __decorate([
209
+ Injectable(),
210
+ __param(1, Inject(OBSERVE_OPTIONS)),
211
+ __metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, NodeRuntimeMetricsService])
212
+ ], ObserveAgentWorker);
213
+ export { ObserveAgentWorker };
@@ -0,0 +1,39 @@
1
+ import { CustomMetric } from "../interfaces/custom-metric.interface.js";
2
+ declare const DEFAULT_LABEL: "default";
3
+ export declare function stringifyLabel(label: Record<string, string | number>): string;
4
+ export declare const MAX_SERIES_PER_METRIC = 1000;
5
+ export declare function admitsSeries(metricName: string, values: Record<string, unknown>, key: string, state: {
6
+ warned: boolean;
7
+ }): boolean;
8
+ export declare class Counter<TLabel extends string = typeof DEFAULT_LABEL> implements CustomMetric<TLabel> {
9
+ private readonly seriesLimit;
10
+ readonly name: string;
11
+ readonly type: "counter";
12
+ readonly description?: string;
13
+ readonly value: Record<string, number>;
14
+ readonly labels?: TLabel[];
15
+ private _tags?;
16
+ private _onChange?;
17
+ private _initialValue;
18
+ private _lastUpdated;
19
+ private _lastFlushedValue;
20
+ get increase(): Record<string, number>;
21
+ markFlushed(): void;
22
+ get lastUpdated(): number;
23
+ get tags(): Record<string, string> | undefined;
24
+ set tags(tags: Record<string, string> | undefined);
25
+ constructor(name: string);
26
+ constructor(name: string, description: string);
27
+ constructor(name: string, description: string, initialValue: number);
28
+ constructor(name: string, description: string, labels: TLabel[]);
29
+ constructor(name: string, description: string, initialValue: number, labels: TLabel[]);
30
+ constructor(name: string, description?: string, initialValue?: number, labels?: TLabel[]);
31
+ getValue(): number;
32
+ getValue(label: Record<TLabel, string | number>): number;
33
+ increment(): void;
34
+ increment(label: Record<TLabel, string | number>): void;
35
+ increment(value: number): void;
36
+ increment(label: Record<TLabel, string | number>, value: number): void;
37
+ private validateLabels;
38
+ }
39
+ export {};