@watchtowerobservability/node 0.5.0 → 0.7.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 +88 -9
- package/dist/cjs/checkin.d.ts +7 -0
- package/dist/cjs/checkin.js +18 -0
- 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/filter.d.ts +2 -0
- package/dist/cjs/filter.js +16 -0
- package/dist/cjs/index.d.ts +48 -10
- package/dist/cjs/index.js +119 -53
- package/dist/cjs/instrument.d.ts +10 -0
- package/dist/cjs/instrument.js +74 -0
- package/dist/cjs/integrations/db.d.ts +3 -0
- package/dist/cjs/integrations/db.js +4 -1
- 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-build.d.ts +31 -0
- package/dist/cjs/integrations/next-build.js +95 -0
- package/dist/cjs/integrations/next-tunnel.d.ts +14 -0
- package/dist/cjs/integrations/next-tunnel.js +52 -0
- package/dist/cjs/integrations/next.d.ts +24 -1
- package/dist/cjs/integrations/next.js +39 -7
- package/dist/cjs/load.js +37 -5
- package/dist/cjs/next-sourcemaps-cli.d.ts +2 -0
- package/dist/cjs/next-sourcemaps-cli.js +9 -0
- 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/cjs/scrub.d.ts +7 -0
- package/dist/cjs/scrub.js +39 -0
- package/dist/cjs/shutdown.d.ts +14 -0
- package/dist/cjs/shutdown.js +26 -0
- package/dist/cjs/sql.js +11 -1
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/esm/checkin.d.ts +7 -0
- package/dist/esm/checkin.js +15 -0
- 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/filter.d.ts +2 -0
- package/dist/esm/filter.js +13 -0
- package/dist/esm/index.d.ts +48 -10
- package/dist/esm/index.js +117 -53
- package/dist/esm/instrument.d.ts +10 -0
- package/dist/esm/instrument.js +71 -0
- package/dist/esm/integrations/db.d.ts +3 -0
- package/dist/esm/integrations/db.js +5 -2
- 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-build.d.ts +31 -0
- package/dist/esm/integrations/next-build.js +58 -0
- package/dist/esm/integrations/next-tunnel.d.ts +14 -0
- package/dist/esm/integrations/next-tunnel.js +49 -0
- package/dist/esm/integrations/next.d.ts +24 -1
- package/dist/esm/integrations/next.js +32 -6
- package/dist/esm/load.js +80 -2
- package/dist/esm/next-sourcemaps-cli.d.ts +2 -0
- package/dist/esm/next-sourcemaps-cli.js +7 -0
- 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/dist/esm/scrub.d.ts +7 -0
- package/dist/esm/scrub.js +34 -0
- package/dist/esm/shutdown.d.ts +14 -0
- package/dist/esm/shutdown.js +23 -0
- package/dist/esm/sql.js +11 -1
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/package.json +40 -2
|
@@ -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;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SpanProcessor } from '@opentelemetry/sdk-trace';
|
|
2
|
+
/** A path segment that reads like a secret or an opaque id: >= 24 chars, or >= 10 chars mixing a letter and a digit (UUIDs included). */
|
|
3
|
+
export declare function looksSecret(seg: string): boolean;
|
|
4
|
+
/** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. */
|
|
5
|
+
export declare function scrubUrl(value: string): string;
|
|
6
|
+
/** Span processor: scrubs URL attributes (query dropped, `url.query` removed, secret path segments redacted) and URLs inside the span name. `http.route` is kept. */
|
|
7
|
+
export declare function urlScrubber(): SpanProcessor;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.looksSecret = looksSecret;
|
|
4
|
+
exports.scrubUrl = scrubUrl;
|
|
5
|
+
exports.urlScrubber = urlScrubber;
|
|
6
|
+
const URL_KEYS = ['http.target', 'url.full', 'url.path', 'http.url', 'http.request.url'];
|
|
7
|
+
const QUERY_KEYS = ['url.query'];
|
|
8
|
+
/** A path segment that reads like a secret or an opaque id: >= 24 chars, or >= 10 chars mixing a letter and a digit (UUIDs included). */
|
|
9
|
+
function looksSecret(seg) {
|
|
10
|
+
return seg.length >= 24 || (seg.length >= 10 && /[A-Za-z]/.test(seg) && /\d/.test(seg));
|
|
11
|
+
}
|
|
12
|
+
/** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. */
|
|
13
|
+
function scrubUrl(value) {
|
|
14
|
+
const m = /^(?:([a-z][a-z0-9+.-]*:\/\/)([^/?#]*))?([^?#]*)/i.exec(value);
|
|
15
|
+
const origin = m[1] ? m[1] + m[2].replace(/^[^@]*@/, '') : '';
|
|
16
|
+
return origin + m[3].split('/').map((s) => (looksSecret(s) ? ':redacted' : s)).join('/');
|
|
17
|
+
}
|
|
18
|
+
function scrubName(name) {
|
|
19
|
+
return name.split(' ').map((t) => (/^(https?:\/\/|\/)/i.test(t) ? scrubUrl(t) : t)).join(' ');
|
|
20
|
+
}
|
|
21
|
+
/** Span processor: scrubs URL attributes (query dropped, `url.query` removed, secret path segments redacted) and URLs inside the span name. `http.route` is kept. */
|
|
22
|
+
function urlScrubber() {
|
|
23
|
+
return {
|
|
24
|
+
onStart() { },
|
|
25
|
+
onEnd(span) {
|
|
26
|
+
const a = span.attributes;
|
|
27
|
+
for (const k of URL_KEYS)
|
|
28
|
+
if (typeof a[k] === 'string')
|
|
29
|
+
a[k] = scrubUrl(a[k]);
|
|
30
|
+
for (const k of QUERY_KEYS)
|
|
31
|
+
delete a[k];
|
|
32
|
+
const n = scrubName(span.name);
|
|
33
|
+
if (n !== span.name)
|
|
34
|
+
span.name = n;
|
|
35
|
+
},
|
|
36
|
+
shutdown: () => Promise.resolve(),
|
|
37
|
+
forceFlush: () => Promise.resolve(),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface SignalProc {
|
|
2
|
+
on(event: string, l: () => void): unknown;
|
|
3
|
+
off(event: string, l: () => void): unknown;
|
|
4
|
+
listenerCount(event: string): number;
|
|
5
|
+
kill(pid: number, signal: string): unknown;
|
|
6
|
+
readonly pid: number;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* On SIGTERM and SIGINT: flush (at most `timeoutMs`). Adding a signal listener turns off Node's default exit, so when
|
|
10
|
+
* ours is the only listener it removes itself and re-sends the signal after the flush; when the app or a framework
|
|
11
|
+
* (`next start`) has its own handler, that handler decides how the process ends and ours only starts the flush.
|
|
12
|
+
* Returns the uninstall function.
|
|
13
|
+
*/
|
|
14
|
+
export declare function installSignalFlush(flush: () => Promise<unknown>, timeoutMs?: number, proc?: SignalProc): () => void;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Flush on SIGTERM / SIGINT without changing how the process ends.
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.installSignalFlush = installSignalFlush;
|
|
5
|
+
/**
|
|
6
|
+
* On SIGTERM and SIGINT: flush (at most `timeoutMs`). Adding a signal listener turns off Node's default exit, so when
|
|
7
|
+
* ours is the only listener it removes itself and re-sends the signal after the flush; when the app or a framework
|
|
8
|
+
* (`next start`) has its own handler, that handler decides how the process ends and ours only starts the flush.
|
|
9
|
+
* Returns the uninstall function.
|
|
10
|
+
*/
|
|
11
|
+
function installSignalFlush(flush, timeoutMs = 2000, proc = process) {
|
|
12
|
+
const handlers = new Map();
|
|
13
|
+
for (const sig of ['SIGTERM', 'SIGINT']) {
|
|
14
|
+
const h = () => {
|
|
15
|
+
const alone = proc.listenerCount(sig) <= 1;
|
|
16
|
+
const done = Promise.race([flush().catch(() => undefined), new Promise((r) => setTimeout(r, timeoutMs).unref())]);
|
|
17
|
+
if (!alone)
|
|
18
|
+
return;
|
|
19
|
+
void done.finally(() => { proc.off(sig, h); proc.kill(proc.pid, sig); });
|
|
20
|
+
};
|
|
21
|
+
handlers.set(sig, h);
|
|
22
|
+
proc.on(sig, h);
|
|
23
|
+
}
|
|
24
|
+
return () => { for (const [sig, h] of handlers)
|
|
25
|
+
proc.off(sig, h); };
|
|
26
|
+
}
|
package/dist/cjs/sql.js
CHANGED
|
@@ -212,9 +212,19 @@ function normalizeAndHash(stmt, pg = false) {
|
|
|
212
212
|
const isPgDialect = (system) => system === 'postgresql' || system === 'cockroachdb' || system === 'redshift';
|
|
213
213
|
exports.isPgDialect = isPgDialect;
|
|
214
214
|
const OP = /^\s*(?:with\b[\s\S]*?\)\s*)?([a-z]+)/i;
|
|
215
|
-
const
|
|
215
|
+
const NAME = '(?:"[^"]+"|[\\w$]+)(?:\\.(?:"[^"]+"|[\\w$]+))?';
|
|
216
|
+
const TARGET = new RegExp(`\\b(?:from|into|update|join|table)\\s+(?:if\\s+(?:not\\s+)?exists\\s+)?(${NAME})`, 'i');
|
|
217
|
+
// DDL: `CREATE [TEMP|VIRTUAL|UNIQUE...] TABLE|INDEX|VIEW [IF NOT EXISTS] name [ON table]`; an index is named after its table
|
|
218
|
+
const CREATE = new RegExp(`^\\s*create\\s+(?:(?:temp|temporary|virtual|unique|fulltext|spatial|clustered|nonclustered|materialized|or\\s+replace)\\s+)*(table|index|view)\\s+(?:if\\s+not\\s+exists\\s+)?(?:concurrently\\s+)?(${NAME})(?:\\s+on\\s+(?:only\\s+)?(${NAME}))?`, 'i');
|
|
216
219
|
/** `SELECT users`-style summary: the operation and first table, never values or the statement text. */
|
|
217
220
|
function querySummary(text, fallback = 'postgres') {
|
|
221
|
+
const ddl = text?.match(CREATE);
|
|
222
|
+
if (ddl) {
|
|
223
|
+
const kind = ddl[1].toLowerCase();
|
|
224
|
+
const operation = `CREATE ${kind.toUpperCase()}`;
|
|
225
|
+
const target = (kind === 'index' ? ddl[3] ?? ddl[2] : ddl[2]).replace(/"/g, '');
|
|
226
|
+
return { operation, target, summary: `${operation} ${target}` };
|
|
227
|
+
}
|
|
218
228
|
const operation = text?.match(OP)?.[1]?.toUpperCase();
|
|
219
229
|
const target = text?.match(TARGET)?.[1]?.replace(/"/g, '');
|
|
220
230
|
return { operation, target, summary: [operation ?? fallback, target].filter(Boolean).join(' ') };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface CheckinTarget {
|
|
2
|
+
endpoint: string;
|
|
3
|
+
headers: Record<string, string>;
|
|
4
|
+
fetch: typeof fetch;
|
|
5
|
+
}
|
|
6
|
+
/** 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. */
|
|
7
|
+
export declare function checkin<T>(c: CheckinTarget, slug: string, fn: () => T | Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** 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
|
+
}
|
|
15
|
+
}
|
|
@@ -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)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function filterExporter(inner, keep) {
|
|
2
|
+
return {
|
|
3
|
+
export(spans, done) {
|
|
4
|
+
const kept = spans.filter(keep);
|
|
5
|
+
if (kept.length)
|
|
6
|
+
inner.export(kept, done);
|
|
7
|
+
else
|
|
8
|
+
done({ code: 0 });
|
|
9
|
+
},
|
|
10
|
+
shutdown: () => inner.shutdown(),
|
|
11
|
+
forceFlush: () => inner.forceFlush?.() ?? Promise.resolve(),
|
|
12
|
+
};
|
|
13
|
+
}
|