@watchtowerobservability/node 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +186 -3
  2. package/dist/cjs/appsec.d.ts +95 -0
  3. package/dist/cjs/appsec.js +206 -0
  4. package/dist/cjs/index.d.ts +3 -0
  5. package/dist/cjs/index.js +14 -1
  6. package/dist/cjs/integrations/amqp.d.ts +13 -0
  7. package/dist/cjs/integrations/amqp.js +96 -0
  8. package/dist/cjs/integrations/bullmq.d.ts +19 -0
  9. package/dist/cjs/integrations/bullmq.js +83 -0
  10. package/dist/cjs/integrations/cache.d.ts +13 -0
  11. package/dist/cjs/integrations/cache.js +51 -0
  12. package/dist/cjs/integrations/db.d.ts +62 -0
  13. package/dist/cjs/integrations/db.js +288 -0
  14. package/dist/cjs/integrations/duckdb.d.ts +22 -0
  15. package/dist/cjs/integrations/duckdb.js +66 -0
  16. package/dist/cjs/integrations/graphile-worker.d.ts +22 -0
  17. package/dist/cjs/integrations/graphile-worker.js +50 -0
  18. package/dist/cjs/integrations/level.d.ts +18 -0
  19. package/dist/cjs/integrations/level.js +71 -0
  20. package/dist/cjs/integrations/lmdb.d.ts +26 -0
  21. package/dist/cjs/integrations/lmdb.js +78 -0
  22. package/dist/cjs/integrations/messaging.d.ts +17 -0
  23. package/dist/cjs/integrations/messaging.js +73 -0
  24. package/dist/cjs/integrations/mqtt.d.ts +7 -0
  25. package/dist/cjs/integrations/mqtt.js +41 -0
  26. package/dist/cjs/integrations/nats.d.ts +17 -0
  27. package/dist/cjs/integrations/nats.js +73 -0
  28. package/dist/cjs/integrations/orm.d.ts +47 -0
  29. package/dist/cjs/integrations/orm.js +93 -0
  30. package/dist/cjs/integrations/pg-boss.d.ts +8 -0
  31. package/dist/cjs/integrations/pg-boss.js +63 -0
  32. package/dist/cjs/integrations/pools.d.ts +41 -0
  33. package/dist/cjs/integrations/pools.js +94 -0
  34. package/dist/cjs/integrations/postgres.d.ts +12 -0
  35. package/dist/cjs/integrations/postgres.js +92 -0
  36. package/dist/cjs/integrations/sqlite.d.ts +36 -0
  37. package/dist/cjs/integrations/sqlite.js +125 -0
  38. package/dist/cjs/pprof.d.ts +6 -0
  39. package/dist/cjs/pprof.js +88 -0
  40. package/dist/cjs/profiling.d.ts +4 -1
  41. package/dist/cjs/profiling.js +18 -8
  42. package/dist/cjs/sql.d.ts +19 -0
  43. package/dist/cjs/sql.js +332 -0
  44. package/dist/cjs/test-plan.d.ts +10 -1
  45. package/dist/cjs/test-plan.js +91 -1
  46. package/dist/esm/appsec.d.ts +95 -0
  47. package/dist/esm/appsec.js +193 -0
  48. package/dist/esm/index.d.ts +3 -0
  49. package/dist/esm/index.js +14 -1
  50. package/dist/esm/integrations/amqp.d.ts +13 -0
  51. package/dist/esm/integrations/amqp.js +92 -0
  52. package/dist/esm/integrations/bullmq.d.ts +19 -0
  53. package/dist/esm/integrations/bullmq.js +79 -0
  54. package/dist/esm/integrations/cache.d.ts +13 -0
  55. package/dist/esm/integrations/cache.js +46 -0
  56. package/dist/esm/integrations/db.d.ts +62 -0
  57. package/dist/esm/integrations/db.js +239 -0
  58. package/dist/esm/integrations/duckdb.d.ts +22 -0
  59. package/dist/esm/integrations/duckdb.js +29 -0
  60. package/dist/esm/integrations/graphile-worker.d.ts +22 -0
  61. package/dist/esm/integrations/graphile-worker.js +46 -0
  62. package/dist/esm/integrations/level.d.ts +18 -0
  63. package/dist/esm/integrations/level.js +35 -0
  64. package/dist/esm/integrations/lmdb.d.ts +26 -0
  65. package/dist/esm/integrations/lmdb.js +42 -0
  66. package/dist/esm/integrations/messaging.d.ts +17 -0
  67. package/dist/esm/integrations/messaging.js +64 -0
  68. package/dist/esm/integrations/mqtt.d.ts +7 -0
  69. package/dist/esm/integrations/mqtt.js +38 -0
  70. package/dist/esm/integrations/nats.d.ts +17 -0
  71. package/dist/esm/integrations/nats.js +70 -0
  72. package/dist/esm/integrations/orm.d.ts +47 -0
  73. package/dist/esm/integrations/orm.js +86 -0
  74. package/dist/esm/integrations/pg-boss.d.ts +8 -0
  75. package/dist/esm/integrations/pg-boss.js +60 -0
  76. package/dist/esm/integrations/pools.d.ts +41 -0
  77. package/dist/esm/integrations/pools.js +89 -0
  78. package/dist/esm/integrations/postgres.d.ts +12 -0
  79. package/dist/esm/integrations/postgres.js +55 -0
  80. package/dist/esm/integrations/sqlite.d.ts +36 -0
  81. package/dist/esm/integrations/sqlite.js +84 -0
  82. package/dist/esm/pprof.d.ts +6 -0
  83. package/dist/esm/pprof.js +85 -0
  84. package/dist/esm/profiling.d.ts +4 -1
  85. package/dist/esm/profiling.js +17 -8
  86. package/dist/esm/sql.d.ts +19 -0
  87. package/dist/esm/sql.js +324 -0
  88. package/dist/esm/test-plan.d.ts +10 -1
  89. package/dist/esm/test-plan.js +89 -1
  90. package/package.json +161 -1
@@ -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,22 @@
1
+ interface Helpers {
2
+ job?: {
3
+ id?: string | number;
4
+ attempts?: number;
5
+ queue_name?: string | null;
6
+ };
7
+ addJob?: unknown;
8
+ }
9
+ type Task = (payload: unknown, helpers: Helpers) => unknown;
10
+ /**
11
+ * `instrumentAddJob(utils)` (from `makeWorkerUtils`, or the runner from `run`): a PRODUCER span on
12
+ * `addJob` with the trace context in the payload under `_wt` (object payloads only).
13
+ * shortcut: the module-level `quickAddJob` cannot be patched under ESM; use `utils.addJob`.
14
+ */
15
+ export declare function instrumentAddJob(utilsOrRunner: object): void;
16
+ /**
17
+ * `run({ taskList: wrapTaskList({ send_email: async (payload, helpers) => ... }) })`: each task runs
18
+ * in a CONSUMER span, child of and linked to the `addJob` that queued it; `_wt` is removed from the
19
+ * payload first, and `helpers.addJob` is instrumented so follow-up jobs stay in the trace.
20
+ */
21
+ export declare function wrapTaskList<T extends Record<string, Task>>(tasks: T): T;
22
+ export {};
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.instrumentAddJob = instrumentAddJob;
4
+ exports.wrapTaskList = wrapTaskList;
5
+ const api_1 = require("@opentelemetry/api");
6
+ const db_js_1 = require("./db.js");
7
+ const messaging_js_1 = require("./messaging.js");
8
+ const attrs = (task, type, op) => ({
9
+ 'messaging.system': 'graphile-worker',
10
+ 'messaging.destination.name': task,
11
+ 'messaging.operation.type': type,
12
+ 'messaging.operation.name': op,
13
+ });
14
+ /**
15
+ * `instrumentAddJob(utils)` (from `makeWorkerUtils`, or the runner from `run`): a PRODUCER span on
16
+ * `addJob` with the trace context in the payload under `_wt` (object payloads only).
17
+ * shortcut: the module-level `quickAddJob` cannot be patched under ESM; use `utils.addJob`.
18
+ */
19
+ function instrumentAddJob(utilsOrRunner) {
20
+ (0, db_js_1.patch)(utilsOrRunner, 'addJob', (orig) => function (identifier, payload, ...rest) {
21
+ return (0, messaging_js_1.produce)(`send ${identifier}`, attrs(identifier, 'send', 'addJob'), () => {
22
+ const span = api_1.trace.getActiveSpan();
23
+ return orig.call(this, identifier, (0, messaging_js_1.injectData)(payload ?? {}), ...rest).then((job) => {
24
+ if (job?.id !== undefined)
25
+ span?.setAttribute('messaging.message.id', String(job.id));
26
+ return job;
27
+ });
28
+ });
29
+ });
30
+ }
31
+ /**
32
+ * `run({ taskList: wrapTaskList({ send_email: async (payload, helpers) => ... }) })`: each task runs
33
+ * in a CONSUMER span, child of and linked to the `addJob` that queued it; `_wt` is removed from the
34
+ * payload first, and `helpers.addJob` is instrumented so follow-up jobs stay in the trace.
35
+ */
36
+ function wrapTaskList(tasks) {
37
+ return Object.fromEntries(Object.entries(tasks).map(([name, fn]) => [name, (payload, helpers) => {
38
+ const carrier = (0, messaging_js_1.takeContext)(payload);
39
+ const a = attrs(name, 'process', 'task');
40
+ if (helpers?.job?.id !== undefined)
41
+ a['messaging.message.id'] = String(helpers.job.id);
42
+ if (helpers?.job?.attempts !== undefined)
43
+ a['messaging.graphile_worker.job.attempt'] = helpers.job.attempts;
44
+ if (helpers?.job?.queue_name)
45
+ a['messaging.consumer.group.name'] = helpers.job.queue_name;
46
+ if (helpers)
47
+ instrumentAddJob(helpers);
48
+ return (0, messaging_js_1.consume)(`process ${name}`, a, [carrier], () => fn(payload, helpers));
49
+ }]));
50
+ }
@@ -0,0 +1,18 @@
1
+ import type { DbOptions } from './db.js';
2
+ interface LevelDb {
3
+ location?: string;
4
+ sublevel?(...a: unknown[]): object;
5
+ }
6
+ /**
7
+ * `instrumentLevel(new ClassicLevel(dir))`, or `instrumentLevel(rocksdb(dir), { system: 'rocksdb' })`:
8
+ * a span per `get`/`getMany`/`put`/`del`/`batch`/`clear` (promise or callback form; keys and values
9
+ * are never recorded), on the db and on its sublevels (`db.collection.name`). With `metrics` (default
10
+ * on) and a `location`, `wt.embedded.file.size` reports the size of the store's directory.
11
+ * Returns `stop()` for the gauge.
12
+ * shortcut: iterators and the chained `batch()` builder are not traced.
13
+ */
14
+ export declare function instrumentLevel(db: LevelDb, opts?: DbOptions & {
15
+ system?: 'leveldb' | 'rocksdb';
16
+ metrics?: boolean;
17
+ }): () => void;
18
+ export {};
@@ -0,0 +1,71 @@
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.instrumentLevel = instrumentLevel;
37
+ const nodePath = __importStar(require("node:path"));
38
+ const db_js_1 = require("./db.js");
39
+ const OPS = ['get', 'getMany', 'put', 'del', 'batch', 'clear'];
40
+ /**
41
+ * `instrumentLevel(new ClassicLevel(dir))`, or `instrumentLevel(rocksdb(dir), { system: 'rocksdb' })`:
42
+ * a span per `get`/`getMany`/`put`/`del`/`batch`/`clear` (promise or callback form; keys and values
43
+ * are never recorded), on the db and on its sublevels (`db.collection.name`). With `metrics` (default
44
+ * on) and a `location`, `wt.embedded.file.size` reports the size of the store's directory.
45
+ * Returns `stop()` for the gauge.
46
+ * shortcut: iterators and the chained `batch()` builder are not traced.
47
+ */
48
+ function instrumentLevel(db, opts) {
49
+ const system = opts?.system ?? 'leveldb';
50
+ const namespace = db.location ? nodePath.basename(db.location) : undefined;
51
+ const wrap = (d, collection) => {
52
+ for (const m of OPS) {
53
+ (0, db_js_1.patch)(d, m, (orig) => function (...a) {
54
+ if (m === 'batch' && a.length === 0)
55
+ return orig.call(this); // chained builder
56
+ return (0, db_js_1.tracedCb)({ system, operation: m, collection, namespace }, opts, a, (args) => orig.apply(this, args));
57
+ });
58
+ }
59
+ (0, db_js_1.patch)(d, 'sublevel', (orig) => function (...a) {
60
+ const sub = orig.apply(this, a);
61
+ if (sub)
62
+ wrap(sub, typeof a[0] === 'string' ? a[0] : undefined);
63
+ return sub;
64
+ });
65
+ };
66
+ wrap(db);
67
+ const dir = db.location;
68
+ if (opts?.metrics === false || !dir)
69
+ return () => { };
70
+ return (0, db_js_1.observeEmbedded)(system, namespace, ['file.size'], () => ({ 'file.size': (0, db_js_1.sizeOf)(dir) }));
71
+ }
@@ -0,0 +1,26 @@
1
+ import type { DbOptions } from './db.js';
2
+ interface LmdbStats {
3
+ pageSize?: number;
4
+ mapSize?: number;
5
+ lastPageNumber?: number;
6
+ entryCount?: number;
7
+ numReaders?: number;
8
+ }
9
+ interface LmdbDb {
10
+ path?: string;
11
+ name?: string;
12
+ getStats?(): LmdbStats;
13
+ openDB?(...a: unknown[]): object;
14
+ }
15
+ /**
16
+ * `instrumentLmdb(open({ path }))` (lmdb-js): spans for async writes (`put`, `remove`, `ifVersion`,
17
+ * `ifNoExists`, `clearAsync`, `drop`), `getMany` and `transaction` (calls inside a transaction get
18
+ * child spans), on the root and on every `openDB` sub-database (`db.collection.name`). Sync reads
19
+ * (`get`) are memory-mapped and take microseconds, so they get no span. With `metrics` (default on)
20
+ * it also reports `wt.embedded.map.size`, `.map.used`, `.entries`, `.readers` and `.file.size`.
21
+ * Returns `stop()` for the gauges.
22
+ */
23
+ export declare function instrumentLmdb(db: LmdbDb, opts?: DbOptions & {
24
+ metrics?: boolean;
25
+ }): () => void;
26
+ export {};
@@ -0,0 +1,78 @@
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.instrumentLmdb = instrumentLmdb;
37
+ const nodePath = __importStar(require("node:path"));
38
+ const db_js_1 = require("./db.js");
39
+ const WRITES = ['put', 'remove', 'ifVersion', 'ifNoExists', 'clearAsync', 'drop', 'getMany', 'prefetch'];
40
+ /**
41
+ * `instrumentLmdb(open({ path }))` (lmdb-js): spans for async writes (`put`, `remove`, `ifVersion`,
42
+ * `ifNoExists`, `clearAsync`, `drop`), `getMany` and `transaction` (calls inside a transaction get
43
+ * child spans), on the root and on every `openDB` sub-database (`db.collection.name`). Sync reads
44
+ * (`get`) are memory-mapped and take microseconds, so they get no span. With `metrics` (default on)
45
+ * it also reports `wt.embedded.map.size`, `.map.used`, `.entries`, `.readers` and `.file.size`.
46
+ * Returns `stop()` for the gauges.
47
+ */
48
+ function instrumentLmdb(db, opts) {
49
+ const namespace = db.path ? nodePath.basename(db.path) : undefined;
50
+ const wrap = (d, collection) => {
51
+ for (const m of WRITES) {
52
+ (0, db_js_1.patch)(d, m, (orig) => function (...a) {
53
+ return (0, db_js_1.traced)({ system: 'lmdb', operation: m, collection, namespace }, opts, () => orig.apply(this, a));
54
+ });
55
+ }
56
+ (0, db_js_1.patch)(d, 'transaction', (orig) => function (...a) {
57
+ return (0, db_js_1.traced)({ system: 'lmdb', operation: 'transaction', collection, namespace }, opts, () => orig.apply(this, a), false);
58
+ });
59
+ (0, db_js_1.patch)(d, 'openDB', (orig) => function (...a) {
60
+ const sub = orig.apply(this, a);
61
+ const name = typeof a[0] === 'string' ? a[0] : a[0]?.name;
62
+ if (sub)
63
+ wrap(sub, name ?? sub.name);
64
+ return sub;
65
+ });
66
+ };
67
+ wrap(db);
68
+ if (opts?.metrics === false || typeof db.getStats !== 'function')
69
+ return () => { };
70
+ return (0, db_js_1.observeEmbedded)('lmdb', namespace, ['map.size', 'map.used', 'entries', 'readers', 'file.size'], () => {
71
+ const s = db.getStats();
72
+ const used = s.pageSize !== undefined && s.lastPageNumber !== undefined ? (s.lastPageNumber + 1) * s.pageSize : undefined;
73
+ return {
74
+ 'map.size': s.mapSize, 'map.used': used, entries: s.entryCount, readers: s.numReaders,
75
+ 'file.size': db.path ? (0, db_js_1.sizeOf)(db.path) : undefined,
76
+ };
77
+ });
78
+ }
@@ -0,0 +1,17 @@
1
+ import type { Attributes } from '@opentelemetry/api';
2
+ /** Key in job data that carries the producer's trace context (W3C `traceparent`/`tracestate`). */
3
+ export declare const CONTEXT_KEY = "_wt";
4
+ export declare function isPlainObject(v: unknown): v is Record<string, unknown>;
5
+ /** The active context as W3C headers. */
6
+ export declare function headers(): Record<string, string>;
7
+ /** Copy of `data` carrying the active context under `_wt`; non-object data is returned unchanged. */
8
+ export declare function injectData(data: unknown): unknown;
9
+ /** Remove and return the `_wt` carrier from object job data. */
10
+ export declare function takeContext(data: unknown): Record<string, unknown> | undefined;
11
+ /** A PRODUCER span around `fn`, which gets the headers to send (the producer span's context). */
12
+ export declare function produce<T>(name: string, attributes: Attributes, fn: (h: Record<string, string>) => T): T;
13
+ /**
14
+ * A CONSUMER span around `fn`, linked to the producer context of each carrier (header maps whose
15
+ * values may be strings or Buffers). With exactly one carrier the producer span is also the parent.
16
+ */
17
+ export declare function consume<T>(name: string, attributes: Attributes, carriers: Array<Record<string, unknown> | undefined>, fn: () => T): T;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONTEXT_KEY = void 0;
4
+ exports.isPlainObject = isPlainObject;
5
+ exports.headers = headers;
6
+ exports.injectData = injectData;
7
+ exports.takeContext = takeContext;
8
+ exports.produce = produce;
9
+ exports.consume = consume;
10
+ // Shared core for queue and broker integrations: PRODUCER spans that hand out W3C headers, and
11
+ // CONSUMER spans parented by (and linked to) the producer, so the server can compute lag.
12
+ const api_1 = require("@opentelemetry/api");
13
+ const db_js_1 = require("./db.js");
14
+ /** Key in job data that carries the producer's trace context (W3C `traceparent`/`tracestate`). */
15
+ exports.CONTEXT_KEY = '_wt';
16
+ function isPlainObject(v) {
17
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
18
+ }
19
+ /** The active context as W3C headers. */
20
+ function headers() {
21
+ const carrier = {};
22
+ api_1.propagation.inject(api_1.context.active(), carrier);
23
+ return carrier;
24
+ }
25
+ /** Copy of `data` carrying the active context under `_wt`; non-object data is returned unchanged. */
26
+ function injectData(data) {
27
+ if (data !== undefined && !isPlainObject(data))
28
+ return data;
29
+ const carrier = headers();
30
+ return Object.keys(carrier).length ? { ...data, [exports.CONTEXT_KEY]: carrier } : data;
31
+ }
32
+ /** Remove and return the `_wt` carrier from object job data. */
33
+ function takeContext(data) {
34
+ if (!isPlainObject(data) || !isPlainObject(data[exports.CONTEXT_KEY]))
35
+ return undefined;
36
+ const c = data[exports.CONTEXT_KEY];
37
+ delete data[exports.CONTEXT_KEY];
38
+ return c;
39
+ }
40
+ /** A PRODUCER span around `fn`, which gets the headers to send (the producer span's context). */
41
+ function produce(name, attributes, fn) {
42
+ const parent = api_1.context.active();
43
+ if ((0, db_js_1.inside)(parent))
44
+ return fn(headers());
45
+ const span = api_1.trace.getTracer('watchtower').startSpan(name, { kind: api_1.SpanKind.PRODUCER, attributes }, parent);
46
+ return (0, db_js_1.settle)(span, () => api_1.context.with((0, db_js_1.enter)(parent, span), () => fn(headers())));
47
+ }
48
+ const str = (v) => (typeof v === 'string' ? v : v instanceof Uint8Array ? Buffer.from(v).toString() : undefined);
49
+ /**
50
+ * A CONSUMER span around `fn`, linked to the producer context of each carrier (header maps whose
51
+ * values may be strings or Buffers). With exactly one carrier the producer span is also the parent.
52
+ */
53
+ function consume(name, attributes, carriers, fn) {
54
+ let parent = api_1.context.active();
55
+ const links = [];
56
+ for (const c of carriers) {
57
+ if (!c)
58
+ continue;
59
+ const tp = str(c.traceparent);
60
+ if (!tp)
61
+ continue;
62
+ const ts = str(c.tracestate);
63
+ const ctx = api_1.propagation.extract(parent, { traceparent: tp, ...(ts ? { tracestate: ts } : {}) });
64
+ const sc = api_1.trace.getSpanContext(ctx);
65
+ if (!sc || !api_1.trace.isSpanContextValid(sc))
66
+ continue;
67
+ links.push({ context: sc });
68
+ if (carriers.length === 1)
69
+ parent = ctx;
70
+ }
71
+ const span = api_1.trace.getTracer('watchtower').startSpan(name, { kind: api_1.SpanKind.CONSUMER, attributes, links }, parent);
72
+ return (0, db_js_1.settle)(span, () => api_1.context.with((0, db_js_1.enter)(parent, span, false), fn));
73
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `instrumentMqtt(mqtt.connect(url))` for mqtt.js: PRODUCER spans on `publish`/`publishAsync`, and a
3
+ * CONSUMER span around the client's `message` listeners. The trace context travels in MQTT 5 user
4
+ * properties, so only `protocolVersion: 5` clients propagate (older clients get unlinked spans).
5
+ * shortcut: `publish` spans end when the call returns, not at the QoS 1/2 ack; use `publishAsync` for ack time.
6
+ */
7
+ export declare function instrumentMqtt(client: object): void;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.instrumentMqtt = instrumentMqtt;
4
+ const db_js_1 = require("./db.js");
5
+ const messaging_js_1 = require("./messaging.js");
6
+ const attrs = (topic, type, op, payload, id) => ({
7
+ 'messaging.system': 'mqtt',
8
+ 'messaging.destination.name': topic,
9
+ 'messaging.operation.type': type,
10
+ 'messaging.operation.name': op,
11
+ ...(typeof payload === 'string' || payload instanceof Uint8Array ? { 'messaging.message.body.size': payload.length } : {}),
12
+ ...(id !== undefined ? { 'messaging.message.id': String(id) } : {}),
13
+ });
14
+ /**
15
+ * `instrumentMqtt(mqtt.connect(url))` for mqtt.js: PRODUCER spans on `publish`/`publishAsync`, and a
16
+ * CONSUMER span around the client's `message` listeners. The trace context travels in MQTT 5 user
17
+ * properties, so only `protocolVersion: 5` clients propagate (older clients get unlinked spans).
18
+ * shortcut: `publish` spans end when the call returns, not at the QoS 1/2 ack; use `publishAsync` for ack time.
19
+ */
20
+ function instrumentMqtt(client) {
21
+ const v5 = () => client.options?.protocolVersion === 5;
22
+ (0, db_js_1.patch)(client, 'publish', (orig) => function (topic, message, opts, cb) {
23
+ if (typeof opts === 'function')
24
+ [cb, opts] = [opts, undefined];
25
+ return (0, messaging_js_1.produce)(`publish ${topic}`, attrs(topic, 'send', 'publish', message), (h) => {
26
+ const o = opts;
27
+ const out = v5() ? { ...o, properties: { ...o?.properties, userProperties: { ...o?.properties?.userProperties, ...h } } } : o;
28
+ return cb === undefined ? orig.call(this, topic, message, out) : orig.call(this, topic, message, out ?? {}, cb);
29
+ });
30
+ });
31
+ // publishAsync calls publish, which then injects the context of this span
32
+ (0, db_js_1.patch)(client, 'publishAsync', (orig) => function (topic, message, ...rest) {
33
+ return (0, messaging_js_1.produce)(`publish ${topic}`, attrs(topic, 'send', 'publishAsync', message), () => orig.call(this, topic, message, ...rest));
34
+ });
35
+ (0, db_js_1.patch)(client, 'emit', (orig) => function (event, ...args) {
36
+ if (event !== 'message')
37
+ return orig.call(this, event, ...args);
38
+ const [topic, payload, packet] = args;
39
+ return (0, messaging_js_1.consume)(`process ${topic}`, attrs(topic, 'process', 'message', payload, packet?.messageId), [packet?.properties?.userProperties], () => orig.call(this, event, ...args));
40
+ });
41
+ }
@@ -0,0 +1,17 @@
1
+ interface MsgHdrs {
2
+ get(k: string): string;
3
+ set(k: string, v: string): void;
4
+ }
5
+ interface NatsModule {
6
+ headers(): MsgHdrs;
7
+ }
8
+ /**
9
+ * `instrumentNats(nc, nats)` (`import * as nats from 'nats'`; `nc = await nats.connect()`): patches the
10
+ * connection class. `publish`/`request` get PRODUCER spans with the context in NATS headers;
11
+ * `subscribe` messages get CONSUMER spans (child of and linked to the producer). With a `callback`
12
+ * subscription the span is active in the callback. With `for await (const m of sub)` each span runs
13
+ * from receipt to the next iteration and is not active in the loop body (child spans there are not
14
+ * parented to it; the producer link still gives lag).
15
+ */
16
+ export declare function instrumentNats(nc: object, nats: NatsModule): void;
17
+ export {};
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.instrumentNats = instrumentNats;
4
+ const db_js_1 = require("./db.js");
5
+ const messaging_js_1 = require("./messaging.js");
6
+ const attrs = (subject, type, op, data, queue) => ({
7
+ 'messaging.system': 'nats',
8
+ 'messaging.destination.name': subject,
9
+ 'messaging.operation.type': type,
10
+ 'messaging.operation.name': op,
11
+ ...(typeof data?.length === 'number' ? { 'messaging.message.body.size': data.length } : {}),
12
+ ...(queue ? { 'messaging.consumer.group.name': queue } : {}),
13
+ });
14
+ const carrier = (m) => ({ traceparent: m.headers?.get('traceparent'), tracestate: m.headers?.get('tracestate') });
15
+ /**
16
+ * `instrumentNats(nc, nats)` (`import * as nats from 'nats'`; `nc = await nats.connect()`): patches the
17
+ * connection class. `publish`/`request` get PRODUCER spans with the context in NATS headers;
18
+ * `subscribe` messages get CONSUMER spans (child of and linked to the producer). With a `callback`
19
+ * subscription the span is active in the callback. With `for await (const m of sub)` each span runs
20
+ * from receipt to the next iteration and is not active in the loop body (child spans there are not
21
+ * parented to it; the producer link still gives lag).
22
+ */
23
+ function instrumentNats(nc, nats) {
24
+ const proto = Object.getPrototypeOf(nc);
25
+ const withHeaders = (o, h) => {
26
+ const hdrs = o?.headers ?? nats.headers();
27
+ for (const [k, v] of Object.entries(h))
28
+ hdrs.set(k, v);
29
+ return { ...o, headers: hdrs };
30
+ };
31
+ (0, db_js_1.patch)(proto, 'publish', (orig) => function (subject, data, o) {
32
+ return (0, messaging_js_1.produce)(`send ${subject}`, attrs(subject, 'send', 'publish', data), (h) => orig.call(this, subject, data, withHeaders(o, h)));
33
+ });
34
+ (0, db_js_1.patch)(proto, 'request', (orig) => function (subject, data, o) {
35
+ return (0, messaging_js_1.produce)(`send ${subject}`, attrs(subject, 'send', 'request', data), (h) => orig.call(this, subject, data, withHeaders(o, h)));
36
+ });
37
+ (0, db_js_1.patch)(proto, 'subscribe', (orig) => function (subject, o) {
38
+ const cb = o?.callback;
39
+ if (typeof cb === 'function') {
40
+ const callback = (err, m) => (err || !m
41
+ ? cb(err, m)
42
+ : (0, messaging_js_1.consume)(`process ${m.subject}`, attrs(m.subject, 'process', 'subscribe', m.data, o?.queue), [carrier(m)], () => cb(err, m)));
43
+ return orig.call(this, subject, { ...o, callback });
44
+ }
45
+ const sub = orig.call(this, subject, o);
46
+ const iter = sub[Symbol.asyncIterator]?.bind(sub);
47
+ if (!iter)
48
+ return sub;
49
+ sub[Symbol.asyncIterator] = () => {
50
+ const inner = iter();
51
+ let end;
52
+ const close = () => { end?.(); end = undefined; };
53
+ return {
54
+ async next() {
55
+ close();
56
+ const r = await inner.next();
57
+ if (!r.done) {
58
+ const m = r.value;
59
+ // the span ends when this promise resolves, i.e. on the next iteration or return
60
+ void (0, messaging_js_1.consume)(`process ${m.subject}`, attrs(m.subject, 'process', 'subscribe', m.data, o?.queue), [carrier(m)], () => new Promise((res) => { end = res; }));
61
+ }
62
+ return r;
63
+ },
64
+ async return(v) {
65
+ close();
66
+ return inner.return ? inner.return(v) : { done: true, value: v };
67
+ },
68
+ [Symbol.asyncIterator]() { return this; },
69
+ };
70
+ };
71
+ return sub;
72
+ });
73
+ }
@@ -0,0 +1,47 @@
1
+ import type { DbOptions } from './db.js';
2
+ /**
3
+ * `instrumentDrizzle(db, 'postgresql')`: a CLIENT span per query a Drizzle database runs (`system`
4
+ * is the `db.system.name`: postgresql, mysql, sqlite, ...). Call once per `drizzle(...)` instance.
5
+ * shortcut: `db.transaction(tx => ...)` runs on its own session and gets no spans; instrument the
6
+ * driver as well if transactions matter.
7
+ */
8
+ export declare function instrumentDrizzle(db: object, system: string, opts?: DbOptions): void;
9
+ interface KyselyLogEvent {
10
+ level: 'query' | 'error';
11
+ query: {
12
+ sql: string;
13
+ };
14
+ queryDurationMillis: number;
15
+ error?: unknown;
16
+ }
17
+ /** `new Kysely({ dialect, log: kyselyLog('postgresql') })`; `next` still gets every event. */
18
+ export declare function kyselyLog(system: string, next?: (e: KyselyLogEvent) => void, opts?: DbOptions): (e: KyselyLogEvent) => void;
19
+ interface DataSourceLike {
20
+ options: {
21
+ type: string;
22
+ database?: unknown;
23
+ };
24
+ driver: object;
25
+ }
26
+ /** `instrumentTypeORM(dataSource)` (before or after `initialize`): a CLIENT span per `QueryRunner.query`. */
27
+ export declare function instrumentTypeORM(dataSource: DataSourceLike, opts?: DbOptions): void;
28
+ /**
29
+ * `new Sequelize(url, { benchmark: true, logging: sequelizeLogging('postgresql') })`: a span per
30
+ * executed query (only lines with a timing, so `benchmark: true` is required). `next` gets every call.
31
+ * shortcut: failed queries are not logged by Sequelize with a timing, so they get no span.
32
+ */
33
+ export declare function sequelizeLogging(system: string, next?: (sql: string, ...rest: unknown[]) => void, opts?: DbOptions): (sql: string, ...rest: unknown[]) => void;
34
+ interface MikroLogContext {
35
+ query?: string;
36
+ took?: number;
37
+ level?: string;
38
+ }
39
+ interface MikroLogger {
40
+ logQuery(context: MikroLogContext): void;
41
+ }
42
+ /**
43
+ * `MikroORM.init({ loggerFactory: mikroOrmLoggerFactory(DefaultLogger, 'postgresql') })`: a span per
44
+ * query MikroORM reports (with its `took`), then the `Base` logger logs as usual.
45
+ */
46
+ export declare function mikroOrmLoggerFactory<O, L extends MikroLogger>(Base: new (options: O) => L, system: string, opts?: DbOptions): (options: O) => L;
47
+ export {};