@culpritsql/devtools 0.0.0-stage → 0.5.6
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 +218 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/react.d.ts +39 -0
- package/dist/react.d.ts.map +1 -0
- package/dist/react.js +261 -0
- package/dist/react.js.map +1 -0
- package/dist/server.d.ts +189 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1179 -0
- package/dist/server.js.map +1 -0
- package/dist/shared.d.ts +58 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +369 -0
- package/dist/shared.js.map +1 -0
- package/dist/styles.css +3956 -0
- package/package.json +79 -4
package/dist/server.js
ADDED
|
@@ -0,0 +1,1179 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import diagnosticsChannel from "node:diagnostics_channel";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { performance } from "node:perf_hooks";
|
|
6
|
+
import { init as initPlansWasm, ParserError, parsePlan } from "@culpritsql/plans";
|
|
7
|
+
import { fingerprintSql, normalizeSqlForFingerprint, } from "./shared.js";
|
|
8
|
+
export { ParserError };
|
|
9
|
+
const INSTRUMENTED = Symbol.for("culprit.devtools.instrumented");
|
|
10
|
+
const CULPRIT_INTERNAL_TAG = "/* culprit */";
|
|
11
|
+
const SINGLE_SELECT_RE = /^\s*(?:with\b[\s\S]+?select|select)\b/i;
|
|
12
|
+
const MUTATING_KEYWORD_RE = /\b(?:insert|update|delete|merge|replace|upset|upsert|drop|alter|create|truncate|grant|revoke|call|exec|execute|copy|into)\b/i;
|
|
13
|
+
const ALREADY_EXPLAIN_RE = /^\s*explain\b/i;
|
|
14
|
+
const MAX_EXPLAIN_BODY_BYTES = 2 * 1024 * 1024;
|
|
15
|
+
let wasmInitPromise = null;
|
|
16
|
+
/**
|
|
17
|
+
* Initializes the `@culpritsql/plans` WebAssembly module once in Node.js / Bun
|
|
18
|
+
* using `import.meta.resolve("@culpritsql/plans")` + `node:fs/promises`.
|
|
19
|
+
*/
|
|
20
|
+
export async function ensurePlansWasm() {
|
|
21
|
+
if (!wasmInitPromise) {
|
|
22
|
+
wasmInitPromise = (async () => {
|
|
23
|
+
const entryUrl = import.meta.resolve("@culpritsql/plans");
|
|
24
|
+
const wasmUrl = new URL("./native/culprit_wasm_bg.wasm", entryUrl);
|
|
25
|
+
const wasmBytes = await readFile(wasmUrl);
|
|
26
|
+
await initPlansWasm({ module_or_path: wasmBytes });
|
|
27
|
+
})().catch((err) => {
|
|
28
|
+
wasmInitPromise = null;
|
|
29
|
+
throw err;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return wasmInitPromise;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Parses raw `EXPLAIN` output (JSON, text, or `.sqlplan` XML) into a typed Culprit `Plan`.
|
|
36
|
+
*/
|
|
37
|
+
export async function parseExplainText(rawExplain, engine) {
|
|
38
|
+
await ensurePlansWasm();
|
|
39
|
+
return parsePlan(rawExplain, engine);
|
|
40
|
+
}
|
|
41
|
+
function coerceEngine(raw, fallback) {
|
|
42
|
+
if (typeof raw !== "string")
|
|
43
|
+
return fallback;
|
|
44
|
+
const v = raw.toLowerCase().trim();
|
|
45
|
+
if (v === "postgres" || v === "postgresql" || v === "pg")
|
|
46
|
+
return "postgres";
|
|
47
|
+
if (v === "mysql" || v === "mysql2" || v === "mariadb")
|
|
48
|
+
return "mysql";
|
|
49
|
+
if (v === "sqlite" || v === "sqlite3" || v === "better-sqlite3" || v === "libsql")
|
|
50
|
+
return "sqlite";
|
|
51
|
+
if (v === "mssql" || v === "sqlserver" || v === "tds")
|
|
52
|
+
return "mssql";
|
|
53
|
+
if (v === "yugabyte" || v === "yugabytedb")
|
|
54
|
+
return "yugabyte";
|
|
55
|
+
return fallback;
|
|
56
|
+
}
|
|
57
|
+
function stripCommentsAndStringsForSafetyCheck(sql) {
|
|
58
|
+
let out = "";
|
|
59
|
+
let i = 0;
|
|
60
|
+
while (i < sql.length) {
|
|
61
|
+
const ch = sql[i];
|
|
62
|
+
const next = sql[i + 1] ?? "";
|
|
63
|
+
if (ch === "-" && next === "-") {
|
|
64
|
+
i += 2;
|
|
65
|
+
while (i < sql.length && sql[i] !== "\n")
|
|
66
|
+
i++;
|
|
67
|
+
out += " ";
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (ch === "/" && next === "*") {
|
|
71
|
+
i += 2;
|
|
72
|
+
while (i < sql.length && !(sql[i] === "*" && sql[i + 1] === "/"))
|
|
73
|
+
i++;
|
|
74
|
+
i += 2;
|
|
75
|
+
out += " ";
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (ch === "'") {
|
|
79
|
+
i++;
|
|
80
|
+
while (i < sql.length) {
|
|
81
|
+
if (sql[i] === "\\") {
|
|
82
|
+
i += 2;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (sql[i] === "'") {
|
|
86
|
+
if (sql[i + 1] === "'") {
|
|
87
|
+
i += 2;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
i++;
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
i++;
|
|
94
|
+
}
|
|
95
|
+
out += "''";
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (ch === '"') {
|
|
99
|
+
i++;
|
|
100
|
+
while (i < sql.length) {
|
|
101
|
+
if (sql[i] === '"') {
|
|
102
|
+
if (sql[i + 1] === '"') {
|
|
103
|
+
i += 2;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
i++;
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
i++;
|
|
110
|
+
}
|
|
111
|
+
out += '""';
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
out += ch;
|
|
115
|
+
i++;
|
|
116
|
+
}
|
|
117
|
+
return out.trim();
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Returns true strictly for read-only, single-statement `SELECT` / `WITH ... SELECT`
|
|
121
|
+
* queries that do not already begin with `EXPLAIN` and contain no data-modifying keywords.
|
|
122
|
+
*/
|
|
123
|
+
export function isSafeForAutoExplain(sql) {
|
|
124
|
+
if (!sql || sql.includes(CULPRIT_INTERNAL_TAG))
|
|
125
|
+
return false;
|
|
126
|
+
const cleaned = stripCommentsAndStringsForSafetyCheck(sql);
|
|
127
|
+
if (!cleaned || ALREADY_EXPLAIN_RE.test(cleaned))
|
|
128
|
+
return false;
|
|
129
|
+
const withoutTrailingSemi = cleaned.replace(/;\s*$/, "");
|
|
130
|
+
if (withoutTrailingSemi.includes(";"))
|
|
131
|
+
return false;
|
|
132
|
+
if (!SINGLE_SELECT_RE.test(withoutTrailingSemi))
|
|
133
|
+
return false;
|
|
134
|
+
if (MUTATING_KEYWORD_RE.test(withoutTrailingSemi))
|
|
135
|
+
return false;
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
function countParams(params, explicit) {
|
|
139
|
+
if (typeof explicit === "number")
|
|
140
|
+
return explicit;
|
|
141
|
+
if (Array.isArray(params))
|
|
142
|
+
return params.length;
|
|
143
|
+
if (typeof params === "string" && params.trim().startsWith("[")) {
|
|
144
|
+
try {
|
|
145
|
+
const parsed = JSON.parse(params);
|
|
146
|
+
if (Array.isArray(parsed))
|
|
147
|
+
return parsed.length;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
export class CulpritCollector {
|
|
156
|
+
maxQueries;
|
|
157
|
+
slowThresholdMs;
|
|
158
|
+
nPlusOneThreshold;
|
|
159
|
+
enabled;
|
|
160
|
+
defaultEngine;
|
|
161
|
+
autoExplainConfig;
|
|
162
|
+
als = new AsyncLocalStorage();
|
|
163
|
+
queries = [];
|
|
164
|
+
explainCount = 0;
|
|
165
|
+
seq = 0;
|
|
166
|
+
activeSubscriptions = new Map();
|
|
167
|
+
constructor(options = {}) {
|
|
168
|
+
this.maxQueries = Math.max(1, options.maxQueries ?? 250);
|
|
169
|
+
this.slowThresholdMs = options.slowThresholdMs ?? 20;
|
|
170
|
+
this.nPlusOneThreshold = Math.max(2, options.nPlusOneThreshold ?? 5);
|
|
171
|
+
this.enabled = options.enabled ?? process.env.NODE_ENV !== "production";
|
|
172
|
+
this.defaultEngine = options.defaultEngine;
|
|
173
|
+
if (typeof options.autoExplain === "boolean") {
|
|
174
|
+
this.autoExplainConfig = { enabled: options.autoExplain };
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
this.autoExplainConfig = options.autoExplain ?? { enabled: false };
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Runs `fn` inside an `AsyncLocalStorage` request scope so every query recorded
|
|
182
|
+
* across async boundaries automatically inherits `requestId` and `requestLabel`.
|
|
183
|
+
*/
|
|
184
|
+
withRequest(label, fn, requestId = randomUUID()) {
|
|
185
|
+
return this.als.run({ requestId, requestLabel: label }, fn);
|
|
186
|
+
}
|
|
187
|
+
/** Returns the active `AsyncLocalStorage` request context, if any. */
|
|
188
|
+
getCurrentRequest() {
|
|
189
|
+
return this.als.getStore();
|
|
190
|
+
}
|
|
191
|
+
/** Clears all recorded queries and resets the auto-EXPLAIN counter. */
|
|
192
|
+
clear() {
|
|
193
|
+
this.queries = [];
|
|
194
|
+
this.explainCount = 0;
|
|
195
|
+
}
|
|
196
|
+
/** Unsubscribes any active `diagnostics_channel` listeners registered by this collector. */
|
|
197
|
+
dispose() {
|
|
198
|
+
for (const [channelName, handler] of this.activeSubscriptions.entries()) {
|
|
199
|
+
diagnosticsChannel.unsubscribe(channelName, handler);
|
|
200
|
+
}
|
|
201
|
+
this.activeSubscriptions.clear();
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Subscribes via `node:diagnostics_channel` so Reylo (`reylo:query`), `pg`, `mysql2`,
|
|
205
|
+
* or custom query emitters stream directly into this collector.
|
|
206
|
+
* Returns an `unsubscribe` cleanup function.
|
|
207
|
+
*/
|
|
208
|
+
subscribeDiagnosticsChannels(channels = ["reylo:query", "pg:query", "mysql2:query"]) {
|
|
209
|
+
const registeredNow = [];
|
|
210
|
+
for (const channelName of channels) {
|
|
211
|
+
if (this.activeSubscriptions.has(channelName))
|
|
212
|
+
continue;
|
|
213
|
+
const inferredEngine = channelName.startsWith("pg:")
|
|
214
|
+
? "postgres"
|
|
215
|
+
: channelName.startsWith("mysql")
|
|
216
|
+
? "mysql"
|
|
217
|
+
: undefined;
|
|
218
|
+
const listener = (message) => {
|
|
219
|
+
if (!this.enabled || !message || typeof message !== "object")
|
|
220
|
+
return;
|
|
221
|
+
const msg = message;
|
|
222
|
+
const rawQuery = msg.sql ?? msg.query ?? msg.text ?? msg.statement;
|
|
223
|
+
let sql;
|
|
224
|
+
let queryValues;
|
|
225
|
+
if (typeof rawQuery === "string") {
|
|
226
|
+
sql = rawQuery;
|
|
227
|
+
}
|
|
228
|
+
else if (rawQuery && typeof rawQuery === "object") {
|
|
229
|
+
const qObj = rawQuery;
|
|
230
|
+
if (typeof qObj.text === "string")
|
|
231
|
+
sql = qObj.text;
|
|
232
|
+
else if (typeof qObj.sql === "string")
|
|
233
|
+
sql = qObj.sql;
|
|
234
|
+
if (Array.isArray(qObj.values))
|
|
235
|
+
queryValues = qObj.values;
|
|
236
|
+
}
|
|
237
|
+
if (!sql)
|
|
238
|
+
return;
|
|
239
|
+
const durationRaw = msg.durationMs ?? msg.duration ?? msg.elapsedMs ?? msg.timeMs;
|
|
240
|
+
const durationMs = typeof durationRaw === "number" && Number.isFinite(durationRaw) ? durationRaw : 0;
|
|
241
|
+
const rawParams = msg.params ?? msg.values ?? msg.parameters ?? msg.args ?? queryValues;
|
|
242
|
+
const paramsCount = typeof msg.paramsCount === "number"
|
|
243
|
+
? msg.paramsCount
|
|
244
|
+
: Array.isArray(rawParams)
|
|
245
|
+
? rawParams.length
|
|
246
|
+
: undefined;
|
|
247
|
+
const rowCount = typeof msg.rowCount === "number"
|
|
248
|
+
? msg.rowCount
|
|
249
|
+
: Array.isArray(msg.rows)
|
|
250
|
+
? msg.rows.length
|
|
251
|
+
: undefined;
|
|
252
|
+
const errVal = msg.error;
|
|
253
|
+
const error = errVal instanceof Error
|
|
254
|
+
? errVal.message
|
|
255
|
+
: typeof errVal === "string"
|
|
256
|
+
? errVal
|
|
257
|
+
: undefined;
|
|
258
|
+
this.recordQuery({
|
|
259
|
+
sql,
|
|
260
|
+
durationMs,
|
|
261
|
+
rowCount,
|
|
262
|
+
paramsCount,
|
|
263
|
+
engine: coerceEngine(msg.engine ?? msg.dialect, inferredEngine ?? this.defaultEngine),
|
|
264
|
+
error,
|
|
265
|
+
requestId: typeof msg.requestId === "string" ? msg.requestId : undefined,
|
|
266
|
+
requestLabel: typeof msg.requestLabel === "string" ? msg.requestLabel : undefined,
|
|
267
|
+
timestamp: typeof msg.timestamp === "number" ? msg.timestamp : undefined,
|
|
268
|
+
plan: msg.plan,
|
|
269
|
+
rawExplain: typeof msg.rawExplain === "string" ? msg.rawExplain : undefined,
|
|
270
|
+
});
|
|
271
|
+
};
|
|
272
|
+
diagnosticsChannel.subscribe(channelName, listener);
|
|
273
|
+
this.activeSubscriptions.set(channelName, listener);
|
|
274
|
+
registeredNow.push(channelName);
|
|
275
|
+
}
|
|
276
|
+
return () => {
|
|
277
|
+
for (const channelName of registeredNow) {
|
|
278
|
+
const listener = this.activeSubscriptions.get(channelName);
|
|
279
|
+
if (listener) {
|
|
280
|
+
diagnosticsChannel.unsubscribe(channelName, listener);
|
|
281
|
+
this.activeSubscriptions.delete(channelName);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Records a single SQL execution into the ring buffer. Suitable for Prisma (`$on('query')`),
|
|
288
|
+
* Drizzle custom loggers, Kysely plugins, or direct instrumentation.
|
|
289
|
+
*/
|
|
290
|
+
recordQuery(input) {
|
|
291
|
+
if (!this.enabled)
|
|
292
|
+
return null;
|
|
293
|
+
const rawSql = (input.sql ?? input.query ?? "").trim();
|
|
294
|
+
if (!rawSql || rawSql.includes(CULPRIT_INTERNAL_TAG))
|
|
295
|
+
return null;
|
|
296
|
+
const ctx = this.als.getStore();
|
|
297
|
+
const normalizedSql = normalizeSqlForFingerprint(rawSql);
|
|
298
|
+
const fingerprint = fingerprintSql(rawSql);
|
|
299
|
+
const durationRaw = input.durationMs ?? input.duration ?? 0;
|
|
300
|
+
const durationMs = Math.max(0, Math.round(durationRaw * 1000) / 1000);
|
|
301
|
+
const entry = {
|
|
302
|
+
id: input.id ?? `q_${++this.seq}_${Date.now().toString(36)}`,
|
|
303
|
+
timestamp: input.timestamp ?? Date.now(),
|
|
304
|
+
requestId: input.requestId ?? ctx?.requestId,
|
|
305
|
+
requestLabel: input.requestLabel ?? ctx?.requestLabel,
|
|
306
|
+
engine: coerceEngine(input.engine, this.defaultEngine),
|
|
307
|
+
sql: rawSql,
|
|
308
|
+
normalizedSql,
|
|
309
|
+
fingerprint,
|
|
310
|
+
durationMs,
|
|
311
|
+
rowCount: input.rowCount,
|
|
312
|
+
paramsCount: countParams(input.params, input.paramsCount),
|
|
313
|
+
error: input.error instanceof Error ? input.error.message : input.error,
|
|
314
|
+
plan: input.plan,
|
|
315
|
+
rawExplain: input.rawExplain,
|
|
316
|
+
};
|
|
317
|
+
this.queries.push(entry);
|
|
318
|
+
if (this.queries.length > this.maxQueries) {
|
|
319
|
+
this.queries.splice(0, this.queries.length - this.maxQueries);
|
|
320
|
+
}
|
|
321
|
+
if (!entry.plan &&
|
|
322
|
+
!entry.error &&
|
|
323
|
+
this.autoExplainConfig.enabled &&
|
|
324
|
+
this.autoExplainConfig.runExplain) {
|
|
325
|
+
void this.maybeAutoExplain(entry, Array.isArray(input.params) ? input.params : undefined, this.autoExplainConfig);
|
|
326
|
+
}
|
|
327
|
+
return entry;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Runs safe `EXPLAIN` for a recorded slow `SELECT` query and attaches the parsed `Plan`.
|
|
331
|
+
*/
|
|
332
|
+
async maybeAutoExplain(entry, params, override) {
|
|
333
|
+
if (!this.enabled || entry.plan || entry.error)
|
|
334
|
+
return entry.plan;
|
|
335
|
+
const merged = typeof override === "boolean"
|
|
336
|
+
? { ...this.autoExplainConfig, enabled: override }
|
|
337
|
+
: { ...this.autoExplainConfig, ...override };
|
|
338
|
+
if (!merged.enabled || !merged.runExplain)
|
|
339
|
+
return undefined;
|
|
340
|
+
const thresholdMs = merged.thresholdMs ?? this.slowThresholdMs;
|
|
341
|
+
const maxExplains = merged.maxExplains ?? 50;
|
|
342
|
+
if (entry.durationMs < thresholdMs)
|
|
343
|
+
return undefined;
|
|
344
|
+
if (this.explainCount >= maxExplains)
|
|
345
|
+
return undefined;
|
|
346
|
+
if (!isSafeForAutoExplain(entry.sql))
|
|
347
|
+
return undefined;
|
|
348
|
+
this.explainCount++;
|
|
349
|
+
try {
|
|
350
|
+
const rawExplain = await merged.runExplain(entry.sql, params);
|
|
351
|
+
if (!rawExplain || !rawExplain.trim())
|
|
352
|
+
return undefined;
|
|
353
|
+
entry.rawExplain = rawExplain;
|
|
354
|
+
const engineHint = merged.engine ?? entry.engine;
|
|
355
|
+
const parsed = await parseExplainText(rawExplain, engineHint);
|
|
356
|
+
if (!parsed.statement) {
|
|
357
|
+
parsed.statement = entry.sql;
|
|
358
|
+
}
|
|
359
|
+
entry.plan = parsed;
|
|
360
|
+
if (!entry.engine) {
|
|
361
|
+
entry.engine = parsed.engine;
|
|
362
|
+
}
|
|
363
|
+
return parsed;
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
// Never fail or disrupt host queries when auto-EXPLAIN is unsupported or rejected.
|
|
367
|
+
return undefined;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Creates a Drizzle ORM `Logger` (`{ logQuery(query, params) }`) bound to this collector.
|
|
372
|
+
*/
|
|
373
|
+
createDrizzleLogger(engine) {
|
|
374
|
+
return {
|
|
375
|
+
logQuery: (query, params) => {
|
|
376
|
+
this.recordQuery({ sql: query, durationMs: 0, params, engine: engine ?? this.defaultEngine });
|
|
377
|
+
},
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Computes a point-in-time `DevtoolsSnapshot` including N+1 bursts and summary counters.
|
|
382
|
+
*/
|
|
383
|
+
getSnapshot() {
|
|
384
|
+
// Newest queries first for responsive HUD display, while keeping deterministic burst grouping
|
|
385
|
+
const queries = [...this.queries].reverse();
|
|
386
|
+
const groups = new Map();
|
|
387
|
+
const ungroupedWindowMs = 2000;
|
|
388
|
+
for (const q of this.queries) {
|
|
389
|
+
let key;
|
|
390
|
+
if (q.requestId) {
|
|
391
|
+
key = `req:${q.requestId}:${q.fingerprint}`;
|
|
392
|
+
}
|
|
393
|
+
else {
|
|
394
|
+
const bucket = Math.floor(q.timestamp / ungroupedWindowMs);
|
|
395
|
+
key = `win:${bucket}:${q.fingerprint}`;
|
|
396
|
+
}
|
|
397
|
+
const existing = groups.get(key);
|
|
398
|
+
if (!existing) {
|
|
399
|
+
groups.set(key, {
|
|
400
|
+
fingerprint: q.fingerprint,
|
|
401
|
+
normalizedSql: q.normalizedSql,
|
|
402
|
+
count: 1,
|
|
403
|
+
totalDurationMs: q.durationMs,
|
|
404
|
+
maxDurationMs: q.durationMs,
|
|
405
|
+
requestId: q.requestId,
|
|
406
|
+
requestLabel: q.requestLabel,
|
|
407
|
+
queryIds: [q.id],
|
|
408
|
+
sampleSql: q.sql,
|
|
409
|
+
anchorTimestamp: q.timestamp,
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
else {
|
|
413
|
+
existing.count += 1;
|
|
414
|
+
existing.totalDurationMs = Math.round((existing.totalDurationMs + q.durationMs) * 1000) / 1000;
|
|
415
|
+
if (q.durationMs > existing.maxDurationMs) {
|
|
416
|
+
existing.maxDurationMs = q.durationMs;
|
|
417
|
+
existing.sampleSql = q.sql;
|
|
418
|
+
}
|
|
419
|
+
existing.queryIds.push(q.id);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
const bursts = [];
|
|
423
|
+
for (const g of groups.values()) {
|
|
424
|
+
if (g.count >= this.nPlusOneThreshold) {
|
|
425
|
+
bursts.push({
|
|
426
|
+
fingerprint: g.fingerprint,
|
|
427
|
+
normalizedSql: g.normalizedSql,
|
|
428
|
+
count: g.count,
|
|
429
|
+
totalDurationMs: g.totalDurationMs,
|
|
430
|
+
maxDurationMs: g.maxDurationMs,
|
|
431
|
+
requestId: g.requestId,
|
|
432
|
+
requestLabel: g.requestLabel,
|
|
433
|
+
queryIds: g.queryIds,
|
|
434
|
+
sampleSql: g.sampleSql,
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
bursts.sort((a, b) => b.totalDurationMs - a.totalDurationMs || b.count - a.count);
|
|
439
|
+
let slowCount = 0;
|
|
440
|
+
let totalDurationMs = 0;
|
|
441
|
+
for (const q of this.queries) {
|
|
442
|
+
totalDurationMs += q.durationMs;
|
|
443
|
+
if (q.durationMs >= this.slowThresholdMs) {
|
|
444
|
+
slowCount += 1;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return {
|
|
448
|
+
queries,
|
|
449
|
+
bursts,
|
|
450
|
+
stats: {
|
|
451
|
+
totalQueries: this.queries.length,
|
|
452
|
+
slowCount,
|
|
453
|
+
burstCount: bursts.length,
|
|
454
|
+
totalDurationMs: Math.round(totalDurationMs * 100) / 100,
|
|
455
|
+
},
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/** Shared default collector singleton for zero-boilerplate driver instrumentation. */
|
|
460
|
+
export const defaultCollector = new CulpritCollector();
|
|
461
|
+
function extractPgExplainText(res) {
|
|
462
|
+
if (!res || typeof res !== "object")
|
|
463
|
+
return null;
|
|
464
|
+
const rows = res.rows;
|
|
465
|
+
if (!Array.isArray(rows) || rows.length === 0)
|
|
466
|
+
return null;
|
|
467
|
+
const first = rows[0];
|
|
468
|
+
if (typeof first === "string")
|
|
469
|
+
return first;
|
|
470
|
+
if (first && typeof first === "object") {
|
|
471
|
+
const record = first;
|
|
472
|
+
const qp = record["QUERY PLAN"] ?? record["query plan"] ?? Object.values(record)[0];
|
|
473
|
+
if (typeof qp === "string") {
|
|
474
|
+
// Multiple text lines returned as rows by EXPLAIN (ANALYZE)
|
|
475
|
+
if (rows.length > 1) {
|
|
476
|
+
return rows
|
|
477
|
+
.map((r) => {
|
|
478
|
+
if (typeof r === "string")
|
|
479
|
+
return r;
|
|
480
|
+
if (r && typeof r === "object") {
|
|
481
|
+
const v = r["QUERY PLAN"] ?? Object.values(r)[0];
|
|
482
|
+
return typeof v === "string" ? v : "";
|
|
483
|
+
}
|
|
484
|
+
return "";
|
|
485
|
+
})
|
|
486
|
+
.join("\n");
|
|
487
|
+
}
|
|
488
|
+
return qp;
|
|
489
|
+
}
|
|
490
|
+
if (qp !== undefined) {
|
|
491
|
+
return JSON.stringify(qp);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Instruments a `pg` `Pool` or `Client` with zero dependencies. Captures SQL text,
|
|
498
|
+
* parameter count, row count, duration, active request context, and optional safe
|
|
499
|
+
* `EXPLAIN (FORMAT JSON)` on slow `SELECT` queries.
|
|
500
|
+
*/
|
|
501
|
+
export function instrumentPg(poolOrClient, opts = {}) {
|
|
502
|
+
if (poolOrClient[INSTRUMENTED]) {
|
|
503
|
+
return poolOrClient;
|
|
504
|
+
}
|
|
505
|
+
const collector = opts.collector ?? defaultCollector;
|
|
506
|
+
const engine = opts.engine ?? "postgres";
|
|
507
|
+
const explainRunner = async (sql, params) => {
|
|
508
|
+
const cleanSql = sql.replace(/;\s*$/, "");
|
|
509
|
+
const explainSql = `${CULPRIT_INTERNAL_TAG} EXPLAIN (FORMAT JSON) ${cleanSql}`;
|
|
510
|
+
const res = params && params.length > 0
|
|
511
|
+
? await poolOrClient.query(explainSql, params)
|
|
512
|
+
: await poolOrClient.query(explainSql);
|
|
513
|
+
return extractPgExplainText(res);
|
|
514
|
+
};
|
|
515
|
+
const proxy = new Proxy(poolOrClient, {
|
|
516
|
+
get(target, prop, receiver) {
|
|
517
|
+
if (prop === INSTRUMENTED)
|
|
518
|
+
return true;
|
|
519
|
+
const orig = Reflect.get(target, prop, receiver);
|
|
520
|
+
if (prop === "connect" && typeof orig === "function") {
|
|
521
|
+
return function (...args) {
|
|
522
|
+
if (typeof args[0] === "function") {
|
|
523
|
+
const cb = args[0];
|
|
524
|
+
return orig.call(target, (err, client, done) => {
|
|
525
|
+
cb(err, client ? instrumentPg(client, opts) : client, done);
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
const p = orig.apply(target, args);
|
|
529
|
+
if (p && typeof p.then === "function") {
|
|
530
|
+
return p.then((client) => client && typeof client.query === "function"
|
|
531
|
+
? instrumentPg(client, opts)
|
|
532
|
+
: client);
|
|
533
|
+
}
|
|
534
|
+
return p;
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
if (prop !== "query" || typeof orig !== "function") {
|
|
538
|
+
return typeof orig === "function" ? orig.bind(target) : orig;
|
|
539
|
+
}
|
|
540
|
+
return function (...args) {
|
|
541
|
+
if (!collector.enabled) {
|
|
542
|
+
return orig.apply(target, args);
|
|
543
|
+
}
|
|
544
|
+
let sql = "";
|
|
545
|
+
let params;
|
|
546
|
+
let callbackIndex = -1;
|
|
547
|
+
if (typeof args[0] === "string") {
|
|
548
|
+
sql = args[0];
|
|
549
|
+
if (Array.isArray(args[1])) {
|
|
550
|
+
params = args[1];
|
|
551
|
+
if (typeof args[2] === "function")
|
|
552
|
+
callbackIndex = 2;
|
|
553
|
+
}
|
|
554
|
+
else if (typeof args[1] === "function") {
|
|
555
|
+
callbackIndex = 1;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
else if (args[0] && typeof args[0] === "object") {
|
|
559
|
+
const cfg = args[0];
|
|
560
|
+
sql = cfg.text ?? "";
|
|
561
|
+
if (Array.isArray(cfg.values))
|
|
562
|
+
params = cfg.values;
|
|
563
|
+
if (typeof args[1] === "function")
|
|
564
|
+
callbackIndex = 1;
|
|
565
|
+
}
|
|
566
|
+
if (!sql || sql.includes(CULPRIT_INTERNAL_TAG)) {
|
|
567
|
+
return orig.apply(target, args);
|
|
568
|
+
}
|
|
569
|
+
const startedAt = performance.now();
|
|
570
|
+
const timestamp = Date.now();
|
|
571
|
+
const reqCtx = collector.getCurrentRequest();
|
|
572
|
+
const resolveExplainOpts = () => {
|
|
573
|
+
if (opts.autoExplain === false)
|
|
574
|
+
return { enabled: false };
|
|
575
|
+
if (opts.autoExplain === true)
|
|
576
|
+
return { enabled: true, engine, runExplain: explainRunner };
|
|
577
|
+
if (opts.autoExplain && typeof opts.autoExplain === "object") {
|
|
578
|
+
return {
|
|
579
|
+
enabled: opts.autoExplain.enabled ?? true,
|
|
580
|
+
engine,
|
|
581
|
+
runExplain: opts.autoExplain.runExplain ?? explainRunner,
|
|
582
|
+
thresholdMs: opts.autoExplain.thresholdMs,
|
|
583
|
+
maxExplains: opts.autoExplain.maxExplains,
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
return { engine, runExplain: explainRunner };
|
|
587
|
+
};
|
|
588
|
+
if (callbackIndex >= 0) {
|
|
589
|
+
const origCb = args[callbackIndex];
|
|
590
|
+
const nextArgs = [...args];
|
|
591
|
+
nextArgs[callbackIndex] = (err, res) => {
|
|
592
|
+
const durationMs = performance.now() - startedAt;
|
|
593
|
+
const rowCount = typeof res?.rowCount === "number"
|
|
594
|
+
? res.rowCount
|
|
595
|
+
: Array.isArray(res?.rows)
|
|
596
|
+
? res.rows.length
|
|
597
|
+
: undefined;
|
|
598
|
+
const entry = collector.recordQuery({
|
|
599
|
+
sql,
|
|
600
|
+
durationMs,
|
|
601
|
+
params,
|
|
602
|
+
rowCount,
|
|
603
|
+
engine,
|
|
604
|
+
timestamp,
|
|
605
|
+
requestId: reqCtx?.requestId,
|
|
606
|
+
requestLabel: reqCtx?.requestLabel,
|
|
607
|
+
error: err ? (err instanceof Error ? err : String(err)) : undefined,
|
|
608
|
+
});
|
|
609
|
+
if (entry && !err) {
|
|
610
|
+
void collector.maybeAutoExplain(entry, params, resolveExplainOpts()).finally(() => {
|
|
611
|
+
origCb(err, res);
|
|
612
|
+
});
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
origCb(err, res);
|
|
616
|
+
};
|
|
617
|
+
return orig.apply(target, nextArgs);
|
|
618
|
+
}
|
|
619
|
+
const resultPromise = orig.apply(target, args);
|
|
620
|
+
if (resultPromise && typeof resultPromise.then === "function") {
|
|
621
|
+
return resultPromise.then(async (res) => {
|
|
622
|
+
const durationMs = performance.now() - startedAt;
|
|
623
|
+
const rowCount = typeof res?.rowCount === "number"
|
|
624
|
+
? res.rowCount
|
|
625
|
+
: Array.isArray(res?.rows)
|
|
626
|
+
? res.rows.length
|
|
627
|
+
: undefined;
|
|
628
|
+
const entry = collector.recordQuery({
|
|
629
|
+
sql,
|
|
630
|
+
durationMs,
|
|
631
|
+
params,
|
|
632
|
+
rowCount,
|
|
633
|
+
engine,
|
|
634
|
+
timestamp,
|
|
635
|
+
requestId: reqCtx?.requestId,
|
|
636
|
+
requestLabel: reqCtx?.requestLabel,
|
|
637
|
+
});
|
|
638
|
+
if (entry) {
|
|
639
|
+
await collector.maybeAutoExplain(entry, params, resolveExplainOpts());
|
|
640
|
+
}
|
|
641
|
+
return res;
|
|
642
|
+
}, (err) => {
|
|
643
|
+
const durationMs = performance.now() - startedAt;
|
|
644
|
+
collector.recordQuery({
|
|
645
|
+
sql,
|
|
646
|
+
durationMs,
|
|
647
|
+
params,
|
|
648
|
+
engine,
|
|
649
|
+
timestamp,
|
|
650
|
+
requestId: reqCtx?.requestId,
|
|
651
|
+
requestLabel: reqCtx?.requestLabel,
|
|
652
|
+
error: err instanceof Error ? err : String(err),
|
|
653
|
+
});
|
|
654
|
+
throw err;
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
return resultPromise;
|
|
658
|
+
};
|
|
659
|
+
},
|
|
660
|
+
});
|
|
661
|
+
return proxy;
|
|
662
|
+
}
|
|
663
|
+
function extractMysqlExplainText(res) {
|
|
664
|
+
const rows = Array.isArray(res) && Array.isArray(res[0]) ? res[0] : Array.isArray(res) ? res : null;
|
|
665
|
+
if (!rows || rows.length === 0)
|
|
666
|
+
return null;
|
|
667
|
+
const first = rows[0];
|
|
668
|
+
if (typeof first === "string")
|
|
669
|
+
return first;
|
|
670
|
+
if (first && typeof first === "object") {
|
|
671
|
+
const rec = first;
|
|
672
|
+
const val = rec.EXPLAIN ?? rec.explain ?? Object.values(rec)[0];
|
|
673
|
+
if (typeof val === "string")
|
|
674
|
+
return val;
|
|
675
|
+
if (val !== undefined)
|
|
676
|
+
return JSON.stringify(val);
|
|
677
|
+
}
|
|
678
|
+
return null;
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Instruments a `mysql2` Promise or callback pool/connection (`query` and `execute`).
|
|
682
|
+
*/
|
|
683
|
+
export function instrumentMysql(poolOrConn, opts = {}) {
|
|
684
|
+
if (poolOrConn[INSTRUMENTED]) {
|
|
685
|
+
return poolOrConn;
|
|
686
|
+
}
|
|
687
|
+
const collector = opts.collector ?? defaultCollector;
|
|
688
|
+
const engine = opts.engine ?? "mysql";
|
|
689
|
+
const explainRunner = async (sql, params) => {
|
|
690
|
+
const cleanSql = sql.replace(/;\s*$/, "");
|
|
691
|
+
const explainSql = `${CULPRIT_INTERNAL_TAG} EXPLAIN FORMAT=JSON ${cleanSql}`;
|
|
692
|
+
const res = params && params.length > 0
|
|
693
|
+
? await poolOrConn.query(explainSql, params)
|
|
694
|
+
: await poolOrConn.query(explainSql);
|
|
695
|
+
return extractMysqlExplainText(res);
|
|
696
|
+
};
|
|
697
|
+
return new Proxy(poolOrConn, {
|
|
698
|
+
get(target, prop, receiver) {
|
|
699
|
+
if (prop === INSTRUMENTED)
|
|
700
|
+
return true;
|
|
701
|
+
const orig = Reflect.get(target, prop, receiver);
|
|
702
|
+
if ((prop !== "query" && prop !== "execute") || typeof orig !== "function") {
|
|
703
|
+
return typeof orig === "function" ? orig.bind(target) : orig;
|
|
704
|
+
}
|
|
705
|
+
return function (...args) {
|
|
706
|
+
if (!collector.enabled)
|
|
707
|
+
return orig.apply(target, args);
|
|
708
|
+
let sql = "";
|
|
709
|
+
let params;
|
|
710
|
+
if (typeof args[0] === "string") {
|
|
711
|
+
sql = args[0];
|
|
712
|
+
if (Array.isArray(args[1]))
|
|
713
|
+
params = args[1];
|
|
714
|
+
}
|
|
715
|
+
else if (args[0] && typeof args[0] === "object") {
|
|
716
|
+
const cfg = args[0];
|
|
717
|
+
sql = cfg.sql ?? "";
|
|
718
|
+
if (Array.isArray(cfg.values))
|
|
719
|
+
params = cfg.values;
|
|
720
|
+
else if (Array.isArray(args[1]))
|
|
721
|
+
params = args[1];
|
|
722
|
+
}
|
|
723
|
+
if (!sql || sql.includes(CULPRIT_INTERNAL_TAG)) {
|
|
724
|
+
return orig.apply(target, args);
|
|
725
|
+
}
|
|
726
|
+
const startedAt = performance.now();
|
|
727
|
+
const timestamp = Date.now();
|
|
728
|
+
const reqCtx = collector.getCurrentRequest();
|
|
729
|
+
const resolveExplainOpts = () => {
|
|
730
|
+
if (opts.autoExplain === false)
|
|
731
|
+
return { enabled: false };
|
|
732
|
+
if (opts.autoExplain === true)
|
|
733
|
+
return { enabled: true, engine, runExplain: explainRunner };
|
|
734
|
+
if (opts.autoExplain && typeof opts.autoExplain === "object") {
|
|
735
|
+
return {
|
|
736
|
+
enabled: opts.autoExplain.enabled ?? true,
|
|
737
|
+
engine,
|
|
738
|
+
runExplain: opts.autoExplain.runExplain ?? explainRunner,
|
|
739
|
+
thresholdMs: opts.autoExplain.thresholdMs,
|
|
740
|
+
maxExplains: opts.autoExplain.maxExplains,
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
return { engine, runExplain: explainRunner };
|
|
744
|
+
};
|
|
745
|
+
const out = orig.apply(target, args);
|
|
746
|
+
if (out && typeof out.then === "function") {
|
|
747
|
+
return out.then(async (res) => {
|
|
748
|
+
const durationMs = performance.now() - startedAt;
|
|
749
|
+
const rowsPart = Array.isArray(res) ? res[0] : res;
|
|
750
|
+
const rowCount = Array.isArray(rowsPart)
|
|
751
|
+
? rowsPart.length
|
|
752
|
+
: rowsPart && typeof rowsPart === "object" && typeof rowsPart.affectedRows === "number"
|
|
753
|
+
? rowsPart.affectedRows
|
|
754
|
+
: undefined;
|
|
755
|
+
const entry = collector.recordQuery({
|
|
756
|
+
sql,
|
|
757
|
+
durationMs,
|
|
758
|
+
params,
|
|
759
|
+
rowCount,
|
|
760
|
+
engine,
|
|
761
|
+
timestamp,
|
|
762
|
+
requestId: reqCtx?.requestId,
|
|
763
|
+
requestLabel: reqCtx?.requestLabel,
|
|
764
|
+
});
|
|
765
|
+
if (entry) {
|
|
766
|
+
await collector.maybeAutoExplain(entry, params, resolveExplainOpts());
|
|
767
|
+
}
|
|
768
|
+
return res;
|
|
769
|
+
}, (err) => {
|
|
770
|
+
collector.recordQuery({
|
|
771
|
+
sql,
|
|
772
|
+
durationMs: performance.now() - startedAt,
|
|
773
|
+
params,
|
|
774
|
+
engine,
|
|
775
|
+
timestamp,
|
|
776
|
+
requestId: reqCtx?.requestId,
|
|
777
|
+
requestLabel: reqCtx?.requestLabel,
|
|
778
|
+
error: err instanceof Error ? err : String(err),
|
|
779
|
+
});
|
|
780
|
+
throw err;
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
return out;
|
|
784
|
+
};
|
|
785
|
+
},
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
function formatSqliteExplainRows(rows) {
|
|
789
|
+
if (typeof rows === "string")
|
|
790
|
+
return rows;
|
|
791
|
+
if (!Array.isArray(rows) || rows.length === 0)
|
|
792
|
+
return null;
|
|
793
|
+
const lines = [];
|
|
794
|
+
for (let idx = 0; idx < rows.length; idx++) {
|
|
795
|
+
const r = rows[idx];
|
|
796
|
+
if (r && typeof r === "object") {
|
|
797
|
+
const rec = r;
|
|
798
|
+
const id = rec.id ?? rec.selectid ?? idx + 1;
|
|
799
|
+
const parent = rec.parent ?? 0;
|
|
800
|
+
const notused = rec.notused ?? 0;
|
|
801
|
+
const detail = rec.detail ?? "";
|
|
802
|
+
if (typeof detail === "string" && detail.length > 0) {
|
|
803
|
+
lines.push(`${id}|${parent}|${notused}|${detail}`);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
return lines.length > 0 ? lines.join("\n") : null;
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Instruments a synchronous SQLite handle (`better-sqlite3`, `node:sqlite`, `bun:sqlite`).
|
|
811
|
+
*/
|
|
812
|
+
export function instrumentSqlite(db, opts = {}) {
|
|
813
|
+
if (db[INSTRUMENTED]) {
|
|
814
|
+
return db;
|
|
815
|
+
}
|
|
816
|
+
const collector = opts.collector ?? defaultCollector;
|
|
817
|
+
const engine = opts.engine ?? "sqlite";
|
|
818
|
+
const explainRunner = async (sql, params) => {
|
|
819
|
+
const cleanSql = sql.replace(/;\s*$/, "");
|
|
820
|
+
const explainSql = `${CULPRIT_INTERNAL_TAG} EXPLAIN QUERY PLAN ${cleanSql}`;
|
|
821
|
+
const prep = db.prepare ?? db.query;
|
|
822
|
+
if (typeof prep !== "function")
|
|
823
|
+
return null;
|
|
824
|
+
const stmt = prep.call(db, explainSql);
|
|
825
|
+
if (typeof stmt.all !== "function")
|
|
826
|
+
return null;
|
|
827
|
+
const rows = params && params.length > 0 ? stmt.all(...params) : stmt.all();
|
|
828
|
+
return formatSqliteExplainRows(rows);
|
|
829
|
+
};
|
|
830
|
+
const wrapStatement = (stmt, sql) => {
|
|
831
|
+
if (!stmt || typeof stmt !== "object" || sql.includes(CULPRIT_INTERNAL_TAG)) {
|
|
832
|
+
return stmt;
|
|
833
|
+
}
|
|
834
|
+
return new Proxy(stmt, {
|
|
835
|
+
get(stmtTarget, methodProp, stmtReceiver) {
|
|
836
|
+
const method = Reflect.get(stmtTarget, methodProp, stmtReceiver);
|
|
837
|
+
if ((methodProp !== "all" && methodProp !== "get" && methodProp !== "run" && methodProp !== "values") ||
|
|
838
|
+
typeof method !== "function") {
|
|
839
|
+
return typeof method === "function" ? method.bind(stmtTarget) : method;
|
|
840
|
+
}
|
|
841
|
+
return function (...callArgs) {
|
|
842
|
+
if (!collector.enabled)
|
|
843
|
+
return method.apply(stmtTarget, callArgs);
|
|
844
|
+
const params = callArgs.length === 1 && Array.isArray(callArgs[0])
|
|
845
|
+
? callArgs[0]
|
|
846
|
+
: callArgs;
|
|
847
|
+
const startedAt = performance.now();
|
|
848
|
+
try {
|
|
849
|
+
const res = method.apply(stmtTarget, callArgs);
|
|
850
|
+
const durationMs = performance.now() - startedAt;
|
|
851
|
+
const rowCount = methodProp === "all" || methodProp === "values"
|
|
852
|
+
? Array.isArray(res)
|
|
853
|
+
? res.length
|
|
854
|
+
: undefined
|
|
855
|
+
: methodProp === "get"
|
|
856
|
+
? res === undefined || res === null
|
|
857
|
+
? 0
|
|
858
|
+
: 1
|
|
859
|
+
: res && typeof res === "object" && typeof res.changes === "number"
|
|
860
|
+
? res.changes
|
|
861
|
+
: undefined;
|
|
862
|
+
const entry = collector.recordQuery({
|
|
863
|
+
sql,
|
|
864
|
+
durationMs,
|
|
865
|
+
params,
|
|
866
|
+
rowCount,
|
|
867
|
+
engine,
|
|
868
|
+
});
|
|
869
|
+
if (entry && opts.autoExplain) {
|
|
870
|
+
const explainOpts = typeof opts.autoExplain === "boolean"
|
|
871
|
+
? { enabled: opts.autoExplain, engine, runExplain: explainRunner }
|
|
872
|
+
: {
|
|
873
|
+
enabled: opts.autoExplain.enabled ?? true,
|
|
874
|
+
engine,
|
|
875
|
+
runExplain: opts.autoExplain.runExplain ?? explainRunner,
|
|
876
|
+
thresholdMs: opts.autoExplain.thresholdMs,
|
|
877
|
+
maxExplains: opts.autoExplain.maxExplains,
|
|
878
|
+
};
|
|
879
|
+
void collector.maybeAutoExplain(entry, params, explainOpts);
|
|
880
|
+
}
|
|
881
|
+
return res;
|
|
882
|
+
}
|
|
883
|
+
catch (err) {
|
|
884
|
+
collector.recordQuery({
|
|
885
|
+
sql,
|
|
886
|
+
durationMs: performance.now() - startedAt,
|
|
887
|
+
params,
|
|
888
|
+
engine,
|
|
889
|
+
error: err instanceof Error ? err : String(err),
|
|
890
|
+
});
|
|
891
|
+
throw err;
|
|
892
|
+
}
|
|
893
|
+
};
|
|
894
|
+
},
|
|
895
|
+
});
|
|
896
|
+
};
|
|
897
|
+
return new Proxy(db, {
|
|
898
|
+
get(target, prop, receiver) {
|
|
899
|
+
if (prop === INSTRUMENTED)
|
|
900
|
+
return true;
|
|
901
|
+
const orig = Reflect.get(target, prop, receiver);
|
|
902
|
+
if ((prop === "prepare" || prop === "query") && typeof orig === "function") {
|
|
903
|
+
return function (sql, ...rest) {
|
|
904
|
+
const stmt = orig.call(target, sql, ...rest);
|
|
905
|
+
return wrapStatement(stmt, sql);
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
if (prop === "exec" && typeof orig === "function") {
|
|
909
|
+
return function (sql, ...rest) {
|
|
910
|
+
if (!collector.enabled || sql.includes(CULPRIT_INTERNAL_TAG)) {
|
|
911
|
+
return orig.call(target, sql, ...rest);
|
|
912
|
+
}
|
|
913
|
+
const startedAt = performance.now();
|
|
914
|
+
try {
|
|
915
|
+
const out = orig.call(target, sql, ...rest);
|
|
916
|
+
collector.recordQuery({ sql, durationMs: performance.now() - startedAt, engine });
|
|
917
|
+
return out;
|
|
918
|
+
}
|
|
919
|
+
catch (err) {
|
|
920
|
+
collector.recordQuery({
|
|
921
|
+
sql,
|
|
922
|
+
durationMs: performance.now() - startedAt,
|
|
923
|
+
engine,
|
|
924
|
+
error: err instanceof Error ? err : String(err),
|
|
925
|
+
});
|
|
926
|
+
throw err;
|
|
927
|
+
}
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
return typeof orig === "function" ? orig.bind(target) : orig;
|
|
931
|
+
},
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
// ───────── HTTP / Fetch DevTools Endpoints ─────────
|
|
935
|
+
function isLoopbackToken(raw) {
|
|
936
|
+
const trimmed = raw.trim().toLowerCase();
|
|
937
|
+
if (!trimmed)
|
|
938
|
+
return false;
|
|
939
|
+
// Strip brackets and optional :port on IPv4 / localhost
|
|
940
|
+
let host = trimmed;
|
|
941
|
+
if (host.startsWith("[")) {
|
|
942
|
+
const close = host.indexOf("]");
|
|
943
|
+
if (close !== -1)
|
|
944
|
+
host = host.slice(1, close);
|
|
945
|
+
}
|
|
946
|
+
else if (host.split(":").length === 2) {
|
|
947
|
+
// host:port (not raw IPv6)
|
|
948
|
+
host = host.split(":")[0];
|
|
949
|
+
}
|
|
950
|
+
return (host === "localhost" ||
|
|
951
|
+
host === "127.0.0.1" ||
|
|
952
|
+
host === "::1" ||
|
|
953
|
+
host === "::ffff:127.0.0.1" ||
|
|
954
|
+
host === "0:0:0:0:0:0:0:1" ||
|
|
955
|
+
host.startsWith("127."));
|
|
956
|
+
}
|
|
957
|
+
function checkAccessAllowed(params, options) {
|
|
958
|
+
if (process.env.NODE_ENV === "production" && !options.allowProduction) {
|
|
959
|
+
return {
|
|
960
|
+
ok: false,
|
|
961
|
+
status: 403,
|
|
962
|
+
reason: "Culprit DevTools endpoint is disabled when NODE_ENV is production.",
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
if (options.allowRemote) {
|
|
966
|
+
return { ok: true };
|
|
967
|
+
}
|
|
968
|
+
if (params.forwardedFor) {
|
|
969
|
+
const hops = params.forwardedFor.split(",").map((s) => s.trim()).filter(Boolean);
|
|
970
|
+
if (hops.some((hop) => !isLoopbackToken(hop))) {
|
|
971
|
+
return {
|
|
972
|
+
ok: false,
|
|
973
|
+
status: 403,
|
|
974
|
+
reason: "Culprit DevTools refuses non-loopback requests unless allowRemote is true.",
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
if (params.remoteAddress && !isLoopbackToken(params.remoteAddress)) {
|
|
979
|
+
return {
|
|
980
|
+
ok: false,
|
|
981
|
+
status: 403,
|
|
982
|
+
reason: "Culprit DevTools refuses non-loopback requests unless allowRemote is true.",
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
if (params.hostHeader && !isLoopbackToken(params.hostHeader)) {
|
|
986
|
+
return {
|
|
987
|
+
ok: false,
|
|
988
|
+
status: 403,
|
|
989
|
+
reason: "Culprit DevTools refuses non-loopback requests unless allowRemote is true.",
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
if (params.urlHost && !isLoopbackToken(params.urlHost)) {
|
|
993
|
+
return {
|
|
994
|
+
ok: false,
|
|
995
|
+
status: 403,
|
|
996
|
+
reason: "Culprit DevTools refuses non-loopback requests unless allowRemote is true.",
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
return { ok: true };
|
|
1000
|
+
}
|
|
1001
|
+
function jsonResponse(body, status = 200) {
|
|
1002
|
+
return new Response(JSON.stringify(body), {
|
|
1003
|
+
status,
|
|
1004
|
+
headers: {
|
|
1005
|
+
"content-type": "application/json; charset=utf-8",
|
|
1006
|
+
"cache-control": "no-store",
|
|
1007
|
+
},
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
function normalizeBasePath(basePath) {
|
|
1011
|
+
const raw = (basePath ?? "/__culprit").trim();
|
|
1012
|
+
if (!raw || raw === "/")
|
|
1013
|
+
return "/__culprit";
|
|
1014
|
+
return raw.endsWith("/") ? raw.slice(0, -1) : raw;
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* Creates a standard Web Fetch `(req: Request) => Promise<Response>` handler
|
|
1018
|
+
* suitable for Next.js Route Handlers, Hono, Remix, SvelteKit, Astro, and Bun.serve.
|
|
1019
|
+
*
|
|
1020
|
+
* Routes:
|
|
1021
|
+
* - `GET /__culprit/snapshot` -> `DevtoolsSnapshot`
|
|
1022
|
+
* - `POST /__culprit/clear` -> clears recorded queries
|
|
1023
|
+
* - `POST /__culprit/parse` -> parses raw `EXPLAIN` text into a `Plan` via `@culpritsql/plans`
|
|
1024
|
+
*/
|
|
1025
|
+
export function createDevtoolsHandler(collector = defaultCollector, options = {}) {
|
|
1026
|
+
const basePath = normalizeBasePath(options.basePath);
|
|
1027
|
+
return async (req, info) => {
|
|
1028
|
+
const parsedUrl = new URL(req.url, "http://localhost");
|
|
1029
|
+
const access = checkAccessAllowed({
|
|
1030
|
+
urlHost: parsedUrl.hostname,
|
|
1031
|
+
hostHeader: req.headers.get("host"),
|
|
1032
|
+
forwardedFor: req.headers.get("x-forwarded-for"),
|
|
1033
|
+
remoteAddress: info?.remoteAddress ?? null,
|
|
1034
|
+
}, options);
|
|
1035
|
+
if (!access.ok) {
|
|
1036
|
+
return jsonResponse({ error: access.reason }, access.status);
|
|
1037
|
+
}
|
|
1038
|
+
const pathname = parsedUrl.pathname.replace(/\/+$/, "") || "/";
|
|
1039
|
+
const route = pathname.startsWith(basePath) ? pathname.slice(basePath.length) || "/" : pathname;
|
|
1040
|
+
if (req.method === "GET" && (route === "/snapshot" || route === "/")) {
|
|
1041
|
+
return jsonResponse(collector.getSnapshot());
|
|
1042
|
+
}
|
|
1043
|
+
if (req.method === "POST" && route === "/clear") {
|
|
1044
|
+
collector.clear();
|
|
1045
|
+
return jsonResponse(collector.getSnapshot());
|
|
1046
|
+
}
|
|
1047
|
+
if (req.method === "POST" && route === "/parse") {
|
|
1048
|
+
const rawText = await req.text();
|
|
1049
|
+
if (Buffer.byteLength(rawText, "utf8") > MAX_EXPLAIN_BODY_BYTES) {
|
|
1050
|
+
return jsonResponse({ error: "EXPLAIN payload exceeds maximum allowed size (2 MB)." }, 413);
|
|
1051
|
+
}
|
|
1052
|
+
let rawExplain = rawText;
|
|
1053
|
+
let engine;
|
|
1054
|
+
const contentType = req.headers.get("content-type") ?? "";
|
|
1055
|
+
if (contentType.includes("application/json") || rawText.trim().startsWith("{")) {
|
|
1056
|
+
try {
|
|
1057
|
+
const parsedBody = JSON.parse(rawText);
|
|
1058
|
+
if (typeof parsedBody.rawExplain === "string") {
|
|
1059
|
+
rawExplain = parsedBody.rawExplain;
|
|
1060
|
+
engine = coerceEngine(parsedBody.engine);
|
|
1061
|
+
}
|
|
1062
|
+
else if (typeof parsedBody.explain === "string") {
|
|
1063
|
+
rawExplain = parsedBody.explain;
|
|
1064
|
+
engine = coerceEngine(parsedBody.engine);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
catch {
|
|
1068
|
+
// If the raw body itself is a JSON plan (e.g. MySQL EXPLAIN FORMAT=JSON object), pass rawText directly.
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
if (!rawExplain || !rawExplain.trim()) {
|
|
1072
|
+
return jsonResponse({ error: "Provide non-empty EXPLAIN output to parse." }, 400);
|
|
1073
|
+
}
|
|
1074
|
+
try {
|
|
1075
|
+
const plan = await parseExplainText(rawExplain, engine);
|
|
1076
|
+
return jsonResponse({ plan });
|
|
1077
|
+
}
|
|
1078
|
+
catch (err) {
|
|
1079
|
+
if (err instanceof ParserError) {
|
|
1080
|
+
return jsonResponse({
|
|
1081
|
+
error: err.error.message,
|
|
1082
|
+
code: err.error.code,
|
|
1083
|
+
hint: err.error.hint,
|
|
1084
|
+
}, 400);
|
|
1085
|
+
}
|
|
1086
|
+
return jsonResponse({ error: err instanceof Error ? err.message : "Failed to parse EXPLAIN output." }, 400);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
return jsonResponse({ error: `Unknown Culprit DevTools route: ${req.method} ${pathname}` }, 404);
|
|
1090
|
+
};
|
|
1091
|
+
}
|
|
1092
|
+
function readNodeRequestBody(req, maxBytes) {
|
|
1093
|
+
return new Promise((resolve, reject) => {
|
|
1094
|
+
const chunks = [];
|
|
1095
|
+
let total = 0;
|
|
1096
|
+
req.on("data", (chunk) => {
|
|
1097
|
+
const buf = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
|
|
1098
|
+
total += buf.length;
|
|
1099
|
+
if (total > maxBytes) {
|
|
1100
|
+
reject(new Error("BODY_TOO_LARGE"));
|
|
1101
|
+
req.destroy();
|
|
1102
|
+
return;
|
|
1103
|
+
}
|
|
1104
|
+
chunks.push(buf);
|
|
1105
|
+
});
|
|
1106
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
1107
|
+
req.on("error", reject);
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Creates a Connect / Express / Node `http.Server` middleware for `/__culprit/*`.
|
|
1112
|
+
* For non-DevTools routes, when `next` is provided, automatically wraps downstream
|
|
1113
|
+
* handlers inside `collector.withRequest("METHOD /path", ...)` so queries inherit request labels!
|
|
1114
|
+
*/
|
|
1115
|
+
export function createNodeDevtoolsMiddleware(collector = defaultCollector, options = {}) {
|
|
1116
|
+
const basePath = normalizeBasePath(options.basePath);
|
|
1117
|
+
const fetchHandler = createDevtoolsHandler(collector, options);
|
|
1118
|
+
const correlate = options.correlateRequests ?? true;
|
|
1119
|
+
return (req, res, next) => {
|
|
1120
|
+
const rawUrl = req.url ?? "/";
|
|
1121
|
+
const hostHeader = typeof req.headers.host === "string" ? req.headers.host : "localhost";
|
|
1122
|
+
const parsedUrl = new URL(rawUrl, `http://${hostHeader}`);
|
|
1123
|
+
if (!parsedUrl.pathname.startsWith(basePath)) {
|
|
1124
|
+
if (next) {
|
|
1125
|
+
if (correlate && collector.enabled) {
|
|
1126
|
+
const label = `${req.method ?? "GET"} ${parsedUrl.pathname}`;
|
|
1127
|
+
collector.withRequest(label, () => next());
|
|
1128
|
+
}
|
|
1129
|
+
else {
|
|
1130
|
+
next();
|
|
1131
|
+
}
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
res.statusCode = 404;
|
|
1135
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
1136
|
+
res.end(JSON.stringify({ error: "Not Found" }));
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
void (async () => {
|
|
1140
|
+
try {
|
|
1141
|
+
const method = req.method ?? "GET";
|
|
1142
|
+
const body = method === "GET" || method === "HEAD"
|
|
1143
|
+
? undefined
|
|
1144
|
+
: await readNodeRequestBody(req, MAX_EXPLAIN_BODY_BYTES + 1024);
|
|
1145
|
+
const headers = new Headers();
|
|
1146
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
1147
|
+
if (typeof value === "string")
|
|
1148
|
+
headers.set(key, value);
|
|
1149
|
+
else if (Array.isArray(value))
|
|
1150
|
+
headers.set(key, value.join(", "));
|
|
1151
|
+
}
|
|
1152
|
+
const webReq = new Request(parsedUrl.toString(), {
|
|
1153
|
+
method,
|
|
1154
|
+
headers,
|
|
1155
|
+
body,
|
|
1156
|
+
});
|
|
1157
|
+
const webRes = await fetchHandler(webReq, {
|
|
1158
|
+
remoteAddress: req.socket?.remoteAddress,
|
|
1159
|
+
});
|
|
1160
|
+
res.statusCode = webRes.status;
|
|
1161
|
+
webRes.headers.forEach((v, k) => res.setHeader(k, v));
|
|
1162
|
+
const text = await webRes.text();
|
|
1163
|
+
res.end(text);
|
|
1164
|
+
}
|
|
1165
|
+
catch (err) {
|
|
1166
|
+
if (err instanceof Error && err.message === "BODY_TOO_LARGE") {
|
|
1167
|
+
res.statusCode = 413;
|
|
1168
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
1169
|
+
res.end(JSON.stringify({ error: "EXPLAIN payload exceeds maximum allowed size (2 MB)." }));
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
res.statusCode = 500;
|
|
1173
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
1174
|
+
res.end(JSON.stringify({ error: "Internal Culprit DevTools error." }));
|
|
1175
|
+
}
|
|
1176
|
+
})();
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
//# sourceMappingURL=server.js.map
|