@reqray/cli 0.0.0-stage → 0.1.1
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/DESIGN.md +350 -0
- package/LICENSE +21 -0
- package/README.md +59 -2
- package/dist/chunk-V6ZCA7CU.js +1625 -0
- package/dist/chunk-V6ZCA7CU.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +21 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +367 -0
- package/dist/index.js +49 -0
- package/dist/index.js.map +1 -0
- package/package.json +59 -3
|
@@ -0,0 +1,1625 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var EXIT_OK = 0;
|
|
3
|
+
var EXIT_FAILED = 1;
|
|
4
|
+
var EXIT_USAGE = 2;
|
|
5
|
+
var CliError = class extends Error {
|
|
6
|
+
exitCode;
|
|
7
|
+
/**
|
|
8
|
+
* Lines printed under the headline: what to check, what to run next.
|
|
9
|
+
*
|
|
10
|
+
* Rendered as given, so they carry their own indentation.
|
|
11
|
+
*/
|
|
12
|
+
hints;
|
|
13
|
+
constructor(message, options = {}) {
|
|
14
|
+
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
15
|
+
this.name = "CliError";
|
|
16
|
+
this.exitCode = options.exitCode ?? EXIT_FAILED;
|
|
17
|
+
this.hints = options.hints ?? [];
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
var UsageError = class extends CliError {
|
|
21
|
+
constructor(message, hints = []) {
|
|
22
|
+
super(message, { exitCode: EXIT_USAGE, hints });
|
|
23
|
+
this.name = "UsageError";
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
var UnreachableError = class extends CliError {
|
|
27
|
+
constructor(url, cause) {
|
|
28
|
+
super("cannot reach the collector", {
|
|
29
|
+
exitCode: EXIT_FAILED,
|
|
30
|
+
hints: [
|
|
31
|
+
"",
|
|
32
|
+
" the panel is served by your app. check that",
|
|
33
|
+
" 1 reqray is attached reqray({ panel: true }) before the routes",
|
|
34
|
+
" 2 the app is running and that NODE_ENV is not production",
|
|
35
|
+
` 3 the address matches REQRAY_URL=${url}`
|
|
36
|
+
],
|
|
37
|
+
cause
|
|
38
|
+
});
|
|
39
|
+
this.name = "UnreachableError";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
function causeOf(error) {
|
|
43
|
+
const cause = error instanceof Error ? error.cause ?? null : null;
|
|
44
|
+
if (cause instanceof Error) {
|
|
45
|
+
const inner = cause.cause;
|
|
46
|
+
return inner instanceof Error ? `${cause.message} \u2014 ${inner.message}` : cause.message;
|
|
47
|
+
}
|
|
48
|
+
return cause === null ? null : String(cause);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/client.ts
|
|
52
|
+
function parsePrintable(text) {
|
|
53
|
+
return JSON.parse(
|
|
54
|
+
text,
|
|
55
|
+
(_key, value) => typeof value === "string" ? value.replace(new RegExp("(?![\\t\\n])\\p{Cc}", "gu"), "") : value
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
var BACKOFF_START = 500;
|
|
59
|
+
var BACKOFF_MAX = 1e4;
|
|
60
|
+
var wait = (ms) => new Promise((resolve) => {
|
|
61
|
+
const timer = setTimeout(resolve, ms);
|
|
62
|
+
timer.unref?.();
|
|
63
|
+
});
|
|
64
|
+
var ReqrayClient = class {
|
|
65
|
+
#url;
|
|
66
|
+
#token;
|
|
67
|
+
#fetch;
|
|
68
|
+
constructor(options) {
|
|
69
|
+
this.#url = options.url.replace(/\/+$/, "");
|
|
70
|
+
this.#token = options.token ?? null;
|
|
71
|
+
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
72
|
+
}
|
|
73
|
+
/** The panel's address, as it was resolved. */
|
|
74
|
+
get url() {
|
|
75
|
+
return this.#url;
|
|
76
|
+
}
|
|
77
|
+
/** What the process behind the panel is. */
|
|
78
|
+
async meta(signal) {
|
|
79
|
+
return this.#json("/api/meta", signal);
|
|
80
|
+
}
|
|
81
|
+
/** One page of the list. */
|
|
82
|
+
async list(query = {}, signal) {
|
|
83
|
+
return this.#json(`/api/requests${searchOf(query)}`, signal);
|
|
84
|
+
}
|
|
85
|
+
/** One request, whole. */
|
|
86
|
+
async detail(id, signal) {
|
|
87
|
+
return this.#json(`/api/requests/${encodeURIComponent(id)}`, signal);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* How the request compares against its route's own history, and whether
|
|
91
|
+
* the process underneath was struggling at the time.
|
|
92
|
+
*
|
|
93
|
+
* Empty when there is nothing to compare against, and empty too when the
|
|
94
|
+
* collector is older than the endpoint: a verdict is worth printing when it
|
|
95
|
+
* is there and worth nothing said when it is not.
|
|
96
|
+
*/
|
|
97
|
+
async baseline(id, signal) {
|
|
98
|
+
try {
|
|
99
|
+
return await this.#json(
|
|
100
|
+
`/api/requests/${encodeURIComponent(id)}/baseline`,
|
|
101
|
+
signal
|
|
102
|
+
);
|
|
103
|
+
} catch {
|
|
104
|
+
return { baseline: null, pressure: null };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** The same, unparsed — what `--json` prints. */
|
|
108
|
+
async detailRaw(id, signal) {
|
|
109
|
+
const response = await this.#get(`/api/requests/${encodeURIComponent(id)}`, signal);
|
|
110
|
+
const text = await response.text();
|
|
111
|
+
if (!response.ok) throw await refusal(response.status, text);
|
|
112
|
+
return text;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* The live feed, until the signal is aborted.
|
|
116
|
+
*
|
|
117
|
+
* A dropped connection is reported and retried with a doubling delay: the
|
|
118
|
+
* application restarting is the common case, and a client that dies with it
|
|
119
|
+
* is a client nobody leaves running.
|
|
120
|
+
*/
|
|
121
|
+
async stream(handlers) {
|
|
122
|
+
const sleep = handlers.sleep ?? wait;
|
|
123
|
+
let backoff = BACKOFF_START;
|
|
124
|
+
let attempt = 0;
|
|
125
|
+
while (!handlers.signal.aborted) {
|
|
126
|
+
try {
|
|
127
|
+
const response = await this.#get("/api/stream", handlers.signal, {
|
|
128
|
+
accept: "text/event-stream"
|
|
129
|
+
});
|
|
130
|
+
if (!response.ok || !response.body) {
|
|
131
|
+
throw await refusal(response.status, await response.text());
|
|
132
|
+
}
|
|
133
|
+
backoff = BACKOFF_START;
|
|
134
|
+
if (attempt > 0) handlers.onNotice("reconnected");
|
|
135
|
+
attempt = 0;
|
|
136
|
+
await readEvents(response.body, handlers);
|
|
137
|
+
if (handlers.signal.aborted) return;
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (handlers.signal.aborted) return;
|
|
140
|
+
if (error instanceof CliError && !(error instanceof UnreachableError)) throw error;
|
|
141
|
+
}
|
|
142
|
+
if (handlers.signal.aborted) return;
|
|
143
|
+
attempt++;
|
|
144
|
+
handlers.onNotice(
|
|
145
|
+
`connection lost, reconnecting in ${seconds(backoff)} (attempt ${attempt})`
|
|
146
|
+
);
|
|
147
|
+
await sleep(backoff);
|
|
148
|
+
backoff = Math.min(backoff * 2, BACKOFF_MAX);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async #json(path, signal) {
|
|
152
|
+
const response = await this.#get(path, signal);
|
|
153
|
+
const text = await response.text();
|
|
154
|
+
if (!response.ok) throw await refusal(response.status, text);
|
|
155
|
+
try {
|
|
156
|
+
return parsePrintable(text);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
throw new CliError(`the panel answered something that is not JSON (${path})`, {
|
|
159
|
+
cause: error
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
async #get(path, signal, headers = {}) {
|
|
164
|
+
const request = {
|
|
165
|
+
headers: this.#token ? { ...headers, "x-reqray-token": this.#token } : headers,
|
|
166
|
+
...signal ? { signal } : {}
|
|
167
|
+
};
|
|
168
|
+
try {
|
|
169
|
+
return await this.#fetch(`${this.#url}${path}`, request);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (signal?.aborted) throw error;
|
|
172
|
+
throw new UnreachableError(this.#url, error);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
async function refusal(status, body) {
|
|
177
|
+
let message = body.trim();
|
|
178
|
+
try {
|
|
179
|
+
const parsed = JSON.parse(body);
|
|
180
|
+
if (typeof parsed.error === "string") message = parsed.error;
|
|
181
|
+
} catch {
|
|
182
|
+
}
|
|
183
|
+
if (status === 404) {
|
|
184
|
+
return new CliError(message || "no such request \u2014 it may have left the buffer already");
|
|
185
|
+
}
|
|
186
|
+
if (status === 401 || status === 403) {
|
|
187
|
+
return new CliError(`the panel refused: ${message || "access denied"}`, {
|
|
188
|
+
hints: [
|
|
189
|
+
"",
|
|
190
|
+
" a collector started with a token wants it back:",
|
|
191
|
+
" reqray watch --token <token> or REQRAY_TOKEN=<token>"
|
|
192
|
+
]
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return new CliError(message || `the panel answered ${status}`);
|
|
196
|
+
}
|
|
197
|
+
function searchOf(query) {
|
|
198
|
+
const params = new URLSearchParams();
|
|
199
|
+
if (query.limit !== void 0) params.set("limit", String(query.limit));
|
|
200
|
+
if (query.query) params.set("q", query.query);
|
|
201
|
+
if (query.cursor) params.set("cursor", query.cursor);
|
|
202
|
+
if (query.minDurationMs !== void 0) params.set("minDurationMs", String(query.minDurationMs));
|
|
203
|
+
if (query.methods?.length) params.set("method", query.methods.join(","));
|
|
204
|
+
if (query.statusClasses?.length) params.set("status", query.statusClasses.join(","));
|
|
205
|
+
if (query.onlyFindings) params.set("findings", "1");
|
|
206
|
+
if (query.onlyErrors) params.set("errors", "1");
|
|
207
|
+
if (query.sort) params.set("sort", query.sort);
|
|
208
|
+
const search = params.toString();
|
|
209
|
+
return search ? `?${search}` : "";
|
|
210
|
+
}
|
|
211
|
+
async function readEvents(body, handlers) {
|
|
212
|
+
const reader = body.getReader();
|
|
213
|
+
const decoder = new TextDecoder();
|
|
214
|
+
let buffered = "";
|
|
215
|
+
const stop = () => void reader.cancel().catch(() => {
|
|
216
|
+
});
|
|
217
|
+
handlers.signal.addEventListener("abort", stop, { once: true });
|
|
218
|
+
try {
|
|
219
|
+
while (!handlers.signal.aborted) {
|
|
220
|
+
const { done, value } = await reader.read();
|
|
221
|
+
if (done) return;
|
|
222
|
+
buffered += decoder.decode(value, { stream: true });
|
|
223
|
+
let split = buffered.indexOf("\n\n");
|
|
224
|
+
while (split !== -1) {
|
|
225
|
+
const event = buffered.slice(0, split);
|
|
226
|
+
buffered = buffered.slice(split + 2);
|
|
227
|
+
const payload = dataOf(event);
|
|
228
|
+
if (payload !== null) {
|
|
229
|
+
try {
|
|
230
|
+
handlers.onRow(parsePrintable(payload));
|
|
231
|
+
} catch {
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
split = buffered.indexOf("\n\n");
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
} finally {
|
|
238
|
+
handlers.signal.removeEventListener("abort", stop);
|
|
239
|
+
reader.releaseLock();
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
function dataOf(event) {
|
|
243
|
+
const lines = event.split("\n").filter((line) => line.startsWith("data:"));
|
|
244
|
+
if (lines.length === 0) return null;
|
|
245
|
+
return lines.map((line) => line.slice(5).trimStart()).join("\n");
|
|
246
|
+
}
|
|
247
|
+
function seconds(ms) {
|
|
248
|
+
return ms >= 1e3 ? `${Math.round(ms / 100) / 10} s` : `${ms} ms`;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// src/render/width.ts
|
|
252
|
+
var MIN_WIDTH = 56;
|
|
253
|
+
var PATH_FLOOR = 21;
|
|
254
|
+
var FIXED = 51;
|
|
255
|
+
var QUERIES = 5;
|
|
256
|
+
var STATUS = 4;
|
|
257
|
+
var IDS = 13;
|
|
258
|
+
function streamColumns(width, ids = false) {
|
|
259
|
+
const room = width - (ids ? IDS : 0);
|
|
260
|
+
if (room - FIXED >= PATH_FLOOR) {
|
|
261
|
+
return { path: room - FIXED, queries: true, status: true, ids };
|
|
262
|
+
}
|
|
263
|
+
if (room - FIXED + QUERIES >= PATH_FLOOR - 3) {
|
|
264
|
+
return { path: room - FIXED + QUERIES, queries: false, status: true, ids };
|
|
265
|
+
}
|
|
266
|
+
return {
|
|
267
|
+
path: Math.max(8, room - FIXED + QUERIES + STATUS),
|
|
268
|
+
queries: false,
|
|
269
|
+
status: false,
|
|
270
|
+
ids
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function pad(text, width) {
|
|
274
|
+
return text.length >= width ? text.slice(0, width) : text + " ".repeat(width - text.length);
|
|
275
|
+
}
|
|
276
|
+
function padStart(text, width) {
|
|
277
|
+
return text.length >= width ? text.slice(-width) : " ".repeat(width - text.length) + text;
|
|
278
|
+
}
|
|
279
|
+
function cut(text, width, ellipsis) {
|
|
280
|
+
if (text.length <= width) return text;
|
|
281
|
+
if (width <= ellipsis.length) return text.slice(0, width);
|
|
282
|
+
return text.slice(0, width - ellipsis.length) + ellipsis;
|
|
283
|
+
}
|
|
284
|
+
function fitPath(path, query, width, ellipsis) {
|
|
285
|
+
const whole = query ? `${path}?${query}` : path;
|
|
286
|
+
if (whole.length <= width) return whole;
|
|
287
|
+
const marker = query ? `?${ellipsis}` : "";
|
|
288
|
+
if (path.length + marker.length <= width) return path + marker;
|
|
289
|
+
const segments = path.split("/").filter(Boolean);
|
|
290
|
+
const head = segments[0] ?? "";
|
|
291
|
+
const tail = segments.slice(1);
|
|
292
|
+
for (const withHead of [true, false]) {
|
|
293
|
+
const prefix = withHead ? `/${head}/${ellipsis}` : `/${ellipsis}`;
|
|
294
|
+
let taken = [];
|
|
295
|
+
for (let index = tail.length - 1; index >= (withHead ? 1 : 0); index--) {
|
|
296
|
+
const candidate = [tail[index], ...taken];
|
|
297
|
+
const length = prefix.length + candidate.join("/").length + 1 + marker.length;
|
|
298
|
+
if (length > width) break;
|
|
299
|
+
taken = candidate;
|
|
300
|
+
}
|
|
301
|
+
if (taken.length > 0) return `${prefix}/${taken.join("/")}${marker}`;
|
|
302
|
+
}
|
|
303
|
+
const leaf = segments[segments.length - 1] ?? path;
|
|
304
|
+
return cut(`/${ellipsis}/${leaf}`, width, ellipsis);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// src/render/format.ts
|
|
308
|
+
var SLOW_MS = 300;
|
|
309
|
+
var VERY_SLOW_MS = 1e3;
|
|
310
|
+
var MANY_QUERIES = 20;
|
|
311
|
+
function duration(ms) {
|
|
312
|
+
if (ms >= 1e5) return `${Math.round(ms / 1e3)}s`;
|
|
313
|
+
if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
|
|
314
|
+
if (ms >= 10) return `${Math.round(ms)}ms`;
|
|
315
|
+
return `${ms.toFixed(1)}ms`;
|
|
316
|
+
}
|
|
317
|
+
function spanDuration(ms) {
|
|
318
|
+
if (ms >= 1e5) return `${Math.round(ms / 1e3)}s`;
|
|
319
|
+
if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
|
|
320
|
+
if (ms >= 100) return `${Math.round(ms)}ms`;
|
|
321
|
+
return `${ms.toFixed(1)}ms`;
|
|
322
|
+
}
|
|
323
|
+
function bytes(count) {
|
|
324
|
+
if (count < 1024) return `${count} B`;
|
|
325
|
+
if (count < 1024 * 1024) return `${(count / 1024).toFixed(1)} KB`;
|
|
326
|
+
return `${(count / (1024 * 1024)).toFixed(1)} MB`;
|
|
327
|
+
}
|
|
328
|
+
function clock(at) {
|
|
329
|
+
const when = new Date(at);
|
|
330
|
+
const two = (value) => String(value).padStart(2, "0");
|
|
331
|
+
const three = String(when.getMilliseconds()).padStart(3, "0");
|
|
332
|
+
return `${two(when.getHours())}:${two(when.getMinutes())}:${two(when.getSeconds())}.${three}`;
|
|
333
|
+
}
|
|
334
|
+
function badgeFor(detector) {
|
|
335
|
+
switch (detector) {
|
|
336
|
+
case "n_plus_one":
|
|
337
|
+
return "N+1";
|
|
338
|
+
case "sequential_http":
|
|
339
|
+
return "SEQ";
|
|
340
|
+
case "dup_http":
|
|
341
|
+
case "dup_cache":
|
|
342
|
+
return "DUP";
|
|
343
|
+
case "slow_budget":
|
|
344
|
+
return "SLOW";
|
|
345
|
+
case "heavy_response":
|
|
346
|
+
return "HEAVY";
|
|
347
|
+
default:
|
|
348
|
+
return detector.toUpperCase();
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
function share(part, whole) {
|
|
352
|
+
if (whole <= 0) return "";
|
|
353
|
+
return `${Math.round(part / whole * 100)}% of total`;
|
|
354
|
+
}
|
|
355
|
+
function queries(count, theme) {
|
|
356
|
+
return count === 0 ? theme.glyph("none") : `${count}q`;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// src/render/row.ts
|
|
360
|
+
function flagOf(row, showStatus) {
|
|
361
|
+
if (!showStatus && row.status >= 400) {
|
|
362
|
+
return [row.status >= 500 ? "errLoud" : "warn", String(row.status)];
|
|
363
|
+
}
|
|
364
|
+
if (row.hasError) return ["errLoud", "ERR"];
|
|
365
|
+
if (row.flag) return [row.flag === "n_plus_one" ? "warnLoud" : "warn", badgeFor(row.flag)];
|
|
366
|
+
if (row.test) return ["cmd", "TEST"];
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
function gutterOf(row) {
|
|
370
|
+
if (row.hasError) return ["err", "!!"];
|
|
371
|
+
if (row.findingCount > 0 || row.durationMs >= SLOW_MS) return ["warn", "!"];
|
|
372
|
+
return ["dim", ""];
|
|
373
|
+
}
|
|
374
|
+
function statusStyle(status) {
|
|
375
|
+
if (status >= 500) return "errLoud";
|
|
376
|
+
if (status >= 400) return "warn";
|
|
377
|
+
return "dim";
|
|
378
|
+
}
|
|
379
|
+
function durationStyle(ms) {
|
|
380
|
+
if (ms >= VERY_SLOW_MS) return "err";
|
|
381
|
+
if (ms >= SLOW_MS) return "warn";
|
|
382
|
+
return "plain";
|
|
383
|
+
}
|
|
384
|
+
function paintPath(text, theme) {
|
|
385
|
+
const ellipsis = theme.glyph("ellipsis");
|
|
386
|
+
const parts = text.split(ellipsis);
|
|
387
|
+
return parts.map((part, index) => {
|
|
388
|
+
const last = index === parts.length - 1;
|
|
389
|
+
if (!last && part.endsWith("?")) {
|
|
390
|
+
return theme.paint("plain", part.slice(0, -1)) + theme.paint("dim", "?");
|
|
391
|
+
}
|
|
392
|
+
return theme.paint("plain", part);
|
|
393
|
+
}).join(theme.paint("dim", ellipsis));
|
|
394
|
+
}
|
|
395
|
+
function join(theme, cells) {
|
|
396
|
+
return cells.map(([style, text]) => theme.paint(style, text)).join("");
|
|
397
|
+
}
|
|
398
|
+
var ID = 12;
|
|
399
|
+
function streamHead(theme, options = {}) {
|
|
400
|
+
const columns = streamColumns(theme.width, options.ids);
|
|
401
|
+
const cells = [["dim", " "]];
|
|
402
|
+
if (columns.ids) cells.push(["dim", pad("ID", ID)], ["dim", " "]);
|
|
403
|
+
cells.push(["dim", pad("TIME", 12)], ["dim", " "], ["dim", pad("METHOD", 6)], ["dim", " "]);
|
|
404
|
+
if (columns.status) cells.push(["dim", pad("ST", 3)], ["dim", " "]);
|
|
405
|
+
cells.push(["dim", pad("PATH", columns.path)], ["dim", " "], ["dim", padStart("DUR", 7)]);
|
|
406
|
+
if (columns.queries) cells.push(["dim", " "], ["dim", padStart("Q", 4)]);
|
|
407
|
+
cells.push(["dim", " "], ["dim", "FLAGS"]);
|
|
408
|
+
return join(theme, cells);
|
|
409
|
+
}
|
|
410
|
+
function streamRow(row, theme, options = {}) {
|
|
411
|
+
const columns = streamColumns(theme.width, options.ids);
|
|
412
|
+
const gutter = gutterOf(row);
|
|
413
|
+
const flag = flagOf(row, columns.status);
|
|
414
|
+
const path = fitPath(row.path, row.query, columns.path, theme.glyph("ellipsis"));
|
|
415
|
+
const cells = [
|
|
416
|
+
[gutter[0], pad(gutter[1], 2)],
|
|
417
|
+
["dim", " "]
|
|
418
|
+
];
|
|
419
|
+
if (columns.ids) cells.push(["cmd", pad(row.id, ID)], ["dim", " "]);
|
|
420
|
+
cells.push(
|
|
421
|
+
["dim", pad(clock(row.startedAt), 12)],
|
|
422
|
+
["dim", " "],
|
|
423
|
+
// POST and DELETE read louder than GET without a colour of their own —
|
|
424
|
+
// only by contrast with a muted one.
|
|
425
|
+
[row.method === "GET" ? "dim" : "plain", pad(row.method, 6)],
|
|
426
|
+
["dim", " "]
|
|
427
|
+
);
|
|
428
|
+
if (columns.status) {
|
|
429
|
+
cells.push([statusStyle(row.status), pad(String(row.status), 3)], ["dim", " "]);
|
|
430
|
+
}
|
|
431
|
+
const painted = [
|
|
432
|
+
join(theme, cells),
|
|
433
|
+
paintPath(pad(path, columns.path), theme),
|
|
434
|
+
theme.paint("dim", " "),
|
|
435
|
+
theme.paint(durationStyle(row.durationMs), padStart(duration(row.durationMs), 7))
|
|
436
|
+
];
|
|
437
|
+
if (columns.queries) {
|
|
438
|
+
painted.push(
|
|
439
|
+
theme.paint("dim", " "),
|
|
440
|
+
theme.paint(
|
|
441
|
+
row.sqlCount > MANY_QUERIES ? "warn" : "dim",
|
|
442
|
+
padStart(queries(row.sqlCount, theme), 4)
|
|
443
|
+
)
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
painted.push(theme.paint("dim", " "), flag ? theme.paint(flag[0], flag[1]) : "");
|
|
447
|
+
return painted.join("").trimEnd();
|
|
448
|
+
}
|
|
449
|
+
function failureLines(row, detail, theme) {
|
|
450
|
+
const error = detail?.error ?? null;
|
|
451
|
+
const command = `reqray show ${row.id}`;
|
|
452
|
+
const corner = theme.glyph("corner");
|
|
453
|
+
if (!error) {
|
|
454
|
+
return [` ${theme.paint("dim", corner)} ${theme.paint("cmd", command)}`];
|
|
455
|
+
}
|
|
456
|
+
const lines = [
|
|
457
|
+
` ${theme.paint("dim", corner)} ${theme.paint("err", error.name)}${theme.paint("dim", `: ${error.message}`)}`
|
|
458
|
+
];
|
|
459
|
+
const frame = frameOf(error.stack);
|
|
460
|
+
const left = ` ${frame ?? ""}`;
|
|
461
|
+
if (frame && left.length + command.length + 3 <= theme.width) {
|
|
462
|
+
const gap = " ".repeat(theme.width - left.length - command.length - 1);
|
|
463
|
+
lines.push(theme.paint("dim", left) + gap + theme.paint("cmd", command));
|
|
464
|
+
} else {
|
|
465
|
+
if (frame) lines.push(theme.paint("dim", left));
|
|
466
|
+
lines.push(` ${theme.paint("cmd", command)}`);
|
|
467
|
+
}
|
|
468
|
+
return lines;
|
|
469
|
+
}
|
|
470
|
+
function frameOf(stack) {
|
|
471
|
+
if (!stack) return null;
|
|
472
|
+
for (const raw of stack.split("\n")) {
|
|
473
|
+
const line = raw.trim();
|
|
474
|
+
if (!line.startsWith("at ")) continue;
|
|
475
|
+
const match = /^at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(line);
|
|
476
|
+
const file = match?.[1];
|
|
477
|
+
if (!file || file.startsWith("node:") || file.includes("node_modules")) continue;
|
|
478
|
+
const parts = file.split(/[/\\]/).filter((part) => part !== "" && part !== "file:");
|
|
479
|
+
return `${parts.slice(-2).join("/")}:${match?.[2]}`;
|
|
480
|
+
}
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// src/filter.ts
|
|
485
|
+
function matches(row, filter) {
|
|
486
|
+
if (filter.slowerThanMs != null && row.durationMs < filter.slowerThanMs) return false;
|
|
487
|
+
if (filter.findingsOnly && row.findingCount === 0) return false;
|
|
488
|
+
const methods = filter.methods ?? [];
|
|
489
|
+
if (methods.length > 0 && !methods.some((method) => method.toUpperCase() === row.method)) {
|
|
490
|
+
return false;
|
|
491
|
+
}
|
|
492
|
+
const statuses = filter.statuses ?? [];
|
|
493
|
+
if (statuses.length > 0 && !statuses.some((spec) => matchesStatus(row.status, spec))) {
|
|
494
|
+
return false;
|
|
495
|
+
}
|
|
496
|
+
if (filter.path && !globOf(filter.path).test(row.path)) return false;
|
|
497
|
+
return true;
|
|
498
|
+
}
|
|
499
|
+
function matchesStatus(status, spec) {
|
|
500
|
+
const trimmed = spec.trim().toLowerCase();
|
|
501
|
+
if (/^[1-5]xx$/.test(trimmed)) return Math.floor(status / 100) === Number(trimmed[0]);
|
|
502
|
+
const exact = Number(trimmed);
|
|
503
|
+
return Number.isFinite(exact) && exact === status;
|
|
504
|
+
}
|
|
505
|
+
var globCache = /* @__PURE__ */ new Map();
|
|
506
|
+
function globOf(glob) {
|
|
507
|
+
const cached2 = globCache.get(glob);
|
|
508
|
+
if (cached2) return cached2;
|
|
509
|
+
const pattern = glob.split("").map((char) => {
|
|
510
|
+
if (char === "*") return ".*";
|
|
511
|
+
if (char === "?") return ".";
|
|
512
|
+
return /[a-zA-Z0-9/_-]/.test(char) ? char : `\\${char}`;
|
|
513
|
+
}).join("");
|
|
514
|
+
const expression = new RegExp(`^${pattern}$`);
|
|
515
|
+
globCache.set(glob, expression);
|
|
516
|
+
return expression;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// src/render/screens.ts
|
|
520
|
+
function header(version, url, meta, theme) {
|
|
521
|
+
const host = hostOf(url);
|
|
522
|
+
return [
|
|
523
|
+
theme.paint("plain", `reqray ${version}`) + theme.paint("dim", ` watching ${host} pid ${meta.pid} ctrl-c to stop`),
|
|
524
|
+
""
|
|
525
|
+
];
|
|
526
|
+
}
|
|
527
|
+
function emptyState(url, meta, theme) {
|
|
528
|
+
const origin = new URL(url).origin;
|
|
529
|
+
const waiting = " waiting";
|
|
530
|
+
const status = `buffer ${meta.bufferSize}, empty`;
|
|
531
|
+
const gap = Math.max(2, theme.width - waiting.length - status.length - 1);
|
|
532
|
+
return [
|
|
533
|
+
theme.paint("plain", " collector attached \u2014 no requests recorded yet"),
|
|
534
|
+
"",
|
|
535
|
+
theme.paint("dim", " try ") + theme.paint("cmd", `curl -s ${origin}/`),
|
|
536
|
+
theme.paint("dim", " or just reload the application in a browser"),
|
|
537
|
+
"",
|
|
538
|
+
theme.paint("dim", waiting) + " ".repeat(gap) + theme.paint("dim", status)
|
|
539
|
+
];
|
|
540
|
+
}
|
|
541
|
+
function renderFailure(error, theme, verbose) {
|
|
542
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
543
|
+
const lines = [theme.paint("errLoud", `reqray: ${message}`)];
|
|
544
|
+
const cause = causeOf(error);
|
|
545
|
+
if (verbose && cause) lines.push("", theme.paint("dim", ` ${cause}`));
|
|
546
|
+
if (error instanceof CliError) lines.push(...error.hints.map((hint) => theme.paint("dim", hint)));
|
|
547
|
+
if (!verbose && cause) {
|
|
548
|
+
lines.push(
|
|
549
|
+
"",
|
|
550
|
+
theme.paint("dim", " ") + theme.paint("cmd", "reqray --verbose") + theme.paint("dim", " prints what actually failed")
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
return lines;
|
|
554
|
+
}
|
|
555
|
+
function noticeLine(text, theme) {
|
|
556
|
+
return theme.paint("dim", ` ${theme.glyph("ellipsis")} ${text}`);
|
|
557
|
+
}
|
|
558
|
+
function hostOf(url) {
|
|
559
|
+
try {
|
|
560
|
+
return new URL(url).host;
|
|
561
|
+
} catch {
|
|
562
|
+
return url;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// src/render/theme.ts
|
|
567
|
+
var SGR = {
|
|
568
|
+
dim: 90,
|
|
569
|
+
plain: 39,
|
|
570
|
+
faint: 37,
|
|
571
|
+
ok: 32,
|
|
572
|
+
warn: 33,
|
|
573
|
+
warnLoud: 93,
|
|
574
|
+
err: 31,
|
|
575
|
+
errLoud: 91,
|
|
576
|
+
cmd: 36,
|
|
577
|
+
invert: 7
|
|
578
|
+
};
|
|
579
|
+
var UNICODE = {
|
|
580
|
+
barFull: "\u2588",
|
|
581
|
+
barSliver: "\u258F",
|
|
582
|
+
bracketOpen: "\u251C",
|
|
583
|
+
bracketClose: "\u2524",
|
|
584
|
+
bracketFill: "\u2500",
|
|
585
|
+
rulerTick: "\u253C",
|
|
586
|
+
ellipsis: "\u2026",
|
|
587
|
+
corner: "\u2514",
|
|
588
|
+
times: "\xD7",
|
|
589
|
+
none: "\u2014"
|
|
590
|
+
};
|
|
591
|
+
var ASCII = {
|
|
592
|
+
barFull: "#",
|
|
593
|
+
barSliver: "|",
|
|
594
|
+
bracketOpen: "[",
|
|
595
|
+
bracketClose: "]",
|
|
596
|
+
bracketFill: "-",
|
|
597
|
+
rulerTick: "+",
|
|
598
|
+
ellipsis: "...",
|
|
599
|
+
corner: "\\_",
|
|
600
|
+
times: "x",
|
|
601
|
+
none: "-"
|
|
602
|
+
};
|
|
603
|
+
var FALLBACK_WIDTH = 80;
|
|
604
|
+
var ESC = "\x1B[";
|
|
605
|
+
function wantsColor(env, stdout, flags) {
|
|
606
|
+
if (flags.color === "always") return true;
|
|
607
|
+
if (flags.color === "never") return false;
|
|
608
|
+
if (env["NO_COLOR"] !== void 0 && env["NO_COLOR"] !== "") return false;
|
|
609
|
+
if (env["TERM"] === "dumb") return false;
|
|
610
|
+
return stdout.isTTY === true;
|
|
611
|
+
}
|
|
612
|
+
function wantsUnicode(env, flags) {
|
|
613
|
+
if (flags.ascii) return false;
|
|
614
|
+
if (env["REQRAY_ASCII"] === "1") return false;
|
|
615
|
+
const locale = env["LC_ALL"] ?? env["LC_CTYPE"] ?? env["LANG"];
|
|
616
|
+
if (!locale) return true;
|
|
617
|
+
return /utf-?8/i.test(locale);
|
|
618
|
+
}
|
|
619
|
+
function resolveTheme(env, stdout, flags = {}) {
|
|
620
|
+
const color = wantsColor(env, stdout, flags);
|
|
621
|
+
const unicode = wantsUnicode(env, flags);
|
|
622
|
+
const glyphs = unicode ? UNICODE : ASCII;
|
|
623
|
+
const columns = Number(env["COLUMNS"]);
|
|
624
|
+
const detected = Number.isFinite(columns) && columns > 0 ? Math.floor(columns) : stdout.columns ?? FALLBACK_WIDTH;
|
|
625
|
+
return {
|
|
626
|
+
color,
|
|
627
|
+
unicode,
|
|
628
|
+
width: flags.width ?? detected,
|
|
629
|
+
// Whitespace is painted only by reverse video, which is the one style
|
|
630
|
+
// that shows on a space. Everything else would be an escape sequence
|
|
631
|
+
// around nothing — invisible on screen and noise in a pipe.
|
|
632
|
+
paint: (style, text) => color && text.trim() !== "" && style !== "invert" ? `${ESC}${SGR[style]}m${text}${ESC}0m` : style === "invert" && color && text !== "" ? `${ESC}${SGR.invert}m${text}${ESC}0m` : text,
|
|
633
|
+
glyph: (name) => glyphs[name]
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
function plainTheme(width = FALLBACK_WIDTH, unicode = true) {
|
|
637
|
+
return resolveTheme({}, {}, { color: "never", width, ascii: !unicode });
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// src/args.ts
|
|
641
|
+
var ALIASES = {
|
|
642
|
+
h: "help",
|
|
643
|
+
V: "version"
|
|
644
|
+
};
|
|
645
|
+
function parseArgs(argv, spec) {
|
|
646
|
+
const flags = {};
|
|
647
|
+
const positionals = [];
|
|
648
|
+
for (let index = 0; index < argv.length; index++) {
|
|
649
|
+
const token = argv[index];
|
|
650
|
+
if (token === "--") {
|
|
651
|
+
positionals.push(...argv.slice(index + 1));
|
|
652
|
+
break;
|
|
653
|
+
}
|
|
654
|
+
if (!token.startsWith("-") || token === "-") {
|
|
655
|
+
positionals.push(token);
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
const bare = token.replace(/^--?/, "");
|
|
659
|
+
const equals = bare.indexOf("=");
|
|
660
|
+
const rawName = equals === -1 ? bare : bare.slice(0, equals);
|
|
661
|
+
const name = ALIASES[rawName] ?? rawName;
|
|
662
|
+
const kind = spec[name];
|
|
663
|
+
if (kind === void 0) throw unknownFlag(token, spec);
|
|
664
|
+
if (kind === "boolean") {
|
|
665
|
+
if (equals !== -1) {
|
|
666
|
+
throw new UsageError(`${token.split("=")[0]} takes no value`);
|
|
667
|
+
}
|
|
668
|
+
flags[name] = true;
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
const attached = equals === -1 ? void 0 : bare.slice(equals + 1);
|
|
672
|
+
const next = argv[index + 1];
|
|
673
|
+
const separate = next !== void 0 && !next.startsWith("-") ? next : void 0;
|
|
674
|
+
if (kind === "optional") {
|
|
675
|
+
if (attached === void 0 && separate !== void 0) index++;
|
|
676
|
+
flags[name] = attached ?? separate ?? "";
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
if (attached === void 0 && separate !== void 0) index++;
|
|
680
|
+
const value = attached ?? separate;
|
|
681
|
+
if (value === void 0) throw new UsageError(`--${name} needs a value`);
|
|
682
|
+
const existing = flags[name];
|
|
683
|
+
flags[name] = kind === "list" && typeof existing === "string" ? `${existing},${value}` : value;
|
|
684
|
+
}
|
|
685
|
+
return { positionals, flags };
|
|
686
|
+
}
|
|
687
|
+
function unknownFlag(token, spec) {
|
|
688
|
+
const typed = token.replace(/^--?/, "").split("=")[0] ?? "";
|
|
689
|
+
const known = Object.keys(spec).sort();
|
|
690
|
+
const near = known.filter(
|
|
691
|
+
(flag) => flag.startsWith(typed.slice(0, 3)) || typed.startsWith(flag.slice(0, 3))
|
|
692
|
+
);
|
|
693
|
+
const hints = near.length ? ["", ` did you mean ${near.map((flag) => `--${flag}`).join(" ")}`] : ["", ` flags here ${known.map((flag) => `--${flag}`).join(" ")}`];
|
|
694
|
+
return new UsageError(`unknown flag ${token}`, hints);
|
|
695
|
+
}
|
|
696
|
+
function stringFlag(args, name) {
|
|
697
|
+
const value = args.flags[name];
|
|
698
|
+
return typeof value === "string" ? value : null;
|
|
699
|
+
}
|
|
700
|
+
function numberFlag(args, name) {
|
|
701
|
+
const raw = stringFlag(args, name);
|
|
702
|
+
if (raw === null) return null;
|
|
703
|
+
const value = Number(raw);
|
|
704
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
705
|
+
throw new UsageError(`--${name} wants a number of milliseconds, not "${raw}"`);
|
|
706
|
+
}
|
|
707
|
+
return value;
|
|
708
|
+
}
|
|
709
|
+
function boolFlag(args, name) {
|
|
710
|
+
return args.flags[name] === true;
|
|
711
|
+
}
|
|
712
|
+
function listFlag(args, name) {
|
|
713
|
+
const raw = stringFlag(args, name);
|
|
714
|
+
if (raw === null) return [];
|
|
715
|
+
return raw.split(",").map((part) => part.trim()).filter(Boolean);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// src/options.ts
|
|
719
|
+
var DEFAULT_URL = "http://localhost:3000/_reqray";
|
|
720
|
+
var GLOBAL_FLAGS = {
|
|
721
|
+
url: "string",
|
|
722
|
+
token: "string",
|
|
723
|
+
color: "string",
|
|
724
|
+
"no-color": "boolean",
|
|
725
|
+
ascii: "boolean",
|
|
726
|
+
verbose: "boolean",
|
|
727
|
+
help: "boolean",
|
|
728
|
+
version: "boolean"
|
|
729
|
+
};
|
|
730
|
+
function normalizeUrl(raw) {
|
|
731
|
+
let parsed;
|
|
732
|
+
try {
|
|
733
|
+
parsed = new URL(raw);
|
|
734
|
+
} catch {
|
|
735
|
+
throw new UsageError(`--url wants an address, not "${raw}"`, [
|
|
736
|
+
"",
|
|
737
|
+
` for example ${DEFAULT_URL}`
|
|
738
|
+
]);
|
|
739
|
+
}
|
|
740
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
741
|
+
throw new UsageError(`--url speaks http or https, not ${parsed.protocol.replace(":", "")}`);
|
|
742
|
+
}
|
|
743
|
+
const path = parsed.pathname.replace(/\/+$/, "");
|
|
744
|
+
return `${parsed.origin}${path === "" ? "/_reqray" : path}`;
|
|
745
|
+
}
|
|
746
|
+
function resolveGlobals(args, runtime) {
|
|
747
|
+
const url = normalizeUrl(stringFlag(args, "url") ?? runtime.env["REQRAY_URL"] ?? DEFAULT_URL);
|
|
748
|
+
const token = stringFlag(args, "token") ?? runtime.env["REQRAY_TOKEN"] ?? null;
|
|
749
|
+
const asked = stringFlag(args, "color");
|
|
750
|
+
if (asked !== null && asked !== "always" && asked !== "never" && asked !== "auto") {
|
|
751
|
+
throw new UsageError(`--color takes auto, always or never, not "${asked}"`);
|
|
752
|
+
}
|
|
753
|
+
const color = boolFlag(args, "no-color") ? "never" : asked ?? "auto";
|
|
754
|
+
return {
|
|
755
|
+
url,
|
|
756
|
+
token,
|
|
757
|
+
verbose: boolFlag(args, "verbose"),
|
|
758
|
+
theme: resolveTheme(runtime.env, runtime.stdout, { color, ascii: boolFlag(args, "ascii") })
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// src/commands/context.ts
|
|
763
|
+
function streamWriter(stream) {
|
|
764
|
+
return {
|
|
765
|
+
line(text) {
|
|
766
|
+
stream.write(`${text}
|
|
767
|
+
`);
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/render/findings.ts
|
|
773
|
+
var LOUD = 2;
|
|
774
|
+
var LOUD_FLOOR_MS = 1;
|
|
775
|
+
var BLOCK = 100;
|
|
776
|
+
var SEVERITY = { critical: 2, warn: 1, info: 0 };
|
|
777
|
+
function ranked(detail) {
|
|
778
|
+
return [...detail.findings].sort(
|
|
779
|
+
(a, b) => (SEVERITY[b.severity] ?? 0) - (SEVERITY[a.severity] ?? 0) || b.costMs - a.costMs
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
function costOf(finding) {
|
|
783
|
+
const evidence = finding.evidence;
|
|
784
|
+
return evidence.kind === "heavy_response" ? bytes(evidence.bytes) : spanDuration(finding.costMs);
|
|
785
|
+
}
|
|
786
|
+
function noteOf(finding, durationMs) {
|
|
787
|
+
const evidence = finding.evidence;
|
|
788
|
+
if (evidence.kind !== "heavy_response") return share(finding.costMs, durationMs);
|
|
789
|
+
return evidence.contentType ?? "";
|
|
790
|
+
}
|
|
791
|
+
function worthShouting(finding) {
|
|
792
|
+
return finding.evidence.kind === "heavy_response" || finding.costMs >= LOUD_FLOOR_MS;
|
|
793
|
+
}
|
|
794
|
+
function where(finding) {
|
|
795
|
+
const site = finding.callsite;
|
|
796
|
+
return site ? `${site.relative}:${site.line}` : "";
|
|
797
|
+
}
|
|
798
|
+
function sampleOf(finding) {
|
|
799
|
+
return "sample" in finding.evidence ? finding.evidence.sample : null;
|
|
800
|
+
}
|
|
801
|
+
function findingLines(detail, theme) {
|
|
802
|
+
const width = Math.min(theme.width, BLOCK);
|
|
803
|
+
const lines = [];
|
|
804
|
+
const findings = ranked(detail);
|
|
805
|
+
findings.forEach((finding, index) => {
|
|
806
|
+
const loud = index < LOUD && worthShouting(finding);
|
|
807
|
+
const cost = costOf(finding);
|
|
808
|
+
const percent = noteOf(finding, detail.durationMs);
|
|
809
|
+
const tag = badgeFor(finding.detector);
|
|
810
|
+
if (index > 0) lines.push("");
|
|
811
|
+
if (loud) {
|
|
812
|
+
const head = ` ${theme.paint("warn", "! ")}${theme.paint("warnLoud", pad(tag, 6))}`;
|
|
813
|
+
const title = finding.title;
|
|
814
|
+
const room2 = width - 10 - 8 - 3 - percent.length;
|
|
815
|
+
lines.push(
|
|
816
|
+
head + theme.paint("plain", pad(title, Math.max(10, room2))) + theme.paint("plain", padStart(cost, 8)) + theme.paint("dim", ` ${percent}`)
|
|
817
|
+
);
|
|
818
|
+
const sample = sampleOf(finding);
|
|
819
|
+
if (sample) lines.push(theme.paint("plain", ` ${sample}`));
|
|
820
|
+
const site = where(finding);
|
|
821
|
+
if (site) lines.push(theme.paint("dim", ` ${site}`));
|
|
822
|
+
lines.push(theme.paint("dim", " fix ") + theme.paint("plain", finding.hint));
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
const room = width - 10 - 8;
|
|
826
|
+
lines.push(
|
|
827
|
+
theme.paint(
|
|
828
|
+
"dim",
|
|
829
|
+
` ${pad(tag.toLowerCase(), 6)}${pad(finding.title, Math.max(10, room))}`
|
|
830
|
+
) + theme.paint("dim", padStart(cost, 8))
|
|
831
|
+
);
|
|
832
|
+
const context = [sampleOf(finding), where(finding)].filter(Boolean).join(" ");
|
|
833
|
+
if (context) lines.push(theme.paint("dim", ` ${context}`));
|
|
834
|
+
});
|
|
835
|
+
return lines.map((line) => line.trimEnd());
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// src/render/waterfall.ts
|
|
839
|
+
import { buildWaterfall as buildBars } from "@reqray/waterfall";
|
|
840
|
+
var TAG = 6;
|
|
841
|
+
var LABEL = 28;
|
|
842
|
+
var INDENT = 2 + TAG + LABEL + 1;
|
|
843
|
+
var RIGHT = 2 + 7 + 1 + 4;
|
|
844
|
+
function barCells(width) {
|
|
845
|
+
return Math.max(12, Math.min(60, width - INDENT - RIGHT - 4));
|
|
846
|
+
}
|
|
847
|
+
var KIND_STYLE = {
|
|
848
|
+
middleware: "dim",
|
|
849
|
+
handler: "cmd",
|
|
850
|
+
db: "ok",
|
|
851
|
+
http: "warn",
|
|
852
|
+
cache: "faint",
|
|
853
|
+
// Faint on purpose: a gap is the absence of an answer, and it must not read
|
|
854
|
+
// as louder than the work around it.
|
|
855
|
+
gap: "faint"
|
|
856
|
+
};
|
|
857
|
+
var KIND_TAG = {
|
|
858
|
+
middleware: "mw",
|
|
859
|
+
handler: "fn",
|
|
860
|
+
db: "sql",
|
|
861
|
+
http: "http",
|
|
862
|
+
cache: "cache",
|
|
863
|
+
gap: "\u2014"
|
|
864
|
+
};
|
|
865
|
+
function sqlLabel(sql) {
|
|
866
|
+
const flat = sql.replace(/\s+/g, " ").trim();
|
|
867
|
+
const select = /^select\b.*?\bfrom\s+([\w."]+)(.*)$/i.exec(flat);
|
|
868
|
+
if (select) return tidy(`SELECT ${table(select[1])}${select[2] ?? ""}`);
|
|
869
|
+
const insert = /^insert\s+into\s+([\w."]+)/i.exec(flat);
|
|
870
|
+
if (insert) return `INSERT ${table(insert[1])}`;
|
|
871
|
+
const update = /^update\s+([\w."]+)(.*)$/i.exec(flat);
|
|
872
|
+
if (update) return tidy(`UPDATE ${table(update[1])}${update[2] ?? ""}`);
|
|
873
|
+
const remove = /^delete\s+from\s+([\w."]+)(.*)$/i.exec(flat);
|
|
874
|
+
if (remove) return tidy(`DELETE ${table(remove[1])}${remove[2] ?? ""}`);
|
|
875
|
+
return flat;
|
|
876
|
+
}
|
|
877
|
+
function table(name) {
|
|
878
|
+
return (name ?? "?").replace(/"/g, "").split(".").pop() ?? "?";
|
|
879
|
+
}
|
|
880
|
+
function tidy(text) {
|
|
881
|
+
const clause = /\b(where|limit|order by|group by)\b/i.exec(text);
|
|
882
|
+
const head = clause ? text.slice(0, clause.index).trim() : text.trim();
|
|
883
|
+
const tail = clause ? ` ${text.slice(clause.index).trim()}` : "";
|
|
884
|
+
return `${head}${tail}`.replace(/\s*=\s*/g, "=").replace(/\s+/g, " ");
|
|
885
|
+
}
|
|
886
|
+
function labelOf(span) {
|
|
887
|
+
switch (span.kind) {
|
|
888
|
+
case "middleware":
|
|
889
|
+
case "handler":
|
|
890
|
+
return span.label;
|
|
891
|
+
case "db":
|
|
892
|
+
return sqlLabel(span.sql);
|
|
893
|
+
case "http": {
|
|
894
|
+
try {
|
|
895
|
+
const url = new URL(span.url);
|
|
896
|
+
return `${url.host} ${url.pathname}`;
|
|
897
|
+
} catch {
|
|
898
|
+
return span.url;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
case "cache":
|
|
902
|
+
return span.key;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
function spanIdsOf(detail, detector) {
|
|
906
|
+
const ids = /* @__PURE__ */ new Set();
|
|
907
|
+
for (const finding of detail.findings) {
|
|
908
|
+
if (finding.detector !== detector) continue;
|
|
909
|
+
for (const id of finding.evidence.spanIds) ids.add(id);
|
|
910
|
+
}
|
|
911
|
+
return ids;
|
|
912
|
+
}
|
|
913
|
+
function repeatsOf(detail, detectors) {
|
|
914
|
+
const ids = /* @__PURE__ */ new Set();
|
|
915
|
+
for (const finding of detail.findings) {
|
|
916
|
+
if (!detectors.includes(finding.detector)) continue;
|
|
917
|
+
for (const id of [...finding.evidence.spanIds].sort((a, b) => a - b).slice(1)) ids.add(id);
|
|
918
|
+
}
|
|
919
|
+
return ids;
|
|
920
|
+
}
|
|
921
|
+
function buildWaterfall(detail, theme) {
|
|
922
|
+
const duplicated = repeatsOf(detail, ["dup_http", "dup_cache"]);
|
|
923
|
+
const sequential = spanIdsOf(detail, "sequential_http");
|
|
924
|
+
return buildBars(detail).map((bar) => {
|
|
925
|
+
const label = bar.span === null ? "uninstrumented" : bar.count > 1 ? `${bar.count}${theme.glyph("times")} ${labelOf(bar.span)}` : labelOf(bar.span);
|
|
926
|
+
return {
|
|
927
|
+
tag: KIND_TAG[bar.kind],
|
|
928
|
+
label,
|
|
929
|
+
depth: bar.depth,
|
|
930
|
+
startedAt: bar.startedAt,
|
|
931
|
+
duration: bar.duration,
|
|
932
|
+
badge: badgeOf(bar, duplicated, sequential),
|
|
933
|
+
style: KIND_STYLE[bar.kind],
|
|
934
|
+
bracket: bar.kind === "handler",
|
|
935
|
+
waitMs: bar.waitMs
|
|
936
|
+
};
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
function badgeOf(bar, duplicated, sequential) {
|
|
940
|
+
if (bar.finding === "n_plus_one") return "N+1";
|
|
941
|
+
if (bar.finding !== null) return badgeFor(bar.finding);
|
|
942
|
+
if (bar.span === null) return null;
|
|
943
|
+
if (duplicated.has(bar.span.id)) return "DUP";
|
|
944
|
+
return sequential.has(bar.span.id) ? badgeFor("sequential_http") : null;
|
|
945
|
+
}
|
|
946
|
+
function barParts(startedAt, length, total, cells, theme, bracket = false) {
|
|
947
|
+
const per = total > 0 ? total / cells : 1;
|
|
948
|
+
let offset = Math.max(0, Math.floor(startedAt / per));
|
|
949
|
+
let width = length / per;
|
|
950
|
+
let body;
|
|
951
|
+
if (width < 0.6) {
|
|
952
|
+
body = theme.glyph("barSliver");
|
|
953
|
+
width = 1;
|
|
954
|
+
} else {
|
|
955
|
+
width = Math.max(2, Math.round(width));
|
|
956
|
+
body = bracket ? theme.glyph("bracketOpen") + theme.glyph("bracketFill").repeat(width - 2) + theme.glyph("bracketClose") : theme.glyph("barFull").repeat(width);
|
|
957
|
+
}
|
|
958
|
+
if (offset + width > cells) offset = Math.max(0, cells - width);
|
|
959
|
+
return {
|
|
960
|
+
lead: " ".repeat(offset),
|
|
961
|
+
body,
|
|
962
|
+
trail: " ".repeat(Math.max(0, cells - offset - width))
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
function ruler(cells, theme) {
|
|
966
|
+
const inner = Math.max(4, cells - 5);
|
|
967
|
+
const segments = [0, 1, 2, 3].map((index) => Math.floor(inner / 4) + (index < inner % 4 ? 1 : 0));
|
|
968
|
+
let line = theme.glyph("bracketOpen");
|
|
969
|
+
const ticks = [0];
|
|
970
|
+
segments.forEach((length, index) => {
|
|
971
|
+
line += theme.glyph("bracketFill").repeat(length);
|
|
972
|
+
line += index === segments.length - 1 ? theme.glyph("bracketClose") : theme.glyph("rulerTick");
|
|
973
|
+
ticks.push(line.length - 1);
|
|
974
|
+
});
|
|
975
|
+
return { line, ticks };
|
|
976
|
+
}
|
|
977
|
+
function scale(total, ticks, room) {
|
|
978
|
+
const cells = (ticks[ticks.length - 1] ?? 0) + 1;
|
|
979
|
+
const allowed = Math.max(cells, room ?? cells);
|
|
980
|
+
for (const step of [1, 2, 4]) {
|
|
981
|
+
const line = layout(total, ticks, step);
|
|
982
|
+
if (line.length <= allowed) return line;
|
|
983
|
+
}
|
|
984
|
+
return padStart(duration(total), cells);
|
|
985
|
+
}
|
|
986
|
+
function layout(total, ticks, step) {
|
|
987
|
+
const last = ticks.length - 1;
|
|
988
|
+
let line = "";
|
|
989
|
+
ticks.forEach((position, index) => {
|
|
990
|
+
if (index % step !== 0 && index !== last) return;
|
|
991
|
+
const at = total * index / last;
|
|
992
|
+
const text = at === 0 ? "0ms" : duration(at);
|
|
993
|
+
const start = index === 0 ? 0 : index === last ? position - text.length + 1 : position - Math.floor(text.length / 2);
|
|
994
|
+
line += " ".repeat(Math.max(index === 0 ? 0 : 1, start - line.length)) + text;
|
|
995
|
+
});
|
|
996
|
+
return line;
|
|
997
|
+
}
|
|
998
|
+
function waterfallLines(detail, theme) {
|
|
999
|
+
const cells = barCells(theme.width);
|
|
1000
|
+
const { line, ticks } = ruler(cells, theme);
|
|
1001
|
+
const rows = buildWaterfall(detail, theme);
|
|
1002
|
+
const total = Math.max(detail.durationMs, ...rows.map((row) => row.startedAt + row.duration));
|
|
1003
|
+
const lines = [
|
|
1004
|
+
theme.paint("dim", " ".repeat(INDENT) + scale(total, ticks, theme.width - INDENT)),
|
|
1005
|
+
theme.paint("dim", " ".repeat(INDENT) + line)
|
|
1006
|
+
];
|
|
1007
|
+
for (const row of rows) {
|
|
1008
|
+
const waited = row.waitMs >= 1 ? ` (${spanDuration(row.waitMs)} queued)` : "";
|
|
1009
|
+
const label = cut(
|
|
1010
|
+
" ".repeat(row.depth * 2) + row.label + waited,
|
|
1011
|
+
LABEL,
|
|
1012
|
+
theme.glyph("ellipsis")
|
|
1013
|
+
);
|
|
1014
|
+
const drawn = barParts(row.startedAt, row.duration, total, cells, theme, row.bracket);
|
|
1015
|
+
lines.push(
|
|
1016
|
+
theme.paint("dim", ` ${pad(row.tag, TAG)}`) + theme.paint(row.tag === "mw" ? "dim" : "plain", pad(label, LABEL)) + " " + drawn.lead + theme.paint(row.style, drawn.body) + drawn.trail + " " + theme.paint("plain", padStart(spanDuration(row.duration), 7)) + " " + (row.badge ? theme.paint(row.badge === "N+1" ? "warnLoud" : "warn", row.badge) : "")
|
|
1017
|
+
);
|
|
1018
|
+
}
|
|
1019
|
+
return lines.map((entry) => entry.trimEnd());
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// src/render/detail.ts
|
|
1023
|
+
var SUMMARY = 31;
|
|
1024
|
+
var LOOP_WORTH_SAYING = 15;
|
|
1025
|
+
var BLOCK2 = 100;
|
|
1026
|
+
function heading(label, summary, theme) {
|
|
1027
|
+
const left = ` ${label}`;
|
|
1028
|
+
return theme.paint("dim", left + " ".repeat(Math.max(2, SUMMARY - left.length)) + summary);
|
|
1029
|
+
}
|
|
1030
|
+
function detailHeader(detail, theme) {
|
|
1031
|
+
const status = statusStyle2(detail.status);
|
|
1032
|
+
const from = detail.test ? ` from ${detail.test}` : "";
|
|
1033
|
+
return theme.paint("plain", ` ${detail.method} ${detail.path}`) + theme.paint(status, ` ${detail.status}`) + theme.paint("plain", ` ${duration(detail.durationMs)}`) + theme.paint("dim", ` ${clock(detail.startedAt)} #${detail.id}${from}`);
|
|
1034
|
+
}
|
|
1035
|
+
function statusStyle2(status) {
|
|
1036
|
+
if (status >= 500) return "errLoud";
|
|
1037
|
+
if (status >= 400) return "warn";
|
|
1038
|
+
return "dim";
|
|
1039
|
+
}
|
|
1040
|
+
function timingLines(detail, compared, theme) {
|
|
1041
|
+
const timing = detail.timing;
|
|
1042
|
+
if (!timing) return [];
|
|
1043
|
+
const waited = [
|
|
1044
|
+
["sql", timing.sqlMs],
|
|
1045
|
+
["external", timing.externalMs],
|
|
1046
|
+
["cache", timing.cacheMs]
|
|
1047
|
+
].filter(([, ms]) => ms >= 0.05);
|
|
1048
|
+
const own = timing.selfMs >= 0.05 ? [["your code", timing.selfMs]] : [];
|
|
1049
|
+
const loopText = detail.host && detail.host.loopMaxMs >= LOOP_WORTH_SAYING ? ` loop behind ${duration(detail.host.loopMaxMs)}` : "";
|
|
1050
|
+
const parallelText = timing.parallel ? " (overlapping)" : "";
|
|
1051
|
+
const full = Math.min(theme.width, BLOCK2) - SUMMARY;
|
|
1052
|
+
const line = (shown2) => [
|
|
1053
|
+
duration(detail.durationMs),
|
|
1054
|
+
...shown2.map(([label, ms]) => `${duration(ms)} ${label}`),
|
|
1055
|
+
...own.map(([label, ms]) => `${duration(ms)} ${label}`)
|
|
1056
|
+
].join(" ");
|
|
1057
|
+
const fit = (room) => {
|
|
1058
|
+
let shown2 = waited;
|
|
1059
|
+
while (shown2.length > 1 && line(shown2).length > room) {
|
|
1060
|
+
const cheapest = shown2.reduce((least, part) => part[1] < least[1] ? part : least);
|
|
1061
|
+
shown2 = shown2.filter((part) => part !== cheapest);
|
|
1062
|
+
}
|
|
1063
|
+
return shown2;
|
|
1064
|
+
};
|
|
1065
|
+
let notes = parallelText + loopText;
|
|
1066
|
+
let shown = fit(full - notes.length);
|
|
1067
|
+
if (line(shown).length > full - notes.length) {
|
|
1068
|
+
notes = "";
|
|
1069
|
+
shown = fit(full);
|
|
1070
|
+
}
|
|
1071
|
+
const summary = line(shown);
|
|
1072
|
+
const lines = [
|
|
1073
|
+
heading("TIME", summary, theme) + theme.paint("dim", notes.includes("(overlapping)") ? parallelText : "") + theme.paint("warn", notes.includes("loop behind") ? loopText : "")
|
|
1074
|
+
];
|
|
1075
|
+
const { baseline, pressure } = compared;
|
|
1076
|
+
if (baseline) {
|
|
1077
|
+
lines.push(
|
|
1078
|
+
theme.paint(
|
|
1079
|
+
baseline.verdict === "slower" ? "warn" : "dim",
|
|
1080
|
+
" ".repeat(SUMMARY) + verdictOf(baseline)
|
|
1081
|
+
)
|
|
1082
|
+
);
|
|
1083
|
+
}
|
|
1084
|
+
if (pressure) {
|
|
1085
|
+
const calls = pressure.elevated.calls + pressure.normal.calls;
|
|
1086
|
+
const slower = `${pressure.ratio.toFixed(1)}\xD7 slower`;
|
|
1087
|
+
const forms = [
|
|
1088
|
+
`when the loop was over ${duration(pressure.cutoffMs)} behind, this route's p95 was ${slower} \u2014 ${Math.round(pressure.share)}% of ${calls} calls`,
|
|
1089
|
+
`loop over ${duration(pressure.cutoffMs)} behind \u2192 p95 ${slower} on ${Math.round(pressure.share)}% of ${calls} calls`,
|
|
1090
|
+
`loop over ${duration(pressure.cutoffMs)} \u2192 p95 ${slower} (${Math.round(pressure.share)}%)`
|
|
1091
|
+
];
|
|
1092
|
+
const fits = forms.find((form) => form.length <= full) ?? forms.at(-1);
|
|
1093
|
+
lines.push(theme.paint("dim", " ".repeat(SUMMARY) + fits));
|
|
1094
|
+
}
|
|
1095
|
+
return lines;
|
|
1096
|
+
}
|
|
1097
|
+
function verdictOf(baseline) {
|
|
1098
|
+
const of = `${baseline.samples} call${baseline.samples === 1 ? "" : "s"} to ${baseline.route}`;
|
|
1099
|
+
if (baseline.verdict === "slower") return `slower than 95% of ${of}`;
|
|
1100
|
+
if (baseline.verdict === "faster") return `faster than the average of ${of}`;
|
|
1101
|
+
return `typical for this route, over ${of}`;
|
|
1102
|
+
}
|
|
1103
|
+
function spanSummary(detail) {
|
|
1104
|
+
const duplicated = /* @__PURE__ */ new Set();
|
|
1105
|
+
for (const finding of detail.findings) {
|
|
1106
|
+
if (finding.detector === "dup_http" || finding.detector === "dup_cache") {
|
|
1107
|
+
for (const id of [...finding.evidence.spanIds].sort((a, b) => a - b).slice(1)) {
|
|
1108
|
+
duplicated.add(id);
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
const parts = [`${detail.spans.length} spans`];
|
|
1113
|
+
if (duplicated.size > 0) parts.push(`${duplicated.size} of them duplicated`);
|
|
1114
|
+
if (detail.droppedSpans > 0) parts.push(`${detail.droppedSpans} dropped`);
|
|
1115
|
+
return parts.join(", ");
|
|
1116
|
+
}
|
|
1117
|
+
function responseSummary(detail, theme) {
|
|
1118
|
+
const headers = detail.responseHeaders;
|
|
1119
|
+
const type = headers["content-type"]?.split(";")[0];
|
|
1120
|
+
const length = Number(headers["content-length"] ?? Number.NaN);
|
|
1121
|
+
const size = Number.isFinite(length) ? bytes(length) : detail.responseBody ? bytes(Buffer.byteLength(detail.responseBody.text)) : null;
|
|
1122
|
+
const rows = detail.weight?.rows ? `${detail.weight.rows.toLocaleString("en-US")} rows` : null;
|
|
1123
|
+
const parts = [
|
|
1124
|
+
String(detail.status),
|
|
1125
|
+
type,
|
|
1126
|
+
size,
|
|
1127
|
+
rows,
|
|
1128
|
+
headers["etag"] ? `etag ${headers["etag"]}` : null
|
|
1129
|
+
];
|
|
1130
|
+
return cut(
|
|
1131
|
+
parts.filter(Boolean).join(" "),
|
|
1132
|
+
Math.min(theme.width, BLOCK2) - SUMMARY - 1,
|
|
1133
|
+
theme.glyph("ellipsis")
|
|
1134
|
+
);
|
|
1135
|
+
}
|
|
1136
|
+
function responseLines(detail, theme) {
|
|
1137
|
+
const lines = [heading("RESPONSE", responseSummary(detail, theme), theme)];
|
|
1138
|
+
const timing = detail.responseHeaders["server-timing"];
|
|
1139
|
+
if (timing) {
|
|
1140
|
+
lines.push(theme.paint("dim", ` server-timing ${timing.split(/,\s*/).join(" ")}`));
|
|
1141
|
+
}
|
|
1142
|
+
if (detail.responseBody) {
|
|
1143
|
+
const room = Math.min(theme.width, BLOCK2) - 16;
|
|
1144
|
+
const body = detail.responseBody.text.replace(/\s+/g, " ").trim();
|
|
1145
|
+
lines.push(
|
|
1146
|
+
theme.paint("dim", " body ") + theme.paint("plain", cut(body, room, theme.glyph("ellipsis")))
|
|
1147
|
+
);
|
|
1148
|
+
}
|
|
1149
|
+
if (detail.error) {
|
|
1150
|
+
lines.push(
|
|
1151
|
+
"",
|
|
1152
|
+
theme.paint("err", ` ${detail.error.name}`) + theme.paint("dim", `: ${detail.error.message}`)
|
|
1153
|
+
);
|
|
1154
|
+
const frame = frameOf(detail.error.stack);
|
|
1155
|
+
if (frame) lines.push(theme.paint("dim", ` ${frame}`));
|
|
1156
|
+
}
|
|
1157
|
+
return lines;
|
|
1158
|
+
}
|
|
1159
|
+
function trailingCommands(detail, theme) {
|
|
1160
|
+
const queries2 = detail.sqlCount;
|
|
1161
|
+
const commands = [];
|
|
1162
|
+
if (detail.responseBody) {
|
|
1163
|
+
commands.push([`reqray show ${detail.id} --body`, "the whole response body"]);
|
|
1164
|
+
}
|
|
1165
|
+
if (queries2 > 0) {
|
|
1166
|
+
commands.push([
|
|
1167
|
+
`reqray show ${detail.id} --sql`,
|
|
1168
|
+
queries2 === 1 ? "the query it ran, and where from" : `all ${queries2} queries with their callsites`
|
|
1169
|
+
]);
|
|
1170
|
+
}
|
|
1171
|
+
const column = Math.max(...commands.map(([command]) => command.length), 0) + 8;
|
|
1172
|
+
return commands.map(
|
|
1173
|
+
([command, note]) => theme.paint("cmd", ` ${command}`) + theme.paint("dim", " ".repeat(Math.max(2, column - command.length)) + note)
|
|
1174
|
+
);
|
|
1175
|
+
}
|
|
1176
|
+
function detailScreen(detail, theme, compared = { baseline: null, pressure: null }) {
|
|
1177
|
+
const lines = [detailHeader(detail, theme), ""];
|
|
1178
|
+
const timing = timingLines(detail, compared, theme);
|
|
1179
|
+
if (timing.length > 0) lines.push(...timing, "");
|
|
1180
|
+
if (detail.spans.length > 0) {
|
|
1181
|
+
lines.push(heading("WATERFALL", spanSummary(detail), theme));
|
|
1182
|
+
lines.push(...waterfallLines(detail, theme));
|
|
1183
|
+
lines.push("");
|
|
1184
|
+
}
|
|
1185
|
+
if (detail.findings.length > 0) {
|
|
1186
|
+
lines.push(heading("FINDINGS", String(detail.findings.length), theme), "");
|
|
1187
|
+
lines.push(...findingLines(detail, theme));
|
|
1188
|
+
lines.push("");
|
|
1189
|
+
}
|
|
1190
|
+
lines.push(...responseLines(detail, theme));
|
|
1191
|
+
const trailing = trailingCommands(detail, theme);
|
|
1192
|
+
if (trailing.length > 0) lines.push("", ...trailing);
|
|
1193
|
+
return lines;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
// src/render/sql.ts
|
|
1197
|
+
var MAX_LINES = 3;
|
|
1198
|
+
var HANG = 7;
|
|
1199
|
+
var BLOCK3 = 100;
|
|
1200
|
+
var isDb = (span) => span.kind === "db";
|
|
1201
|
+
function queriesOf(detail) {
|
|
1202
|
+
const looped = /* @__PURE__ */ new Set();
|
|
1203
|
+
for (const finding of detail.findings) {
|
|
1204
|
+
if (finding.detector !== "n_plus_one") continue;
|
|
1205
|
+
for (const id of finding.evidence.spanIds) looped.add(id);
|
|
1206
|
+
}
|
|
1207
|
+
const entries = [];
|
|
1208
|
+
let loopDone = false;
|
|
1209
|
+
for (const span of detail.spans.filter(isDb)) {
|
|
1210
|
+
if (looped.has(span.id)) {
|
|
1211
|
+
if (loopDone) continue;
|
|
1212
|
+
loopDone = true;
|
|
1213
|
+
const group = detail.spans.filter((entry) => isDb(entry) && looped.has(entry.id));
|
|
1214
|
+
entries.push({
|
|
1215
|
+
ref: `q${entries.length + 1}`,
|
|
1216
|
+
sql: span.sql,
|
|
1217
|
+
totalMs: group.reduce((sum, entry) => sum + entry.duration, 0),
|
|
1218
|
+
calls: group.length,
|
|
1219
|
+
rows: span.rowCount,
|
|
1220
|
+
callsite: siteOf(span),
|
|
1221
|
+
badge: "N+1"
|
|
1222
|
+
});
|
|
1223
|
+
continue;
|
|
1224
|
+
}
|
|
1225
|
+
entries.push({
|
|
1226
|
+
ref: `q${entries.length + 1}`,
|
|
1227
|
+
sql: span.sql,
|
|
1228
|
+
totalMs: span.duration,
|
|
1229
|
+
calls: 1,
|
|
1230
|
+
rows: span.rowCount,
|
|
1231
|
+
callsite: siteOf(span),
|
|
1232
|
+
badge: null
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
return entries;
|
|
1236
|
+
}
|
|
1237
|
+
function siteOf(span) {
|
|
1238
|
+
return span.callsite ? `${span.callsite.relative}:${span.callsite.line}` : null;
|
|
1239
|
+
}
|
|
1240
|
+
var KEYWORDS = /^(SELECT|FROM|WHERE|INNER|OUTER|LEFT|RIGHT|JOIN|ON|AND|OR|ORDER|GROUP|BY|LIMIT|OFFSET|IN|AS|COUNT|SUM|AVG|MIN|MAX|NOT|NULL|IS|DESC|ASC|INSERT|INTO|VALUES|UPDATE|SET|DELETE|RETURNING|DISTINCT|HAVING|WITH|CASE|WHEN|THEN|ELSE|END)$/i;
|
|
1241
|
+
function paintSql(line, theme) {
|
|
1242
|
+
return line.split(/(\s+|,|\(|\))/).filter((token) => token !== "").map((token) => {
|
|
1243
|
+
const bare = token.trim();
|
|
1244
|
+
if (!bare) return token;
|
|
1245
|
+
if (KEYWORDS.test(bare)) return theme.paint("cmd", token);
|
|
1246
|
+
if (/^'.*'$/.test(bare) || /^\$\d+$/.test(bare) || /^\d+$/.test(bare)) {
|
|
1247
|
+
return theme.paint("ok", token);
|
|
1248
|
+
}
|
|
1249
|
+
return theme.paint("plain", token);
|
|
1250
|
+
}).join("");
|
|
1251
|
+
}
|
|
1252
|
+
function wrapSql(sql, width) {
|
|
1253
|
+
const words = sql.replace(/\s+/g, " ").trim().split(" ");
|
|
1254
|
+
const lines = [];
|
|
1255
|
+
let current = "";
|
|
1256
|
+
for (const word of words) {
|
|
1257
|
+
if (current === "") current = word;
|
|
1258
|
+
else if (current.length + 1 + word.length <= width) current += ` ${word}`;
|
|
1259
|
+
else {
|
|
1260
|
+
lines.push(current);
|
|
1261
|
+
current = word;
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
if (current !== "") lines.push(current);
|
|
1265
|
+
return lines;
|
|
1266
|
+
}
|
|
1267
|
+
function sqlLines(detail, theme, options = {}) {
|
|
1268
|
+
const entries = queriesOf(detail);
|
|
1269
|
+
const asked = options.only?.toLowerCase() ?? null;
|
|
1270
|
+
const wanted = asked ? entries.filter((entry) => entry.ref === asked) : entries;
|
|
1271
|
+
if (entries.length === 0) {
|
|
1272
|
+
return [theme.paint("plain", " this request ran no queries")];
|
|
1273
|
+
}
|
|
1274
|
+
if (wanted.length === 0) {
|
|
1275
|
+
return [
|
|
1276
|
+
theme.paint("plain", ` no query called ${options.only} in this request`),
|
|
1277
|
+
theme.paint("dim", ` it has ${entries.length}: ${entries.map((e) => e.ref).join(" ")}`)
|
|
1278
|
+
];
|
|
1279
|
+
}
|
|
1280
|
+
const width = Math.max(20, Math.min(theme.width, BLOCK3) - HANG - 1);
|
|
1281
|
+
const lines = [];
|
|
1282
|
+
wanted.forEach((entry, index) => {
|
|
1283
|
+
if (index > 0) lines.push("");
|
|
1284
|
+
const cells = [
|
|
1285
|
+
[entry.badge ? "! " : " ", (text) => theme.paint("warn", text)],
|
|
1286
|
+
[pad(entry.ref, 5), (text) => theme.paint("dim", text)],
|
|
1287
|
+
[pad(spanDuration(entry.totalMs), 8), (text) => theme.paint("plain", text)],
|
|
1288
|
+
[
|
|
1289
|
+
pad(entry.calls > 1 ? `${entry.calls} calls` : rowsOf(entry), 12),
|
|
1290
|
+
(t) => theme.paint("dim", t)
|
|
1291
|
+
],
|
|
1292
|
+
[entry.callsite ?? "", (text) => theme.paint("dim", text)]
|
|
1293
|
+
];
|
|
1294
|
+
const plain = cells.map(([text]) => text).join("").trimEnd();
|
|
1295
|
+
let head = cells.map(([text, paint]) => paint(text)).join("").trimEnd();
|
|
1296
|
+
if (entry.badge) {
|
|
1297
|
+
const gap = Math.max(3, Math.min(theme.width, BLOCK3) - plain.length - entry.badge.length - 1);
|
|
1298
|
+
head += " ".repeat(gap) + theme.paint("warnLoud", entry.badge);
|
|
1299
|
+
}
|
|
1300
|
+
lines.push(head, "");
|
|
1301
|
+
const wrapped = wrapSql(entry.sql, width);
|
|
1302
|
+
const shown = options.full ? wrapped : wrapped.slice(0, MAX_LINES);
|
|
1303
|
+
for (const line of shown) lines.push(" ".repeat(HANG) + paintSql(line, theme));
|
|
1304
|
+
const rest = wrapped.length - shown.length;
|
|
1305
|
+
if (rest > 0) {
|
|
1306
|
+
const tail = `${" ".repeat(HANG)}${theme.glyph("ellipsis")} ${rest} more lines`;
|
|
1307
|
+
const command = `reqray show ${detail.id} --sql ${entry.ref} --full`;
|
|
1308
|
+
const gap = Math.max(3, Math.min(theme.width, BLOCK3) - tail.length - command.length - 1);
|
|
1309
|
+
lines.push(theme.paint("dim", tail) + " ".repeat(gap) + theme.paint("cmd", command));
|
|
1310
|
+
}
|
|
1311
|
+
});
|
|
1312
|
+
return lines.map((line) => line.trimEnd());
|
|
1313
|
+
}
|
|
1314
|
+
function rowsOf(entry) {
|
|
1315
|
+
return entry.rows === null ? "" : `${entry.rows} rows`;
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
// src/commands/show.ts
|
|
1319
|
+
var FLAGS = {
|
|
1320
|
+
last: "boolean",
|
|
1321
|
+
failed: "boolean",
|
|
1322
|
+
slowest: "boolean",
|
|
1323
|
+
path: "string",
|
|
1324
|
+
json: "boolean",
|
|
1325
|
+
body: "boolean",
|
|
1326
|
+
sql: "optional",
|
|
1327
|
+
full: "boolean"
|
|
1328
|
+
};
|
|
1329
|
+
function sqlRef(context) {
|
|
1330
|
+
const raw = stringFlag(context.args, "sql");
|
|
1331
|
+
if (raw === null) return void 0;
|
|
1332
|
+
return raw.trim() === "" ? null : raw.trim();
|
|
1333
|
+
}
|
|
1334
|
+
var show = {
|
|
1335
|
+
name: "show",
|
|
1336
|
+
summary: "one request, whole",
|
|
1337
|
+
flags: FLAGS,
|
|
1338
|
+
async run(context) {
|
|
1339
|
+
const { client, globals, out, signal } = context;
|
|
1340
|
+
const id = await resolveId(context);
|
|
1341
|
+
if (id === null) return EXIT_OK;
|
|
1342
|
+
if (boolFlag(context.args, "json")) {
|
|
1343
|
+
out.line(await client.detailRaw(id, signal));
|
|
1344
|
+
return EXIT_OK;
|
|
1345
|
+
}
|
|
1346
|
+
const detail = await client.detail(id, signal);
|
|
1347
|
+
if (boolFlag(context.args, "body")) {
|
|
1348
|
+
out.line(bodyOf(detail));
|
|
1349
|
+
return EXIT_OK;
|
|
1350
|
+
}
|
|
1351
|
+
const ref = sqlRef(context);
|
|
1352
|
+
if (ref !== void 0) {
|
|
1353
|
+
const lines = sqlLines(detail, globals.theme, {
|
|
1354
|
+
only: ref,
|
|
1355
|
+
full: boolFlag(context.args, "full")
|
|
1356
|
+
});
|
|
1357
|
+
for (const line of lines) out.line(line);
|
|
1358
|
+
return EXIT_OK;
|
|
1359
|
+
}
|
|
1360
|
+
const compared = await client.baseline(id, signal);
|
|
1361
|
+
for (const line of detailScreen(detail, globals.theme, compared)) out.line(line);
|
|
1362
|
+
return EXIT_OK;
|
|
1363
|
+
}
|
|
1364
|
+
};
|
|
1365
|
+
function pathQuery(context) {
|
|
1366
|
+
const raw = stringFlag(context.args, "path");
|
|
1367
|
+
if (raw === null) return null;
|
|
1368
|
+
const trimmed = raw.replace(/^\*+/, "").replace(/\*+$/, "").trim();
|
|
1369
|
+
if (trimmed === "") {
|
|
1370
|
+
throw new UsageError("--path wants something to look for, not just a wildcard");
|
|
1371
|
+
}
|
|
1372
|
+
return trimmed;
|
|
1373
|
+
}
|
|
1374
|
+
function bodyOf(detail) {
|
|
1375
|
+
if (!detail.responseBody) return "this request recorded no response body";
|
|
1376
|
+
const { text, truncated } = detail.responseBody;
|
|
1377
|
+
return truncated ? `${text}
|
|
1378
|
+
\u2026 cut at the recorded limit` : text;
|
|
1379
|
+
}
|
|
1380
|
+
var FORMS = [
|
|
1381
|
+
"",
|
|
1382
|
+
" reqray show 8974 that request",
|
|
1383
|
+
" reqray show --last the one that just finished",
|
|
1384
|
+
" reqray show --last --failed the last one that failed",
|
|
1385
|
+
" reqray show --last --slowest the slowest one recorded",
|
|
1386
|
+
" reqray show --last --path /orders the last one to a path",
|
|
1387
|
+
"",
|
|
1388
|
+
" reqray watch --ids prints the identifier of every row"
|
|
1389
|
+
];
|
|
1390
|
+
async function resolveId(context) {
|
|
1391
|
+
const { args, client, out, globals, signal } = context;
|
|
1392
|
+
const given = args.positionals[0];
|
|
1393
|
+
const failed = boolFlag(args, "failed");
|
|
1394
|
+
const slowest = boolFlag(args, "slowest");
|
|
1395
|
+
const path = pathQuery(context);
|
|
1396
|
+
const last = boolFlag(args, "last") || failed || slowest || path !== null;
|
|
1397
|
+
if (given && last) {
|
|
1398
|
+
throw new UsageError("give show an id or a question, not both", FORMS);
|
|
1399
|
+
}
|
|
1400
|
+
if (given) return given;
|
|
1401
|
+
if (!last) {
|
|
1402
|
+
throw new UsageError("show needs an id, or a question to ask instead", FORMS);
|
|
1403
|
+
}
|
|
1404
|
+
const query = {
|
|
1405
|
+
limit: 1,
|
|
1406
|
+
...failed ? { onlyErrors: true } : {},
|
|
1407
|
+
...slowest ? { sort: "slowest" } : {},
|
|
1408
|
+
...path ? { query: path } : {}
|
|
1409
|
+
};
|
|
1410
|
+
const page = await client.list(query, signal);
|
|
1411
|
+
const row = page.requests[0];
|
|
1412
|
+
if (row) return row.id;
|
|
1413
|
+
const what = path ? `nothing recorded matches "${path}"` : failed ? "no request has failed yet" : "nothing has been recorded yet";
|
|
1414
|
+
out.line(globals.theme.paint("plain", ` ${what}`));
|
|
1415
|
+
out.line(
|
|
1416
|
+
globals.theme.paint(
|
|
1417
|
+
"dim",
|
|
1418
|
+
" the panel is attached and answering \u2014 it just has nothing to show"
|
|
1419
|
+
)
|
|
1420
|
+
);
|
|
1421
|
+
return null;
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
// src/commands/watch.ts
|
|
1425
|
+
var DETAIL_TIMEOUT_MS = 1e3;
|
|
1426
|
+
var FLAGS2 = {
|
|
1427
|
+
ids: "boolean",
|
|
1428
|
+
"slower-than": "string",
|
|
1429
|
+
status: "list",
|
|
1430
|
+
method: "list",
|
|
1431
|
+
path: "string",
|
|
1432
|
+
"findings-only": "boolean"
|
|
1433
|
+
};
|
|
1434
|
+
function filterFrom(context) {
|
|
1435
|
+
return {
|
|
1436
|
+
slowerThanMs: numberFlag(context.args, "slower-than"),
|
|
1437
|
+
statuses: listFlag(context.args, "status"),
|
|
1438
|
+
methods: listFlag(context.args, "method"),
|
|
1439
|
+
path: stringFlag(context.args, "path"),
|
|
1440
|
+
findingsOnly: boolFlag(context.args, "findings-only")
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
var watch = {
|
|
1444
|
+
name: "watch",
|
|
1445
|
+
summary: "follow requests as they happen",
|
|
1446
|
+
flags: FLAGS2,
|
|
1447
|
+
async run(context) {
|
|
1448
|
+
const { client, globals, out, signal } = context;
|
|
1449
|
+
const filter = filterFrom(context);
|
|
1450
|
+
const meta = await client.meta(signal);
|
|
1451
|
+
for (const line of header(context.version, globals.url, meta, globals.theme)) out.line(line);
|
|
1452
|
+
const ids = { ids: boolFlag(context.args, "ids") };
|
|
1453
|
+
const recorded = await client.list({ limit: 1 }, signal);
|
|
1454
|
+
let headPrinted = false;
|
|
1455
|
+
if (recorded.requests.length === 0) {
|
|
1456
|
+
for (const line of emptyState(globals.url, meta, globals.theme)) out.line(line);
|
|
1457
|
+
} else {
|
|
1458
|
+
out.line(streamHead(globals.theme, ids));
|
|
1459
|
+
headPrinted = true;
|
|
1460
|
+
}
|
|
1461
|
+
let printing = Promise.resolve();
|
|
1462
|
+
await client.stream({
|
|
1463
|
+
signal,
|
|
1464
|
+
onNotice: (text) => {
|
|
1465
|
+
printing = printing.then(() => {
|
|
1466
|
+
out.line(noticeLine(text, globals.theme));
|
|
1467
|
+
});
|
|
1468
|
+
},
|
|
1469
|
+
onRow: (payload) => {
|
|
1470
|
+
const row = payload;
|
|
1471
|
+
if (!matches(row, filter)) return;
|
|
1472
|
+
printing = printing.then(async () => {
|
|
1473
|
+
if (!headPrinted) {
|
|
1474
|
+
out.line("");
|
|
1475
|
+
out.line(streamHead(globals.theme, ids));
|
|
1476
|
+
headPrinted = true;
|
|
1477
|
+
}
|
|
1478
|
+
out.line(streamRow(row, globals.theme, ids));
|
|
1479
|
+
if (!row.hasError) return;
|
|
1480
|
+
const detail = await detailFor(context, row);
|
|
1481
|
+
for (const line of failureLines(row, detail, globals.theme)) out.line(line);
|
|
1482
|
+
});
|
|
1483
|
+
}
|
|
1484
|
+
});
|
|
1485
|
+
await printing;
|
|
1486
|
+
return EXIT_OK;
|
|
1487
|
+
}
|
|
1488
|
+
};
|
|
1489
|
+
async function detailFor(context, row) {
|
|
1490
|
+
const timeout = AbortSignal.timeout(DETAIL_TIMEOUT_MS);
|
|
1491
|
+
const signal = AbortSignal.any([context.signal, timeout]);
|
|
1492
|
+
try {
|
|
1493
|
+
return await context.client.detail(row.id, signal);
|
|
1494
|
+
} catch {
|
|
1495
|
+
return null;
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
// src/commands/index.ts
|
|
1500
|
+
var COMMANDS = [watch, show];
|
|
1501
|
+
function commandNamed(name) {
|
|
1502
|
+
return COMMANDS.find((command) => command.name === name) ?? null;
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
// src/version.ts
|
|
1506
|
+
import { readFileSync } from "fs";
|
|
1507
|
+
var cached = null;
|
|
1508
|
+
function cliVersion() {
|
|
1509
|
+
if (cached !== null) return cached;
|
|
1510
|
+
try {
|
|
1511
|
+
const manifest = readFileSync(new URL("../package.json", import.meta.url), "utf8");
|
|
1512
|
+
cached = JSON.parse(manifest).version ?? "0.0.0";
|
|
1513
|
+
} catch {
|
|
1514
|
+
cached = "0.0.0";
|
|
1515
|
+
}
|
|
1516
|
+
return cached;
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
// src/app.ts
|
|
1520
|
+
async function run(argv, runtime) {
|
|
1521
|
+
const version = cliVersion();
|
|
1522
|
+
const out = streamWriter(runtime.stdout);
|
|
1523
|
+
const errors = streamWriter(runtime.stderr);
|
|
1524
|
+
try {
|
|
1525
|
+
const first = argv[0];
|
|
1526
|
+
if (first === void 0 || first === "--help" || first === "-h") {
|
|
1527
|
+
for (const line of usage(version, runtime)) out.line(line);
|
|
1528
|
+
return first === void 0 ? EXIT_USAGE : EXIT_OK;
|
|
1529
|
+
}
|
|
1530
|
+
if (first === "--version" || first === "-V") {
|
|
1531
|
+
out.line(version);
|
|
1532
|
+
return EXIT_OK;
|
|
1533
|
+
}
|
|
1534
|
+
if (first.startsWith("-")) {
|
|
1535
|
+
throw new UsageError(`reqray needs a command before ${first}`, [
|
|
1536
|
+
"",
|
|
1537
|
+
` commands ${COMMANDS.map((command2) => command2.name).join(" ")}`
|
|
1538
|
+
]);
|
|
1539
|
+
}
|
|
1540
|
+
const command = commandNamed(first);
|
|
1541
|
+
if (!command) {
|
|
1542
|
+
throw new UsageError(`there is no command called "${first}"`, [
|
|
1543
|
+
"",
|
|
1544
|
+
` commands ${COMMANDS.map((entry) => entry.name).join(" ")}`
|
|
1545
|
+
]);
|
|
1546
|
+
}
|
|
1547
|
+
const args = parseArgs(argv.slice(1), { ...GLOBAL_FLAGS, ...command.flags });
|
|
1548
|
+
if (args.flags["help"] === true) {
|
|
1549
|
+
for (const line of usage(version, runtime)) out.line(line);
|
|
1550
|
+
return EXIT_OK;
|
|
1551
|
+
}
|
|
1552
|
+
const globals = resolveGlobals(args, runtime);
|
|
1553
|
+
if (globals.theme.width < MIN_WIDTH && args.flags["json"] !== true) {
|
|
1554
|
+
throw new UsageError(
|
|
1555
|
+
`this terminal is ${globals.theme.width} columns wide; reqray needs ${MIN_WIDTH}`,
|
|
1556
|
+
["", " widen the window, or pipe the output somewhere that has room"]
|
|
1557
|
+
);
|
|
1558
|
+
}
|
|
1559
|
+
const client = new ReqrayClient({ url: globals.url, token: globals.token });
|
|
1560
|
+
return await command.run({
|
|
1561
|
+
client,
|
|
1562
|
+
globals,
|
|
1563
|
+
args,
|
|
1564
|
+
out,
|
|
1565
|
+
version,
|
|
1566
|
+
signal: runtime.signal ?? new AbortController().signal
|
|
1567
|
+
});
|
|
1568
|
+
} catch (error) {
|
|
1569
|
+
if (isAbort(error)) return EXIT_OK;
|
|
1570
|
+
const theme = resolveTheme(runtime.env, runtime.stderr);
|
|
1571
|
+
for (const line of renderFailure(error, theme, argv.includes("--verbose"))) errors.line(line);
|
|
1572
|
+
return error instanceof CliError ? error.exitCode : EXIT_FAILED;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
function isAbort(error) {
|
|
1576
|
+
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
|
|
1577
|
+
}
|
|
1578
|
+
function usage(version, runtime) {
|
|
1579
|
+
const theme = resolveTheme(runtime.env, runtime.stdout);
|
|
1580
|
+
const command = (name, summary) => theme.paint("cmd", ` reqray ${name}`.padEnd(22)) + theme.paint("dim", summary);
|
|
1581
|
+
const flag = (name, summary) => theme.paint("dim", ` ${name.padEnd(20)}${summary}`);
|
|
1582
|
+
return [
|
|
1583
|
+
theme.paint("plain", `reqray ${version}`) + theme.paint("dim", " the panel, from the terminal"),
|
|
1584
|
+
"",
|
|
1585
|
+
command("watch", "follow requests as they happen"),
|
|
1586
|
+
command("show <id>", "one request, whole"),
|
|
1587
|
+
"",
|
|
1588
|
+
flag("--ids", "watch: print the identifier show takes"),
|
|
1589
|
+
flag("--last --path <s>", "show: the last request to a path"),
|
|
1590
|
+
"",
|
|
1591
|
+
flag("--url <address>", `where the panel is (${DEFAULT_URL})`),
|
|
1592
|
+
flag("--token <token>", "for a collector started with one"),
|
|
1593
|
+
flag("--no-color", "no escape codes, whatever the terminal is"),
|
|
1594
|
+
flag("--ascii", "no box-drawing characters"),
|
|
1595
|
+
flag("--verbose", "print what actually failed"),
|
|
1596
|
+
"",
|
|
1597
|
+
theme.paint("dim", " REQRAY_URL and REQRAY_TOKEN say the same as the two flags.")
|
|
1598
|
+
];
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
export {
|
|
1602
|
+
EXIT_OK,
|
|
1603
|
+
EXIT_FAILED,
|
|
1604
|
+
EXIT_USAGE,
|
|
1605
|
+
CliError,
|
|
1606
|
+
UsageError,
|
|
1607
|
+
UnreachableError,
|
|
1608
|
+
ReqrayClient,
|
|
1609
|
+
MIN_WIDTH,
|
|
1610
|
+
streamColumns,
|
|
1611
|
+
fitPath,
|
|
1612
|
+
streamHead,
|
|
1613
|
+
streamRow,
|
|
1614
|
+
failureLines,
|
|
1615
|
+
matches,
|
|
1616
|
+
header,
|
|
1617
|
+
emptyState,
|
|
1618
|
+
renderFailure,
|
|
1619
|
+
resolveTheme,
|
|
1620
|
+
plainTheme,
|
|
1621
|
+
DEFAULT_URL,
|
|
1622
|
+
normalizeUrl,
|
|
1623
|
+
run
|
|
1624
|
+
};
|
|
1625
|
+
//# sourceMappingURL=chunk-V6ZCA7CU.js.map
|