@watchtowerobservability/node 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +304 -2
- package/dist/cjs/appsec.d.ts +95 -0
- package/dist/cjs/appsec.js +206 -0
- package/dist/cjs/buffer.d.ts +49 -0
- package/dist/cjs/buffer.js +134 -0
- package/dist/cjs/errors.d.ts +17 -0
- package/dist/cjs/errors.js +55 -0
- package/dist/cjs/index.d.ts +123 -0
- package/dist/cjs/index.js +315 -0
- package/dist/cjs/integrations/amqp.d.ts +13 -0
- package/dist/cjs/integrations/amqp.js +96 -0
- package/dist/cjs/integrations/azure-functions.d.ts +18 -0
- package/dist/cjs/integrations/azure-functions.js +97 -0
- package/dist/cjs/integrations/bullmq.d.ts +19 -0
- package/dist/cjs/integrations/bullmq.js +83 -0
- package/dist/cjs/integrations/cache.d.ts +13 -0
- package/dist/cjs/integrations/cache.js +51 -0
- package/dist/cjs/integrations/db.d.ts +62 -0
- package/dist/cjs/integrations/db.js +288 -0
- package/dist/cjs/integrations/duckdb.d.ts +22 -0
- package/dist/cjs/integrations/duckdb.js +66 -0
- package/dist/cjs/integrations/express.d.ts +25 -0
- package/dist/cjs/integrations/express.js +58 -0
- package/dist/cjs/integrations/fastify.d.ts +6 -0
- package/dist/cjs/integrations/fastify.js +44 -0
- package/dist/cjs/integrations/genai-agents.d.ts +36 -0
- package/dist/cjs/integrations/genai-agents.js +124 -0
- package/dist/cjs/integrations/genai-stream.d.ts +19 -0
- package/dist/cjs/integrations/genai-stream.js +135 -0
- package/dist/cjs/integrations/genai.d.ts +18 -0
- package/dist/cjs/integrations/genai.js +150 -0
- package/dist/cjs/integrations/graphile-worker.d.ts +22 -0
- package/dist/cjs/integrations/graphile-worker.js +50 -0
- package/dist/cjs/integrations/koa.d.ts +19 -0
- package/dist/cjs/integrations/koa.js +34 -0
- package/dist/cjs/integrations/lambda.d.ts +11 -0
- package/dist/cjs/integrations/lambda.js +68 -0
- package/dist/cjs/integrations/level.d.ts +18 -0
- package/dist/cjs/integrations/level.js +71 -0
- package/dist/cjs/integrations/lmdb.d.ts +26 -0
- package/dist/cjs/integrations/lmdb.js +78 -0
- package/dist/cjs/integrations/logs.d.ts +10 -0
- package/dist/cjs/integrations/logs.js +77 -0
- package/dist/cjs/integrations/messaging.d.ts +17 -0
- package/dist/cjs/integrations/messaging.js +73 -0
- package/dist/cjs/integrations/mqtt.d.ts +7 -0
- package/dist/cjs/integrations/mqtt.js +41 -0
- package/dist/cjs/integrations/nats.d.ts +17 -0
- package/dist/cjs/integrations/nats.js +73 -0
- package/dist/cjs/integrations/nestjs.d.ts +16 -0
- package/dist/cjs/integrations/nestjs.js +30 -0
- package/dist/cjs/integrations/next.d.ts +11 -0
- package/dist/cjs/integrations/next.js +59 -0
- package/dist/cjs/integrations/orm.d.ts +47 -0
- package/dist/cjs/integrations/orm.js +93 -0
- package/dist/cjs/integrations/pg-boss.d.ts +8 -0
- package/dist/cjs/integrations/pg-boss.js +63 -0
- package/dist/cjs/integrations/pools.d.ts +41 -0
- package/dist/cjs/integrations/pools.js +94 -0
- package/dist/cjs/integrations/postgres.d.ts +12 -0
- package/dist/cjs/integrations/postgres.js +92 -0
- package/dist/cjs/integrations/prisma.d.ts +3 -0
- package/dist/cjs/integrations/prisma.js +33 -0
- package/dist/cjs/integrations/sqlite.d.ts +36 -0
- package/dist/cjs/integrations/sqlite.js +125 -0
- package/dist/cjs/integrations/util.d.ts +9 -0
- package/dist/cjs/integrations/util.js +37 -0
- package/dist/cjs/jest.d.ts +21 -0
- package/dist/cjs/jest.js +45 -0
- package/dist/cjs/load.d.ts +1 -0
- package/dist/cjs/load.js +11 -0
- package/dist/cjs/metrics.d.ts +10 -0
- package/dist/cjs/metrics.js +81 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/payload.d.ts +42 -0
- package/dist/cjs/payload.js +145 -0
- package/dist/cjs/pprof.d.ts +6 -0
- package/dist/cjs/pprof.js +88 -0
- package/dist/cjs/probes.d.ts +97 -0
- package/dist/cjs/probes.js +422 -0
- package/dist/cjs/profiling.d.ts +84 -0
- package/dist/cjs/profiling.js +263 -0
- package/dist/cjs/reporter-core.d.ts +32 -0
- package/dist/cjs/reporter-core.js +102 -0
- package/dist/cjs/sql.d.ts +19 -0
- package/dist/cjs/sql.js +332 -0
- package/dist/cjs/test-plan.d.ts +102 -0
- package/dist/cjs/test-plan.js +352 -0
- package/dist/cjs/vitest.d.ts +27 -0
- package/dist/cjs/vitest.js +52 -0
- package/dist/esm/appsec.d.ts +95 -0
- package/dist/esm/appsec.js +193 -0
- package/dist/esm/buffer.d.ts +49 -0
- package/dist/esm/buffer.js +92 -0
- package/dist/esm/errors.d.ts +17 -0
- package/dist/esm/errors.js +50 -0
- package/dist/esm/index.d.ts +123 -0
- package/dist/esm/index.js +264 -0
- package/dist/esm/integrations/amqp.d.ts +13 -0
- package/dist/esm/integrations/amqp.js +92 -0
- package/dist/esm/integrations/azure-functions.d.ts +18 -0
- package/dist/esm/integrations/azure-functions.js +60 -0
- package/dist/esm/integrations/bullmq.d.ts +19 -0
- package/dist/esm/integrations/bullmq.js +79 -0
- package/dist/esm/integrations/cache.d.ts +13 -0
- package/dist/esm/integrations/cache.js +46 -0
- package/dist/esm/integrations/db.d.ts +62 -0
- package/dist/esm/integrations/db.js +239 -0
- package/dist/esm/integrations/duckdb.d.ts +22 -0
- package/dist/esm/integrations/duckdb.js +29 -0
- package/dist/esm/integrations/express.d.ts +25 -0
- package/dist/esm/integrations/express.js +54 -0
- package/dist/esm/integrations/fastify.d.ts +6 -0
- package/dist/esm/integrations/fastify.js +41 -0
- package/dist/esm/integrations/genai-agents.d.ts +36 -0
- package/dist/esm/integrations/genai-agents.js +118 -0
- package/dist/esm/integrations/genai-stream.d.ts +19 -0
- package/dist/esm/integrations/genai-stream.js +130 -0
- package/dist/esm/integrations/genai.d.ts +18 -0
- package/dist/esm/integrations/genai.js +138 -0
- package/dist/esm/integrations/graphile-worker.d.ts +22 -0
- package/dist/esm/integrations/graphile-worker.js +46 -0
- package/dist/esm/integrations/koa.d.ts +19 -0
- package/dist/esm/integrations/koa.js +31 -0
- package/dist/esm/integrations/lambda.d.ts +11 -0
- package/dist/esm/integrations/lambda.js +32 -0
- package/dist/esm/integrations/level.d.ts +18 -0
- package/dist/esm/integrations/level.js +35 -0
- package/dist/esm/integrations/lmdb.d.ts +26 -0
- package/dist/esm/integrations/lmdb.js +42 -0
- package/dist/esm/integrations/logs.d.ts +10 -0
- package/dist/esm/integrations/logs.js +40 -0
- package/dist/esm/integrations/messaging.d.ts +17 -0
- package/dist/esm/integrations/messaging.js +64 -0
- package/dist/esm/integrations/mqtt.d.ts +7 -0
- package/dist/esm/integrations/mqtt.js +38 -0
- package/dist/esm/integrations/nats.d.ts +17 -0
- package/dist/esm/integrations/nats.js +70 -0
- package/dist/esm/integrations/nestjs.d.ts +16 -0
- package/dist/esm/integrations/nestjs.js +26 -0
- package/dist/esm/integrations/next.d.ts +11 -0
- package/dist/esm/integrations/next.js +22 -0
- package/dist/esm/integrations/orm.d.ts +47 -0
- package/dist/esm/integrations/orm.js +86 -0
- package/dist/esm/integrations/pg-boss.d.ts +8 -0
- package/dist/esm/integrations/pg-boss.js +60 -0
- package/dist/esm/integrations/pools.d.ts +41 -0
- package/dist/esm/integrations/pools.js +89 -0
- package/dist/esm/integrations/postgres.d.ts +12 -0
- package/dist/esm/integrations/postgres.js +55 -0
- package/dist/esm/integrations/prisma.d.ts +3 -0
- package/dist/esm/integrations/prisma.js +30 -0
- package/dist/esm/integrations/sqlite.d.ts +36 -0
- package/dist/esm/integrations/sqlite.js +84 -0
- package/dist/esm/integrations/util.d.ts +9 -0
- package/dist/esm/integrations/util.js +32 -0
- package/dist/esm/jest.d.ts +21 -0
- package/dist/esm/jest.js +41 -0
- package/dist/esm/load.d.ts +1 -0
- package/dist/esm/load.js +5 -0
- package/dist/esm/metrics.d.ts +10 -0
- package/dist/esm/metrics.js +44 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/payload.d.ts +42 -0
- package/dist/esm/payload.js +131 -0
- package/dist/esm/pprof.d.ts +6 -0
- package/dist/esm/pprof.js +85 -0
- package/dist/esm/probes.d.ts +97 -0
- package/dist/esm/probes.js +412 -0
- package/dist/esm/profiling.d.ts +84 -0
- package/dist/esm/profiling.js +251 -0
- package/dist/esm/reporter-core.d.ts +32 -0
- package/dist/esm/reporter-core.js +63 -0
- package/dist/esm/sql.d.ts +19 -0
- package/dist/esm/sql.js +324 -0
- package/dist/esm/test-plan.d.ts +102 -0
- package/dist/esm/test-plan.js +336 -0
- package/dist/esm/vitest.d.ts +27 -0
- package/dist/esm/vitest.js +48 -0
- package/package.json +379 -4
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.instrumentNodeCache = instrumentNodeCache;
|
|
4
|
+
exports.instrumentLruCache = instrumentLruCache;
|
|
5
|
+
exports.instrumentKeyv = instrumentKeyv;
|
|
6
|
+
const db_js_1 = require("./db.js");
|
|
7
|
+
/** Count hits and misses of `get`-like methods: `undefined` is a miss; arrays and objects count per key. */
|
|
8
|
+
function count(c, keys, v) {
|
|
9
|
+
if (Array.isArray(keys)) {
|
|
10
|
+
const found = Array.isArray(v) ? v.filter((x) => x !== undefined).length
|
|
11
|
+
: v && typeof v === 'object' ? Object.keys(v).length : 0;
|
|
12
|
+
c.hit(found);
|
|
13
|
+
c.miss(keys.length - found);
|
|
14
|
+
}
|
|
15
|
+
else if (v === undefined) {
|
|
16
|
+
c.miss();
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
c.hit();
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function wrapGets(cache, system, name, methods) {
|
|
23
|
+
const c = (0, db_js_1.cacheCounters)(system, name);
|
|
24
|
+
for (const m of methods) {
|
|
25
|
+
(0, db_js_1.patch)(cache, m, (orig) => function (key, ...a) {
|
|
26
|
+
const v = orig.call(this, key, ...a);
|
|
27
|
+
if (v && typeof v.then === 'function') {
|
|
28
|
+
v.then((x) => count(c, key, x), () => { });
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
count(c, key, v);
|
|
32
|
+
}
|
|
33
|
+
return v;
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** Hit/miss counters and entry count for a node-cache instance (`get`, `mget`). Returns `stop()`. */
|
|
38
|
+
function instrumentNodeCache(cache, name = 'default') {
|
|
39
|
+
wrapGets(cache, 'node-cache', name, ['get', 'mget']);
|
|
40
|
+
return (0, db_js_1.observeEmbedded)('node-cache', name, ['cache.entries'], () => ({ 'cache.entries': cache.getStats?.().keys }));
|
|
41
|
+
}
|
|
42
|
+
/** Hit/miss counters and entry count for an lru-cache instance (`get`). Returns `stop()`.
|
|
43
|
+
* shortcut: `fetch()` (the async loader) is not counted. */
|
|
44
|
+
function instrumentLruCache(cache, name = 'default') {
|
|
45
|
+
wrapGets(cache, 'lru-cache', name, ['get']);
|
|
46
|
+
return (0, db_js_1.observeEmbedded)('lru-cache', name, ['cache.entries'], () => ({ 'cache.entries': cache.size }));
|
|
47
|
+
}
|
|
48
|
+
/** Hit/miss counters for a Keyv instance (`get` with one key or an array; also `getMany`). */
|
|
49
|
+
function instrumentKeyv(keyv, name = 'default') {
|
|
50
|
+
wrapGets(keyv, 'keyv', name, ['get', 'getMany']);
|
|
51
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Attributes, Context, Span, TimeInput } from '@opentelemetry/api';
|
|
2
|
+
export interface DbOptions {
|
|
3
|
+
/** Add the literal-free statement as `db.query.text`. Default: `WATCHTOWER_DB_QUERY_TEXT=1`. */
|
|
4
|
+
queryText?: boolean;
|
|
5
|
+
/** Flag a statement run more than this many times under one parent span. Default:
|
|
6
|
+
* `WATCHTOWER_DB_N_PLUS_ONE` or 5; 0 turns it off. */
|
|
7
|
+
nPlusOne?: number;
|
|
8
|
+
}
|
|
9
|
+
export interface DbOp {
|
|
10
|
+
/** `db.system.name`, e.g. `sqlite`. */
|
|
11
|
+
system: string;
|
|
12
|
+
operation?: string;
|
|
13
|
+
collection?: string;
|
|
14
|
+
namespace?: string;
|
|
15
|
+
/** Statement text: summarised and hashed, never recorded raw. */
|
|
16
|
+
sql?: string | null;
|
|
17
|
+
attributes?: Attributes;
|
|
18
|
+
}
|
|
19
|
+
export declare const inside: (ctx?: Context) => boolean;
|
|
20
|
+
/** `parent` with `span` active; `nested` marks it as inside an instrumented call (no inner spans). */
|
|
21
|
+
export declare const enter: (parent: Context, span: Span, nested?: boolean) => Context;
|
|
22
|
+
/** A CLIENT span for `op` (not made active): summary, hash, N+1 hint. Prefer `traced`. */
|
|
23
|
+
export declare function startDbSpan(op: DbOp, opts: DbOptions | undefined, parent: Context, startTime?: TimeInput): Span;
|
|
24
|
+
/** A finished CLIENT span for a query a library reports after the fact (ORM loggers): it ends now. */
|
|
25
|
+
export declare function recordDbSpan(op: DbOp, opts: DbOptions | undefined, durationMs: number, error?: unknown): void;
|
|
26
|
+
/** Error status with the driver's code; the message is not recorded (it can quote values). */
|
|
27
|
+
export declare function fail(span: Span, e: unknown): void;
|
|
28
|
+
/** Run `fn` and end `span` when it returns, throws or its promise settles. The result is returned as is. */
|
|
29
|
+
export declare function settle<T>(span: Span, fn: () => T): T;
|
|
30
|
+
/** A CLIENT span around `fn` (sync or promise), child of the active span. `nested: false` lets
|
|
31
|
+
* calls made inside `fn` (a transaction callback) get their own spans. */
|
|
32
|
+
export declare function traced<T>(op: DbOp, opts: DbOptions | undefined, fn: () => T, nested?: boolean): T;
|
|
33
|
+
/** `traced` for node-style callback APIs: the last function argument ends the span and runs in the caller's context. */
|
|
34
|
+
export declare function tracedCb<T>(op: DbOp, opts: DbOptions | undefined, args: unknown[], call: (args: unknown[]) => T): T;
|
|
35
|
+
/** Wrap `obj[name]` once; `wrap` gets the original. Missing methods are skipped. */
|
|
36
|
+
export declare function patch<T extends object>(obj: T, name: string, wrap: (orig: (...a: any[]) => any) => (...a: any[]) => any): void;
|
|
37
|
+
export interface PoolState {
|
|
38
|
+
used?: number;
|
|
39
|
+
idle?: number;
|
|
40
|
+
pending?: number;
|
|
41
|
+
max?: number;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Pool gauges per OTel db semconv, read at each export: `db.client.connection.count{state}`,
|
|
45
|
+
* `.max`, `.pending_requests`, with `db.client.connection.pool.name` and `db.system.name`.
|
|
46
|
+
* Returns the recorders for wait/use time and timeouts, and `stop()`.
|
|
47
|
+
*/
|
|
48
|
+
export declare function observePool(system: string, pool: string, read: () => PoolState): {
|
|
49
|
+
wait: (seconds: number) => void;
|
|
50
|
+
use: (seconds: number) => void;
|
|
51
|
+
timeout: () => void;
|
|
52
|
+
stop: () => void;
|
|
53
|
+
};
|
|
54
|
+
/** `wt.embedded.<key>` gauges for an embedded store, read at each export. Returns `stop()`. */
|
|
55
|
+
export declare function observeEmbedded(system: string, namespace: string | undefined, keys: string[], read: () => Partial<Record<string, number>>): () => void;
|
|
56
|
+
/** Hit/miss counters (`wt.embedded.cache.hits` / `.misses`) for an in-memory cache. */
|
|
57
|
+
export declare function cacheCounters(system: string, name: string): {
|
|
58
|
+
hit: (n?: number) => void;
|
|
59
|
+
miss: (n?: number) => void;
|
|
60
|
+
};
|
|
61
|
+
/** Size in bytes of a file, or of the files directly in a directory; 0 when missing. */
|
|
62
|
+
export declare function sizeOf(path: string): number;
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.enter = exports.inside = void 0;
|
|
37
|
+
exports.startDbSpan = startDbSpan;
|
|
38
|
+
exports.recordDbSpan = recordDbSpan;
|
|
39
|
+
exports.fail = fail;
|
|
40
|
+
exports.settle = settle;
|
|
41
|
+
exports.traced = traced;
|
|
42
|
+
exports.tracedCb = tracedCb;
|
|
43
|
+
exports.patch = patch;
|
|
44
|
+
exports.observePool = observePool;
|
|
45
|
+
exports.observeEmbedded = observeEmbedded;
|
|
46
|
+
exports.cacheCounters = cacheCounters;
|
|
47
|
+
exports.sizeOf = sizeOf;
|
|
48
|
+
// Shared core for the datastore and queue integrations: CLIENT spans with OTel db semconv, the
|
|
49
|
+
// statement hash and N+1 hint, connection-pool metrics and embedded-store gauges.
|
|
50
|
+
const fs = __importStar(require("node:fs"));
|
|
51
|
+
const nodePath = __importStar(require("node:path"));
|
|
52
|
+
const api_1 = require("@opentelemetry/api");
|
|
53
|
+
const sql_js_1 = require("../sql.js");
|
|
54
|
+
/** Set inside an instrumented call so a wrapper the library calls internally adds no second span. */
|
|
55
|
+
const INSIDE = (0, api_1.createContextKey)('watchtower.db.inside');
|
|
56
|
+
const inside = (ctx = api_1.context.active()) => ctx.getValue(INSIDE) === true;
|
|
57
|
+
exports.inside = inside;
|
|
58
|
+
/** `parent` with `span` active; `nested` marks it as inside an instrumented call (no inner spans). */
|
|
59
|
+
const enter = (parent, span, nested = true) => nested ? api_1.trace.setSpan(parent, span).setValue(INSIDE, true) : api_1.trace.setSpan(parent, span).deleteValue(INSIDE);
|
|
60
|
+
exports.enter = enter;
|
|
61
|
+
const on = (v) => ['1', 'true', 'on', 'yes'].includes((v || '').trim().toLowerCase());
|
|
62
|
+
const threshold = (o) => o?.nPlusOne ?? (Number(process.env.WATCHTOWER_DB_N_PLUS_ONE) || 5);
|
|
63
|
+
// parent span id -> statement key -> count.
|
|
64
|
+
// shortcut: keeps the 1000 most recently seen parents; raise it if very wide fan-out traces miss hints.
|
|
65
|
+
const seen = new Map();
|
|
66
|
+
function repeats(parent, key) {
|
|
67
|
+
let m = seen.get(parent);
|
|
68
|
+
if (!m) {
|
|
69
|
+
if (seen.size >= 1000)
|
|
70
|
+
seen.delete(seen.keys().next().value);
|
|
71
|
+
seen.set(parent, (m = new Map()));
|
|
72
|
+
}
|
|
73
|
+
const n = (m.get(key) ?? 0) + 1;
|
|
74
|
+
m.set(key, n);
|
|
75
|
+
return n;
|
|
76
|
+
}
|
|
77
|
+
/** A CLIENT span for `op` (not made active): summary, hash, N+1 hint. Prefer `traced`. */
|
|
78
|
+
function startDbSpan(op, opts, parent, startTime) {
|
|
79
|
+
const attrs = { 'db.system.name': op.system, ...op.attributes };
|
|
80
|
+
let { operation, collection } = op;
|
|
81
|
+
let name = [operation, collection].filter(Boolean).join(' ') || op.system;
|
|
82
|
+
let key = name;
|
|
83
|
+
if (op.sql) {
|
|
84
|
+
const [norm, hash] = (0, sql_js_1.normalizeAndHash)(op.sql, (0, sql_js_1.isPgDialect)(op.system));
|
|
85
|
+
const s = (0, sql_js_1.querySummary)(norm, op.system);
|
|
86
|
+
operation ??= s.operation;
|
|
87
|
+
collection ??= s.target;
|
|
88
|
+
name = s.summary;
|
|
89
|
+
key = hash;
|
|
90
|
+
attrs['db.query.summary'] = s.summary;
|
|
91
|
+
attrs['db.query.hash'] = hash;
|
|
92
|
+
if (opts?.queryText ?? on(process.env.WATCHTOWER_DB_QUERY_TEXT))
|
|
93
|
+
attrs['db.query.text'] = norm;
|
|
94
|
+
}
|
|
95
|
+
if (operation)
|
|
96
|
+
attrs['db.operation.name'] = operation;
|
|
97
|
+
if (collection)
|
|
98
|
+
attrs['db.collection.name'] = collection;
|
|
99
|
+
if (op.namespace)
|
|
100
|
+
attrs['db.namespace'] = op.namespace;
|
|
101
|
+
const p = api_1.trace.getSpan(parent)?.spanContext();
|
|
102
|
+
const max = threshold(opts);
|
|
103
|
+
if (p && max > 0) {
|
|
104
|
+
const n = repeats(p.spanId, key);
|
|
105
|
+
if (n > max) {
|
|
106
|
+
attrs['db.query.repeat_count'] = n;
|
|
107
|
+
attrs['db.n_plus_one'] = true;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return api_1.trace.getTracer('watchtower').startSpan(name, { kind: api_1.SpanKind.CLIENT, attributes: attrs, startTime }, parent);
|
|
111
|
+
}
|
|
112
|
+
/** A finished CLIENT span for a query a library reports after the fact (ORM loggers): it ends now. */
|
|
113
|
+
function recordDbSpan(op, opts, durationMs, error) {
|
|
114
|
+
const end = Date.now();
|
|
115
|
+
const span = startDbSpan(op, opts, api_1.context.active(), end - Math.max(0, durationMs || 0));
|
|
116
|
+
if (error)
|
|
117
|
+
fail(span, error);
|
|
118
|
+
span.end(end);
|
|
119
|
+
}
|
|
120
|
+
/** Error status with the driver's code; the message is not recorded (it can quote values). */
|
|
121
|
+
function fail(span, e) {
|
|
122
|
+
const code = e?.code;
|
|
123
|
+
if (typeof code === 'string' || typeof code === 'number') {
|
|
124
|
+
span.setAttribute('db.response.status_code', String(code));
|
|
125
|
+
span.setAttribute('error.type', String(code));
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
span.setAttribute('error.type', e?.name || 'Error');
|
|
129
|
+
}
|
|
130
|
+
span.setStatus({ code: api_1.SpanStatusCode.ERROR });
|
|
131
|
+
}
|
|
132
|
+
const isThenable = (v) => !!v && (typeof v === 'object' || typeof v === 'function') && typeof v.then === 'function';
|
|
133
|
+
/** Run `fn` and end `span` when it returns, throws or its promise settles. The result is returned as is. */
|
|
134
|
+
function settle(span, fn) {
|
|
135
|
+
let r;
|
|
136
|
+
try {
|
|
137
|
+
r = fn();
|
|
138
|
+
}
|
|
139
|
+
catch (e) {
|
|
140
|
+
fail(span, e);
|
|
141
|
+
span.end();
|
|
142
|
+
throw e;
|
|
143
|
+
}
|
|
144
|
+
if (isThenable(r)) {
|
|
145
|
+
r.then(() => span.end(), (e) => { fail(span, e); span.end(); });
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
span.end();
|
|
149
|
+
}
|
|
150
|
+
return r;
|
|
151
|
+
}
|
|
152
|
+
/** A CLIENT span around `fn` (sync or promise), child of the active span. `nested: false` lets
|
|
153
|
+
* calls made inside `fn` (a transaction callback) get their own spans. */
|
|
154
|
+
function traced(op, opts, fn, nested = true) {
|
|
155
|
+
const parent = api_1.context.active();
|
|
156
|
+
if ((0, exports.inside)(parent))
|
|
157
|
+
return fn();
|
|
158
|
+
const span = startDbSpan(op, opts, parent);
|
|
159
|
+
return settle(span, () => api_1.context.with((0, exports.enter)(parent, span, nested), fn));
|
|
160
|
+
}
|
|
161
|
+
/** `traced` for node-style callback APIs: the last function argument ends the span and runs in the caller's context. */
|
|
162
|
+
function tracedCb(op, opts, args, call) {
|
|
163
|
+
const last = args.length - 1;
|
|
164
|
+
const cb = args[last];
|
|
165
|
+
const parent = api_1.context.active();
|
|
166
|
+
if (typeof cb !== 'function')
|
|
167
|
+
return traced(op, opts, () => call(args));
|
|
168
|
+
if ((0, exports.inside)(parent))
|
|
169
|
+
return call(args);
|
|
170
|
+
const span = startDbSpan(op, opts, parent);
|
|
171
|
+
const copy = args.slice();
|
|
172
|
+
copy[last] = api_1.context.bind(parent, function (err, ...rest) {
|
|
173
|
+
if (err)
|
|
174
|
+
fail(span, err);
|
|
175
|
+
span.end();
|
|
176
|
+
return cb.apply(this, [err, ...rest]);
|
|
177
|
+
});
|
|
178
|
+
try {
|
|
179
|
+
return api_1.context.with((0, exports.enter)(parent, span), () => call(copy));
|
|
180
|
+
}
|
|
181
|
+
catch (e) {
|
|
182
|
+
fail(span, e);
|
|
183
|
+
span.end();
|
|
184
|
+
throw e;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** Wrap `obj[name]` once; `wrap` gets the original. Missing methods are skipped. */
|
|
188
|
+
function patch(obj, name, wrap) {
|
|
189
|
+
const o = obj;
|
|
190
|
+
const orig = o[name];
|
|
191
|
+
if (typeof orig !== 'function' || orig[WRAPPED])
|
|
192
|
+
return;
|
|
193
|
+
const w = wrap(orig);
|
|
194
|
+
w[WRAPPED] = true;
|
|
195
|
+
o[name] = w;
|
|
196
|
+
}
|
|
197
|
+
const WRAPPED = Symbol.for('watchtower.wrapped');
|
|
198
|
+
// ---- metrics (instruments come from the global meter: call the observe* helpers after init) ----
|
|
199
|
+
const meter = () => api_1.metrics.getMeter('watchtower');
|
|
200
|
+
let cached;
|
|
201
|
+
function inst() {
|
|
202
|
+
const m = meter();
|
|
203
|
+
if (cached?.m !== m) {
|
|
204
|
+
cached = {
|
|
205
|
+
m,
|
|
206
|
+
wait: m.createHistogram('db.client.connection.wait_time', { unit: 's' }),
|
|
207
|
+
use: m.createHistogram('db.client.connection.use_time', { unit: 's' }),
|
|
208
|
+
timeouts: m.createCounter('db.client.connection.timeouts'),
|
|
209
|
+
hits: m.createCounter('wt.embedded.cache.hits'),
|
|
210
|
+
misses: m.createCounter('wt.embedded.cache.misses'),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
return cached;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Pool gauges per OTel db semconv, read at each export: `db.client.connection.count{state}`,
|
|
217
|
+
* `.max`, `.pending_requests`, with `db.client.connection.pool.name` and `db.system.name`.
|
|
218
|
+
* Returns the recorders for wait/use time and timeouts, and `stop()`.
|
|
219
|
+
*/
|
|
220
|
+
function observePool(system, pool, read) {
|
|
221
|
+
const attrs = { 'db.system.name': system, 'db.client.connection.pool.name': pool };
|
|
222
|
+
const m = meter();
|
|
223
|
+
const count = m.createObservableGauge('db.client.connection.count');
|
|
224
|
+
const max = m.createObservableGauge('db.client.connection.max');
|
|
225
|
+
const pending = m.createObservableGauge('db.client.connection.pending_requests');
|
|
226
|
+
const cb = (r) => {
|
|
227
|
+
const s = read();
|
|
228
|
+
if (s.used !== undefined)
|
|
229
|
+
r.observe(count, s.used, { ...attrs, 'db.client.connection.state': 'used' });
|
|
230
|
+
if (s.idle !== undefined)
|
|
231
|
+
r.observe(count, s.idle, { ...attrs, 'db.client.connection.state': 'idle' });
|
|
232
|
+
if (s.max !== undefined)
|
|
233
|
+
r.observe(max, s.max, attrs);
|
|
234
|
+
if (s.pending !== undefined)
|
|
235
|
+
r.observe(pending, s.pending, attrs);
|
|
236
|
+
};
|
|
237
|
+
m.addBatchObservableCallback(cb, [count, max, pending]);
|
|
238
|
+
return {
|
|
239
|
+
wait: (seconds) => inst().wait.record(seconds, attrs),
|
|
240
|
+
use: (seconds) => inst().use.record(seconds, attrs),
|
|
241
|
+
timeout: () => inst().timeouts.add(1, attrs),
|
|
242
|
+
stop: () => m.removeBatchObservableCallback(cb, [count, max, pending]),
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
/** `wt.embedded.<key>` gauges for an embedded store, read at each export. Returns `stop()`. */
|
|
246
|
+
function observeEmbedded(system, namespace, keys, read) {
|
|
247
|
+
const attrs = { 'db.system.name': system, ...(namespace ? { 'db.namespace': namespace } : {}) };
|
|
248
|
+
const m = meter();
|
|
249
|
+
const gauges = keys.map((k) => [k, m.createObservableGauge(`wt.embedded.${k}`)]);
|
|
250
|
+
const cb = (r) => {
|
|
251
|
+
let v;
|
|
252
|
+
try {
|
|
253
|
+
v = read();
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
for (const [k, g] of gauges)
|
|
259
|
+
if (typeof v[k] === 'number')
|
|
260
|
+
r.observe(g, v[k], attrs);
|
|
261
|
+
};
|
|
262
|
+
m.addBatchObservableCallback(cb, gauges.map(([, g]) => g));
|
|
263
|
+
return () => m.removeBatchObservableCallback(cb, gauges.map(([, g]) => g));
|
|
264
|
+
}
|
|
265
|
+
/** Hit/miss counters (`wt.embedded.cache.hits` / `.misses`) for an in-memory cache. */
|
|
266
|
+
function cacheCounters(system, name) {
|
|
267
|
+
const attrs = { 'db.system.name': system, 'db.namespace': name };
|
|
268
|
+
return { hit: (n = 1) => inst().hits.add(n, attrs), miss: (n = 1) => inst().misses.add(n, attrs) };
|
|
269
|
+
}
|
|
270
|
+
/** Size in bytes of a file, or of the files directly in a directory; 0 when missing. */
|
|
271
|
+
function sizeOf(path) {
|
|
272
|
+
try {
|
|
273
|
+
const st = fs.statSync(path);
|
|
274
|
+
if (!st.isDirectory())
|
|
275
|
+
return st.size;
|
|
276
|
+
return fs.readdirSync(path).reduce((n, f) => {
|
|
277
|
+
try {
|
|
278
|
+
return n + fs.statSync(nodePath.join(path, f)).size;
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return n;
|
|
282
|
+
}
|
|
283
|
+
}, 0);
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
return 0;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { DbOptions } from './db.js';
|
|
2
|
+
type Proto = Record<string, any>;
|
|
3
|
+
/**
|
|
4
|
+
* `import * as duckdb from '@duckdb/node-api'` (or the classic `duckdb` package);
|
|
5
|
+
* `instrumentDuckDB(duckdb)`: a span per statement run on a `DuckDBConnection` (or a classic
|
|
6
|
+
* `Database`/`Connection`), `db.system.name=duckdb`. Returns false when neither API is found.
|
|
7
|
+
* shortcut: prepared statements (`connection.prepare`) are not traced.
|
|
8
|
+
*/
|
|
9
|
+
export declare function instrumentDuckDB(duckdb: {
|
|
10
|
+
DuckDBConnection?: {
|
|
11
|
+
prototype: Proto;
|
|
12
|
+
};
|
|
13
|
+
Database?: {
|
|
14
|
+
prototype: Proto;
|
|
15
|
+
};
|
|
16
|
+
Connection?: {
|
|
17
|
+
prototype: Proto;
|
|
18
|
+
};
|
|
19
|
+
}, opts?: DbOptions): boolean;
|
|
20
|
+
/** `wt.embedded.file.size` and `wt.embedded.wal.size` (the `.wal` file) of a DuckDB database file. Returns `stop()`. */
|
|
21
|
+
export declare function observeDuckDBFile(path: string): () => void;
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.instrumentDuckDB = instrumentDuckDB;
|
|
37
|
+
exports.observeDuckDBFile = observeDuckDBFile;
|
|
38
|
+
const nodePath = __importStar(require("node:path"));
|
|
39
|
+
const db_js_1 = require("./db.js");
|
|
40
|
+
const sqlite_js_1 = require("./sqlite.js");
|
|
41
|
+
const NEO = ['run', 'runAndRead', 'runAndReadAll', 'runAndReadUntil', 'stream', 'streamAndRead', 'streamAndReadAll',
|
|
42
|
+
'streamAndReadUntil'];
|
|
43
|
+
/**
|
|
44
|
+
* `import * as duckdb from '@duckdb/node-api'` (or the classic `duckdb` package);
|
|
45
|
+
* `instrumentDuckDB(duckdb)`: a span per statement run on a `DuckDBConnection` (or a classic
|
|
46
|
+
* `Database`/`Connection`), `db.system.name=duckdb`. Returns false when neither API is found.
|
|
47
|
+
* shortcut: prepared statements (`connection.prepare`) are not traced.
|
|
48
|
+
*/
|
|
49
|
+
function instrumentDuckDB(duckdb, opts) {
|
|
50
|
+
const neo = duckdb.DuckDBConnection?.prototype;
|
|
51
|
+
if (neo) {
|
|
52
|
+
for (const m of NEO) {
|
|
53
|
+
(0, db_js_1.patch)(neo, m, (orig) => function (sql, ...a) {
|
|
54
|
+
return (0, db_js_1.traced)({ system: 'duckdb', sql: typeof sql === 'string' ? sql : undefined }, opts, () => orig.call(this, sql, ...a));
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
const protos = [duckdb.Database?.prototype, duckdb.Connection?.prototype].filter((p) => !!p);
|
|
60
|
+
(0, sqlite_js_1.patchCallbackDb)(protos, 'duckdb', opts);
|
|
61
|
+
return protos.length > 0;
|
|
62
|
+
}
|
|
63
|
+
/** `wt.embedded.file.size` and `wt.embedded.wal.size` (the `.wal` file) of a DuckDB database file. Returns `stop()`. */
|
|
64
|
+
function observeDuckDBFile(path) {
|
|
65
|
+
return (0, db_js_1.observeEmbedded)('duckdb', nodePath.basename(path), ['file.size', 'wal.size'], () => ({ 'file.size': (0, db_js_1.sizeOf)(path), 'wal.size': (0, db_js_1.sizeOf)(`${path}.wal`) }));
|
|
66
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** The slice of an Express request this integration reads. */
|
|
2
|
+
export interface ExpressRequest {
|
|
3
|
+
method: string;
|
|
4
|
+
originalUrl?: string;
|
|
5
|
+
url?: string;
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
route?: {
|
|
8
|
+
path: string;
|
|
9
|
+
};
|
|
10
|
+
/** Parsed by a body parser before this handler's span ends (payload capture). */
|
|
11
|
+
body?: unknown;
|
|
12
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
13
|
+
}
|
|
14
|
+
/** The slice of an Express response this integration reads. */
|
|
15
|
+
export interface ExpressResponse {
|
|
16
|
+
statusCode: number;
|
|
17
|
+
on(event: string, listener: () => void): unknown;
|
|
18
|
+
write?: (...a: unknown[]) => boolean;
|
|
19
|
+
end?: (...a: unknown[]) => unknown;
|
|
20
|
+
getHeader?: (name: string) => unknown;
|
|
21
|
+
}
|
|
22
|
+
/** app.use(requestHandler()) first: a server span per request, named by the matched route. */
|
|
23
|
+
export declare function requestHandler(): (req: ExpressRequest, res: ExpressResponse, next: (err?: unknown) => void) => void;
|
|
24
|
+
/** app.use(errorHandler()) after all routes: captures 5xx errors, then passes them on. */
|
|
25
|
+
export declare function errorHandler(): (err: unknown, req: ExpressRequest, res: ExpressResponse, next: (err?: unknown) => void) => void;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.requestHandler = requestHandler;
|
|
4
|
+
exports.errorHandler = errorHandler;
|
|
5
|
+
const api_1 = require("@opentelemetry/api");
|
|
6
|
+
const errors_js_1 = require("../errors.js");
|
|
7
|
+
const payload_js_1 = require("../payload.js");
|
|
8
|
+
const util_js_1 = require("./util.js");
|
|
9
|
+
/** Keep the first HARD_MAX * 2 response bytes for payload capture; the response itself is untouched. */
|
|
10
|
+
function tapBody(res) {
|
|
11
|
+
const chunks = [];
|
|
12
|
+
let size = 0;
|
|
13
|
+
const keep = (c) => {
|
|
14
|
+
if (size >= payload_js_1.HARD_MAX * 2 || (typeof c !== 'string' && !Buffer.isBuffer(c)))
|
|
15
|
+
return;
|
|
16
|
+
const b = Buffer.isBuffer(c) ? c : Buffer.from(c);
|
|
17
|
+
chunks.push(b);
|
|
18
|
+
size += b.length;
|
|
19
|
+
};
|
|
20
|
+
const { write, end } = res;
|
|
21
|
+
if (write)
|
|
22
|
+
res.write = (...a) => { keep(a[0]); return write.apply(res, a); };
|
|
23
|
+
if (end)
|
|
24
|
+
res.end = (...a) => { if (typeof a[0] !== 'function')
|
|
25
|
+
keep(a[0]); return end.apply(res, a); };
|
|
26
|
+
return () => Buffer.concat(chunks).toString('utf8');
|
|
27
|
+
}
|
|
28
|
+
/** app.use(requestHandler()) first: a server span per request, named by the matched route. */
|
|
29
|
+
function requestHandler() {
|
|
30
|
+
return (req, res, next) => {
|
|
31
|
+
const s = (0, util_js_1.serverSpan)(req.method, req.originalUrl || req.url);
|
|
32
|
+
let body = (0, payload_js_1.captureActive)() ? tapBody(res) : undefined;
|
|
33
|
+
const end = () => {
|
|
34
|
+
const route = req.route ? `${req.baseUrl || ''}${req.route.path}` : undefined;
|
|
35
|
+
if (body) {
|
|
36
|
+
const h = req.headers || {};
|
|
37
|
+
(0, payload_js_1.capturePayload)(s.span, {
|
|
38
|
+
route: route || String(req.originalUrl || req.url || '').split('?')[0],
|
|
39
|
+
reqType: String(h['content-type'] || ''), reqBody: req.body,
|
|
40
|
+
resType: String((res.getHeader && res.getHeader('content-type')) || ''), resBody: body(),
|
|
41
|
+
});
|
|
42
|
+
body = undefined; // 'finish' and 'close' both fire; capture once
|
|
43
|
+
}
|
|
44
|
+
s.finish(res.statusCode, route);
|
|
45
|
+
};
|
|
46
|
+
res.on('finish', end);
|
|
47
|
+
res.on('close', end);
|
|
48
|
+
api_1.context.with(s.ctx, next);
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** app.use(errorHandler()) after all routes: captures 5xx errors, then passes them on. */
|
|
52
|
+
function errorHandler() {
|
|
53
|
+
return (err, req, _res, next) => {
|
|
54
|
+
if ((0, util_js_1.statusOf)(err) >= 500)
|
|
55
|
+
(0, errors_js_1.captureException)(err, { attributes: { 'http.route': req.route && req.route.path } });
|
|
56
|
+
next(err);
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** The slice of a Fastify instance this plugin uses. `any` args: Fastify types each hook's handler separately. */
|
|
2
|
+
export interface FastifyLike {
|
|
3
|
+
addHook(name: string, fn: (...args: any[]) => void): unknown;
|
|
4
|
+
}
|
|
5
|
+
/** await app.register(plugin): server span per request plus 5xx error capture. */
|
|
6
|
+
export declare function plugin(fastify: FastifyLike, _opts: unknown, done: (err?: Error) => void): void;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.plugin = plugin;
|
|
4
|
+
const api_1 = require("@opentelemetry/api");
|
|
5
|
+
const errors_js_1 = require("../errors.js");
|
|
6
|
+
const payload_js_1 = require("../payload.js");
|
|
7
|
+
const util_js_1 = require("./util.js");
|
|
8
|
+
const KEY = Symbol('wt.span');
|
|
9
|
+
const SENT = Symbol('wt.sent');
|
|
10
|
+
/** await app.register(plugin): server span per request plus 5xx error capture. */
|
|
11
|
+
function plugin(fastify, _opts, done) {
|
|
12
|
+
fastify.addHook('onRequest', (req, _reply, next) => {
|
|
13
|
+
const s = (0, util_js_1.serverSpan)(req.method, req.url);
|
|
14
|
+
req[KEY] = s;
|
|
15
|
+
api_1.context.with(s.ctx, next);
|
|
16
|
+
});
|
|
17
|
+
fastify.addHook('onError', (_req, _reply, err, next) => {
|
|
18
|
+
if ((0, util_js_1.statusOf)(err) >= 500)
|
|
19
|
+
(0, errors_js_1.captureException)(err);
|
|
20
|
+
next();
|
|
21
|
+
});
|
|
22
|
+
// the serialized response body (string, Buffer or stream); passed on unchanged
|
|
23
|
+
fastify.addHook('onSend', (req, _reply, payload, next) => {
|
|
24
|
+
if ((0, payload_js_1.captureActive)())
|
|
25
|
+
req[SENT] = payload;
|
|
26
|
+
next(null, payload);
|
|
27
|
+
});
|
|
28
|
+
fastify.addHook('onResponse', (req, reply, next) => {
|
|
29
|
+
const route = (req.routeOptions && req.routeOptions.url) || req.routerPath;
|
|
30
|
+
const s = req[KEY];
|
|
31
|
+
if (s && (0, payload_js_1.captureActive)()) {
|
|
32
|
+
(0, payload_js_1.capturePayload)(s.span, {
|
|
33
|
+
route: route || req.url.split('?')[0],
|
|
34
|
+
reqType: String((req.headers && req.headers['content-type']) || ''), reqBody: req.body,
|
|
35
|
+
resType: String((reply.getHeader && reply.getHeader('content-type')) || ''), resBody: req[SENT],
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
if (s)
|
|
39
|
+
s.finish(reply.statusCode, route);
|
|
40
|
+
next();
|
|
41
|
+
});
|
|
42
|
+
done();
|
|
43
|
+
}
|
|
44
|
+
plugin[Symbol.for('skip-override')] = true; // what fastify-plugin sets: hooks apply app-wide
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Span } from '@opentelemetry/api';
|
|
2
|
+
type Obj = Record<string, unknown>;
|
|
3
|
+
/** The part of LlamaIndex.TS `Settings.callbackManager` used here. */
|
|
4
|
+
export interface CallbackManagerLike {
|
|
5
|
+
on(event: string, handler: (e: {
|
|
6
|
+
detail?: unknown;
|
|
7
|
+
}) => void): unknown;
|
|
8
|
+
}
|
|
9
|
+
/** instrumentLlamaIndex(Settings) (from `llamaindex`): llm-start/stream/end and tool call events as spans. */
|
|
10
|
+
export declare function instrumentLlamaIndex(settings: {
|
|
11
|
+
callbackManager: CallbackManagerLike;
|
|
12
|
+
}): {
|
|
13
|
+
open: Map<string, Span>;
|
|
14
|
+
};
|
|
15
|
+
/** An OpenAI Agents SDK span as the trace processor sees it. */
|
|
16
|
+
interface AgentSpan {
|
|
17
|
+
spanId?: string;
|
|
18
|
+
parentId?: string | null;
|
|
19
|
+
spanData?: Obj;
|
|
20
|
+
error?: {
|
|
21
|
+
message?: string;
|
|
22
|
+
} | null;
|
|
23
|
+
}
|
|
24
|
+
/** The processor `addTraceProcessor` takes (`@openai/agents`). */
|
|
25
|
+
export declare class AgentsProcessor {
|
|
26
|
+
readonly open: Map<string, Span>;
|
|
27
|
+
onTraceStart(): Promise<void>;
|
|
28
|
+
onTraceEnd(): Promise<void>;
|
|
29
|
+
onSpanStart(sp: AgentSpan): Promise<void>;
|
|
30
|
+
onSpanEnd(sp: AgentSpan): Promise<void>;
|
|
31
|
+
shutdown(): Promise<void>;
|
|
32
|
+
forceFlush(): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
/** instrumentOpenAIAgents(addTraceProcessor) with `addTraceProcessor` from `@openai/agents`; the SDK's own tracing keeps running. */
|
|
35
|
+
export declare function instrumentOpenAIAgents(addTraceProcessor: (p: AgentsProcessor) => void): AgentsProcessor;
|
|
36
|
+
export {};
|