@reqray/instrumentation-pg 0.0.0-stage → 0.1.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 +13 -2
- package/dist/index.cjs +278 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +26 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +267 -0
- package/dist/index.js.map +1 -0
- package/package.json +72 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ruslan Kryklyvyi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @reqray/instrumentation-pg
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
pg driver instrumentation for Reqray.
|
|
4
|
+
|
|
5
|
+
Part of [Reqray](https://github.com/reqray/reqray) — a dev panel and request-inspection tool for
|
|
6
|
+
Node.js. It instruments HTTP, SQL, outgoing calls and cache on its own, shows
|
|
7
|
+
every request as a waterfall, and finds N+1 down to the file and the line.
|
|
8
|
+
|
|
9
|
+
Documentation, screenshots and a demo that runs with one command are in the
|
|
10
|
+
[main README](https://github.com/reqray/reqray#readme).
|
|
11
|
+
|
|
12
|
+
## License
|
|
13
|
+
|
|
14
|
+
[MIT](https://github.com/reqray/reqray/blob/main/LICENSE)
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
instrumentPg: () => instrumentPg
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(index_exports);
|
|
26
|
+
var import_core = require("@reqray/core");
|
|
27
|
+
var WAIT = /* @__PURE__ */ Symbol.for("reqray.pg.wait");
|
|
28
|
+
var MIN_WAIT_MS = 0.5;
|
|
29
|
+
function fingerprintOf(sql) {
|
|
30
|
+
try {
|
|
31
|
+
return (0, import_core.fingerprintSql)(sql);
|
|
32
|
+
} catch {
|
|
33
|
+
return sql;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function targetIdOf(candidate) {
|
|
37
|
+
try {
|
|
38
|
+
if (candidate === null || typeof candidate !== "object") return null;
|
|
39
|
+
return (0, import_core.registerExplainTarget)(candidate);
|
|
40
|
+
} catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
var known = /* @__PURE__ */ new WeakSet();
|
|
45
|
+
function readPool(pool) {
|
|
46
|
+
const candidate = pool;
|
|
47
|
+
const max = candidate.options?.max;
|
|
48
|
+
if (typeof max !== "number") return null;
|
|
49
|
+
return {
|
|
50
|
+
source: "pg",
|
|
51
|
+
max,
|
|
52
|
+
total: typeof candidate.totalCount === "number" ? candidate.totalCount : 0,
|
|
53
|
+
idle: typeof candidate.idleCount === "number" ? candidate.idleCount : 0,
|
|
54
|
+
waiting: typeof candidate.waitingCount === "number" ? candidate.waitingCount : 0
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function notePool(pool) {
|
|
58
|
+
try {
|
|
59
|
+
if (pool === null || typeof pool !== "object" || known.has(pool)) return;
|
|
60
|
+
known.add(pool);
|
|
61
|
+
(0, import_core.registerPool)(pool, readPool);
|
|
62
|
+
} catch {
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function queueing(pool) {
|
|
66
|
+
try {
|
|
67
|
+
if (pool === null || typeof pool !== "object") return false;
|
|
68
|
+
const candidate = pool;
|
|
69
|
+
const max = candidate.options?.max;
|
|
70
|
+
if (typeof max !== "number") return false;
|
|
71
|
+
const idle = typeof candidate.idleCount === "number" ? candidate.idleCount : 0;
|
|
72
|
+
const total = typeof candidate.totalCount === "number" ? candidate.totalCount : 0;
|
|
73
|
+
const waiting = typeof candidate.waitingCount === "number" ? candidate.waitingCount : 0;
|
|
74
|
+
return waiting >= idle + Math.max(0, max - total);
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function sqlOf(first) {
|
|
80
|
+
if (typeof first === "string") return first;
|
|
81
|
+
if (first && typeof first === "object") {
|
|
82
|
+
const text = first.text;
|
|
83
|
+
if (typeof text === "string") return text;
|
|
84
|
+
}
|
|
85
|
+
return void 0;
|
|
86
|
+
}
|
|
87
|
+
var MAX_VALUES = 50;
|
|
88
|
+
var MAX_VALUE_CHARS = 200;
|
|
89
|
+
function valuesOf(args) {
|
|
90
|
+
try {
|
|
91
|
+
const first = args[0];
|
|
92
|
+
const raw = typeof first === "object" && first !== null && Array.isArray(first.values) ? first.values : Array.isArray(args[1]) ? args[1] : null;
|
|
93
|
+
if (!raw) return null;
|
|
94
|
+
return raw.slice(0, MAX_VALUES).map((value) => {
|
|
95
|
+
const text = value === null || value === void 0 ? "NULL" : typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
96
|
+
return text.length > MAX_VALUE_CHARS ? `${text.slice(0, MAX_VALUE_CHARS)}\u2026` : text;
|
|
97
|
+
});
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function takeWait(client, scopeId) {
|
|
103
|
+
try {
|
|
104
|
+
if (client === null || typeof client !== "object") return null;
|
|
105
|
+
const holder = client;
|
|
106
|
+
const pending = holder[WAIT];
|
|
107
|
+
if (!pending) return null;
|
|
108
|
+
holder[WAIT] = null;
|
|
109
|
+
if (pending.scopeId !== scopeId) return null;
|
|
110
|
+
return pending.ms >= MIN_WAIT_MS ? pending.ms : null;
|
|
111
|
+
} catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function patchQuery(proto) {
|
|
116
|
+
(0, import_core.patchMethod)(
|
|
117
|
+
proto,
|
|
118
|
+
"query",
|
|
119
|
+
(original) => function reqrayQuery(...args) {
|
|
120
|
+
const scope = (0, import_core.current)();
|
|
121
|
+
if (!scope) return original.apply(this, args);
|
|
122
|
+
const sql = sqlOf(args[0]);
|
|
123
|
+
if (sql === void 0) return original.apply(this, args);
|
|
124
|
+
const startTime = performance.now();
|
|
125
|
+
const fingerprint = fingerprintOf(sql);
|
|
126
|
+
const callsite = (0, import_core.resolveCallsite)(scope, fingerprint, reqrayQuery);
|
|
127
|
+
const connectionId = targetIdOf(this);
|
|
128
|
+
const clientId = (0, import_core.handedCallsite)()?.clientId ?? connectionId;
|
|
129
|
+
const waitMs = takeWait(this, scope.id);
|
|
130
|
+
const values = scope.options.collectSqlValues ? valuesOf(args) : null;
|
|
131
|
+
const finish = (result2, error) => {
|
|
132
|
+
try {
|
|
133
|
+
const rowCount = result2?.rowCount;
|
|
134
|
+
(0, import_core.record)(scope, {
|
|
135
|
+
kind: "db",
|
|
136
|
+
sql,
|
|
137
|
+
fingerprint,
|
|
138
|
+
duration: performance.now() - startTime,
|
|
139
|
+
startTime,
|
|
140
|
+
rowCount: typeof rowCount === "number" ? rowCount : null,
|
|
141
|
+
source: "pg",
|
|
142
|
+
callsite,
|
|
143
|
+
clientId,
|
|
144
|
+
connectionId,
|
|
145
|
+
waitMs,
|
|
146
|
+
values,
|
|
147
|
+
error: (0, import_core.toSpanError)(error)
|
|
148
|
+
});
|
|
149
|
+
} catch {
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
const lastIndex = args.length - 1;
|
|
153
|
+
const callback = lastIndex >= 0 ? args[lastIndex] : void 0;
|
|
154
|
+
if (typeof callback === "function") {
|
|
155
|
+
args[lastIndex] = function reqrayCallback(error, result2) {
|
|
156
|
+
finish(result2, error);
|
|
157
|
+
return callback.call(this, error, result2);
|
|
158
|
+
};
|
|
159
|
+
return original.apply(this, args);
|
|
160
|
+
}
|
|
161
|
+
const result = original.apply(this, args);
|
|
162
|
+
if (result && typeof result.then === "function") {
|
|
163
|
+
return result.then(
|
|
164
|
+
(value) => {
|
|
165
|
+
finish(value, void 0);
|
|
166
|
+
return value;
|
|
167
|
+
},
|
|
168
|
+
(error) => {
|
|
169
|
+
finish(void 0, error);
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
return result;
|
|
175
|
+
}
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
function patchPoolQuery(proto) {
|
|
179
|
+
(0, import_core.patchMethod)(
|
|
180
|
+
proto,
|
|
181
|
+
"query",
|
|
182
|
+
(original) => function reqrayPoolQuery(...args) {
|
|
183
|
+
const scope = (0, import_core.current)();
|
|
184
|
+
if (!scope) return original.apply(this, args);
|
|
185
|
+
const sql = sqlOf(args[0]);
|
|
186
|
+
if (sql === void 0) return original.apply(this, args);
|
|
187
|
+
notePool(this);
|
|
188
|
+
const callsite = (0, import_core.resolveCallsite)(scope, fingerprintOf(sql), reqrayPoolQuery);
|
|
189
|
+
const clientId = targetIdOf(this);
|
|
190
|
+
return (0, import_core.withHandedCallsite)(
|
|
191
|
+
clientId === null ? { callsite } : { callsite, clientId },
|
|
192
|
+
() => original.apply(this, args)
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
function patchConnect(proto) {
|
|
198
|
+
(0, import_core.patchMethod)(
|
|
199
|
+
proto,
|
|
200
|
+
"connect",
|
|
201
|
+
(original) => function reqrayConnect(...args) {
|
|
202
|
+
const scope = (0, import_core.current)();
|
|
203
|
+
if (!scope) return original.apply(this, args);
|
|
204
|
+
notePool(this);
|
|
205
|
+
if (!queueing(this)) return original.apply(this, args);
|
|
206
|
+
const handed = (0, import_core.handedCallsite)();
|
|
207
|
+
const startTime = performance.now();
|
|
208
|
+
const stamp = (client) => {
|
|
209
|
+
try {
|
|
210
|
+
if (client !== null && typeof client === "object") {
|
|
211
|
+
client[WAIT] = {
|
|
212
|
+
ms: performance.now() - startTime,
|
|
213
|
+
scopeId: scope.id
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
} catch {
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
const lastIndex = args.length - 1;
|
|
220
|
+
const callback = lastIndex >= 0 ? args[lastIndex] : void 0;
|
|
221
|
+
if (typeof callback === "function") {
|
|
222
|
+
args[lastIndex] = function reqrayConnectCallback(...given) {
|
|
223
|
+
if (!given[0]) stamp(given[1]);
|
|
224
|
+
const dispatch = handed ? () => (0, import_core.withHandedCallsite)(handed, () => callback.apply(this, given)) : () => callback.apply(this, given);
|
|
225
|
+
return (0, import_core.runInScope)(scope, dispatch);
|
|
226
|
+
};
|
|
227
|
+
return original.apply(this, args);
|
|
228
|
+
}
|
|
229
|
+
const result = original.apply(this, args);
|
|
230
|
+
if (result && typeof result.then === "function") {
|
|
231
|
+
return result.then((client) => {
|
|
232
|
+
stamp(client);
|
|
233
|
+
return client;
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
return result;
|
|
237
|
+
}
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
function moduleOf(exports2) {
|
|
241
|
+
return exports2?.Client ? exports2 : exports2?.default ?? exports2;
|
|
242
|
+
}
|
|
243
|
+
function instrumentPg() {
|
|
244
|
+
return {
|
|
245
|
+
name: "pg",
|
|
246
|
+
supportedVersions: ">=8 <9",
|
|
247
|
+
captures: "SQL",
|
|
248
|
+
apply(exports2) {
|
|
249
|
+
(0, import_core.guarded)("pg", () => {
|
|
250
|
+
const pg = moduleOf(exports2);
|
|
251
|
+
patchQuery(pg?.Client?.prototype);
|
|
252
|
+
patchConnect(pg?.Pool?.prototype);
|
|
253
|
+
patchPoolQuery(pg?.Pool?.prototype);
|
|
254
|
+
try {
|
|
255
|
+
patchQuery(pg?.native?.Client?.prototype);
|
|
256
|
+
} catch {
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
},
|
|
260
|
+
unapply(exports2) {
|
|
261
|
+
(0, import_core.guarded)("pg", () => {
|
|
262
|
+
const pg = moduleOf(exports2);
|
|
263
|
+
(0, import_core.unpatchMethod)(pg?.Client?.prototype, "query");
|
|
264
|
+
(0, import_core.unpatchMethod)(pg?.Pool?.prototype, "connect");
|
|
265
|
+
(0, import_core.unpatchMethod)(pg?.Pool?.prototype, "query");
|
|
266
|
+
try {
|
|
267
|
+
(0, import_core.unpatchMethod)(pg?.native?.Client?.prototype, "query");
|
|
268
|
+
} catch {
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
275
|
+
0 && (module.exports = {
|
|
276
|
+
instrumentPg
|
|
277
|
+
});
|
|
278
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@reqray/instrumentation-pg` — interception of the `pg` driver.\n *\n * **Interception method: prototype patching.** None of the more preferred\n * options applied: `pg` publishes no `diagnostics_channel`, it has no official\n * extension point for observing queries, and `@opentelemetry/instrumentation-pg`\n * produces spans in its own model and without the callsite the N+1 detector\n * needs.\n *\n * `Client.prototype.query` is patched rather than the pool: `Pool.query` calls\n * `client.query` internally, so patching the prototype covers pools, standalone\n * connections, and avoids double recording.\n *\n * `Pool.prototype.connect` is patched too, for a different reason: the time\n * between asking the pool for a connection and getting one is invisible in\n * the query's own duration, and a query that took 340 ms because it queued\n * for 338 of them looks exactly like one that worked for 340. `Pool.query`\n * acquires through the same method, so one patch covers both the explicit\n * checkout and the one the pool does on the caller's behalf.\n */\n\nimport {\n current,\n fingerprintSql,\n guarded,\n handedCallsite,\n type Instrumentation,\n type PoolReading,\n patchMethod,\n record,\n registerExplainTarget,\n registerPool,\n resolveCallsite,\n runInScope,\n toSpanError,\n unpatchMethod,\n withHandedCallsite,\n} from '@reqray/core';\n\n/**\n * How long the client in hand waited to be handed over, left on the client\n * itself by the `connect` wrapper and taken by its first query.\n */\nconst WAIT = Symbol.for('reqray.pg.wait');\n\n/** What `connect` leaves behind for the query that follows it. */\ninterface PendingWait {\n readonly ms: number;\n /**\n * Which request was waiting.\n *\n * A checkout held across two requests is an application bug, but it must\n * not become a lie in the panel: the wait belongs to the request that\n * queued for it, and a query from any other one takes nothing.\n */\n readonly scopeId: string;\n}\n\n/**\n * Below this, a wait is the cost of asking rather than the cost of queueing.\n *\n * An idle pool hands a connection back in a few microseconds; recording that\n * as a number would put a lead-in on every bar in the waterfall and a figure\n * in front of the reader that means nothing.\n */\nconst MIN_WAIT_MS = 0.5;\n\nfunction fingerprintOf(sql: string): string {\n try {\n return fingerprintSql(sql);\n } catch {\n return sql;\n }\n}\n\n/** Registry id of the executor, or `null` — never throws into the host query. */\nfunction targetIdOf(candidate: unknown): number | null {\n try {\n if (candidate === null || typeof candidate !== 'object') return null;\n return registerExplainTarget(candidate);\n } catch {\n return null;\n }\n}\n\n/** Pools already handed to the registry, so a query costs one lookup. */\nconst known = new WeakSet<object>();\n\n/**\n * A `pg` pool's own account of itself.\n *\n * The names are pg-pool's: `options.max` is the ceiling, `totalCount` the\n * connections open, `idleCount` those free, `waitingCount` the acquires\n * queued. A pool that answers something else is a version this does not\n * understand, and it reports nothing rather than guessing.\n */\nfunction readPool(pool: object): PoolReading | null {\n const candidate = pool as {\n options?: { max?: unknown };\n totalCount?: unknown;\n idleCount?: unknown;\n waitingCount?: unknown;\n };\n const max = candidate.options?.max;\n if (typeof max !== 'number') return null;\n return {\n source: 'pg',\n max,\n total: typeof candidate.totalCount === 'number' ? candidate.totalCount : 0,\n idle: typeof candidate.idleCount === 'number' ? candidate.idleCount : 0,\n waiting: typeof candidate.waitingCount === 'number' ? candidate.waitingCount : 0,\n };\n}\n\n/** Registers the pool the first time a request goes through it. */\nfunction notePool(pool: unknown): void {\n try {\n if (pool === null || typeof pool !== 'object' || known.has(pool)) return;\n known.add(pool);\n registerPool(pool, readPool);\n } catch {\n // Never into the host query.\n }\n}\n\n/**\n * Whether this acquire will have to wait for somebody to let go.\n *\n * There are three ways a pool answers, and only one of them is contention:\n * it hands over a connection that is already idle, it opens a new one while\n * it is below `max`, or it puts the caller in a queue. The first is\n * scheduling — a `nextTick`, not a wait. The second is TCP, TLS and\n * authentication, which can take tens of milliseconds and is fixed by warming\n * the pool rather than enlarging it; calling that a queue would send somebody\n * to raise `max`, the one change that makes a cold pool slower. Only the\n * third is a queue, and only the third is measured.\n *\n * So the question is what capacity is left at this instant, and the trap is\n * that `idleCount` does not answer it. pg-pool defers the handover to a\n * `nextTick`, so five queries issued in one tick all see the same idle\n * connection and only the first of them gets it. What separates them is the\n * queue that has already formed: this caller is the one after `waitingCount`,\n * and it waits when everything free is already spoken for.\n */\nfunction queueing(pool: unknown): boolean {\n try {\n if (pool === null || typeof pool !== 'object') return false;\n // The counts are read one by one rather than through `readPool`: this\n // runs in front of every pooled query, and building an object to answer\n // a yes-or-no question would put an allocation on the hot path.\n const candidate = pool as {\n options?: { max?: unknown };\n totalCount?: unknown;\n idleCount?: unknown;\n waitingCount?: unknown;\n };\n const max = candidate.options?.max;\n if (typeof max !== 'number') return false;\n const idle = typeof candidate.idleCount === 'number' ? candidate.idleCount : 0;\n const total = typeof candidate.totalCount === 'number' ? candidate.totalCount : 0;\n const waiting = typeof candidate.waitingCount === 'number' ? candidate.waitingCount : 0;\n return waiting >= idle + Math.max(0, max - total);\n } catch {\n return false;\n }\n}\n\n/** Extracts the query text from any call shape of `query`. */\nfunction sqlOf(first: unknown): string | undefined {\n if (typeof first === 'string') return first;\n if (first && typeof first === 'object') {\n const text = (first as { text?: unknown }).text;\n if (typeof text === 'string') return text;\n }\n return undefined;\n}\n\nconst MAX_VALUES = 50;\nconst MAX_VALUE_CHARS = 200;\n\n/**\n * Parameter values as strings — only under `collectSqlValues: true`.\n *\n * Both call shapes are covered: `query(text, values)` and\n * `query({ text, values })`. Never throws into the host query.\n */\nfunction valuesOf(args: readonly unknown[]): readonly string[] | null {\n try {\n const first = args[0] as { values?: unknown } | string | undefined;\n const raw =\n typeof first === 'object' && first !== null && Array.isArray(first.values)\n ? first.values\n : Array.isArray(args[1])\n ? args[1]\n : null;\n if (!raw) return null;\n\n return raw.slice(0, MAX_VALUES).map((value) => {\n const text =\n value === null || value === undefined\n ? 'NULL'\n : typeof value === 'object'\n ? JSON.stringify(value)\n : String(value);\n return text.length > MAX_VALUE_CHARS ? `${text.slice(0, MAX_VALUE_CHARS)}…` : text;\n });\n } catch {\n return null;\n }\n}\n\n/**\n * The wait this client queued for, taken once.\n *\n * Once, because it belongs to the acquire and not to every query that follows\n * it: a checkout that runs five queries waited before the first one, and\n * printing the same figure in front of the other four would turn one wait\n * into five.\n */\nfunction takeWait(client: unknown, scopeId: string): number | null {\n try {\n if (client === null || typeof client !== 'object') return null;\n const holder = client as { [WAIT]?: PendingWait | null };\n const pending = holder[WAIT];\n if (!pending) return null;\n holder[WAIT] = null;\n if (pending.scopeId !== scopeId) return null;\n return pending.ms >= MIN_WAIT_MS ? pending.ms : null;\n } catch {\n return null;\n }\n}\n\nfunction patchQuery(proto: any): void {\n patchMethod(\n proto,\n 'query',\n (original: any) =>\n function reqrayQuery(this: unknown, ...args: any[]) {\n const scope = current();\n // Outside a request nothing is touched: no allocations, no branching beyond this check.\n if (!scope) return original.apply(this, args);\n\n const sql = sqlOf(args[0]);\n // A submittable carries no query text (Cursor, QueryStream) — not our case.\n if (sql === undefined) return original.apply(this, args);\n\n const startTime = performance.now();\n const fingerprint = fingerprintOf(sql);\n\n // The wrapper itself is the boundary: otherwise the top frame would be\n // Reqray code instead of the line from which the user called `query`.\n const callsite = resolveCallsite(scope, fingerprint, reqrayQuery);\n // Two different questions, and both are asked here. `connectionId` is the\n // connection this query ran on — what makes a `BEGIN` and a `COMMIT` on\n // one wire into a transaction. `clientId` is where EXPLAIN should go\n // later, and for a pooled query that is the pool: the connection itself\n // has long since gone back into it.\n const connectionId = targetIdOf(this);\n const clientId = handedCallsite()?.clientId ?? connectionId;\n const waitMs = takeWait(this, scope.id);\n const values = scope.options.collectSqlValues ? valuesOf(args) : null;\n\n const finish = (result: unknown, error: unknown): void => {\n try {\n const rowCount = (result as { rowCount?: unknown } | undefined)?.rowCount;\n record(scope, {\n kind: 'db',\n sql,\n fingerprint,\n duration: performance.now() - startTime,\n startTime,\n rowCount: typeof rowCount === 'number' ? rowCount : null,\n source: 'pg',\n callsite,\n clientId,\n connectionId,\n waitMs,\n values,\n error: toSpanError(error),\n });\n } catch {\n // Instrumentation must never break the host query.\n }\n };\n\n // Callback style: pg takes it as the last argument.\n const lastIndex = args.length - 1;\n const callback = lastIndex >= 0 ? args[lastIndex] : undefined;\n if (typeof callback === 'function') {\n args[lastIndex] = function reqrayCallback(\n this: unknown,\n error: unknown,\n result: unknown,\n ) {\n finish(result, error);\n return callback.call(this, error, result);\n };\n return original.apply(this, args);\n }\n\n const result = original.apply(this, args);\n if (result && typeof result.then === 'function') {\n return result.then(\n (value: unknown) => {\n finish(value, undefined);\n return value;\n },\n (error: unknown) => {\n finish(undefined, error);\n // The original exception is rethrown unchanged.\n throw error;\n },\n );\n }\n\n // Neither a promise nor a callback means a submittable, which completes\n // on its own. Recording a zero-duration span would be a lie.\n return result;\n },\n );\n}\n\n/**\n * Wraps `Pool.prototype.query`.\n *\n * The pool resolves a connection asynchronously and only then calls\n * `client.query`, by which point the caller's frame is gone from the stack.\n * This wrapper records nothing itself — it exists solely to capture the\n * callsite while the frame is still reachable and hand it down. Without it the\n * N+1 detector stays silent for every application that queries through a pool,\n * which is most of them.\n */\nfunction patchPoolQuery(proto: any): void {\n patchMethod(\n proto,\n 'query',\n (original: any) =>\n function reqrayPoolQuery(this: unknown, ...args: any[]) {\n const scope = current();\n if (!scope) return original.apply(this, args);\n\n const sql = sqlOf(args[0]);\n if (sql === undefined) return original.apply(this, args);\n\n notePool(this);\n const callsite = resolveCallsite(scope, fingerprintOf(sql), reqrayPoolQuery);\n const clientId = targetIdOf(this);\n\n return withHandedCallsite(clientId === null ? { callsite } : { callsite, clientId }, () =>\n original.apply(this, args),\n );\n },\n );\n}\n\n/**\n * Wraps `Pool.prototype.connect` to measure the queue in front of it.\n *\n * Records nothing on its own: what it measures is a property of the query\n * that follows, and a row of its own in the waterfall saying \"waited\" would\n * double the rows without adding a place to look. The figure is left on the\n * client and the first query on it picks it up.\n *\n * Both call shapes matter here, and not only because the driver offers them:\n * `Pool.query` acquires with a callback internally, so the callback branch is\n * the one that covers ordinary pooled queries.\n */\nfunction patchConnect(proto: any): void {\n patchMethod(\n proto,\n 'connect',\n (original: any) =>\n function reqrayConnect(this: unknown, ...args: any[]) {\n const scope = current();\n if (!scope) return original.apply(this, args);\n\n notePool(this);\n // Nothing to measure unless this acquire is about to queue — and the\n // ordinary case, a pool with a connection free, leaves through here\n // having done three property reads and allocated nothing.\n if (!queueing(this)) return original.apply(this, args);\n\n /**\n * Everything the queue would otherwise lose.\n *\n * An acquire that finds a connection free is dispatched through\n * `process.nextTick`, and a `nextTick` carries the context that scheduled\n * it. An acquire that has to *queue* is dispatched by whoever releases a\n * connection — from inside that request's callback, or from the driver's\n * socket, in a context that never saw this request. Two things are lost\n * with it, and the second one is the serious one:\n *\n * - the callsite `pool.query` handed down, so the query that waited would\n * be the one query with no line of code attached, and the N+1 detector\n * would go quiet exactly when the pool is under pressure;\n * - the request scope itself. `current()` in the driver wrapper would\n * return whatever scope the releasing context happens to carry — a\n * finished request, or none at all — and the query would be filed under\n * somebody else's request or dropped outright. Five queries issued\n * through `Promise.all` on a pool of one showed up in the panel as one.\n */\n const handed = handedCallsite();\n\n const startTime = performance.now();\n const stamp = (client: unknown): void => {\n try {\n if (client !== null && typeof client === 'object') {\n (client as { [WAIT]?: PendingWait | null })[WAIT] = {\n ms: performance.now() - startTime,\n scopeId: scope.id,\n };\n }\n } catch {\n // A frozen or proxied client simply goes unmeasured.\n }\n };\n\n const lastIndex = args.length - 1;\n const callback = lastIndex >= 0 ? args[lastIndex] : undefined;\n if (typeof callback === 'function') {\n args[lastIndex] = function reqrayConnectCallback(this: unknown, ...given: any[]) {\n // `(error, client, release)` — a failed acquire waited too, but there\n // is no query to hang the figure on.\n if (!given[0]) stamp(given[1]);\n // The dispatch happens here, inside the callback, so this is where\n // the request has to be put back: the query issued below then finds\n // the scope it belongs to and the callsite it was asked from.\n const dispatch = handed\n ? () => withHandedCallsite(handed, () => callback.apply(this, given))\n : () => callback.apply(this, given);\n return runInScope(scope, dispatch);\n };\n return original.apply(this, args);\n }\n\n const result = original.apply(this, args);\n if (result && typeof result.then === 'function') {\n return result.then((client: unknown) => {\n stamp(client);\n return client;\n });\n // No rejection handler: the acquire error passes through untouched.\n }\n return result;\n },\n );\n}\n\n/**\n * Where the classes are in what the loader hook handed over.\n *\n * `require('pg')` gives the module. `import pg from 'pg'` of a build with no\n * ESM wrapper gives a namespace whose only member is `default`, with the\n * classes one level down — read as the module, it has no `Client`, nothing is\n * patched, and the startup report still says pg is instrumented.\n */\nfunction moduleOf(exports: any): any {\n return exports?.Client ? exports : (exports?.default ?? exports);\n}\n\nexport function instrumentPg(): Instrumentation {\n return {\n name: 'pg',\n supportedVersions: '>=8 <9',\n captures: 'SQL',\n\n apply(exports: any) {\n guarded('pg', () => {\n const pg = moduleOf(exports);\n patchQuery(pg?.Client?.prototype);\n // Two patches on one prototype; the kit keys idempotence by method\n // name, so they do not collide.\n patchConnect(pg?.Pool?.prototype);\n patchPoolQuery(pg?.Pool?.prototype);\n\n // Accessing `pg.native` throws when `pg-native` is not installed —\n // that is normal, not an error.\n try {\n patchQuery(pg?.native?.Client?.prototype);\n } catch {\n // No native client.\n }\n });\n },\n\n unapply(exports: any) {\n guarded('pg', () => {\n const pg = moduleOf(exports);\n unpatchMethod(pg?.Client?.prototype, 'query');\n unpatchMethod(pg?.Pool?.prototype, 'connect');\n unpatchMethod(pg?.Pool?.prototype, 'query');\n try {\n unpatchMethod(pg?.native?.Client?.prototype, 'query');\n } catch {\n // No native client.\n }\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,kBAgBO;AAMP,IAAM,OAAO,uBAAO,IAAI,gBAAgB;AAsBxC,IAAM,cAAc;AAEpB,SAAS,cAAc,KAAqB;AAC1C,MAAI;AACF,eAAO,4BAAe,GAAG;AAAA,EAC3B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,WAAW,WAAmC;AACrD,MAAI;AACF,QAAI,cAAc,QAAQ,OAAO,cAAc,SAAU,QAAO;AAChE,eAAO,mCAAsB,SAAS;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,IAAM,QAAQ,oBAAI,QAAgB;AAUlC,SAAS,SAAS,MAAkC;AAClD,QAAM,YAAY;AAMlB,QAAM,MAAM,UAAU,SAAS;AAC/B,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,SAAO;AAAA,IACL,QAAQ;AAAA,IACR;AAAA,IACA,OAAO,OAAO,UAAU,eAAe,WAAW,UAAU,aAAa;AAAA,IACzE,MAAM,OAAO,UAAU,cAAc,WAAW,UAAU,YAAY;AAAA,IACtE,SAAS,OAAO,UAAU,iBAAiB,WAAW,UAAU,eAAe;AAAA,EACjF;AACF;AAGA,SAAS,SAAS,MAAqB;AACrC,MAAI;AACF,QAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,MAAM,IAAI,IAAI,EAAG;AAClE,UAAM,IAAI,IAAI;AACd,kCAAa,MAAM,QAAQ;AAAA,EAC7B,QAAQ;AAAA,EAER;AACF;AAqBA,SAAS,SAAS,MAAwB;AACxC,MAAI;AACF,QAAI,SAAS,QAAQ,OAAO,SAAS,SAAU,QAAO;AAItD,UAAM,YAAY;AAMlB,UAAM,MAAM,UAAU,SAAS;AAC/B,QAAI,OAAO,Q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BAAW,IAAI,QAAQ,SAAS;AAGhC,qBAAa,IAAI,MAAM,SAAS;AAChC,uBAAe,IAAI,MAAM,SAAS;AAIlC,YAAI;AACF,qBAAW,IAAI,QAAQ,QAAQ,SAAS;AAAA,QAC1C,QAAQ;AAAA,QAER;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IAEA,QAAQA,UAAc;AACpB,+BAAQ,MAAM,MAAM;AAClB,cAAM,KAAK,SAASA,QAAO;AAC3B,uCAAc,IAAI,QAAQ,WAAW,OAAO;AAC5C,uCAAc,IAAI,MAAM,WAAW,SAAS;AAC5C,uCAAc,IAAI,MAAM,WAAW,OAAO;AAC1C,YAAI;AACF,yCAAc,IAAI,QAAQ,QAAQ,WAAW,OAAO;AAAA,QACtD,QAAQ;AAAA,QAER;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["result","exports"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Instrumentation } from '@reqray/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `@reqray/instrumentation-pg` — interception of the `pg` driver.
|
|
5
|
+
*
|
|
6
|
+
* **Interception method: prototype patching.** None of the more preferred
|
|
7
|
+
* options applied: `pg` publishes no `diagnostics_channel`, it has no official
|
|
8
|
+
* extension point for observing queries, and `@opentelemetry/instrumentation-pg`
|
|
9
|
+
* produces spans in its own model and without the callsite the N+1 detector
|
|
10
|
+
* needs.
|
|
11
|
+
*
|
|
12
|
+
* `Client.prototype.query` is patched rather than the pool: `Pool.query` calls
|
|
13
|
+
* `client.query` internally, so patching the prototype covers pools, standalone
|
|
14
|
+
* connections, and avoids double recording.
|
|
15
|
+
*
|
|
16
|
+
* `Pool.prototype.connect` is patched too, for a different reason: the time
|
|
17
|
+
* between asking the pool for a connection and getting one is invisible in
|
|
18
|
+
* the query's own duration, and a query that took 340 ms because it queued
|
|
19
|
+
* for 338 of them looks exactly like one that worked for 340. `Pool.query`
|
|
20
|
+
* acquires through the same method, so one patch covers both the explicit
|
|
21
|
+
* checkout and the one the pool does on the caller's behalf.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
declare function instrumentPg(): Instrumentation;
|
|
25
|
+
|
|
26
|
+
export { instrumentPg };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Instrumentation } from '@reqray/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `@reqray/instrumentation-pg` — interception of the `pg` driver.
|
|
5
|
+
*
|
|
6
|
+
* **Interception method: prototype patching.** None of the more preferred
|
|
7
|
+
* options applied: `pg` publishes no `diagnostics_channel`, it has no official
|
|
8
|
+
* extension point for observing queries, and `@opentelemetry/instrumentation-pg`
|
|
9
|
+
* produces spans in its own model and without the callsite the N+1 detector
|
|
10
|
+
* needs.
|
|
11
|
+
*
|
|
12
|
+
* `Client.prototype.query` is patched rather than the pool: `Pool.query` calls
|
|
13
|
+
* `client.query` internally, so patching the prototype covers pools, standalone
|
|
14
|
+
* connections, and avoids double recording.
|
|
15
|
+
*
|
|
16
|
+
* `Pool.prototype.connect` is patched too, for a different reason: the time
|
|
17
|
+
* between asking the pool for a connection and getting one is invisible in
|
|
18
|
+
* the query's own duration, and a query that took 340 ms because it queued
|
|
19
|
+
* for 338 of them looks exactly like one that worked for 340. `Pool.query`
|
|
20
|
+
* acquires through the same method, so one patch covers both the explicit
|
|
21
|
+
* checkout and the one the pool does on the caller's behalf.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
declare function instrumentPg(): Instrumentation;
|
|
25
|
+
|
|
26
|
+
export { instrumentPg };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import {
|
|
3
|
+
current,
|
|
4
|
+
fingerprintSql,
|
|
5
|
+
guarded,
|
|
6
|
+
handedCallsite,
|
|
7
|
+
patchMethod,
|
|
8
|
+
record,
|
|
9
|
+
registerExplainTarget,
|
|
10
|
+
registerPool,
|
|
11
|
+
resolveCallsite,
|
|
12
|
+
runInScope,
|
|
13
|
+
toSpanError,
|
|
14
|
+
unpatchMethod,
|
|
15
|
+
withHandedCallsite
|
|
16
|
+
} from "@reqray/core";
|
|
17
|
+
var WAIT = /* @__PURE__ */ Symbol.for("reqray.pg.wait");
|
|
18
|
+
var MIN_WAIT_MS = 0.5;
|
|
19
|
+
function fingerprintOf(sql) {
|
|
20
|
+
try {
|
|
21
|
+
return fingerprintSql(sql);
|
|
22
|
+
} catch {
|
|
23
|
+
return sql;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function targetIdOf(candidate) {
|
|
27
|
+
try {
|
|
28
|
+
if (candidate === null || typeof candidate !== "object") return null;
|
|
29
|
+
return registerExplainTarget(candidate);
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
var known = /* @__PURE__ */ new WeakSet();
|
|
35
|
+
function readPool(pool) {
|
|
36
|
+
const candidate = pool;
|
|
37
|
+
const max = candidate.options?.max;
|
|
38
|
+
if (typeof max !== "number") return null;
|
|
39
|
+
return {
|
|
40
|
+
source: "pg",
|
|
41
|
+
max,
|
|
42
|
+
total: typeof candidate.totalCount === "number" ? candidate.totalCount : 0,
|
|
43
|
+
idle: typeof candidate.idleCount === "number" ? candidate.idleCount : 0,
|
|
44
|
+
waiting: typeof candidate.waitingCount === "number" ? candidate.waitingCount : 0
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function notePool(pool) {
|
|
48
|
+
try {
|
|
49
|
+
if (pool === null || typeof pool !== "object" || known.has(pool)) return;
|
|
50
|
+
known.add(pool);
|
|
51
|
+
registerPool(pool, readPool);
|
|
52
|
+
} catch {
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function queueing(pool) {
|
|
56
|
+
try {
|
|
57
|
+
if (pool === null || typeof pool !== "object") return false;
|
|
58
|
+
const candidate = pool;
|
|
59
|
+
const max = candidate.options?.max;
|
|
60
|
+
if (typeof max !== "number") return false;
|
|
61
|
+
const idle = typeof candidate.idleCount === "number" ? candidate.idleCount : 0;
|
|
62
|
+
const total = typeof candidate.totalCount === "number" ? candidate.totalCount : 0;
|
|
63
|
+
const waiting = typeof candidate.waitingCount === "number" ? candidate.waitingCount : 0;
|
|
64
|
+
return waiting >= idle + Math.max(0, max - total);
|
|
65
|
+
} catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function sqlOf(first) {
|
|
70
|
+
if (typeof first === "string") return first;
|
|
71
|
+
if (first && typeof first === "object") {
|
|
72
|
+
const text = first.text;
|
|
73
|
+
if (typeof text === "string") return text;
|
|
74
|
+
}
|
|
75
|
+
return void 0;
|
|
76
|
+
}
|
|
77
|
+
var MAX_VALUES = 50;
|
|
78
|
+
var MAX_VALUE_CHARS = 200;
|
|
79
|
+
function valuesOf(args) {
|
|
80
|
+
try {
|
|
81
|
+
const first = args[0];
|
|
82
|
+
const raw = typeof first === "object" && first !== null && Array.isArray(first.values) ? first.values : Array.isArray(args[1]) ? args[1] : null;
|
|
83
|
+
if (!raw) return null;
|
|
84
|
+
return raw.slice(0, MAX_VALUES).map((value) => {
|
|
85
|
+
const text = value === null || value === void 0 ? "NULL" : typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
86
|
+
return text.length > MAX_VALUE_CHARS ? `${text.slice(0, MAX_VALUE_CHARS)}\u2026` : text;
|
|
87
|
+
});
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function takeWait(client, scopeId) {
|
|
93
|
+
try {
|
|
94
|
+
if (client === null || typeof client !== "object") return null;
|
|
95
|
+
const holder = client;
|
|
96
|
+
const pending = holder[WAIT];
|
|
97
|
+
if (!pending) return null;
|
|
98
|
+
holder[WAIT] = null;
|
|
99
|
+
if (pending.scopeId !== scopeId) return null;
|
|
100
|
+
return pending.ms >= MIN_WAIT_MS ? pending.ms : null;
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function patchQuery(proto) {
|
|
106
|
+
patchMethod(
|
|
107
|
+
proto,
|
|
108
|
+
"query",
|
|
109
|
+
(original) => function reqrayQuery(...args) {
|
|
110
|
+
const scope = current();
|
|
111
|
+
if (!scope) return original.apply(this, args);
|
|
112
|
+
const sql = sqlOf(args[0]);
|
|
113
|
+
if (sql === void 0) return original.apply(this, args);
|
|
114
|
+
const startTime = performance.now();
|
|
115
|
+
const fingerprint = fingerprintOf(sql);
|
|
116
|
+
const callsite = resolveCallsite(scope, fingerprint, reqrayQuery);
|
|
117
|
+
const connectionId = targetIdOf(this);
|
|
118
|
+
const clientId = handedCallsite()?.clientId ?? connectionId;
|
|
119
|
+
const waitMs = takeWait(this, scope.id);
|
|
120
|
+
const values = scope.options.collectSqlValues ? valuesOf(args) : null;
|
|
121
|
+
const finish = (result2, error) => {
|
|
122
|
+
try {
|
|
123
|
+
const rowCount = result2?.rowCount;
|
|
124
|
+
record(scope, {
|
|
125
|
+
kind: "db",
|
|
126
|
+
sql,
|
|
127
|
+
fingerprint,
|
|
128
|
+
duration: performance.now() - startTime,
|
|
129
|
+
startTime,
|
|
130
|
+
rowCount: typeof rowCount === "number" ? rowCount : null,
|
|
131
|
+
source: "pg",
|
|
132
|
+
callsite,
|
|
133
|
+
clientId,
|
|
134
|
+
connectionId,
|
|
135
|
+
waitMs,
|
|
136
|
+
values,
|
|
137
|
+
error: toSpanError(error)
|
|
138
|
+
});
|
|
139
|
+
} catch {
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
const lastIndex = args.length - 1;
|
|
143
|
+
const callback = lastIndex >= 0 ? args[lastIndex] : void 0;
|
|
144
|
+
if (typeof callback === "function") {
|
|
145
|
+
args[lastIndex] = function reqrayCallback(error, result2) {
|
|
146
|
+
finish(result2, error);
|
|
147
|
+
return callback.call(this, error, result2);
|
|
148
|
+
};
|
|
149
|
+
return original.apply(this, args);
|
|
150
|
+
}
|
|
151
|
+
const result = original.apply(this, args);
|
|
152
|
+
if (result && typeof result.then === "function") {
|
|
153
|
+
return result.then(
|
|
154
|
+
(value) => {
|
|
155
|
+
finish(value, void 0);
|
|
156
|
+
return value;
|
|
157
|
+
},
|
|
158
|
+
(error) => {
|
|
159
|
+
finish(void 0, error);
|
|
160
|
+
throw error;
|
|
161
|
+
}
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
return result;
|
|
165
|
+
}
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
function patchPoolQuery(proto) {
|
|
169
|
+
patchMethod(
|
|
170
|
+
proto,
|
|
171
|
+
"query",
|
|
172
|
+
(original) => function reqrayPoolQuery(...args) {
|
|
173
|
+
const scope = current();
|
|
174
|
+
if (!scope) return original.apply(this, args);
|
|
175
|
+
const sql = sqlOf(args[0]);
|
|
176
|
+
if (sql === void 0) return original.apply(this, args);
|
|
177
|
+
notePool(this);
|
|
178
|
+
const callsite = resolveCallsite(scope, fingerprintOf(sql), reqrayPoolQuery);
|
|
179
|
+
const clientId = targetIdOf(this);
|
|
180
|
+
return withHandedCallsite(
|
|
181
|
+
clientId === null ? { callsite } : { callsite, clientId },
|
|
182
|
+
() => original.apply(this, args)
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
function patchConnect(proto) {
|
|
188
|
+
patchMethod(
|
|
189
|
+
proto,
|
|
190
|
+
"connect",
|
|
191
|
+
(original) => function reqrayConnect(...args) {
|
|
192
|
+
const scope = current();
|
|
193
|
+
if (!scope) return original.apply(this, args);
|
|
194
|
+
notePool(this);
|
|
195
|
+
if (!queueing(this)) return original.apply(this, args);
|
|
196
|
+
const handed = handedCallsite();
|
|
197
|
+
const startTime = performance.now();
|
|
198
|
+
const stamp = (client) => {
|
|
199
|
+
try {
|
|
200
|
+
if (client !== null && typeof client === "object") {
|
|
201
|
+
client[WAIT] = {
|
|
202
|
+
ms: performance.now() - startTime,
|
|
203
|
+
scopeId: scope.id
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
} catch {
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
const lastIndex = args.length - 1;
|
|
210
|
+
const callback = lastIndex >= 0 ? args[lastIndex] : void 0;
|
|
211
|
+
if (typeof callback === "function") {
|
|
212
|
+
args[lastIndex] = function reqrayConnectCallback(...given) {
|
|
213
|
+
if (!given[0]) stamp(given[1]);
|
|
214
|
+
const dispatch = handed ? () => withHandedCallsite(handed, () => callback.apply(this, given)) : () => callback.apply(this, given);
|
|
215
|
+
return runInScope(scope, dispatch);
|
|
216
|
+
};
|
|
217
|
+
return original.apply(this, args);
|
|
218
|
+
}
|
|
219
|
+
const result = original.apply(this, args);
|
|
220
|
+
if (result && typeof result.then === "function") {
|
|
221
|
+
return result.then((client) => {
|
|
222
|
+
stamp(client);
|
|
223
|
+
return client;
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
return result;
|
|
227
|
+
}
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
function moduleOf(exports) {
|
|
231
|
+
return exports?.Client ? exports : exports?.default ?? exports;
|
|
232
|
+
}
|
|
233
|
+
function instrumentPg() {
|
|
234
|
+
return {
|
|
235
|
+
name: "pg",
|
|
236
|
+
supportedVersions: ">=8 <9",
|
|
237
|
+
captures: "SQL",
|
|
238
|
+
apply(exports) {
|
|
239
|
+
guarded("pg", () => {
|
|
240
|
+
const pg = moduleOf(exports);
|
|
241
|
+
patchQuery(pg?.Client?.prototype);
|
|
242
|
+
patchConnect(pg?.Pool?.prototype);
|
|
243
|
+
patchPoolQuery(pg?.Pool?.prototype);
|
|
244
|
+
try {
|
|
245
|
+
patchQuery(pg?.native?.Client?.prototype);
|
|
246
|
+
} catch {
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
},
|
|
250
|
+
unapply(exports) {
|
|
251
|
+
guarded("pg", () => {
|
|
252
|
+
const pg = moduleOf(exports);
|
|
253
|
+
unpatchMethod(pg?.Client?.prototype, "query");
|
|
254
|
+
unpatchMethod(pg?.Pool?.prototype, "connect");
|
|
255
|
+
unpatchMethod(pg?.Pool?.prototype, "query");
|
|
256
|
+
try {
|
|
257
|
+
unpatchMethod(pg?.native?.Client?.prototype, "query");
|
|
258
|
+
} catch {
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
export {
|
|
265
|
+
instrumentPg
|
|
266
|
+
};
|
|
267
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@reqray/instrumentation-pg` — interception of the `pg` driver.\n *\n * **Interception method: prototype patching.** None of the more preferred\n * options applied: `pg` publishes no `diagnostics_channel`, it has no official\n * extension point for observing queries, and `@opentelemetry/instrumentation-pg`\n * produces spans in its own model and without the callsite the N+1 detector\n * needs.\n *\n * `Client.prototype.query` is patched rather than the pool: `Pool.query` calls\n * `client.query` internally, so patching the prototype covers pools, standalone\n * connections, and avoids double recording.\n *\n * `Pool.prototype.connect` is patched too, for a different reason: the time\n * between asking the pool for a connection and getting one is invisible in\n * the query's own duration, and a query that took 340 ms because it queued\n * for 338 of them looks exactly like one that worked for 340. `Pool.query`\n * acquires through the same method, so one patch covers both the explicit\n * checkout and the one the pool does on the caller's behalf.\n */\n\nimport {\n current,\n fingerprintSql,\n guarded,\n handedCallsite,\n type Instrumentation,\n type PoolReading,\n patchMethod,\n record,\n registerExplainTarget,\n registerPool,\n resolveCallsite,\n runInScope,\n toSpanError,\n unpatchMethod,\n withHandedCallsite,\n} from '@reqray/core';\n\n/**\n * How long the client in hand waited to be handed over, left on the client\n * itself by the `connect` wrapper and taken by its first query.\n */\nconst WAIT = Symbol.for('reqray.pg.wait');\n\n/** What `connect` leaves behind for the query that follows it. */\ninterface PendingWait {\n readonly ms: number;\n /**\n * Which request was waiting.\n *\n * A checkout held across two requests is an application bug, but it must\n * not become a lie in the panel: the wait belongs to the request that\n * queued for it, and a query from any other one takes nothing.\n */\n readonly scopeId: string;\n}\n\n/**\n * Below this, a wait is the cost of asking rather than the cost of queueing.\n *\n * An idle pool hands a connection back in a few microseconds; recording that\n * as a number would put a lead-in on every bar in the waterfall and a figure\n * in front of the reader that means nothing.\n */\nconst MIN_WAIT_MS = 0.5;\n\nfunction fingerprintOf(sql: string): string {\n try {\n return fingerprintSql(sql);\n } catch {\n return sql;\n }\n}\n\n/** Registry id of the executor, or `null` — never throws into the host query. */\nfunction targetIdOf(candidate: unknown): number | null {\n try {\n if (candidate === null || typeof candidate !== 'object') return null;\n return registerExplainTarget(candidate);\n } catch {\n return null;\n }\n}\n\n/** Pools already handed to the registry, so a query costs one lookup. */\nconst known = new WeakSet<object>();\n\n/**\n * A `pg` pool's own account of itself.\n *\n * The names are pg-pool's: `options.max` is the ceiling, `totalCount` the\n * connections open, `idleCount` those free, `waitingCount` the acquires\n * queued. A pool that answers something else is a version this does not\n * understand, and it reports nothing rather than guessing.\n */\nfunction readPool(pool: object): PoolReading | null {\n const candidate = pool as {\n options?: { max?: unknown };\n totalCount?: unknown;\n idleCount?: unknown;\n waitingCount?: unknown;\n };\n const max = candidate.options?.max;\n if (typeof max !== 'number') return null;\n return {\n source: 'pg',\n max,\n total: typeof candidate.totalCount === 'number' ? candidate.totalCount : 0,\n idle: typeof candidate.idleCount === 'number' ? candidate.idleCount : 0,\n waiting: typeof candidate.waitingCount === 'number' ? candidate.waitingCount : 0,\n };\n}\n\n/** Registers the pool the first time a request goes through it. */\nfunction notePool(pool: unknown): void {\n try {\n if (pool === null || typeof pool !== 'object' || known.has(pool)) return;\n known.add(pool);\n registerPool(pool, readPool);\n } catch {\n // Never into the host query.\n }\n}\n\n/**\n * Whether this acquire will have to wait for somebody to let go.\n *\n * There are three ways a pool answers, and only one of them is contention:\n * it hands over a connection that is already idle, it opens a new one while\n * it is below `max`, or it puts the caller in a queue. The first is\n * scheduling — a `nextTick`, not a wait. The second is TCP, TLS and\n * authentication, which can take tens of milliseconds and is fixed by warming\n * the pool rather than enlarging it; calling that a queue would send somebody\n * to raise `max`, the one change that makes a cold pool slower. Only the\n * third is a queue, and only the third is measured.\n *\n * So the question is what capacity is left at this instant, and the trap is\n * that `idleCount` does not answer it. pg-pool defers the handover to a\n * `nextTick`, so five queries issued in one tick all see the same idle\n * connection and only the first of them gets it. What separates them is the\n * queue that has already formed: this caller is the one after `waitingCount`,\n * and it waits when everything free is already spoken for.\n */\nfunction queueing(pool: unknown): boolean {\n try {\n if (pool === null || typeof pool !== 'object') return false;\n // The counts are read one by one rather than through `readPool`: this\n // runs in front of every pooled query, and building an object to answer\n // a yes-or-no question would put an allocation on the hot path.\n const candidate = pool as {\n options?: { max?: unknown };\n totalCount?: unknown;\n idleCount?: unknown;\n waitingCount?: unknown;\n };\n const max = candidate.options?.max;\n if (typeof max !== 'number') return false;\n const idle = typeof candidate.idleCount === 'number' ? candidate.idleCount : 0;\n const total = typeof candidate.totalCount === 'number' ? candidate.totalCount : 0;\n const waiting = typeof candidate.waitingCount === 'number' ? candidate.waitingCount : 0;\n return waiting >= idle + Math.max(0, max - total);\n } catch {\n return false;\n }\n}\n\n/** Extracts the query text from any call shape of `query`. */\nfunction sqlOf(first: unknown): string | undefined {\n if (typeof first === 'string') return first;\n if (first && typeof first === 'object') {\n const text = (first as { text?: unknown }).text;\n if (typeof text === 'string') return text;\n }\n return undefined;\n}\n\nconst MAX_VALUES = 50;\nconst MAX_VALUE_CHARS = 200;\n\n/**\n * Parameter values as strings — only under `collectSqlValues: true`.\n *\n * Both call shapes are covered: `query(text, values)` and\n * `query({ text, values })`. Never throws into the host query.\n */\nfunction valuesOf(args: readonly unknown[]): readonly string[] | null {\n try {\n const first = args[0] as { values?: unknown } | string | undefined;\n const raw =\n typeof first === 'object' && first !== null && Array.isArray(first.values)\n ? first.values\n : Array.isArray(args[1])\n ? args[1]\n : null;\n if (!raw) return null;\n\n return raw.slice(0, MAX_VALUES).map((value) => {\n const text =\n value === null || value === undefined\n ? 'NULL'\n : typeof value === 'object'\n ? JSON.stringify(value)\n : String(value);\n return text.length > MAX_VALUE_CHARS ? `${text.slice(0, MAX_VALUE_CHARS)}…` : text;\n });\n } catch {\n return null;\n }\n}\n\n/**\n * The wait this client queued for, taken once.\n *\n * Once, because it belongs to the acquire and not to every query that follows\n * it: a checkout that runs five queries waited before the first one, and\n * printing the same figure in front of the other four would turn one wait\n * into five.\n */\nfunction takeWait(client: unknown, scopeId: string): number | null {\n try {\n if (client === null || typeof client !== 'object') return null;\n const holder = client as { [WAIT]?: PendingWait | null };\n const pending = holder[WAIT];\n if (!pending) return null;\n holder[WAIT] = null;\n if (pending.scopeId !== scopeId) return null;\n return pending.ms >= MIN_WAIT_MS ? pending.ms : null;\n } catch {\n return null;\n }\n}\n\nfunction patchQuery(proto: any): void {\n patchMethod(\n proto,\n 'query',\n (original: any) =>\n function reqrayQuery(this: unknown, ...args: any[]) {\n const scope = current();\n // Outside a request nothing is touched: no allocations, no branching beyond this check.\n if (!scope) return original.apply(this, args);\n\n const sql = sqlOf(args[0]);\n // A submittable carries no query text (Cursor, QueryStream) — not our case.\n if (sql === undefined) return original.apply(this, args);\n\n const startTime = performance.now();\n const fingerprint = fingerprintOf(sql);\n\n // The wrapper itself is the boundary: otherwise the top frame would be\n // Reqray code instead of the line from which the user called `query`.\n const callsite = resolveCallsite(scope, fingerprint, reqrayQuery);\n // Two different questions, and both are asked here. `connectionId` is the\n // connection this query ran on — what makes a `BEGIN` and a `COMMIT` on\n // one wire into a transaction. `clientId` is where EXPLAIN should go\n // later, and for a pooled query that is the pool: the connection itself\n // has long since gone back into it.\n const connectionId = targetIdOf(this);\n const clientId = handedCallsite()?.clientId ?? connectionId;\n const waitMs = takeWait(this, scope.id);\n const values = scope.options.collectSqlValues ? valuesOf(args) : null;\n\n const finish = (result: unknown, error: unknown): void => {\n try {\n const rowCount = (result as { rowCount?: unknown } | undefined)?.rowCount;\n record(scope, {\n kind: 'db',\n sql,\n fingerprint,\n duration: performance.now() - startTime,\n startTime,\n rowCount: typeof rowCount === 'number' ? rowCount : null,\n source: 'pg',\n callsite,\n clientId,\n connectionId,\n waitMs,\n values,\n error: toSpanError(error),\n });\n } catch {\n // Instrumentation must never break the host query.\n }\n };\n\n // Callback style: pg takes it as the last argument.\n const lastIndex = args.length - 1;\n const callback = lastIndex >= 0 ? args[lastIndex] : undefined;\n if (typeof callback === 'function') {\n args[lastIndex] = function reqrayCallback(\n this: unknown,\n error: unknown,\n result: unknown,\n ) {\n finish(result, error);\n return callback.call(this, error, result);\n };\n return original.apply(this, args);\n }\n\n const result = original.apply(this, args);\n if (result && typeof result.then === 'function') {\n return result.then(\n (value: unknown) => {\n finish(value, undefined);\n return value;\n },\n (error: unknown) => {\n finish(undefined, error);\n // The original exception is rethrown unchanged.\n throw error;\n },\n );\n }\n\n // Neither a promise nor a callback means a submittable, which completes\n // on its own. Recording a zero-duration span would be a lie.\n return result;\n },\n );\n}\n\n/**\n * Wraps `Pool.prototype.query`.\n *\n * The pool resolves a connection asynchronously and only then calls\n * `client.query`, by which point the caller's frame is gone from the stack.\n * This wrapper records nothing itself — it exists solely to capture the\n * callsite while the frame is still reachable and hand it down. Without it the\n * N+1 detector stays silent for every application that queries through a pool,\n * which is most of them.\n */\nfunction patchPoolQuery(proto: any): void {\n patchMethod(\n proto,\n 'query',\n (original: any) =>\n function reqrayPoolQuery(this: unknown, ...args: any[]) {\n const scope = current();\n if (!scope) return original.apply(this, args);\n\n const sql = sqlOf(args[0]);\n if (sql === undefined) return original.apply(this, args);\n\n notePool(this);\n const callsite = resolveCallsite(scope, fingerprintOf(sql), reqrayPoolQuery);\n const clientId = targetIdOf(this);\n\n return withHandedCallsite(clientId === null ? { callsite } : { callsite, clientId }, () =>\n original.apply(this, args),\n );\n },\n );\n}\n\n/**\n * Wraps `Pool.prototype.connect` to measure the queue in front of it.\n *\n * Records nothing on its own: what it measures is a property of the query\n * that follows, and a row of its own in the waterfall saying \"waited\" would\n * double the rows without adding a place to look. The figure is left on the\n * client and the first query on it picks it up.\n *\n * Both call shapes matter here, and not only because the driver offers them:\n * `Pool.query` acquires with a callback internally, so the callback branch is\n * the one that covers ordinary pooled queries.\n */\nfunction patchConnect(proto: any): void {\n patchMethod(\n proto,\n 'connect',\n (original: any) =>\n function reqrayConnect(this: unknown, ...args: any[]) {\n const scope = current();\n if (!scope) return original.apply(this, args);\n\n notePool(this);\n // Nothing to measure unless this acquire is about to queue — and the\n // ordinary case, a pool with a connection free, leaves through here\n // having done three property reads and allocated nothing.\n if (!queueing(this)) return original.apply(this, args);\n\n /**\n * Everything the queue would otherwise lose.\n *\n * An acquire that finds a connection free is dispatched through\n * `process.nextTick`, and a `nextTick` carries the context that scheduled\n * it. An acquire that has to *queue* is dispatched by whoever releases a\n * connection — from inside that request's callback, or from the driver's\n * socket, in a context that never saw this request. Two things are lost\n * with it, and the second one is the serious one:\n *\n * - the callsite `pool.query` handed down, so the query that waited would\n * be the one query with no line of code attached, and the N+1 detector\n * would go quiet exactly when the pool is under pressure;\n * - the request scope itself. `current()` in the driver wrapper would\n * return whatever scope the releasing context happens to carry — a\n * finished request, or none at all — and the query would be filed under\n * somebody else's request or dropped outright. Five queries issued\n * through `Promise.all` on a pool of one showed up in the panel as one.\n */\n const handed = handedCallsite();\n\n const startTime = performance.now();\n const stamp = (client: unknown): void => {\n try {\n if (client !== null && typeof client === 'object') {\n (client as { [WAIT]?: PendingWait | null })[WAIT] = {\n ms: performance.now() - startTime,\n scopeId: scope.id,\n };\n }\n } catch {\n // A frozen or proxied client simply goes unmeasured.\n }\n };\n\n const lastIndex = args.length - 1;\n const callback = lastIndex >= 0 ? args[lastIndex] : undefined;\n if (typeof callback === 'function') {\n args[lastIndex] = function reqrayConnectCallback(this: unknown, ...given: any[]) {\n // `(error, client, release)` — a failed acquire waited too, but there\n // is no query to hang the figure on.\n if (!given[0]) stamp(given[1]);\n // The dispatch happens here, inside the callback, so this is where\n // the request has to be put back: the query issued below then finds\n // the scope it belongs to and the callsite it was asked from.\n const dispatch = handed\n ? () => withHandedCallsite(handed, () => callback.apply(this, given))\n : () => callback.apply(this, given);\n return runInScope(scope, dispatch);\n };\n return original.apply(this, args);\n }\n\n const result = original.apply(this, args);\n if (result && typeof result.then === 'function') {\n return result.then((client: unknown) => {\n stamp(client);\n return client;\n });\n // No rejection handler: the acquire error passes through untouched.\n }\n return result;\n },\n );\n}\n\n/**\n * Where the classes are in what the loader hook handed over.\n *\n * `require('pg')` gives the module. `import pg from 'pg'` of a build with no\n * ESM wrapper gives a namespace whose only member is `default`, with the\n * classes one level down — read as the module, it has no `Client`, nothing is\n * patched, and the startup report still says pg is instrumented.\n */\nfunction moduleOf(exports: any): any {\n return exports?.Client ? exports : (exports?.default ?? exports);\n}\n\nexport function instrumentPg(): Instrumentation {\n return {\n name: 'pg',\n supportedVersions: '>=8 <9',\n captures: 'SQL',\n\n apply(exports: any) {\n guarded('pg', () => {\n const pg = moduleOf(exports);\n patchQuery(pg?.Client?.prototype);\n // Two patches on one prototype; the kit keys idempotence by method\n // name, so they do not collide.\n patchConnect(pg?.Pool?.prototype);\n patchPoolQuery(pg?.Pool?.prototype);\n\n // Accessing `pg.native` throws when `pg-native` is not installed —\n // that is normal, not an error.\n try {\n patchQuery(pg?.native?.Client?.prototype);\n } catch {\n // No native client.\n }\n });\n },\n\n unapply(exports: any) {\n guarded('pg', () => {\n const pg = moduleOf(exports);\n unpatchMethod(pg?.Client?.prototype, 'query');\n unpatchMethod(pg?.Pool?.prototype, 'connect');\n unpatchMethod(pg?.Pool?.prototype, 'query');\n try {\n unpatchMethod(pg?.native?.Client?.prototype, 'query');\n } catch {\n // No native client.\n }\n });\n },\n };\n}\n"],"mappings":";AAqBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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C,QAAQ;AAAA,QAER;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IAEA,QAAQ,SAAc;AACpB,cAAQ,MAAM,MAAM;AAClB,cAAM,KAAK,SAAS,OAAO;AAC3B,sBAAc,IAAI,QAAQ,WAAW,OAAO;AAC5C,sBAAc,IAAI,MAAM,WAAW,SAAS;AAC5C,sBAAc,IAAI,MAAM,WAAW,OAAO;AAC1C,YAAI;AACF,wBAAc,IAAI,QAAQ,QAAQ,WAAW,OAAO;AAAA,QACtD,QAAQ;AAAA,QAER;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["result"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,75 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reqray/instrumentation-pg",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "pg driver instrumentation for Reqray.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"nodejs",
|
|
8
|
+
"debugging",
|
|
9
|
+
"profiling",
|
|
10
|
+
"n+1",
|
|
11
|
+
"sql",
|
|
12
|
+
"observability",
|
|
13
|
+
"devtools",
|
|
14
|
+
"fastify",
|
|
15
|
+
"express",
|
|
16
|
+
"nestjs"
|
|
17
|
+
],
|
|
18
|
+
"homepage": "https://github.com/reqray/reqray#readme",
|
|
19
|
+
"bugs": "https://github.com/reqray/reqray/issues",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/reqray/reqray.git",
|
|
23
|
+
"directory": "packages/instrumentation-pg"
|
|
24
|
+
},
|
|
25
|
+
"type": "module",
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=20"
|
|
28
|
+
},
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"import": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
},
|
|
35
|
+
"require": {
|
|
36
|
+
"types": "./dist/index.d.cts",
|
|
37
|
+
"default": "./dist/index.cjs"
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"main": "./dist/index.cjs",
|
|
42
|
+
"module": "./dist/index.js",
|
|
43
|
+
"types": "./dist/index.d.ts",
|
|
44
|
+
"files": [
|
|
45
|
+
"dist"
|
|
46
|
+
],
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"@reqray/core": "^0.1.0"
|
|
52
|
+
},
|
|
53
|
+
"peerDependencies": {
|
|
54
|
+
"pg": ">=8 <9"
|
|
55
|
+
},
|
|
56
|
+
"peerDependenciesMeta": {
|
|
57
|
+
"pg": {
|
|
58
|
+
"optional": true
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"devDependencies": {
|
|
62
|
+
"@types/node": "^26.2.0",
|
|
63
|
+
"tsup": "^8.5.1",
|
|
64
|
+
"typescript": "^6.0.3",
|
|
65
|
+
"@testcontainers/postgresql": "^12.1.0",
|
|
66
|
+
"pg": "^8.23.0",
|
|
67
|
+
"@types/pg": "^8.23.1",
|
|
68
|
+
"@electric-sql/pglite": "^0.5.5",
|
|
69
|
+
"@electric-sql/pglite-socket": "^0.2.8"
|
|
70
|
+
},
|
|
71
|
+
"scripts": {
|
|
72
|
+
"build": "tsup",
|
|
73
|
+
"typecheck": "tsc --noEmit"
|
|
74
|
+
}
|
|
6
75
|
}
|