@watchtowerobservability/node 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -9
- package/dist/cjs/buffer.d.ts +2 -3
- package/dist/cjs/buffer.js +6 -6
- package/dist/cjs/env.d.ts +12 -0
- package/dist/cjs/env.js +37 -0
- package/dist/cjs/errors.d.ts +8 -0
- package/dist/cjs/errors.js +23 -0
- package/dist/cjs/index.d.ts +34 -12
- package/dist/cjs/index.js +106 -52
- package/dist/cjs/instrument.d.ts +7 -0
- package/dist/cjs/instrument.js +51 -0
- package/dist/cjs/integrations/genai-agents.d.ts +4 -1
- package/dist/cjs/integrations/genai-agents.js +27 -24
- package/dist/cjs/integrations/genai-frameworks.d.ts +25 -0
- package/dist/cjs/integrations/genai-frameworks.js +211 -0
- package/dist/cjs/integrations/genai.d.ts +1 -0
- package/dist/cjs/integrations/genai.js +7 -2
- package/dist/cjs/integrations/next.d.ts +4 -1
- package/dist/cjs/integrations/next.js +13 -7
- package/dist/cjs/load.d.ts +2 -0
- package/dist/cjs/load.js +54 -5
- package/dist/cjs/metrics.d.ts +1 -2
- package/dist/cjs/metrics.js +6 -6
- package/dist/cjs/origin.d.ts +9 -0
- package/dist/cjs/origin.js +43 -0
- package/dist/cjs/redact.d.ts +8 -0
- package/dist/cjs/redact.js +43 -0
- package/dist/cjs/register.d.ts +1 -0
- package/dist/cjs/register.js +29 -0
- package/dist/cjs/sampling.d.ts +53 -0
- package/dist/cjs/sampling.js +98 -0
- package/dist/esm/buffer.d.ts +2 -3
- package/dist/esm/buffer.js +6 -6
- package/dist/esm/env.d.ts +12 -0
- package/dist/esm/env.js +33 -0
- package/dist/esm/errors.d.ts +8 -0
- package/dist/esm/errors.js +22 -0
- package/dist/esm/index.d.ts +34 -12
- package/dist/esm/index.js +104 -51
- package/dist/esm/instrument.d.ts +7 -0
- package/dist/esm/instrument.js +48 -0
- package/dist/esm/integrations/genai-agents.d.ts +4 -1
- package/dist/esm/integrations/genai-agents.js +4 -4
- package/dist/esm/integrations/genai-frameworks.d.ts +25 -0
- package/dist/esm/integrations/genai-frameworks.js +206 -0
- package/dist/esm/integrations/genai.d.ts +1 -0
- package/dist/esm/integrations/genai.js +3 -1
- package/dist/esm/integrations/next.d.ts +4 -1
- package/dist/esm/integrations/next.js +11 -6
- package/dist/esm/load.d.ts +2 -0
- package/dist/esm/load.js +78 -2
- package/dist/esm/metrics.d.ts +1 -2
- package/dist/esm/metrics.js +5 -5
- package/dist/esm/origin.d.ts +9 -0
- package/dist/esm/origin.js +39 -0
- package/dist/esm/redact.d.ts +8 -0
- package/dist/esm/redact.js +39 -0
- package/dist/esm/register.d.ts +1 -0
- package/dist/esm/register.js +27 -0
- package/dist/esm/sampling.d.ts +53 -0
- package/dist/esm/sampling.js +91 -0
- package/package.json +86 -14
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.firstAppFrame = firstAppFrame;
|
|
4
|
+
exports.codeOrigin = codeOrigin;
|
|
5
|
+
const FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):\d+\)?$/;
|
|
6
|
+
const SKIP = /node_modules|^node:|[\\/]watchtower[\\/](?:dist|src)[\\/]|@watchtowerobservability[\\/]node/;
|
|
7
|
+
/** The first application frame of a V8 stack, or undefined. */
|
|
8
|
+
function firstAppFrame(stack) {
|
|
9
|
+
for (const line of stack.split('\n').slice(1)) {
|
|
10
|
+
const m = FRAME.exec(line);
|
|
11
|
+
if (!m)
|
|
12
|
+
continue;
|
|
13
|
+
const file = m[2].replace(/^file:\/\//, '');
|
|
14
|
+
if (SKIP.test(file) || SKIP.test(line.trim().slice(3)))
|
|
15
|
+
continue;
|
|
16
|
+
return { file, line: Number(m[3]), fn: m[1] && m[1] !== '<anonymous>' ? m[1] : undefined };
|
|
17
|
+
}
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
function codeOrigin() {
|
|
21
|
+
return {
|
|
22
|
+
onStart(span) {
|
|
23
|
+
const s = span;
|
|
24
|
+
if (s.attributes?.['code.filepath'] !== undefined)
|
|
25
|
+
return;
|
|
26
|
+
const holder = {};
|
|
27
|
+
const prev = Error.stackTraceLimit;
|
|
28
|
+
Error.stackTraceLimit = 30;
|
|
29
|
+
Error.captureStackTrace(holder);
|
|
30
|
+
Error.stackTraceLimit = prev;
|
|
31
|
+
const f = firstAppFrame(holder.stack ?? '');
|
|
32
|
+
if (!f)
|
|
33
|
+
return;
|
|
34
|
+
s.setAttribute('code.filepath', f.file);
|
|
35
|
+
s.setAttribute('code.lineno', f.line);
|
|
36
|
+
if (f.fn)
|
|
37
|
+
s.setAttribute('code.function', f.fn);
|
|
38
|
+
},
|
|
39
|
+
onEnd() { },
|
|
40
|
+
shutdown: () => Promise.resolve(),
|
|
41
|
+
forceFlush: () => Promise.resolve(),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { SpanProcessor } from '@opentelemetry/sdk-trace';
|
|
2
|
+
export type RedactHook = (key: string, value: unknown) => unknown;
|
|
3
|
+
/** Hook keys for the non-attribute fields. Event attributes (incl. exception.message / exception.stacktrace) use their own keys. */
|
|
4
|
+
export declare const SPAN_NAME_KEY = "span.name";
|
|
5
|
+
export declare const STATUS_MESSAGE_KEY = "status.message";
|
|
6
|
+
export declare const LOG_BODY_KEY = "log.body";
|
|
7
|
+
/** Span processor that redacts the name, status message, attributes, every event's and link's attributes before export. */
|
|
8
|
+
export declare function redactor(hook: RedactHook): SpanProcessor;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LOG_BODY_KEY = exports.STATUS_MESSAGE_KEY = exports.SPAN_NAME_KEY = void 0;
|
|
4
|
+
exports.redactor = redactor;
|
|
5
|
+
/** Hook keys for the non-attribute fields. Event attributes (incl. exception.message / exception.stacktrace) use their own keys. */
|
|
6
|
+
exports.SPAN_NAME_KEY = 'span.name';
|
|
7
|
+
exports.STATUS_MESSAGE_KEY = 'status.message';
|
|
8
|
+
exports.LOG_BODY_KEY = 'log.body';
|
|
9
|
+
function attrs(a, hook) {
|
|
10
|
+
if (!a)
|
|
11
|
+
return;
|
|
12
|
+
for (const k of Object.keys(a))
|
|
13
|
+
a[k] = hook(k, a[k]);
|
|
14
|
+
}
|
|
15
|
+
/** Assign, falling back to defineProperty if the SDK exposes the field as a getter. */
|
|
16
|
+
function put(o, k, v) {
|
|
17
|
+
try {
|
|
18
|
+
o[k] = v;
|
|
19
|
+
}
|
|
20
|
+
catch { /* readonly accessor */ }
|
|
21
|
+
if (o[k] !== v)
|
|
22
|
+
Object.defineProperty(o, k, { value: v, configurable: true, enumerable: true, writable: true });
|
|
23
|
+
}
|
|
24
|
+
/** Span processor that redacts the name, status message, attributes, every event's and link's attributes before export. */
|
|
25
|
+
function redactor(hook) {
|
|
26
|
+
return {
|
|
27
|
+
onStart() { },
|
|
28
|
+
onEnd(span) {
|
|
29
|
+
// ReadableSpan fields are readonly in the types but are plain mutable fields on the SDK span
|
|
30
|
+
const s = span;
|
|
31
|
+
put(s, 'name', String(hook(exports.SPAN_NAME_KEY, s.name) ?? ''));
|
|
32
|
+
if (s.status?.message)
|
|
33
|
+
put(s.status, 'message', String(hook(exports.STATUS_MESSAGE_KEY, s.status.message) ?? ''));
|
|
34
|
+
attrs(span.attributes, hook);
|
|
35
|
+
for (const e of s.events || [])
|
|
36
|
+
attrs(e.attributes, hook);
|
|
37
|
+
for (const l of s.links || [])
|
|
38
|
+
attrs(l.attributes, hook);
|
|
39
|
+
},
|
|
40
|
+
shutdown: () => Promise.resolve(),
|
|
41
|
+
forceFlush: () => Promise.resolve(),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// Preload entry: `node --import @watchtowerobservability/node/register app.mjs` (ESM) or `node -r @watchtowerobservability/node/register app.js` (CommonJS).
|
|
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.
|
|
6
|
+
const node_url_1 = require("node:url");
|
|
7
|
+
const node_module_1 = require("node:module");
|
|
8
|
+
const index_js_1 = require("./index.js");
|
|
9
|
+
if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
|
|
10
|
+
try {
|
|
11
|
+
// ESM modules (node:http imported from an ES module) are only patched through OpenTelemetry's loader hook
|
|
12
|
+
// (import-in-the-middle). Resolve it from the app, once per process, and skip quietly when it is not installed.
|
|
13
|
+
const g = globalThis;
|
|
14
|
+
const key = Symbol.for('watchtower.node.esm-hook');
|
|
15
|
+
if (!g[key]) {
|
|
16
|
+
g[key] = true;
|
|
17
|
+
try {
|
|
18
|
+
(0, node_module_1.register)('@opentelemetry/instrumentation/hook.mjs', (0, node_url_1.pathToFileURL)(`${process.cwd()}/`));
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// @opentelemetry/instrumentation not installed: CommonJS apps are still instrumented
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
(0, index_js_1.init)({});
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
console.warn(`[watchtower] register: ${e.message}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Attributes, Context, Link, SpanKind } from '@opentelemetry/api';
|
|
2
|
+
import type { Sampler, SamplingResult } from '@opentelemetry/sdk-trace';
|
|
3
|
+
export interface SamplingRule {
|
|
4
|
+
name?: string;
|
|
5
|
+
enabled?: boolean | null;
|
|
6
|
+
match?: {
|
|
7
|
+
service?: string;
|
|
8
|
+
env?: string;
|
|
9
|
+
span_name_prefix?: string;
|
|
10
|
+
span_name_glob?: string;
|
|
11
|
+
span_name_regex?: string;
|
|
12
|
+
attrs?: Record<string, string>;
|
|
13
|
+
min_duration_ms?: number | null;
|
|
14
|
+
status?: string;
|
|
15
|
+
};
|
|
16
|
+
action?: {
|
|
17
|
+
kind?: string;
|
|
18
|
+
ratio?: number | null;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
export interface RemoteConfig {
|
|
22
|
+
strategyType?: string;
|
|
23
|
+
probabilisticSampling?: {
|
|
24
|
+
samplingRate: number;
|
|
25
|
+
};
|
|
26
|
+
rules?: SamplingRule[];
|
|
27
|
+
}
|
|
28
|
+
/** fnv64a of the trace id's bytes, as a fraction of 2^64; matches the gateway's `ratioKeeps`. */
|
|
29
|
+
export declare function traceFraction(traceIdHex: string): number;
|
|
30
|
+
export declare function globMatches(glob: string, text: string): boolean;
|
|
31
|
+
/** The keep ratio for a span under `cfg` (1 = keep). First matching ratio/drop rule wins. */
|
|
32
|
+
export declare function ratioFor(cfg: RemoteConfig, service: string, env: string, name: string, attrs: Attributes): number;
|
|
33
|
+
export interface RemoteSamplerOptions {
|
|
34
|
+
endpoint: string;
|
|
35
|
+
headers: Record<string, string>;
|
|
36
|
+
service: string;
|
|
37
|
+
env?: string;
|
|
38
|
+
intervalMs?: number;
|
|
39
|
+
fetch?: typeof fetch;
|
|
40
|
+
}
|
|
41
|
+
export declare class RemoteSampler implements Sampler {
|
|
42
|
+
private readonly o;
|
|
43
|
+
cfg: RemoteConfig;
|
|
44
|
+
private etag;
|
|
45
|
+
private timer?;
|
|
46
|
+
private readonly fetchFn;
|
|
47
|
+
constructor(o: RemoteSamplerOptions);
|
|
48
|
+
/** One poll; a failure or 304 keeps the current config. */
|
|
49
|
+
poll(): Promise<void>;
|
|
50
|
+
stop(): void;
|
|
51
|
+
shouldSample(_c: Context, traceId: string, name: string, _k: SpanKind, attributes: Attributes, _l: Link[]): SamplingResult;
|
|
52
|
+
toString(): string;
|
|
53
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RemoteSampler = void 0;
|
|
4
|
+
exports.traceFraction = traceFraction;
|
|
5
|
+
exports.globMatches = globMatches;
|
|
6
|
+
exports.ratioFor = ratioFor;
|
|
7
|
+
const NOT_RECORD = 0;
|
|
8
|
+
const RECORD_AND_SAMPLED = 2;
|
|
9
|
+
const FNV_OFFSET = 0xcbf29ce484222325n;
|
|
10
|
+
const FNV_PRIME = 0x100000001b3n;
|
|
11
|
+
const MASK = 0xffffffffffffffffn;
|
|
12
|
+
const TWO_64 = 18446744073709551616;
|
|
13
|
+
/** fnv64a of the trace id's bytes, as a fraction of 2^64; matches the gateway's `ratioKeeps`. */
|
|
14
|
+
function traceFraction(traceIdHex) {
|
|
15
|
+
let h = FNV_OFFSET;
|
|
16
|
+
for (let i = 0; i + 1 < traceIdHex.length; i += 2)
|
|
17
|
+
h = ((h ^ BigInt(parseInt(traceIdHex.slice(i, i + 2), 16))) * FNV_PRIME) & MASK;
|
|
18
|
+
return Number(h) / TWO_64;
|
|
19
|
+
}
|
|
20
|
+
function globMatches(glob, text) {
|
|
21
|
+
const re = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
|
|
22
|
+
return new RegExp(`^${re}$`, 's').test(text);
|
|
23
|
+
}
|
|
24
|
+
function ruleMatches(r, service, env, name, attrs) {
|
|
25
|
+
const m = r.match ?? {};
|
|
26
|
+
// duration and status are only known at the end of the span: the gateway decides those
|
|
27
|
+
if (m.min_duration_ms != null || m.status)
|
|
28
|
+
return false;
|
|
29
|
+
if ((m.service && m.service !== service) || (m.env && m.env !== env))
|
|
30
|
+
return false;
|
|
31
|
+
if (m.span_name_prefix && !name.startsWith(m.span_name_prefix))
|
|
32
|
+
return false;
|
|
33
|
+
if (m.span_name_glob && !globMatches(m.span_name_glob, name))
|
|
34
|
+
return false;
|
|
35
|
+
if (m.span_name_regex) {
|
|
36
|
+
try {
|
|
37
|
+
if (!new RegExp(m.span_name_regex).test(name))
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return Object.entries(m.attrs ?? {}).every(([k, v]) => String(attrs[k]) === v);
|
|
45
|
+
}
|
|
46
|
+
/** The keep ratio for a span under `cfg` (1 = keep). First matching ratio/drop rule wins. */
|
|
47
|
+
function ratioFor(cfg, service, env, name, attrs) {
|
|
48
|
+
if (cfg.strategyType === 'PROBABILISTIC')
|
|
49
|
+
return clamp(cfg.probabilisticSampling?.samplingRate);
|
|
50
|
+
for (const r of cfg.rules ?? []) {
|
|
51
|
+
if (r.enabled === false || !ruleMatches(r, service, env, name, attrs))
|
|
52
|
+
continue;
|
|
53
|
+
if (r.action?.kind === 'drop')
|
|
54
|
+
return 0;
|
|
55
|
+
if (r.action?.kind === 'ratio' && r.action.ratio != null)
|
|
56
|
+
return clamp(r.action.ratio);
|
|
57
|
+
return 1; // keep, tail, rate: decided later
|
|
58
|
+
}
|
|
59
|
+
return 1;
|
|
60
|
+
}
|
|
61
|
+
const clamp = (r) => (typeof r === 'number' && Number.isFinite(r) ? Math.min(1, Math.max(0, r)) : 1);
|
|
62
|
+
class RemoteSampler {
|
|
63
|
+
o;
|
|
64
|
+
cfg = {};
|
|
65
|
+
etag = '';
|
|
66
|
+
timer;
|
|
67
|
+
fetchFn;
|
|
68
|
+
constructor(o) {
|
|
69
|
+
this.o = o;
|
|
70
|
+
this.fetchFn = o.fetch ?? globalThis.fetch;
|
|
71
|
+
void this.poll();
|
|
72
|
+
this.timer = setInterval(() => void this.poll(), Math.max(1000, o.intervalMs ?? 30_000));
|
|
73
|
+
this.timer.unref?.();
|
|
74
|
+
}
|
|
75
|
+
/** One poll; a failure or 304 keeps the current config. */
|
|
76
|
+
async poll() {
|
|
77
|
+
try {
|
|
78
|
+
const q = new URLSearchParams({ service: this.o.service, ...(this.o.env ? { env: this.o.env } : {}) });
|
|
79
|
+
const res = await this.fetchFn(`${this.o.endpoint}/v1/sampling?${q}`, {
|
|
80
|
+
headers: { ...this.o.headers, ...(this.etag ? { 'If-None-Match': this.etag } : {}) },
|
|
81
|
+
});
|
|
82
|
+
if (res.status === 304 || !res.ok)
|
|
83
|
+
return;
|
|
84
|
+
this.cfg = (await res.json());
|
|
85
|
+
this.etag = res.headers.get('ETag') ?? '';
|
|
86
|
+
}
|
|
87
|
+
catch { /* fallback: keep the last good config */ }
|
|
88
|
+
}
|
|
89
|
+
stop() { if (this.timer)
|
|
90
|
+
clearInterval(this.timer); }
|
|
91
|
+
shouldSample(_c, traceId, name, _k, attributes, _l) {
|
|
92
|
+
const r = ratioFor(this.cfg, this.o.service, this.o.env ?? '', name, attributes);
|
|
93
|
+
const keep = r >= 1 || (r > 0 && traceFraction(traceId) < r);
|
|
94
|
+
return { decision: keep ? RECORD_AND_SAMPLED : NOT_RECORD };
|
|
95
|
+
}
|
|
96
|
+
toString() { return 'WatchtowerRemoteSampler'; }
|
|
97
|
+
}
|
|
98
|
+
exports.RemoteSampler = RemoteSampler;
|
package/dist/esm/buffer.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import type { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace
|
|
1
|
+
import type { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace';
|
|
2
2
|
import type { LogRecordExporter, ReadableLogRecord } from '@opentelemetry/sdk-logs';
|
|
3
|
-
import { AggregationTemporality } from '@opentelemetry/sdk-metrics';
|
|
4
|
-
import type { InstrumentType, PushMetricExporter, ResourceMetrics } from '@opentelemetry/sdk-metrics';
|
|
3
|
+
import type { AggregationTemporality, InstrumentType, PushMetricExporter, ResourceMetrics } from '@opentelemetry/sdk-metrics';
|
|
5
4
|
type Done = Parameters<SpanExporter['export']>[1];
|
|
6
5
|
/** What the spool wraps: a span, log record or metric exporter; `B` is one export batch. */
|
|
7
6
|
export interface BatchExporter<B> {
|
package/dist/esm/buffer.js
CHANGED
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
import * as fs from 'node:fs';
|
|
5
5
|
import * as path from 'node:path';
|
|
6
6
|
import * as crypto from 'node:crypto';
|
|
7
|
-
import {
|
|
8
|
-
|
|
7
|
+
import { need } from './load.js';
|
|
8
|
+
const ser = () => need('@opentelemetry/otlp-transformer');
|
|
9
9
|
/** OTLP/JSON encoders for the three signals. */
|
|
10
|
-
export const encodeSpans = (spans) => Buffer.from(JsonTraceSerializer.serializeRequest(spans));
|
|
11
|
-
export const encodeLogs = (logs) => Buffer.from(JsonLogsSerializer.serializeRequest(logs));
|
|
12
|
-
export const encodeMetrics = (rm) => Buffer.from(JsonMetricsSerializer.serializeRequest(rm));
|
|
10
|
+
export const encodeSpans = (spans) => Buffer.from(ser().JsonTraceSerializer.serializeRequest(spans));
|
|
11
|
+
export const encodeLogs = (logs) => Buffer.from(ser().JsonLogsSerializer.serializeRequest(logs));
|
|
12
|
+
export const encodeMetrics = (rm) => Buffer.from(ser().JsonMetricsSerializer.serializeRequest(rm));
|
|
13
13
|
export class SpoolExporter {
|
|
14
14
|
inner;
|
|
15
15
|
dir;
|
|
@@ -84,7 +84,7 @@ export class MetricSpool extends SpoolExporter {
|
|
|
84
84
|
}
|
|
85
85
|
selectAggregationTemporality(t) {
|
|
86
86
|
const pick = this.metricInner.selectAggregationTemporality;
|
|
87
|
-
return pick ? pick.call(this.metricInner, t) :
|
|
87
|
+
return pick ? pick.call(this.metricInner, t) : 1; // CUMULATIVE, the SDK default (enum value, so sdk-metrics is not imported eagerly)
|
|
88
88
|
}
|
|
89
89
|
forceFlush() {
|
|
90
90
|
return this.metricInner.forceFlush();
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Parse `k=v,k2=v2` (OTEL_RESOURCE_ATTRIBUTES / OTEL_EXPORTER_OTLP_HEADERS); values are percent-decoded. */
|
|
2
|
+
export declare function parseKv(s: string | undefined): Record<string, string>;
|
|
3
|
+
export interface OtelEnv {
|
|
4
|
+
endpoint?: string;
|
|
5
|
+
/** Header names are lower-cased by nobody: they are kept as written, except `Authorization` is matched case-insensitively. */
|
|
6
|
+
headers: Record<string, string>;
|
|
7
|
+
/** `Authorization: Bearer <key>` from OTEL_EXPORTER_OTLP_HEADERS, the key only. */
|
|
8
|
+
bearer?: string;
|
|
9
|
+
serviceName?: string;
|
|
10
|
+
resource: Record<string, string>;
|
|
11
|
+
}
|
|
12
|
+
export declare function otelEnv(env?: NodeJS.ProcessEnv): OtelEnv;
|
package/dist/esm/env.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Standard OTEL_* environment variables, used as fallbacks after the WT_* ones.
|
|
2
|
+
/** Parse `k=v,k2=v2` (OTEL_RESOURCE_ATTRIBUTES / OTEL_EXPORTER_OTLP_HEADERS); values are percent-decoded. */
|
|
3
|
+
export function parseKv(s) {
|
|
4
|
+
const out = {};
|
|
5
|
+
for (const part of (s || '').split(',')) {
|
|
6
|
+
const i = part.indexOf('=');
|
|
7
|
+
if (i <= 0)
|
|
8
|
+
continue;
|
|
9
|
+
const dec = (x) => { try {
|
|
10
|
+
return decodeURIComponent(x.trim());
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return x.trim();
|
|
14
|
+
} };
|
|
15
|
+
out[dec(part.slice(0, i))] = dec(part.slice(i + 1));
|
|
16
|
+
}
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
19
|
+
export function otelEnv(env = process.env) {
|
|
20
|
+
const headers = parseKv(env.OTEL_EXPORTER_OTLP_HEADERS);
|
|
21
|
+
const authKey = Object.keys(headers).find((k) => k.toLowerCase() === 'authorization');
|
|
22
|
+
const auth = authKey ? headers[authKey] : undefined;
|
|
23
|
+
if (authKey)
|
|
24
|
+
delete headers[authKey];
|
|
25
|
+
const resource = parseKv(env.OTEL_RESOURCE_ATTRIBUTES);
|
|
26
|
+
return {
|
|
27
|
+
endpoint: env.OTEL_EXPORTER_OTLP_ENDPOINT || undefined,
|
|
28
|
+
headers,
|
|
29
|
+
bearer: auth && /^bearer\s+/i.test(auth) ? auth.replace(/^bearer\s+/i, '') : undefined,
|
|
30
|
+
serviceName: env.OTEL_SERVICE_NAME || resource['service.name'] || undefined,
|
|
31
|
+
resource,
|
|
32
|
+
};
|
|
33
|
+
}
|
package/dist/esm/errors.d.ts
CHANGED
|
@@ -2,7 +2,15 @@ export interface CaptureContext {
|
|
|
2
2
|
/** false for crashes (uncaught); default true. Keys starting with `wt.` are dropped. */
|
|
3
3
|
handled?: boolean;
|
|
4
4
|
attributes?: Record<string, string | number | boolean | undefined>;
|
|
5
|
+
/**
|
|
6
|
+
* Exception replay: variables to show on the throwing frame. Node cannot read another frame's locals, so
|
|
7
|
+
* the caller names them. Secret-looking names are masked, values are shortened; the project must also turn
|
|
8
|
+
* on "exception replay" in its issue settings or the server drops them.
|
|
9
|
+
*/
|
|
10
|
+
locals?: Record<string, unknown>;
|
|
5
11
|
}
|
|
12
|
+
/** `exception.locals` for the innermost stack frame of `e`: the function and line come from its stack, the values from `locals`. */
|
|
13
|
+
export declare function localsAttribute(e: Error, locals: Record<string, unknown>): string | undefined;
|
|
6
14
|
/** The slice of `process` the hooks need; tests pass an EventEmitter. */
|
|
7
15
|
export interface ProcessLike {
|
|
8
16
|
on(event: string, listener: (arg: unknown) => void): unknown;
|
package/dist/esm/errors.js
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
// Error capture: an exception becomes an OTel span event (exception.*) with trace and span ids.
|
|
2
2
|
import { trace, SpanStatusCode } from '@opentelemetry/api';
|
|
3
3
|
const captured = new WeakMap(); // error object -> traceId, so framework + process hooks never double-report
|
|
4
|
+
const SENSITIVE = /pass|secret|token|api[-_]?key|auth|cookie|session|credit|card|ssn|private|bearer/i;
|
|
5
|
+
/** `exception.locals` for the innermost stack frame of `e`: the function and line come from its stack, the values from `locals`. */
|
|
6
|
+
export function localsAttribute(e, locals) {
|
|
7
|
+
const m = /^\s+at (?:(\S+) \()?(.*?):(\d+):\d+\)?$/m.exec(e.stack || '');
|
|
8
|
+
const vars = {};
|
|
9
|
+
for (const [k, v] of Object.entries(locals).slice(0, 20)) {
|
|
10
|
+
let text;
|
|
11
|
+
try {
|
|
12
|
+
text = typeof v === 'string' ? v : JSON.stringify(v) ?? String(v);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
text = '<unrepresentable>';
|
|
16
|
+
}
|
|
17
|
+
vars[k] = SENSITIVE.test(k) ? '[Filtered]' : text.slice(0, 120);
|
|
18
|
+
}
|
|
19
|
+
if (!Object.keys(vars).length)
|
|
20
|
+
return undefined;
|
|
21
|
+
return JSON.stringify([{ function: m?.[1] ?? '', filename: m?.[2] ?? '', lineno: m ? Number(m[3]) : undefined, vars }]);
|
|
22
|
+
}
|
|
4
23
|
export function dropReserved(attrs) {
|
|
5
24
|
return Object.fromEntries(Object.entries(attrs || {}).filter(([k]) => !k.startsWith('wt.')));
|
|
6
25
|
}
|
|
@@ -15,7 +34,10 @@ export function captureException(err, ctx) {
|
|
|
15
34
|
const active = trace.getActiveSpan();
|
|
16
35
|
const span = active && active.isRecording() ? active : trace.getTracer('watchtower').startSpan('exception');
|
|
17
36
|
span.setAttributes(attrs);
|
|
37
|
+
const replay = o.locals ? localsAttribute(e, o.locals) : undefined;
|
|
18
38
|
span.recordException(e);
|
|
39
|
+
if (replay)
|
|
40
|
+
span.setAttribute('exception.locals', replay); // the OTel JS exception event takes no attributes
|
|
19
41
|
span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
|
|
20
42
|
const traceId = span.spanContext().traceId;
|
|
21
43
|
if (span !== active)
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { inspect } from 'node:util';
|
|
2
2
|
import { metrics, trace } from '@opentelemetry/api';
|
|
3
3
|
import type { Tracer } from '@opentelemetry/api';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import type { Resource } from '@opentelemetry/resources';
|
|
5
|
+
import type { TracerProvider } from '@opentelemetry/sdk-trace';
|
|
6
|
+
import type { LoggerProvider } from '@opentelemetry/sdk-logs';
|
|
6
7
|
import type { MeterProvider } from '@opentelemetry/sdk-metrics';
|
|
7
8
|
import { captureException } from './errors.js';
|
|
8
9
|
import type { CaptureContext } from './errors.js';
|
|
10
|
+
import { RemoteSampler } from './sampling.js';
|
|
9
11
|
import type { Profiler } from './profiling.js';
|
|
10
12
|
export { captureException, metrics, trace };
|
|
11
13
|
export { setCaptureRules, capturePayload } from './payload.js';
|
|
@@ -13,40 +15,56 @@ export type { CaptureRule } from './payload.js';
|
|
|
13
15
|
export type { CaptureContext };
|
|
14
16
|
export declare const DEFAULT_ENDPOINT = "http://localhost:4318";
|
|
15
17
|
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
|
18
|
+
/** code.filepath/code.lineno of the frame that called `log()` (stack line 0 is "Error", 1 is `log`, 2 the caller). */
|
|
19
|
+
export declare function callerOf(stack: string | undefined): Record<string, string | number>;
|
|
16
20
|
export interface InitOptions {
|
|
17
|
-
/** Ingest key; defaults to WT_INGEST_KEY. */
|
|
21
|
+
/** Ingest key; defaults to WT_INGEST_KEY, then a `Bearer` Authorization in OTEL_EXPORTER_OTLP_HEADERS. */
|
|
18
22
|
apiKey?: string;
|
|
19
23
|
/** Defaults to WT_ENVIRONMENT. */
|
|
20
24
|
environment?: string;
|
|
21
|
-
/** Defaults to WT_RELEASE. */
|
|
25
|
+
/** Sent as `service.version`; the server links an issue's first release by matching it to an existing release's version. Defaults to WT_RELEASE, then `service.version` in OTEL_RESOURCE_ATTRIBUTES. */
|
|
22
26
|
release?: string;
|
|
23
27
|
/** Hook uncaughtException / unhandledRejection (default true). */
|
|
24
28
|
captureProcessErrors?: boolean;
|
|
25
|
-
/** Replace the log exporter (tests). */
|
|
29
|
+
/** Replace the log exporter (tests); setting it turns logs on unless `logs` is false. Exported through a batch processor. */
|
|
26
30
|
logExporter?: unknown;
|
|
27
31
|
/** Export OTLP logs; defaults to WATCHTOWER_LOGS (on unless `off`; OTEL_LOGS_EXPORTER=none also turns it off). */
|
|
28
32
|
logs?: boolean;
|
|
33
|
+
/** Stamp code.filepath/code.lineno of the `log()` caller (reads the stack); defaults to WATCHTOWER_LOG_CALLER=1. */
|
|
34
|
+
logCaller?: boolean;
|
|
29
35
|
/** Export OTLP metrics; defaults to WATCHTOWER_METRICS (on unless `off`; OTEL_METRICS_EXPORTER=none also turns it off). */
|
|
30
36
|
metrics?: boolean;
|
|
31
|
-
/** Replace the metric exporter (tests). */
|
|
37
|
+
/** Replace the metric exporter (tests); setting it turns metrics on unless `metrics` is false. */
|
|
32
38
|
metricExporter?: unknown;
|
|
33
|
-
/** OTLP/HTTP base URL; defaults to WT_OTLP_ENDPOINT
|
|
39
|
+
/** OTLP/HTTP base URL; defaults to WT_OTLP_ENDPOINT, then OTEL_EXPORTER_OTLP_ENDPOINT, then http://localhost:4318. */
|
|
34
40
|
endpoint?: string;
|
|
35
41
|
/** REST API base URL for getPrompt/score; defaults to WT_API_URL or endpoint. */
|
|
36
42
|
apiUrl?: string;
|
|
37
43
|
project?: string;
|
|
38
|
-
/** Defaults to WT_SERVICE. */
|
|
44
|
+
/** Defaults to WT_SERVICE, then OTEL_SERVICE_NAME, then `service.name` in OTEL_RESOURCE_ATTRIBUTES, then `app`. */
|
|
39
45
|
serviceName?: string;
|
|
40
|
-
/** Resource attributes; keys starting with `wt.` are dropped. */
|
|
46
|
+
/** Resource attributes (on top of OTEL_RESOURCE_ATTRIBUTES); keys starting with `wt.` are dropped. */
|
|
41
47
|
resource?: Record<string, string | number | boolean>;
|
|
42
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
* Called before export for every span attribute, every span event's and link's attributes (so `exception.message`
|
|
50
|
+
* and `exception.stacktrace`), the span name (key `span.name`), the status message (`status.message`) and each log
|
|
51
|
+
* body (`log.body`) and log attribute; return the value to keep.
|
|
52
|
+
*/
|
|
43
53
|
redact?: (key: string, value: unknown) => unknown;
|
|
44
54
|
/** Directory for the offline buffer. */
|
|
45
55
|
bufferDir?: string;
|
|
56
|
+
/** Apply the project's head sampling rules in the SDK, polled from /v1/sampling; defaults to WT_REMOTE_SAMPLING=1. Spans dropped here never reach the gateway, so its exact request counts see only what is kept. */
|
|
57
|
+
remoteSampling?: boolean;
|
|
58
|
+
/** Seconds between sampling polls; defaults to WT_SAMPLING_INTERVAL_S or 30. */
|
|
59
|
+
samplingIntervalS?: number;
|
|
60
|
+
/** Stamp code.filepath / code.lineno / code.function on spans (the code that started the span); defaults to WT_CODE_ORIGIN=1. */
|
|
61
|
+
codeOrigin?: boolean;
|
|
46
62
|
/** Fetch the service's payload capture rules (APM-016) and record bodies/GraphQL where a rule matches; defaults to WT_CAPTURE_RULES=1. */
|
|
47
63
|
captureRules?: boolean;
|
|
48
64
|
/** Replace the span exporter (tests). */
|
|
49
65
|
exporter?: unknown;
|
|
66
|
+
/** Patch node:http, fetch (undici), pg and ioredis for those whose `@opentelemetry/instrumentation-*` peer is installed; defaults to on unless WT_INSTRUMENT=0. `init` only: use the `/register` preload so it runs before the app imports them. */
|
|
67
|
+
instrument?: boolean;
|
|
50
68
|
fetch?: typeof fetch;
|
|
51
69
|
}
|
|
52
70
|
export interface EvalRow {
|
|
@@ -76,10 +94,12 @@ export declare class Client {
|
|
|
76
94
|
readonly project: string | undefined;
|
|
77
95
|
readonly headers: {
|
|
78
96
|
Authorization: string;
|
|
79
|
-
}
|
|
97
|
+
} & Record<string, string>;
|
|
80
98
|
readonly fetch: typeof fetch;
|
|
81
99
|
readonly redact: InitOptions['redact'];
|
|
82
|
-
readonly
|
|
100
|
+
private readonly logCaller;
|
|
101
|
+
readonly provider: TracerProvider;
|
|
102
|
+
readonly resource: Resource;
|
|
83
103
|
readonly tracer: Tracer;
|
|
84
104
|
readonly loggerProvider: LoggerProvider;
|
|
85
105
|
readonly logger: ReturnType<LoggerProvider['getLogger']>;
|
|
@@ -87,6 +107,8 @@ export declare class Client {
|
|
|
87
107
|
readonly meterProvider?: MeterProvider;
|
|
88
108
|
private readonly stopRuntime;
|
|
89
109
|
uninstall?: () => void;
|
|
110
|
+
/** Set when remote sampling is on. */
|
|
111
|
+
remoteSampler?: RemoteSampler;
|
|
90
112
|
/** Set when WT_PROFILING=1 started the continuous profiler. */
|
|
91
113
|
profiler?: Promise<Profiler | undefined>;
|
|
92
114
|
constructor(opts: InitOptions);
|