@watchtowerobservability/node 0.0.0-stage → 0.3.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 (181) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +304 -2
  3. package/dist/cjs/appsec.d.ts +95 -0
  4. package/dist/cjs/appsec.js +206 -0
  5. package/dist/cjs/buffer.d.ts +49 -0
  6. package/dist/cjs/buffer.js +134 -0
  7. package/dist/cjs/errors.d.ts +17 -0
  8. package/dist/cjs/errors.js +55 -0
  9. package/dist/cjs/index.d.ts +123 -0
  10. package/dist/cjs/index.js +315 -0
  11. package/dist/cjs/integrations/amqp.d.ts +13 -0
  12. package/dist/cjs/integrations/amqp.js +96 -0
  13. package/dist/cjs/integrations/azure-functions.d.ts +18 -0
  14. package/dist/cjs/integrations/azure-functions.js +97 -0
  15. package/dist/cjs/integrations/bullmq.d.ts +19 -0
  16. package/dist/cjs/integrations/bullmq.js +83 -0
  17. package/dist/cjs/integrations/cache.d.ts +13 -0
  18. package/dist/cjs/integrations/cache.js +51 -0
  19. package/dist/cjs/integrations/db.d.ts +62 -0
  20. package/dist/cjs/integrations/db.js +288 -0
  21. package/dist/cjs/integrations/duckdb.d.ts +22 -0
  22. package/dist/cjs/integrations/duckdb.js +66 -0
  23. package/dist/cjs/integrations/express.d.ts +25 -0
  24. package/dist/cjs/integrations/express.js +58 -0
  25. package/dist/cjs/integrations/fastify.d.ts +6 -0
  26. package/dist/cjs/integrations/fastify.js +44 -0
  27. package/dist/cjs/integrations/genai-agents.d.ts +36 -0
  28. package/dist/cjs/integrations/genai-agents.js +124 -0
  29. package/dist/cjs/integrations/genai-stream.d.ts +19 -0
  30. package/dist/cjs/integrations/genai-stream.js +135 -0
  31. package/dist/cjs/integrations/genai.d.ts +18 -0
  32. package/dist/cjs/integrations/genai.js +150 -0
  33. package/dist/cjs/integrations/graphile-worker.d.ts +22 -0
  34. package/dist/cjs/integrations/graphile-worker.js +50 -0
  35. package/dist/cjs/integrations/koa.d.ts +19 -0
  36. package/dist/cjs/integrations/koa.js +34 -0
  37. package/dist/cjs/integrations/lambda.d.ts +11 -0
  38. package/dist/cjs/integrations/lambda.js +68 -0
  39. package/dist/cjs/integrations/level.d.ts +18 -0
  40. package/dist/cjs/integrations/level.js +71 -0
  41. package/dist/cjs/integrations/lmdb.d.ts +26 -0
  42. package/dist/cjs/integrations/lmdb.js +78 -0
  43. package/dist/cjs/integrations/logs.d.ts +10 -0
  44. package/dist/cjs/integrations/logs.js +77 -0
  45. package/dist/cjs/integrations/messaging.d.ts +17 -0
  46. package/dist/cjs/integrations/messaging.js +73 -0
  47. package/dist/cjs/integrations/mqtt.d.ts +7 -0
  48. package/dist/cjs/integrations/mqtt.js +41 -0
  49. package/dist/cjs/integrations/nats.d.ts +17 -0
  50. package/dist/cjs/integrations/nats.js +73 -0
  51. package/dist/cjs/integrations/nestjs.d.ts +16 -0
  52. package/dist/cjs/integrations/nestjs.js +30 -0
  53. package/dist/cjs/integrations/next.d.ts +11 -0
  54. package/dist/cjs/integrations/next.js +59 -0
  55. package/dist/cjs/integrations/orm.d.ts +47 -0
  56. package/dist/cjs/integrations/orm.js +93 -0
  57. package/dist/cjs/integrations/pg-boss.d.ts +8 -0
  58. package/dist/cjs/integrations/pg-boss.js +63 -0
  59. package/dist/cjs/integrations/pools.d.ts +41 -0
  60. package/dist/cjs/integrations/pools.js +94 -0
  61. package/dist/cjs/integrations/postgres.d.ts +12 -0
  62. package/dist/cjs/integrations/postgres.js +92 -0
  63. package/dist/cjs/integrations/prisma.d.ts +3 -0
  64. package/dist/cjs/integrations/prisma.js +33 -0
  65. package/dist/cjs/integrations/sqlite.d.ts +36 -0
  66. package/dist/cjs/integrations/sqlite.js +125 -0
  67. package/dist/cjs/integrations/util.d.ts +9 -0
  68. package/dist/cjs/integrations/util.js +37 -0
  69. package/dist/cjs/jest.d.ts +21 -0
  70. package/dist/cjs/jest.js +45 -0
  71. package/dist/cjs/load.d.ts +1 -0
  72. package/dist/cjs/load.js +11 -0
  73. package/dist/cjs/metrics.d.ts +10 -0
  74. package/dist/cjs/metrics.js +81 -0
  75. package/dist/cjs/package.json +1 -0
  76. package/dist/cjs/payload.d.ts +42 -0
  77. package/dist/cjs/payload.js +145 -0
  78. package/dist/cjs/pprof.d.ts +6 -0
  79. package/dist/cjs/pprof.js +88 -0
  80. package/dist/cjs/probes.d.ts +97 -0
  81. package/dist/cjs/probes.js +422 -0
  82. package/dist/cjs/profiling.d.ts +84 -0
  83. package/dist/cjs/profiling.js +263 -0
  84. package/dist/cjs/reporter-core.d.ts +32 -0
  85. package/dist/cjs/reporter-core.js +102 -0
  86. package/dist/cjs/sql.d.ts +19 -0
  87. package/dist/cjs/sql.js +332 -0
  88. package/dist/cjs/test-plan.d.ts +102 -0
  89. package/dist/cjs/test-plan.js +352 -0
  90. package/dist/cjs/vitest.d.ts +27 -0
  91. package/dist/cjs/vitest.js +52 -0
  92. package/dist/esm/appsec.d.ts +95 -0
  93. package/dist/esm/appsec.js +193 -0
  94. package/dist/esm/buffer.d.ts +49 -0
  95. package/dist/esm/buffer.js +92 -0
  96. package/dist/esm/errors.d.ts +17 -0
  97. package/dist/esm/errors.js +50 -0
  98. package/dist/esm/index.d.ts +123 -0
  99. package/dist/esm/index.js +264 -0
  100. package/dist/esm/integrations/amqp.d.ts +13 -0
  101. package/dist/esm/integrations/amqp.js +92 -0
  102. package/dist/esm/integrations/azure-functions.d.ts +18 -0
  103. package/dist/esm/integrations/azure-functions.js +60 -0
  104. package/dist/esm/integrations/bullmq.d.ts +19 -0
  105. package/dist/esm/integrations/bullmq.js +79 -0
  106. package/dist/esm/integrations/cache.d.ts +13 -0
  107. package/dist/esm/integrations/cache.js +46 -0
  108. package/dist/esm/integrations/db.d.ts +62 -0
  109. package/dist/esm/integrations/db.js +239 -0
  110. package/dist/esm/integrations/duckdb.d.ts +22 -0
  111. package/dist/esm/integrations/duckdb.js +29 -0
  112. package/dist/esm/integrations/express.d.ts +25 -0
  113. package/dist/esm/integrations/express.js +54 -0
  114. package/dist/esm/integrations/fastify.d.ts +6 -0
  115. package/dist/esm/integrations/fastify.js +41 -0
  116. package/dist/esm/integrations/genai-agents.d.ts +36 -0
  117. package/dist/esm/integrations/genai-agents.js +118 -0
  118. package/dist/esm/integrations/genai-stream.d.ts +19 -0
  119. package/dist/esm/integrations/genai-stream.js +130 -0
  120. package/dist/esm/integrations/genai.d.ts +18 -0
  121. package/dist/esm/integrations/genai.js +138 -0
  122. package/dist/esm/integrations/graphile-worker.d.ts +22 -0
  123. package/dist/esm/integrations/graphile-worker.js +46 -0
  124. package/dist/esm/integrations/koa.d.ts +19 -0
  125. package/dist/esm/integrations/koa.js +31 -0
  126. package/dist/esm/integrations/lambda.d.ts +11 -0
  127. package/dist/esm/integrations/lambda.js +32 -0
  128. package/dist/esm/integrations/level.d.ts +18 -0
  129. package/dist/esm/integrations/level.js +35 -0
  130. package/dist/esm/integrations/lmdb.d.ts +26 -0
  131. package/dist/esm/integrations/lmdb.js +42 -0
  132. package/dist/esm/integrations/logs.d.ts +10 -0
  133. package/dist/esm/integrations/logs.js +40 -0
  134. package/dist/esm/integrations/messaging.d.ts +17 -0
  135. package/dist/esm/integrations/messaging.js +64 -0
  136. package/dist/esm/integrations/mqtt.d.ts +7 -0
  137. package/dist/esm/integrations/mqtt.js +38 -0
  138. package/dist/esm/integrations/nats.d.ts +17 -0
  139. package/dist/esm/integrations/nats.js +70 -0
  140. package/dist/esm/integrations/nestjs.d.ts +16 -0
  141. package/dist/esm/integrations/nestjs.js +26 -0
  142. package/dist/esm/integrations/next.d.ts +11 -0
  143. package/dist/esm/integrations/next.js +22 -0
  144. package/dist/esm/integrations/orm.d.ts +47 -0
  145. package/dist/esm/integrations/orm.js +86 -0
  146. package/dist/esm/integrations/pg-boss.d.ts +8 -0
  147. package/dist/esm/integrations/pg-boss.js +60 -0
  148. package/dist/esm/integrations/pools.d.ts +41 -0
  149. package/dist/esm/integrations/pools.js +89 -0
  150. package/dist/esm/integrations/postgres.d.ts +12 -0
  151. package/dist/esm/integrations/postgres.js +55 -0
  152. package/dist/esm/integrations/prisma.d.ts +3 -0
  153. package/dist/esm/integrations/prisma.js +30 -0
  154. package/dist/esm/integrations/sqlite.d.ts +36 -0
  155. package/dist/esm/integrations/sqlite.js +84 -0
  156. package/dist/esm/integrations/util.d.ts +9 -0
  157. package/dist/esm/integrations/util.js +32 -0
  158. package/dist/esm/jest.d.ts +21 -0
  159. package/dist/esm/jest.js +41 -0
  160. package/dist/esm/load.d.ts +1 -0
  161. package/dist/esm/load.js +5 -0
  162. package/dist/esm/metrics.d.ts +10 -0
  163. package/dist/esm/metrics.js +44 -0
  164. package/dist/esm/package.json +1 -0
  165. package/dist/esm/payload.d.ts +42 -0
  166. package/dist/esm/payload.js +131 -0
  167. package/dist/esm/pprof.d.ts +6 -0
  168. package/dist/esm/pprof.js +85 -0
  169. package/dist/esm/probes.d.ts +97 -0
  170. package/dist/esm/probes.js +412 -0
  171. package/dist/esm/profiling.d.ts +84 -0
  172. package/dist/esm/profiling.js +251 -0
  173. package/dist/esm/reporter-core.d.ts +32 -0
  174. package/dist/esm/reporter-core.js +63 -0
  175. package/dist/esm/sql.d.ts +19 -0
  176. package/dist/esm/sql.js +324 -0
  177. package/dist/esm/test-plan.d.ts +102 -0
  178. package/dist/esm/test-plan.js +336 -0
  179. package/dist/esm/vitest.d.ts +27 -0
  180. package/dist/esm/vitest.js +48 -0
  181. package/package.json +379 -4
@@ -0,0 +1,264 @@
1
+ // Thin Watchtower layer over the OpenTelemetry Node SDK: key header, endpoint default,
2
+ // offline buffer, wt.*-safe resource attributes, redaction hook, getPrompt/score/evaluate/observe.
3
+ import { inspect } from 'node:util';
4
+ import { metrics, trace } from '@opentelemetry/api';
5
+ import { Resource } from '@opentelemetry/resources';
6
+ import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
7
+ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
8
+ import { LoggerProvider, SimpleLogRecordProcessor, BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';
9
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
10
+ import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
11
+ import { SpoolExporter, spoolLogs } from './buffer.js';
12
+ import { startMetrics, switchOn } from './metrics.js';
13
+ import * as nodePath from 'node:path';
14
+ import { captureException, installProcessHandlers, dropReserved } from './errors.js';
15
+ import { loadCaptureRules } from './payload.js';
16
+ import { startProfiling } from './profiling.js';
17
+ export { captureException, metrics, trace };
18
+ export { setCaptureRules, capturePayload } from './payload.js';
19
+ export const DEFAULT_ENDPOINT = 'http://localhost:4318';
20
+ const SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 };
21
+ /** Drop caller-supplied wt.* keys: tenant identity comes only from the key. */
22
+ export function safeResource(attrs) {
23
+ return dropReserved(attrs);
24
+ }
25
+ const errMessage = (e) => String(e?.message || e);
26
+ export class Client {
27
+ endpoint;
28
+ apiUrl;
29
+ project;
30
+ headers;
31
+ fetch;
32
+ redact;
33
+ provider;
34
+ tracer;
35
+ loggerProvider;
36
+ logger;
37
+ /** Set when metrics are on; `init` makes it the global meter provider (`metrics.getMeter`). */
38
+ meterProvider;
39
+ stopRuntime = () => { };
40
+ uninstall;
41
+ /** Set when WT_PROFILING=1 started the continuous profiler. */
42
+ profiler;
43
+ constructor(opts) {
44
+ const o = opts || {};
45
+ const env = process.env;
46
+ const apiKey = o.apiKey || env.WT_INGEST_KEY;
47
+ if (!apiKey)
48
+ throw new Error('apiKey is required (or set WT_INGEST_KEY)');
49
+ this.endpoint = (o.endpoint || env.WT_OTLP_ENDPOINT || DEFAULT_ENDPOINT).replace(/\/+$/, '');
50
+ this.apiUrl = (o.apiUrl || env.WT_API_URL || this.endpoint).replace(/\/+$/, '');
51
+ this.project = o.project || env.WT_PROJECT_ID;
52
+ this.headers = { Authorization: `Bearer ${apiKey}` };
53
+ this.fetch = o.fetch || globalThis.fetch;
54
+ const environment = o.environment || env.WT_ENVIRONMENT;
55
+ const release = o.release || env.WT_RELEASE;
56
+ const resource = new Resource({
57
+ 'service.name': o.serviceName || env.WT_SERVICE || 'app',
58
+ ...(environment ? { 'deployment.environment.name': environment } : {}),
59
+ ...(release ? { 'service.version': release } : {}),
60
+ ...safeResource(o.resource),
61
+ });
62
+ this.redact = o.redact;
63
+ this.provider = new NodeTracerProvider({ resource });
64
+ if (o.redact)
65
+ this.provider.addSpanProcessor(redactor(o.redact));
66
+ let exporter = o.exporter;
67
+ if (!exporter) {
68
+ const url = `${this.endpoint}/v1/traces`;
69
+ exporter = new OTLPTraceExporter({ url, headers: this.headers });
70
+ // spans and log records spool to their own subdirectories
71
+ if (o.bufferDir)
72
+ exporter = new SpoolExporter(exporter, nodePath.join(o.bufferDir, 'traces'), url, this.headers, this.fetch);
73
+ }
74
+ this.provider.addSpanProcessor(new BatchSpanProcessor(exporter));
75
+ this.tracer = this.provider.getTracer('watchtower');
76
+ this.loggerProvider = new LoggerProvider({ resource });
77
+ const logsOn = switchOn('WATCHTOWER_LOGS', 'OTEL_LOGS_EXPORTER', o.logs);
78
+ let logExporter = logsOn ? o.logExporter : undefined;
79
+ if (logsOn && !logExporter && !o.exporter) {
80
+ const url = `${this.endpoint}/v1/logs`;
81
+ logExporter = new OTLPLogExporter({ url, headers: this.headers });
82
+ if (o.bufferDir)
83
+ logExporter = spoolLogs(logExporter, nodePath.join(o.bufferDir, 'logs'), url, this.headers, this.fetch);
84
+ }
85
+ if (logExporter) {
86
+ this.loggerProvider.addLogRecordProcessor(o.logExporter ? new SimpleLogRecordProcessor(logExporter) : new BatchLogRecordProcessor(logExporter));
87
+ }
88
+ this.logger = this.loggerProvider.getLogger('watchtower');
89
+ // with a test span exporter only an explicit metric exporter is used, as for logs
90
+ if (switchOn('WATCHTOWER_METRICS', 'OTEL_METRICS_EXPORTER', o.metrics) && (o.metricExporter || !o.exporter)) {
91
+ const m = startMetrics(this.endpoint, this.headers, resource, o.bufferDir, this.fetch, o.metricExporter);
92
+ this.meterProvider = m.provider;
93
+ this.stopRuntime = m.stop;
94
+ }
95
+ if (o.captureRules ?? env.WT_CAPTURE_RULES === '1') {
96
+ void loadCaptureRules({ apiUrl: this.apiUrl, key: apiKey, service: String(resource.attributes['service.name']), fetch: this.fetch });
97
+ }
98
+ }
99
+ /** Emit an OTLP log record; trace and span ids come from the active context. */
100
+ log(level, body, attributes) {
101
+ let attrs = dropReserved(attributes);
102
+ const redact = this.redact;
103
+ if (redact)
104
+ attrs = Object.fromEntries(Object.entries(attrs).map(([k, v]) => [k, redact(k, v)]));
105
+ this.logger.emit({
106
+ severityNumber: SEVERITY[level] || SEVERITY.info,
107
+ severityText: String(level).toUpperCase(),
108
+ body,
109
+ attributes: attrs,
110
+ });
111
+ }
112
+ forceFlush() {
113
+ return Promise.all([this.provider.forceFlush(), this.loggerProvider.forceFlush(), this.meterProvider?.forceFlush()]);
114
+ }
115
+ // keep the key out of console.log / JSON.stringify
116
+ toJSON() {
117
+ return { endpoint: this.endpoint, project: this.project, headers: { Authorization: 'Bearer ****' } };
118
+ }
119
+ [inspect.custom]() {
120
+ return `Client ${JSON.stringify(this)}`;
121
+ }
122
+ async _call(method, path, body) {
123
+ const url = `${this.apiUrl}/v1/projects/${this.project}/llm/${path}`;
124
+ const res = await this.fetch(url, {
125
+ method,
126
+ headers: { ...this.headers, 'Content-Type': 'application/json' },
127
+ body: body === undefined ? undefined : JSON.stringify(body),
128
+ });
129
+ if (!res.ok)
130
+ throw new Error(`watchtower ${method} ${path}: HTTP ${res.status}`);
131
+ return res.json();
132
+ }
133
+ getPrompt(promptId) {
134
+ return this._call('GET', `prompts/${promptId}`);
135
+ }
136
+ score(traceId, value, o) {
137
+ const x = o || {};
138
+ const body = { trace_id: traceId, value, name: x.name || 'user_feedback', source: 'sdk' };
139
+ if (x.spanId)
140
+ body.span_id = x.spanId;
141
+ if (x.comment)
142
+ body.comment = x.comment;
143
+ return this._call('POST', 'scores', body);
144
+ }
145
+ /** Run task per case under a span; record each scorer result as a score when a project is set. */
146
+ async evaluate(dataset, task, scorers, o) {
147
+ const x = { name: 'evaluate', errorTolerance: true, ...o };
148
+ const rows = [];
149
+ // resume: rows of an earlier run; cases that finished without errors are kept, not re-run
150
+ const done = new Map((x.resume || []).filter((r) => !Object.keys(r.errors || {}).length).map((r) => [r.case, r]));
151
+ for (const [i, c] of dataset.entries()) {
152
+ const kept = done.get(i);
153
+ if (kept) {
154
+ rows.push(kept);
155
+ continue;
156
+ }
157
+ await this.tracer.startActiveSpan(`${x.name}.case`, async (span) => {
158
+ const traceId = span.spanContext().traceId;
159
+ const row = { case: i, traceId, scores: {}, errors: {} };
160
+ rows.push(row);
161
+ try {
162
+ const input = c !== null && c !== undefined ? c.input : undefined;
163
+ const out = await task(input !== undefined ? input : c);
164
+ for (const [name, fn] of Object.entries(scorers)) {
165
+ try {
166
+ row.scores[name] = await fn(c, out);
167
+ if (this.project)
168
+ await this.score(traceId, row.scores[name], { name });
169
+ }
170
+ catch (e) {
171
+ if (!x.errorTolerance)
172
+ throw e;
173
+ row.errors[name] = errMessage(e);
174
+ }
175
+ }
176
+ }
177
+ catch (e) {
178
+ if (!x.errorTolerance)
179
+ throw e;
180
+ row.errors.task = errMessage(e);
181
+ }
182
+ finally {
183
+ span.end();
184
+ }
185
+ });
186
+ }
187
+ return rows;
188
+ }
189
+ /** Re-run only the cases that errored or are missing in `previous`. */
190
+ evaluateResume(dataset, task, scorers, previous, o) {
191
+ return this.evaluate(dataset, task, scorers, { ...o, resume: previous });
192
+ }
193
+ /** Wrap fn in a span. */
194
+ observe(name, fn) {
195
+ return (...args) => this.tracer.startActiveSpan(name, (span) => {
196
+ const end = () => span.end();
197
+ try {
198
+ const r = fn(...args);
199
+ if (r && typeof r.then === 'function')
200
+ return r.finally(end);
201
+ end();
202
+ return r;
203
+ }
204
+ catch (e) {
205
+ end();
206
+ throw e;
207
+ }
208
+ });
209
+ }
210
+ shutdown() {
211
+ this.stopRuntime();
212
+ return Promise.all([this.profiler?.then((p) => p?.stop()), this.provider.shutdown(), this.loggerProvider.shutdown(), this.meterProvider?.shutdown()]).then(() => undefined);
213
+ }
214
+ }
215
+ function redactor(hook) {
216
+ return {
217
+ onStart() { },
218
+ onEnd(span) {
219
+ for (const k of Object.keys(span.attributes))
220
+ span.attributes[k] = hook(k, span.attributes[k]);
221
+ },
222
+ shutdown: () => Promise.resolve(),
223
+ forceFlush: () => Promise.resolve(),
224
+ };
225
+ }
226
+ let current;
227
+ export function init(opts) {
228
+ if (current && current.uninstall)
229
+ current.uninstall();
230
+ void current?.profiler?.then((p) => p?.stop());
231
+ const c = new Client(opts);
232
+ current = c;
233
+ c.provider.register(); // global tracer + async context so trace.getActiveSpan() works
234
+ if (c.meterProvider) {
235
+ metrics.disable(); // a re-init replaces the previous client's provider
236
+ metrics.setGlobalMeterProvider(c.meterProvider);
237
+ }
238
+ if (process.env.WT_PROFILING === '1') {
239
+ const attrs = c.provider.resource.attributes;
240
+ c.profiler = startProfiling({
241
+ apiKey: c.headers.Authorization.slice('Bearer '.length),
242
+ endpoint: c.endpoint,
243
+ service: String(attrs['service.name']),
244
+ tags: { version: attrs['service.version'] },
245
+ }).catch(() => undefined); // best effort: never break init
246
+ }
247
+ if ((opts || {}).captureProcessErrors !== false) {
248
+ c.uninstall = installProcessHandlers(() => c.forceFlush());
249
+ }
250
+ return c;
251
+ }
252
+ function need() {
253
+ if (!current)
254
+ throw new Error('watchtower.init() has not been called');
255
+ return current;
256
+ }
257
+ export const flush = () => (current ? current.forceFlush() : Promise.resolve());
258
+ export const log = (l, b, a) => need().log(l, b, a);
259
+ export const getPrompt = (id) => need().getPrompt(id);
260
+ export const score = (t, v, o) => need().score(t, v, o);
261
+ export const evaluate = (d, t, s, o) => need().evaluate(d, t, s, o);
262
+ export const evaluateResume = (d, t, s, prev, o) => need().evaluateResume(d, t, s, prev, o);
263
+ export const observe = (n, f) => need().observe(n, f);
264
+ export const shutdown = () => (current ? current.shutdown() : Promise.resolve());
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `instrumentAmqplib(await conn.createChannel())`: patches that channel's class (every channel of
3
+ * it): PRODUCER spans on `publish`/`sendToQueue` with the trace context in `options.headers`, and a
4
+ * CONSUMER span (child of and linked to the producer) around each `consume` callback.
5
+ * shortcut: a ConfirmChannel is its own class; pass one of those too if you use both kinds.
6
+ */
7
+ export declare function instrumentAmqplib(channel: object): void;
8
+ /**
9
+ * `instrumentRabbitmqClient(new Connection(url))` for rabbitmq-client: publishers made by
10
+ * `createPublisher` get PRODUCER spans on `send` (context in the envelope headers); handlers given
11
+ * to `createConsumer` run in a CONSUMER span. Call it before creating publishers and consumers.
12
+ */
13
+ export declare function instrumentRabbitmqClient(connection: object): void;
@@ -0,0 +1,92 @@
1
+ import { patch } from './db.js';
2
+ import { consume, produce } from './messaging.js';
3
+ const sendAttrs = (dest, routingKey, op, messageId, size) => ({
4
+ 'messaging.system': 'rabbitmq',
5
+ 'messaging.destination.name': dest,
6
+ 'messaging.operation.type': 'send',
7
+ 'messaging.operation.name': op,
8
+ 'messaging.rabbitmq.destination.routing_key': routingKey,
9
+ ...(typeof messageId === 'string' ? { 'messaging.message.id': messageId } : {}),
10
+ ...(typeof size === 'number' ? { 'messaging.message.body.size': size } : {}),
11
+ });
12
+ function processAttrs(queue, m) {
13
+ const a = {
14
+ 'messaging.system': 'rabbitmq',
15
+ 'messaging.destination.name': queue,
16
+ 'messaging.operation.type': 'process',
17
+ 'messaging.operation.name': 'consume',
18
+ };
19
+ if (m.properties?.messageId)
20
+ a['messaging.message.id'] = m.properties.messageId;
21
+ if (typeof m.content?.length === 'number')
22
+ a['messaging.message.body.size'] = m.content.length;
23
+ if (m.fields?.deliveryTag !== undefined)
24
+ a['messaging.rabbitmq.message.delivery_tag'] = m.fields.deliveryTag;
25
+ if (m.fields?.redelivered !== undefined)
26
+ a['messaging.rabbitmq.message.redelivered'] = m.fields.redelivered;
27
+ if (m.fields?.consumerTag)
28
+ a['messaging.consumer.group.name'] = m.fields.consumerTag;
29
+ return a;
30
+ }
31
+ const withHeaders = (o, h) => ({ ...o, headers: { ...o?.headers, ...h } });
32
+ /**
33
+ * `instrumentAmqplib(await conn.createChannel())`: patches that channel's class (every channel of
34
+ * it): PRODUCER spans on `publish`/`sendToQueue` with the trace context in `options.headers`, and a
35
+ * CONSUMER span (child of and linked to the producer) around each `consume` callback.
36
+ * shortcut: a ConfirmChannel is its own class; pass one of those too if you use both kinds.
37
+ */
38
+ export function instrumentAmqplib(channel) {
39
+ const proto = Object.getPrototypeOf(channel);
40
+ patch(proto, 'publish', (orig) => function (exchange, routingKey, content, options, ...rest) {
41
+ const dest = exchange || routingKey;
42
+ return produce(`publish ${dest}`, sendAttrs(dest, routingKey, 'publish', options?.messageId, content?.length), (h) => orig.call(this, exchange, routingKey, content, withHeaders(options, h), ...rest));
43
+ });
44
+ // amqplib's sendToQueue calls publish('', queue): that inner call adds no second span
45
+ patch(proto, 'sendToQueue', (orig) => function (queue, content, options, ...rest) {
46
+ return produce(`publish ${queue}`, sendAttrs(queue, queue, 'sendToQueue', options?.messageId, content?.length), (h) => orig.call(this, queue, content, withHeaders(options, h), ...rest));
47
+ });
48
+ patch(proto, 'consume', (orig) => function (queue, onMessage, ...rest) {
49
+ if (typeof onMessage !== 'function')
50
+ return orig.call(this, queue, onMessage, ...rest);
51
+ const wrapped = (m) => (m
52
+ ? consume(`process ${queue}`, processAttrs(queue, m), [m.properties?.headers], () => onMessage(m))
53
+ : onMessage(m)); // null: the server cancelled the consumer
54
+ return orig.call(this, queue, wrapped, ...rest);
55
+ });
56
+ }
57
+ /**
58
+ * `instrumentRabbitmqClient(new Connection(url))` for rabbitmq-client: publishers made by
59
+ * `createPublisher` get PRODUCER spans on `send` (context in the envelope headers); handlers given
60
+ * to `createConsumer` run in a CONSUMER span. Call it before creating publishers and consumers.
61
+ */
62
+ export function instrumentRabbitmqClient(connection) {
63
+ patch(connection, 'createPublisher', (orig) => function (...a) {
64
+ const pub = orig.apply(this, a);
65
+ patch(pub, 'send', (send) => function (envelope, body, ...rest) {
66
+ const env = typeof envelope === 'string' ? { routingKey: envelope } : { ...envelope };
67
+ const rk = env.routingKey ?? '';
68
+ const dest = env.exchange || rk;
69
+ const size = typeof body === 'string' || body instanceof Uint8Array ? body.length : undefined;
70
+ return produce(`publish ${dest}`, sendAttrs(dest, rk, 'send', env.messageId, size), (h) => send.call(this, { ...env, headers: { ...env.headers, ...h } }, body, ...rest));
71
+ });
72
+ return pub;
73
+ });
74
+ patch(connection, 'createConsumer', (orig) => function (props, handler, ...rest) {
75
+ if (typeof handler !== 'function')
76
+ return orig.call(this, props, handler, ...rest);
77
+ const queue = (typeof props === 'string' ? props : props?.queue) ?? '';
78
+ const wrapped = function (m, ...more) {
79
+ const a = {
80
+ 'messaging.system': 'rabbitmq',
81
+ 'messaging.destination.name': queue,
82
+ 'messaging.operation.type': 'process',
83
+ 'messaging.operation.name': 'consume',
84
+ ...(m?.messageId ? { 'messaging.message.id': m.messageId } : {}),
85
+ ...(m?.deliveryTag !== undefined ? { 'messaging.rabbitmq.message.delivery_tag': m.deliveryTag } : {}),
86
+ ...(m?.redelivered !== undefined ? { 'messaging.rabbitmq.message.redelivered': m.redelivered } : {}),
87
+ };
88
+ return consume(`process ${queue}`, a, [m?.headers], () => handler.call(this, m, ...more));
89
+ };
90
+ return orig.call(this, props, wrapped, ...rest);
91
+ });
92
+ }
@@ -0,0 +1,18 @@
1
+ /** The slice of the Azure Functions v4 InvocationContext this wrapper reads. */
2
+ export interface AzureContextLike {
3
+ invocationId?: string;
4
+ functionName?: string;
5
+ options?: {
6
+ trigger?: {
7
+ type?: string;
8
+ };
9
+ };
10
+ }
11
+ /** Maps an Azure binding type to the OTel `faas.trigger` value. */
12
+ export declare function faasTrigger(type: string | undefined): string;
13
+ /** app.http('fn', { handler: wrapFunction(async (request, context) => ...) }). One span per
14
+ * invocation with cold start, invocation id and trigger; errors captured; HTTP 5xx results mark the
15
+ * span failed; spans flushed before the host may freeze the worker. */
16
+ export declare function wrapFunction<T, R, C extends AzureContextLike = AzureContextLike>(handler: (trigger: T, context: C) => Promise<R>, o?: {
17
+ name?: string;
18
+ }): (trigger: T, context: C) => Promise<R>;
@@ -0,0 +1,60 @@
1
+ import { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
2
+ import { captureException } from '../errors.js';
3
+ import * as wt from '../index.js';
4
+ const PUBSUB = ['serviceBusTrigger', 'eventHubTrigger', 'queueTrigger', 'eventGridTrigger', 'kafkaTrigger', 'rabbitMQTrigger'];
5
+ const DATASOURCE = ['blobTrigger', 'cosmosDBTrigger', 'sqlTrigger'];
6
+ /** Maps an Azure binding type to the OTel `faas.trigger` value. */
7
+ export function faasTrigger(type) {
8
+ if (type === 'httpTrigger')
9
+ return 'http';
10
+ if (type === 'timerTrigger')
11
+ return 'timer';
12
+ if (type && PUBSUB.includes(type))
13
+ return 'pubsub';
14
+ if (type && DATASOURCE.includes(type))
15
+ return 'datasource';
16
+ return 'other';
17
+ }
18
+ let cold = true;
19
+ /** app.http('fn', { handler: wrapFunction(async (request, context) => ...) }). One span per
20
+ * invocation with cold start, invocation id and trigger; errors captured; HTTP 5xx results mark the
21
+ * span failed; spans flushed before the host may freeze the worker. */
22
+ export function wrapFunction(handler, o) {
23
+ return async (input, context) => {
24
+ const c = context || {};
25
+ const coldstart = cold;
26
+ cold = false;
27
+ const kind = faasTrigger(c.options?.trigger?.type);
28
+ return trace.getTracer('watchtower').startActiveSpan(o?.name || c.functionName || 'function', {
29
+ kind: kind === 'http' ? SpanKind.SERVER : SpanKind.CONSUMER,
30
+ attributes: {
31
+ 'cloud.provider': 'azure',
32
+ 'cloud.platform': 'azure_functions',
33
+ 'faas.name': c.functionName,
34
+ 'faas.invocation_id': c.invocationId,
35
+ 'faas.trigger': kind,
36
+ 'faas.coldstart': coldstart,
37
+ },
38
+ }, async (span) => {
39
+ try {
40
+ const r = await handler(input, context);
41
+ const status = r?.status;
42
+ if (kind === 'http' && typeof status === 'number') {
43
+ span.setAttribute('http.response.status_code', status);
44
+ if (status >= 500)
45
+ span.setStatus({ code: SpanStatusCode.ERROR });
46
+ }
47
+ return r;
48
+ }
49
+ catch (e) {
50
+ span.setStatus({ code: SpanStatusCode.ERROR });
51
+ captureException(e, { handled: false, attributes: { 'error.mechanism': 'azure_functions' } });
52
+ throw e;
53
+ }
54
+ finally {
55
+ span.end();
56
+ await wt.flush().catch(() => { });
57
+ }
58
+ });
59
+ };
60
+ }
@@ -0,0 +1,19 @@
1
+ import { CONTEXT_KEY } from './messaging.js';
2
+ export { CONTEXT_KEY };
3
+ interface BullMQLike {
4
+ Queue: {
5
+ prototype: Record<string | symbol, unknown>;
6
+ };
7
+ Worker: {
8
+ prototype: Record<string | symbol, unknown>;
9
+ };
10
+ }
11
+ /**
12
+ * `import * as bullmq from 'bullmq'; instrumentBullMQ(bullmq)` (ESM or CJS): PRODUCER spans on
13
+ * `Queue.add`/`addBulk`, CONSUMER spans around each job a `Worker` processes, parented by the
14
+ * producer's context carried in job data under `_wt` (stripped before your processor runs; object
15
+ * data only). Call it once, before creating queues and workers. Returns false when this bullmq
16
+ * has no `Worker.callProcessJob` (consumer spans off; producer spans still on).
17
+ * shortcut: sandboxed (file path) processors run in a child process and get no consumer span.
18
+ */
19
+ export declare function instrumentBullMQ(bullmq: BullMQLike): boolean;
@@ -0,0 +1,79 @@
1
+ import { context, propagation, trace, SpanKind, SpanStatusCode } from '@opentelemetry/api';
2
+ import { CONTEXT_KEY, injectData as inject, isPlainObject } from './messaging.js';
3
+ export { CONTEXT_KEY };
4
+ const PATCHED = Symbol.for('watchtower.bullmq');
5
+ const tracer = () => trace.getTracer('watchtower');
6
+ const base = (queue, op, name) => ({
7
+ 'messaging.system': 'bullmq',
8
+ 'messaging.destination.name': queue,
9
+ 'messaging.operation.type': op,
10
+ 'messaging.operation.name': name,
11
+ });
12
+ async function run(span, fn) {
13
+ try {
14
+ return await fn();
15
+ }
16
+ catch (e) {
17
+ span.recordException(e);
18
+ span.setStatus({ code: SpanStatusCode.ERROR, message: e?.message });
19
+ throw e;
20
+ }
21
+ finally {
22
+ span.end();
23
+ }
24
+ }
25
+ /**
26
+ * `import * as bullmq from 'bullmq'; instrumentBullMQ(bullmq)` (ESM or CJS): PRODUCER spans on
27
+ * `Queue.add`/`addBulk`, CONSUMER spans around each job a `Worker` processes, parented by the
28
+ * producer's context carried in job data under `_wt` (stripped before your processor runs; object
29
+ * data only). Call it once, before creating queues and workers. Returns false when this bullmq
30
+ * has no `Worker.callProcessJob` (consumer spans off; producer spans still on).
31
+ * shortcut: sandboxed (file path) processors run in a child process and get no consumer span.
32
+ */
33
+ export function instrumentBullMQ(bullmq) {
34
+ const q = bullmq.Queue.prototype;
35
+ const w = bullmq.Worker.prototype;
36
+ if (q[PATCHED])
37
+ return typeof w.callProcessJob === 'function';
38
+ q[PATCHED] = true;
39
+ const add = q.add;
40
+ q.add = function (name, data, opts) {
41
+ const attrs = { ...base(this.name, 'send', 'add'), 'messaging.bullmq.job.name': name };
42
+ if (opts?.delay)
43
+ attrs['messaging.bullmq.job.delay_ms'] = opts.delay;
44
+ return tracer().startActiveSpan(`send ${this.name}`, { kind: SpanKind.PRODUCER, attributes: attrs }, (span) => run(span, async () => {
45
+ const job = (await add.call(this, name, inject(data), opts));
46
+ if (job?.id)
47
+ span.setAttribute('messaging.message.id', job.id);
48
+ return job;
49
+ }));
50
+ };
51
+ const addBulk = q.addBulk;
52
+ if (addBulk) {
53
+ q.addBulk = function (jobs) {
54
+ const attrs = { ...base(this.name, 'send', 'addBulk'), 'messaging.batch.message_count': jobs.length };
55
+ return tracer().startActiveSpan(`send ${this.name}`, { kind: SpanKind.PRODUCER, attributes: attrs }, (span) => run(span, () => addBulk.call(this, jobs.map((j) => ({ ...j, data: inject(j.data) })))));
56
+ };
57
+ }
58
+ const call = w.callProcessJob;
59
+ if (typeof call !== 'function')
60
+ return false;
61
+ w.callProcessJob = function (job, ...rest) {
62
+ let parent = context.active();
63
+ if (isPlainObject(job.data) && isPlainObject(job.data[CONTEXT_KEY])) {
64
+ parent = propagation.extract(parent, job.data[CONTEXT_KEY]);
65
+ delete job.data[CONTEXT_KEY];
66
+ }
67
+ const attrs = {
68
+ ...base(this.name, 'process', 'process'),
69
+ 'messaging.bullmq.job.name': job.name,
70
+ 'messaging.bullmq.job.attempt': (job.attemptsMade ?? 0) + 1,
71
+ };
72
+ if (job.id)
73
+ attrs['messaging.message.id'] = job.id;
74
+ if (job.opts?.delay)
75
+ attrs['messaging.bullmq.job.delay_ms'] = job.opts.delay;
76
+ return tracer().startActiveSpan(`process ${this.name}`, { kind: SpanKind.CONSUMER, attributes: attrs }, parent, (span) => run(span, () => call.call(this, job, ...rest)));
77
+ };
78
+ return true;
79
+ }
@@ -0,0 +1,13 @@
1
+ /** Hit/miss counters and entry count for a node-cache instance (`get`, `mget`). Returns `stop()`. */
2
+ export declare function instrumentNodeCache(cache: {
3
+ getStats?(): {
4
+ keys?: number;
5
+ };
6
+ }, name?: string): () => void;
7
+ /** Hit/miss counters and entry count for an lru-cache instance (`get`). Returns `stop()`.
8
+ * shortcut: `fetch()` (the async loader) is not counted. */
9
+ export declare function instrumentLruCache(cache: {
10
+ size?: number;
11
+ }, name?: string): () => void;
12
+ /** Hit/miss counters for a Keyv instance (`get` with one key or an array; also `getMany`). */
13
+ export declare function instrumentKeyv(keyv: object, name?: string): void;
@@ -0,0 +1,46 @@
1
+ import { cacheCounters, observeEmbedded, patch } from './db.js';
2
+ /** Count hits and misses of `get`-like methods: `undefined` is a miss; arrays and objects count per key. */
3
+ function count(c, keys, v) {
4
+ if (Array.isArray(keys)) {
5
+ const found = Array.isArray(v) ? v.filter((x) => x !== undefined).length
6
+ : v && typeof v === 'object' ? Object.keys(v).length : 0;
7
+ c.hit(found);
8
+ c.miss(keys.length - found);
9
+ }
10
+ else if (v === undefined) {
11
+ c.miss();
12
+ }
13
+ else {
14
+ c.hit();
15
+ }
16
+ }
17
+ function wrapGets(cache, system, name, methods) {
18
+ const c = cacheCounters(system, name);
19
+ for (const m of methods) {
20
+ patch(cache, m, (orig) => function (key, ...a) {
21
+ const v = orig.call(this, key, ...a);
22
+ if (v && typeof v.then === 'function') {
23
+ v.then((x) => count(c, key, x), () => { });
24
+ }
25
+ else {
26
+ count(c, key, v);
27
+ }
28
+ return v;
29
+ });
30
+ }
31
+ }
32
+ /** Hit/miss counters and entry count for a node-cache instance (`get`, `mget`). Returns `stop()`. */
33
+ export function instrumentNodeCache(cache, name = 'default') {
34
+ wrapGets(cache, 'node-cache', name, ['get', 'mget']);
35
+ return observeEmbedded('node-cache', name, ['cache.entries'], () => ({ 'cache.entries': cache.getStats?.().keys }));
36
+ }
37
+ /** Hit/miss counters and entry count for an lru-cache instance (`get`). Returns `stop()`.
38
+ * shortcut: `fetch()` (the async loader) is not counted. */
39
+ export function instrumentLruCache(cache, name = 'default') {
40
+ wrapGets(cache, 'lru-cache', name, ['get']);
41
+ return observeEmbedded('lru-cache', name, ['cache.entries'], () => ({ 'cache.entries': cache.size }));
42
+ }
43
+ /** Hit/miss counters for a Keyv instance (`get` with one key or an array; also `getMany`). */
44
+ export function instrumentKeyv(keyv, name = 'default') {
45
+ wrapGets(keyv, 'keyv', name, ['get', 'getMany']);
46
+ }