@obzerver/node 0.0.0-stage → 0.6.0

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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +97 -2
  3. package/dist/agent-types.d.ts +28 -0
  4. package/dist/agent-types.js +6 -0
  5. package/dist/agent-types.js.map +1 -0
  6. package/dist/agent.d.ts +97 -0
  7. package/dist/agent.js +651 -0
  8. package/dist/agent.js.map +1 -0
  9. package/dist/context.d.ts +86 -0
  10. package/dist/context.js +136 -0
  11. package/dist/context.js.map +1 -0
  12. package/dist/errors.d.ts +18 -0
  13. package/dist/errors.js +108 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/glob.d.ts +7 -0
  16. package/dist/glob.js +56 -0
  17. package/dist/glob.js.map +1 -0
  18. package/dist/index.d.ts +76 -0
  19. package/dist/index.js +89 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/instrument/classes.d.ts +18 -0
  22. package/dist/instrument/classes.js +103 -0
  23. package/dist/instrument/classes.js.map +1 -0
  24. package/dist/instrument/console.d.ts +11 -0
  25. package/dist/instrument/console.js +68 -0
  26. package/dist/instrument/console.js.map +1 -0
  27. package/dist/instrument/db.d.ts +7 -0
  28. package/dist/instrument/db.js +155 -0
  29. package/dist/instrument/db.js.map +1 -0
  30. package/dist/instrument/express.d.ts +3 -0
  31. package/dist/instrument/express.js +133 -0
  32. package/dist/instrument/express.js.map +1 -0
  33. package/dist/instrument/fastify.d.ts +35 -0
  34. package/dist/instrument/fastify.js +88 -0
  35. package/dist/instrument/fastify.js.map +1 -0
  36. package/dist/instrument/http.d.ts +10 -0
  37. package/dist/instrument/http.js +149 -0
  38. package/dist/instrument/http.js.map +1 -0
  39. package/dist/instrument/jobs.d.ts +15 -0
  40. package/dist/instrument/jobs.js +90 -0
  41. package/dist/instrument/jobs.js.map +1 -0
  42. package/dist/options.d.ts +110 -0
  43. package/dist/options.js +3 -0
  44. package/dist/options.js.map +1 -0
  45. package/dist/protocol.d.ts +146 -0
  46. package/dist/protocol.js +4 -0
  47. package/dist/protocol.js.map +1 -0
  48. package/dist/redact.d.ts +12 -0
  49. package/dist/redact.js +54 -0
  50. package/dist/redact.js.map +1 -0
  51. package/dist/register.d.ts +1 -0
  52. package/dist/register.js +9 -0
  53. package/dist/register.js.map +1 -0
  54. package/dist/release.d.ts +32 -0
  55. package/dist/release.js +141 -0
  56. package/dist/release.js.map +1 -0
  57. package/dist/runtime.d.ts +37 -0
  58. package/dist/runtime.js +142 -0
  59. package/dist/runtime.js.map +1 -0
  60. package/dist/transport.d.ts +32 -0
  61. package/dist/transport.js +122 -0
  62. package/dist/transport.js.map +1 -0
  63. package/package.json +51 -4
package/dist/agent.js ADDED
@@ -0,0 +1,651 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Agent = exports.DEFAULT_AUTO_INSTRUMENT = exports.SDK_VERSION = void 0;
4
+ exports.normalizePath = normalizePath;
5
+ const fs = require("node:fs");
6
+ const os = require("node:os");
7
+ const path = require("node:path");
8
+ const dc = require("node:diagnostics_channel");
9
+ // transport must load before http is patched so the SDK keeps raw references.
10
+ const transport_1 = require("./transport");
11
+ const context_1 = require("./context");
12
+ const redact_1 = require("./redact");
13
+ const errors_1 = require("./errors");
14
+ const http_1 = require("./instrument/http");
15
+ const express_1 = require("./instrument/express");
16
+ const fastify_1 = require("./instrument/fastify");
17
+ const db_1 = require("./instrument/db");
18
+ const console_1 = require("./instrument/console");
19
+ const jobs_1 = require("./instrument/jobs");
20
+ const node_url_1 = require("node:url");
21
+ const runtime_1 = require("./runtime");
22
+ const release_1 = require("./release");
23
+ const glob_1 = require("./glob");
24
+ const classes_1 = require("./instrument/classes");
25
+ exports.SDK_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8')).version;
26
+ /** Files whose exported classes are instrumented automatically (NestJS-style names). */
27
+ exports.DEFAULT_AUTO_INSTRUMENT = ['**/*.service.{ts,mts,cts,js,mjs,cjs}', '**/*.repository.{ts,mts,cts,js,mjs,cjs}'];
28
+ const DEFAULT_CAPTURE_HEADERS = ['user-agent', 'content-type', 'accept', 'referer', 'x-request-id', 'content-length', 'origin'];
29
+ const MODULE_NAMES = ['express', 'pg', 'mysql2', 'ioredis', 'bullmq', 'node-cron', 'cron'];
30
+ /** Packages that ship separate ESM builds: ESM imports are routed to the patched CommonJS copy. */
31
+ // Packages whose ESM imports are routed through the resolve hook so they get patched
32
+ // (dual packages would otherwise load an unpatched ESM copy, and CJS-only ones can
33
+ // bypass Module._load when imported from ESM).
34
+ const DUAL_PACKAGES = new Set(['bullmq', 'node-cron', 'cron']);
35
+ function readPackage(cwd) {
36
+ try {
37
+ return JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
38
+ }
39
+ catch {
40
+ return {};
41
+ }
42
+ }
43
+ function matchIgnore(rule, method, p, req) {
44
+ if (typeof rule === 'string')
45
+ return rule === p;
46
+ if (rule instanceof RegExp)
47
+ return rule.test(p);
48
+ if (typeof rule === 'function')
49
+ return !!rule(req);
50
+ if (rule && typeof rule === 'object') {
51
+ if (rule.method && String(rule.method).toUpperCase() !== method)
52
+ return false;
53
+ return matchIgnore(rule.path, method, p, req);
54
+ }
55
+ return false;
56
+ }
57
+ /** /orders/123/items/9f1c… -> /orders/:id/items/:id (only when no framework route is known) */
58
+ function normalizePath(p) {
59
+ return p.split('/').map((seg) => {
60
+ if (!seg)
61
+ return seg;
62
+ if (/^\d+$/.test(seg) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(seg) || /^[0-9a-f]{16,}$/i.test(seg) || /^[A-Za-z0-9_-]{20,}$/.test(seg))
63
+ return ':id';
64
+ return seg;
65
+ }).join('/') || '/';
66
+ }
67
+ function resolveOptions(options, cwd) {
68
+ const env = process.env;
69
+ const pkg = readPackage(cwd);
70
+ const release = (0, release_1.inferRelease)(options.serviceVersion, env, cwd, pkg.version);
71
+ const autoEnv = env.OBZERVER_AUTO_INSTRUMENT?.trim();
72
+ const autoInstrument = options.autoInstrument !== undefined
73
+ ? (options.autoInstrument === false ? false : [...options.autoInstrument])
74
+ : autoEnv === 'false' ? false
75
+ : autoEnv ? autoEnv.split(',').map((g) => g.trim()).filter(Boolean)
76
+ : [...exports.DEFAULT_AUTO_INSTRUMENT];
77
+ const capture = options.http?.capture;
78
+ return {
79
+ enabled: options.enabled ?? env.OBZERVER_ENABLED !== 'false',
80
+ appKey: options.appKey || env.OBZERVER_KEY || env.OBZERVER_APP_KEY || '',
81
+ endpoint: options.endpoint || env.OBZERVER_ENDPOINT || 'http://localhost:4319',
82
+ serviceId: options.serviceId || env.OBZERVER_SERVICE || pkg.name || path.basename(cwd),
83
+ serviceVersion: release.version,
84
+ release,
85
+ environment: options.environment || env.OBZERVER_ENV || env.NODE_ENV || 'development',
86
+ instanceId: options.instanceId || `${os.hostname()}:${process.pid}`,
87
+ debug: options.debug ?? env.OBZERVER_DEBUG === 'true',
88
+ tracesSampleRate: options.tracesSampleRate ?? (env.OBZERVER_SAMPLE_RATE ? Number(env.OBZERVER_SAMPLE_RATE) : 1),
89
+ autoInstrument,
90
+ tracePreflights: options.tracePreflights ?? env.OBZERVER_TRACE_PREFLIGHTS === 'true',
91
+ flushInterval: options.flushInterval ?? 5000,
92
+ maxTracesPerBatch: options.maxTracesPerBatch ?? 1000,
93
+ runtimeMetricsInterval: options.runtimeMetricsInterval ?? 15000,
94
+ forwardLogs: options.forwardLogs ?? env.OBZERVER_FORWARD_LOGS !== 'false',
95
+ spanCollapse: options.spanCollapse === false ? false : { threshold: 20, keepSlowest: 3, ...(options.spanCollapse || {}) },
96
+ sourceContext: options.sourceContext ?? { linesOfContext: 5, maxFrames: 5 },
97
+ http: {
98
+ ignore: options.http?.ignore ?? ['/favicon.ico'],
99
+ getUserId: options.http?.getUserId ?? null,
100
+ capture: capture === false ? false : { headers: capture?.headers ?? [], body: capture?.body ?? false, slowerThanMs: capture?.slowerThanMs ?? 2000 },
101
+ },
102
+ instrument: { http: true, fetch: true, express: true, fastify: true, pg: true, mysql2: true, ioredis: true, console: true, bullmq: true, nodeCron: true, cron: true, ...(options.instrument || {}) },
103
+ };
104
+ }
105
+ class Agent {
106
+ cwd;
107
+ options;
108
+ redactor;
109
+ frameworks = new Set();
110
+ transport = null;
111
+ runtime = null;
112
+ metrics = null;
113
+ inflight = 0;
114
+ inLog = false;
115
+ patched = new Set();
116
+ constructor(options = {}) {
117
+ this.cwd = options.cwd || process.cwd();
118
+ this.options = resolveOptions(options, this.cwd);
119
+ this.redactor = (0, redact_1.createRedactor)(options.redaction);
120
+ }
121
+ log(...args) { process.stderr.write(`[obzerver] ${args.join(' ')}\n`); }
122
+ debug(...args) { if (this.options.debug)
123
+ this.log(...args.map((a) => (a instanceof Error ? a.stack : String(a)))); }
124
+ start() {
125
+ const o = this.options;
126
+ if (!o.enabled) {
127
+ this.debug('disabled');
128
+ return this;
129
+ }
130
+ this.transport = new transport_1.Transport(o, (m) => this.log(m));
131
+ const frameworks = this.frameworks;
132
+ this.transport.meta = {
133
+ sdk: { name: '@obzerver/node', version: exports.SDK_VERSION },
134
+ service: {
135
+ id: o.serviceId, version: o.serviceVersion, instance: o.instanceId, environment: o.environment, node: process.version, host: os.hostname(), pid: process.pid,
136
+ get frameworks() { return [...frameworks]; },
137
+ },
138
+ };
139
+ this.loadSpool();
140
+ if (o.instrument.http) {
141
+ (0, http_1.patchServers)(this);
142
+ (0, http_1.patchClients)(this);
143
+ }
144
+ if (o.instrument.fetch)
145
+ (0, http_1.patchFetch)(this);
146
+ if (o.forwardLogs && o.instrument.console)
147
+ (0, console_1.patchConsole)(this);
148
+ this.hookModules();
149
+ this.runtime = new runtime_1.RuntimeSampler(this, o.runtimeMetricsInterval);
150
+ this.metrics = new runtime_1.Metrics(this, 10000);
151
+ this.installProcessHooks();
152
+ this.debug(`started service=${o.serviceId} version=${o.serviceVersion ?? 'none'} (from ${o.release.source}${o.release.from ? ` ${o.release.from}` : ''}) endpoint=${o.endpoint}`);
153
+ if (!o.appKey)
154
+ this.log('no OBZERVER_KEY set; sending without a key (accepted only by an open collector).');
155
+ return this;
156
+ }
157
+ // ---------------------------------------------------------------- modules
158
+ applyPatch(name, exportsObj) {
159
+ if (!exportsObj || this.patched.has(exportsObj))
160
+ return exportsObj;
161
+ const ins = this.options.instrument;
162
+ try {
163
+ if (name === 'express' && ins.express)
164
+ (0, express_1.instrumentExpress)(this, exportsObj);
165
+ else if (name === 'pg' && ins.pg && (0, db_1.patchPg)(exportsObj))
166
+ this.frameworks.add('pg');
167
+ else if (name === 'mysql2' && ins.mysql2 && (0, db_1.patchMysql2)(exportsObj))
168
+ this.frameworks.add('mysql2');
169
+ else if (name === 'ioredis' && ins.ioredis && (0, db_1.patchIoredis)(exportsObj))
170
+ this.frameworks.add('ioredis');
171
+ else if (name === 'bullmq' && ins.bullmq && (0, jobs_1.patchBullmq)(exportsObj, this))
172
+ this.frameworks.add('bullmq');
173
+ else if (name === 'node-cron' && ins.nodeCron && (0, jobs_1.patchNodeCron)(exportsObj, this))
174
+ this.frameworks.add('node-cron');
175
+ else if (name === 'cron' && ins.cron && (0, jobs_1.patchCron)(exportsObj, this))
176
+ this.frameworks.add('cron');
177
+ this.patched.add(exportsObj);
178
+ }
179
+ catch (e) {
180
+ this.debug(`failed to instrument ${name}`, e);
181
+ }
182
+ return exportsObj;
183
+ }
184
+ /** Matches app files whose exported classes are instrumented automatically (null when off). */
185
+ autoMatch = null;
186
+ autoDone = new Set();
187
+ /** Instrument the classes a matching module exports. Safe to call more than once per file. */
188
+ autoInstrumentModule(file, exports) {
189
+ try {
190
+ const names = (0, classes_1.instrumentExports)(exports);
191
+ if (names.length && !this.autoDone.has(file)) {
192
+ this.autoDone.add(file);
193
+ this.debug(`auto-instrumented ${names.join(', ')} from ${path.relative(this.cwd, file)}`);
194
+ }
195
+ }
196
+ catch (e) {
197
+ this.debug('auto-instrument failed', file, e);
198
+ }
199
+ }
200
+ hookModules() {
201
+ if (this.options.autoInstrument && this.options.autoInstrument.length) {
202
+ this.autoMatch = (0, glob_1.fileMatcher)(this.options.autoInstrument, this.cwd, path.relative);
203
+ globalThis[classes_1.AUTO_INSTRUMENT_HOOK] = (file, exports) => this.autoInstrumentModule(file, exports);
204
+ }
205
+ // Already loaded, or declared by the app: patch the shared copy now so a
206
+ // later ESM `import` (which reuses the CommonJS cache) gets it too.
207
+ const pkg = readPackage(this.cwd);
208
+ const declared = new Set([...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.devDependencies || {})]);
209
+ for (const n of MODULE_NAMES) {
210
+ try {
211
+ const resolved = require.resolve(n, { paths: [this.cwd] });
212
+ if (require.cache[resolved] || declared.has(n))
213
+ this.applyPatch(n, require(resolved));
214
+ }
215
+ catch { /* not installed */ }
216
+ }
217
+ this.routeEsmImports();
218
+ // Anything required later (nested node_modules, lazy requires).
219
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
220
+ const Module = require('node:module');
221
+ const origLoad = Module._load;
222
+ if (!origLoad.__obzerver) {
223
+ const agent = this;
224
+ const load = function (request, ...rest) {
225
+ // App files (relative or absolute paths) may hold classes to auto-instrument.
226
+ let file = null;
227
+ if (agent.autoMatch && (request.startsWith('.') || path.isAbsolute(request))) {
228
+ try {
229
+ file = Module._resolveFilename(request, rest[0], rest[1]);
230
+ }
231
+ catch { /* let load throw */ }
232
+ }
233
+ const out = origLoad.call(this, request, ...rest);
234
+ if (MODULE_NAMES.includes(request))
235
+ agent.applyPatch(request, out);
236
+ else if (file && agent.autoMatch(file))
237
+ agent.autoInstrumentModule(file, out);
238
+ return out;
239
+ };
240
+ load.__obzerver = true;
241
+ Module._load = load;
242
+ }
243
+ // Fastify announces every instance it creates on a diagnostics channel (v4+).
244
+ if (this.options.instrument.fastify) {
245
+ dc.subscribe('fastify.initialization', (msg) => {
246
+ const f = msg?.fastify;
247
+ if (f)
248
+ (0, fastify_1.instrumentFastify)(this, f);
249
+ });
250
+ }
251
+ }
252
+ /**
253
+ * bullmq and node-cron ship separate ESM builds, so an ESM `import` would load an
254
+ * unpatched copy. With module.registerHooks (Node 22.15+) those imports resolve to
255
+ * the CommonJS build instead, which is the copy the SDK has patched.
256
+ */
257
+ routeEsmImports() {
258
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
259
+ const mod = require('node:module');
260
+ if (typeof mod.registerHooks !== 'function') {
261
+ if (this.autoMatch)
262
+ this.debug('autoInstrument covers require() only on this Node.js version (ESM needs 22.15+)');
263
+ return;
264
+ }
265
+ const wanted = [...DUAL_PACKAGES].filter((n) => this.isEnabled(n));
266
+ const hooks = {};
267
+ if (wanted.length) {
268
+ hooks.resolve = (specifier, context, nextResolve) => {
269
+ if (wanted.includes(specifier) && context.conditions?.includes('import')) {
270
+ try {
271
+ const from = context.parentURL?.startsWith('file:') ? (0, node_url_1.fileURLToPath)(context.parentURL) : path.join(this.cwd, 'index.js');
272
+ const resolved = mod.createRequire(from).resolve(specifier);
273
+ // Patch now if this copy was not loaded yet (e.g. a nested node_modules).
274
+ this.applyPatch(specifier, require(resolved));
275
+ return { url: (0, node_url_1.pathToFileURL)(resolved).href, format: 'commonjs', shortCircuit: true };
276
+ }
277
+ catch { /* fall through to the default resolution */ }
278
+ }
279
+ return nextResolve(specifier, context);
280
+ };
281
+ }
282
+ const match = this.autoMatch;
283
+ if (match) {
284
+ // Append one line to matching modules that hands their classes to the SDK once they have run.
285
+ hooks.load = (url, context, nextLoad) => {
286
+ const result = nextLoad(url, context);
287
+ if (!url.startsWith('file:') || result.source == null)
288
+ return result;
289
+ let file;
290
+ try {
291
+ file = (0, node_url_1.fileURLToPath)(url.split('?')[0]);
292
+ }
293
+ catch {
294
+ return result;
295
+ }
296
+ if (!match(file))
297
+ return result;
298
+ const source = typeof result.source === 'string' ? result.source : Buffer.from(result.source).toString('utf8');
299
+ const suffix = (0, classes_1.autoInstrumentSuffix)(source, result.format, file);
300
+ return suffix ? { ...result, source: source + suffix } : result;
301
+ };
302
+ }
303
+ if (!hooks.resolve && !hooks.load)
304
+ return;
305
+ try {
306
+ mod.registerHooks(hooks);
307
+ }
308
+ catch (e) {
309
+ this.debug('registerHooks failed', e);
310
+ }
311
+ }
312
+ isEnabled(name) {
313
+ const ins = this.options.instrument;
314
+ return name === 'node-cron' ? ins.nodeCron : ins[name] ?? false;
315
+ }
316
+ // ---------------------------------------------------------------- http
317
+ startHttp(req, res) {
318
+ const method = (req.method || 'GET').toUpperCase();
319
+ const rawPath = String(req.url || '/').split('?')[0];
320
+ if (req.headers['x-obzerver-internal'])
321
+ return null;
322
+ if (method === 'OPTIONS' && !this.options.tracePreflights)
323
+ return null;
324
+ for (const rule of this.options.http.ignore)
325
+ if (matchIgnore(rule, method, rawPath, req))
326
+ return null;
327
+ const remote = (0, context_1.parseTraceparent)(req.headers.traceparent);
328
+ const sampled = remote ? remote.sampled : Math.random() < this.options.tracesSampleRate;
329
+ const trace = new context_1.Trace({ kind: 'http', name: method, traceId: remote?.traceId, parentSpanId: remote?.parentSpanId, sampled });
330
+ trace.method = method;
331
+ trace.path = rawPath;
332
+ this.inflight++;
333
+ const done = () => this.finishHttp(trace, req, res);
334
+ res.once('finish', done);
335
+ res.once('close', done);
336
+ return trace;
337
+ }
338
+ recordRequestError(trace, err) {
339
+ if (!trace || !err || trace.errors.some((e) => e.raw === err))
340
+ return;
341
+ trace.errors.push({ raw: err, at: (0, context_1.nowMs)() });
342
+ }
343
+ finishHttp(trace, req, res) {
344
+ if (trace.finished)
345
+ return;
346
+ trace.finished = true;
347
+ this.inflight = Math.max(0, this.inflight - 1);
348
+ try {
349
+ for (const end of trace.openSpans)
350
+ end();
351
+ trace.root.finish();
352
+ const aborted = !res.writableFinished;
353
+ const status = aborted ? 499 : res.statusCode;
354
+ const route = trace.route || (status === 404 ? null : normalizePath(trace.path));
355
+ trace.name = `${trace.method} ${route || '(unmatched)'}`;
356
+ const fwReq = (trace.frameworkRequest || req);
357
+ let userId = trace.userId;
358
+ try {
359
+ if (!userId && this.options.http.getUserId)
360
+ userId = (this.options.http.getUserId(fwReq) ?? null);
361
+ if (!userId && fwReq.user)
362
+ userId = (fwReq.user.id ?? fwReq.user.sub ?? fwReq.user.userId ?? null);
363
+ }
364
+ catch { /* user hook failed */ }
365
+ const unhandled = status >= 500;
366
+ const duration = trace.root.duration;
367
+ const errorEvents = trace.errors.map((e) => {
368
+ const s = (0, errors_1.statusOf)(e.raw);
369
+ return this.makeErrorEvent(e.raw, trace, { status, unhandled: unhandled && (s === undefined || s >= 500), route: trace.name });
370
+ });
371
+ const cap = this.options.http.capture;
372
+ let capture;
373
+ if (cap && (unhandled || errorEvents.length || duration >= cap.slowerThanMs)) {
374
+ const headers = {};
375
+ for (const h of [...DEFAULT_CAPTURE_HEADERS, ...cap.headers])
376
+ if (req.headers[h] !== undefined)
377
+ headers[h] = req.headers[h];
378
+ capture = { headers: this.redactor.value(headers), reason: unhandled ? 'failed' : errorEvents.length ? 'error' : 'slow' };
379
+ const q = String(req.url || '').split('?')[1];
380
+ if (q)
381
+ capture.query = this.redactor.string(q).slice(0, 2000);
382
+ if (cap.body) {
383
+ const body = fwReq.body ?? req.body;
384
+ if (body !== undefined) {
385
+ const max = (typeof cap.body === 'object' && cap.body.maxBytes) || 4096;
386
+ const s = typeof body === 'string' ? body : JSON.stringify(this.redactor.value(body));
387
+ capture.body = s.length > max ? `${s.slice(0, max)}…` : s;
388
+ }
389
+ }
390
+ }
391
+ this.emitTrace(trace, {
392
+ method: trace.method, route: route || '(unmatched)', path: this.redactor.string(trace.path), status,
393
+ userId: userId != null ? String(userId) : null, unhandled, capture, errorEvents,
394
+ slow: !!cap && duration >= cap.slowerThanMs,
395
+ });
396
+ }
397
+ catch (e) {
398
+ this.debug('finishHttp failed', e);
399
+ }
400
+ }
401
+ makeErrorEvent(err, trace, { status, unhandled, route }) {
402
+ const ev = (0, errors_1.buildError)(err, { cwd: this.cwd, redactor: this.redactor, sourceOptions: this.options.sourceContext, handled: !unhandled });
403
+ return {
404
+ ...ev,
405
+ handled: !unhandled,
406
+ httpStatus: status ?? null,
407
+ traceId: trace ? trace.traceId : null,
408
+ operation: route || trace?.name || null,
409
+ kind: trace ? trace.kind : 'process',
410
+ userId: trace?.userId ? String(trace.userId) : null,
411
+ };
412
+ }
413
+ // ---------------------------------------------------------------- serialization
414
+ serializeSpans(trace) {
415
+ const t0 = trace.root.start;
416
+ const tEnd = trace.root.end ?? (0, context_1.nowMs)();
417
+ for (const s of trace.spans)
418
+ if (s.end === null) {
419
+ s.end = tEnd;
420
+ s.attrs.incomplete = true;
421
+ }
422
+ const children = new Map();
423
+ for (const s of trace.spans) {
424
+ if (!s.parentId)
425
+ continue;
426
+ if (!children.has(s.parentId))
427
+ children.set(s.parentId, []);
428
+ children.get(s.parentId).push(s);
429
+ }
430
+ // Self time = own duration minus the union of child intervals.
431
+ const selfOf = (s) => {
432
+ const end = s.end;
433
+ const kids = (children.get(s.id) || []).map((c) => [Math.max(c.start, s.start), Math.min(c.end, end)]).filter(([a, b]) => b > a).sort((a, b) => a[0] - b[0]);
434
+ let covered = 0;
435
+ let curS = -1;
436
+ let curE = -1;
437
+ for (const [a, b] of kids) {
438
+ if (a > curE) {
439
+ if (curE > curS)
440
+ covered += curE - curS;
441
+ curS = a;
442
+ curE = b;
443
+ }
444
+ else
445
+ curE = Math.max(curE, b);
446
+ }
447
+ if (curE > curS)
448
+ covered += curE - curS;
449
+ return Math.max(0, (end - s.start) - covered);
450
+ };
451
+ let out = trace.spans.map((s) => ({
452
+ id: s.id, parentId: s.parentId, name: s.name, kind: s.kind,
453
+ start: +(s.start - t0).toFixed(3), duration: +(s.end - s.start).toFixed(3), self: +selfOf(s).toFixed(3),
454
+ attrs: Object.keys(s.attrs).length ? s.attrs : undefined, error: s.error || undefined,
455
+ }));
456
+ const sc = this.options.spanCollapse;
457
+ if (sc) {
458
+ const groups = new Map();
459
+ for (const s of out) {
460
+ const k = `${s.parentId}|${s.name}`;
461
+ if (!groups.has(k))
462
+ groups.set(k, []);
463
+ groups.get(k).push(s);
464
+ }
465
+ const drop = new Set();
466
+ const extra = [];
467
+ for (const list of groups.values()) {
468
+ if (list.length <= sc.threshold)
469
+ continue;
470
+ const rest = [...list].sort((a, b) => b.duration - a.duration).slice(sc.keepSlowest).filter((s) => !(children.get(s.id) || []).length);
471
+ if (rest.length < 2)
472
+ continue;
473
+ for (const s of rest)
474
+ drop.add(s.id);
475
+ const start = Math.min(...rest.map((s) => s.start));
476
+ const end = Math.max(...rest.map((s) => s.start + s.duration));
477
+ extra.push({
478
+ id: `${rest[0].id}c`, parentId: rest[0].parentId, name: rest[0].name, kind: rest[0].kind, start, duration: +(end - start).toFixed(3),
479
+ self: +rest.reduce((n, s) => n + s.self, 0).toFixed(3), count: rest.length,
480
+ attrs: { ...(rest[0].attrs || {}), collapsed: rest.length, totalMs: +rest.reduce((n, s) => n + s.duration, 0).toFixed(3) },
481
+ error: rest.find((s) => s.error)?.error,
482
+ });
483
+ }
484
+ if (drop.size)
485
+ out = out.filter((s) => !drop.has(s.id)).concat(extra).sort((a, b) => a.start - b.start);
486
+ }
487
+ return out.slice(0, 2000);
488
+ }
489
+ emitTrace(trace, f) {
490
+ if (!this.transport)
491
+ return;
492
+ const failed = !!(f.unhandled || f.failed);
493
+ const keepSpans = trace.sampled || failed || f.errorEvents.length > 0 || f.slow;
494
+ const firstErr = f.errorEvents.find((e) => !e.handled) || f.errorEvents[0];
495
+ for (const ev of f.errorEvents)
496
+ this.transport.push('errors', { ...ev, ts: Math.round(trace.start) });
497
+ this.transport.push('traces', {
498
+ traceId: trace.traceId,
499
+ spanId: trace.root.id,
500
+ parentSpanId: trace.parentSpanId,
501
+ kind: trace.kind,
502
+ name: trace.name,
503
+ method: f.method || null,
504
+ route: f.route || null,
505
+ path: f.path || null,
506
+ status: f.status ?? null,
507
+ ts: Math.round(trace.start),
508
+ duration: +trace.root.duration.toFixed(3),
509
+ userId: f.userId || (trace.userId ? String(trace.userId) : null),
510
+ failed,
511
+ errorClass: firstErr ? firstErr.class : null,
512
+ fingerprint: firstErr ? firstErr.fingerprint : null,
513
+ errorMessage: firstErr ? firstErr.message.slice(0, 300) : (f.failMessage || null),
514
+ tags: Object.keys(trace.tags).length ? this.redactor.value(trace.tags) : undefined,
515
+ capture: f.capture,
516
+ queue: f.queue || null,
517
+ queueWait: f.queueWait ?? null,
518
+ attempt: f.attempt ?? null,
519
+ sampled: keepSpans,
520
+ spans: keepSpans ? this.serializeSpans(trace) : undefined,
521
+ });
522
+ }
523
+ // ---------------------------------------------------------------- jobs
524
+ /** Run one invocation of fn as its own job trace (used by job() and the BullMQ/cron instrumentations). */
525
+ runJob(name, fn, meta, auto = false) {
526
+ if (!this.transport)
527
+ return fn();
528
+ // A manual job()/bullmq() wrapper running directly inside an auto-instrumented job: reuse that trace.
529
+ const cur = context_1.als.getStore();
530
+ if (!auto && cur && cur.trace.kind === 'job' && cur.trace.autoJob && cur.span === cur.trace.root && !cur.trace.finished)
531
+ return fn();
532
+ const trace = new context_1.Trace({ kind: 'job', name: meta.name || name, sampled: Math.random() < this.options.tracesSampleRate });
533
+ trace.autoJob = auto;
534
+ const finish = (err) => {
535
+ if (trace.finished)
536
+ return;
537
+ trace.finished = true;
538
+ for (const end of trace.openSpans)
539
+ end();
540
+ if (err)
541
+ trace.root.fail(err);
542
+ trace.root.finish();
543
+ const errorEvents = err ? [this.makeErrorEvent(err, trace, { unhandled: true, route: trace.name })] : [];
544
+ this.emitTrace(trace, {
545
+ route: trace.name, status: err ? 500 : 200, failed: !!err, errorEvents, failMessage: err ? String(err.message ?? err) : null,
546
+ queue: meta.queue || 'default', queueWait: meta.queueWait ?? null, attempt: meta.attempt ?? 1, slow: false,
547
+ });
548
+ };
549
+ return context_1.als.run({ trace, span: trace.root }, () => {
550
+ let out;
551
+ try {
552
+ out = fn();
553
+ }
554
+ catch (e) {
555
+ finish(e);
556
+ throw e;
557
+ }
558
+ if ((0, context_1.isThenable)(out))
559
+ return Promise.resolve(out).then((v) => { finish(); return v; }, (e) => { finish(e); throw e; });
560
+ finish();
561
+ return out;
562
+ });
563
+ }
564
+ job(name, fn, opts = {}) {
565
+ const agent = this;
566
+ return function obzerverJob(...args) {
567
+ const meta = opts.meta?.(...args) || {};
568
+ return agent.runJob(name, () => fn.apply(this, args), { ...meta, queue: meta.queue || opts.queue });
569
+ };
570
+ }
571
+ // ---------------------------------------------------------------- logs, errors, process
572
+ currentTraceId() { return (0, context_1.currentTrace)()?.traceId ?? null; }
573
+ recordLog(level, message, logger, attrs) {
574
+ if (!this.transport || !this.options.forwardLogs)
575
+ return;
576
+ const store = context_1.als.getStore();
577
+ const t = store?.trace;
578
+ if (t)
579
+ t.logs++;
580
+ this.transport.push('logs', {
581
+ ts: Date.now(), level, message: this.redactor.string(String(message)).slice(0, 8000), logger: logger || null,
582
+ traceId: t ? t.traceId : null, spanId: store?.span ? store.span.id : null,
583
+ attrs: attrs ? this.redactor.value(attrs) : undefined,
584
+ });
585
+ }
586
+ captureError(err, extra = {}) {
587
+ if (!this.transport || !err)
588
+ return;
589
+ const t = (0, context_1.currentTrace)();
590
+ if (t && !t.finished && !extra.standalone) {
591
+ // Handled inside a request: record as an error event on the trace.
592
+ const ev = this.makeErrorEvent(err, t, { unhandled: false, route: t.name });
593
+ this.transport.push('errors', { ...ev, handled: extra.handled ?? true, ts: Date.now() });
594
+ const span = (0, context_1.currentSpan)();
595
+ if (span)
596
+ span.attrs.error = ev.message.slice(0, 200);
597
+ return;
598
+ }
599
+ const ev = this.makeErrorEvent(err, null, { unhandled: extra.handled === undefined ? true : !extra.handled, route: extra.operation || null });
600
+ this.transport.push('errors', { ...ev, ts: Date.now() });
601
+ }
602
+ installProcessHooks() {
603
+ process.on('uncaughtExceptionMonitor', (err) => {
604
+ try {
605
+ this.captureError(err, { standalone: true, handled: false, operation: 'uncaughtException' });
606
+ this.writeSpool();
607
+ }
608
+ catch { /* ignore */ }
609
+ });
610
+ const onSignal = (sig) => {
611
+ const exit = () => { if (process.listenerCount(sig) === 0)
612
+ process.kill(process.pid, sig); };
613
+ void Promise.race([this.shutdown(), new Promise((r) => setTimeout(r, 2000).unref())]).finally(exit);
614
+ };
615
+ for (const sig of ['SIGTERM', 'SIGINT'])
616
+ process.once(sig, () => onSignal(sig));
617
+ process.once('beforeExit', () => { void this.shutdown(); });
618
+ }
619
+ spoolFile() { return path.join(os.tmpdir(), `obzerver-spool-${this.options.serviceId.replace(/[^\w.-]/g, '_')}.json`); }
620
+ writeSpool() {
621
+ try {
622
+ if (this.transport)
623
+ fs.writeFileSync(this.spoolFile(), JSON.stringify(this.transport.q));
624
+ }
625
+ catch { /* ignore */ }
626
+ }
627
+ loadSpool() {
628
+ try {
629
+ const f = this.spoolFile();
630
+ if (!fs.existsSync(f) || !this.transport)
631
+ return;
632
+ const q = JSON.parse(fs.readFileSync(f, 'utf8'));
633
+ fs.unlinkSync(f);
634
+ const tr = this.transport;
635
+ for (const k of Object.keys(tr.q))
636
+ for (const it of q[k] || [])
637
+ tr.push(k, it);
638
+ this.debug('recovered spooled telemetry from previous crash');
639
+ }
640
+ catch { /* ignore */ }
641
+ }
642
+ async shutdown() {
643
+ if (!this.transport)
644
+ return;
645
+ this.runtime?.sample();
646
+ this.metrics?.flush();
647
+ await this.transport.flush();
648
+ }
649
+ }
650
+ exports.Agent = Agent;
651
+ //# sourceMappingURL=agent.js.map