@watchtowerobservability/node 0.0.0-stage → 0.2.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 (105) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +121 -2
  3. package/dist/cjs/buffer.d.ts +49 -0
  4. package/dist/cjs/buffer.js +134 -0
  5. package/dist/cjs/errors.d.ts +17 -0
  6. package/dist/cjs/errors.js +55 -0
  7. package/dist/cjs/index.d.ts +120 -0
  8. package/dist/cjs/index.js +302 -0
  9. package/dist/cjs/integrations/azure-functions.d.ts +18 -0
  10. package/dist/cjs/integrations/azure-functions.js +97 -0
  11. package/dist/cjs/integrations/express.d.ts +25 -0
  12. package/dist/cjs/integrations/express.js +58 -0
  13. package/dist/cjs/integrations/fastify.d.ts +6 -0
  14. package/dist/cjs/integrations/fastify.js +44 -0
  15. package/dist/cjs/integrations/genai-agents.d.ts +36 -0
  16. package/dist/cjs/integrations/genai-agents.js +124 -0
  17. package/dist/cjs/integrations/genai-stream.d.ts +19 -0
  18. package/dist/cjs/integrations/genai-stream.js +135 -0
  19. package/dist/cjs/integrations/genai.d.ts +18 -0
  20. package/dist/cjs/integrations/genai.js +150 -0
  21. package/dist/cjs/integrations/koa.d.ts +19 -0
  22. package/dist/cjs/integrations/koa.js +34 -0
  23. package/dist/cjs/integrations/lambda.d.ts +11 -0
  24. package/dist/cjs/integrations/lambda.js +68 -0
  25. package/dist/cjs/integrations/logs.d.ts +10 -0
  26. package/dist/cjs/integrations/logs.js +77 -0
  27. package/dist/cjs/integrations/nestjs.d.ts +16 -0
  28. package/dist/cjs/integrations/nestjs.js +30 -0
  29. package/dist/cjs/integrations/next.d.ts +11 -0
  30. package/dist/cjs/integrations/next.js +59 -0
  31. package/dist/cjs/integrations/prisma.d.ts +3 -0
  32. package/dist/cjs/integrations/prisma.js +33 -0
  33. package/dist/cjs/integrations/util.d.ts +9 -0
  34. package/dist/cjs/integrations/util.js +37 -0
  35. package/dist/cjs/jest.d.ts +21 -0
  36. package/dist/cjs/jest.js +45 -0
  37. package/dist/cjs/load.d.ts +1 -0
  38. package/dist/cjs/load.js +11 -0
  39. package/dist/cjs/metrics.d.ts +10 -0
  40. package/dist/cjs/metrics.js +81 -0
  41. package/dist/cjs/package.json +1 -0
  42. package/dist/cjs/payload.d.ts +42 -0
  43. package/dist/cjs/payload.js +145 -0
  44. package/dist/cjs/probes.d.ts +97 -0
  45. package/dist/cjs/probes.js +422 -0
  46. package/dist/cjs/profiling.d.ts +81 -0
  47. package/dist/cjs/profiling.js +253 -0
  48. package/dist/cjs/reporter-core.d.ts +32 -0
  49. package/dist/cjs/reporter-core.js +102 -0
  50. package/dist/cjs/test-plan.d.ts +93 -0
  51. package/dist/cjs/test-plan.js +262 -0
  52. package/dist/cjs/vitest.d.ts +27 -0
  53. package/dist/cjs/vitest.js +52 -0
  54. package/dist/esm/buffer.d.ts +49 -0
  55. package/dist/esm/buffer.js +92 -0
  56. package/dist/esm/errors.d.ts +17 -0
  57. package/dist/esm/errors.js +50 -0
  58. package/dist/esm/index.d.ts +120 -0
  59. package/dist/esm/index.js +251 -0
  60. package/dist/esm/integrations/azure-functions.d.ts +18 -0
  61. package/dist/esm/integrations/azure-functions.js +60 -0
  62. package/dist/esm/integrations/express.d.ts +25 -0
  63. package/dist/esm/integrations/express.js +54 -0
  64. package/dist/esm/integrations/fastify.d.ts +6 -0
  65. package/dist/esm/integrations/fastify.js +41 -0
  66. package/dist/esm/integrations/genai-agents.d.ts +36 -0
  67. package/dist/esm/integrations/genai-agents.js +118 -0
  68. package/dist/esm/integrations/genai-stream.d.ts +19 -0
  69. package/dist/esm/integrations/genai-stream.js +130 -0
  70. package/dist/esm/integrations/genai.d.ts +18 -0
  71. package/dist/esm/integrations/genai.js +138 -0
  72. package/dist/esm/integrations/koa.d.ts +19 -0
  73. package/dist/esm/integrations/koa.js +31 -0
  74. package/dist/esm/integrations/lambda.d.ts +11 -0
  75. package/dist/esm/integrations/lambda.js +32 -0
  76. package/dist/esm/integrations/logs.d.ts +10 -0
  77. package/dist/esm/integrations/logs.js +40 -0
  78. package/dist/esm/integrations/nestjs.d.ts +16 -0
  79. package/dist/esm/integrations/nestjs.js +26 -0
  80. package/dist/esm/integrations/next.d.ts +11 -0
  81. package/dist/esm/integrations/next.js +22 -0
  82. package/dist/esm/integrations/prisma.d.ts +3 -0
  83. package/dist/esm/integrations/prisma.js +30 -0
  84. package/dist/esm/integrations/util.d.ts +9 -0
  85. package/dist/esm/integrations/util.js +32 -0
  86. package/dist/esm/jest.d.ts +21 -0
  87. package/dist/esm/jest.js +41 -0
  88. package/dist/esm/load.d.ts +1 -0
  89. package/dist/esm/load.js +5 -0
  90. package/dist/esm/metrics.d.ts +10 -0
  91. package/dist/esm/metrics.js +44 -0
  92. package/dist/esm/package.json +1 -0
  93. package/dist/esm/payload.d.ts +42 -0
  94. package/dist/esm/payload.js +131 -0
  95. package/dist/esm/probes.d.ts +97 -0
  96. package/dist/esm/probes.js +412 -0
  97. package/dist/esm/profiling.d.ts +81 -0
  98. package/dist/esm/profiling.js +242 -0
  99. package/dist/esm/reporter-core.d.ts +32 -0
  100. package/dist/esm/reporter-core.js +63 -0
  101. package/dist/esm/test-plan.d.ts +93 -0
  102. package/dist/esm/test-plan.js +248 -0
  103. package/dist/esm/vitest.d.ts +27 -0
  104. package/dist/esm/vitest.js +48 -0
  105. package/package.json +219 -4
@@ -0,0 +1,412 @@
1
+ // Dynamic probes for running Node.js code (PLT-044), with the safety model of the Python, Go and
2
+ // browser agents: off until `startProbes` is called, read-only and bounded.
3
+ //
4
+ // A worker thread connects the inspector to the main thread and sets a breakpoint per live probe
5
+ // (`file` + `line`). On a hit it reads the frame's local scopes with `Runtime.getProperties`
6
+ // (own data properties only: getters, proxies' traps and user methods never run; depth at most 3,
7
+ // 50 properties per object) and resumes at once. The main thread then evaluates the probe's
8
+ // condition (a subset with no calls) over those plain values, applies the per-minute rate
9
+ // limit, flattens them to `code.snapshot.*` (8 KiB, 1 KiB per value) and emits `probe.snapshot`.
10
+ // With no live probe the debugger is disabled and nothing pauses.
11
+ //
12
+ // Kind `span` wraps a CommonJS export named by `location.function` (`src/billing.js:charge`,
13
+ // `Billing.prototype.charge` or a bare export name) in a current span `probe <fn>`; removing the
14
+ // probe restores the original. Kind `span_decoration` at `file` + `line` sets `capture.tags`
15
+ // (templates over the locals) on the span active in the paused frame, through one fixed
16
+ // expression of ours evaluated on that frame (it reads the OpenTelemetry API global and calls
17
+ // `setAttributes` with JSON literals; no user code is called). At `function` it tags at entry.
18
+ // shortcut: ES module namespaces are read-only, so span probes reach CommonJS exports only;
19
+ // upgrade with a loader hook (`module.register`) when ESM apps need them.
20
+ import { createRequire } from 'node:module';
21
+ import { Worker } from 'node:worker_threads';
22
+ import { context, SpanStatusCode, trace } from '@opentelemetry/api';
23
+ const VALUE_MAX = 1024;
24
+ /** Collected pauses per probe and minute; beyond it the worker resumes without reading locals. */
25
+ const MAX_PAUSES_PER_MIN = 600;
26
+ /** Compile a condition; throws on anything outside the subset (calls included). Self-contained: the worker embeds its source. */
27
+ export function compile(src = '') {
28
+ if (!src.trim())
29
+ return () => true;
30
+ const TOKEN = /\s*(&&|\|\||==|!=|<=|>=|[<>!()[\],]|'[^']*'|"[^"]*"|-?\d+(?:\.\d+)?|[A-Za-z_][\w.]*)/y;
31
+ const t = [];
32
+ TOKEN.lastIndex = 0;
33
+ let end = 0;
34
+ for (let m; (m = TOKEN.exec(src)); end = TOKEN.lastIndex)
35
+ t.push(m[1]);
36
+ if (end !== src.trimEnd().length)
37
+ throw new Error('bad condition');
38
+ let i = 0;
39
+ const eat = (s) => (t[i] === s ? (i++, true) : false);
40
+ const get = (v, name) => name.split('.').reduce((o, k) => (o && typeof o === 'object' ? o[k] : undefined), v);
41
+ const lit = (x) => x === 'true' ? true : x === 'false' ? false : x === 'null' ? null : /^['"]/.test(x) ? x.slice(1, -1) : Number(x);
42
+ const atom = () => {
43
+ const x = t[i++];
44
+ if (x === undefined)
45
+ throw new Error('bad condition');
46
+ if (x === '(') {
47
+ const e = or();
48
+ if (!eat(')'))
49
+ throw new Error('bad condition');
50
+ return e;
51
+ }
52
+ if (x === '[') {
53
+ const items = [];
54
+ while (t[i] !== ']') {
55
+ if (i >= t.length)
56
+ throw new Error('bad condition');
57
+ const n = t[i++];
58
+ if (n !== ',')
59
+ items.push(lit(n));
60
+ }
61
+ i++;
62
+ return () => items;
63
+ }
64
+ if (/^['"]|^-?\d/.test(x) || x === 'true' || x === 'false' || x === 'null') {
65
+ const val = lit(x);
66
+ return () => val;
67
+ }
68
+ if (t[i] === '(')
69
+ throw new Error('function calls are not allowed');
70
+ return (v) => get(v, x);
71
+ };
72
+ const cmp = () => {
73
+ const a = atom();
74
+ for (const op of ['==', '!=', '<=', '>=', '<', '>', 'in', 'contains']) {
75
+ if (!eat(op))
76
+ continue;
77
+ const b = atom();
78
+ return (v) => {
79
+ const x = a(v), y = b(v);
80
+ switch (op) {
81
+ case '==': return x === y;
82
+ case '!=': return x !== y;
83
+ case '<': return x < y;
84
+ case '<=': return x <= y;
85
+ case '>': return x > y;
86
+ case '>=': return x >= y;
87
+ case 'in': return Array.isArray(y) && y.includes(x);
88
+ default: return typeof x === 'string' && typeof y === 'string' && x.includes(y);
89
+ }
90
+ };
91
+ }
92
+ return a;
93
+ };
94
+ const not = () => {
95
+ if (eat('!')) {
96
+ const n = not();
97
+ return (v) => !n(v);
98
+ }
99
+ return cmp();
100
+ };
101
+ const and = () => {
102
+ let l = not();
103
+ while (eat('&&')) {
104
+ const a = l, r = not();
105
+ l = (v) => !!a(v) && !!r(v);
106
+ }
107
+ return l;
108
+ };
109
+ const or = () => {
110
+ let l = and();
111
+ while (eat('||')) {
112
+ const a = l, r = and();
113
+ l = (v) => !!a(v) || !!r(v);
114
+ }
115
+ return l;
116
+ };
117
+ const root = or();
118
+ if (i !== t.length)
119
+ throw new Error('bad condition');
120
+ return (v) => !!root(v);
121
+ }
122
+ /** Flatten to dotted names: nesting past `depth` collapses, values cut to 1 KiB, total to `maxBytes`. */
123
+ export function capture(vars, depth, maxBytes) {
124
+ const out = {};
125
+ let used = 0;
126
+ const put = (name, val) => {
127
+ const s = val.slice(0, VALUE_MAX);
128
+ if (used + name.length + s.length <= maxBytes) {
129
+ used += name.length + s.length;
130
+ out[name] = s;
131
+ }
132
+ };
133
+ const walk = (prefix, v, d) => {
134
+ if (v && typeof v === 'object') {
135
+ if (d > depth)
136
+ return put(prefix, '[depth limit]');
137
+ for (const k of Object.keys(v).sort())
138
+ walk(prefix ? `${prefix}.${k}` : k, v[k], d + 1);
139
+ }
140
+ else
141
+ put(prefix, String(v));
142
+ };
143
+ walk('', vars, 0);
144
+ return out;
145
+ }
146
+ /** Fill `{a.b}` from vars (missing names render empty), cut to 1 KiB. Self-contained: the worker embeds it. */
147
+ export function render(template, vars) {
148
+ return template.replace(/\{([A-Za-z_][\w.]*)\}/g, (_m, name) => {
149
+ const v = name.split('.').reduce((o, k) => (o && typeof o === 'object' ? o[k] : undefined), vars);
150
+ return v === undefined || v === null ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v);
151
+ }).slice(0, 1024);
152
+ }
153
+ /** `capture.tags` rendered over vars; `wt.*` names are never set. */
154
+ export function tags(def, vars) {
155
+ const out = {};
156
+ for (const t of def.capture?.tags ?? [])
157
+ if (t.name && !t.name.startsWith('wt.'))
158
+ out[t.name] = render(t.value ?? '', vars);
159
+ return out;
160
+ }
161
+ /** The expression the worker evaluates on a paused frame: tag the active span (OTel API 1.x global). */
162
+ export function decorateExpr(attrs) {
163
+ return `(() => { const g = globalThis[Symbol.for('opentelemetry.js.api.1')]; ` +
164
+ `const s = g && g.context && g.context.active().getValue(Symbol.for('OpenTelemetry Context Key SPAN')); ` +
165
+ `if (s && s.isRecording()) s.setAttributes(${JSON.stringify(attrs)}); })()`;
166
+ }
167
+ // The worker: inspector bridge; decorations are judged here because the main thread is paused.
168
+ const WORKER = `
169
+ const compile = ${compile.toString()};
170
+ const render = ${render.toString()};
171
+ const decorateExpr = ${decorateExpr.toString()};
172
+ const { parentPort } = require('node:worker_threads');
173
+ const { Session } = require('node:inspector');
174
+ const s = new Session();
175
+ s.connectToMainThread();
176
+ const post = (m, p) => new Promise((ok, no) => s.post(m, p || {}, (e, r) => (e ? no(e) : ok(r))));
177
+ let enabled = false, byBp = new Map(), counts = new Map(), win = 0, decs = new Map();
178
+ const MAX = ${MAX_PAUSES_PER_MIN};
179
+ async function plain(objectId, d) {
180
+ const { result } = await post('Runtime.getProperties', { objectId, ownProperties: true, generatePreview: false });
181
+ const out = {};
182
+ for (const p of result.slice(0, 50)) {
183
+ const v = p.value;
184
+ if (!v || v.type === 'function' || v.type === 'symbol') continue; // accessors stay unread
185
+ if (v.type === 'object' && v.subtype !== 'null') out[p.name] = d >= 3 ? '[depth limit]' : await plain(v.objectId, d + 1);
186
+ else out[p.name] = v.subtype === 'null' ? null : v.type === 'undefined' ? 'undefined' : v.unserializableValue ?? v.value;
187
+ }
188
+ return out;
189
+ }
190
+ s.on('Debugger.paused', async ({ params }) => {
191
+ try {
192
+ const all = (params.hitBreakpoints || []).map((b) => byBp.get(b)).filter(Boolean);
193
+ const now = Date.now(), minute = Math.floor(now / 60000);
194
+ if (minute !== win) { win = minute; counts = new Map(); }
195
+ const take = all.filter((id) => { const n = (counts.get(id) || 0) + 1; counts.set(id, n); return n <= (decs.has(id) ? Math.min(decs.get(id).rate || 60, 60) : MAX); });
196
+ if (!take.length) return;
197
+ const f = params.callFrames[0];
198
+ const vars = {};
199
+ for (const sc of f.scopeChain) if (sc.type === 'local' || sc.type === 'block') Object.assign(vars, await plain(sc.object.objectId, 1));
200
+ for (const id of take.filter((i) => decs.has(i))) {
201
+ const d = decs.get(id);
202
+ if ((d.exp && now >= d.exp) || !d.ok(vars)) continue;
203
+ const attrs = {};
204
+ for (const t of d.tags) if (t.name && !t.name.startsWith('wt.')) attrs[t.name] = render(t.value || '', vars);
205
+ await post('Debugger.evaluateOnCallFrame', { callFrameId: f.callFrameId, expression: decorateExpr(attrs), silent: true });
206
+ }
207
+ const ids = take.filter((i) => !decs.has(i));
208
+ if (ids.length) parentPort.postMessage({ ids, fn: f.functionName, url: f.url, line: f.location.lineNumber + 1, vars });
209
+ } catch {} finally { s.post('Debugger.resume'); }
210
+ });
211
+ parentPort.on('message', async (defs) => {
212
+ try {
213
+ for (const bp of byBp.keys()) await post('Debugger.removeBreakpoint', { breakpointId: bp });
214
+ byBp = new Map();
215
+ decs = new Map();
216
+ for (const d of defs) if (d.dec) { try { decs.set(d.id, { ...d.dec, ok: compile(d.dec.cond) }); } catch {} }
217
+ if (!defs.length) { if (enabled) await post('Debugger.disable'); enabled = false; return; }
218
+ if (!enabled) { await post('Debugger.enable'); enabled = true; }
219
+ for (const d of defs) {
220
+ const r = await post('Debugger.setBreakpointByUrl', { lineNumber: d.line - 1, urlRegex: d.urlRegex });
221
+ byBp.set(r.breakpointId, d.id);
222
+ }
223
+ } catch {}
224
+ });
225
+ `;
226
+ /** Parameter names of a function from its source (`argN` where a parameter is destructured or unknown). */
227
+ export function paramNames(fn) {
228
+ const m = /^[^(]*\(([^)]*)\)/.exec(Function.prototype.toString.call(fn)) ?? /^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/.exec(Function.prototype.toString.call(fn));
229
+ return (m?.[1] ?? '').split(',').map((p, i) => /^\s*(?:\.\.\.)?([A-Za-z_$][\w$]*)\s*(=.*)?$/.exec(p)?.[1] ?? `arg${i}`);
230
+ }
231
+ /** The object holding `path` (dots) in a module's exports, or null. */
232
+ function locate(exports, path) {
233
+ const parts = path.split('.');
234
+ let holder = exports;
235
+ for (const k of parts.slice(0, -1))
236
+ holder = holder && (typeof holder === 'object' || typeof holder === 'function') ? holder[k] : undefined;
237
+ const key = parts[parts.length - 1];
238
+ if (!holder || (typeof holder !== 'object' && typeof holder !== 'function'))
239
+ return null;
240
+ const desc = Object.getOwnPropertyDescriptor(holder, key);
241
+ return desc && desc.writable && typeof desc.value === 'function' ? { holder, key } : null;
242
+ }
243
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
244
+ /** The probe set of one service: `set` replaces it, `poll` refreshes it, `onHit` handles a pause. */
245
+ export function createProbes(o) {
246
+ const now = o.now ?? Date.now;
247
+ const emit = o.emit ?? ((name, attrs) => o.logger?.emit({ body: name, attributes: attrs }));
248
+ const endpoint = (o.endpoint ?? process.env.WT_API_URL ?? 'https://api.watchtower.dev').replace(/\/+$/, '');
249
+ const modules = o.modules ?? (() => createRequire(`${process.cwd()}/`).cache);
250
+ let live = new Map();
251
+ let wraps = [];
252
+ let etag = '';
253
+ /** Not expired (expires_at is unix seconds), inside the per-minute budget, condition holds; counts the hit. */
254
+ const allowed = (p, vars) => {
255
+ const t = now();
256
+ if (p.def.expires_at && t >= p.def.expires_at * 1000)
257
+ return false;
258
+ const minute = Math.floor(t / 60000);
259
+ if (p.win !== minute) {
260
+ p.win = minute;
261
+ p.n = 0;
262
+ }
263
+ if (p.n >= Math.min(p.def.max_rate_per_min || 60, 60) || !p.ok(vars))
264
+ return false;
265
+ p.n++;
266
+ return true;
267
+ };
268
+ const wrap = (p, holder, key) => {
269
+ const orig = holder[key];
270
+ const names = paramNames(orig);
271
+ const fnName = p.def.location.function;
272
+ const wrapped = function (...args) {
273
+ const vars = {};
274
+ args.forEach((a, i) => { vars[names[i] ?? `arg${i}`] = a; });
275
+ if (!allowed(p, vars))
276
+ return orig.apply(this, args);
277
+ if (p.def.kind === 'span_decoration') {
278
+ try {
279
+ trace.getActiveSpan()?.setAttributes(tags(p.def, vars));
280
+ }
281
+ catch { /* never fail the app */ }
282
+ return orig.apply(this, args);
283
+ }
284
+ const span = trace.getTracer('watchtower.probes').startSpan(`probe ${key}`, {
285
+ attributes: { 'probe.id': p.def.id, 'code.function': fnName },
286
+ });
287
+ const fail = (e) => {
288
+ span.recordException(e instanceof Error ? e : String(e));
289
+ span.setStatus({ code: SpanStatusCode.ERROR });
290
+ span.end();
291
+ };
292
+ return context.with(trace.setSpan(context.active(), span), () => {
293
+ let r;
294
+ try {
295
+ r = orig.apply(this, args);
296
+ }
297
+ catch (e) {
298
+ fail(e);
299
+ throw e;
300
+ }
301
+ if (r && typeof r.then === 'function') {
302
+ return r.then((v) => { span.end(); return v; }, (e) => { fail(e); throw e; });
303
+ }
304
+ span.end();
305
+ return r;
306
+ });
307
+ };
308
+ Object.defineProperty(wrapped, 'name', { value: orig.name });
309
+ holder[key] = wrapped;
310
+ wraps.push({ holder, key, orig });
311
+ };
312
+ /** Wrap `file.js:path` (or `path` in any app module) for span and function-located decoration probes. */
313
+ const attach = (p) => {
314
+ const fn = p.def.location.function ?? '';
315
+ const at = fn.lastIndexOf(':');
316
+ const [file, path] = at > 0 ? [fn.slice(0, at), fn.slice(at + 1)] : ['', fn];
317
+ let hit = false;
318
+ for (const [filename, m] of Object.entries(modules())) {
319
+ if (!m || (file ? !filename.endsWith(file.replace(/^\/+/, '')) : filename.includes('/node_modules/')))
320
+ continue;
321
+ const loc = locate(m.exports, path);
322
+ if (loc) {
323
+ wrap(p, loc.holder, loc.key);
324
+ hit = true;
325
+ }
326
+ }
327
+ return hit;
328
+ };
329
+ const set = (defs) => {
330
+ for (const w of wraps.reverse())
331
+ w.holder[w.key] = w.orig;
332
+ wraps = [];
333
+ const next = new Map();
334
+ const bps = [];
335
+ for (const d of defs) {
336
+ try {
337
+ const p = { def: d, ok: compile(d.condition), win: 0, n: 0 };
338
+ const fnProbe = d.kind === 'span' || (d.kind === 'span_decoration' && !d.location.line);
339
+ if (fnProbe) {
340
+ if (d.location.function && attach(p))
341
+ next.set(d.id, p);
342
+ continue;
343
+ }
344
+ // shortcut: other Node probes need file + line (the source view always sends both).
345
+ if (!d.location.file || !d.location.line)
346
+ continue;
347
+ next.set(d.id, p);
348
+ const bp = { id: d.id, line: d.location.line, urlRegex: `(^|/)${escapeRe(d.location.file.replace(/^\/+/, ''))}$` };
349
+ if (d.kind === 'span_decoration') {
350
+ bp.dec = { cond: d.condition ?? '', tags: d.capture?.tags ?? [], rate: d.max_rate_per_min ?? 60, exp: (d.expires_at ?? 0) * 1000 };
351
+ }
352
+ bps.push(bp);
353
+ }
354
+ catch { /* a probe we cannot evaluate is skipped */ }
355
+ }
356
+ live = next;
357
+ o.post?.(bps);
358
+ };
359
+ const onHit = (h) => {
360
+ for (const id of h.ids) {
361
+ const p = live.get(id);
362
+ if (!p || !allowed(p, h.vars))
363
+ continue;
364
+ const cap = p.def.capture ?? {};
365
+ const attrs = { 'probe.id': id, 'code.function': h.fn, 'code.filepath': h.url, 'code.lineno': String(h.line) };
366
+ if (p.def.message)
367
+ attrs['probe.message'] = p.def.message;
368
+ const snap = capture(h.vars, Math.min(cap.locals_depth || 3, 3), Math.min(cap.max_bytes || 8192, 8192));
369
+ for (const [k, v] of Object.entries(snap))
370
+ attrs[`code.snapshot.${k}`] = v;
371
+ try {
372
+ emit('probe.snapshot', attrs);
373
+ }
374
+ catch { /* the app must never fail because of a probe */ }
375
+ }
376
+ };
377
+ const poll = async () => {
378
+ const q = new URLSearchParams({ service: o.service ?? process.env.OTEL_SERVICE_NAME ?? 'unknown', env: o.env ?? '', version: o.version ?? '',
379
+ kinds: 'log,snapshot,metric,span,span_decoration' });
380
+ const headers = { authorization: `Bearer ${o.key ?? process.env.WT_INGEST_KEY ?? ''}` };
381
+ if (etag)
382
+ headers['if-none-match'] = etag;
383
+ try {
384
+ const r = await (o.fetch ?? fetch)(`${endpoint}/v1/probes/active?${q}`, { headers, signal: AbortSignal.timeout(10_000) });
385
+ if (r.status !== 200)
386
+ return;
387
+ etag = r.headers.get('etag') ?? '';
388
+ set((await r.json()).probes ?? []);
389
+ }
390
+ catch { /* retried on the next poll */ }
391
+ };
392
+ return { set, poll, onHit, live: () => live };
393
+ }
394
+ /** Poll active probes and hook them through an inspector worker; `stop()` detaches everything. */
395
+ export function startProbes(o = {}) {
396
+ const w = new Worker(WORKER, { eval: true });
397
+ w.unref();
398
+ const p = createProbes({ ...o, post: (defs) => w.postMessage(defs) });
399
+ w.on('message', p.onHit);
400
+ w.on('error', () => { });
401
+ void p.poll();
402
+ const timer = setInterval(() => void p.poll(), Math.max(o.intervalMs ?? 30_000, 5_000));
403
+ timer.unref();
404
+ return {
405
+ async stop() {
406
+ clearInterval(timer);
407
+ w.postMessage([]);
408
+ await new Promise((r) => setTimeout(r, 100));
409
+ await w.terminate();
410
+ },
411
+ };
412
+ }
@@ -0,0 +1,81 @@
1
+ export interface CallFrame {
2
+ functionName: string;
3
+ url: string;
4
+ lineNumber: number;
5
+ }
6
+ export interface CpuProfileNode {
7
+ id: number;
8
+ callFrame: CallFrame;
9
+ children?: number[];
10
+ }
11
+ export interface CpuProfile {
12
+ nodes: CpuProfileNode[];
13
+ samples?: number[];
14
+ /** Microseconds on the monotonic clock. */
15
+ startTime?: number;
16
+ timeDeltas?: number[];
17
+ }
18
+ /** A span's time on the JS thread, microseconds on the same clock as the profile. */
19
+ export interface SpanInterval {
20
+ start: number;
21
+ end: number;
22
+ prefix: string;
23
+ }
24
+ /**
25
+ * Opt-in (overhead unmeasured): `withSpan` also labels its async function's code after each
26
+ * `await`. The span rides in an AsyncLocalStorage; a promise created under it is tagged, and each
27
+ * run of its continuation (V8 promise hooks `before` to `after`) is one more interval. Plain
28
+ * callbacks it starts (timers, events) are labeled only from their own `await`s on.
29
+ */
30
+ export declare function enableAsyncSpanLabels(): void;
31
+ /**
32
+ * Labels samples taken while `fn` runs with a span (default: the active OpenTelemetry span). Only
33
+ * `fn`'s synchronous part, unless [[enableAsyncSpanLabels]] (or the profiler's `asyncSpans`) is on.
34
+ */
35
+ export declare function withSpan<T>(fn: () => T, ids?: {
36
+ spanId: string;
37
+ traceId: string;
38
+ }): T;
39
+ /** Takes the intervals a profile up to `until` can need; open ones stay for the next profile. */
40
+ export declare function takeIntervals(until: number): SpanInterval[];
41
+ export interface ProfilerOptions {
42
+ /** Ingest key; defaults to WT_INGEST_KEY. */
43
+ apiKey?: string;
44
+ /** Gateway base URL; defaults to WT_OTLP_ENDPOINT or http://localhost:4318. */
45
+ endpoint?: string;
46
+ /** Defaults to WT_SERVICE or `app`. */
47
+ service?: string;
48
+ tags?: Record<string, string | undefined>;
49
+ /** Sampling interval in microseconds (default 10 000 = 100 Hz). */
50
+ intervalUs?: number;
51
+ /** Upload period (default 15 000 ms). */
52
+ periodMs?: number;
53
+ /** Label `withSpan` code after `await` too (see [[enableAsyncSpanLabels]]). Default false. */
54
+ asyncSpans?: boolean;
55
+ }
56
+ /** Root-first folded stacks with their sample counts; V8's synthetic `(root)` is left out. */
57
+ export declare function foldProfile(p: CpuProfile, spans?: SpanInterval[]): Map<string, number>;
58
+ export declare function foldedBody(counts: Map<string, number>): string;
59
+ export declare function ingestUrl(endpoint: string, service: string, tags: Record<string, string | undefined>, fromS: number, untilS: number, hz: number): string;
60
+ export declare class Profiler {
61
+ uploaded: number;
62
+ dropped: number;
63
+ private readonly key;
64
+ private readonly endpoint;
65
+ private readonly service;
66
+ private readonly tags;
67
+ private readonly intervalUs;
68
+ private readonly periodMs;
69
+ private session?;
70
+ private timer?;
71
+ private from;
72
+ constructor(o?: ProfilerOptions);
73
+ private post;
74
+ start(): Promise<this>;
75
+ /** Stop the current profile, upload it and (when `restart`) start the next one. */
76
+ flush(restart: boolean): Promise<void>;
77
+ upload(counts: Map<string, number>, fromS: number, untilS: number): Promise<void>;
78
+ stop(): Promise<void>;
79
+ }
80
+ /** Start a [[Profiler]] with the SDK's environment defaults. */
81
+ export declare function startProfiling(o?: ProfilerOptions): Promise<Profiler>;