@warlock.js/devtools 5.54.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 +36 -0
- package/README.md +26 -13
- package/cjs/{ai-source-CSPh1HqJ.cjs → ai-source-DTpxumMA.cjs} +54 -3
- package/cjs/{ai-source-CSPh1HqJ.cjs.map → ai-source-DTpxumMA.cjs.map} +1 -1
- 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-BzuntLcd.cjs → src-Ce-3Lniv.cjs} +171 -308
- 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 -12
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +137 -18
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +3 -2
- package/esm/options.mjs +3 -1
- package/esm/options.mjs.map +1 -1
- package/esm/panels.mjs +267 -0
- package/esm/panels.mjs.map +1 -0
- package/esm/process-panel.mjs +20 -1
- package/esm/process-panel.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 +16 -6
- 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/panel-routes.mjs +44 -0
- package/esm/server/panel-routes.mjs.map +1 -0
- 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 -12
- 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 +271 -1
- package/esm/types.d.mts.map +1 -1
- package/esm/ui-root.mjs +11 -6
- package/esm/ui-root.mjs.map +1 -1
- package/llms-full.txt +208 -19
- package/llms.txt +2 -2
- package/package.json +32 -8
- package/skills/SKILL.md +208 -19
- 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/ui/panels/processes.js +15 -0
- package/cjs/server-BlQshJLE.cjs +0 -658
- package/cjs/server-BlQshJLE.cjs.map +0 -1
- package/cjs/src-BzuntLcd.cjs.map +0 -1
- package/esm/server/process-routes.mjs +0 -11
- package/esm/server/process-routes.mjs.map +0 -1
- package/ui/app.css +0 -376
- package/ui/app.js +0 -1054
- package/ui/index.html +0 -28
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { DevtoolsApiError, createErrorRef } from "../errors.mjs";
|
|
2
|
+
import { log } from "@warlock.js/logger";
|
|
3
|
+
|
|
4
|
+
//#region ../../packages/devtools/src/production/capture/explain.ts
|
|
5
|
+
/** Words that write, lock, call or create something. A read statement holds none of them. */
|
|
6
|
+
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;
|
|
7
|
+
const isIdentifierCharacter = (character) => character !== void 0 && /[A-Za-z0-9_$\u0080-\uffff]/.test(character);
|
|
8
|
+
/** The index after the comment starting at `index` (`--` or a nested block comment), or `-1` when it is not closed. */
|
|
9
|
+
function commentEnd(sql, index) {
|
|
10
|
+
if (sql.startsWith("--", index)) {
|
|
11
|
+
const newline = sql.indexOf("\n", index + 2);
|
|
12
|
+
return newline === -1 ? sql.length : newline + 1;
|
|
13
|
+
}
|
|
14
|
+
let depth = 0;
|
|
15
|
+
let at = index;
|
|
16
|
+
while (at < sql.length) if (sql.startsWith("/*", at)) {
|
|
17
|
+
depth++;
|
|
18
|
+
at += 2;
|
|
19
|
+
} else if (sql.startsWith("*/", at)) {
|
|
20
|
+
depth--;
|
|
21
|
+
at += 2;
|
|
22
|
+
if (depth === 0) return at;
|
|
23
|
+
} else at++;
|
|
24
|
+
return -1;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* `sql` as the server reads it, with every comment turned into a space and
|
|
28
|
+
* every string, quoted identifier and dollar-quoted body into `?`; `null`
|
|
29
|
+
* when one of them is not closed. `backslashEscapes` reads a backslash as an
|
|
30
|
+
* escape in every string (`standard_conforming_strings = off`); escape
|
|
31
|
+
* strings (`E'…'`) always use it.
|
|
32
|
+
*/
|
|
33
|
+
function maskSql(sql, backslashEscapes) {
|
|
34
|
+
let out = "";
|
|
35
|
+
let at = 0;
|
|
36
|
+
while (at < sql.length) {
|
|
37
|
+
const character = sql[at];
|
|
38
|
+
if (sql.startsWith("--", at) || sql.startsWith("/*", at)) {
|
|
39
|
+
const end = commentEnd(sql, at);
|
|
40
|
+
if (end === -1) return null;
|
|
41
|
+
out += " ";
|
|
42
|
+
at = end;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (character === "'" || character === "\"") {
|
|
46
|
+
const escapes = character === "'" && (backslashEscapes || /[eE]/.test(sql[at - 1] ?? "") && !isIdentifierCharacter(sql[at - 2]));
|
|
47
|
+
let closed = false;
|
|
48
|
+
at++;
|
|
49
|
+
while (at < sql.length) {
|
|
50
|
+
const current = sql[at];
|
|
51
|
+
if (escapes && current === "\\") at += 2;
|
|
52
|
+
else if (current === character) {
|
|
53
|
+
at++;
|
|
54
|
+
if (sql[at] !== character) {
|
|
55
|
+
closed = true;
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
at++;
|
|
59
|
+
} else at++;
|
|
60
|
+
}
|
|
61
|
+
if (!closed) return null;
|
|
62
|
+
out += " ? ";
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (character === "$" && !isIdentifierCharacter(sql[at - 1])) {
|
|
66
|
+
const opener = /^\$(?:[A-Za-z_\u0080-\uffff][A-Za-z0-9_\u0080-\uffff]*)?\$/.exec(sql.slice(at))?.[0];
|
|
67
|
+
if (opener !== void 0) {
|
|
68
|
+
const end = sql.indexOf(opener, at + opener.length);
|
|
69
|
+
if (end === -1) return null;
|
|
70
|
+
out += " ? ";
|
|
71
|
+
at = end + opener.length;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
out += character;
|
|
76
|
+
at++;
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
/** `sql` without its leading whitespace and comments, or `null` when a leading comment is not closed. */
|
|
81
|
+
function withoutLeadingNoise(sql) {
|
|
82
|
+
let at = 0;
|
|
83
|
+
while (at < sql.length) if (/\s/.test(sql[at])) at++;
|
|
84
|
+
else if (sql.startsWith("--", at) || sql.startsWith("/*", at)) {
|
|
85
|
+
const end = commentEnd(sql, at);
|
|
86
|
+
if (end === -1) return null;
|
|
87
|
+
at = end;
|
|
88
|
+
} else break;
|
|
89
|
+
return sql.slice(at);
|
|
90
|
+
}
|
|
91
|
+
/** Whether the masked statement is one read: it starts with SELECT or WITH, ends at most at one `;`, writes nothing. */
|
|
92
|
+
function isOneRead(masked) {
|
|
93
|
+
if (masked === null) return false;
|
|
94
|
+
const bare = masked.trim().replace(/;\s*$/, "");
|
|
95
|
+
return /^(select|with)\b/i.test(bare) && !bare.includes(";") && !FORBIDDEN_WORDS.test(bare);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The statement to explain when `sql` is one plain read (`SELECT` or `WITH`,
|
|
99
|
+
* one statement, nothing that writes, locks or calls a function with side
|
|
100
|
+
* effects), without its leading comments; `null` otherwise. Strings, quoted
|
|
101
|
+
* identifiers, dollar-quoted bodies and nested comments are read the way the
|
|
102
|
+
* server reads them, under both settings of `standard_conforming_strings`, so
|
|
103
|
+
* a `;` or a keyword cannot hide inside what only looks like a string.
|
|
104
|
+
*/
|
|
105
|
+
function explainableSql(sql) {
|
|
106
|
+
if (sql === void 0) return null;
|
|
107
|
+
const statement = withoutLeadingNoise(sql)?.trimEnd();
|
|
108
|
+
if (statement === void 0 || !isOneRead(maskSql(statement, false)) || !isOneRead(maskSql(statement, true))) return null;
|
|
109
|
+
return statement.replace(/;\s*$/, "");
|
|
110
|
+
}
|
|
111
|
+
/** Keys of a recorded MongoDB command that an inner `explain` command does not accept. */
|
|
112
|
+
const MONGO_SESSION_KEYS = /* @__PURE__ */ new Set([
|
|
113
|
+
"lsid",
|
|
114
|
+
"txnNumber",
|
|
115
|
+
"autocommit",
|
|
116
|
+
"startTransaction",
|
|
117
|
+
"readConcern",
|
|
118
|
+
"writeConcern"
|
|
119
|
+
]);
|
|
120
|
+
const MONGO_COMMANDS = /* @__PURE__ */ new Set([
|
|
121
|
+
"find",
|
|
122
|
+
"aggregate",
|
|
123
|
+
"count"
|
|
124
|
+
]);
|
|
125
|
+
/** Aggregation stages that write their result to a collection. */
|
|
126
|
+
const MONGO_WRITE_STAGES = /* @__PURE__ */ new Set(["$out", "$merge"]);
|
|
127
|
+
/** Whether a recorded command or pipeline has a stage that writes. */
|
|
128
|
+
function writesInPipeline(recorded) {
|
|
129
|
+
const pipeline = Array.isArray(recorded) ? recorded : recorded !== null && typeof recorded === "object" ? recorded.pipeline : void 0;
|
|
130
|
+
return Array.isArray(pipeline) && pipeline.some((stage) => stage !== null && typeof stage === "object" && Object.keys(stage).some((key) => MONGO_WRITE_STAGES.has(key)));
|
|
131
|
+
}
|
|
132
|
+
function mongoExplainCommand(query, executing) {
|
|
133
|
+
const name = query.command;
|
|
134
|
+
if (name === void 0 || !MONGO_COMMANDS.has(name) || query.collection === void 0) return null;
|
|
135
|
+
if (name === "aggregate" && writesInPipeline(query.pipeline)) return null;
|
|
136
|
+
let inner;
|
|
137
|
+
const recorded = query.pipeline;
|
|
138
|
+
if (recorded !== null && typeof recorded === "object" && !Array.isArray(recorded)) {
|
|
139
|
+
inner = {};
|
|
140
|
+
for (const [key, value] of Object.entries(recorded)) {
|
|
141
|
+
if (key.startsWith("$") || MONGO_SESSION_KEYS.has(key)) continue;
|
|
142
|
+
inner[key] = value;
|
|
143
|
+
}
|
|
144
|
+
inner[name] = query.collection;
|
|
145
|
+
} else if (name === "aggregate") inner = {
|
|
146
|
+
aggregate: query.collection,
|
|
147
|
+
pipeline: Array.isArray(recorded) ? recorded : [],
|
|
148
|
+
cursor: {}
|
|
149
|
+
};
|
|
150
|
+
else inner = { [name]: query.collection };
|
|
151
|
+
return {
|
|
152
|
+
explain: inner,
|
|
153
|
+
verbosity: executing ? "executionStats" : "queryPlanner"
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function statementFor(query, executing) {
|
|
157
|
+
if (query.driver === "postgres") {
|
|
158
|
+
const sql = explainableSql(query.sql);
|
|
159
|
+
if (sql === null) return null;
|
|
160
|
+
return {
|
|
161
|
+
type: "sql",
|
|
162
|
+
sql: `${executing ? "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)" : "EXPLAIN (FORMAT JSON)"} ${sql}`
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
const command = mongoExplainCommand(query, executing);
|
|
166
|
+
return command === null ? null : {
|
|
167
|
+
type: "mongo",
|
|
168
|
+
command
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Runs `sql` in a read-only transaction on its own pooled client and rolls it
|
|
173
|
+
* back, so nothing the statement reaches (a function with side effects under
|
|
174
|
+
* `ANALYZE`, a second statement) can write.
|
|
175
|
+
*/
|
|
176
|
+
async function explainReadOnly(driver, sql, bindings) {
|
|
177
|
+
const begin = driver.beginTransaction;
|
|
178
|
+
if (typeof begin !== "function") throw new Error("The connection cannot open a read-only transaction, so EXPLAIN was not run.");
|
|
179
|
+
const transaction = await begin.call(driver, { readOnly: true });
|
|
180
|
+
try {
|
|
181
|
+
const { rows } = await transaction.context.query(sql, bindings ?? []);
|
|
182
|
+
return rows;
|
|
183
|
+
} finally {
|
|
184
|
+
await transaction.rollback();
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** Runs the statement on the query's own connection through cascade's data source registry. */
|
|
188
|
+
const runOnDataSource = async (query, statement) => {
|
|
189
|
+
const { dataSourceRegistry } = await import("@warlock.js/cascade");
|
|
190
|
+
const dataSource = dataSourceRegistry.get(query.connection);
|
|
191
|
+
if (statement.type === "sql") return explainReadOnly(dataSource.driver, statement.sql, query.bindings);
|
|
192
|
+
return dataSource.driver.getDatabase().command(statement.command);
|
|
193
|
+
};
|
|
194
|
+
/** Keys of a MongoDB plan whose values come from the query (filters, bounds, the echoed command). */
|
|
195
|
+
const MONGO_VALUE_KEYS = /* @__PURE__ */ new Set([
|
|
196
|
+
"parsedQuery",
|
|
197
|
+
"filter",
|
|
198
|
+
"indexBounds",
|
|
199
|
+
"command",
|
|
200
|
+
"originalCommand",
|
|
201
|
+
"query",
|
|
202
|
+
"pipeline"
|
|
203
|
+
]);
|
|
204
|
+
/** SQL literals inside a PostgreSQL plan's condition text: `'text'` (with `''`), `E'…'` and numbers. */
|
|
205
|
+
const SQL_LITERAL = /(?:(?<!\w)[Ee])?'(?:''|\\.|[^'])*'|(?<![\w.$])-?\d+(?:\.\d+)?(?![\w.])/g;
|
|
206
|
+
function maskMongoValues(value) {
|
|
207
|
+
if (Array.isArray(value)) return value.map(maskMongoValues);
|
|
208
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, maskMongoValues(inner)]));
|
|
209
|
+
return value === null || value === void 0 ? value : "?";
|
|
210
|
+
}
|
|
211
|
+
function redactMongoPlan(value) {
|
|
212
|
+
if (Array.isArray(value)) return value.map(redactMongoPlan);
|
|
213
|
+
if (value === null || typeof value !== "object") return value;
|
|
214
|
+
return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, MONGO_VALUE_KEYS.has(key) ? maskMongoValues(inner) : redactMongoPlan(inner)]));
|
|
215
|
+
}
|
|
216
|
+
function redactSqlPlan(value) {
|
|
217
|
+
if (typeof value === "string") return value.replace(SQL_LITERAL, "?");
|
|
218
|
+
if (Array.isArray(value)) return value.map(redactSqlPlan);
|
|
219
|
+
if (value === null || typeof value !== "object") return value;
|
|
220
|
+
return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, redactSqlPlan(inner)]));
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* A plan without the query's values. Plans repeat them: MongoDB echoes the
|
|
224
|
+
* filter (`parsedQuery`, `indexBounds`, the command), PostgreSQL writes them
|
|
225
|
+
* into conditions (`Filter: (email = 'a@b.c'::text)`). Values become `?`;
|
|
226
|
+
* the plan's shape, costs, row counts and index choices stay.
|
|
227
|
+
*/
|
|
228
|
+
function redactExplainPlan(plan, driver) {
|
|
229
|
+
return driver === "mongodb" ? redactMongoPlan(plan) : redactSqlPlan(plan);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* EXPLAIN by shape id from the examples `queries` kept, used by the production
|
|
233
|
+
* capture and by development (`POST /api/queries/:shapeId/explain`). Plain
|
|
234
|
+
* `EXPLAIN (FORMAT JSON)` / MongoDB `queryPlanner` unless `executing`; never
|
|
235
|
+
* an executing plan for anything but a PostgreSQL `SELECT`/`WITH` or a
|
|
236
|
+
* MongoDB `find`/`aggregate`/`count` (never an aggregate with `$out` or
|
|
237
|
+
* `$merge`). `run` executes the statement on the query's own connection
|
|
238
|
+
* (injected for specs; default: cascade's `dataSourceRegistry`, PostgreSQL
|
|
239
|
+
* inside a read-only transaction that is always rolled back).
|
|
240
|
+
*/
|
|
241
|
+
function createShapeExplainer(input) {
|
|
242
|
+
const run = input.run ?? runOnDataSource;
|
|
243
|
+
return async (shapeId) => {
|
|
244
|
+
const example = input.queries.example(shapeId);
|
|
245
|
+
if (!example) throw new DevtoolsApiError("explain.elsewhere", { instance: input.instance });
|
|
246
|
+
const statement = statementFor(example, input.executing);
|
|
247
|
+
if (!statement) throw new DevtoolsApiError("explain.unsupported", { instance: input.instance });
|
|
248
|
+
try {
|
|
249
|
+
const plan = await run(example, statement);
|
|
250
|
+
return {
|
|
251
|
+
shapeId,
|
|
252
|
+
driver: example.driver,
|
|
253
|
+
executing: input.executing,
|
|
254
|
+
plan: input.redact === true ? redactExplainPlan(plan, example.driver) : plan,
|
|
255
|
+
instance: input.instance
|
|
256
|
+
};
|
|
257
|
+
} catch (cause) {
|
|
258
|
+
const ref = createErrorRef();
|
|
259
|
+
log.error("devtools", "explain", `EXPLAIN failed for query shape ${shapeId} (ref ${ref}): ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
260
|
+
throw new DevtoolsApiError("explain.failed", {
|
|
261
|
+
ref,
|
|
262
|
+
cause,
|
|
263
|
+
instance: input.instance
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
//#endregion
|
|
270
|
+
export { createShapeExplainer, explainableSql, redactExplainPlan };
|
|
271
|
+
//# sourceMappingURL=explain.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"explain.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/capture/explain.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport type { DevtoolsExplainResult } from \"../contracts\";\nimport { createErrorRef, DevtoolsApiError } from \"../errors\";\nimport type { DevtoolsQuery } from \"../../types\";\nimport type { DevtoolsExplainRunner, DevtoolsExplainStatement, DevtoolsQueryStats } from \"./types\";\n\ntype ExplainStatement = DevtoolsExplainStatement;\ntype ExplainRunner = DevtoolsExplainRunner;\n\n/** Words that write, lock, call or create something. A read statement holds none of them. */\nconst FORBIDDEN_WORDS =\n /\\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;\n\nconst isIdentifierCharacter = (character: string | undefined): boolean =>\n character !== undefined && /[A-Za-z0-9_$\\u0080-\\uffff]/.test(character);\n\n/** The index after the comment starting at `index` (`--` or a nested block comment), or `-1` when it is not closed. */\nfunction commentEnd(sql: string, index: number): number {\n if (sql.startsWith(\"--\", index)) {\n const newline = sql.indexOf(\"\\n\", index + 2);\n\n return newline === -1 ? sql.length : newline + 1;\n }\n\n let depth = 0;\n let at = index;\n\n while (at < sql.length) {\n if (sql.startsWith(\"/*\", at)) {\n depth++;\n at += 2;\n } else if (sql.startsWith(\"*/\", at)) {\n depth--;\n at += 2;\n\n if (depth === 0) return at;\n } else {\n at++;\n }\n }\n\n return -1;\n}\n\n/**\n * `sql` as the server reads it, with every comment turned into a space and\n * every string, quoted identifier and dollar-quoted body into `?`; `null`\n * when one of them is not closed. `backslashEscapes` reads a backslash as an\n * escape in every string (`standard_conforming_strings = off`); escape\n * strings (`E'…'`) always use it.\n */\nfunction maskSql(sql: string, backslashEscapes: boolean): string | null {\n let out = \"\";\n let at = 0;\n\n while (at < sql.length) {\n const character = sql[at] as string;\n\n if (sql.startsWith(\"--\", at) || sql.startsWith(\"/*\", at)) {\n const end = commentEnd(sql, at);\n\n if (end === -1) return null;\n\n out += \" \";\n at = end;\n continue;\n }\n\n if (character === \"'\" || character === '\"') {\n const escapes =\n character === \"'\" &&\n (backslashEscapes ||\n (/[eE]/.test(sql[at - 1] ?? \"\") && !isIdentifierCharacter(sql[at - 2])));\n let closed = false;\n\n at++;\n\n while (at < sql.length) {\n const current = sql[at];\n\n if (escapes && current === \"\\\\\") {\n at += 2;\n } else if (current === character) {\n at++;\n\n if (sql[at] !== character) {\n closed = true;\n break;\n }\n\n at++;\n } else {\n at++;\n }\n }\n\n if (!closed) return null;\n\n out += \" ? \";\n continue;\n }\n\n if (character === \"$\" && !isIdentifierCharacter(sql[at - 1])) {\n const tag = /^\\$(?:[A-Za-z_\\u0080-\\uffff][A-Za-z0-9_\\u0080-\\uffff]*)?\\$/.exec(sql.slice(at));\n\n const opener = tag?.[0];\n\n if (opener !== undefined) {\n const end = sql.indexOf(opener, at + opener.length);\n\n if (end === -1) return null;\n\n out += \" ? \";\n at = end + opener.length;\n continue;\n }\n }\n\n out += character;\n at++;\n }\n\n return out;\n}\n\n/** `sql` without its leading whitespace and comments, or `null` when a leading comment is not closed. */\nfunction withoutLeadingNoise(sql: string): string | null {\n let at = 0;\n\n while (at < sql.length) {\n if (/\\s/.test(sql[at] as string)) {\n at++;\n } else if (sql.startsWith(\"--\", at) || sql.startsWith(\"/*\", at)) {\n const end = commentEnd(sql, at);\n\n if (end === -1) return null;\n\n at = end;\n } else {\n break;\n }\n }\n\n return sql.slice(at);\n}\n\n/** Whether the masked statement is one read: it starts with SELECT or WITH, ends at most at one `;`, writes nothing. */\nfunction isOneRead(masked: string | null): boolean {\n if (masked === null) return false;\n\n const bare = masked.trim().replace(/;\\s*$/, \"\");\n\n return /^(select|with)\\b/i.test(bare) && !bare.includes(\";\") && !FORBIDDEN_WORDS.test(bare);\n}\n\n/**\n * The statement to explain when `sql` is one plain read (`SELECT` or `WITH`,\n * one statement, nothing that writes, locks or calls a function with side\n * effects), without its leading comments; `null` otherwise. Strings, quoted\n * identifiers, dollar-quoted bodies and nested comments are read the way the\n * server reads them, under both settings of `standard_conforming_strings`, so\n * a `;` or a keyword cannot hide inside what only looks like a string.\n */\nexport function explainableSql(sql: string | undefined): string | null {\n if (sql === undefined) return null;\n\n const statement = withoutLeadingNoise(sql)?.trimEnd();\n\n if (\n statement === undefined ||\n !isOneRead(maskSql(statement, false)) ||\n !isOneRead(maskSql(statement, true))\n ) {\n return null;\n }\n\n return statement.replace(/;\\s*$/, \"\");\n}\n\n/** Keys of a recorded MongoDB command that an inner `explain` command does not accept. */\nconst MONGO_SESSION_KEYS = new Set([\n \"lsid\",\n \"txnNumber\",\n \"autocommit\",\n \"startTransaction\",\n \"readConcern\",\n \"writeConcern\",\n]);\n\nconst MONGO_COMMANDS = new Set([\"find\", \"aggregate\", \"count\"]);\n\n/** Aggregation stages that write their result to a collection. */\nconst MONGO_WRITE_STAGES = new Set([\"$out\", \"$merge\"]);\n\n/** Whether a recorded command or pipeline has a stage that writes. */\nfunction writesInPipeline(recorded: unknown): boolean {\n const pipeline = Array.isArray(recorded)\n ? recorded\n : recorded !== null && typeof recorded === \"object\"\n ? (recorded as Record<string, unknown>).pipeline\n : undefined;\n\n return (\n Array.isArray(pipeline) &&\n pipeline.some(\n (stage) =>\n stage !== null &&\n typeof stage === \"object\" &&\n Object.keys(stage as Record<string, unknown>).some((key) => MONGO_WRITE_STAGES.has(key)),\n )\n );\n}\n\nfunction mongoExplainCommand(\n query: DevtoolsQuery,\n executing: boolean,\n): Record<string, unknown> | null {\n const name = query.command;\n\n if (name === undefined || !MONGO_COMMANDS.has(name) || query.collection === undefined) {\n return null;\n }\n\n if (name === \"aggregate\" && writesInPipeline(query.pipeline)) return null;\n\n let inner: Record<string, unknown>;\n const recorded = query.pipeline;\n\n if (recorded !== null && typeof recorded === \"object\" && !Array.isArray(recorded)) {\n inner = {};\n\n for (const [key, value] of Object.entries(recorded as Record<string, unknown>)) {\n if (key.startsWith(\"$\") || MONGO_SESSION_KEYS.has(key)) continue;\n\n inner[key] = value;\n }\n\n inner[name] = query.collection;\n } else if (name === \"aggregate\") {\n inner = {\n aggregate: query.collection,\n pipeline: Array.isArray(recorded) ? recorded : [],\n cursor: {},\n };\n } else {\n inner = { [name]: query.collection };\n }\n\n return { explain: inner, verbosity: executing ? \"executionStats\" : \"queryPlanner\" };\n}\n\nfunction statementFor(query: DevtoolsQuery, executing: boolean): ExplainStatement | null {\n if (query.driver === \"postgres\") {\n const sql = explainableSql(query.sql);\n\n if (sql === null) return null;\n\n const prefix = executing ? \"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)\" : \"EXPLAIN (FORMAT JSON)\";\n\n return { type: \"sql\", sql: `${prefix} ${sql}` };\n }\n\n const command = mongoExplainCommand(query, executing);\n\n return command === null ? null : { type: \"mongo\", command };\n}\n\ntype ReadOnlyTransaction = {\n context: { query(sql: string, params?: unknown[]): Promise<{ rows: unknown }> };\n commit(): Promise<void>;\n rollback(): Promise<void>;\n};\n\n/**\n * Runs `sql` in a read-only transaction on its own pooled client and rolls it\n * back, so nothing the statement reaches (a function with side effects under\n * `ANALYZE`, a second statement) can write.\n */\nasync function explainReadOnly(\n driver: unknown,\n sql: string,\n bindings: unknown[] | undefined,\n): Promise<unknown> {\n const begin = (driver as { beginTransaction?: unknown }).beginTransaction;\n\n if (typeof begin !== \"function\") {\n throw new Error(\"The connection cannot open a read-only transaction, so EXPLAIN was not run.\");\n }\n\n const transaction = (await begin.call(driver, { readOnly: true })) as ReadOnlyTransaction;\n\n try {\n const { rows } = await transaction.context.query(sql, bindings ?? []);\n\n return rows;\n } finally {\n await transaction.rollback();\n }\n}\n\n/** Runs the statement on the query's own connection through cascade's data source registry. */\nconst runOnDataSource: ExplainRunner = async (query, statement) => {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n\n if (statement.type === \"sql\") {\n return explainReadOnly(dataSource.driver, statement.sql, query.bindings);\n }\n\n const driver = dataSource.driver as unknown as {\n getDatabase(): { command(command: Record<string, unknown>): Promise<unknown> };\n };\n\n return driver.getDatabase().command(statement.command);\n};\n\n/** Keys of a MongoDB plan whose values come from the query (filters, bounds, the echoed command). */\nconst MONGO_VALUE_KEYS = new Set([\n \"parsedQuery\",\n \"filter\",\n \"indexBounds\",\n \"command\",\n \"originalCommand\",\n \"query\",\n \"pipeline\",\n]);\n/** SQL literals inside a PostgreSQL plan's condition text: `'text'` (with `''`), `E'…'` and numbers. */\nconst SQL_LITERAL = /(?:(?<!\\w)[Ee])?'(?:''|\\\\.|[^'])*'|(?<![\\w.$])-?\\d+(?:\\.\\d+)?(?![\\w.])/g;\n\nfunction maskMongoValues(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(maskMongoValues);\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).map(([key, inner]) => [key, maskMongoValues(inner)]),\n );\n }\n\n return value === null || value === undefined ? value : \"?\";\n}\n\nfunction redactMongoPlan(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactMongoPlan);\n if (value === null || typeof value !== \"object\") return value;\n\n return Object.fromEntries(\n Object.entries(value).map(([key, inner]) => [\n key,\n MONGO_VALUE_KEYS.has(key) ? maskMongoValues(inner) : redactMongoPlan(inner),\n ]),\n );\n}\n\nfunction redactSqlPlan(value: unknown): unknown {\n if (typeof value === \"string\") return value.replace(SQL_LITERAL, \"?\");\n if (Array.isArray(value)) return value.map(redactSqlPlan);\n if (value === null || typeof value !== \"object\") return value;\n\n return Object.fromEntries(\n Object.entries(value).map(([key, inner]) => [key, redactSqlPlan(inner)]),\n );\n}\n\n/**\n * A plan without the query's values. Plans repeat them: MongoDB echoes the\n * filter (`parsedQuery`, `indexBounds`, the command), PostgreSQL writes them\n * into conditions (`Filter: (email = 'a@b.c'::text)`). Values become `?`;\n * the plan's shape, costs, row counts and index choices stay.\n */\nexport function redactExplainPlan(plan: unknown, driver: string): unknown {\n return driver === \"mongodb\" ? redactMongoPlan(plan) : redactSqlPlan(plan);\n}\n\n/**\n * EXPLAIN by shape id from the examples `queries` kept, used by the production\n * capture and by development (`POST /api/queries/:shapeId/explain`). Plain\n * `EXPLAIN (FORMAT JSON)` / MongoDB `queryPlanner` unless `executing`; never\n * an executing plan for anything but a PostgreSQL `SELECT`/`WITH` or a\n * MongoDB `find`/`aggregate`/`count` (never an aggregate with `$out` or\n * `$merge`). `run` executes the statement on the query's own connection\n * (injected for specs; default: cascade's `dataSourceRegistry`, PostgreSQL\n * inside a read-only transaction that is always rolled back).\n */\nexport function createShapeExplainer(input: {\n queries: DevtoolsQueryStats;\n executing: boolean;\n instance: string;\n run?: ExplainRunner;\n /** Remove the query's values from the plan (`redactExplainPlan`); production sets it. */\n redact?: boolean;\n}): (shapeId: string) => Promise<DevtoolsExplainResult> {\n const run = input.run ?? runOnDataSource;\n\n return async (shapeId) => {\n const example = input.queries.example(shapeId);\n\n if (!example) throw new DevtoolsApiError(\"explain.elsewhere\", { instance: input.instance });\n\n const statement = statementFor(example, input.executing);\n\n if (!statement) throw new DevtoolsApiError(\"explain.unsupported\", { instance: input.instance });\n\n try {\n const plan = await run(example, statement);\n\n return {\n shapeId,\n driver: example.driver,\n executing: input.executing,\n plan: input.redact === true ? redactExplainPlan(plan, example.driver) : plan,\n instance: input.instance,\n };\n } catch (cause) {\n const ref = createErrorRef();\n\n log.error(\n \"devtools\",\n \"explain\",\n `EXPLAIN failed for query shape ${shapeId} (ref ${ref}): ${\n cause instanceof Error ? cause.message : String(cause)\n }`,\n );\n\n throw new DevtoolsApiError(\"explain.failed\", { ref, cause, instance: input.instance });\n }\n };\n}\n"],"mappings":";;;;;AAUA,MAAM,kBACJ;AAEF,MAAM,yBAAyB,cAC7B,cAAc,UAAa,6BAA6B,KAAK,SAAS;;AAGxE,SAAS,WAAW,KAAa,OAAuB;CACtD,IAAI,IAAI,WAAW,MAAM,KA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Q,QAAQ,IAAI,KACpD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAEzD;GAEA,MAAM,IAAI,iBAAiB,kBAAkB;IAAE;IAAK;IAAO,UAAU,MAAM;GAAS,CAAC;EACvF;CACF;AACF"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
//#region ../../packages/devtools/src/production/capture/filter.ts
|
|
2
|
+
/** Whether a stored sample's row passes a request filter (the same rules as the store). */
|
|
3
|
+
function sampleMatchesFilter(summary, filter) {
|
|
4
|
+
if (filter.status !== void 0 && !statusMatches(filter.status, summary.status)) return false;
|
|
5
|
+
if (filter.method !== void 0 && summary.method.toUpperCase() !== filter.method.toUpperCase()) return false;
|
|
6
|
+
if (filter.route !== void 0) {
|
|
7
|
+
if (!`${summary.route ?? ""} ${summary.path}`.toLowerCase().includes(filter.route.toLowerCase())) return false;
|
|
8
|
+
}
|
|
9
|
+
if (filter.q !== void 0 && !summary.path.toLowerCase().includes(filter.q.toLowerCase())) return false;
|
|
10
|
+
if (filter.since !== void 0 && summary.startedAt < filter.since) return false;
|
|
11
|
+
if (filter.until !== void 0 && summary.startedAt > filter.until) return false;
|
|
12
|
+
if (filter.instance !== void 0 && summary.instance !== filter.instance) return false;
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
function statusMatches(filter, status) {
|
|
16
|
+
if (status === void 0) return false;
|
|
17
|
+
const range = /^([1-5])xx$/i.exec(filter);
|
|
18
|
+
if (range) return Math.floor(status / 100) === Number(range[1]);
|
|
19
|
+
return status === Number(filter);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
//#endregion
|
|
23
|
+
export { sampleMatchesFilter };
|
|
24
|
+
//# sourceMappingURL=filter.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"filter.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/capture/filter.ts"],"sourcesContent":["import type { DevtoolsSampleSummary } from \"../contracts\";\nimport type { DevtoolsSampleFilter } from \"../store/types\";\n\n/** Whether a stored sample's row passes a request filter (the same rules as the store). */\nexport function sampleMatchesFilter(\n summary: DevtoolsSampleSummary,\n filter: DevtoolsSampleFilter,\n): boolean {\n if (filter.status !== undefined && !statusMatches(filter.status, summary.status)) return false;\n\n if (filter.method !== undefined && summary.method.toUpperCase() !== filter.method.toUpperCase()) {\n return false;\n }\n\n if (filter.route !== undefined) {\n const haystack = `${summary.route ?? \"\"} ${summary.path}`.toLowerCase();\n\n if (!haystack.includes(filter.route.toLowerCase())) return false;\n }\n\n if (filter.q !== undefined && !summary.path.toLowerCase().includes(filter.q.toLowerCase())) {\n return false;\n }\n\n if (filter.since !== undefined && summary.startedAt < filter.since) return false;\n if (filter.until !== undefined && summary.startedAt > filter.until) return false;\n if (filter.instance !== undefined && summary.instance !== filter.instance) return false;\n\n return true;\n}\n\nfunction statusMatches(filter: string, status: number | undefined): boolean {\n if (status === undefined) return false;\n\n const range = /^([1-5])xx$/i.exec(filter);\n\n if (range) return Math.floor(status / 100) === Number(range[1]);\n\n return status === Number(filter);\n}\n"],"mappings":";;AAIA,SAAgB,oBACd,SACA,QACS;CACT,IAAI,OAAO,WAAW,UAAa,CAAC,cAAc,OAAO,QAAQ,QAAQ,MAAM,GAAG,OAAO;CAEzF,IAAI,OAAO,WAAW,UAAa,QAAQ,OAAO,YAAY,MAAM,OAAO,OAAO,YAAY,GAC5F,OAAO;CAGT,IAAI,OAAO,UAAU,QAGnB;MAAI,CAFa,GAAG,QAAQ,SAAS,GAAG,GAAG,QAAQ,OAAO,YAE9C,CAAC,CAAC,SAAS,OAAO,MAAM,YAAY,CAAC,GAAG,OAAO;CAAK;CAGlE,IAAI,OAAO,MAAM,UAAa,CAAC,QAAQ,KAAK,YAAY,CAAC,CAAC,SAAS,OAAO,EAAE,YAAY,CAAC,GACvF,OAAO;CAGT,IAAI,OAAO,UAAU,UAAa,QAAQ,YAAY,OAAO,OAAO,OAAO;CAC3E,IAAI,OAAO,UAAU,UAAa,QAAQ,YAAY,OAAO,OAAO,OAAO;CAC3E,IAAI,OAAO,aAAa,UAAa,QAAQ,aAAa,OAAO,UAAU,OAAO;CAElF,OAAO;AACT;AAEA,SAAS,cAAc,QAAgB,QAAqC;CAC1E,IAAI,WAAW,QAAW,OAAO;CAEjC,MAAM,QAAQ,eAAe,KAAK,MAAM;CAExC,IAAI,OAAO,OAAO,KAAK,MAAM,SAAS,GAAG,MAAM,OAAO,MAAM,EAAE;CAE9D,OAAO,WAAW,OAAO,MAAM;AACjC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { attachDevelopmentStats } from "./dev-stats.mjs";
|
|
2
|
+
import { createShapeExplainer } from "./explain.mjs";
|
|
3
|
+
import { createErrorGroups, createQueryStats, createRecentLogs, createRouteStats } from "./stats-stores.mjs";
|
|
4
|
+
import { toStoredSample } from "./redact.mjs";
|
|
5
|
+
import { createProductionCapture } from "./production-capture.mjs";
|
|
6
|
+
|
|
7
|
+
export { attachDevelopmentStats, createErrorGroups, createProductionCapture, createQueryStats, createRecentLogs, createRouteStats, createShapeExplainer, toStoredSample };
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { scrubErrorText } from "./redact.mjs";
|
|
2
|
+
import { createCaptureEngine } from "./engine.mjs";
|
|
3
|
+
import { LogChannel, log } from "@warlock.js/logger";
|
|
4
|
+
|
|
5
|
+
//#region ../../packages/devtools/src/production/capture/production-capture.ts
|
|
6
|
+
/** Longest log message kept, as in the capture engine. */
|
|
7
|
+
const LOG_MESSAGE_MAX = 1e3;
|
|
8
|
+
/** Cache events counted for sampled requests. */
|
|
9
|
+
const CACHE_EVENT_TYPES = [
|
|
10
|
+
"hit",
|
|
11
|
+
"miss",
|
|
12
|
+
"set",
|
|
13
|
+
"removed",
|
|
14
|
+
"invalidated",
|
|
15
|
+
"flushed"
|
|
16
|
+
];
|
|
17
|
+
/** `LoggingData.type` includes `fatal`, which devtools folds into `error`. */
|
|
18
|
+
function toLevel(type) {
|
|
19
|
+
return type === "fatal" ? "error" : type;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The production capture of this process: sampling, the bounded in-memory
|
|
23
|
+
* ring of sampled requests (the live view), statistics, error groups, recent
|
|
24
|
+
* logs, the sample writer and EXPLAIN.
|
|
25
|
+
*
|
|
26
|
+
* Unsampled requests cost one random draw at start and one comparison at
|
|
27
|
+
* end; they add nothing to the statistics.
|
|
28
|
+
*/
|
|
29
|
+
function createProductionCapture(deps) {
|
|
30
|
+
const engine = createCaptureEngine({
|
|
31
|
+
...deps,
|
|
32
|
+
warn: deps.warn ?? ((message) => log.warn("devtools", "capture", message))
|
|
33
|
+
});
|
|
34
|
+
const { hooks } = engine;
|
|
35
|
+
let detach;
|
|
36
|
+
const warnFailed = (name, error) => {
|
|
37
|
+
log.warn("devtools", "capture", `devtools' ${name} capture failed to attach: ${error instanceof Error ? error.message : String(error)}`);
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
collector: engine.collector,
|
|
41
|
+
queries: engine.queries,
|
|
42
|
+
routes: engine.routes,
|
|
43
|
+
errors: engine.errors,
|
|
44
|
+
logs: engine.logs,
|
|
45
|
+
requests: engine.requests,
|
|
46
|
+
counters: engine.counters,
|
|
47
|
+
explain: engine.explain,
|
|
48
|
+
flush: engine.flush,
|
|
49
|
+
async attach() {
|
|
50
|
+
if (detach) return detach;
|
|
51
|
+
const disposers = [];
|
|
52
|
+
const { currentRequestId } = await import("../../current-request-id.mjs");
|
|
53
|
+
try {
|
|
54
|
+
const { registerTracingHooks } = await import("@warlock.js/core");
|
|
55
|
+
disposers.push(registerTracingHooks({
|
|
56
|
+
onRequestStart: hooks.onRequestStart,
|
|
57
|
+
onPhase: hooks.onPhase,
|
|
58
|
+
onRequestEnd: hooks.onRequestEnd
|
|
59
|
+
}));
|
|
60
|
+
} catch (error) {
|
|
61
|
+
warnFailed("request", error);
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
let dataSourceRegistry;
|
|
65
|
+
({dataSourceRegistry} = await import("@warlock.js/cascade"));
|
|
66
|
+
const listener = (event) => hooks.onQuery(currentRequestId(), event);
|
|
67
|
+
dataSourceRegistry.on("query", listener);
|
|
68
|
+
disposers.push(() => dataSourceRegistry.off("query", listener));
|
|
69
|
+
} catch {}
|
|
70
|
+
try {
|
|
71
|
+
const channel = new class extends LogChannel {
|
|
72
|
+
constructor(..._args) {
|
|
73
|
+
super(..._args);
|
|
74
|
+
this.name = "devtools-monitor";
|
|
75
|
+
this.active = true;
|
|
76
|
+
}
|
|
77
|
+
log(data) {
|
|
78
|
+
if (!this.active) return;
|
|
79
|
+
const level = toLevel(data.type);
|
|
80
|
+
const text = typeof data.message === "string" ? data.message : String(data.message);
|
|
81
|
+
hooks.onLog(currentRequestId(), {
|
|
82
|
+
level,
|
|
83
|
+
module: data.module,
|
|
84
|
+
action: data.action,
|
|
85
|
+
message: level === "error" ? scrubErrorText(text, LOG_MESSAGE_MAX) : text,
|
|
86
|
+
at: Date.now()
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}();
|
|
90
|
+
log.addChannel(channel);
|
|
91
|
+
disposers.push(() => {
|
|
92
|
+
channel.active = false;
|
|
93
|
+
});
|
|
94
|
+
} catch (error) {
|
|
95
|
+
warnFailed("log", error);
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
let cache;
|
|
99
|
+
({cache} = await import("@warlock.js/cache"));
|
|
100
|
+
const handlers = CACHE_EVENT_TYPES.map((type) => {
|
|
101
|
+
const handler = (data) => hooks.onCache(currentRequestId(), {
|
|
102
|
+
type,
|
|
103
|
+
driver: data.driver,
|
|
104
|
+
at: Date.now()
|
|
105
|
+
});
|
|
106
|
+
cache.on(type, handler);
|
|
107
|
+
return {
|
|
108
|
+
type,
|
|
109
|
+
handler
|
|
110
|
+
};
|
|
111
|
+
});
|
|
112
|
+
disposers.push(() => {
|
|
113
|
+
for (const { type, handler } of handlers) cache.off(type, handler);
|
|
114
|
+
});
|
|
115
|
+
} catch {}
|
|
116
|
+
engine.startWriter();
|
|
117
|
+
const dispose = () => {
|
|
118
|
+
for (const disposer of disposers.splice(0)) disposer();
|
|
119
|
+
engine.stopWriter();
|
|
120
|
+
detach = void 0;
|
|
121
|
+
};
|
|
122
|
+
detach = dispose;
|
|
123
|
+
return dispose;
|
|
124
|
+
},
|
|
125
|
+
async dispose() {
|
|
126
|
+
detach?.();
|
|
127
|
+
await engine.flush();
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
//#endregion
|
|
133
|
+
export { createProductionCapture };
|
|
134
|
+
//# sourceMappingURL=production-capture.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"production-capture.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/capture/production-capture.ts"],"sourcesContent":["import { LogChannel, log, type LoggingData } from \"@warlock.js/logger\";\nimport type { DevtoolsDisposer, DevtoolsLogEntry } from \"../../types\";\nimport { scrubErrorText } from \"./redact\";\nimport { createCaptureEngine, type DevtoolsQueryEvent } from \"./engine\";\nimport type { DevtoolsCaptureDeps, DevtoolsProductionCapture } from \"./types\";\n\n/** Longest log message kept, as in the capture engine. */\nconst LOG_MESSAGE_MAX = 1000;\n\n/** Cache events counted for sampled requests. */\nconst CACHE_EVENT_TYPES = [\"hit\", \"miss\", \"set\", \"removed\", \"invalidated\", \"flushed\"] as const;\n\ntype CacheEventData = {\n key?: string;\n driver: string;\n tags?: string[];\n keys?: string[];\n durationMs?: number;\n};\n\n/** `LoggingData.type` includes `fatal`, which devtools folds into `error`. */\nfunction toLevel(type: LoggingData[\"type\"]): DevtoolsLogEntry[\"level\"] {\n return type === \"fatal\" ? \"error\" : type;\n}\n\n/**\n * The production capture of this process: sampling, the bounded in-memory\n * ring of sampled requests (the live view), statistics, error groups, recent\n * logs, the sample writer and EXPLAIN.\n *\n * Unsampled requests cost one random draw at start and one comparison at\n * end; they add nothing to the statistics.\n */\nexport function createProductionCapture(deps: DevtoolsCaptureDeps): DevtoolsProductionCapture {\n const engine = createCaptureEngine({\n ...deps,\n warn: deps.warn ?? ((message) => log.warn(\"devtools\", \"capture\", message)),\n });\n const { hooks } = engine;\n let detach: DevtoolsDisposer | undefined;\n\n const warnFailed = (name: string, error: unknown) => {\n log.warn(\n \"devtools\",\n \"capture\",\n `devtools' ${name} capture failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n };\n\n return {\n collector: engine.collector,\n queries: engine.queries,\n routes: engine.routes,\n errors: engine.errors,\n logs: engine.logs,\n requests: engine.requests,\n counters: engine.counters,\n explain: engine.explain,\n flush: engine.flush,\n\n async attach() {\n if (detach) return detach;\n\n const disposers: DevtoolsDisposer[] = [];\n\n // Reached only here so a process that never enables the monitor never loads core.\n const { currentRequestId } = await import(\"../../current-request-id\");\n\n try {\n const { registerTracingHooks } = await import(\"@warlock.js/core\");\n\n disposers.push(\n registerTracingHooks({\n onRequestStart: hooks.onRequestStart,\n onPhase: hooks.onPhase,\n onRequestEnd: hooks.onRequestEnd,\n }),\n );\n } catch (error) {\n warnFailed(\"request\", error);\n }\n\n try {\n let dataSourceRegistry: {\n on(event: \"query\", listener: (event: DevtoolsQueryEvent) => void): void;\n off(event: \"query\", listener: (event: DevtoolsQueryEvent) => void): void;\n };\n\n ({ dataSourceRegistry } = await import(\"@warlock.js/cascade\"));\n\n const listener = (event: DevtoolsQueryEvent) => hooks.onQuery(currentRequestId(), event);\n\n dataSourceRegistry.on(\"query\", listener);\n disposers.push(() => dataSourceRegistry.off(\"query\", listener));\n } catch {\n // Cascade is an optional peer: without it there are no queries to capture.\n }\n\n try {\n const channel = new (class extends LogChannel {\n public override name = \"devtools-monitor\";\n public active = true;\n\n public log(data: LoggingData): void {\n if (!this.active) return;\n\n const level = toLevel(data.type);\n const text = typeof data.message === \"string\" ? data.message : String(data.message);\n\n hooks.onLog(currentRequestId(), {\n level,\n module: data.module,\n action: data.action,\n // Error lines feed the Errors tab's groups: they lose quoted values, emails and documents.\n message: level === \"error\" ? scrubErrorText(text, LOG_MESSAGE_MAX) : text,\n at: Date.now(),\n });\n }\n })();\n\n log.addChannel(channel);\n // `Logger` cannot remove a channel: a disposed one ignores further entries.\n disposers.push(() => {\n channel.active = false;\n });\n } catch (error) {\n warnFailed(\"log\", error);\n }\n\n try {\n let cache: {\n on(\n event: (typeof CACHE_EVENT_TYPES)[number],\n handler: (data: CacheEventData) => void,\n ): unknown;\n off(\n event: (typeof CACHE_EVENT_TYPES)[number],\n handler: (data: CacheEventData) => void,\n ): unknown;\n };\n\n ({ cache } = await import(\"@warlock.js/cache\"));\n\n const handlers = CACHE_EVENT_TYPES.map((type) => {\n const handler = (data: CacheEventData) =>\n hooks.onCache(currentRequestId(), { type, driver: data.driver, at: Date.now() });\n\n cache.on(type, handler);\n\n return { type, handler };\n });\n\n disposers.push(() => {\n for (const { type, handler } of handlers) cache.off(type, handler);\n });\n } catch {\n // The cache package is an optional peer.\n }\n\n engine.startWriter();\n\n const dispose: DevtoolsDisposer = () => {\n for (const disposer of disposers.splice(0)) disposer();\n\n engine.stopWriter();\n detach = undefined;\n };\n\n detach = dispose;\n\n return dispose;\n },\n\n async dispose() {\n detach?.();\n await engine.flush();\n },\n };\n}\n"],"mappings":";;;;;;AAOA,MAAM,kBAAkB;;AAGxB,MAAM,oBAAoB;CAAC;CAAO;CAAQ;CAAO;CAAW;CAAe;AAAS;;AAWpF,SAAS,QAAQ,MAAsD;CACrE,OAAO,SAAS,UAAU,UAAU;AACtC;;;;;;;;;AAUA,SAAgB,wBAAwB,MAAsD;CAC5F,MAAM,SAAS,oBAAoB;EACjC,GAAG;EACH,MAAM,KAAK,UAAU,YAAY,IAAI,KAAK,YAAY,WAAW,OAAO;CAC1E,CAAC;CACD,MAAM,EAAE,UAAU;CAClB,IAAI;CAEJ,MAAM,cAAc,MAAc,UAAmB;EACnD,IAAI,KACF,YACA,WACA,aAAa,KAAK,6BAA6B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,K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AO,KAAK;GACzB;GAEA,IAAI;IACF,IAAI;IAWJ,CAAC,CAAE,SAAU,MAAM,OAAO;IAE1B,MAAM,WAAW,kBAAkB,KAAK,SAAS;KAC/C,MAAM,WAAW,SACf,MAAM,QAAQ,iBAAiB,GAAG;MAAE;MAAM,QAAQ,KAAK;MAAQ,IAAI,KAAK,IAAI;KAAE,CAAC;KAEjF,MAAM,GAAG,MAAM,OAAO;KAEtB,OAAO;MAAE;MAAM;KAAQ;IACzB,CAAC;IAED,UAAU,WAAW;KACnB,KAAK,MAAM,EAAE,MAAM,aAAa,UAAU,MAAM,IAAI,MAAM,OAAO;IACnE,CAAC;GACH,QAAQ,CAER;GAEA,OAAO,YAAY;GAEnB,MAAM,gBAAkC;IACtC,KAAK,MAAM,YAAY,UAAU,OAAO,CAAC,GAAG,SAAS;IAErD,OAAO,WAAW;IAClB,SAAS;GACX;GAEA,SAAS;GAET,OAAO;EACT;EAEA,MAAM,UAAU;GACd,SAAS;GACT,MAAM,OAAO,MAAM;EACrB;CACF;AACF"}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { queryShape } from "../../query-shape.mjs";
|
|
2
|
+
import { shapeIdOf, truncate } from "./stats-stores.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../../packages/devtools/src/production/capture/redact.ts
|
|
5
|
+
const SHAPE_MAX = 2e3;
|
|
6
|
+
const ERROR_MAX = 500;
|
|
7
|
+
const QUERY_ERROR_MAX = 300;
|
|
8
|
+
const LOG_MESSAGE_MAX = 1e3;
|
|
9
|
+
const QUOTED = /'(?:''|[^'])*'|"(?:\\.|[^"\\])*"/g;
|
|
10
|
+
const BRACES = /\{[^{}]*\}/g;
|
|
11
|
+
const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
|
|
12
|
+
/**
|
|
13
|
+
* Error text without the values a driver or a handler put in it (a duplicate
|
|
14
|
+
* key message carries the key): quoted strings, emails and `{ … }` documents
|
|
15
|
+
* become `?`, then the text is cut to `max` characters.
|
|
16
|
+
*/
|
|
17
|
+
function scrubErrorText(text, max) {
|
|
18
|
+
return truncate(text.replace(QUOTED, "?").replace(EMAIL, "?").replace(BRACES, "{?}"), max);
|
|
19
|
+
}
|
|
20
|
+
/** A database error message without the values the driver quoted in it. */
|
|
21
|
+
function scrubQueryError(message) {
|
|
22
|
+
return scrubErrorText(message, QUERY_ERROR_MAX);
|
|
23
|
+
}
|
|
24
|
+
function redactQuery(query) {
|
|
25
|
+
const shape = truncate(query.shape || queryShape(query), SHAPE_MAX);
|
|
26
|
+
const sample = {
|
|
27
|
+
id: query.id,
|
|
28
|
+
connection: query.connection,
|
|
29
|
+
driver: query.driver,
|
|
30
|
+
sql: shape,
|
|
31
|
+
shape,
|
|
32
|
+
shapeId: shapeIdOf(query.shape || shape),
|
|
33
|
+
startedAt: query.startedAt,
|
|
34
|
+
durationMs: query.durationMs
|
|
35
|
+
};
|
|
36
|
+
if (query.collection !== void 0) sample.collection = query.collection;
|
|
37
|
+
if (query.command !== void 0) sample.command = query.command;
|
|
38
|
+
if (query.rowCount !== void 0) sample.rowCount = query.rowCount;
|
|
39
|
+
if (query.error !== void 0) sample.error = scrubQueryError(query.error);
|
|
40
|
+
return sample;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Turns a sampled request into a stored sample with every value removed: SQL
|
|
44
|
+
* replaced by its shape, no bindings, no Mongo pipeline, no log context, no
|
|
45
|
+
* phase attributes, cache operations reduced to counts, no caller paths.
|
|
46
|
+
* Headers, bodies, query strings and parameters are not part of a request
|
|
47
|
+
* record and never appear.
|
|
48
|
+
*/
|
|
49
|
+
function toStoredSample(request, instance, droppedQueries) {
|
|
50
|
+
const path = request.path.split("?")[0] ?? request.path;
|
|
51
|
+
const summary = {
|
|
52
|
+
id: request.id,
|
|
53
|
+
method: request.method,
|
|
54
|
+
path,
|
|
55
|
+
startedAt: request.startedAt,
|
|
56
|
+
queryCount: request.queries.length + droppedQueries,
|
|
57
|
+
warningCount: request.warnings.length,
|
|
58
|
+
instance
|
|
59
|
+
};
|
|
60
|
+
if (request.route !== void 0) summary.route = request.route;
|
|
61
|
+
if (request.status !== void 0) summary.status = request.status;
|
|
62
|
+
if (request.durationMs !== void 0) summary.durationMs = request.durationMs;
|
|
63
|
+
let hits = 0;
|
|
64
|
+
let misses = 0;
|
|
65
|
+
let writes = 0;
|
|
66
|
+
for (const operation of request.cache) if (operation.type === "hit") hits++;
|
|
67
|
+
else if (operation.type === "miss") misses++;
|
|
68
|
+
else if (operation.type === "set") writes++;
|
|
69
|
+
const detail = {
|
|
70
|
+
...summary,
|
|
71
|
+
phases: request.phases.map((phase) => ({
|
|
72
|
+
name: phase.name,
|
|
73
|
+
startedAt: phase.startedAt,
|
|
74
|
+
durationMs: phase.durationMs
|
|
75
|
+
})),
|
|
76
|
+
queries: request.queries.map(redactQuery),
|
|
77
|
+
cache: {
|
|
78
|
+
hits,
|
|
79
|
+
misses,
|
|
80
|
+
writes
|
|
81
|
+
},
|
|
82
|
+
logs: request.logs.map((entry) => ({
|
|
83
|
+
level: entry.level,
|
|
84
|
+
module: entry.module,
|
|
85
|
+
action: entry.action,
|
|
86
|
+
message: truncate(entry.message, LOG_MESSAGE_MAX),
|
|
87
|
+
at: entry.at
|
|
88
|
+
})),
|
|
89
|
+
warnings: request.warnings.map((warning) => ({
|
|
90
|
+
type: warning.type,
|
|
91
|
+
message: warning.message,
|
|
92
|
+
shape: truncate(warning.shape, SHAPE_MAX),
|
|
93
|
+
count: warning.count
|
|
94
|
+
})),
|
|
95
|
+
droppedQueries
|
|
96
|
+
};
|
|
97
|
+
if (request.error !== void 0) detail.error = scrubErrorText(request.error, ERROR_MAX);
|
|
98
|
+
return {
|
|
99
|
+
id: request.id,
|
|
100
|
+
instance,
|
|
101
|
+
startedAt: request.startedAt,
|
|
102
|
+
summary,
|
|
103
|
+
detail
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
//#endregion
|
|
108
|
+
export { scrubErrorText, scrubQueryError, toStoredSample };
|
|
109
|
+
//# sourceMappingURL=redact.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redact.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/capture/redact.ts"],"sourcesContent":["import type {\n DevtoolsSampleDetail,\n DevtoolsSampleQuery,\n DevtoolsSampleSummary,\n} from \"../contracts\";\nimport type { DevtoolsStoredSample } from \"../store/types\";\nimport type { DevtoolsQuery, DevtoolsRequest } from \"../../types\";\nimport { queryShape } from \"../../query-shape\";\nimport { shapeIdOf, truncate } from \"./stats-stores\";\n\nconst SHAPE_MAX = 2000;\nconst ERROR_MAX = 500;\nconst QUERY_ERROR_MAX = 300;\nconst LOG_MESSAGE_MAX = 1000;\n\nconst QUOTED = /'(?:''|[^'])*'|\"(?:\\\\.|[^\"\\\\])*\"/g;\nconst BRACES = /\\{[^{}]*\\}/g;\nconst EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/g;\n\n/**\n * Error text without the values a driver or a handler put in it (a duplicate\n * key message carries the key): quoted strings, emails and `{ … }` documents\n * become `?`, then the text is cut to `max` characters.\n */\nexport function scrubErrorText(text: string, max: number): string {\n return truncate(text.replace(QUOTED, \"?\").replace(EMAIL, \"?\").replace(BRACES, \"{?}\"), max);\n}\n\n/** A database error message without the values the driver quoted in it. */\nexport function scrubQueryError(message: string): string {\n return scrubErrorText(message, QUERY_ERROR_MAX);\n}\n\nfunction redactQuery(query: DevtoolsQuery): DevtoolsSampleQuery {\n const shape = truncate(query.shape || queryShape(query), SHAPE_MAX);\n const sample: DevtoolsSampleQuery = {\n id: query.id,\n connection: query.connection,\n driver: query.driver,\n sql: shape,\n shape,\n shapeId: shapeIdOf(query.shape || shape),\n startedAt: query.startedAt,\n durationMs: query.durationMs,\n };\n\n if (query.collection !== undefined) sample.collection = query.collection;\n if (query.command !== undefined) sample.command = query.command;\n if (query.rowCount !== undefined) sample.rowCount = query.rowCount;\n if (query.error !== undefined) sample.error = scrubQueryError(query.error);\n\n return sample;\n}\n\n/**\n * Turns a sampled request into a stored sample with every value removed: SQL\n * replaced by its shape, no bindings, no Mongo pipeline, no log context, no\n * phase attributes, cache operations reduced to counts, no caller paths.\n * Headers, bodies, query strings and parameters are not part of a request\n * record and never appear.\n */\nexport function toStoredSample(\n request: DevtoolsRequest,\n instance: string,\n droppedQueries: number,\n): DevtoolsStoredSample {\n const path = request.path.split(\"?\")[0] ?? request.path;\n const summary: DevtoolsSampleSummary = {\n id: request.id,\n method: request.method,\n path,\n startedAt: request.startedAt,\n queryCount: request.queries.length + droppedQueries,\n warningCount: request.warnings.length,\n instance,\n };\n\n if (request.route !== undefined) summary.route = request.route;\n if (request.status !== undefined) summary.status = request.status;\n if (request.durationMs !== undefined) summary.durationMs = request.durationMs;\n\n let hits = 0;\n let misses = 0;\n let writes = 0;\n\n for (const operation of request.cache) {\n if (operation.type === \"hit\") hits++;\n else if (operation.type === \"miss\") misses++;\n else if (operation.type === \"set\") writes++;\n }\n\n const detail: DevtoolsSampleDetail = {\n ...summary,\n phases: request.phases.map((phase) => ({\n name: phase.name,\n startedAt: phase.startedAt,\n durationMs: phase.durationMs,\n })),\n queries: request.queries.map(redactQuery),\n cache: { hits, misses, writes },\n logs: request.logs.map((entry) => ({\n level: entry.level,\n module: entry.module,\n action: entry.action,\n message: truncate(entry.message, LOG_MESSAGE_MAX),\n at: entry.at,\n })),\n warnings: request.warnings.map((warning) => ({\n type: warning.type,\n message: warning.message,\n shape: truncate(warning.shape, SHAPE_MAX),\n count: warning.count,\n })),\n droppedQueries,\n };\n\n if (request.error !== undefined) detail.error = scrubErrorText(request.error, ERROR_MAX);\n\n return { id: request.id, instance, startedAt: request.startedAt, summary, detail };\n}\n"],"mappings":";;;;AAUA,MAAM,YAAY;AAClB,MAAM,YAAY;AAClB,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AAExB,MAAM,SAAS;AACf,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