@watchtowerobservability/node 0.7.3 → 0.7.5

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 (97) hide show
  1. package/CHANGELOG.md +40 -1
  2. package/README.md +96 -12
  3. package/dist/cjs/attach.d.ts +7 -0
  4. package/dist/cjs/attach.js +29 -0
  5. package/dist/cjs/checkin.js +4 -13
  6. package/dist/cjs/cron/monitor.d.ts +47 -0
  7. package/dist/cjs/cron/monitor.js +95 -0
  8. package/dist/cjs/cron/schedulers.d.ts +36 -0
  9. package/dist/cjs/cron/schedulers.js +65 -0
  10. package/dist/cjs/env.d.ts +10 -0
  11. package/dist/cjs/env.js +98 -1
  12. package/dist/cjs/index.d.ts +50 -6
  13. package/dist/cjs/index.js +114 -37
  14. package/dist/cjs/instrument-for.d.ts +17 -0
  15. package/dist/cjs/instrument-for.js +44 -0
  16. package/dist/cjs/instrument.d.ts +4 -0
  17. package/dist/cjs/instrument.js +32 -1
  18. package/dist/cjs/integrations/bullmq.d.ts +8 -2
  19. package/dist/cjs/integrations/bullmq.js +32 -5
  20. package/dist/cjs/integrations/db.d.ts +7 -2
  21. package/dist/cjs/integrations/db.js +32 -4
  22. package/dist/cjs/integrations/fastify.d.ts +1 -1
  23. package/dist/cjs/integrations/fastify.js +3 -2
  24. package/dist/cjs/integrations/logs.js +16 -5
  25. package/dist/cjs/integrations/next-build.d.ts +25 -8
  26. package/dist/cjs/integrations/next-build.js +159 -34
  27. package/dist/cjs/integrations/next-tunnel.d.ts +6 -1
  28. package/dist/cjs/integrations/next-tunnel.js +13 -2
  29. package/dist/cjs/integrations/postgres.d.ts +2 -0
  30. package/dist/cjs/integrations/postgres.js +43 -1
  31. package/dist/cjs/integrations/temporal.d.ts +97 -0
  32. package/dist/cjs/integrations/temporal.js +144 -0
  33. package/dist/cjs/integrations/util.d.ts +17 -0
  34. package/dist/cjs/integrations/util.js +38 -0
  35. package/dist/cjs/load.d.ts +6 -0
  36. package/dist/cjs/load.js +28 -4
  37. package/dist/cjs/next-doctor-cli.d.ts +2 -0
  38. package/dist/cjs/next-doctor-cli.js +15 -0
  39. package/dist/cjs/next-doctor.d.ts +2 -0
  40. package/dist/cjs/next-doctor.js +50 -0
  41. package/dist/cjs/pprof.d.ts +2 -0
  42. package/dist/cjs/pprof.js +18 -5
  43. package/dist/cjs/profiling.d.ts +31 -0
  44. package/dist/cjs/profiling.js +67 -11
  45. package/dist/cjs/redact-presets.d.ts +16 -0
  46. package/dist/cjs/redact-presets.js +66 -0
  47. package/dist/cjs/register.js +19 -6
  48. package/dist/cjs/version.d.ts +1 -1
  49. package/dist/cjs/version.js +1 -1
  50. package/dist/esm/attach.d.ts +7 -0
  51. package/dist/esm/attach.js +25 -0
  52. package/dist/esm/checkin.js +4 -13
  53. package/dist/esm/cron/monitor.d.ts +47 -0
  54. package/dist/esm/cron/monitor.js +85 -0
  55. package/dist/esm/cron/schedulers.d.ts +36 -0
  56. package/dist/esm/cron/schedulers.js +61 -0
  57. package/dist/esm/env.d.ts +10 -0
  58. package/dist/esm/env.js +62 -0
  59. package/dist/esm/index.d.ts +50 -6
  60. package/dist/esm/index.js +109 -39
  61. package/dist/esm/instrument-for.d.ts +17 -0
  62. package/dist/esm/instrument-for.js +41 -0
  63. package/dist/esm/instrument.d.ts +4 -0
  64. package/dist/esm/instrument.js +30 -1
  65. package/dist/esm/integrations/bullmq.d.ts +8 -2
  66. package/dist/esm/integrations/bullmq.js +32 -5
  67. package/dist/esm/integrations/db.d.ts +7 -2
  68. package/dist/esm/integrations/db.js +29 -4
  69. package/dist/esm/integrations/fastify.d.ts +1 -1
  70. package/dist/esm/integrations/fastify.js +4 -3
  71. package/dist/esm/integrations/logs.js +16 -5
  72. package/dist/esm/integrations/next-build.d.ts +25 -8
  73. package/dist/esm/integrations/next-build.js +158 -34
  74. package/dist/esm/integrations/next-tunnel.d.ts +6 -1
  75. package/dist/esm/integrations/next-tunnel.js +13 -2
  76. package/dist/esm/integrations/postgres.d.ts +2 -0
  77. package/dist/esm/integrations/postgres.js +43 -2
  78. package/dist/esm/integrations/temporal.d.ts +97 -0
  79. package/dist/esm/integrations/temporal.js +139 -0
  80. package/dist/esm/integrations/util.d.ts +17 -0
  81. package/dist/esm/integrations/util.js +35 -0
  82. package/dist/esm/load.d.ts +6 -0
  83. package/dist/esm/load.js +21 -3
  84. package/dist/esm/next-doctor-cli.d.ts +2 -0
  85. package/dist/esm/next-doctor-cli.js +13 -0
  86. package/dist/esm/next-doctor.d.ts +2 -0
  87. package/dist/esm/next-doctor.js +14 -0
  88. package/dist/esm/pprof.d.ts +2 -0
  89. package/dist/esm/pprof.js +17 -5
  90. package/dist/esm/profiling.d.ts +31 -0
  91. package/dist/esm/profiling.js +66 -12
  92. package/dist/esm/redact-presets.d.ts +16 -0
  93. package/dist/esm/redact-presets.js +58 -0
  94. package/dist/esm/register.js +20 -7
  95. package/dist/esm/version.d.ts +1 -1
  96. package/dist/esm/version.js +1 -1
  97. package/package.json +42 -1
@@ -4,12 +4,14 @@ exports.Profiler = void 0;
4
4
  exports.enableAsyncSpanLabels = enableAsyncSpanLabels;
5
5
  exports.withSpan = withSpan;
6
6
  exports.takeIntervals = takeIntervals;
7
+ exports.parseProfilingTypes = parseProfilingTypes;
7
8
  exports.foldProfile = foldProfile;
9
+ exports.foldHeap = foldHeap;
8
10
  exports.foldedBody = foldedBody;
9
11
  exports.profilesUrl = profilesUrl;
10
12
  exports.ingestUrl = ingestUrl;
11
13
  exports.startProfiling = startProfiling;
12
- // Continuous CPU profiler on V8's own sampler (`node:inspector`, no native addon): every
14
+ // Continuous CPU (and opt-in heap) profiler on V8's own samplers (`node:inspector`, no native addon): every
13
15
  // `periodMs` the CPU profile is folded into stacks, encoded as pprof and posted to the gateway's
14
16
  // `/v1/profiles?format=pprof` with `service` and `version`. Best effort: a failed upload is
15
17
  // counted and dropped. `withSpan` labels samples taken while its function runs, joined
@@ -108,6 +110,11 @@ function prefixAt(sorted, t) {
108
110
  return sorted[i].prefix;
109
111
  return '';
110
112
  }
113
+ /** `cpu,heap` (WT_PROFILING_TYPES) to types; unknown names are ignored, nothing valid means cpu only. */
114
+ function parseProfilingTypes(v) {
115
+ const t = [...new Set((v ?? '').split(',').map((x) => x.trim().toLowerCase()))].filter((x) => x === 'cpu' || x === 'heap');
116
+ return t.length ? t : ['cpu'];
117
+ }
111
118
  const MAX_DEPTH = 128;
112
119
  function frameName(f) {
113
120
  const file = f.url ? f.url.split('/').pop() : '';
@@ -146,6 +153,28 @@ function foldProfile(p, spans = []) {
146
153
  }
147
154
  return counts;
148
155
  }
156
+ /**
157
+ * Root-first stacks of live heap with `[objects, bytes]`: bytes are the node's self size, objects the
158
+ * number of sampled allocations that still live in it (at least 1 for a node with bytes).
159
+ */
160
+ function foldHeap(p) {
161
+ const objs = new Map();
162
+ for (const x of p.samples ?? [])
163
+ objs.set(x.nodeId, (objs.get(x.nodeId) ?? 0) + 1);
164
+ const out = new Map();
165
+ const walk = (n, path) => {
166
+ const names = n.callFrame.functionName === '(root)' ? path : [...path, frameName(n.callFrame)];
167
+ if (n.selfSize > 0 && names.length && names.length <= MAX_DEPTH) {
168
+ const key = names.join(';');
169
+ const cur = out.get(key) ?? [0, 0];
170
+ out.set(key, [cur[0] + Math.max(objs.get(n.id) ?? 0, 1), cur[1] + n.selfSize]);
171
+ }
172
+ for (const c of n.children ?? [])
173
+ walk(c, names);
174
+ };
175
+ walk(p.head, []);
176
+ return out;
177
+ }
149
178
  function foldedBody(counts) {
150
179
  let out = '';
151
180
  for (const [k, n] of counts)
@@ -178,6 +207,8 @@ class Profiler {
178
207
  tags;
179
208
  intervalUs;
180
209
  periodMs;
210
+ types;
211
+ heapIntervalBytes;
181
212
  session;
182
213
  timer;
183
214
  from = 0;
@@ -191,6 +222,8 @@ class Profiler {
191
222
  this.tags = { env: process.env.WT_ENVIRONMENT, version: process.env.WT_RELEASE, ...o.tags };
192
223
  this.intervalUs = Math.min(Math.max(o.intervalUs ?? 10_000, 1_000), 1_000_000);
193
224
  this.periodMs = Math.max(o.periodMs ?? 60_000, 1_000);
225
+ this.types = o.types?.length ? o.types : parseProfilingTypes(process.env.WT_PROFILING_TYPES);
226
+ this.heapIntervalBytes = Math.max(o.heapIntervalBytes ?? 524_288, 1024);
194
227
  if (o.asyncSpans)
195
228
  enableAsyncSpanLabels();
196
229
  }
@@ -208,9 +241,14 @@ class Profiler {
208
241
  return this;
209
242
  this.session = new node_inspector_1.Session();
210
243
  this.session.connect();
211
- await this.post('Profiler.enable');
212
- await this.post('Profiler.setSamplingInterval', { interval: this.intervalUs });
213
- await this.post('Profiler.start');
244
+ if (this.types.includes('cpu')) {
245
+ await this.post('Profiler.enable');
246
+ await this.post('Profiler.setSamplingInterval', { interval: this.intervalUs });
247
+ await this.post('Profiler.start');
248
+ }
249
+ if (this.types.includes('heap')) {
250
+ await this.post('HeapProfiler.startSampling', { samplingInterval: this.heapIntervalBytes });
251
+ }
214
252
  this.from = Date.now() / 1000;
215
253
  this.timer = setInterval(() => void this.flush(true), this.periodMs);
216
254
  this.timer.unref();
@@ -221,19 +259,35 @@ class Profiler {
221
259
  if (!this.session)
222
260
  return;
223
261
  const until = Date.now() / 1000;
224
- const { profile } = await this.post('Profiler.stop');
225
262
  const from = this.from;
226
- if (restart) {
227
- await this.post('Profiler.start');
228
- this.from = until;
263
+ let heap;
264
+ if (this.types.includes('heap')) {
265
+ // live-heap snapshot; sampling keeps running
266
+ const { profile } = await this.post('HeapProfiler.getSamplingProfile');
267
+ heap = foldHeap(profile);
229
268
  }
230
- const counts = foldProfile(profile, takeIntervals(nowUs()));
231
- if (counts.size)
269
+ let counts;
270
+ if (this.types.includes('cpu')) {
271
+ const { profile } = await this.post('Profiler.stop');
272
+ if (restart)
273
+ await this.post('Profiler.start');
274
+ counts = foldProfile(profile, takeIntervals(nowUs()));
275
+ }
276
+ if (restart)
277
+ this.from = until;
278
+ if (counts?.size)
232
279
  await this.upload(counts, from, until);
280
+ if (heap?.size)
281
+ await this.uploadHeap(heap, from, until);
282
+ }
283
+ async uploadHeap(stacks, fromS, untilS) {
284
+ await this.send((0, pprof_js_1.heapToPprof)(stacks, this.heapIntervalBytes, fromS * 1000, (untilS - fromS) * 1000));
233
285
  }
234
286
  async upload(counts, fromS, untilS) {
287
+ await this.send((0, pprof_js_1.foldedToPprof)(counts, this.intervalUs * 1000, fromS * 1000, (untilS - fromS) * 1000));
288
+ }
289
+ async send(body) {
235
290
  try {
236
- const body = (0, pprof_js_1.foldedToPprof)(counts, this.intervalUs * 1000, fromS * 1000, (untilS - fromS) * 1000);
237
291
  const r = await fetch(profilesUrl(this.endpoint, this.service, this.tags.version), {
238
292
  method: 'POST', body,
239
293
  headers: { authorization: `Bearer ${this.key}`, 'content-type': 'application/octet-stream' },
@@ -252,6 +306,8 @@ class Profiler {
252
306
  if (this.timer)
253
307
  clearInterval(this.timer);
254
308
  await this.flush(false).catch(() => undefined);
309
+ if (this.types.includes('heap'))
310
+ await this.post('HeapProfiler.stopSampling').catch(() => undefined);
255
311
  this.session?.disconnect();
256
312
  this.session = undefined;
257
313
  }
@@ -0,0 +1,16 @@
1
+ import type { RedactHook } from './redact.js';
2
+ export type RedactPreset = 'strict' | 'pii' | 'off';
3
+ export declare const REDACTED = "[redacted]";
4
+ /** Luhn checksum over the digits of `s` (13 to 19 digits). */
5
+ export declare function luhn(s: string): boolean;
6
+ /** Replace emails, phone numbers, Luhn-valid card numbers and IP addresses in free text with `[redacted:<kind>]`. */
7
+ export declare function scrubPii(s: string): string;
8
+ /** True for attribute keys that carry secrets (`http.request.header.authorization`, `db.password`, `x-api-key`); `gen_ai.*` token counters and types are not. */
9
+ export declare const isSecretKey: (k: string) => boolean;
10
+ /** The hook for a preset, or undefined for `off`. Only strings (and arrays of strings) are touched; numbers and booleans pass. */
11
+ export declare function presetHook(level: RedactPreset | undefined): RedactHook | undefined;
12
+ /** `redact` option -> the combined hook: the preset first (default `strict`), then the user's function. */
13
+ export declare function resolveRedact(opt: RedactHook | RedactPreset | undefined): {
14
+ preset: RedactPreset;
15
+ hook: RedactHook | undefined;
16
+ };
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isSecretKey = exports.REDACTED = void 0;
4
+ exports.luhn = luhn;
5
+ exports.scrubPii = scrubPii;
6
+ exports.presetHook = presetHook;
7
+ exports.resolveRedact = resolveRedact;
8
+ exports.REDACTED = '[redacted]';
9
+ /** Attribute keys whose string values are secrets: the server's list plus session, credential, private key. */
10
+ const SECRET_KEY = /(?:^|[._-])(?:authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_]?key|session|sid|credential|private[-_]?key)(?:$|[._-])/i;
11
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g;
12
+ const PHONE = /\+\d{1,3}[ .-]?\(?\d{2,4}\)?[ .-]?\d{3,4}[ .-]?\d{3,4}\b/g;
13
+ const CARD = /\b\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{1,7}\b/g;
14
+ const IPV4 = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;
15
+ const IPV6 = /\b(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}\b|\b(?:[0-9A-Fa-f]{1,4}:){1,6}:(?:[0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4}\b/g;
16
+ /** Luhn checksum over the digits of `s` (13 to 19 digits). */
17
+ function luhn(s) {
18
+ const d = s.replace(/\D/g, '');
19
+ if (d.length < 13 || d.length > 19)
20
+ return false;
21
+ let sum = 0;
22
+ for (let i = 0; i < d.length; i++) {
23
+ let n = d.charCodeAt(d.length - 1 - i) - 48;
24
+ if (i % 2 === 1 && (n *= 2) > 9)
25
+ n -= 9;
26
+ sum += n;
27
+ }
28
+ return sum % 10 === 0;
29
+ }
30
+ /** Replace emails, phone numbers, Luhn-valid card numbers and IP addresses in free text with `[redacted:<kind>]`. */
31
+ function scrubPii(s) {
32
+ return s
33
+ .replace(EMAIL, '[redacted:email]')
34
+ .replace(CARD, (m) => (luhn(m) ? '[redacted:card]' : m))
35
+ .replace(PHONE, '[redacted:phone]')
36
+ .replace(IPV4, (m) => (m.split('.').every((o) => Number(o) <= 255) ? '[redacted:ipv4]' : m))
37
+ .replace(IPV6, '[redacted:ipv6]');
38
+ }
39
+ /** True for attribute keys that carry secrets (`http.request.header.authorization`, `db.password`, `x-api-key`); `gen_ai.*` token counters and types are not. */
40
+ const isSecretKey = (k) => !k.startsWith('gen_ai.') && SECRET_KEY.test(k);
41
+ exports.isSecretKey = isSecretKey;
42
+ /** The hook for a preset, or undefined for `off`. Only strings (and arrays of strings) are touched; numbers and booleans pass. */
43
+ function presetHook(level) {
44
+ if (level === 'off')
45
+ return undefined;
46
+ const pii = level === 'pii';
47
+ const hook = (k, v) => {
48
+ if (Array.isArray(v))
49
+ return v.map((x) => hook(k, x));
50
+ if (typeof v !== 'string')
51
+ return v;
52
+ if ((0, exports.isSecretKey)(k))
53
+ return exports.REDACTED;
54
+ return pii ? scrubPii(v) : v;
55
+ };
56
+ return hook;
57
+ }
58
+ /** `redact` option -> the combined hook: the preset first (default `strict`), then the user's function. */
59
+ function resolveRedact(opt) {
60
+ const preset = typeof opt === 'string' ? opt : 'strict';
61
+ const user = typeof opt === 'function' ? opt : undefined;
62
+ const base = presetHook(preset);
63
+ if (!user)
64
+ return { preset, hook: base };
65
+ return { preset, hook: base ? (k, v) => user(k, base(k, v)) : user };
66
+ }
@@ -2,10 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  // Preload entry: `node --import @watchtowerobservability/node/register app.mjs` (ESM) or `node -r @watchtowerobservability/node/register app.js` (CommonJS).
4
4
  // Starts the SDK from WT_*/OTEL_* env before the app loads, so http, fetch, pg and ioredis are patched in time.
5
- // No-op without WT_INGEST_KEY.
5
+ // Without WT_INGEST_KEY it starts nothing and says so.
6
6
  const node_url_1 = require("node:url");
7
7
  const node_module_1 = require("node:module");
8
8
  const index_js_1 = require("./index.js");
9
+ const load_js_1 = require("./load.js");
9
10
  if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
10
11
  try {
11
12
  // ESM modules (node:http imported from an ES module) are only patched through OpenTelemetry's loader hook
@@ -23,10 +24,16 @@ if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
23
24
  return emit.call(process, w, ...a);
24
25
  });
25
26
  try {
26
- (0, node_module_1.register)('@opentelemetry/instrumentation/hook.mjs', (0, node_url_1.pathToFileURL)(`${process.cwd()}/`));
27
- }
28
- catch {
29
- // @opentelemetry/instrumentation not installed: CommonJS apps are still instrumented
27
+ // same search order as the peers: SDK location, cwd, entry script directory; the first that resolves wins
28
+ // (none: @opentelemetry/instrumentation not installed, CommonJS apps are still instrumented)
29
+ for (const p of (0, load_js_1.searchPaths)()) {
30
+ try {
31
+ // .ts/.tsx (tsx, ts-node): the hook would re-parse their TypeScript source as JS and fail once per file.
32
+ (0, node_module_1.register)('@opentelemetry/instrumentation/hook.mjs', (0, node_url_1.pathToFileURL)(p), { data: { exclude: [/\.[cm]?tsx?(?:[?#]|$)/] } });
33
+ break;
34
+ }
35
+ catch { /* try the next location */ }
36
+ }
30
37
  }
31
38
  finally {
32
39
  process.emitWarning = emit;
@@ -35,6 +42,12 @@ if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
35
42
  (0, index_js_1.init)({});
36
43
  }
37
44
  catch (e) {
38
- console.warn(`[watchtower] register: ${e.message}`);
45
+ (0, index_js_1.setOffReason)(`the preload could not start the SDK (${e.message})`);
46
+ console.warn(`[watchtower] telemetry is OFF: register failed: ${e.message}`);
39
47
  }
40
48
  }
49
+ else {
50
+ (0, index_js_1.setOffReason)('WT_INGEST_KEY is not set');
51
+ if (process.env.NODE_ENV !== 'test')
52
+ console.warn('[watchtower] telemetry is OFF: WT_INGEST_KEY is not set, so the register preload started nothing');
53
+ }
@@ -1,2 +1,2 @@
1
1
  /** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
2
- export declare const VERSION = "0.7.3";
2
+ export declare const VERSION = "0.7.5";
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
4
  /** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
5
- exports.VERSION = '0.7.3';
5
+ exports.VERSION = '0.7.5';
@@ -0,0 +1,7 @@
1
+ /** The real provider behind the global proxy, or undefined when none (or only the no-op one) is registered. */
2
+ export declare function foreignProvider(): any;
3
+ /**
4
+ * Add processors to `provider`: `addSpanProcessor` (sdk-trace v1) or the v2 `_activeSpanProcessor._spanProcessors` list.
5
+ * shortcut: v2+ has no public hook, so this reaches into a private field; replace when the SDK adds one.
6
+ */
7
+ export declare function attachProcessors(provider: any, procs: unknown[]): boolean;
@@ -0,0 +1,25 @@
1
+ // Coexistence with another OpenTelemetry setup (Sentry, a vendor agent): find the tracer provider already registered
2
+ // globally and add our span processors to it instead of replacing it.
3
+ import { trace } from '@opentelemetry/api';
4
+ /** The real provider behind the global proxy, or undefined when none (or only the no-op one) is registered. */
5
+ export function foreignProvider() {
6
+ const g = trace.getTracerProvider();
7
+ const d = typeof g?.getDelegate === 'function' ? g.getDelegate() : g;
8
+ return !d || d.constructor?.name === 'NoopTracerProvider' || d.constructor?.name === 'ProxyTracerProvider' ? undefined : d;
9
+ }
10
+ /**
11
+ * Add processors to `provider`: `addSpanProcessor` (sdk-trace v1) or the v2 `_activeSpanProcessor._spanProcessors` list.
12
+ * shortcut: v2+ has no public hook, so this reaches into a private field; replace when the SDK adds one.
13
+ */
14
+ export function attachProcessors(provider, procs) {
15
+ if (typeof provider.addSpanProcessor === 'function') {
16
+ for (const p of procs)
17
+ provider.addSpanProcessor(p);
18
+ return true;
19
+ }
20
+ const list = provider._activeSpanProcessor?._spanProcessors;
21
+ if (!Array.isArray(list))
22
+ return false;
23
+ list.push(...procs);
24
+ return true;
25
+ }
@@ -1,15 +1,6 @@
1
+ // Cron / scheduler check-ins: POST /v1/checkins/{slug} (key scope `ingest:checkins`; the edge accepts 6 a minute per monitor).
2
+ import { withMonitor } from './cron/monitor.js';
1
3
  /** Send `in_progress`, run `fn`, then send `ok` or `error` with its duration. Check-in failures never affect `fn`; its result or error is passed through. */
2
- export async function checkin(c, slug, fn) {
3
- const send = (status, ms) => c.fetch(`${c.endpoint}/v1/checkins/${encodeURIComponent(slug)}?status=${status}${ms === undefined ? '' : `&duration_ms=${Math.min(ms, 86_400_000)}`}`, { method: 'POST', headers: c.headers }).catch(() => undefined);
4
- await send('in_progress');
5
- const t = Date.now();
6
- try {
7
- const r = await fn();
8
- await send('ok', Date.now() - t);
9
- return r;
10
- }
11
- catch (e) {
12
- await send('error', Date.now() - t);
13
- throw e;
14
- }
4
+ export function checkin(c, slug, fn) {
5
+ return withMonitor(c, slug, fn, { wait: true });
15
6
  }
@@ -0,0 +1,47 @@
1
+ import type { CheckinTarget } from '../checkin.js';
2
+ export type CheckInStatus = 'in_progress' | 'ok' | 'error';
3
+ /** Sent in the check-in body so the server can create or update the monitor on first contact (Sentry's `monitor_config` shape, minutes). */
4
+ export interface MonitorConfig {
5
+ schedule: {
6
+ type: 'crontab';
7
+ value: string;
8
+ };
9
+ timezone?: string;
10
+ checkin_margin_m?: number;
11
+ max_runtime_m?: number;
12
+ failure_threshold?: number;
13
+ }
14
+ export interface MonitorOptions {
15
+ /** Crontab, 5 fields (or 6 with leading seconds, which are dropped when they are `0`). */
16
+ schedule?: string;
17
+ timezone?: string;
18
+ /** Minutes a check-in may be late before it counts as missed. */
19
+ checkinMargin?: number;
20
+ /** Minutes a run may stay `in_progress` before it counts as failed. */
21
+ maxRuntime?: number;
22
+ /** Consecutive failures before an issue opens. */
23
+ failureThreshold?: number;
24
+ /** Await the check-in requests (default false: fire and forget, capped at 5 s). Use it in short-lived processes. */
25
+ wait?: boolean;
26
+ }
27
+ export interface CheckInOptions {
28
+ wait?: boolean;
29
+ durationMs?: number;
30
+ monitorConfig?: MonitorConfig;
31
+ /** Default 5000. */
32
+ timeoutMs?: number;
33
+ }
34
+ /** The client `init()` made (the one per-process state `index.ts` keeps), without importing it. */
35
+ export declare function currentTarget(): CheckinTarget | undefined;
36
+ /** Check-ins are served by the edge host, not the OTLP gateway: `ingest.x` becomes `edge.x`. `WT_CHECKIN_URL` overrides. */
37
+ export declare function checkinBase(endpoint: string): string;
38
+ export declare function normalizeCron(expr: string): string;
39
+ export declare function toConfig(o: MonitorOptions): MonitorConfig | undefined;
40
+ /** Send one check-in. Never throws or rejects; without `wait` it returns at once and the request is capped at 5 s. */
41
+ export declare function checkIn(c: CheckinTarget, slug: string, status: CheckInStatus, o?: CheckInOptions): Promise<void>;
42
+ /** Run `fn` as a monitored job: `in_progress`, then `ok` or `error` with the duration. Returns fn's result or rethrows its error; check-in failures never reach it. */
43
+ export declare function withMonitor<T>(c: CheckinTarget, slug: string, fn: () => T | Promise<T>, o?: MonitorOptions): Promise<T>;
44
+ /** Lowercase kebab slug of a job or method name (`MyService.nightlyReport` -> `my-service-nightly-report`). Empty for a uuid. */
45
+ export declare function slugify(name: string): string;
46
+ /** `withMonitor` against the client `init()` made; just runs `fn` when there is none. */
47
+ export declare function monitorJob<T>(slug: string, fn: () => T | Promise<T>, o?: MonitorOptions): Promise<T>;
@@ -0,0 +1,85 @@
1
+ // Cron monitor check-ins: POST {edge}/v1/checkins/{slug} (key scope `ingest:checkins`; the edge accepts 6 a minute per monitor).
2
+ import { context } from '@opentelemetry/api';
3
+ /** The client `init()` made (the one per-process state `index.ts` keeps), without importing it. */
4
+ export function currentTarget() {
5
+ const s = globalThis[Symbol.for('watchtower.node.state')];
6
+ return s?.current;
7
+ }
8
+ /** Check-ins are served by the edge host, not the OTLP gateway: `ingest.x` becomes `edge.x`. `WT_CHECKIN_URL` overrides. */
9
+ export function checkinBase(endpoint) {
10
+ const env = process.env.WT_CHECKIN_URL;
11
+ if (env)
12
+ return env.replace(/\/+$/, '');
13
+ return endpoint.replace(/^(https?:\/\/)ingest\./i, '$1edge.');
14
+ }
15
+ // `0 */5 * * * *` -> `*/5 * * * *`; a 6-field expression with another seconds value stays as it is.
16
+ export function normalizeCron(expr) {
17
+ const f = expr.trim().split(/\s+/);
18
+ return f.length === 6 && /^0+$/.test(f[0]) ? f.slice(1).join(' ') : f.join(' ');
19
+ }
20
+ export function toConfig(o) {
21
+ if (typeof o.schedule !== 'string' || !o.schedule.trim())
22
+ return undefined;
23
+ const c = { schedule: { type: 'crontab', value: normalizeCron(o.schedule) } };
24
+ if (o.timezone)
25
+ c.timezone = o.timezone;
26
+ if (o.checkinMargin !== undefined)
27
+ c.checkin_margin_m = o.checkinMargin;
28
+ if (o.maxRuntime !== undefined)
29
+ c.max_runtime_m = o.maxRuntime;
30
+ if (o.failureThreshold !== undefined)
31
+ c.failure_threshold = o.failureThreshold;
32
+ return c;
33
+ }
34
+ // The OTel SDK's own key (`@opentelemetry/core` suppressTracing), so our HTTP call makes no span.
35
+ const SUPPRESS = Symbol.for('OpenTelemetry SDK Context Key SUPPRESS_TRACING');
36
+ /** Send one check-in. Never throws or rejects; without `wait` it returns at once and the request is capped at 5 s. */
37
+ export function checkIn(c, slug, status, o = {}) {
38
+ const ms = o.durationMs === undefined ? undefined : Math.min(Math.max(Math.round(o.durationMs), 0), 86_400_000);
39
+ const url = `${checkinBase(c.endpoint)}/v1/checkins/${encodeURIComponent(slug)}?status=${status}${ms === undefined ? '' : `&duration_ms=${ms}`}`;
40
+ const body = { status };
41
+ if (ms !== undefined)
42
+ body.duration_ms = ms;
43
+ if (o.monitorConfig)
44
+ body.monitor_config = o.monitorConfig;
45
+ const ac = new AbortController();
46
+ const timer = setTimeout(() => ac.abort(), o.timeoutMs ?? 5000);
47
+ timer.unref?.();
48
+ let p;
49
+ try {
50
+ p = context.with(context.active().setValue(SUPPRESS, true), () => c.fetch(url, { method: 'POST', headers: { ...c.headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: ac.signal }))
51
+ .then(() => undefined, () => undefined);
52
+ }
53
+ catch {
54
+ p = Promise.resolve();
55
+ }
56
+ p = p.finally(() => clearTimeout(timer));
57
+ return o.wait ? p : Promise.resolve();
58
+ }
59
+ /** Run `fn` as a monitored job: `in_progress`, then `ok` or `error` with the duration. Returns fn's result or rethrows its error; check-in failures never reach it. */
60
+ export async function withMonitor(c, slug, fn, o = {}) {
61
+ const monitorConfig = toConfig(o);
62
+ const send = (status, durationMs) => checkIn(c, slug, status, { wait: o.wait, durationMs, monitorConfig });
63
+ await send('in_progress');
64
+ const t = Date.now();
65
+ try {
66
+ const r = await fn();
67
+ await send('ok', Date.now() - t);
68
+ return r;
69
+ }
70
+ catch (e) {
71
+ await send('error', Date.now() - t);
72
+ throw e;
73
+ }
74
+ }
75
+ /** Lowercase kebab slug of a job or method name (`MyService.nightlyReport` -> `my-service-nightly-report`). Empty for a uuid. */
76
+ export function slugify(name) {
77
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(name))
78
+ return '';
79
+ return name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64);
80
+ }
81
+ /** `withMonitor` against the client `init()` made; just runs `fn` when there is none. */
82
+ export function monitorJob(slug, fn, o = {}) {
83
+ const c = currentTarget();
84
+ return c ? withMonitor(c, slug, fn, o) : Promise.resolve().then(fn);
85
+ }
@@ -0,0 +1,36 @@
1
+ type Fn = (...a: any[]) => unknown;
2
+ declare const DONE: unique symbol;
3
+ interface CronJobLike {
4
+ cronTime?: {
5
+ source?: unknown;
6
+ zone?: unknown;
7
+ timeZone?: unknown;
8
+ };
9
+ _callbacks?: Fn[];
10
+ [DONE]?: boolean;
11
+ }
12
+ interface SchedulerRegistryLike {
13
+ addCronJob: (name: string, job: CronJobLike) => unknown;
14
+ getCronJobs: () => Map<string, CronJobLike>;
15
+ [DONE]?: boolean;
16
+ }
17
+ /**
18
+ * `instrumentNestSchedule(app.get(SchedulerRegistry))` after `app.init()` (or in `onApplicationBootstrap`): every `@Cron`
19
+ * job, already registered or added later, runs as a monitor named after its `@Cron(expr, { name })` (kebab-cased) with its
20
+ * cron expression and timezone as the schedule. Give jobs a name; unnamed ones (uuid) are skipped. Returns how many were wrapped now.
21
+ * shortcut: reads the `cron` package's private `_callbacks` (cron 3 and 4); a version that moves it wraps nothing.
22
+ */
23
+ export declare function instrumentNestSchedule(registry: SchedulerRegistryLike): number;
24
+ interface NodeCronLike {
25
+ schedule: (expr: string, fn: Fn, opts?: {
26
+ name?: string;
27
+ timezone?: string;
28
+ }) => unknown;
29
+ }
30
+ /**
31
+ * `import cron from 'node-cron'; instrumentNodeCron(cron)`: tasks scheduled afterwards with `cron.schedule(expr, fn, { name })`
32
+ * run as monitors (a function's own name is not used: bundlers rename them). Pass the default export (a CommonJS object), not an ESM namespace.
33
+ * Returns false when it cannot patch it.
34
+ */
35
+ export declare function instrumentNodeCron(cron: NodeCronLike): boolean;
36
+ export {};
@@ -0,0 +1,61 @@
1
+ // Cron monitors for `@nestjs/schedule` (`@Cron`) and `node-cron`: each job becomes a monitor via `withMonitor`.
2
+ import { monitorJob, slugify } from './monitor.js';
3
+ const DONE = Symbol.for('watchtower.cron.wrapped');
4
+ /** Wrap one `cron` CronJob's callbacks. False when this `cron` version keeps them elsewhere than `_callbacks`. */
5
+ function wrapJob(name, job) {
6
+ const slug = slugify(name); // a Nest job without `{ name }` gets a uuid: nothing stable to monitor
7
+ if (!slug || job[DONE] || !Array.isArray(job._callbacks))
8
+ return false;
9
+ job[DONE] = true;
10
+ const src = job.cronTime?.source;
11
+ const tz = job.cronTime?.zone ?? job.cronTime?.timeZone;
12
+ const o = { schedule: typeof src === 'string' ? src : undefined, timezone: typeof tz === 'string' ? tz : undefined };
13
+ job._callbacks = job._callbacks.map((cb) => function (...a) { return monitorJob(slug, () => cb.apply(this, a), o); });
14
+ return true;
15
+ }
16
+ /**
17
+ * `instrumentNestSchedule(app.get(SchedulerRegistry))` after `app.init()` (or in `onApplicationBootstrap`): every `@Cron`
18
+ * job, already registered or added later, runs as a monitor named after its `@Cron(expr, { name })` (kebab-cased) with its
19
+ * cron expression and timezone as the schedule. Give jobs a name; unnamed ones (uuid) are skipped. Returns how many were wrapped now.
20
+ * shortcut: reads the `cron` package's private `_callbacks` (cron 3 and 4); a version that moves it wraps nothing.
21
+ */
22
+ export function instrumentNestSchedule(registry) {
23
+ let n = 0;
24
+ for (const [name, job] of registry.getCronJobs())
25
+ if (wrapJob(name, job))
26
+ n++;
27
+ if (!registry[DONE]) {
28
+ registry[DONE] = true;
29
+ const add = registry.addCronJob;
30
+ registry.addCronJob = function (name, job) {
31
+ wrapJob(name, job);
32
+ return add.call(this, name, job);
33
+ };
34
+ }
35
+ return n;
36
+ }
37
+ /**
38
+ * `import cron from 'node-cron'; instrumentNodeCron(cron)`: tasks scheduled afterwards with `cron.schedule(expr, fn, { name })`
39
+ * run as monitors (a function's own name is not used: bundlers rename them). Pass the default export (a CommonJS object), not an ESM namespace.
40
+ * Returns false when it cannot patch it.
41
+ */
42
+ export function instrumentNodeCron(cron) {
43
+ const orig = cron.schedule;
44
+ if (typeof orig !== 'function' || orig[DONE])
45
+ return false;
46
+ const wrapped = function (expr, fn, opts, ...rest) {
47
+ const slug = typeof fn === 'function' ? slugify(opts?.name || '') : '';
48
+ if (!slug)
49
+ return orig.call(this, expr, fn, opts, ...rest);
50
+ const o = { schedule: expr, timezone: opts?.timezone };
51
+ return orig.call(this, expr, function (...a) { return monitorJob(slug, () => fn.apply(this, a), o); }, opts, ...rest);
52
+ };
53
+ wrapped[DONE] = true;
54
+ try {
55
+ cron.schedule = wrapped;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ return cron.schedule === wrapped;
61
+ }
package/dist/esm/env.d.ts CHANGED
@@ -10,3 +10,13 @@ export interface OtelEnv {
10
10
  resource: Record<string, string>;
11
11
  }
12
12
  export declare function otelEnv(env?: NodeJS.ProcessEnv): OtelEnv;
13
+ /**
14
+ * The commit `HEAD` points at, found by walking up from `from` to a `.git` directory (a `.git` file of a worktree or submodule is
15
+ * followed through its `gitdir:` line). Reads `HEAD`, then the ref file or `packed-refs`; no child process. undefined when not found.
16
+ */
17
+ export declare function gitHeadSha(from: string): string | undefined;
18
+ /**
19
+ * service.version: explicit option, WT_RELEASE, OTEL_RESOURCE_ATTRIBUTES, the first CI commit-sha variable, the build stamp
20
+ * (`WT_BUILD_STAMP`, `BUILD_STAMP`), then the `.git` HEAD found upward from `gitFrom` (skipped when not given). Empty and `unknown` count as absent.
21
+ */
22
+ export declare function resolveRelease(opt: string | undefined, env: NodeJS.ProcessEnv, otelResource: Record<string, string>, gitFrom?: string): string | undefined;