@warlock.js/devtools 5.55.0 → 5.56.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/CHANGELOG.md +29 -0
- package/README.md +26 -13
- package/cjs/ai-source-DTpxumMA.cjs +381 -0
- package/cjs/ai-source-DTpxumMA.cjs.map +1 -0
- package/cjs/auth-DzU0gHDG.cjs +1655 -0
- package/cjs/auth-DzU0gHDG.cjs.map +1 -0
- package/cjs/boot-BQi0Etor.cjs +138 -0
- package/cjs/boot-BQi0Etor.cjs.map +1 -0
- package/cjs/capture-CqIiaznN.cjs +1342 -0
- package/cjs/capture-CqIiaznN.cjs.map +1 -0
- package/cjs/cascade-store-pHjKeSFm.cjs +863 -0
- package/cjs/cascade-store-pHjKeSFm.cjs.map +1 -0
- package/cjs/collector-CJbQbzzK.cjs +271 -0
- package/cjs/collector-CJbQbzzK.cjs.map +1 -0
- package/cjs/contracts-CVmplkNb.cjs +112 -0
- package/cjs/contracts-CVmplkNb.cjs.map +1 -0
- package/cjs/current-request-id-BoJJb3y7.cjs +37 -0
- package/cjs/current-request-id-BoJJb3y7.cjs.map +1 -0
- package/cjs/errors-CyZp5yS-.cjs +177 -0
- package/cjs/errors-CyZp5yS-.cjs.map +1 -0
- package/cjs/histogram-BaI-PnCv.cjs +102 -0
- package/cjs/histogram-BaI-PnCv.cjs.map +1 -0
- package/cjs/http-CabcUwBx.cjs +870 -0
- package/cjs/http-CabcUwBx.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/insights-BKtqxdnP.cjs +811 -0
- package/cjs/insights-BKtqxdnP.cjs.map +1 -0
- package/cjs/ip-DbNhPOzi.cjs +153 -0
- package/cjs/ip-DbNhPOzi.cjs.map +1 -0
- package/cjs/migrations-w7GMsrQw.cjs +297 -0
- package/cjs/migrations-w7GMsrQw.cjs.map +1 -0
- package/cjs/openapi-CC7OAUc6.cjs +52 -0
- package/cjs/openapi-CC7OAUc6.cjs.map +1 -0
- package/cjs/options-CWqFC5__.cjs +181 -0
- package/cjs/options-CWqFC5__.cjs.map +1 -0
- package/cjs/panels-B0dAfGbJ.cjs +298 -0
- package/cjs/panels-B0dAfGbJ.cjs.map +1 -0
- package/cjs/process-panel-DEOnLxoT.cjs +48 -0
- package/cjs/process-panel-DEOnLxoT.cjs.map +1 -0
- package/cjs/production/index.cjs +238 -0
- package/cjs/production/index.cjs.map +1 -0
- package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +52 -0
- package/cjs/server-B6xdeKS8.cjs +184 -0
- package/cjs/server-B6xdeKS8.cjs.map +1 -0
- package/cjs/{src-Xwm3Eel9.cjs → src-Ce-3Lniv.cjs} +163 -295
- package/cjs/src-Ce-3Lniv.cjs.map +1 -0
- package/cjs/store-aq207T8v.cjs +9 -0
- package/cjs/stream-route-BGJa-zQu.cjs +875 -0
- package/cjs/stream-route-BGJa-zQu.cjs.map +1 -0
- package/esm/devtools-connector.d.mts +16 -13
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +127 -18
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +3 -2
- package/esm/options.mjs +2 -1
- package/esm/options.mjs.map +1 -1
- package/esm/panels.mjs +50 -5
- package/esm/panels.mjs.map +1 -1
- package/esm/production/auth/common-passwords.mjs +303 -0
- package/esm/production/auth/common-passwords.mjs.map +1 -0
- package/esm/production/auth/default-crypto.mjs +19 -0
- package/esm/production/auth/default-crypto.mjs.map +1 -0
- package/esm/production/auth/helpers.mjs +77 -0
- package/esm/production/auth/helpers.mjs.map +1 -0
- package/esm/production/auth/index.mjs +6 -0
- package/esm/production/auth/passkeys.mjs +96 -0
- package/esm/production/auth/passkeys.mjs.map +1 -0
- package/esm/production/auth/service.mjs +1166 -0
- package/esm/production/auth/service.mjs.map +1 -0
- package/esm/production/boot.mjs +138 -0
- package/esm/production/boot.mjs.map +1 -0
- package/esm/production/capture/dev-stats.mjs +83 -0
- package/esm/production/capture/dev-stats.mjs.map +1 -0
- package/esm/production/capture/engine.mjs +442 -0
- package/esm/production/capture/engine.mjs.map +1 -0
- package/esm/production/capture/explain.mjs +271 -0
- package/esm/production/capture/explain.mjs.map +1 -0
- package/esm/production/capture/filter.mjs +24 -0
- package/esm/production/capture/filter.mjs.map +1 -0
- package/esm/production/capture/index.mjs +7 -0
- package/esm/production/capture/production-capture.mjs +134 -0
- package/esm/production/capture/production-capture.mjs.map +1 -0
- package/esm/production/capture/redact.mjs +109 -0
- package/esm/production/capture/redact.mjs.map +1 -0
- package/esm/production/capture/stats-stores.mjs +300 -0
- package/esm/production/capture/stats-stores.mjs.map +1 -0
- package/esm/production/cli/actions.mjs +151 -0
- package/esm/production/cli/actions.mjs.map +1 -0
- package/esm/production/cli/index.d.mts +17 -0
- package/esm/production/cli/index.d.mts.map +1 -0
- package/esm/production/cli/index.mjs +86 -0
- package/esm/production/cli/index.mjs.map +1 -0
- package/esm/production/contracts.d.mts +592 -0
- package/esm/production/contracts.d.mts.map +1 -0
- package/esm/production/contracts.mjs +95 -0
- package/esm/production/contracts.mjs.map +1 -0
- package/esm/production/errors.d.mts +31 -0
- package/esm/production/errors.d.mts.map +1 -0
- package/esm/production/errors.mjs +142 -0
- package/esm/production/errors.mjs.map +1 -0
- package/esm/production/http/access.mjs +124 -0
- package/esm/production/http/access.mjs.map +1 -0
- package/esm/production/http/auth-routes.mjs +280 -0
- package/esm/production/http/auth-routes.mjs.map +1 -0
- package/esm/production/http/client.mjs +57 -0
- package/esm/production/http/client.mjs.map +1 -0
- package/esm/production/http/constants.mjs +11 -0
- package/esm/production/http/constants.mjs.map +1 -0
- package/esm/production/http/context.mjs +14 -0
- package/esm/production/http/context.mjs.map +1 -0
- package/esm/production/http/cookie.mjs +39 -0
- package/esm/production/http/cookie.mjs.map +1 -0
- package/esm/production/http/headers.mjs +25 -0
- package/esm/production/http/headers.mjs.map +1 -0
- package/esm/production/http/index.mjs +10 -0
- package/esm/production/http/ip.mjs +130 -0
- package/esm/production/http/ip.mjs.map +1 -0
- package/esm/production/http/mount.mjs +300 -0
- package/esm/production/http/mount.mjs.map +1 -0
- package/esm/production/http/state.mjs +54 -0
- package/esm/production/http/state.mjs.map +1 -0
- package/esm/production/index.d.mts +6 -0
- package/esm/production/index.mjs +5 -0
- package/esm/production/insights/cap-report.mjs +67 -0
- package/esm/production/insights/cap-report.mjs.map +1 -0
- package/esm/production/insights/health.mjs +88 -0
- package/esm/production/insights/health.mjs.map +1 -0
- package/esm/production/insights/index.mjs +10 -0
- package/esm/production/insights/insights.mjs +167 -0
- package/esm/production/insights/insights.mjs.map +1 -0
- package/esm/production/insights/instance.mjs +24 -0
- package/esm/production/insights/instance.mjs.map +1 -0
- package/esm/production/insights/jobs.mjs +100 -0
- package/esm/production/insights/jobs.mjs.map +1 -0
- package/esm/production/insights/reporter.mjs +59 -0
- package/esm/production/insights/reporter.mjs.map +1 -0
- package/esm/production/insights/resources.mjs +139 -0
- package/esm/production/insights/resources.mjs.map +1 -0
- package/esm/production/insights/writer.mjs +72 -0
- package/esm/production/insights/writer.mjs.map +1 -0
- package/esm/production/openapi.mjs +52 -0
- package/esm/production/openapi.mjs.map +1 -0
- package/esm/production/options.d.mts +60 -0
- package/esm/production/options.d.mts.map +1 -0
- package/esm/production/options.mjs +170 -0
- package/esm/production/options.mjs.map +1 -0
- package/esm/production/stats/histogram.mjs +67 -0
- package/esm/production/stats/histogram.mjs.map +1 -0
- package/esm/production/stats/merge.mjs +106 -0
- package/esm/production/stats/merge.mjs.map +1 -0
- package/esm/production/store/cascade-store.mjs +322 -0
- package/esm/production/store/cascade-store.mjs.map +1 -0
- package/esm/production/store/index.mjs +5 -0
- package/esm/production/store/mapping.mjs +258 -0
- package/esm/production/store/mapping.mjs.map +1 -0
- package/esm/production/store/memory-store.mjs +291 -0
- package/esm/production/store/memory-store.mjs.map +1 -0
- package/esm/production/store/migrations.d.mts +11 -0
- package/esm/production/store/migrations.d.mts.map +1 -0
- package/esm/production/store/migrations.mjs +29 -0
- package/esm/production/store/migrations.mjs.map +1 -0
- package/esm/production/store/models/account.migration.mjs +34 -0
- package/esm/production/store/models/account.migration.mjs.map +1 -0
- package/esm/production/store/models/account.model.mjs +13 -0
- package/esm/production/store/models/account.model.mjs.map +1 -0
- package/esm/production/store/models/audit.migration.mjs +30 -0
- package/esm/production/store/models/audit.migration.mjs.map +1 -0
- package/esm/production/store/models/audit.model.mjs +13 -0
- package/esm/production/store/models/audit.model.mjs.map +1 -0
- package/esm/production/store/models/base.mjs +27 -0
- package/esm/production/store/models/base.mjs.map +1 -0
- package/esm/production/store/models/index.mjs +17 -0
- package/esm/production/store/models/invite.migration.mjs +26 -0
- package/esm/production/store/models/invite.migration.mjs.map +1 -0
- package/esm/production/store/models/invite.model.mjs +13 -0
- package/esm/production/store/models/invite.model.mjs.map +1 -0
- package/esm/production/store/models/report.migration.mjs +20 -0
- package/esm/production/store/models/report.migration.mjs.map +1 -0
- package/esm/production/store/models/report.model.mjs +13 -0
- package/esm/production/store/models/report.model.mjs.map +1 -0
- package/esm/production/store/models/sample.migration.mjs +25 -0
- package/esm/production/store/models/sample.migration.mjs.map +1 -0
- package/esm/production/store/models/sample.model.mjs +13 -0
- package/esm/production/store/models/sample.model.mjs.map +1 -0
- package/esm/production/store/models/session.migration.mjs +31 -0
- package/esm/production/store/models/session.migration.mjs.map +1 -0
- package/esm/production/store/models/session.model.mjs +13 -0
- package/esm/production/store/models/session.model.mjs.map +1 -0
- package/esm/production/store/models/state.migration.mjs +26 -0
- package/esm/production/store/models/state.migration.mjs.map +1 -0
- package/esm/production/store/models/state.model.mjs +13 -0
- package/esm/production/store/models/state.model.mjs.map +1 -0
- package/esm/query-shape.mjs +14 -1
- package/esm/query-shape.mjs.map +1 -1
- package/esm/server/explain-route.mjs +26 -1
- package/esm/server/explain-route.mjs.map +1 -1
- package/esm/server/index.mjs +9 -4
- package/esm/server/index.mjs.map +1 -1
- package/esm/server/insights-routes.mjs +62 -0
- package/esm/server/insights-routes.mjs.map +1 -0
- package/esm/server/log-routes.mjs +32 -5
- package/esm/server/log-routes.mjs.map +1 -1
- package/esm/server/openapi-routes.mjs +3 -2
- package/esm/server/openapi-routes.mjs.map +1 -1
- package/esm/server/requests-routes.mjs +125 -0
- package/esm/server/requests-routes.mjs.map +1 -1
- package/esm/server/session-routes.mjs +42 -0
- package/esm/server/session-routes.mjs.map +1 -0
- package/esm/server/stream-route.mjs +81 -11
- package/esm/server/stream-route.mjs.map +1 -1
- package/esm/server/ui-assets.mjs +34 -25
- package/esm/server/ui-assets.mjs.map +1 -1
- package/esm/sources/log-source.mjs +14 -1
- package/esm/sources/log-source.mjs.map +1 -1
- package/esm/types.d.mts +202 -1
- package/esm/types.d.mts.map +1 -1
- package/esm/ui-root.mjs +9 -4
- package/esm/ui-root.mjs.map +1 -1
- package/llms-full.txt +159 -21
- package/llms.txt +2 -2
- package/package.json +32 -8
- package/skills/SKILL.md +159 -21
- package/ui/dashboard/assets/app.css +3 -0
- package/ui/dashboard/assets/app.js +50 -0
- package/ui/dashboard/build-info.json +21 -0
- package/ui/dashboard/index.html +15 -0
- package/cjs/ai-source-Dz_3tlZ5.cjs +0 -703
- package/cjs/ai-source-Dz_3tlZ5.cjs.map +0 -1
- package/cjs/server-B11ShQYE.cjs +0 -628
- package/cjs/server-B11ShQYE.cjs.map +0 -1
- package/cjs/src-Xwm3Eel9.cjs.map +0 -1
- package/ui/app.css +0 -376
- package/ui/app.js +0 -1158
- package/ui/index.html +0 -28
|
@@ -0,0 +1,1342 @@
|
|
|
1
|
+
const require_collector = require("./collector-CJbQbzzK.cjs");
|
|
2
|
+
const require_errors = require("./errors-CyZp5yS-.cjs");
|
|
3
|
+
const require_histogram = require("./histogram-BaI-PnCv.cjs");
|
|
4
|
+
let _warlock_js_logger = require("@warlock.js/logger");
|
|
5
|
+
|
|
6
|
+
//#region ../../packages/devtools/src/production/capture/dev-stats.ts
|
|
7
|
+
/**
|
|
8
|
+
* Development: feeds the statistics from the development collector's settled
|
|
9
|
+
* requests (every request, no sampling), so the Queries, Routes and Errors
|
|
10
|
+
* tabs work in `warlock dev` too.
|
|
11
|
+
*/
|
|
12
|
+
function attachDevelopmentStats(collector, parts) {
|
|
13
|
+
const feed = (request) => {
|
|
14
|
+
const failed = request.status !== void 0 && request.status >= 500 || request.error !== void 0;
|
|
15
|
+
const route = request.route ?? null;
|
|
16
|
+
for (const query of request.queries) {
|
|
17
|
+
parts.queries.record({
|
|
18
|
+
shape: query.shape,
|
|
19
|
+
driver: query.driver,
|
|
20
|
+
connection: query.connection,
|
|
21
|
+
durationMs: query.durationMs,
|
|
22
|
+
failed: query.error !== void 0,
|
|
23
|
+
at: query.startedAt,
|
|
24
|
+
route,
|
|
25
|
+
requestId: request.id
|
|
26
|
+
});
|
|
27
|
+
parts.queries.rememberExample(query);
|
|
28
|
+
}
|
|
29
|
+
for (const warning of require_collector.detectNPlusOne(request.queries, parts.nPlusOneThreshold)) parts.queries.recordNPlusOne(warning.shape, warning.count);
|
|
30
|
+
parts.routes.record({
|
|
31
|
+
method: request.method,
|
|
32
|
+
route: request.route ?? "",
|
|
33
|
+
status: request.status ?? null,
|
|
34
|
+
failed,
|
|
35
|
+
durationMs: request.durationMs ?? 0,
|
|
36
|
+
at: request.startedAt,
|
|
37
|
+
requestId: request.id,
|
|
38
|
+
phases: request.phases.map((phase) => ({
|
|
39
|
+
name: phase.name,
|
|
40
|
+
durationMs: phase.durationMs
|
|
41
|
+
}))
|
|
42
|
+
});
|
|
43
|
+
if (failed) parts.errors.record({
|
|
44
|
+
source: "request",
|
|
45
|
+
message: request.error ?? `HTTP ${request.status}`,
|
|
46
|
+
name: null,
|
|
47
|
+
stack: null,
|
|
48
|
+
route,
|
|
49
|
+
status: request.status ?? null,
|
|
50
|
+
requestId: request.id,
|
|
51
|
+
at: request.startedAt
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
return collector.subscribe((event) => {
|
|
55
|
+
if (event.type === "request") {
|
|
56
|
+
const request = collector.getRequest(event.data.id);
|
|
57
|
+
if (request) feed(request);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (event.type !== "log") return;
|
|
61
|
+
const entry = event.data;
|
|
62
|
+
if (entry.level !== "warn" && entry.level !== "error") return;
|
|
63
|
+
parts.logs.record({
|
|
64
|
+
level: entry.level,
|
|
65
|
+
module: entry.module,
|
|
66
|
+
action: entry.action,
|
|
67
|
+
message: entry.message,
|
|
68
|
+
at: entry.at,
|
|
69
|
+
requestId: null
|
|
70
|
+
});
|
|
71
|
+
if (entry.level === "error") parts.errors.record({
|
|
72
|
+
source: "log",
|
|
73
|
+
message: entry.message,
|
|
74
|
+
name: null,
|
|
75
|
+
stack: null,
|
|
76
|
+
route: null,
|
|
77
|
+
status: null,
|
|
78
|
+
requestId: null,
|
|
79
|
+
at: entry.at
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region ../../packages/devtools/src/production/capture/explain.ts
|
|
86
|
+
/** Words that write, lock, call or create something. A read statement holds none of them. */
|
|
87
|
+
const FORBIDDEN_WORDS = /\b(insert|update|delete|merge|truncate|alter|drop|create|grant|revoke|call|copy|vacuum|reindex|lock|into|refresh|execute|prepare|nextval|setval|pg_sleep\w*|pg_advisory\w*|lo_\w+|dblink\w*)\b/i;
|
|
88
|
+
const isIdentifierCharacter = (character) => character !== void 0 && /[A-Za-z0-9_$\u0080-\uffff]/.test(character);
|
|
89
|
+
/** The index after the comment starting at `index` (`--` or a nested block comment), or `-1` when it is not closed. */
|
|
90
|
+
function commentEnd(sql, index) {
|
|
91
|
+
if (sql.startsWith("--", index)) {
|
|
92
|
+
const newline = sql.indexOf("\n", index + 2);
|
|
93
|
+
return newline === -1 ? sql.length : newline + 1;
|
|
94
|
+
}
|
|
95
|
+
let depth = 0;
|
|
96
|
+
let at = index;
|
|
97
|
+
while (at < sql.length) if (sql.startsWith("/*", at)) {
|
|
98
|
+
depth++;
|
|
99
|
+
at += 2;
|
|
100
|
+
} else if (sql.startsWith("*/", at)) {
|
|
101
|
+
depth--;
|
|
102
|
+
at += 2;
|
|
103
|
+
if (depth === 0) return at;
|
|
104
|
+
} else at++;
|
|
105
|
+
return -1;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* `sql` as the server reads it, with every comment turned into a space and
|
|
109
|
+
* every string, quoted identifier and dollar-quoted body into `?`; `null`
|
|
110
|
+
* when one of them is not closed. `backslashEscapes` reads a backslash as an
|
|
111
|
+
* escape in every string (`standard_conforming_strings = off`); escape
|
|
112
|
+
* strings (`E'…'`) always use it.
|
|
113
|
+
*/
|
|
114
|
+
function maskSql(sql, backslashEscapes) {
|
|
115
|
+
let out = "";
|
|
116
|
+
let at = 0;
|
|
117
|
+
while (at < sql.length) {
|
|
118
|
+
const character = sql[at];
|
|
119
|
+
if (sql.startsWith("--", at) || sql.startsWith("/*", at)) {
|
|
120
|
+
const end = commentEnd(sql, at);
|
|
121
|
+
if (end === -1) return null;
|
|
122
|
+
out += " ";
|
|
123
|
+
at = end;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (character === "'" || character === "\"") {
|
|
127
|
+
const escapes = character === "'" && (backslashEscapes || /[eE]/.test(sql[at - 1] ?? "") && !isIdentifierCharacter(sql[at - 2]));
|
|
128
|
+
let closed = false;
|
|
129
|
+
at++;
|
|
130
|
+
while (at < sql.length) {
|
|
131
|
+
const current = sql[at];
|
|
132
|
+
if (escapes && current === "\\") at += 2;
|
|
133
|
+
else if (current === character) {
|
|
134
|
+
at++;
|
|
135
|
+
if (sql[at] !== character) {
|
|
136
|
+
closed = true;
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
at++;
|
|
140
|
+
} else at++;
|
|
141
|
+
}
|
|
142
|
+
if (!closed) return null;
|
|
143
|
+
out += " ? ";
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (character === "$" && !isIdentifierCharacter(sql[at - 1])) {
|
|
147
|
+
const opener = /^\$(?:[A-Za-z_\u0080-\uffff][A-Za-z0-9_\u0080-\uffff]*)?\$/.exec(sql.slice(at))?.[0];
|
|
148
|
+
if (opener !== void 0) {
|
|
149
|
+
const end = sql.indexOf(opener, at + opener.length);
|
|
150
|
+
if (end === -1) return null;
|
|
151
|
+
out += " ? ";
|
|
152
|
+
at = end + opener.length;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
out += character;
|
|
157
|
+
at++;
|
|
158
|
+
}
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
/** `sql` without its leading whitespace and comments, or `null` when a leading comment is not closed. */
|
|
162
|
+
function withoutLeadingNoise(sql) {
|
|
163
|
+
let at = 0;
|
|
164
|
+
while (at < sql.length) if (/\s/.test(sql[at])) at++;
|
|
165
|
+
else if (sql.startsWith("--", at) || sql.startsWith("/*", at)) {
|
|
166
|
+
const end = commentEnd(sql, at);
|
|
167
|
+
if (end === -1) return null;
|
|
168
|
+
at = end;
|
|
169
|
+
} else break;
|
|
170
|
+
return sql.slice(at);
|
|
171
|
+
}
|
|
172
|
+
/** Whether the masked statement is one read: it starts with SELECT or WITH, ends at most at one `;`, writes nothing. */
|
|
173
|
+
function isOneRead(masked) {
|
|
174
|
+
if (masked === null) return false;
|
|
175
|
+
const bare = masked.trim().replace(/;\s*$/, "");
|
|
176
|
+
return /^(select|with)\b/i.test(bare) && !bare.includes(";") && !FORBIDDEN_WORDS.test(bare);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The statement to explain when `sql` is one plain read (`SELECT` or `WITH`,
|
|
180
|
+
* one statement, nothing that writes, locks or calls a function with side
|
|
181
|
+
* effects), without its leading comments; `null` otherwise. Strings, quoted
|
|
182
|
+
* identifiers, dollar-quoted bodies and nested comments are read the way the
|
|
183
|
+
* server reads them, under both settings of `standard_conforming_strings`, so
|
|
184
|
+
* a `;` or a keyword cannot hide inside what only looks like a string.
|
|
185
|
+
*/
|
|
186
|
+
function explainableSql(sql) {
|
|
187
|
+
if (sql === void 0) return null;
|
|
188
|
+
const statement = withoutLeadingNoise(sql)?.trimEnd();
|
|
189
|
+
if (statement === void 0 || !isOneRead(maskSql(statement, false)) || !isOneRead(maskSql(statement, true))) return null;
|
|
190
|
+
return statement.replace(/;\s*$/, "");
|
|
191
|
+
}
|
|
192
|
+
/** Keys of a recorded MongoDB command that an inner `explain` command does not accept. */
|
|
193
|
+
const MONGO_SESSION_KEYS = /* @__PURE__ */ new Set([
|
|
194
|
+
"lsid",
|
|
195
|
+
"txnNumber",
|
|
196
|
+
"autocommit",
|
|
197
|
+
"startTransaction",
|
|
198
|
+
"readConcern",
|
|
199
|
+
"writeConcern"
|
|
200
|
+
]);
|
|
201
|
+
const MONGO_COMMANDS = /* @__PURE__ */ new Set([
|
|
202
|
+
"find",
|
|
203
|
+
"aggregate",
|
|
204
|
+
"count"
|
|
205
|
+
]);
|
|
206
|
+
/** Aggregation stages that write their result to a collection. */
|
|
207
|
+
const MONGO_WRITE_STAGES = /* @__PURE__ */ new Set(["$out", "$merge"]);
|
|
208
|
+
/** Whether a recorded command or pipeline has a stage that writes. */
|
|
209
|
+
function writesInPipeline(recorded) {
|
|
210
|
+
const pipeline = Array.isArray(recorded) ? recorded : recorded !== null && typeof recorded === "object" ? recorded.pipeline : void 0;
|
|
211
|
+
return Array.isArray(pipeline) && pipeline.some((stage) => stage !== null && typeof stage === "object" && Object.keys(stage).some((key) => MONGO_WRITE_STAGES.has(key)));
|
|
212
|
+
}
|
|
213
|
+
function mongoExplainCommand(query, executing) {
|
|
214
|
+
const name = query.command;
|
|
215
|
+
if (name === void 0 || !MONGO_COMMANDS.has(name) || query.collection === void 0) return null;
|
|
216
|
+
if (name === "aggregate" && writesInPipeline(query.pipeline)) return null;
|
|
217
|
+
let inner;
|
|
218
|
+
const recorded = query.pipeline;
|
|
219
|
+
if (recorded !== null && typeof recorded === "object" && !Array.isArray(recorded)) {
|
|
220
|
+
inner = {};
|
|
221
|
+
for (const [key, value] of Object.entries(recorded)) {
|
|
222
|
+
if (key.startsWith("$") || MONGO_SESSION_KEYS.has(key)) continue;
|
|
223
|
+
inner[key] = value;
|
|
224
|
+
}
|
|
225
|
+
inner[name] = query.collection;
|
|
226
|
+
} else if (name === "aggregate") inner = {
|
|
227
|
+
aggregate: query.collection,
|
|
228
|
+
pipeline: Array.isArray(recorded) ? recorded : [],
|
|
229
|
+
cursor: {}
|
|
230
|
+
};
|
|
231
|
+
else inner = { [name]: query.collection };
|
|
232
|
+
return {
|
|
233
|
+
explain: inner,
|
|
234
|
+
verbosity: executing ? "executionStats" : "queryPlanner"
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
function statementFor(query, executing) {
|
|
238
|
+
if (query.driver === "postgres") {
|
|
239
|
+
const sql = explainableSql(query.sql);
|
|
240
|
+
if (sql === null) return null;
|
|
241
|
+
return {
|
|
242
|
+
type: "sql",
|
|
243
|
+
sql: `${executing ? "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)" : "EXPLAIN (FORMAT JSON)"} ${sql}`
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
const command = mongoExplainCommand(query, executing);
|
|
247
|
+
return command === null ? null : {
|
|
248
|
+
type: "mongo",
|
|
249
|
+
command
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Runs `sql` in a read-only transaction on its own pooled client and rolls it
|
|
254
|
+
* back, so nothing the statement reaches (a function with side effects under
|
|
255
|
+
* `ANALYZE`, a second statement) can write.
|
|
256
|
+
*/
|
|
257
|
+
async function explainReadOnly(driver, sql, bindings) {
|
|
258
|
+
const begin = driver.beginTransaction;
|
|
259
|
+
if (typeof begin !== "function") throw new Error("The connection cannot open a read-only transaction, so EXPLAIN was not run.");
|
|
260
|
+
const transaction = await begin.call(driver, { readOnly: true });
|
|
261
|
+
try {
|
|
262
|
+
const { rows } = await transaction.context.query(sql, bindings ?? []);
|
|
263
|
+
return rows;
|
|
264
|
+
} finally {
|
|
265
|
+
await transaction.rollback();
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/** Runs the statement on the query's own connection through cascade's data source registry. */
|
|
269
|
+
const runOnDataSource = async (query, statement) => {
|
|
270
|
+
const { dataSourceRegistry } = await import("@warlock.js/cascade");
|
|
271
|
+
const dataSource = dataSourceRegistry.get(query.connection);
|
|
272
|
+
if (statement.type === "sql") return explainReadOnly(dataSource.driver, statement.sql, query.bindings);
|
|
273
|
+
return dataSource.driver.getDatabase().command(statement.command);
|
|
274
|
+
};
|
|
275
|
+
/** Keys of a MongoDB plan whose values come from the query (filters, bounds, the echoed command). */
|
|
276
|
+
const MONGO_VALUE_KEYS = /* @__PURE__ */ new Set([
|
|
277
|
+
"parsedQuery",
|
|
278
|
+
"filter",
|
|
279
|
+
"indexBounds",
|
|
280
|
+
"command",
|
|
281
|
+
"originalCommand",
|
|
282
|
+
"query",
|
|
283
|
+
"pipeline"
|
|
284
|
+
]);
|
|
285
|
+
/** SQL literals inside a PostgreSQL plan's condition text: `'text'` (with `''`), `E'…'` and numbers. */
|
|
286
|
+
const SQL_LITERAL = /(?:(?<!\w)[Ee])?'(?:''|\\.|[^'])*'|(?<![\w.$])-?\d+(?:\.\d+)?(?![\w.])/g;
|
|
287
|
+
function maskMongoValues(value) {
|
|
288
|
+
if (Array.isArray(value)) return value.map(maskMongoValues);
|
|
289
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, maskMongoValues(inner)]));
|
|
290
|
+
return value === null || value === void 0 ? value : "?";
|
|
291
|
+
}
|
|
292
|
+
function redactMongoPlan(value) {
|
|
293
|
+
if (Array.isArray(value)) return value.map(redactMongoPlan);
|
|
294
|
+
if (value === null || typeof value !== "object") return value;
|
|
295
|
+
return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, MONGO_VALUE_KEYS.has(key) ? maskMongoValues(inner) : redactMongoPlan(inner)]));
|
|
296
|
+
}
|
|
297
|
+
function redactSqlPlan(value) {
|
|
298
|
+
if (typeof value === "string") return value.replace(SQL_LITERAL, "?");
|
|
299
|
+
if (Array.isArray(value)) return value.map(redactSqlPlan);
|
|
300
|
+
if (value === null || typeof value !== "object") return value;
|
|
301
|
+
return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, redactSqlPlan(inner)]));
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* A plan without the query's values. Plans repeat them: MongoDB echoes the
|
|
305
|
+
* filter (`parsedQuery`, `indexBounds`, the command), PostgreSQL writes them
|
|
306
|
+
* into conditions (`Filter: (email = 'a@b.c'::text)`). Values become `?`;
|
|
307
|
+
* the plan's shape, costs, row counts and index choices stay.
|
|
308
|
+
*/
|
|
309
|
+
function redactExplainPlan(plan, driver) {
|
|
310
|
+
return driver === "mongodb" ? redactMongoPlan(plan) : redactSqlPlan(plan);
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* EXPLAIN by shape id from the examples `queries` kept, used by the production
|
|
314
|
+
* capture and by development (`POST /api/queries/:shapeId/explain`). Plain
|
|
315
|
+
* `EXPLAIN (FORMAT JSON)` / MongoDB `queryPlanner` unless `executing`; never
|
|
316
|
+
* an executing plan for anything but a PostgreSQL `SELECT`/`WITH` or a
|
|
317
|
+
* MongoDB `find`/`aggregate`/`count` (never an aggregate with `$out` or
|
|
318
|
+
* `$merge`). `run` executes the statement on the query's own connection
|
|
319
|
+
* (injected for specs; default: cascade's `dataSourceRegistry`, PostgreSQL
|
|
320
|
+
* inside a read-only transaction that is always rolled back).
|
|
321
|
+
*/
|
|
322
|
+
function createShapeExplainer(input) {
|
|
323
|
+
const run = input.run ?? runOnDataSource;
|
|
324
|
+
return async (shapeId) => {
|
|
325
|
+
const example = input.queries.example(shapeId);
|
|
326
|
+
if (!example) throw new require_errors.DevtoolsApiError("explain.elsewhere", { instance: input.instance });
|
|
327
|
+
const statement = statementFor(example, input.executing);
|
|
328
|
+
if (!statement) throw new require_errors.DevtoolsApiError("explain.unsupported", { instance: input.instance });
|
|
329
|
+
try {
|
|
330
|
+
const plan = await run(example, statement);
|
|
331
|
+
return {
|
|
332
|
+
shapeId,
|
|
333
|
+
driver: example.driver,
|
|
334
|
+
executing: input.executing,
|
|
335
|
+
plan: input.redact === true ? redactExplainPlan(plan, example.driver) : plan,
|
|
336
|
+
instance: input.instance
|
|
337
|
+
};
|
|
338
|
+
} catch (cause) {
|
|
339
|
+
const ref = require_errors.createErrorRef();
|
|
340
|
+
_warlock_js_logger.log.error("devtools", "explain", `EXPLAIN failed for query shape ${shapeId} (ref ${ref}): ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
341
|
+
throw new require_errors.DevtoolsApiError("explain.failed", {
|
|
342
|
+
ref,
|
|
343
|
+
cause,
|
|
344
|
+
instance: input.instance
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
//#endregion
|
|
351
|
+
//#region ../../packages/devtools/src/production/capture/stats-stores.ts
|
|
352
|
+
const SHAPE_MAX$1 = 2e3;
|
|
353
|
+
const MESSAGE_MAX = 500;
|
|
354
|
+
const STACK_MAX = 4e3;
|
|
355
|
+
const LOG_MESSAGE_MAX$3 = 1e3;
|
|
356
|
+
const PHASES_PER_ROUTE = 30;
|
|
357
|
+
const MONGO_EXPLAINABLE = /* @__PURE__ */ new Set([
|
|
358
|
+
"find",
|
|
359
|
+
"aggregate",
|
|
360
|
+
"count"
|
|
361
|
+
]);
|
|
362
|
+
const SQL_START = /^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*(select|with)\b/i;
|
|
363
|
+
/** Whether a normalized query shape can be explained (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */
|
|
364
|
+
function isExplainableShape(driver, shape) {
|
|
365
|
+
if (driver === "postgres") return SQL_START.test(shape);
|
|
366
|
+
const space = shape.indexOf(" ");
|
|
367
|
+
const head = space === -1 ? shape : shape.slice(0, space);
|
|
368
|
+
const command = head.slice(head.lastIndexOf(".") + 1);
|
|
369
|
+
return MONGO_EXPLAINABLE.has(command);
|
|
370
|
+
}
|
|
371
|
+
const shapeIds = /* @__PURE__ */ new Map();
|
|
372
|
+
const SHAPE_ID_CACHE = 2e3;
|
|
373
|
+
/** `shortId` of a query shape, remembered: the same few hundred shapes arrive over and over. */
|
|
374
|
+
function shapeIdOf(shape) {
|
|
375
|
+
let id = shapeIds.get(shape);
|
|
376
|
+
if (id === void 0) {
|
|
377
|
+
if (shapeIds.size >= SHAPE_ID_CACHE) shapeIds.clear();
|
|
378
|
+
id = require_histogram.shortId(shape);
|
|
379
|
+
shapeIds.set(shape, id);
|
|
380
|
+
}
|
|
381
|
+
return id;
|
|
382
|
+
}
|
|
383
|
+
function truncate(value, maximum) {
|
|
384
|
+
return value.length > maximum ? value.slice(0, maximum) : value;
|
|
385
|
+
}
|
|
386
|
+
function copyHistogram(histogram) {
|
|
387
|
+
return {
|
|
388
|
+
...histogram,
|
|
389
|
+
counts: [...histogram.counts]
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
/** Bounded per-shape query statistics. */
|
|
393
|
+
function createQueryStats(limits) {
|
|
394
|
+
const entries = /* @__PURE__ */ new Map();
|
|
395
|
+
let evictedCount = 0;
|
|
396
|
+
const touch = (shape, driver, connection, at) => {
|
|
397
|
+
const id = shapeIdOf(shape);
|
|
398
|
+
let entry = entries.get(id);
|
|
399
|
+
if (entry) {
|
|
400
|
+
entries.delete(id);
|
|
401
|
+
entry.stats.lastSeen = Math.max(entry.stats.lastSeen, at);
|
|
402
|
+
} else entry = {
|
|
403
|
+
example: void 0,
|
|
404
|
+
stats: {
|
|
405
|
+
id,
|
|
406
|
+
shape: truncate(shape, SHAPE_MAX$1),
|
|
407
|
+
driver,
|
|
408
|
+
connection,
|
|
409
|
+
count: 0,
|
|
410
|
+
errors: 0,
|
|
411
|
+
histogram: require_histogram.createHistogram(),
|
|
412
|
+
nPlusOne: {
|
|
413
|
+
requests: 0,
|
|
414
|
+
maxPerRequest: 0
|
|
415
|
+
},
|
|
416
|
+
slowest: null,
|
|
417
|
+
firstSeen: at,
|
|
418
|
+
lastSeen: at,
|
|
419
|
+
explainable: isExplainableShape(driver, shape)
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
entries.set(id, entry);
|
|
423
|
+
while (entries.size > limits.maxShapes) {
|
|
424
|
+
const oldest = entries.keys().next().value;
|
|
425
|
+
entries.delete(oldest);
|
|
426
|
+
evictedCount++;
|
|
427
|
+
}
|
|
428
|
+
return entry;
|
|
429
|
+
};
|
|
430
|
+
return {
|
|
431
|
+
record(query) {
|
|
432
|
+
const entry = touch(query.shape, query.driver, query.connection, query.at);
|
|
433
|
+
entry.stats.count++;
|
|
434
|
+
if (query.failed) entry.stats.errors++;
|
|
435
|
+
require_histogram.recordDuration(entry.stats.histogram, query.durationMs);
|
|
436
|
+
const slowest = entry.stats.slowest;
|
|
437
|
+
if (!slowest || query.durationMs > slowest.durationMs) entry.stats.slowest = {
|
|
438
|
+
durationMs: query.durationMs,
|
|
439
|
+
at: query.at,
|
|
440
|
+
route: query.route,
|
|
441
|
+
requestId: query.requestId,
|
|
442
|
+
instance: limits.instance
|
|
443
|
+
};
|
|
444
|
+
},
|
|
445
|
+
recordNPlusOne(shape, count) {
|
|
446
|
+
const known = entries.get(shapeIdOf(shape))?.stats;
|
|
447
|
+
const entry = touch(shape, known?.driver ?? "postgres", known?.connection ?? "", Date.now());
|
|
448
|
+
entry.stats.nPlusOne.requests++;
|
|
449
|
+
if (count > entry.stats.nPlusOne.maxPerRequest) entry.stats.nPlusOne.maxPerRequest = count;
|
|
450
|
+
},
|
|
451
|
+
rememberExample(query) {
|
|
452
|
+
const entry = touch(query.shape, query.driver, query.connection, query.startedAt);
|
|
453
|
+
if (!entry.example || query.durationMs > entry.example.durationMs) entry.example = {
|
|
454
|
+
...query,
|
|
455
|
+
...query.bindings === void 0 ? {} : { bindings: [...query.bindings] }
|
|
456
|
+
};
|
|
457
|
+
const slowest = entry.stats.slowest;
|
|
458
|
+
if (!slowest || query.durationMs > slowest.durationMs) entry.stats.slowest = {
|
|
459
|
+
durationMs: query.durationMs,
|
|
460
|
+
at: query.startedAt,
|
|
461
|
+
route: null,
|
|
462
|
+
requestId: null,
|
|
463
|
+
instance: limits.instance
|
|
464
|
+
};
|
|
465
|
+
},
|
|
466
|
+
example(shapeId) {
|
|
467
|
+
return entries.get(shapeId)?.example;
|
|
468
|
+
},
|
|
469
|
+
snapshot(limit) {
|
|
470
|
+
return [...entries.values()].map(({ stats }) => stats).sort((a, b) => b.histogram.sumMs - a.histogram.sumMs).slice(0, Math.max(0, limit)).map((stats) => ({
|
|
471
|
+
...stats,
|
|
472
|
+
histogram: copyHistogram(stats.histogram),
|
|
473
|
+
nPlusOne: { ...stats.nPlusOne },
|
|
474
|
+
slowest: stats.slowest ? { ...stats.slowest } : null
|
|
475
|
+
}));
|
|
476
|
+
},
|
|
477
|
+
evicted: () => evictedCount,
|
|
478
|
+
clear() {
|
|
479
|
+
entries.clear();
|
|
480
|
+
}
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
/** Bounded per-route statistics. */
|
|
484
|
+
function createRouteStats(limits) {
|
|
485
|
+
const entries = /* @__PURE__ */ new Map();
|
|
486
|
+
let evictedCount = 0;
|
|
487
|
+
return {
|
|
488
|
+
record(request) {
|
|
489
|
+
const route = request.route === "" ? "(unmatched)" : request.route;
|
|
490
|
+
const key = `${request.method} ${route}`;
|
|
491
|
+
let entry = entries.get(key);
|
|
492
|
+
if (entry) entries.delete(key);
|
|
493
|
+
else entry = {
|
|
494
|
+
phases: /* @__PURE__ */ new Map(),
|
|
495
|
+
stats: {
|
|
496
|
+
key,
|
|
497
|
+
method: request.method,
|
|
498
|
+
route,
|
|
499
|
+
count: 0,
|
|
500
|
+
errors: 0,
|
|
501
|
+
histogram: require_histogram.createHistogram(),
|
|
502
|
+
phases: [],
|
|
503
|
+
slowest: null
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
entries.set(key, entry);
|
|
507
|
+
while (entries.size > limits.maxRoutes) {
|
|
508
|
+
entries.delete(entries.keys().next().value);
|
|
509
|
+
evictedCount++;
|
|
510
|
+
}
|
|
511
|
+
entry.stats.count++;
|
|
512
|
+
if (request.failed) entry.stats.errors++;
|
|
513
|
+
require_histogram.recordDuration(entry.stats.histogram, request.durationMs);
|
|
514
|
+
const slowest = entry.stats.slowest;
|
|
515
|
+
if (!slowest || request.durationMs > slowest.durationMs) entry.stats.slowest = {
|
|
516
|
+
durationMs: request.durationMs,
|
|
517
|
+
at: request.at,
|
|
518
|
+
requestId: request.requestId,
|
|
519
|
+
instance: limits.instance
|
|
520
|
+
};
|
|
521
|
+
for (const phase of request.phases) {
|
|
522
|
+
let stats = entry.phases.get(phase.name);
|
|
523
|
+
if (!stats) {
|
|
524
|
+
if (entry.phases.size >= PHASES_PER_ROUTE) {
|
|
525
|
+
let smallest;
|
|
526
|
+
for (const [name, candidate] of entry.phases) if (smallest === void 0 || candidate.sumMs < (entry.phases.get(smallest)?.sumMs ?? 0)) smallest = name;
|
|
527
|
+
if (smallest !== void 0) entry.phases.delete(smallest);
|
|
528
|
+
}
|
|
529
|
+
stats = {
|
|
530
|
+
name: phase.name,
|
|
531
|
+
count: 0,
|
|
532
|
+
sumMs: 0,
|
|
533
|
+
maxMs: 0
|
|
534
|
+
};
|
|
535
|
+
entry.phases.set(phase.name, stats);
|
|
536
|
+
}
|
|
537
|
+
const duration = Number.isFinite(phase.durationMs) ? Math.max(0, phase.durationMs) : 0;
|
|
538
|
+
stats.count++;
|
|
539
|
+
stats.sumMs += duration;
|
|
540
|
+
if (duration > stats.maxMs) stats.maxMs = duration;
|
|
541
|
+
}
|
|
542
|
+
},
|
|
543
|
+
snapshot(limit) {
|
|
544
|
+
return [...entries.values()].sort((a, b) => b.stats.histogram.sumMs - a.stats.histogram.sumMs).slice(0, Math.max(0, limit)).map(({ stats, phases }) => ({
|
|
545
|
+
...stats,
|
|
546
|
+
histogram: copyHistogram(stats.histogram),
|
|
547
|
+
slowest: stats.slowest ? { ...stats.slowest } : null,
|
|
548
|
+
phases: [...phases.values()].sort((a, b) => b.sumMs - a.sumMs).slice(0, PHASES_PER_ROUTE).map((phase) => ({ ...phase }))
|
|
549
|
+
}));
|
|
550
|
+
},
|
|
551
|
+
evicted: () => evictedCount,
|
|
552
|
+
clear() {
|
|
553
|
+
entries.clear();
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
const QUOTED$1 = /'(?:''|[^'])*'|"(?:\\.|[^"\\])*"/g;
|
|
558
|
+
const UUID = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
|
|
559
|
+
const EMAIL$1 = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
|
|
560
|
+
const HEX_ID = /\b0x[0-9a-f]+\b|\b(?=[0-9a-f]*\d)[0-9a-f]{8,}\b/gi;
|
|
561
|
+
/** A random id of letters and digits (request ids, tokens): 16+ characters with both. */
|
|
562
|
+
const TOKEN_ID = /\b(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{16,}\b/g;
|
|
563
|
+
const NUMBER = /\d+(?:\.\d+)?/g;
|
|
564
|
+
/**
|
|
565
|
+
* Replaces the parts of an error message that change between occurrences
|
|
566
|
+
* (quoted strings, emails, UUIDs, hex ids, random ids such as request ids,
|
|
567
|
+
* numbers) so equal errors group.
|
|
568
|
+
*/
|
|
569
|
+
function normalizeErrorMessage(message) {
|
|
570
|
+
return message.replace(QUOTED$1, "<str>").replace(UUID, "<uuid>").replace(EMAIL$1, "<email>").replace(HEX_ID, "<hex>").replace(TOKEN_ID, "<id>").replace(NUMBER, "<n>");
|
|
571
|
+
}
|
|
572
|
+
/** Bounded error groups. */
|
|
573
|
+
function createErrorGroups(limits) {
|
|
574
|
+
const groups = /* @__PURE__ */ new Map();
|
|
575
|
+
let evictedCount = 0;
|
|
576
|
+
return {
|
|
577
|
+
record(input) {
|
|
578
|
+
const id = require_histogram.shortId(`${input.source}\n${input.name ?? ""}\n${normalizeErrorMessage(input.message)}\n${input.route ?? ""}`);
|
|
579
|
+
const known = groups.get(id);
|
|
580
|
+
const message = truncate(input.message, MESSAGE_MAX);
|
|
581
|
+
const stack = input.stack === null ? null : truncate(input.stack, STACK_MAX);
|
|
582
|
+
if (known) {
|
|
583
|
+
groups.delete(id);
|
|
584
|
+
known.count++;
|
|
585
|
+
known.message = message;
|
|
586
|
+
known.lastSeen = Math.max(known.lastSeen, input.at);
|
|
587
|
+
known.lastRequestId = input.requestId;
|
|
588
|
+
known.status = input.status ?? known.status;
|
|
589
|
+
if (stack !== null) known.stack = stack;
|
|
590
|
+
groups.set(id, known);
|
|
591
|
+
} else groups.set(id, {
|
|
592
|
+
id,
|
|
593
|
+
message,
|
|
594
|
+
name: input.name,
|
|
595
|
+
source: input.source,
|
|
596
|
+
route: input.route,
|
|
597
|
+
status: input.status,
|
|
598
|
+
count: 1,
|
|
599
|
+
firstSeen: input.at,
|
|
600
|
+
lastSeen: input.at,
|
|
601
|
+
lastRequestId: input.requestId,
|
|
602
|
+
stack
|
|
603
|
+
});
|
|
604
|
+
while (groups.size > limits.maxGroups) {
|
|
605
|
+
groups.delete(groups.keys().next().value);
|
|
606
|
+
evictedCount++;
|
|
607
|
+
}
|
|
608
|
+
},
|
|
609
|
+
snapshot(limit) {
|
|
610
|
+
return [...groups.values()].sort((a, b) => b.lastSeen - a.lastSeen).slice(0, Math.max(0, limit)).map((group) => ({ ...group }));
|
|
611
|
+
},
|
|
612
|
+
evicted: () => evictedCount,
|
|
613
|
+
clear() {
|
|
614
|
+
groups.clear();
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
/** Recent warn/error log entries, bounded. */
|
|
619
|
+
function createRecentLogs(limits) {
|
|
620
|
+
const entries = [];
|
|
621
|
+
return {
|
|
622
|
+
record(entry) {
|
|
623
|
+
entries.push({
|
|
624
|
+
...entry,
|
|
625
|
+
message: truncate(entry.message, LOG_MESSAGE_MAX$3)
|
|
626
|
+
});
|
|
627
|
+
while (entries.length > limits.maxEntries) entries.shift();
|
|
628
|
+
},
|
|
629
|
+
snapshot(limit, filter = {}) {
|
|
630
|
+
const module = filter.module?.toLowerCase();
|
|
631
|
+
const result = [];
|
|
632
|
+
for (let index = entries.length - 1; index >= 0 && result.length < limit; index--) {
|
|
633
|
+
const entry = entries[index];
|
|
634
|
+
if (filter.level && entry.level !== filter.level) continue;
|
|
635
|
+
if (module && !entry.module.toLowerCase().includes(module)) continue;
|
|
636
|
+
result.push({ ...entry });
|
|
637
|
+
}
|
|
638
|
+
return result;
|
|
639
|
+
},
|
|
640
|
+
clear() {
|
|
641
|
+
entries.length = 0;
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
//#endregion
|
|
647
|
+
//#region ../../packages/devtools/src/production/capture/redact.ts
|
|
648
|
+
const SHAPE_MAX = 2e3;
|
|
649
|
+
const ERROR_MAX = 500;
|
|
650
|
+
const QUERY_ERROR_MAX = 300;
|
|
651
|
+
const LOG_MESSAGE_MAX$2 = 1e3;
|
|
652
|
+
const QUOTED = /'(?:''|[^'])*'|"(?:\\.|[^"\\])*"/g;
|
|
653
|
+
const BRACES = /\{[^{}]*\}/g;
|
|
654
|
+
const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
|
|
655
|
+
/**
|
|
656
|
+
* Error text without the values a driver or a handler put in it (a duplicate
|
|
657
|
+
* key message carries the key): quoted strings, emails and `{ … }` documents
|
|
658
|
+
* become `?`, then the text is cut to `max` characters.
|
|
659
|
+
*/
|
|
660
|
+
function scrubErrorText(text, max) {
|
|
661
|
+
return truncate(text.replace(QUOTED, "?").replace(EMAIL, "?").replace(BRACES, "{?}"), max);
|
|
662
|
+
}
|
|
663
|
+
/** A database error message without the values the driver quoted in it. */
|
|
664
|
+
function scrubQueryError(message) {
|
|
665
|
+
return scrubErrorText(message, QUERY_ERROR_MAX);
|
|
666
|
+
}
|
|
667
|
+
function redactQuery(query) {
|
|
668
|
+
const shape = truncate(query.shape || require_collector.queryShape(query), SHAPE_MAX);
|
|
669
|
+
const sample = {
|
|
670
|
+
id: query.id,
|
|
671
|
+
connection: query.connection,
|
|
672
|
+
driver: query.driver,
|
|
673
|
+
sql: shape,
|
|
674
|
+
shape,
|
|
675
|
+
shapeId: shapeIdOf(query.shape || shape),
|
|
676
|
+
startedAt: query.startedAt,
|
|
677
|
+
durationMs: query.durationMs
|
|
678
|
+
};
|
|
679
|
+
if (query.collection !== void 0) sample.collection = query.collection;
|
|
680
|
+
if (query.command !== void 0) sample.command = query.command;
|
|
681
|
+
if (query.rowCount !== void 0) sample.rowCount = query.rowCount;
|
|
682
|
+
if (query.error !== void 0) sample.error = scrubQueryError(query.error);
|
|
683
|
+
return sample;
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* Turns a sampled request into a stored sample with every value removed: SQL
|
|
687
|
+
* replaced by its shape, no bindings, no Mongo pipeline, no log context, no
|
|
688
|
+
* phase attributes, cache operations reduced to counts, no caller paths.
|
|
689
|
+
* Headers, bodies, query strings and parameters are not part of a request
|
|
690
|
+
* record and never appear.
|
|
691
|
+
*/
|
|
692
|
+
function toStoredSample(request, instance, droppedQueries) {
|
|
693
|
+
const path = request.path.split("?")[0] ?? request.path;
|
|
694
|
+
const summary = {
|
|
695
|
+
id: request.id,
|
|
696
|
+
method: request.method,
|
|
697
|
+
path,
|
|
698
|
+
startedAt: request.startedAt,
|
|
699
|
+
queryCount: request.queries.length + droppedQueries,
|
|
700
|
+
warningCount: request.warnings.length,
|
|
701
|
+
instance
|
|
702
|
+
};
|
|
703
|
+
if (request.route !== void 0) summary.route = request.route;
|
|
704
|
+
if (request.status !== void 0) summary.status = request.status;
|
|
705
|
+
if (request.durationMs !== void 0) summary.durationMs = request.durationMs;
|
|
706
|
+
let hits = 0;
|
|
707
|
+
let misses = 0;
|
|
708
|
+
let writes = 0;
|
|
709
|
+
for (const operation of request.cache) if (operation.type === "hit") hits++;
|
|
710
|
+
else if (operation.type === "miss") misses++;
|
|
711
|
+
else if (operation.type === "set") writes++;
|
|
712
|
+
const detail = {
|
|
713
|
+
...summary,
|
|
714
|
+
phases: request.phases.map((phase) => ({
|
|
715
|
+
name: phase.name,
|
|
716
|
+
startedAt: phase.startedAt,
|
|
717
|
+
durationMs: phase.durationMs
|
|
718
|
+
})),
|
|
719
|
+
queries: request.queries.map(redactQuery),
|
|
720
|
+
cache: {
|
|
721
|
+
hits,
|
|
722
|
+
misses,
|
|
723
|
+
writes
|
|
724
|
+
},
|
|
725
|
+
logs: request.logs.map((entry) => ({
|
|
726
|
+
level: entry.level,
|
|
727
|
+
module: entry.module,
|
|
728
|
+
action: entry.action,
|
|
729
|
+
message: truncate(entry.message, LOG_MESSAGE_MAX$2),
|
|
730
|
+
at: entry.at
|
|
731
|
+
})),
|
|
732
|
+
warnings: request.warnings.map((warning) => ({
|
|
733
|
+
type: warning.type,
|
|
734
|
+
message: warning.message,
|
|
735
|
+
shape: truncate(warning.shape, SHAPE_MAX),
|
|
736
|
+
count: warning.count
|
|
737
|
+
})),
|
|
738
|
+
droppedQueries
|
|
739
|
+
};
|
|
740
|
+
if (request.error !== void 0) detail.error = scrubErrorText(request.error, ERROR_MAX);
|
|
741
|
+
return {
|
|
742
|
+
id: request.id,
|
|
743
|
+
instance,
|
|
744
|
+
startedAt: request.startedAt,
|
|
745
|
+
summary,
|
|
746
|
+
detail
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
//#endregion
|
|
751
|
+
//#region ../../packages/devtools/src/production/capture/filter.ts
|
|
752
|
+
/** Whether a stored sample's row passes a request filter (the same rules as the store). */
|
|
753
|
+
function sampleMatchesFilter(summary, filter) {
|
|
754
|
+
if (filter.status !== void 0 && !statusMatches(filter.status, summary.status)) return false;
|
|
755
|
+
if (filter.method !== void 0 && summary.method.toUpperCase() !== filter.method.toUpperCase()) return false;
|
|
756
|
+
if (filter.route !== void 0) {
|
|
757
|
+
if (!`${summary.route ?? ""} ${summary.path}`.toLowerCase().includes(filter.route.toLowerCase())) return false;
|
|
758
|
+
}
|
|
759
|
+
if (filter.q !== void 0 && !summary.path.toLowerCase().includes(filter.q.toLowerCase())) return false;
|
|
760
|
+
if (filter.since !== void 0 && summary.startedAt < filter.since) return false;
|
|
761
|
+
if (filter.until !== void 0 && summary.startedAt > filter.until) return false;
|
|
762
|
+
if (filter.instance !== void 0 && summary.instance !== filter.instance) return false;
|
|
763
|
+
return true;
|
|
764
|
+
}
|
|
765
|
+
function statusMatches(filter, status) {
|
|
766
|
+
if (status === void 0) return false;
|
|
767
|
+
const range = /^([1-5])xx$/i.exec(filter);
|
|
768
|
+
if (range) return Math.floor(status / 100) === Number(range[1]);
|
|
769
|
+
return status === Number(filter);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
//#endregion
|
|
773
|
+
//#region ../../packages/devtools/src/production/capture/engine.ts
|
|
774
|
+
/** Per sampled request limits (see "Bounded memory"). */
|
|
775
|
+
const MAX_LOGS_PER_REQUEST = 50;
|
|
776
|
+
const MAX_PHASES_PER_REQUEST = 100;
|
|
777
|
+
const MAX_CACHE_PER_REQUEST = 1e3;
|
|
778
|
+
const MAX_ACTIVE = 2e3;
|
|
779
|
+
const MAX_PENDING = 500;
|
|
780
|
+
const FLUSH_AT = 50;
|
|
781
|
+
const FLUSH_EVERY_MS = 5e3;
|
|
782
|
+
const WARN_EVERY_MS = 6e4;
|
|
783
|
+
const LOG_MESSAGE_MAX$1 = 1e3;
|
|
784
|
+
function stripQuery(path) {
|
|
785
|
+
const index = path.indexOf("?");
|
|
786
|
+
return index === -1 ? path : path.slice(0, index);
|
|
787
|
+
}
|
|
788
|
+
/** The lengths the error groups keep (see `createErrorGroups`). */
|
|
789
|
+
const REQUEST_ERROR_MAX = 500;
|
|
790
|
+
const REQUEST_STACK_MAX = 4e3;
|
|
791
|
+
function errorMessage(error) {
|
|
792
|
+
return error instanceof Error ? error.message : String(error);
|
|
793
|
+
}
|
|
794
|
+
/** A request's error message as the monitor keeps it: without the values in it (see `scrubErrorText`). */
|
|
795
|
+
function requestErrorMessage(error) {
|
|
796
|
+
return scrubErrorText(errorMessage(error), REQUEST_ERROR_MAX);
|
|
797
|
+
}
|
|
798
|
+
function touchesMonitorTables(event) {
|
|
799
|
+
return event.sql !== void 0 && event.sql.includes("devtools_") || event.collection !== void 0 && event.collection.startsWith("devtools_");
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* The capture of one process without any registration: sampling, the ring,
|
|
803
|
+
* the statistics, the sample writer and the request source. The hooks are
|
|
804
|
+
* plain functions so a spec (or the benchmark) can drive them directly.
|
|
805
|
+
*/
|
|
806
|
+
function createCaptureEngine(deps) {
|
|
807
|
+
const { production, instance, store } = deps;
|
|
808
|
+
const random = deps.random ?? Math.random;
|
|
809
|
+
const now = deps.now ?? (() => performance.timeOrigin + performance.now());
|
|
810
|
+
const warn = deps.warn ?? (() => {});
|
|
811
|
+
const logLevels = new Set(production.logLevels);
|
|
812
|
+
const collector = require_collector.createCollector({
|
|
813
|
+
...deps.options,
|
|
814
|
+
maxRequests: production.maxRequests
|
|
815
|
+
});
|
|
816
|
+
const queries = createQueryStats({
|
|
817
|
+
maxShapes: production.maxShapes,
|
|
818
|
+
instance: instance.id
|
|
819
|
+
});
|
|
820
|
+
const routes = createRouteStats({
|
|
821
|
+
maxRoutes: production.maxRoutes,
|
|
822
|
+
instance: instance.id
|
|
823
|
+
});
|
|
824
|
+
const errors = createErrorGroups({ maxGroups: production.maxErrorGroups });
|
|
825
|
+
const logs = createRecentLogs({ maxEntries: 200 });
|
|
826
|
+
const active = /* @__PURE__ */ new Map();
|
|
827
|
+
const recent = /* @__PURE__ */ new Map();
|
|
828
|
+
const pending = [];
|
|
829
|
+
const counts = {
|
|
830
|
+
requests: 0,
|
|
831
|
+
sampled: 0,
|
|
832
|
+
keptUnsampled: 0,
|
|
833
|
+
stored: 0,
|
|
834
|
+
droppedStored: 0,
|
|
835
|
+
droppedQueries: 0
|
|
836
|
+
};
|
|
837
|
+
let exampleSequence = 0;
|
|
838
|
+
let budgetMinute = -1;
|
|
839
|
+
let budgetUsed = 0;
|
|
840
|
+
let lastWarnAt = -Infinity;
|
|
841
|
+
let flushing = Promise.resolve();
|
|
842
|
+
let timer;
|
|
843
|
+
const remember = (sample) => {
|
|
844
|
+
recent.delete(sample.id);
|
|
845
|
+
recent.set(sample.id, sample);
|
|
846
|
+
while (recent.size > production.maxRequests) recent.delete(recent.keys().next().value);
|
|
847
|
+
};
|
|
848
|
+
const doFlush = async () => {
|
|
849
|
+
if (!store || pending.length === 0) return;
|
|
850
|
+
const batch = pending.splice(0, pending.length);
|
|
851
|
+
try {
|
|
852
|
+
await store.samples.insert(batch);
|
|
853
|
+
counts.stored += batch.length;
|
|
854
|
+
} catch (error) {
|
|
855
|
+
counts.droppedStored += batch.length;
|
|
856
|
+
const at = now();
|
|
857
|
+
if (at - lastWarnAt >= WARN_EVERY_MS) {
|
|
858
|
+
lastWarnAt = at;
|
|
859
|
+
warn(`devtools could not store ${batch.length} request sample(s), they were dropped: ${errorMessage(error)}. Check the database connection and that the devtools migrations ran.`);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
const flush = () => {
|
|
864
|
+
flushing = flushing.then(doFlush, doFlush);
|
|
865
|
+
return flushing;
|
|
866
|
+
};
|
|
867
|
+
const enqueue = (sample) => {
|
|
868
|
+
remember(sample);
|
|
869
|
+
if (!store) return;
|
|
870
|
+
const minute = Math.floor(now() / 6e4);
|
|
871
|
+
if (minute !== budgetMinute) {
|
|
872
|
+
budgetMinute = minute;
|
|
873
|
+
budgetUsed = 0;
|
|
874
|
+
}
|
|
875
|
+
if (budgetUsed >= production.maxStoredSamplesPerMinute) {
|
|
876
|
+
counts.droppedStored++;
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
budgetUsed++;
|
|
880
|
+
pending.push(sample);
|
|
881
|
+
if (pending.length > MAX_PENDING) {
|
|
882
|
+
pending.shift();
|
|
883
|
+
counts.droppedStored++;
|
|
884
|
+
}
|
|
885
|
+
if (pending.length >= FLUSH_AT) flush();
|
|
886
|
+
};
|
|
887
|
+
const newState = (route) => ({
|
|
888
|
+
queries: 0,
|
|
889
|
+
logs: 0,
|
|
890
|
+
phases: 0,
|
|
891
|
+
cache: 0,
|
|
892
|
+
dropped: 0,
|
|
893
|
+
route
|
|
894
|
+
});
|
|
895
|
+
const recordRequestError = (request, result, route) => {
|
|
896
|
+
const status = result.status;
|
|
897
|
+
if (!(status !== void 0 && status >= 500 || result.error !== void 0)) return;
|
|
898
|
+
const error = result.error;
|
|
899
|
+
errors.record({
|
|
900
|
+
source: "request",
|
|
901
|
+
message: error === void 0 ? `HTTP ${status}` : requestErrorMessage(error),
|
|
902
|
+
name: error instanceof Error ? error.name : null,
|
|
903
|
+
stack: error instanceof Error && error.stack !== void 0 ? scrubErrorText(error.stack, REQUEST_STACK_MAX) : null,
|
|
904
|
+
route: route ?? null,
|
|
905
|
+
status: status ?? null,
|
|
906
|
+
requestId: request.requestId,
|
|
907
|
+
at: now()
|
|
908
|
+
});
|
|
909
|
+
};
|
|
910
|
+
const finishSampled = (request, state, result) => {
|
|
911
|
+
const route = request.route ?? state.route;
|
|
912
|
+
collector.endRequest(request.requestId, {
|
|
913
|
+
...result.status === void 0 ? {} : { status: result.status },
|
|
914
|
+
durationMs: result.durationMs,
|
|
915
|
+
...result.error === void 0 ? {} : { error: requestErrorMessage(result.error) },
|
|
916
|
+
...route === void 0 ? {} : { route }
|
|
917
|
+
});
|
|
918
|
+
const settled = collector.getRequest(request.requestId);
|
|
919
|
+
if (!settled) return;
|
|
920
|
+
const failed = result.status !== void 0 && result.status >= 500 || result.error !== void 0;
|
|
921
|
+
routes.record({
|
|
922
|
+
method: request.method,
|
|
923
|
+
route: route ?? "",
|
|
924
|
+
status: result.status ?? null,
|
|
925
|
+
failed,
|
|
926
|
+
durationMs: result.durationMs,
|
|
927
|
+
at: now(),
|
|
928
|
+
requestId: request.requestId,
|
|
929
|
+
phases: settled.phases.map((phase) => ({
|
|
930
|
+
name: phase.name,
|
|
931
|
+
durationMs: phase.durationMs
|
|
932
|
+
}))
|
|
933
|
+
});
|
|
934
|
+
for (const warning of settled.warnings) queries.recordNPlusOne(warning.shape, warning.count);
|
|
935
|
+
recordRequestError(request, result, route);
|
|
936
|
+
enqueue(toStoredSample(settled, instance.id, state.dropped));
|
|
937
|
+
};
|
|
938
|
+
const finishUnsampled = (request, result) => {
|
|
939
|
+
if (deps.isDashboardPath(request.path)) return;
|
|
940
|
+
counts.keptUnsampled++;
|
|
941
|
+
const startedAt = now() - result.durationMs;
|
|
942
|
+
const path = stripQuery(request.path);
|
|
943
|
+
const summary = {
|
|
944
|
+
id: request.requestId,
|
|
945
|
+
method: request.method,
|
|
946
|
+
path,
|
|
947
|
+
startedAt,
|
|
948
|
+
durationMs: result.durationMs,
|
|
949
|
+
queryCount: 0,
|
|
950
|
+
warningCount: 0,
|
|
951
|
+
instance: instance.id,
|
|
952
|
+
partial: true
|
|
953
|
+
};
|
|
954
|
+
if (request.route !== void 0) summary.route = request.route;
|
|
955
|
+
if (result.status !== void 0) summary.status = result.status;
|
|
956
|
+
recordRequestError(request, result, request.route);
|
|
957
|
+
enqueue({
|
|
958
|
+
id: request.requestId,
|
|
959
|
+
instance: instance.id,
|
|
960
|
+
startedAt,
|
|
961
|
+
summary,
|
|
962
|
+
detail: null
|
|
963
|
+
});
|
|
964
|
+
collector.startRequest({
|
|
965
|
+
id: request.requestId,
|
|
966
|
+
method: request.method,
|
|
967
|
+
path,
|
|
968
|
+
...request.route === void 0 ? {} : { route: request.route },
|
|
969
|
+
startedAt
|
|
970
|
+
});
|
|
971
|
+
collector.endRequest(request.requestId, {
|
|
972
|
+
...result.status === void 0 ? {} : { status: result.status },
|
|
973
|
+
durationMs: result.durationMs,
|
|
974
|
+
...result.error === void 0 ? {} : { error: requestErrorMessage(result.error) },
|
|
975
|
+
...request.route === void 0 ? {} : { route: request.route }
|
|
976
|
+
});
|
|
977
|
+
};
|
|
978
|
+
/** The query without an id or a shape, from what the driver emitted. */
|
|
979
|
+
const queryInput = (event) => {
|
|
980
|
+
const input = {
|
|
981
|
+
connection: event.connection,
|
|
982
|
+
driver: event.driver,
|
|
983
|
+
startedAt: event.startedAt,
|
|
984
|
+
durationMs: event.durationMs
|
|
985
|
+
};
|
|
986
|
+
if (event.sql !== void 0) input.sql = event.sql;
|
|
987
|
+
if (event.bindings !== void 0) input.bindings = event.bindings;
|
|
988
|
+
if (event.collection !== void 0) input.collection = event.collection;
|
|
989
|
+
if (event.command !== void 0) input.command = event.command;
|
|
990
|
+
if (event.pipeline !== void 0) input.pipeline = event.pipeline;
|
|
991
|
+
if (event.rowCount !== void 0) input.rowCount = event.rowCount;
|
|
992
|
+
if (event.error !== void 0) input.error = scrubQueryError(errorMessage(event.error));
|
|
993
|
+
return input;
|
|
994
|
+
};
|
|
995
|
+
const exampleOf = (event) => ({
|
|
996
|
+
...queryInput(event),
|
|
997
|
+
id: `x${++exampleSequence}`,
|
|
998
|
+
shape: require_collector.queryShape(event)
|
|
999
|
+
});
|
|
1000
|
+
const recordQuery = (query, route, requestId) => {
|
|
1001
|
+
queries.record({
|
|
1002
|
+
shape: query.shape,
|
|
1003
|
+
driver: query.driver,
|
|
1004
|
+
connection: query.connection,
|
|
1005
|
+
durationMs: query.durationMs,
|
|
1006
|
+
failed: query.error !== void 0,
|
|
1007
|
+
at: query.startedAt,
|
|
1008
|
+
route,
|
|
1009
|
+
requestId
|
|
1010
|
+
});
|
|
1011
|
+
queries.rememberExample(query);
|
|
1012
|
+
};
|
|
1013
|
+
return {
|
|
1014
|
+
collector,
|
|
1015
|
+
queries,
|
|
1016
|
+
routes,
|
|
1017
|
+
errors,
|
|
1018
|
+
logs,
|
|
1019
|
+
requests: {
|
|
1020
|
+
async list(filter) {
|
|
1021
|
+
let storedRows = [];
|
|
1022
|
+
if (store) try {
|
|
1023
|
+
storedRows = await store.samples.list(filter);
|
|
1024
|
+
} catch (error) {
|
|
1025
|
+
warn(`devtools could not read request samples: ${errorMessage(error)}. Showing this process's requests only.`);
|
|
1026
|
+
}
|
|
1027
|
+
const merged = /* @__PURE__ */ new Map();
|
|
1028
|
+
for (const row of storedRows) merged.set(row.id, row);
|
|
1029
|
+
for (const sample of recent.values()) if (!merged.has(sample.id) && sampleMatchesFilter(sample.summary, filter)) merged.set(sample.id, sample.summary);
|
|
1030
|
+
return [...merged.values()].sort((a, b) => b.startedAt - a.startedAt).slice(0, Math.max(1, filter.limit));
|
|
1031
|
+
},
|
|
1032
|
+
async get(id) {
|
|
1033
|
+
let stored = null;
|
|
1034
|
+
if (store) try {
|
|
1035
|
+
stored = await store.samples.get(id);
|
|
1036
|
+
} catch {
|
|
1037
|
+
stored = null;
|
|
1038
|
+
}
|
|
1039
|
+
stored ??= recent.get(id) ?? null;
|
|
1040
|
+
if (stored) return stored.detail ?? stored.summary;
|
|
1041
|
+
const live = collector.getRequest(id);
|
|
1042
|
+
if (!live) return null;
|
|
1043
|
+
const dropped = active.get(id)?.dropped ?? 0;
|
|
1044
|
+
const sample = toStoredSample(live, instance.id, dropped);
|
|
1045
|
+
return sample.detail ?? sample.summary;
|
|
1046
|
+
},
|
|
1047
|
+
async clear() {
|
|
1048
|
+
const memory = recent.size;
|
|
1049
|
+
const waiting = pending.length;
|
|
1050
|
+
recent.clear();
|
|
1051
|
+
pending.length = 0;
|
|
1052
|
+
collector.clear();
|
|
1053
|
+
if (!store) return memory;
|
|
1054
|
+
return await store.samples.clear() + waiting;
|
|
1055
|
+
}
|
|
1056
|
+
},
|
|
1057
|
+
hooks: {
|
|
1058
|
+
onRequestStart(request) {
|
|
1059
|
+
if (deps.isDashboardPath(request.path)) return;
|
|
1060
|
+
counts.requests++;
|
|
1061
|
+
if (!(random() < production.sampleRate)) return;
|
|
1062
|
+
counts.sampled++;
|
|
1063
|
+
if (active.size >= MAX_ACTIVE) active.delete(active.keys().next().value);
|
|
1064
|
+
active.set(request.requestId, newState(request.route));
|
|
1065
|
+
collector.startRequest({
|
|
1066
|
+
id: request.requestId,
|
|
1067
|
+
method: request.method,
|
|
1068
|
+
path: stripQuery(request.path),
|
|
1069
|
+
...request.route === void 0 ? {} : { route: request.route },
|
|
1070
|
+
startedAt: now()
|
|
1071
|
+
});
|
|
1072
|
+
},
|
|
1073
|
+
onPhase(request, phase) {
|
|
1074
|
+
const state = active.get(request.requestId);
|
|
1075
|
+
if (!state) return;
|
|
1076
|
+
if (request.route !== void 0) state.route = request.route;
|
|
1077
|
+
if (state.phases >= MAX_PHASES_PER_REQUEST) return;
|
|
1078
|
+
state.phases++;
|
|
1079
|
+
collector.addPhase(request.requestId, {
|
|
1080
|
+
name: phase.name,
|
|
1081
|
+
durationMs: phase.durationMs,
|
|
1082
|
+
startedAt: phase.startedAt ?? now() - phase.durationMs
|
|
1083
|
+
});
|
|
1084
|
+
},
|
|
1085
|
+
onRequestEnd(request, result) {
|
|
1086
|
+
const state = active.get(request.requestId);
|
|
1087
|
+
if (state) {
|
|
1088
|
+
active.delete(request.requestId);
|
|
1089
|
+
finishSampled(request, state, result);
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
if (result.durationMs >= production.slowRequestMs || result.status !== void 0 && result.status >= 500 || result.error !== void 0) finishUnsampled(request, result);
|
|
1093
|
+
},
|
|
1094
|
+
onQuery(requestId, event) {
|
|
1095
|
+
const state = requestId === void 0 ? void 0 : active.get(requestId);
|
|
1096
|
+
if (state && requestId !== void 0) {
|
|
1097
|
+
if (touchesMonitorTables(event)) return;
|
|
1098
|
+
let query;
|
|
1099
|
+
if (state.queries < production.maxQueriesPerRequest) {
|
|
1100
|
+
state.queries++;
|
|
1101
|
+
query = collector.addQuery(requestId, queryInput(event));
|
|
1102
|
+
} else {
|
|
1103
|
+
state.dropped++;
|
|
1104
|
+
counts.droppedQueries++;
|
|
1105
|
+
query = exampleOf(event);
|
|
1106
|
+
}
|
|
1107
|
+
recordQuery(query, state.route ?? null, requestId);
|
|
1108
|
+
delete query.sql;
|
|
1109
|
+
delete query.bindings;
|
|
1110
|
+
delete query.pipeline;
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
if (requestId === void 0) {
|
|
1114
|
+
if (touchesMonitorTables(event)) return;
|
|
1115
|
+
if (random() < production.sampleRate) {
|
|
1116
|
+
const query = exampleOf(event);
|
|
1117
|
+
recordQuery(query, null, null);
|
|
1118
|
+
} else if (event.durationMs >= production.slowQueryMs) queries.rememberExample(exampleOf(event));
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
if (event.durationMs >= production.slowQueryMs && !touchesMonitorTables(event)) queries.rememberExample(exampleOf(event));
|
|
1122
|
+
},
|
|
1123
|
+
onLog(requestId, entry) {
|
|
1124
|
+
const wanted = logLevels.has(entry.level);
|
|
1125
|
+
const state = requestId === void 0 ? void 0 : active.get(requestId);
|
|
1126
|
+
if (!wanted && !state) return;
|
|
1127
|
+
const message = truncate(entry.message, LOG_MESSAGE_MAX$1);
|
|
1128
|
+
const kept = {
|
|
1129
|
+
level: entry.level,
|
|
1130
|
+
module: entry.module,
|
|
1131
|
+
action: entry.action,
|
|
1132
|
+
message,
|
|
1133
|
+
at: entry.at
|
|
1134
|
+
};
|
|
1135
|
+
if (state && requestId !== void 0) {
|
|
1136
|
+
if (state.logs < MAX_LOGS_PER_REQUEST) {
|
|
1137
|
+
state.logs++;
|
|
1138
|
+
collector.addLog(requestId, kept);
|
|
1139
|
+
}
|
|
1140
|
+
} else collector.addLog(void 0, kept);
|
|
1141
|
+
if (!wanted) return;
|
|
1142
|
+
logs.record({
|
|
1143
|
+
level: entry.level,
|
|
1144
|
+
module: entry.module,
|
|
1145
|
+
action: entry.action,
|
|
1146
|
+
message,
|
|
1147
|
+
at: entry.at,
|
|
1148
|
+
requestId: state && requestId !== void 0 ? requestId : null
|
|
1149
|
+
});
|
|
1150
|
+
if (entry.level === "error") errors.record({
|
|
1151
|
+
source: "log",
|
|
1152
|
+
message: entry.message,
|
|
1153
|
+
name: null,
|
|
1154
|
+
stack: null,
|
|
1155
|
+
route: state?.route ?? null,
|
|
1156
|
+
status: null,
|
|
1157
|
+
requestId: state && requestId !== void 0 ? requestId : null,
|
|
1158
|
+
at: entry.at
|
|
1159
|
+
});
|
|
1160
|
+
},
|
|
1161
|
+
onCache(requestId, operation) {
|
|
1162
|
+
if (requestId === void 0) return;
|
|
1163
|
+
const state = active.get(requestId);
|
|
1164
|
+
if (!state || state.cache >= MAX_CACHE_PER_REQUEST) return;
|
|
1165
|
+
state.cache++;
|
|
1166
|
+
collector.addCacheOperation(requestId, {
|
|
1167
|
+
type: operation.type,
|
|
1168
|
+
driver: operation.driver,
|
|
1169
|
+
at: operation.at
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
},
|
|
1173
|
+
explain: createShapeExplainer({
|
|
1174
|
+
queries,
|
|
1175
|
+
executing: production.explain.executing,
|
|
1176
|
+
instance: instance.id,
|
|
1177
|
+
redact: true,
|
|
1178
|
+
...deps.run === void 0 ? {} : { run: deps.run }
|
|
1179
|
+
}),
|
|
1180
|
+
flush,
|
|
1181
|
+
counters: () => ({
|
|
1182
|
+
sampleRate: production.sampleRate,
|
|
1183
|
+
requests: counts.requests,
|
|
1184
|
+
sampled: counts.sampled,
|
|
1185
|
+
keptUnsampled: counts.keptUnsampled,
|
|
1186
|
+
stored: counts.stored,
|
|
1187
|
+
droppedStored: counts.droppedStored,
|
|
1188
|
+
evictedShapes: queries.evicted(),
|
|
1189
|
+
evictedRoutes: routes.evicted(),
|
|
1190
|
+
evictedErrors: errors.evicted(),
|
|
1191
|
+
droppedQueries: counts.droppedQueries
|
|
1192
|
+
}),
|
|
1193
|
+
startWriter() {
|
|
1194
|
+
if (!store || timer) return;
|
|
1195
|
+
timer = setInterval(() => void flush(), FLUSH_EVERY_MS);
|
|
1196
|
+
timer.unref();
|
|
1197
|
+
},
|
|
1198
|
+
stopWriter() {
|
|
1199
|
+
if (timer) clearInterval(timer);
|
|
1200
|
+
timer = void 0;
|
|
1201
|
+
}
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
//#endregion
|
|
1206
|
+
//#region ../../packages/devtools/src/production/capture/production-capture.ts
|
|
1207
|
+
/** Longest log message kept, as in the capture engine. */
|
|
1208
|
+
const LOG_MESSAGE_MAX = 1e3;
|
|
1209
|
+
/** Cache events counted for sampled requests. */
|
|
1210
|
+
const CACHE_EVENT_TYPES = [
|
|
1211
|
+
"hit",
|
|
1212
|
+
"miss",
|
|
1213
|
+
"set",
|
|
1214
|
+
"removed",
|
|
1215
|
+
"invalidated",
|
|
1216
|
+
"flushed"
|
|
1217
|
+
];
|
|
1218
|
+
/** `LoggingData.type` includes `fatal`, which devtools folds into `error`. */
|
|
1219
|
+
function toLevel(type) {
|
|
1220
|
+
return type === "fatal" ? "error" : type;
|
|
1221
|
+
}
|
|
1222
|
+
/**
|
|
1223
|
+
* The production capture of this process: sampling, the bounded in-memory
|
|
1224
|
+
* ring of sampled requests (the live view), statistics, error groups, recent
|
|
1225
|
+
* logs, the sample writer and EXPLAIN.
|
|
1226
|
+
*
|
|
1227
|
+
* Unsampled requests cost one random draw at start and one comparison at
|
|
1228
|
+
* end; they add nothing to the statistics.
|
|
1229
|
+
*/
|
|
1230
|
+
function createProductionCapture(deps) {
|
|
1231
|
+
const engine = createCaptureEngine({
|
|
1232
|
+
...deps,
|
|
1233
|
+
warn: deps.warn ?? ((message) => _warlock_js_logger.log.warn("devtools", "capture", message))
|
|
1234
|
+
});
|
|
1235
|
+
const { hooks } = engine;
|
|
1236
|
+
let detach;
|
|
1237
|
+
const warnFailed = (name, error) => {
|
|
1238
|
+
_warlock_js_logger.log.warn("devtools", "capture", `devtools' ${name} capture failed to attach: ${error instanceof Error ? error.message : String(error)}`);
|
|
1239
|
+
};
|
|
1240
|
+
return {
|
|
1241
|
+
collector: engine.collector,
|
|
1242
|
+
queries: engine.queries,
|
|
1243
|
+
routes: engine.routes,
|
|
1244
|
+
errors: engine.errors,
|
|
1245
|
+
logs: engine.logs,
|
|
1246
|
+
requests: engine.requests,
|
|
1247
|
+
counters: engine.counters,
|
|
1248
|
+
explain: engine.explain,
|
|
1249
|
+
flush: engine.flush,
|
|
1250
|
+
async attach() {
|
|
1251
|
+
if (detach) return detach;
|
|
1252
|
+
const disposers = [];
|
|
1253
|
+
const { currentRequestId } = await Promise.resolve().then(() => require("./current-request-id-BoJJb3y7.cjs")).then((n) => n.current_request_id_exports);
|
|
1254
|
+
try {
|
|
1255
|
+
const { registerTracingHooks } = await import("@warlock.js/core");
|
|
1256
|
+
disposers.push(registerTracingHooks({
|
|
1257
|
+
onRequestStart: hooks.onRequestStart,
|
|
1258
|
+
onPhase: hooks.onPhase,
|
|
1259
|
+
onRequestEnd: hooks.onRequestEnd
|
|
1260
|
+
}));
|
|
1261
|
+
} catch (error) {
|
|
1262
|
+
warnFailed("request", error);
|
|
1263
|
+
}
|
|
1264
|
+
try {
|
|
1265
|
+
let dataSourceRegistry;
|
|
1266
|
+
({dataSourceRegistry} = await import("@warlock.js/cascade"));
|
|
1267
|
+
const listener = (event) => hooks.onQuery(currentRequestId(), event);
|
|
1268
|
+
dataSourceRegistry.on("query", listener);
|
|
1269
|
+
disposers.push(() => dataSourceRegistry.off("query", listener));
|
|
1270
|
+
} catch {}
|
|
1271
|
+
try {
|
|
1272
|
+
const channel = new class extends _warlock_js_logger.LogChannel {
|
|
1273
|
+
constructor(..._args) {
|
|
1274
|
+
super(..._args);
|
|
1275
|
+
this.name = "devtools-monitor";
|
|
1276
|
+
this.active = true;
|
|
1277
|
+
}
|
|
1278
|
+
log(data) {
|
|
1279
|
+
if (!this.active) return;
|
|
1280
|
+
const level = toLevel(data.type);
|
|
1281
|
+
const text = typeof data.message === "string" ? data.message : String(data.message);
|
|
1282
|
+
hooks.onLog(currentRequestId(), {
|
|
1283
|
+
level,
|
|
1284
|
+
module: data.module,
|
|
1285
|
+
action: data.action,
|
|
1286
|
+
message: level === "error" ? scrubErrorText(text, LOG_MESSAGE_MAX) : text,
|
|
1287
|
+
at: Date.now()
|
|
1288
|
+
});
|
|
1289
|
+
}
|
|
1290
|
+
}();
|
|
1291
|
+
_warlock_js_logger.log.addChannel(channel);
|
|
1292
|
+
disposers.push(() => {
|
|
1293
|
+
channel.active = false;
|
|
1294
|
+
});
|
|
1295
|
+
} catch (error) {
|
|
1296
|
+
warnFailed("log", error);
|
|
1297
|
+
}
|
|
1298
|
+
try {
|
|
1299
|
+
let cache;
|
|
1300
|
+
({cache} = await import("@warlock.js/cache"));
|
|
1301
|
+
const handlers = CACHE_EVENT_TYPES.map((type) => {
|
|
1302
|
+
const handler = (data) => hooks.onCache(currentRequestId(), {
|
|
1303
|
+
type,
|
|
1304
|
+
driver: data.driver,
|
|
1305
|
+
at: Date.now()
|
|
1306
|
+
});
|
|
1307
|
+
cache.on(type, handler);
|
|
1308
|
+
return {
|
|
1309
|
+
type,
|
|
1310
|
+
handler
|
|
1311
|
+
};
|
|
1312
|
+
});
|
|
1313
|
+
disposers.push(() => {
|
|
1314
|
+
for (const { type, handler } of handlers) cache.off(type, handler);
|
|
1315
|
+
});
|
|
1316
|
+
} catch {}
|
|
1317
|
+
engine.startWriter();
|
|
1318
|
+
const dispose = () => {
|
|
1319
|
+
for (const disposer of disposers.splice(0)) disposer();
|
|
1320
|
+
engine.stopWriter();
|
|
1321
|
+
detach = void 0;
|
|
1322
|
+
};
|
|
1323
|
+
detach = dispose;
|
|
1324
|
+
return dispose;
|
|
1325
|
+
},
|
|
1326
|
+
async dispose() {
|
|
1327
|
+
detach?.();
|
|
1328
|
+
await engine.flush();
|
|
1329
|
+
}
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
//#endregion
|
|
1334
|
+
exports.attachDevelopmentStats = attachDevelopmentStats;
|
|
1335
|
+
exports.createErrorGroups = createErrorGroups;
|
|
1336
|
+
exports.createProductionCapture = createProductionCapture;
|
|
1337
|
+
exports.createQueryStats = createQueryStats;
|
|
1338
|
+
exports.createRecentLogs = createRecentLogs;
|
|
1339
|
+
exports.createRouteStats = createRouteStats;
|
|
1340
|
+
exports.createShapeExplainer = createShapeExplainer;
|
|
1341
|
+
exports.toStoredSample = toStoredSample;
|
|
1342
|
+
//# sourceMappingURL=capture-CqIiaznN.cjs.map
|