@obzerver/node 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +97 -2
- package/dist/agent-types.d.ts +28 -0
- package/dist/agent-types.js +6 -0
- package/dist/agent-types.js.map +1 -0
- package/dist/agent.d.ts +97 -0
- package/dist/agent.js +651 -0
- package/dist/agent.js.map +1 -0
- package/dist/context.d.ts +86 -0
- package/dist/context.js +136 -0
- package/dist/context.js.map +1 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.js +108 -0
- package/dist/errors.js.map +1 -0
- package/dist/glob.d.ts +7 -0
- package/dist/glob.js +56 -0
- package/dist/glob.js.map +1 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +89 -0
- package/dist/index.js.map +1 -0
- package/dist/instrument/classes.d.ts +18 -0
- package/dist/instrument/classes.js +103 -0
- package/dist/instrument/classes.js.map +1 -0
- package/dist/instrument/console.d.ts +11 -0
- package/dist/instrument/console.js +68 -0
- package/dist/instrument/console.js.map +1 -0
- package/dist/instrument/db.d.ts +7 -0
- package/dist/instrument/db.js +155 -0
- package/dist/instrument/db.js.map +1 -0
- package/dist/instrument/express.d.ts +3 -0
- package/dist/instrument/express.js +133 -0
- package/dist/instrument/express.js.map +1 -0
- package/dist/instrument/fastify.d.ts +35 -0
- package/dist/instrument/fastify.js +88 -0
- package/dist/instrument/fastify.js.map +1 -0
- package/dist/instrument/http.d.ts +10 -0
- package/dist/instrument/http.js +149 -0
- package/dist/instrument/http.js.map +1 -0
- package/dist/instrument/jobs.d.ts +15 -0
- package/dist/instrument/jobs.js +90 -0
- package/dist/instrument/jobs.js.map +1 -0
- package/dist/options.d.ts +110 -0
- package/dist/options.js +3 -0
- package/dist/options.js.map +1 -0
- package/dist/protocol.d.ts +146 -0
- package/dist/protocol.js +4 -0
- package/dist/protocol.js.map +1 -0
- package/dist/redact.d.ts +12 -0
- package/dist/redact.js +54 -0
- package/dist/redact.js.map +1 -0
- package/dist/register.d.ts +1 -0
- package/dist/register.js +9 -0
- package/dist/register.js.map +1 -0
- package/dist/release.d.ts +32 -0
- package/dist/release.js +141 -0
- package/dist/release.js.map +1 -0
- package/dist/runtime.d.ts +37 -0
- package/dist/runtime.js +142 -0
- package/dist/runtime.js.map +1 -0
- package/dist/transport.d.ts +32 -0
- package/dist/transport.js +122 -0
- package/dist/transport.js.map +1 -0
- package/package.json +51 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Agent = exports.flush = exports.pino = exports.fastify = exports.metrics = exports.bullmq = exports.cron = exports.job = exports.currentTraceId = exports.log = exports.captureError = exports.setUser = exports.tag = exports.instrument = exports.wrap = exports.startSpan = exports.span = exports.init = void 0;
|
|
4
|
+
const agent_1 = require("./agent");
|
|
5
|
+
Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return agent_1.Agent; } });
|
|
6
|
+
const ctx = require("./context");
|
|
7
|
+
const express_1 = require("./instrument/express");
|
|
8
|
+
const fastify_1 = require("./instrument/fastify");
|
|
9
|
+
const console_1 = require("./instrument/console");
|
|
10
|
+
const classes_1 = require("./instrument/classes");
|
|
11
|
+
let agent = null;
|
|
12
|
+
const getAgent = () => agent;
|
|
13
|
+
const noopSpan = { end() { }, setAttr: () => noopSpan, addTags: () => noopSpan, fail: () => noopSpan };
|
|
14
|
+
const noop = { inc() { }, set() { }, observe() { } };
|
|
15
|
+
const obzerver = {
|
|
16
|
+
init(options = {}) {
|
|
17
|
+
if (!agent)
|
|
18
|
+
agent = new agent_1.Agent(options).start();
|
|
19
|
+
return obzerver;
|
|
20
|
+
},
|
|
21
|
+
get agent() { return agent; },
|
|
22
|
+
span(name, fn, attrs) { return ctx.runSpan(name, 'custom', fn, attrs); },
|
|
23
|
+
startSpan(name, attrs) {
|
|
24
|
+
const s = ctx.startSpan(name, 'custom', attrs);
|
|
25
|
+
if (!s)
|
|
26
|
+
return noopSpan;
|
|
27
|
+
const h = {
|
|
28
|
+
end: (err) => { if (err)
|
|
29
|
+
s.fail(err); s.finish(); },
|
|
30
|
+
setAttr: (k, v) => { s.setAttr(k, v); return h; },
|
|
31
|
+
addTags: (t) => { s.addTags(t); return h; },
|
|
32
|
+
fail: (e) => { s.fail(e); return h; },
|
|
33
|
+
};
|
|
34
|
+
return h;
|
|
35
|
+
},
|
|
36
|
+
wrap(name, fn, kind = 'function') {
|
|
37
|
+
const w = function (...args) { return ctx.runSpan(name, kind, fn, undefined, this, args); };
|
|
38
|
+
Object.defineProperty(w, 'length', { value: fn.length });
|
|
39
|
+
return w;
|
|
40
|
+
},
|
|
41
|
+
instrument(target, name) {
|
|
42
|
+
if (typeof target === 'function' && target.prototype)
|
|
43
|
+
(0, classes_1.wrapMethods)(target.prototype, name || target.name);
|
|
44
|
+
else if (target && typeof target === 'object')
|
|
45
|
+
(0, classes_1.wrapMethods)(target, name || target.constructor?.name || 'object');
|
|
46
|
+
return target;
|
|
47
|
+
},
|
|
48
|
+
tag(key, value) {
|
|
49
|
+
const s = ctx.current();
|
|
50
|
+
if (!s)
|
|
51
|
+
return;
|
|
52
|
+
if (typeof key === 'object')
|
|
53
|
+
Object.assign(s.trace.tags, key);
|
|
54
|
+
else
|
|
55
|
+
s.trace.tags[key] = value;
|
|
56
|
+
},
|
|
57
|
+
setUser(id) { const t = ctx.currentTrace(); if (t)
|
|
58
|
+
t.userId = id == null ? null : String(id); },
|
|
59
|
+
captureError(err, extra) { agent?.captureError(err, extra); },
|
|
60
|
+
log(level, message, attrs) { agent?.recordLog(level, message, 'app', attrs); },
|
|
61
|
+
currentTraceId() { return agent ? agent.currentTraceId() : null; },
|
|
62
|
+
job(name, fn, opts) { return agent ? agent.job(name, fn, opts) : fn; },
|
|
63
|
+
cron(name, fn) { return obzerver.job(name, fn, { queue: 'cron' }); },
|
|
64
|
+
bullmq(processor, opts = {}) {
|
|
65
|
+
return obzerver.job(opts.name || processor.name || 'job', processor, {
|
|
66
|
+
meta: (job) => ({
|
|
67
|
+
name: job?.name,
|
|
68
|
+
queue: job?.queueName || opts.queue,
|
|
69
|
+
attempt: job ? (job.attemptsMade || 0) + 1 : 1,
|
|
70
|
+
queueWait: job?.timestamp ? Math.max(0, (job.processedOn || Date.now()) - job.timestamp) : null,
|
|
71
|
+
}),
|
|
72
|
+
});
|
|
73
|
+
},
|
|
74
|
+
metrics: {
|
|
75
|
+
counter: (name, labels) => agent?.metrics?.counter(name, labels) ?? noop,
|
|
76
|
+
gauge: (name, labels) => agent?.metrics?.gauge(name, labels) ?? noop,
|
|
77
|
+
summary: (name, labels) => agent?.metrics?.summary(name, labels) ?? noop,
|
|
78
|
+
},
|
|
79
|
+
express(expressModule) { if (agent)
|
|
80
|
+
(0, express_1.instrumentExpress)(agent, expressModule); return expressModule; },
|
|
81
|
+
fastify: (0, fastify_1.fastifyPlugin)(getAgent),
|
|
82
|
+
pino: () => (0, console_1.pinoOptions)(getAgent),
|
|
83
|
+
flush() { return agent ? agent.shutdown() : Promise.resolve(); },
|
|
84
|
+
};
|
|
85
|
+
// CommonJS consumers get the API object itself (`require('@obzerver/node').init()`),
|
|
86
|
+
// ESM consumers can use the default export or named functions.
|
|
87
|
+
exports.default = obzerver;
|
|
88
|
+
exports.init = obzerver.init, exports.span = obzerver.span, exports.startSpan = obzerver.startSpan, exports.wrap = obzerver.wrap, exports.instrument = obzerver.instrument, exports.tag = obzerver.tag, exports.setUser = obzerver.setUser, exports.captureError = obzerver.captureError, exports.log = obzerver.log, exports.currentTraceId = obzerver.currentTraceId, exports.job = obzerver.job, exports.cron = obzerver.cron, exports.bullmq = obzerver.bullmq, exports.metrics = obzerver.metrics, exports.fastify = obzerver.fastify, exports.pino = obzerver.pino, exports.flush = obzerver.flush;
|
|
89
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","s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;QAAE,IAAA,2BAAiB,EAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,OAAO,aAAa,CAAC,CAAC,CAAC;IACpG,OAAO,EAAE,IAAA,uBAAa,EAAC,QAAQ,CAAC;IAChC,IAAI,EAAE,GAAG,EAAE,CAAC,IAAA,qBAAW,EAAC,QAAQ,CAAC;IACjC,KAAK,KAAK,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;CACjE,CAAC;AAEF,qFAAqF;AACrF,+DAA+D;AAC/D,kBAAe,QAAQ,CAAC;AACT,YAAI,GAA2I,QAAQ,OAAjJ,YAAI,GAAqI,QAAQ,OAA3I,iBAAS,GAA0H,QAAQ,YAAhI,YAAI,GAAoH,QAAQ,OAA1H,kBAAU,GAAwG,QAAQ,aAA9G,WAAG,GAAmG,QAAQ,MAAzG,eAAO,GAA0F,QAAQ,UAAhG,oBAAY,GAA4E,QAAQ,eAAlF,WAAG,GAAuE,QAAQ,MAA7E,sBAAc,GAAuD,QAAQ,iBAA7D,WAAG,GAAkD,QAAQ,MAAxD,YAAI,GAA4C,QAAQ,OAAlD,cAAM,GAAoC,QAAQ,SAA1C,eAAO,GAA2B,QAAQ,UAAjC,eAAO,GAAkB,QAAQ,UAAxB,YAAI,GAAY,QAAQ,OAAlB,aAAK,GAAK,QAAQ,OAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wrap every method on `target` and the user-defined part of its prototype chain as a timed span
|
|
3
|
+
* named `<prefix>.<method>`. Stops at built-in prototypes, so `class X extends Error` never wraps
|
|
4
|
+
* Error.prototype for the whole process. Idempotent.
|
|
5
|
+
*/
|
|
6
|
+
export declare function wrapMethods(target: object, prefix: string): void;
|
|
7
|
+
/** True for `class X {}` (not plain functions, arrow functions or bound functions). */
|
|
8
|
+
export declare function isClass(v: unknown): v is new (...a: unknown[]) => unknown;
|
|
9
|
+
/** Instrument every class among a module's exports (or the export itself). Returns the class names wrapped. */
|
|
10
|
+
export declare function instrumentExports(exports: unknown): string[];
|
|
11
|
+
/** The global hook that transformed ES modules call at the end of their body. */
|
|
12
|
+
export declare const AUTO_INSTRUMENT_HOOK: unique symbol;
|
|
13
|
+
/**
|
|
14
|
+
* Source to append to a matching module so its classes reach the SDK once the module has run.
|
|
15
|
+
* ES modules: names its top-level classes (a `typeof` guard keeps a wrong guess harmless).
|
|
16
|
+
* CommonJS: hands over `module.exports`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function autoInstrumentSuffix(source: string, format: string | null | undefined, file: string): string | null;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AUTO_INSTRUMENT_HOOK = void 0;
|
|
4
|
+
exports.wrapMethods = wrapMethods;
|
|
5
|
+
exports.isClass = isClass;
|
|
6
|
+
exports.instrumentExports = instrumentExports;
|
|
7
|
+
exports.autoInstrumentSuffix = autoInstrumentSuffix;
|
|
8
|
+
const ctx = require("../context");
|
|
9
|
+
/** A prototype owned by the runtime or a built-in class (Error, Map, EventEmitter's natives…), never wrapped. */
|
|
10
|
+
function isBuiltinPrototype(proto) {
|
|
11
|
+
const ctor = Object.getOwnPropertyDescriptor(proto, 'constructor')?.value;
|
|
12
|
+
if (typeof ctor !== 'function')
|
|
13
|
+
return false;
|
|
14
|
+
try {
|
|
15
|
+
return /\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(ctor));
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Wrap every method on `target` and the user-defined part of its prototype chain as a timed span
|
|
23
|
+
* named `<prefix>.<method>`. Stops at built-in prototypes, so `class X extends Error` never wraps
|
|
24
|
+
* Error.prototype for the whole process. Idempotent.
|
|
25
|
+
*/
|
|
26
|
+
function wrapMethods(target, prefix) {
|
|
27
|
+
const seen = new Set();
|
|
28
|
+
let proto = target;
|
|
29
|
+
while (proto && proto !== Object.prototype && proto !== Function.prototype && !isBuiltinPrototype(proto)) {
|
|
30
|
+
for (const key of Object.getOwnPropertyNames(proto)) {
|
|
31
|
+
if (key === 'constructor' || seen.has(key))
|
|
32
|
+
continue;
|
|
33
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
34
|
+
if (!desc || typeof desc.value !== 'function' || desc.value.__obzerver)
|
|
35
|
+
continue;
|
|
36
|
+
seen.add(key);
|
|
37
|
+
const fn = desc.value;
|
|
38
|
+
const name = `${prefix}.${key}`;
|
|
39
|
+
const w = function (...args) { return ctx.runSpan(name, 'function', fn, { class: prefix, method: key }, this, args); };
|
|
40
|
+
Object.defineProperty(w, 'name', { value: key });
|
|
41
|
+
Object.defineProperty(w, 'length', { value: fn.length });
|
|
42
|
+
w.__obzerver = true;
|
|
43
|
+
Object.defineProperty(proto, key, { ...desc, value: w });
|
|
44
|
+
}
|
|
45
|
+
proto = Object.getPrototypeOf(proto);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** True for `class X {}` (not plain functions, arrow functions or bound functions). */
|
|
49
|
+
function isClass(v) {
|
|
50
|
+
if (typeof v !== 'function')
|
|
51
|
+
return false;
|
|
52
|
+
try {
|
|
53
|
+
return /^class[\s{]/.test(Function.prototype.toString.call(v));
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Instrument every class among a module's exports (or the export itself). Returns the class names wrapped. */
|
|
60
|
+
function instrumentExports(exports) {
|
|
61
|
+
const done = [];
|
|
62
|
+
const visit = (v) => {
|
|
63
|
+
if (!isClass(v) || done.includes(v.name))
|
|
64
|
+
return;
|
|
65
|
+
wrapMethods(v.prototype, v.name || 'anonymous');
|
|
66
|
+
done.push(v.name);
|
|
67
|
+
};
|
|
68
|
+
visit(exports);
|
|
69
|
+
if (exports && (typeof exports === 'object' || typeof exports === 'function')) {
|
|
70
|
+
for (const key of Object.keys(exports)) {
|
|
71
|
+
try {
|
|
72
|
+
visit(exports[key]);
|
|
73
|
+
}
|
|
74
|
+
catch { /* getter threw */ }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return done;
|
|
78
|
+
}
|
|
79
|
+
/** The global hook that transformed ES modules call at the end of their body. */
|
|
80
|
+
exports.AUTO_INSTRUMENT_HOOK = Symbol.for('obzerver.autoInstrument');
|
|
81
|
+
// Top-level class declarations: `class X`, `export class X`, `export default class X`, `export abstract class X`.
|
|
82
|
+
const TOP_LEVEL_CLASS = /^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/gm;
|
|
83
|
+
/**
|
|
84
|
+
* Source to append to a matching module so its classes reach the SDK once the module has run.
|
|
85
|
+
* ES modules: names its top-level classes (a `typeof` guard keeps a wrong guess harmless).
|
|
86
|
+
* CommonJS: hands over `module.exports`.
|
|
87
|
+
*/
|
|
88
|
+
function autoInstrumentSuffix(source, format, file) {
|
|
89
|
+
const call = `globalThis[Symbol.for('obzerver.autoInstrument')]`;
|
|
90
|
+
if (format === 'commonjs' || format === 'commonjs-typescript') {
|
|
91
|
+
return `\n;${call}?.(${JSON.stringify(file)}, module.exports);\n`;
|
|
92
|
+
}
|
|
93
|
+
if (format !== 'module' && format !== 'module-typescript')
|
|
94
|
+
return null;
|
|
95
|
+
const names = new Set();
|
|
96
|
+
for (const m of source.matchAll(TOP_LEVEL_CLASS))
|
|
97
|
+
names.add(m[1]);
|
|
98
|
+
if (!names.size)
|
|
99
|
+
return null;
|
|
100
|
+
const fields = [...names].map((n) => `${n}: typeof ${n} === 'undefined' ? undefined : ${n}`).join(', ');
|
|
101
|
+
return `\n;${call}?.(${JSON.stringify(file)}, { ${fields} });\n`;
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=classes.js.map
|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ACvE,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAC;IAChC,KAAK,MAAM,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC;QAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAClE,IAAI,CAAC,KAAK,CAAC,IAAI;QAAE,OAAO,IAAI,CAAC;IAC7B,MAAM,MAAM,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,YAAY,CAAC,kCAAkC,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxG,OAAO,MAAM,IAAI,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,MAAM,QAAQ,CAAC;AACnE,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { AgentHooks } from '../agent-types';
|
|
2
|
+
/** Forward console output (still printed as usual), correlated to the active trace. */
|
|
3
|
+
export declare function patchConsole(agent: AgentHooks): void;
|
|
4
|
+
export interface PinoOptions {
|
|
5
|
+
mixin(): Record<string, unknown>;
|
|
6
|
+
hooks: {
|
|
7
|
+
logMethod(this: unknown, args: unknown[], method: (...a: unknown[]) => void, level: number): void;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
/** Options to spread into pino() / Fastify's logger: adds traceId to every line and forwards it. */
|
|
11
|
+
export declare function pinoOptions(agentGetter: () => AgentHooks | null): PinoOptions;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.patchConsole = patchConsole;
|
|
4
|
+
exports.pinoOptions = pinoOptions;
|
|
5
|
+
const util = require("node:util");
|
|
6
|
+
const kPatched = Symbol.for('obzerver.console.patched');
|
|
7
|
+
const LEVELS = { debug: 'debug', log: 'info', info: 'info', warn: 'warn', error: 'error', trace: 'debug' };
|
|
8
|
+
/** Forward console output (still printed as usual), correlated to the active trace. */
|
|
9
|
+
function patchConsole(agent) {
|
|
10
|
+
const c = console;
|
|
11
|
+
if (c[kPatched])
|
|
12
|
+
return;
|
|
13
|
+
for (const method of Object.keys(LEVELS)) {
|
|
14
|
+
const orig = c[method];
|
|
15
|
+
if (typeof orig !== 'function')
|
|
16
|
+
continue;
|
|
17
|
+
c[method] = function (...args) {
|
|
18
|
+
if (agent.inLog) {
|
|
19
|
+
orig.apply(this, args);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
agent.inLog = true;
|
|
23
|
+
try {
|
|
24
|
+
orig.apply(this, args);
|
|
25
|
+
agent.recordLog(LEVELS[method], util.format(...args), 'console');
|
|
26
|
+
}
|
|
27
|
+
catch { /* never break logging */ }
|
|
28
|
+
finally {
|
|
29
|
+
agent.inLog = false;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
c[kPatched] = true;
|
|
34
|
+
}
|
|
35
|
+
const PINO_LEVELS = { 10: 'trace', 20: 'debug', 30: 'info', 40: 'warn', 50: 'error', 60: 'fatal' };
|
|
36
|
+
/** Options to spread into pino() / Fastify's logger: adds traceId to every line and forwards it. */
|
|
37
|
+
function pinoOptions(agentGetter) {
|
|
38
|
+
return {
|
|
39
|
+
mixin() {
|
|
40
|
+
const t = agentGetter()?.currentTraceId();
|
|
41
|
+
return t ? { traceId: t } : {};
|
|
42
|
+
},
|
|
43
|
+
hooks: {
|
|
44
|
+
logMethod(args, method, level) {
|
|
45
|
+
const a = agentGetter();
|
|
46
|
+
if (a) {
|
|
47
|
+
try {
|
|
48
|
+
let attrs;
|
|
49
|
+
let msgArgs = args;
|
|
50
|
+
if (args[0] && typeof args[0] === 'object') {
|
|
51
|
+
attrs = args[0];
|
|
52
|
+
msgArgs = args.slice(1);
|
|
53
|
+
}
|
|
54
|
+
if (attrs instanceof Error) {
|
|
55
|
+
a.captureError(attrs);
|
|
56
|
+
attrs = { err: attrs.message };
|
|
57
|
+
}
|
|
58
|
+
const bindings = this?.bindings?.();
|
|
59
|
+
a.recordLog(PINO_LEVELS[level] || 'info', util.format(...msgArgs), bindings?.name || 'pino', attrs);
|
|
60
|
+
}
|
|
61
|
+
catch { /* ignore */ }
|
|
62
|
+
}
|
|
63
|
+
method.apply(this, args);
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=console.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"console.js","sourceRoot":"","sources":["../../src/instrument/console.ts"],"names":[],"mappings":";;AAQA,oCAkBC;AAUD,kCAuBC;AA3DD,kCAAkC;AAGlC,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;AACxD,MAAM,MAAM,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAW,CAAC;AAGpH,uFAAuF;AACvF,SAAgB,YAAY,CAAC,KAAiB;IAC5C,MAAM,CAAC,GAAG,OAA6C,CAAC;IACxD,IAAI,CAAC,CAAC,QAAQ,CAAC;QAAE,OAAO;IACxB,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAoB,EAAE,CAAC;QAC5D,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAA8B,CAAC;QACpD,IAAI,OAAO,IAAI,KAAK,UAAU;YAAE,SAAS;QACzC,CAAC,CAAC,MAAM,CAAC,GAAG,UAAyB,GAAG,IAAe;YACrD,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;gBAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;gBAAC,OAAO;YAAC,CAAC;YACpD,KAAK,CAAC,KAAK,GA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4BAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;wBAAC,CAAC;wBACpH,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;4BAAC,CAAC,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;4BAAC,KAAK,GAAG,EAAE,GAAG,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;wBAAC,CAAC;wBACtF,MAAM,QAAQ,GAAI,IAA2D,EAAE,QAAQ,EAAE,EAAE,CAAC;wBAC5F,CAAC,CAAC,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,EAAE,QAAQ,EAAE,IAAI,IAAI,MAAM,EAAE,KAAK,CAAC,CAAC;oBACtG,CAAC;oBAAC,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC;gBAC1B,CAAC;gBACD,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAC3B,CAAC;SACF;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Strip literal values from a statement so nothing sensitive leaves the process. */
|
|
2
|
+
export declare function normalizeSql(sql: string): string;
|
|
3
|
+
/** "SELECT orders", "INSERT order_items", "UPDATE users" */
|
|
4
|
+
export declare function summarizeSql(sql: string): string;
|
|
5
|
+
export declare function patchPg(pg: unknown): boolean;
|
|
6
|
+
export declare function patchMysql2(mysql: unknown): boolean;
|
|
7
|
+
export declare function patchIoredis(Redis: unknown): boolean;
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.normalizeSql = normalizeSql;
|
|
4
|
+
exports.summarizeSql = summarizeSql;
|
|
5
|
+
exports.patchPg = patchPg;
|
|
6
|
+
exports.patchMysql2 = patchMysql2;
|
|
7
|
+
exports.patchIoredis = patchIoredis;
|
|
8
|
+
const context_1 = require("../context");
|
|
9
|
+
const kPatched = Symbol.for('obzerver.db.patched');
|
|
10
|
+
const isEmitter = (v) => !!v && typeof v.once === 'function';
|
|
11
|
+
/** Strip literal values from a statement so nothing sensitive leaves the process. */
|
|
12
|
+
function normalizeSql(sql) {
|
|
13
|
+
return String(sql)
|
|
14
|
+
.replace(/'(?:[^'\\]|\\.|'')*'/g, '?')
|
|
15
|
+
.replace(/"(?:[^"\\]|\\.)*"(?=\s*(?:=|,|\)|$))/g, '?')
|
|
16
|
+
.replace(/\$\d+/g, '?')
|
|
17
|
+
.replace(/\b\d+(?:\.\d+)?\b/g, '?')
|
|
18
|
+
.replace(/\(\s*\?(?:\s*,\s*\?)+\s*\)/g, '(?)')
|
|
19
|
+
.replace(/\s+/g, ' ')
|
|
20
|
+
.trim()
|
|
21
|
+
.slice(0, 2000);
|
|
22
|
+
}
|
|
23
|
+
/** "SELECT orders", "INSERT order_items", "UPDATE users" */
|
|
24
|
+
function summarizeSql(sql) {
|
|
25
|
+
const s = String(sql).trim();
|
|
26
|
+
const verb = (/^\s*(\w+)/.exec(s)?.[1] ?? 'QUERY').toUpperCase();
|
|
27
|
+
const table = /\b(?:from|into|update|join|table)\s+[`"[]?([\w.]+)/i.exec(s)?.[1];
|
|
28
|
+
return table ? `${verb} ${table.replace(/^public\./, '')}` : verb;
|
|
29
|
+
}
|
|
30
|
+
function dbSpan(system, statement, extra) {
|
|
31
|
+
if (system === 'redis')
|
|
32
|
+
return (0, context_1.startSpan)(`redis ${statement}`, 'db', { system, statement, ...extra });
|
|
33
|
+
const norm = normalizeSql(statement);
|
|
34
|
+
return (0, context_1.startSpan)(summarizeSql(norm), 'db', { system, statement: norm, ...extra });
|
|
35
|
+
}
|
|
36
|
+
/** Wrap the trailing callback of a driver call so it finishes the span. */
|
|
37
|
+
function wrapCallback(args, span, rowsOf) {
|
|
38
|
+
const i = args.findIndex((a) => typeof a === 'function');
|
|
39
|
+
if (i < 0)
|
|
40
|
+
return false;
|
|
41
|
+
const ucb = args[i];
|
|
42
|
+
args[i] = function (err, res, ...rest) {
|
|
43
|
+
if (err)
|
|
44
|
+
span.fail(err);
|
|
45
|
+
else {
|
|
46
|
+
const n = rowsOf(res);
|
|
47
|
+
if (n !== undefined)
|
|
48
|
+
span.attrs.rows = n;
|
|
49
|
+
}
|
|
50
|
+
span.finish();
|
|
51
|
+
return ucb.call(this, err, res, ...rest);
|
|
52
|
+
};
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
const pgRows = (r) => (r && typeof r.rowCount === 'number' ? r.rowCount : undefined);
|
|
56
|
+
function patchPg(pg) {
|
|
57
|
+
const mod = pg;
|
|
58
|
+
const Client = mod.Client || mod.default?.Client;
|
|
59
|
+
if (!Client || Client.prototype.query[kPatched])
|
|
60
|
+
return false;
|
|
61
|
+
const orig = Client.prototype.query;
|
|
62
|
+
const query = function (...args) {
|
|
63
|
+
const config = args[0];
|
|
64
|
+
const text = typeof config === 'string' ? config : config?.text;
|
|
65
|
+
if (!text)
|
|
66
|
+
return orig.apply(this, args);
|
|
67
|
+
const span = dbSpan('postgres', text, { db: this.database, host: this.host });
|
|
68
|
+
if (!span)
|
|
69
|
+
return orig.apply(this, args);
|
|
70
|
+
if (wrapCallback(args, span, pgRows))
|
|
71
|
+
return orig.apply(this, args);
|
|
72
|
+
let out;
|
|
73
|
+
try {
|
|
74
|
+
out = orig.apply(this, args);
|
|
75
|
+
}
|
|
76
|
+
catch (e) {
|
|
77
|
+
span.fail(e).finish();
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
if ((0, context_1.isThenable)(out)) {
|
|
81
|
+
out.then((r) => { const n = pgRows(r); if (n !== undefined)
|
|
82
|
+
span.attrs.rows = n; span.finish(); }, (e) => span.fail(e).finish());
|
|
83
|
+
}
|
|
84
|
+
else if (isEmitter(out)) { // Submittable (cursor, stream)
|
|
85
|
+
out.once('end', () => span.finish());
|
|
86
|
+
out.once('error', (e) => span.fail(e).finish());
|
|
87
|
+
}
|
|
88
|
+
else
|
|
89
|
+
span.finish();
|
|
90
|
+
return out;
|
|
91
|
+
};
|
|
92
|
+
query[kPatched] = true;
|
|
93
|
+
Client.prototype.query = query;
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
function patchMysql2(mysql) {
|
|
97
|
+
const Conn = mysql.Connection;
|
|
98
|
+
if (!Conn)
|
|
99
|
+
return false;
|
|
100
|
+
let patched = false;
|
|
101
|
+
for (const method of ['query', 'execute']) {
|
|
102
|
+
let proto = Conn.prototype;
|
|
103
|
+
while (proto && !Object.prototype.hasOwnProperty.call(proto, method))
|
|
104
|
+
proto = Object.getPrototypeOf(proto);
|
|
105
|
+
if (!proto || proto[method][kPatched])
|
|
106
|
+
continue;
|
|
107
|
+
const orig = proto[method];
|
|
108
|
+
const fn = function (...args) {
|
|
109
|
+
const sql = args[0];
|
|
110
|
+
const text = typeof sql === 'string' ? sql : sql?.sql;
|
|
111
|
+
if (!text)
|
|
112
|
+
return orig.apply(this, args);
|
|
113
|
+
const span = dbSpan('mysql', text, { db: this.config?.database, host: this.config?.host });
|
|
114
|
+
if (!span)
|
|
115
|
+
return orig.apply(this, args);
|
|
116
|
+
if (wrapCallback(args, span, (rows) => (Array.isArray(rows) ? rows.length : undefined)))
|
|
117
|
+
return orig.apply(this, args);
|
|
118
|
+
const out = orig.apply(this, args);
|
|
119
|
+
if (isEmitter(out)) {
|
|
120
|
+
out.once('end', () => span.finish());
|
|
121
|
+
out.once('error', (e) => span.fail(e).finish());
|
|
122
|
+
}
|
|
123
|
+
else
|
|
124
|
+
span.finish();
|
|
125
|
+
return out;
|
|
126
|
+
};
|
|
127
|
+
fn[kPatched] = true;
|
|
128
|
+
proto[method] = fn;
|
|
129
|
+
patched = true;
|
|
130
|
+
}
|
|
131
|
+
return patched;
|
|
132
|
+
}
|
|
133
|
+
function patchIoredis(Redis) {
|
|
134
|
+
const mod = Redis;
|
|
135
|
+
const R = (mod.default || mod);
|
|
136
|
+
const proto = R.prototype;
|
|
137
|
+
if (!proto || !proto.sendCommand || proto.sendCommand[kPatched])
|
|
138
|
+
return false;
|
|
139
|
+
const orig = proto.sendCommand;
|
|
140
|
+
const send = function (command, ...rest) {
|
|
141
|
+
const span = command?.name ? dbSpan('redis', String(command.name).toUpperCase(), { host: this.options?.host }) : null;
|
|
142
|
+
const out = orig.call(this, command, ...rest);
|
|
143
|
+
if (span) {
|
|
144
|
+
if ((0, context_1.isThenable)(command?.promise))
|
|
145
|
+
command.promise.then(() => span.finish(), (e) => span.fail(e).finish());
|
|
146
|
+
else
|
|
147
|
+
span.finish();
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
};
|
|
151
|
+
send[kPatched] = true;
|
|
152
|
+
proto.sendCommand = send;
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
//# sourceMappingURL=db.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db.js","sourceRoot":"","sources":["../../src/instrument/db.ts"],"names":[],"mappings":";;AASA,oCAUC;AAGD,oCAKC;AAwBD,0BAyBC;AAED,kCA4BC;AAED,oCAkBC;AA9HD,wCAA8D;AAE9D,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAInD,MAAM,SAAS,GAAG,CAAC,CAAU,EAAmB,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,OAAQ,CAAgB,CAAC,IAAI,KAAK,UAAU,CAAC;AAEvG,qFAAqF;AACrF,SAAgB,YAAY,CAAC,GAAW;IACtC,OAAO,MAAM,CAAC,GAAG,CAAC;SACf,OAAO,CAAC,uBAAuB,EAAE,GAAG,CAAC;SACrC,OAAO,CAAC,uCAAuC,EAAE,GAAG,CAAC;SACrD,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;SACtB,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC;SAClC,OAAO,CAAC,6BAA6B,EAAE,KAAK,CAAC;SAC7C,OAAO,CA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,CAAC,GAAG,IAAI,CAAC;IACtB,KAAK,CAAC,WAAW,GAAG,IAAI,CAAC;IACzB,OAAO,IAAI,CAAC;AACd,CAAC"}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.instrumentExpress = instrumentExpress;
|
|
4
|
+
const context_1 = require("../context");
|
|
5
|
+
const agent_types_1 = require("../agent-types");
|
|
6
|
+
const kWrapped = Symbol.for('obzerver.express.wrapped');
|
|
7
|
+
const kDone = Symbol.for('obzerver.express.done');
|
|
8
|
+
const SKIP_NAMES = new Set(['query', 'expressInit']);
|
|
9
|
+
const METHODS = ['get', 'post', 'put', 'delete', 'patch', 'options', 'head', 'all'];
|
|
10
|
+
const cleanName = (fn) => (fn.name || '').replace(/^bound /, '');
|
|
11
|
+
/**
|
|
12
|
+
* Wrap one middleware/handler so it records a span, captures the route template
|
|
13
|
+
* and any error passed to next() or thrown. Arity is preserved exactly because
|
|
14
|
+
* Express decides error-handler vs normal handler from fn.length.
|
|
15
|
+
*/
|
|
16
|
+
function wrapHandler(agent, fn, info, handlesPromises) {
|
|
17
|
+
if (fn[kWrapped] || fn.handle || fn.stack || fn.set)
|
|
18
|
+
return fn;
|
|
19
|
+
const name = cleanName(fn);
|
|
20
|
+
if (SKIP_NAMES.has(name))
|
|
21
|
+
return fn;
|
|
22
|
+
const invoke = (self, args, req, res, next) => {
|
|
23
|
+
const trace = req && req[agent_types_1.kTrace];
|
|
24
|
+
if (!trace || trace.finished || typeof next !== 'function')
|
|
25
|
+
return fn.apply(self, typeof next === 'function' ? [...args, next] : args);
|
|
26
|
+
if (info.route && req.route && typeof req.route.path === 'string')
|
|
27
|
+
trace.route = `${req.baseUrl || ''}${req.route.path}` || '/';
|
|
28
|
+
const spanName = name || (info.isHandler ? `${(info.method || '').toUpperCase()} ${trace.route || info.path || ''} handler` : 'anonymous middleware');
|
|
29
|
+
const span = new context_1.Span(trace, spanName, info.isHandler ? 'handler' : 'middleware', trace.root.id, info.errorHandler ? { errorHandler: true } : undefined);
|
|
30
|
+
let ended = false;
|
|
31
|
+
const end = (err) => {
|
|
32
|
+
if (ended)
|
|
33
|
+
return;
|
|
34
|
+
ended = true;
|
|
35
|
+
if (err)
|
|
36
|
+
span.fail(err);
|
|
37
|
+
span.finish();
|
|
38
|
+
};
|
|
39
|
+
trace.openSpans.push(end);
|
|
40
|
+
const wrappedNext = function (err) {
|
|
41
|
+
const isErr = !!err && err !== 'route' && err !== 'router';
|
|
42
|
+
if (isErr)
|
|
43
|
+
agent.recordRequestError(trace, err);
|
|
44
|
+
end(isErr ? err : null);
|
|
45
|
+
// eslint-disable-next-line prefer-rest-params
|
|
46
|
+
const a = arguments;
|
|
47
|
+
return context_1.als.run({ trace, span: trace.root }, () => next.apply(this, a));
|
|
48
|
+
};
|
|
49
|
+
return context_1.als.run({ trace, span }, () => {
|
|
50
|
+
let out;
|
|
51
|
+
try {
|
|
52
|
+
out = fn.apply(self, [...args, wrappedNext]);
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
agent.recordRequestError(trace, e);
|
|
56
|
+
end(e);
|
|
57
|
+
throw e;
|
|
58
|
+
}
|
|
59
|
+
if ((0, context_1.isThenable)(out)) {
|
|
60
|
+
out.then(() => { if (res.headersSent || res.writableEnded)
|
|
61
|
+
end(); }, (e) => {
|
|
62
|
+
agent.recordRequestError(trace, e);
|
|
63
|
+
end(e);
|
|
64
|
+
// Express 4 does not handle rejected promises: keep the original
|
|
65
|
+
// unhandled-rejection behaviour instead of silently swallowing it.
|
|
66
|
+
if (!handlesPromises)
|
|
67
|
+
void Promise.reject(e);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
});
|
|
72
|
+
};
|
|
73
|
+
const w = fn.length === 4
|
|
74
|
+
? function (err, req, res, next) { return invoke(this, [err, req, res], req, res, next); }
|
|
75
|
+
: function (req, res, next) { return invoke(this, [req, res], req, res, next); };
|
|
76
|
+
Object.defineProperty(w, 'name', { value: name || 'anonymous' });
|
|
77
|
+
w[kWrapped] = true;
|
|
78
|
+
return w;
|
|
79
|
+
}
|
|
80
|
+
function wrapArgs(agent, args, info, handlesPromises) {
|
|
81
|
+
const flat = Array.from(args).flat(Infinity);
|
|
82
|
+
const fns = flat.filter((a) => typeof a === 'function');
|
|
83
|
+
const last = fns[fns.length - 1];
|
|
84
|
+
return flat.map((a) => {
|
|
85
|
+
if (typeof a !== 'function')
|
|
86
|
+
return a;
|
|
87
|
+
// On a route, everything before the final function is route-level middleware.
|
|
88
|
+
const fn = a;
|
|
89
|
+
return wrapHandler(agent, fn, { ...info, isHandler: info.route && fn === last, errorHandler: fn.length === 4 }, handlesPromises);
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function expressMajor(agent, express) {
|
|
93
|
+
let major = 4;
|
|
94
|
+
try {
|
|
95
|
+
const pkgPath = require.resolve('express/package.json', { paths: [agent.cwd] });
|
|
96
|
+
major = Number(require(pkgPath).version.split('.')[0]) || 4;
|
|
97
|
+
}
|
|
98
|
+
catch { /* default */ }
|
|
99
|
+
if (typeof express.Router?.prototype?.use === 'function')
|
|
100
|
+
major = Math.max(major, 5);
|
|
101
|
+
return major;
|
|
102
|
+
}
|
|
103
|
+
/** Instrument the express module (idempotent): every Router and Route created from it. */
|
|
104
|
+
function instrumentExpress(agent, express) {
|
|
105
|
+
const ex = express;
|
|
106
|
+
if (!ex || ex[kDone])
|
|
107
|
+
return;
|
|
108
|
+
const major = expressMajor(agent, ex);
|
|
109
|
+
const handlesPromises = major >= 5;
|
|
110
|
+
const RouterProto = (typeof ex.Router?.prototype?.use === 'function' ? ex.Router.prototype : ex.Router);
|
|
111
|
+
if (RouterProto && typeof RouterProto.use === 'function') {
|
|
112
|
+
const origUse = RouterProto.use;
|
|
113
|
+
RouterProto.use = function (...args) {
|
|
114
|
+
const first = args[0];
|
|
115
|
+
const p = typeof first === 'string' || first instanceof RegExp ? String(first) : undefined;
|
|
116
|
+
return origUse.apply(this, wrapArgs(agent, args, { route: false, path: p }, handlesPromises));
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
const RouteProto = ex.Route?.prototype;
|
|
120
|
+
if (RouteProto) {
|
|
121
|
+
for (const m of METHODS) {
|
|
122
|
+
const orig = RouteProto[m];
|
|
123
|
+
if (typeof orig !== 'function')
|
|
124
|
+
continue;
|
|
125
|
+
RouteProto[m] = function (...args) {
|
|
126
|
+
return orig.apply(this, wrapArgs(agent, args, { route: true, method: m === 'all' ? 'ALL' : m, path: this.path }, handlesPromises));
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
ex[kDone] = true;
|
|
131
|
+
agent.frameworks.add(`express@${major}`);
|
|
132
|
+
}
|
|
133
|
+
//# sourceMappingURL=express.js.map
|