@reqray/core 0.1.0 → 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/README.md +50 -5
- package/dist/panel/index.cjs.map +1 -1
- package/dist/panel/index.d.cts +1 -1
- package/dist/panel/index.d.ts +1 -1
- package/dist/panel/index.js.map +1 -1
- package/package.json +2 -2
package/dist/panel/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/panel/activity.ts","../../src/panel/api.ts","../../src/panel/findings.ts","../../src/panel/routes.ts","../../src/panel/baseline.ts","../../src/panel/exceptions.ts","../../src/panel/explain.ts","../../src/panel/export.ts","../../src/panel/filters.ts","../../src/panel/timeline.ts","../../src/panel/history.ts","../../src/panel/paging.ts","../../src/panel/page-from-list.ts","../../src/panel/pressure.ts","../../src/panel/replay.ts","../../src/panel/series.ts"],"sourcesContent":["/**\n * What ran here.\n *\n * A chart nobody can click is decoration. Clicking a moment on one should\n * answer the only question worth asking of it — what was different then —\n * and the answer has to be ranked by *how far each route strayed from its own\n * behaviour*, not by how much traffic it had. Ranked by volume, the busiest\n * endpoint tops every list and the moment explains nothing.\n *\n * Every route is compared against itself over the rest of the window, so a\n * spike does not inflate the baseline it is being measured against. When\n * nothing stands out, the answer is that nothing did: whatever moved the\n * chart came from garbage collection, a neighbour on the box, or the host —\n * and a list of ordinary routes presented as an explanation is worse than a\n * sentence admitting there is none.\n */\n\nimport type { ActivityReport, Outlier } from '@reqray/protocol';\n\nexport type { ActivityReport, Outlier };\n\n/** One route's traffic over a stretch of time, as the store groups it. */\nexport interface RouteWindow {\n readonly method: string;\n readonly route: string;\n readonly calls: number;\n /** Mean duration over those calls, ms. */\n readonly avgMs: number;\n}\n\n/**\n * Calls a route needs in the moment before it can be called unusual.\n *\n * Two calls that happened to be slow are two calls that happened to be slow.\n */\nconst MIN_CALLS = 3;\n\n/**\n * How far from its own baseline a route has to be.\n *\n * Half again, on either rate or duration. Below that the difference is inside\n * the noise of a handful of calls, and a list that includes it is a list of\n * everything that ran.\n */\nconst MIN_RATIO = 1.5;\n\n/**\n * How many calls above its usual count a route has to be.\n *\n * A ratio alone is not enough at low rates: a route called twice a minute\n * that happens to be called three times has run at 1.5× its rate and nothing\n * has happened. Three extra calls is the smallest excess that is a count\n * rather than a rounding of one.\n */\nconst MIN_EXCESS_CALLS = 3;\n\n/**\n * How much slower, in milliseconds, before a ratio means anything.\n *\n * A route that goes from 0.2 ms to 0.4 ms has doubled and nobody has noticed.\n * Five milliseconds is the smallest difference somebody could experience, and\n * below it a ratio is reporting the jitter of the clock.\n */\nconst MIN_EXCESS_MS = 5;\n\n/**\n * What stood out in one stretch of time.\n *\n * @param moment routes grouped over the clicked stretch.\n * @param overall the same, over the whole window the chart covers — the\n * moment included, and subtracted here so a spike is not its own baseline.\n */\nexport function whatRanAt(\n moment: readonly RouteWindow[],\n overall: readonly RouteWindow[],\n window: { from: number; to: number; overallMs: number },\n): ActivityReport {\n const before = new Map(overall.map((entry) => [`${entry.method} ${entry.route}`, entry]));\n const momentMs = Math.max(1, window.to - window.from);\n // The rest of the window: what the route usually does, with the moment\n // taken out of it. Never negative, and never zero as a divisor.\n const restMs = Math.max(1, window.overallMs - momentMs);\n\n // How the moment compares as a whole. Bursty traffic — a demo restarting, a\n // cron waking up, a deploy draining a queue — lifts every route at once, and\n // without this every route is an outlier in every burst.\n const momentCalls = moment.reduce((total, entry) => total + entry.calls, 0);\n const overallCalls = overall.reduce((total, entry) => total + entry.calls, 0);\n const restOverall = Math.max(0, overallCalls - momentCalls);\n const overallRatio = restOverall > 0 ? momentCalls / momentMs / (restOverall / restMs) : null;\n\n /**\n * How much busier the moment was for everything *except* this route.\n *\n * Each route is judged against how the rest of the traffic moved, not\n * against the total it is part of — otherwise a route that is the only\n * thing running compares against itself and can never stand out, which is\n * exactly the case where it obviously does.\n */\n const withoutRatio = (entry: RouteWindow, restCalls: number): number | null => {\n const otherMoment = momentCalls - entry.calls;\n const otherRest = restOverall - restCalls;\n if (otherMoment <= 0 || otherRest <= 0) return null;\n return otherMoment / momentMs / (otherRest / restMs);\n };\n\n const outliers: Outlier[] = [];\n for (const entry of moment) {\n if (entry.calls < MIN_CALLS) continue;\n\n const all = before.get(`${entry.method} ${entry.route}`);\n const restCalls = Math.max(0, (all?.calls ?? 0) - entry.calls);\n\n // Never ran outside this moment: not a ratio, a fact.\n if (restCalls === 0) {\n outliers.push({\n method: entry.method,\n route: entry.route,\n calls: entry.calls,\n avgMs: entry.avgMs,\n rateRatio: null,\n slowerRatio: null,\n firstSeen: true,\n });\n continue;\n }\n\n const rate = restCalls / restMs;\n const rateRatio = entry.calls / momentMs / rate;\n // What this moment would have held if the route had simply grown with\n // everything else. The excess over *that* is the part worth reporting,\n // and at low rates it is what tells a burst from a coin toss.\n const others = withoutRatio(entry, restCalls);\n const expected = rate * momentMs * (others ?? 1);\n // The route against how the rest of the traffic moved: one means it rose\n // exactly as much as everything around it, which is not an answer to\n // \"what was different here\".\n const shareRatio = others === null ? rateRatio : rateRatio / others;\n // The mean over the rest, recovered from the totals: the store grouped\n // once, and asking it twice for overlapping ranges would cost a scan to\n // learn something arithmetic already knows.\n const restAvg =\n all && all.calls > 0\n ? Math.max(0, (all.avgMs * all.calls - entry.avgMs * entry.calls) / restCalls)\n : 0;\n const slowerRatio = restAvg > 0 ? entry.avgMs / restAvg : null;\n\n const busier = shareRatio >= MIN_RATIO && entry.calls - expected >= MIN_EXCESS_CALLS;\n const slower =\n slowerRatio !== null && slowerRatio >= MIN_RATIO && entry.avgMs - restAvg >= MIN_EXCESS_MS;\n if (!busier && !slower) continue;\n\n outliers.push({\n method: entry.method,\n route: entry.route,\n calls: entry.calls,\n avgMs: entry.avgMs,\n rateRatio,\n slowerRatio,\n firstSeen: false,\n });\n }\n\n const strength = (outlier: Outlier): number =>\n outlier.firstSeen\n ? Number.POSITIVE_INFINITY\n : Math.max(outlier.rateRatio ?? 0, outlier.slowerRatio ?? 0);\n\n return {\n from: window.from,\n to: window.to,\n calls: momentCalls,\n rateRatio: overallRatio,\n outliers: outliers.sort((a, b) => strength(b) - strength(a)),\n };\n}\n","/**\n * Panel HTTP API.\n *\n * The handler is written against raw `IncomingMessage`/`ServerResponse`, so\n * Express and Fastify mount the very same code — no need to duplicate the API\n * in each adapter.\n */\n\nimport { createReadStream, statSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { extname, resolve, sep } from 'node:path';\nimport type {\n FiledPatternState,\n PanelMeta,\n RequestRow,\n RequestSort,\n RequestSummary,\n SeriesMetric,\n StoredPatternState,\n} from '@reqray/protocol';\nimport type { ResolvedOptions } from '../config.js';\nimport { detectorSettings } from '../detectors/index.js';\nimport { warnOnce } from '../logger.js';\nimport { isPanelRequestAllowed } from '../panel.js';\nimport type { RetentionLimits } from '../retention.js';\nimport { ensureTiming } from '../timing.js';\nimport type { RecordedRequest } from '../types.js';\nimport { type RouteWindow, whatRanAt } from './activity.js';\nimport { type BaselineQuery, baselineFor } from './baseline.js';\nimport { blameLine } from './blame.js';\nimport { groupExceptions } from './exceptions.js';\nimport { ExplainError, runExplain } from './explain.js';\nimport { toCurlScript, toHar } from './export.js';\nimport { filterRequests, type RequestFilter } from './filters.js';\nimport { type FindingSamples, type FindingsQuery, flagWithMutes, patternsOf } from './findings.js';\nimport { type HistoryQuery, type HistorySamples, historyOf, SERIES_COLUMNS } from './history.js';\nimport { pageFromList } from './page-from-list.js';\nimport { pressureFor } from './pressure.js';\nimport { logOf, projectReport, retentionOf } from './project.js';\nimport { type ReplayInput, runReplay } from './replay.js';\nimport { normalizeRoute, routeStats } from './routes.js';\nimport { routeSeries, SERIES_BUCKETS } from './series.js';\nimport { buildTimeline, TIMELINE_BUCKETS, type TimePoint } from './timeline.js';\n\nexport type { RequestRow } from '@reqray/protocol';\n\n/** One page of the request list, newest first. */\nexport interface RequestPage {\n readonly rows: readonly RequestRow[];\n /** Feed back as `cursor` to get the next, older page. `null` — the end. */\n readonly nextCursor: string | null;\n /** Numbers for the status bar, over the whole store rather than the page. */\n readonly summary: RequestSummary;\n}\n\n/** What the panel asks a store for when it wants a page. */\nexport interface PageQuery {\n readonly filter: RequestFilter;\n readonly limit: number;\n /** Where to continue from. Absent or `null` — start at the beginning. */\n readonly cursor?: string | null | undefined;\n /**\n * What \"the beginning\" means: the newest requests, or the slowest.\n *\n * Defaults to `recent`. Sorting is the store's job rather than the\n * caller's — \"the slowest request\" over a history on disk cannot be found\n * by reading a page of it and comparing.\n */\n readonly sort?: RequestSort | undefined;\n}\n\n/** Where the panel gets its data. Implemented by the transport store. */\nexport interface PanelSource {\n /** Requests from newest to oldest. */\n list(): readonly RecordedRequest[];\n get(id: string): RecordedRequest | undefined;\n clear(): void;\n subscribe(listener: (request: RecordedRequest) => void): () => void;\n /**\n * Keeps a request past its turn in the ring buffer, or lets it go again.\n *\n * Optional: a store without pinning is still a valid source, and the panel\n * answers the pin route with an explanation instead of pretending.\n *\n * @returns `false` when the request is gone or the pin limit is reached.\n */\n pin?(id: string, pinned: boolean): boolean;\n /** Ids currently pinned. */\n pinned?(): readonly string[];\n /**\n * When, how long, and whether it failed — for every request the store\n * holds.\n *\n * Optional, and cheap on purpose: three numbers per request, so the strip\n * above the list can span the whole history instead of the page that\n * happens to be loaded. A source without it leaves the panel to draw from\n * the rows it has, which is what it always did.\n */\n timeSeries?(): readonly TimePoint[];\n /**\n * One page of the list, filtered and cut by the store itself.\n *\n * Optional, and the difference between a buffer and a history: reading\n * everything into memory to filter it is what an in-memory ring can afford\n * and a store on disk cannot. A source without this method is served by\n * `list()`, whole.\n */\n page?(query: PageQuery): RequestPage;\n /**\n * Durations of other calls of one route.\n *\n * Optional, and asked for rather than derived from `list()`: judging one\n * call against its route means reading that route's whole history, which a\n * ring buffer can afford to scan and a store on disk should answer with a\n * query. A source without it leaves the detail page with no verdict, which\n * is better than a verdict drawn from the last page that happened to load.\n */\n durations?(query: BaselineQuery): readonly DurationSample[];\n /**\n * Traffic grouped by route over a stretch of time.\n *\n * Optional, and an aggregate rather than a page: answering \"what ran in\n * this moment\" by reading the moment's requests would mean loading a busy\n * minute of them to count four numbers per route.\n */\n counts?(query: { from: number; to: number }): readonly RouteWindow[];\n /**\n * A period's requests, a handful of numbers each.\n *\n * Optional, and the one method that reads a *stretch* rather than a page or\n * a route: the history screen asks what a week did, and answering that from\n * `list()` would mean holding a week of payloads in memory to look at ten\n * fields in each. A store must bound what it reads and say when it stopped\n * — a truncated total presented as a complete one is worse than no screen.\n */\n history?(query: HistoryQuery): HistorySamples;\n /**\n * Finding occurrences over a stretch of time, one row each.\n *\n * Optional, and rare rows on purpose: requests with findings are a small\n * minority, so a store answers this from them alone instead of reading the\n * window. A source without it leaves the findings tab explaining itself\n * rather than empty.\n */\n findings?(query: FindingsQuery): FindingSamples;\n /**\n * The reader's own bookkeeping per pattern: `ack` or `muted`.\n *\n * Patterns in neither state are `new` and are simply absent. A store that\n * persists (SQLite) keeps these across restarts; the in-memory ring keeps\n * them exactly as long as it keeps the requests they are about.\n */\n findingStates?(): ReadonlyMap<string, FiledPatternState>;\n /** Remembers a state; `new` forgets the pattern. */\n setFindingState?(id: string, state: StoredPatternState): void;\n}\n\n/**\n * One call of a route, as the store hands it over.\n *\n * Four numbers rather than a record: judging a call against its route, or\n * drawing the route's last hour, means reading every call of it, and parsing\n * a few thousand JSON documents to look at one field in each is how a page\n * becomes slow.\n */\nexport interface DurationSample {\n readonly durationMs: number;\n /** Epoch ms — what the window the samples cover is measured from. */\n readonly startedAt: number;\n /** Threw, or answered 5xx — what the error-rate chart counts. */\n readonly hasError: boolean;\n /**\n * Mean event-loop delay while it ran, or `null` when nothing measured it.\n *\n * What splits a route's calls into \"the host was fine\" and \"the host was\n * struggling\" — the comparison that says whether the process was to blame.\n */\n readonly loopDelayMs: number | null;\n}\n\n/** Everything the panel handler needs to serve a request. */\nexport interface PanelHandlerInit {\n readonly source: PanelSource;\n readonly options: ResolvedOptions;\n /**\n * Directory with the built dashboard.\n *\n * Left out when `@reqray/dashboard` is not installed: the API keeps working\n * and the UI route answers with an explanation instead of a blank page.\n */\n readonly assetsDir?: string | undefined;\n}\n\n/**\n * Panel request handler.\n *\n * @returns `true` if the request belonged to the panel and has been handled.\n * `false` means it is an ordinary application request and must be passed on.\n */\nexport type PanelHandler = (request: IncomingMessage, response: ServerResponse) => boolean;\n\n/**\n * The transport the panel can read from, if there is one.\n *\n * A transport is a store when it can answer the four questions the panel\n * asks. An HTTP transport to an external collector cannot — the panel then\n * runs in the collector. Neither can a log file, which is write-only by\n * design, so a fan-out is searched through rather than tested as a whole.\n *\n * Warns when the panel is configured and nothing can serve it: a panel that\n * quietly does not mount is a 404 nobody can explain.\n */\nexport function panelSourceFor(transport: unknown, options: ResolvedOptions): PanelSource | null {\n const direct = asPanelSource(transport);\n if (direct) return direct;\n\n const members = (transport as { transports?: readonly unknown[] } | null)?.transports;\n if (Array.isArray(members)) {\n for (const member of members) {\n const found = asPanelSource(member);\n if (found) return found;\n }\n }\n\n if (options.enabled && options.panel) {\n const name = (transport as { name?: unknown } | null)?.name;\n warnOnce(\n 'panel.source',\n `the panel is not mounted: ${typeof name === 'string' ? name : 'this transport'} keeps no requests to show. ` +\n 'A store — @reqray/store-memory or @reqray/store-sqlite — has to be among the transports.',\n );\n }\n return null;\n}\n\n/** Whether a transport can answer what the panel asks of a store. */\nfunction asPanelSource(transport: unknown): PanelSource | null {\n const candidate = transport as Partial<PanelSource> | null;\n if (!candidate) return null;\n const complete =\n typeof candidate.list === 'function' &&\n typeof candidate.get === 'function' &&\n typeof candidate.clear === 'function' &&\n typeof candidate.subscribe === 'function';\n return complete ? (candidate as PanelSource) : null;\n}\n\n/**\n * Projects a record into a list row.\n *\n * The whole list is served on every panel open, and full records with spans\n * and bodies would weigh megabytes. Details come from a separate request by\n * identifier.\n */\nexport function toRow(request: RecordedRequest, pinned = false): RequestRow {\n let sqlCount = 0;\n let httpCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n else if (span.kind === 'http') httpCount++;\n }\n\n return {\n id: request.id,\n method: request.method,\n path: request.path,\n query: request.query,\n route: normalizeRoute(request.path),\n status: request.status,\n durationMs: request.durationMs,\n startedAt: request.startedAt,\n sqlCount,\n httpCount,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n findingCount: request.findings.length,\n flag: [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null,\n hasError: request.error !== null || request.status >= 500,\n // Straight through, including the nulls: a row from a store written\n // before cost was measured has no cost, and inventing a zero would put a\n // cheap-looking request next to genuinely cheap ones.\n cpuMs: request.cost?.cpuMs ?? null,\n cpuShare: request.cost?.cpuShare ?? null,\n pinned,\n test: request.test,\n };\n}\n\n/** A file the browser saves rather than renders. */\nfunction sendDownload(\n response: ServerResponse,\n filename: string,\n contentType: string,\n body: string,\n): void {\n response.writeHead(200, {\n 'content-type': contentType,\n 'content-disposition': `attachment; filename=\"${filename}\"`,\n 'cache-control': 'no-store',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\nfunction sendJson(response: ServerResponse, status: number, payload: unknown): void {\n const body = JSON.stringify(payload);\n response.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\n/**\n * How many rows one page may hold.\n *\n * Capped rather than trusted: the parameter comes from a browser, and an\n * unbounded page defeats the point of having pages at all.\n */\nconst DEFAULT_PAGE_LIMIT = 100;\nconst MAX_PAGE_LIMIT = 500;\n\nfunction pageLimit(params: URLSearchParams): number {\n const asked = Number(params.get('limit'));\n if (!Number.isFinite(asked) || asked <= 0) return DEFAULT_PAGE_LIMIT;\n return Math.min(Math.floor(asked), MAX_PAGE_LIMIT);\n}\n\n/** A positive finite number from a query parameter, or `undefined`. */\nfunction positive(raw: string | null): number | undefined {\n const value = Number(raw);\n return Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\nconst HOUR_MS = 60 * 60 * 1000;\n\n/** Every metric the history screen may ask for. Nothing outside this list. */\nconst METRICS: readonly SeriesMetric[] = [\n 'p50',\n 'p95',\n 'p99',\n 'throughput',\n 'errorRate',\n 'sqlPerRequest',\n 'httpPerRequest',\n 'bytes',\n 'loopDelay',\n 'findingsPerRequest',\n];\n\n/**\n * Which metrics to draw.\n *\n * Two at most: a third line is a dashboard, and a chart nobody can read is\n * not a better answer than a chart with one line on it.\n */\nfunction parseMetrics(params: URLSearchParams): SeriesMetric[] {\n const asked = params\n .getAll('metric')\n .flatMap((value) => value.split(','))\n .map((value) => value.trim())\n .filter((value): value is SeriesMetric => (METRICS as readonly string[]).includes(value));\n\n const unique = [...new Set(asked)].slice(0, 2);\n return unique.length > 0 ? unique : ['p95'];\n}\n\n/**\n * The query string, as the filter the store applies.\n *\n * Exported so the panel's client-side filter is checked against this and not\n * against a second reading of the same parameters.\n */\nexport function parseFilter(params: URLSearchParams): RequestFilter {\n const methods = params\n .getAll('method')\n .flatMap((value) => value.split(','))\n .filter(Boolean);\n const statusClasses = params\n .getAll('status')\n .flatMap((value) => value.split(','))\n .map((value) => Number.parseInt(value, 10))\n .filter((value) => Number.isFinite(value));\n\n const minDuration = Number(params.get('minDurationMs'));\n const minSql = Number(params.get('minSql'));\n const status = Number(params.get('statusExact'));\n const flagged = params\n .getAll('flagged')\n .flatMap((value) => value.split(','))\n .filter(Boolean);\n const route = params.get('route');\n const routeMethod = params.get('routeMethod');\n const from = Number(params.get('from'));\n const to = Number(params.get('to'));\n\n return {\n from: Number.isFinite(from) && from > 0 ? from : undefined,\n to: Number.isFinite(to) && to > 0 ? to : undefined,\n query: params.get('q') ?? undefined,\n methods,\n statusClasses,\n minDurationMs: Number.isFinite(minDuration) && minDuration > 0 ? minDuration : undefined,\n onlyFindings: params.get('findings') === '1',\n onlyNPlusOne: params.get('nplus') === '1',\n onlyTests: params.get('tests') === '1',\n onlyErrors: params.get('errors') === '1',\n route: route && routeMethod ? { method: routeMethod, route } : undefined,\n path: params.get('path') ?? undefined,\n status: Number.isFinite(status) && status > 0 ? status : undefined,\n minSql: Number.isFinite(minSql) && minSql > 0 ? minSql : undefined,\n flagged: flagged.length > 0 ? flagged : undefined,\n test: params.get('test') ?? undefined,\n };\n}\n\n/**\n * Reads the body of a panel request.\n *\n * An already-parsed body is taken first: the application almost certainly has\n * a json parser (`express.json()`) that consumed the stream before us —\n * reading the socket a second time is pointless, it is already empty.\n */\nasync function readBody(request: IncomingMessage, limitBytes = 1_000_000): Promise<unknown> {\n const parsed = (request as IncomingMessage & { body?: unknown }).body;\n if (parsed !== undefined && parsed !== null) {\n return typeof parsed === 'string' ? JSON.parse(parsed) : parsed;\n }\n\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n const buffer = chunk as Buffer;\n size += buffer.length;\n if (size > limitBytes) throw new Error('request body too large');\n chunks.push(buffer);\n }\n const raw = Buffer.concat(chunks).toString('utf8');\n return raw ? JSON.parse(raw) : {};\n}\n\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.woff2': 'font/woff2',\n '.ico': 'image/x-icon',\n};\n\n/**\n * Serves the built dashboard.\n *\n * Anything that is not an existing file falls back to `index.html`: the panel\n * is a single-page app, and its inner screens are state, not server routes.\n */\nfunction serveAsset(assetsDir: string, route: string, response: ServerResponse): boolean {\n const root = resolve(assetsDir);\n const requested = route === '/' ? 'index.html' : route.replace(/^\\/+/, '');\n let target = resolve(root, requested);\n\n // A path escaping the assets directory can only come from a traversal attempt.\n if (target !== root && !target.startsWith(root + sep)) return false;\n\n let file = statSync(target, { throwIfNoEntry: false });\n if (!file?.isFile()) {\n target = resolve(root, 'index.html');\n file = statSync(target, { throwIfNoEntry: false });\n if (!file?.isFile()) return false;\n }\n\n response.writeHead(200, {\n 'content-type': MIME_TYPES[extname(target)] ?? 'application/octet-stream',\n 'content-length': file.size,\n // Asset names are content-hashed by the build; index.html must not be cached.\n 'cache-control': target.endsWith('index.html') ? 'no-store' : 'public, max-age=31536000',\n });\n createReadStream(target).pipe(response);\n return true;\n}\n\n/**\n * The application's own address — replay needs it to call back into itself.\n *\n * From the socket, never from `Host`. Replay follows this address carrying\n * headers the caller chose, so a forged `Host` would aim it — cookies and all\n * — at any host that resolves.\n */\nfunction originOf(request: IncomingMessage): string {\n const port = request.socket.localPort;\n const address = request.socket.localAddress ?? '127.0.0.1';\n // IPv6 literals need brackets in a URL; `::1` is the ordinary local case.\n const host = address.includes(':') ? `[${address}]` : address;\n // TLS never reaches this far: the panel is mounted inside the application,\n // and replay always goes to its own local address.\n return `http://${host}${port ? `:${port}` : ''}`;\n}\n\n/**\n * Whether a state-changing request came from the panel itself.\n *\n * The gate says who may use the panel, not what page is asking. Without this,\n * any site open in a developer's browser can POST to `/api/replay` and make\n * the application run a recorded request again — a second charge, a second\n * email. That the reply is unreadable to that page is no comfort: the effect\n * has happened.\n *\n * `Sec-Fetch-Site` is the browser's own account and cannot be set by script.\n * `same-site` is refused with `cross-site`: two ports of localhost are one\n * site, and the dev server on the other port is the neighbour in question.\n *\n * Neither header means the caller is not a browser, and CSRF is not that.\n */\nfunction isSameOrigin(request: IncomingMessage): boolean {\n const site = request.headers['sec-fetch-site'];\n if (typeof site === 'string') return site === 'same-origin' || site === 'none';\n\n const origin = request.headers.origin;\n if (typeof origin !== 'string' || origin === '') return true;\n\n const host = request.headers.host;\n if (typeof host !== 'string') return false;\n try {\n return new URL(origin).host === host;\n } catch {\n // An origin that is not a URL is not one this panel wrote.\n return false;\n }\n}\n\n/**\n * How many requests one export may carry.\n *\n * It serializes whole records into one string, synchronously, answering a GET.\n * The stores bound `list()`, but a bound living in the store is not this\n * endpoint's: a store written elsewhere would hand over its whole history.\n */\nconst EXPORT_LIMIT = 1_000;\n\n/** The newest requests matching the filter, and how many did not fit. */\nfunction forExport(\n source: PanelSource,\n params: URLSearchParams,\n): { requests: readonly RecordedRequest[]; dropped: number } {\n const matched = filterRequests(source.list(), parseFilter(params));\n if (matched.length <= EXPORT_LIMIT) return { requests: matched, dropped: 0 };\n // The newest, because a truncated export should be the recent part of the\n // story rather than an arbitrary slice of it.\n return {\n requests: matched.slice(-EXPORT_LIMIT),\n dropped: matched.length - EXPORT_LIMIT,\n };\n}\n\n/**\n * What a truncated export says about itself.\n *\n * An export is evidence: a cap nobody is told about reads as \"this is\n * everything\".\n */\nfunction exportNote(dropped: number): string | null {\n return dropped === 0\n ? null\n : `${dropped} older request${dropped === 1 ? '' : 's'} matched and were left out: an export carries at most ${EXPORT_LIMIT}.`;\n}\n\n/**\n * How many live feeds one panel may hold open at once.\n *\n * Each one is a listener on the store and a timer; nothing else bounds them,\n * and a stream is opened by a GET that anything can repeat.\n */\nconst MAX_STREAMS = 32;\n\n/**\n * How much one feed may have written that its reader has not taken.\n *\n * A tab left in the background or a proxy that stalled stops reading, and\n * every row since then sits in this process's memory, per feed, without end.\n * Past this the feed is dropped; the panel reconnects and re-reads the list,\n * which is what it does after any gap.\n */\nconst MAX_STREAM_BACKLOG_BYTES = 1024 * 1024;\n\n/**\n * How many feeds one panel is holding.\n *\n * Per handler rather than per process: two applications in one process are two\n * panels, and a cap they share is a cap that depends on a neighbour.\n */\ninterface StreamCount {\n open: number;\n}\n\nfunction streamEvents(\n source: PanelSource,\n mutes: MuteView,\n request: IncomingMessage,\n response: ServerResponse,\n streams: StreamCount,\n): void {\n if (streams.open >= MAX_STREAMS) {\n sendJson(response, 503, { error: `too many live feeds open (${MAX_STREAMS})` });\n return;\n }\n streams.open++;\n\n response.writeHead(200, {\n 'content-type': 'text/event-stream; charset=utf-8',\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n // Disables nginx buffering: without it the feed stalls.\n 'x-accel-buffering': 'no',\n });\n response.write(': reqray stream\\n\\n');\n\n const unsubscribe = source.subscribe((recorded) => {\n // The live feed obeys mutes the same way the list does.\n const [row] = mutes.silence([toRow(recorded)]);\n if (response.writableLength > MAX_STREAM_BACKLOG_BYTES) {\n response.destroy();\n return;\n }\n response.write(`data: ${JSON.stringify(row)}\\n\\n`);\n });\n\n const keepAlive = setInterval(() => response.write(': ping\\n\\n'), 20_000);\n keepAlive.unref?.();\n\n let stopped = false;\n const stop = (): void => {\n // Both `close` events fire for one disconnect; the count must move once.\n if (stopped) return;\n stopped = true;\n streams.open--;\n clearInterval(keepAlive);\n unsubscribe();\n };\n request.on('close', stop);\n response.on('close', stop);\n}\n\n/**\n * Creates the panel handler.\n *\n * Returns `null` if the panel is disabled by options: the adapter then has\n * nothing to mount.\n */\nexport function createPanelHandler(init: PanelHandlerInit): PanelHandler | null {\n const { source, options } = init;\n const panel = options.panel;\n if (!panel || !options.enabled) return null;\n\n const mount = panel.path.endsWith('/') ? panel.path.slice(0, -1) : panel.path;\n const streams: StreamCount = { open: 0 };\n const mutes = new MuteView(source);\n\n const serve: PanelHandler = (request, response) => {\n // Express strips the matched mount prefix from `url` inside `app.use`;\n // `originalUrl` keeps the full path. Anything non-Express has no such\n // property and falls back to the plain url.\n const rawUrl = (request as { originalUrl?: string }).originalUrl ?? request.url ?? '/';\n if (rawUrl !== mount && !rawUrl.startsWith(`${mount}/`) && !rawUrl.startsWith(`${mount}?`)) {\n return false;\n }\n\n const url = new URL(rawUrl, 'http://reqray.local');\n const route = url.pathname.slice(mount.length) || '/';\n\n if (\n !isPanelRequestAllowed(panel.gate, {\n headers: request.headers,\n ip: request.socket.remoteAddress ?? null,\n })\n ) {\n sendJson(response, 403, {\n error: panel.gate\n ? 'panel access denied by the gate'\n : 'without a gate the panel answers only to this machine, at a local address. ' +\n \"To open it further, set one: reqray({ panel: { gate: 'open' } }) or a function.\",\n });\n return true;\n }\n\n const method = request.method ?? 'GET';\n\n // Before anything reads a body: a refusal has to come earlier than the\n // work it refuses, and every state-changing route is behind this line.\n if (method !== 'GET' && method !== 'HEAD' && !isSameOrigin(request)) {\n sendJson(response, 403, { error: 'this request did not come from the panel' });\n return true;\n }\n\n if (route === '/api/meta' && method === 'GET') {\n // Typed rather than inline: this object is the `/api/meta` contract, and\n // the protocol is where that contract is written down.\n const meta: PanelMeta = {\n pid: process.pid,\n startedAt: Date.now() - Math.round(process.uptime() * 1000),\n mode: options.mode,\n bufferSize: options.bufferSize,\n replayEnabled: options.replay,\n blameEnabled: options.blame,\n detectors: detectorSettings(options),\n };\n sendJson(response, 200, meta);\n return true;\n }\n\n if (route === '/api/project' && method === 'GET') {\n // Async, unlike every other route here: it asks git which commit is\n // running, and a panel that lies about the build is worse than one that\n // takes a few milliseconds.\n void projectReport(options, source)\n .then((report) => sendJson(response, 200, report))\n .catch((error: unknown) => {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 500, { error: `project report unavailable: ${reason}` });\n });\n return true;\n }\n\n if (route === '/api/retention' && method === 'GET') {\n sendJson(response, 200, { retention: retentionOf(options), log: logOf(options) });\n return true;\n }\n\n if (route === '/api/retention' && method === 'POST') {\n handleRetention(options, request, response);\n return true;\n }\n\n if (route === '/api/timeline' && method === 'GET') {\n if (!source.timeSeries) {\n sendJson(response, 200, { timeline: null });\n return true;\n }\n const asked = Number(url.searchParams.get('buckets'));\n const buckets =\n Number.isFinite(asked) && asked > 0 ? Math.min(Math.floor(asked), 512) : TIMELINE_BUCKETS;\n // A stretch, when the caller names one. A store with days of history\n // and an hour of traffic draws a strip that is empty but for two\n // columns; being able to ask for the part worth looking at is what\n // makes the strip readable without making it lie about the rest.\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const points =\n Number.isFinite(from) && Number.isFinite(to) && to > from\n ? source.timeSeries().filter((point) => point.startedAt >= from && point.startedAt <= to)\n : source.timeSeries();\n sendJson(response, 200, { timeline: buildTimeline(points, buckets) });\n return true;\n }\n\n if (route === '/api/requests' && method === 'GET') {\n const filter = parseFilter(url.searchParams);\n const limit = pageLimit(url.searchParams);\n const sort: RequestSort = url.searchParams.get('sort') === 'slowest' ? 'slowest' : 'recent';\n\n // A store that can page does its own filtering: a history on disk must\n // not be read into memory to answer one screenful.\n if (source.page) {\n const page = source.page({\n filter,\n limit,\n sort,\n cursor: url.searchParams.get('cursor'),\n });\n sendJson(response, 200, {\n requests: mutes.silence(page.rows),\n summary: page.summary,\n nextCursor: page.nextCursor,\n });\n return true;\n }\n\n // No `page()`: the same rule, applied here over everything the store\n // holds, rather than a second implementation of it.\n const page = pageFromList(\n source.list(),\n { filter, limit, sort, cursor: url.searchParams.get('cursor') },\n {\n pinned: new Set(source.pinned?.() ?? []),\n slowMs: options.sampling.slowMs || 500,\n },\n );\n sendJson(response, 200, {\n requests: mutes.silence(page.rows),\n summary: page.summary,\n nextCursor: page.nextCursor,\n });\n return true;\n }\n\n if (route === '/api/export/har' && method === 'GET') {\n const { requests: shown, dropped } = forExport(source, url.searchParams);\n sendDownload(\n response,\n 'reqray.har',\n 'application/json; charset=utf-8',\n JSON.stringify(toHar(shown, new Date(), exportNote(dropped)), null, 2),\n );\n return true;\n }\n\n if (route === '/api/export/curl' && method === 'GET') {\n const { requests: shown, dropped } = forExport(source, url.searchParams);\n sendDownload(\n response,\n 'reqray-requests.sh',\n 'text/x-shellscript; charset=utf-8',\n toCurlScript(shown, originOf(request), exportNote(dropped)),\n );\n return true;\n }\n\n if (route === '/api/blame' && method === 'POST') {\n if (!options.blame) {\n sendJson(response, 403, {\n error:\n 'git blame from the panel is off. Outside local development it is enabled explicitly: reqray({ blame: true }).',\n });\n return true;\n }\n handleBlame(options, request, response);\n return true;\n }\n\n if (route === '/api/routes' && method === 'GET') {\n sendJson(response, 200, routeStats(source.list(), mutes.set()));\n return true;\n }\n\n if (route === '/api/series' && method === 'GET') {\n if (!source.history) {\n // The store cannot read a stretch. Said plainly rather than drawn as\n // an empty chart, which would be a claim about a quiet week.\n sendJson(response, 200, { series: null });\n return true;\n }\n\n const now = Date.now();\n const to = positive(url.searchParams.get('to')) ?? now;\n const from = positive(url.searchParams.get('from')) ?? to - HOUR_MS;\n if (to <= from) {\n sendJson(response, 400, { error: 'the period must end after it starts' });\n return true;\n }\n\n const askedColumns = positive(url.searchParams.get('buckets'));\n const columns = askedColumns ? Math.min(Math.floor(askedColumns), 512) : SERIES_COLUMNS;\n const metrics = parseMetrics(url.searchParams);\n const filter = parseFilter(url.searchParams);\n\n const query = (span: { from: number; to: number }): HistoryQuery => ({\n ...span,\n // The period is the period, whatever the filter's own range says: the\n // screen owns the window, and a stale `from` in the filter would\n // silently narrow it.\n filter: { ...filter, from: span.from, to: span.to },\n });\n\n const current: HistorySamples = source.history(query({ from, to }));\n // The same length again, immediately before. Only ever used for a\n // comparison, so a truncated reading of it changes nothing that is\n // presented as complete.\n const before = source.history(query({ from: from - (to - from), to: from - 1 }));\n\n sendJson(response, 200, {\n series: historyOf(current, before.samples, { from, to, metrics, columns }),\n });\n return true;\n }\n\n if (route === '/api/findings' && method === 'GET') {\n if (!source.findings) {\n // The store cannot read its findings back. Said plainly rather than\n // rendered as an empty work list, which would be a claim about the\n // code being clean.\n sendJson(response, 200, { findings: null });\n return true;\n }\n const read = source.findings({\n from: positive(url.searchParams.get('from')),\n to: positive(url.searchParams.get('to')),\n });\n sendJson(response, 200, {\n findings: patternsOf(read, {\n states: source.findingStates?.(),\n changedAt: fileChangedAt,\n }),\n });\n return true;\n }\n\n if (route === '/api/findings/state' && method === 'POST') {\n handleFindingState(source, mutes, request, response);\n return true;\n }\n\n if (route === '/api/routes/series' && method === 'GET') {\n const wanted = url.searchParams.get('route');\n const verb = url.searchParams.get('method');\n if (!wanted || !verb) {\n sendJson(response, 400, { error: 'a route and a method are needed to draw one' });\n return true;\n }\n // A store that cannot answer draws nothing, rather than a chart of\n // whatever page the browser happened to be holding.\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const samples = source.durations?.({\n method: verb,\n route: wanted,\n // A chart is drawn over the stretch the caller names, so that it\n // covers the same traffic the table beside it describes.\n ...(Number.isFinite(from) && Number.isFinite(to) && to > from ? { from, to } : {}),\n });\n const asked = Number(url.searchParams.get('buckets'));\n const buckets =\n Number.isFinite(asked) && asked > 0 ? Math.min(Math.floor(asked), 256) : SERIES_BUCKETS;\n sendJson(response, 200, {\n series: samples ? routeSeries(verb, wanted, samples, buckets) : null,\n });\n return true;\n }\n\n if (route === '/api/timeline/at' && method === 'GET') {\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const overallFrom = Number(url.searchParams.get('overallFrom'));\n const overallTo = Number(url.searchParams.get('overallTo'));\n if (![from, to, overallFrom, overallTo].every(Number.isFinite) || to <= from) {\n sendJson(response, 400, { error: 'a moment needs a start and an end, in epoch ms' });\n return true;\n }\n if (!source.counts) {\n sendJson(response, 200, { activity: null });\n return true;\n }\n sendJson(response, 200, {\n activity: whatRanAt(\n source.counts({ from, to }),\n source.counts({ from: overallFrom, to: overallTo }),\n { from, to, overallMs: overallTo - overallFrom },\n ),\n });\n return true;\n }\n\n if (route === '/api/pin' && method === 'POST') {\n handlePin(source, request, response);\n return true;\n }\n\n if (route === '/api/requests' && method === 'DELETE') {\n source.clear();\n sendJson(response, 200, { cleared: true });\n return true;\n }\n\n // ORDER MATTERS from here to the end of the `/api/requests/` group: these\n // are prefix matches, not exact ones, and `/api/requests/:id` below would\n // swallow `/api/requests/:id/baseline` if it came first. The chain has no\n // way to say so structurally, so it says so here.\n if (route.startsWith('/api/requests/') && route.endsWith('/baseline') && method === 'GET') {\n const id = decodeURIComponent(route.slice('/api/requests/'.length, -'/baseline'.length));\n const found = source.get(id);\n if (!found) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return true;\n }\n // A store that cannot answer produces no baseline, and the panel shows\n // no card: an absent comparison is an ordinary answer here.\n const samples = source.durations?.({\n method: found.method,\n route: normalizeRoute(found.path),\n excludeId: found.id,\n });\n sendJson(response, 200, {\n baseline: baselineFor(found, samples),\n pressure: samples ? pressureFor(samples) : null,\n });\n return true;\n }\n\n if (route.startsWith('/api/requests/') && method === 'GET') {\n const id = decodeURIComponent(route.slice('/api/requests/'.length));\n const found = source.get(id);\n if (!found) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return true;\n }\n // The row fields travel with the record: the panel's detail type\n // extends its row type, and a payload missing half of it is a contract\n // that silently reads `undefined`.\n sendJson(response, 200, {\n ...toRow(found, (source.pinned?.() ?? []).includes(id)),\n ...ensureTiming(found),\n });\n return true;\n }\n\n if (route === '/api/exceptions' && method === 'GET') {\n sendJson(response, 200, { groups: groupExceptions(source.list(), options.stack) });\n return true;\n }\n\n if (route === '/api/stream' && method === 'GET') {\n streamEvents(source, mutes, request, response, streams);\n return true;\n }\n\n if (route === '/api/explain' && method === 'POST') {\n if (!options.explain) {\n sendJson(response, 403, {\n error:\n 'EXPLAIN from the panel is off. Outside local development it is enabled explicitly: reqray({ explain: true }).',\n });\n return true;\n }\n handleExplain(source, request, response);\n return true;\n }\n\n if (route === '/api/replay' && method === 'POST') {\n if (!options.replay) {\n sendJson(response, 403, {\n error:\n 'replay is off. Outside local development it is enabled only explicitly: reqray({ replay: true }) — a replay in production means a second charge and a second email.',\n });\n return true;\n }\n handleReplay(source, request, response);\n return true;\n }\n\n if (route.startsWith('/api/')) {\n sendJson(response, 404, { error: 'no such panel endpoint' });\n return true;\n }\n\n if (method === 'GET' && init.assetsDir && serveAsset(init.assetsDir, route, response)) {\n return true;\n }\n\n sendJson(response, 404, {\n error: init.assetsDir\n ? 'panel asset not found'\n : 'the panel UI is not installed: add @reqray/dashboard. The API keeps working.',\n });\n return true;\n };\n\n return function handlePanelRequest(request, response): boolean {\n try {\n return serve(request, response);\n } catch (error) {\n // Only a panel request gets this far before anything can throw — a\n // malformed `%` in an id, say — and it must end here: on a bare\n // `node:http` server an exception in the listener takes the process,\n // which is the application's.\n const reason = error instanceof Error ? error.message : String(error);\n if (response.headersSent) response.destroy();\n else sendJson(response, 400, { error: `bad panel request: ${reason}` });\n return true;\n }\n };\n}\n\n/**\n * Changes how long requests are kept.\n *\n * The only setting the panel can write, and it deletes data on the way down,\n * so it is refused unless the application handed the panel a policy and said\n * it may be changed. Values are checked here rather than trusted: the panel\n * is a client like any other.\n */\nfunction handleRetention(\n options: ResolvedOptions,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n const policy = options.retention;\n if (!policy) {\n sendJson(response, 501, {\n error:\n 'this application keeps to fixed limits: pass reqray({ retention: retentionPolicy({ … }) }) to make them changeable.',\n });\n return;\n }\n if (!policy.writable) {\n sendJson(response, 403, {\n error: 'retention is read-only here: the policy was created with writable: false.',\n });\n return;\n }\n\n try {\n const payload = (await readBody(request)) as Partial<RetentionLimits>;\n const patch: Record<string, unknown> = {};\n for (const key of ['days', 'maxBytes', 'maxRequests'] as const) {\n if (key in payload) patch[key] = payload[key];\n }\n if (Object.keys(patch).length === 0) {\n sendJson(response, 400, { error: 'nothing to change: days, maxBytes or maxRequests' });\n return;\n }\n\n const limits = policy.update(patch as Partial<RetentionLimits>);\n // The stores sweep on their own schedule; what is reported back is the\n // policy, not a promise that the disk is already smaller.\n sendJson(response, 200, { retention: retentionOf(options), limits });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `retention unchanged: ${reason}` });\n }\n })();\n}\n\nfunction handleBlame(\n options: ResolvedOptions,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as {\n frames?: Array<{ file?: unknown; line?: unknown }>;\n };\n const frames = Array.isArray(payload.frames) ? payload.frames.slice(0, 30) : [];\n\n const blamed = await Promise.all(\n frames.map(async (frame) => {\n if (typeof frame.file !== 'string' || typeof frame.line !== 'number') return null;\n return blameLine(frame.file, frame.line, options.stack.projectRoot);\n }),\n );\n sendJson(response, 200, { frames: blamed });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `blame failed: ${reason}` });\n }\n })();\n}\n\n/**\n * When a file last changed, epoch ms — what `fixed?` is guessed from.\n *\n * The file's mtime rather than git: honest enough for a guess drawn with a\n * question mark, and free. Unreadable files answer \"nobody knows\".\n */\nfunction fileChangedAt(file: string): number | null {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return null;\n }\n}\n\n/**\n * What is muted, remembered between changes.\n *\n * Muting is presentation, not detection: the record keeps its findings, but a\n * muted pattern must stop flagging the list, the live feed and the routes\n * table alike — one that flashes amber on arrival and goes grey on reload is a\n * haunting.\n *\n * Held rather than rebuilt per call: it changes only when somebody mutes\n * something, and the live feed would otherwise walk the whole state map once\n * per request delivered.\n */\nclass MuteView {\n #muted: Set<string> | null = null;\n\n constructor(private readonly source: PanelSource) {}\n\n /** Pattern ids the reader muted, or an empty set when nothing is. */\n set(): ReadonlySet<string> {\n if (this.#muted) return this.#muted;\n\n const muted = new Set<string>();\n const states = this.source.findingStates?.();\n if (states) {\n for (const [id, state] of states) if (state === 'muted') muted.add(id);\n }\n this.#muted = muted;\n return muted;\n }\n\n /** Called when a state changes; the next read rebuilds. */\n forget(): void {\n this.#muted = null;\n }\n\n /**\n * Rows with muted patterns silenced.\n *\n * Only flagged rows are looked up — they are the rare ones — and a record\n * the store has already dropped keeps the flag it had.\n */\n silence(rows: readonly RequestRow[]): readonly RequestRow[] {\n const muted = this.set();\n if (muted.size === 0) return rows;\n return rows.map((row) => {\n if (row.flag === null) return row;\n const record = this.source.get(row.id);\n if (!record) return row;\n const flag = flagWithMutes(record, muted);\n return flag === row.flag ? row : { ...row, flag };\n });\n }\n}\n\n/**\n * The states a client may set.\n *\n * `fixed` is deliberately absent: it is a computed guess, and a stored one\n * would outlive the change it guessed about. The list is what both the check\n * and the refusal message are built from, so they cannot drift apart.\n */\nconst SETTABLE_STATES: readonly StoredPatternState[] = ['new', 'ack', 'muted'];\n\nfunction isSettable(value: unknown): value is StoredPatternState {\n return (SETTABLE_STATES as readonly unknown[]).includes(value);\n}\n\nfunction handleFindingState(\n source: PanelSource,\n mutes: MuteView,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n if (!source.setFindingState) {\n sendJson(response, 501, { error: 'this store cannot remember finding states' });\n return;\n }\n try {\n const payload = (await readBody(request)) as { id?: unknown; state?: unknown };\n if (typeof payload.id !== 'string' || payload.id.length === 0 || !isSettable(payload.state)) {\n sendJson(response, 400, {\n error: `a pattern id and a state (${SETTABLE_STATES.join(', ')}) are needed`,\n });\n return;\n }\n const state = payload.state;\n source.setFindingState(payload.id, state);\n // The only moment what is muted can change.\n mutes.forget();\n sendJson(response, 200, { ok: true });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `state change failed: ${reason}` });\n }\n })();\n}\n\nfunction handlePin(source: PanelSource, request: IncomingMessage, response: ServerResponse): void {\n void (async () => {\n if (!source.pin) {\n sendJson(response, 501, { error: 'this store cannot pin requests' });\n return;\n }\n try {\n const payload = (await readBody(request)) as { id?: unknown; pinned?: unknown };\n if (typeof payload.id !== 'string') {\n sendJson(response, 400, { error: 'id is required' });\n return;\n }\n const wanted = payload.pinned !== false;\n const ok = source.pin(payload.id, wanted);\n if (!ok && wanted) {\n // Either the record is already gone, or the pin board is full — both\n // are worth saying out loud rather than silently doing nothing.\n sendJson(response, 409, {\n error: 'could not pin: the request is gone, or too many are pinned already',\n });\n return;\n }\n sendJson(response, 200, { id: payload.id, pinned: wanted && ok });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `pin failed: ${reason}` });\n }\n })();\n}\n\nfunction handleExplain(\n source: PanelSource,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as { id?: unknown; spanId?: unknown };\n const record = typeof payload.id === 'string' ? source.get(payload.id) : undefined;\n if (!record) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return;\n }\n const spanId = typeof payload.spanId === 'number' ? payload.spanId : Number.NaN;\n\n sendJson(response, 200, await runExplain(record, spanId));\n } catch (error) {\n if (error instanceof ExplainError) {\n sendJson(response, error.status, { error: error.message });\n return;\n }\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('panel.explain', `EXPLAIN failed: ${reason}`);\n sendJson(response, 500, { error: `EXPLAIN failed: ${reason}` });\n }\n })();\n}\n\nfunction handleReplay(\n source: PanelSource,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as {\n id?: unknown;\n method?: unknown;\n path?: unknown;\n headers?: unknown;\n body?: unknown;\n };\n\n const original = typeof payload.id === 'string' ? source.get(payload.id) : undefined;\n if (!original) {\n sendJson(response, 404, { error: 'original request not found' });\n return;\n }\n\n const input: ReplayInput = {\n method: typeof payload.method === 'string' ? payload.method : original.method,\n path: typeof payload.path === 'string' ? payload.path : original.path,\n headers:\n payload.headers && typeof payload.headers === 'object'\n ? (payload.headers as Record<string, string>)\n : {},\n body: typeof payload.body === 'string' ? payload.body : undefined,\n };\n\n sendJson(response, 200, await runReplay(originOf(request), input, original));\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('panel.replay', `replay failed: ${reason}`);\n sendJson(response, 500, { error: `replay failed: ${reason}` });\n }\n })();\n}\n","/**\n * Occurrences into patterns — the arithmetic behind the findings tab.\n *\n * The grouping happens here, once, for every store: a store hands over one\n * row per occurrence and says when it stopped reading, the same division of\n * labour the history screen uses. Grouping is by detector plus code\n * location, not by request — `GET /api/orders` and `GET /api/orders/flaky`\n * both firing N+1 at the same line are one problem — and falls back to the\n * route when a finding carries no location, because \"somewhere on this\n * endpoint\" is still one somewhere.\n */\n\nimport type {\n Callsite,\n FindingPattern,\n FindingSeverity,\n FindingsResponse,\n PatternExample,\n StoredPatternState,\n} from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { normalizeRoute } from './routes.js';\n\n/**\n * One finding occurrence, as the tab needs it.\n *\n * A dozen fields rather than a record: the requests that carry findings are\n * a small minority, but a window of them is still not something to hold as\n * payloads to look at one finding in each.\n */\nexport interface FindingSample {\n readonly requestId: string;\n readonly startedAt: number;\n readonly method: string;\n readonly route: string;\n readonly status: number;\n readonly durationMs: number;\n readonly detector: string;\n readonly severity: FindingSeverity;\n readonly title: string;\n readonly costMs: number;\n readonly callsite: Callsite | null;\n readonly hint: string;\n}\n\n/** What a store hands back, and whether it read the whole window. */\nexport interface FindingSamples {\n readonly samples: readonly FindingSample[];\n readonly truncated: boolean;\n}\n\n/** The stretch of time a findings reading covers. Absent bounds mean all. */\nexport interface FindingsQuery {\n readonly from?: number | undefined;\n readonly to?: number | undefined;\n}\n\n/**\n * A request's findings, reduced to occurrence rows.\n *\n * For every store that keeps whole records, so the tab does not depend on\n * which store is behind it.\n */\nexport function findingSamplesOf(request: RecordedRequest): FindingSample[] {\n return request.findings.map((finding) => ({\n requestId: request.id,\n startedAt: request.startedAt,\n method: request.method,\n route: normalizeRoute(request.path),\n status: request.status,\n durationMs: request.durationMs,\n detector: finding.detector,\n severity: finding.severity,\n title: finding.title,\n costMs: finding.costMs,\n callsite: finding.callsite,\n hint: finding.hint,\n }));\n}\n\n/**\n * The pattern a finding belongs to.\n *\n * The code location when there is one — the same problem fires from the same\n * line whatever route reached it — and the route otherwise, so locationless\n * findings (a blown budget, a heavy response) still group by where they live.\n */\nexport function patternKey(sample: {\n readonly detector: string;\n readonly callsite: Callsite | null;\n readonly method: string;\n readonly route: string;\n}): string {\n return sample.callsite\n ? `${sample.detector}@${sample.callsite.relative}:${sample.callsite.line}`\n : `${sample.detector}@${sample.method} ${sample.route}`;\n}\n\n/** How many example requests a pattern carries. */\nconst EXAMPLE_LIMIT = 3;\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = { info: 0, warn: 1, critical: 2 };\n\nexport interface PatternsOptions {\n /** `ack`/`muted` per pattern id, as the store remembered them. */\n readonly states?: ReadonlyMap<string, StoredPatternState> | undefined;\n /**\n * When a file last changed, epoch ms, or `null` when nobody knows.\n *\n * Injected rather than read here: the aggregation stays pure, and what\n * \"changed\" means (mtime, a commit) is the caller's business.\n */\n readonly changedAt?: ((file: string) => number | null) | undefined;\n}\n\n/** Groups occurrences into the tab's patterns, costliest first. */\nexport function patternsOf(read: FindingSamples, options: PatternsOptions = {}): FindingsResponse {\n interface Bucket {\n latest: FindingSample;\n occurrences: number;\n recoverableMs: number;\n firstSeen: number;\n lastSeen: number;\n severity: FindingSeverity;\n routes: Map<string, { method: string; route: string; calls: number }>;\n /** Worst occurrence per request — five findings in one request are one way in. */\n examples: Map<string, PatternExample>;\n }\n\n const buckets = new Map<string, Bucket>();\n for (const sample of read.samples) {\n const key = patternKey(sample);\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = {\n latest: sample,\n occurrences: 0,\n recoverableMs: 0,\n firstSeen: sample.startedAt,\n lastSeen: sample.startedAt,\n severity: sample.severity,\n routes: new Map(),\n examples: new Map(),\n };\n buckets.set(key, bucket);\n }\n\n bucket.occurrences++;\n bucket.recoverableMs += sample.costMs;\n if (sample.startedAt < bucket.firstSeen) bucket.firstSeen = sample.startedAt;\n if (sample.startedAt >= bucket.lastSeen) {\n bucket.lastSeen = sample.startedAt;\n // The sentence and the hint follow the freshest occurrence: \"150\n // identical queries\" must not describe last week's count.\n bucket.latest = sample;\n }\n if (SEVERITY_RANK[sample.severity] > SEVERITY_RANK[bucket.severity]) {\n bucket.severity = sample.severity;\n }\n\n const routeKey = `${sample.method} ${sample.route}`;\n const route = bucket.routes.get(routeKey);\n if (route) route.calls++;\n else bucket.routes.set(routeKey, { method: sample.method, route: sample.route, calls: 1 });\n\n const example = bucket.examples.get(sample.requestId);\n if (!example || sample.costMs > example.costMs) {\n bucket.examples.set(sample.requestId, {\n requestId: sample.requestId,\n startedAt: sample.startedAt,\n method: sample.method,\n route: sample.route,\n status: sample.status,\n durationMs: sample.durationMs,\n costMs: sample.costMs,\n });\n }\n }\n\n const patterns: FindingPattern[] = [...buckets.entries()].map(([id, bucket]) => ({\n id,\n detector: bucket.latest.detector,\n severity: bucket.severity,\n title: bucket.latest.title,\n hint: bucket.latest.hint,\n callsite: bucket.latest.callsite,\n occurrences: bucket.occurrences,\n recoverableMs: bucket.recoverableMs,\n routes: [...bucket.routes.values()].sort((a, b) => b.calls - a.calls),\n firstSeen: bucket.firstSeen,\n lastSeen: bucket.lastSeen,\n state: stateOf(id, bucket, options),\n examples: [...bucket.examples.values()]\n .sort((a, b) => b.costMs - a.costMs)\n .slice(0, EXAMPLE_LIMIT),\n }));\n\n patterns.sort((a, b) => b.recoverableMs - a.recoverableMs || b.occurrences - a.occurrences);\n\n return {\n patterns,\n occurrences: read.samples.length,\n recoverableMs: patterns.reduce(\n (sum, pattern) => (pattern.state === 'muted' ? sum : sum + pattern.recoverableMs),\n 0,\n ),\n truncated: read.truncated,\n };\n}\n\n/**\n * What a pattern's state is, muted winning over everything.\n *\n * `fixed` outranks `ack` because it says more: the pattern has been silent\n * since the file it points at changed. It is only ever a guess — hence the\n * question mark a client draws — and only claimed when somebody did change\n * the file after the last occurrence.\n */\nfunction stateOf(\n id: string,\n bucket: { latest: FindingSample; lastSeen: number },\n options: PatternsOptions,\n): FindingPattern['state'] {\n const stored = options.states?.get(id);\n if (stored === 'muted') return 'muted';\n\n const file = bucket.latest.callsite?.file;\n if (file && options.changedAt) {\n const changed = options.changedAt(file);\n if (changed !== null && changed > bucket.lastSeen) return 'fixed';\n }\n\n return stored === 'ack' ? 'ack' : 'new';\n}\n\n/**\n * The row's flag, with muted patterns silenced.\n *\n * Muting is presentation, not detection: the detector keeps running and the\n * findings stay on the record, but a muted pattern must stop shouting from\n * the list. The flag falls back to the costliest finding that is not muted,\n * and to nothing when they all are.\n */\nexport function flagWithMutes(request: RecordedRequest, muted: ReadonlySet<string>): string | null {\n if (muted.size === 0 || request.findings.length === 0) {\n return [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null;\n }\n const audible = request.findings.filter(\n (finding) =>\n !muted.has(\n patternKey({\n detector: finding.detector,\n callsite: finding.callsite,\n method: request.method,\n route: normalizeRoute(request.path),\n }),\n ),\n );\n return [...audible].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null;\n}\n","/**\n * Per-route aggregates.\n *\n * The request list answers \"what happened just now\"; this answers \"which\n * endpoint is expensive\". It is computed over whatever the store still holds,\n * which is a dev session rather than a statistically sound window — the\n * numbers are for spotting the obvious offender, not for a capacity plan, and\n * the screen says as much by showing the sample count next to them.\n */\n\nimport type { Callsite, RouteFinding, RouteStats, RoutesReport } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { patternKey } from './findings.js';\n\nexport type { RouteFinding, RouteStats, RoutesReport };\n\n/**\n * How many columns a route's sparkline is cut into.\n *\n * Ten: enough to see a shape, few enough that one column of a short window\n * still holds calls rather than drawing a comb of ones and zeroes.\n */\nexport const TREND_BUCKETS = 10;\n\n/**\n * Collapses the variable parts of a path.\n *\n * Per segment rather than by regex over the whole path, so that a route with\n * several ids normalizes cleanly. A hex token must contain a digit to count\n * as an id: otherwise ordinary words like `feed` or `cafe` would normalize\n * away and two unrelated routes would merge into one row.\n */\nexport function normalizeRoute(path: string): string {\n return path\n .split('?')[0]\n ?.split('/')\n .map((segment) => {\n if (/^\\d+$/.test(segment)) return ':id';\n if (/^\\d{4}-\\d{2}/.test(segment)) return ':date';\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment)) {\n return ':id';\n }\n if (/^[0-9a-f]{4,}$/i.test(segment) && /\\d/.test(segment)) return ':id';\n return segment;\n })\n .join('/') as string;\n}\n\n/**\n * A percentile with linear interpolation between neighbouring samples.\n *\n * Index-based selection would collapse p95 and p99 onto the same sample at\n * the sample counts a dev session produces, and two columns showing the same\n * number are worse than one.\n *\n * @param sorted values in ascending order.\n */\nexport function percentile(sorted: readonly number[], p: number): number {\n if (sorted.length === 0) return 0;\n if (sorted.length === 1) return sorted[0] as number;\n\n const position = p * (sorted.length - 1);\n const lower = Math.floor(position);\n const upper = Math.ceil(position);\n const low = sorted[lower] as number;\n if (lower === upper) return low;\n const high = sorted[upper] as number;\n return low + (high - low) * (position - lower);\n}\n\n/** One detector's tally on one route, while it is being accumulated. */\ninterface FoundHere {\n calls: number;\n recoverableMs: number;\n /** When the occurrence that supplied the words happened. */\n at: number;\n title: string;\n hint: string;\n callsite: Callsite | null;\n}\n\ninterface Accumulator {\n method: string;\n route: string;\n durations: number[];\n errors: number;\n sql: number;\n totalMs: number;\n bytes: number;\n /** Calls that reported a size — the divisor for the average. */\n weighed: number;\n /** Per detector, accumulated across the route's calls. */\n findings: Map<string, FoundHere>;\n /** When each call started — bucketed into the trend once the window is known. */\n starts: number[];\n}\n\n/**\n * Aggregates the retained requests by normalized route.\n *\n * @param muted pattern ids the reader silenced, as {@link patternKey} spells\n * them. Their findings stay on the records and out of this table: the column\n * is a shout, and a muted pattern has been told to stop shouting.\n */\nexport function routeStats(\n requests: readonly RecordedRequest[],\n muted: ReadonlySet<string> = new Set(),\n): RoutesReport {\n if (requests.length === 0) {\n return { routes: [], samples: 0, windowMs: 0, from: 0, to: 0 };\n }\n\n const byRoute = new Map<string, Accumulator>();\n let overallMs = 0;\n let oldest = Number.POSITIVE_INFINITY;\n let newest = Number.NEGATIVE_INFINITY;\n\n for (const request of requests) {\n const route = normalizeRoute(request.path);\n const key = `${request.method} ${route}`;\n let bucket = byRoute.get(key);\n if (!bucket) {\n bucket = {\n method: request.method,\n route,\n durations: [],\n errors: 0,\n sql: 0,\n totalMs: 0,\n bytes: 0,\n weighed: 0,\n findings: new Map(),\n starts: [],\n };\n byRoute.set(key, bucket);\n }\n\n bucket.durations.push(request.durationMs);\n bucket.starts.push(request.startedAt);\n\n for (const finding of request.findings) {\n if (\n muted.has(\n patternKey({\n detector: finding.detector,\n callsite: finding.callsite,\n method: request.method,\n route,\n }),\n )\n ) {\n continue;\n }\n const seen = bucket.findings.get(finding.detector);\n if (seen) {\n seen.calls++;\n seen.recoverableMs += finding.costMs;\n // The freshest occurrence speaks: \"150 identical queries\" must not be\n // last week's count.\n if (request.startedAt >= seen.at) {\n seen.at = request.startedAt;\n seen.title = finding.title;\n seen.hint = finding.hint;\n seen.callsite = finding.callsite;\n }\n continue;\n }\n bucket.findings.set(finding.detector, {\n calls: 1,\n recoverableMs: finding.costMs,\n at: request.startedAt,\n title: finding.title,\n hint: finding.hint,\n callsite: finding.callsite,\n });\n }\n bucket.totalMs += request.durationMs;\n const bytesOut = request.weight?.bytesOut ?? null;\n if (bytesOut !== null) {\n bucket.bytes += bytesOut;\n bucket.weighed++;\n }\n if (request.error !== null || request.status >= 500) bucket.errors++;\n for (const span of request.spans) {\n if (span.kind === 'db') bucket.sql++;\n }\n\n overallMs += request.durationMs;\n if (request.startedAt < oldest) oldest = request.startedAt;\n if (request.startedAt > newest) newest = request.startedAt;\n }\n\n // A single request spans no time; one second keeps rps finite and honest.\n const windowMs = Math.max(1_000, newest - oldest);\n\n const routes = [...byRoute.values()].map((bucket): RouteStats => {\n const sorted = [...bucket.durations].sort((a, b) => a - b);\n const calls = sorted.length;\n\n // The shape of the traffic, over the same window every other row uses —\n // so two sparklines on this screen are comparable by eye.\n const trend = new Array<number>(TREND_BUCKETS).fill(0);\n const span = Math.max(1, newest - oldest);\n for (const at of bucket.starts) {\n const index = Math.min(TREND_BUCKETS - 1, Math.floor(((at - oldest) / span) * TREND_BUCKETS));\n trend[index] = (trend[index] ?? 0) + 1;\n }\n\n return {\n method: bucket.method,\n route: bucket.route,\n calls,\n rps: calls / (windowMs / 1_000),\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n errorRate: (bucket.errors / calls) * 100,\n sqlAvg: bucket.sql / calls,\n bytesAvg: bucket.weighed > 0 ? bucket.bytes / bucket.weighed : null,\n timeShare: overallMs > 0 ? (bucket.totalMs / overallMs) * 100 : 0,\n findings: [...bucket.findings.entries()]\n .map(([detector, found]) => ({\n detector,\n calls: found.calls,\n recoverableMs: found.recoverableMs,\n title: found.title,\n hint: found.hint,\n callsite: found.callsite,\n }))\n .sort((a, b) => b.recoverableMs - a.recoverableMs || b.calls - a.calls),\n trend,\n };\n });\n\n // Most expensive first — the order the screen opens in.\n routes.sort((a, b) => b.timeShare - a.timeShare);\n return { routes, samples: requests.length, windowMs, from: oldest, to: newest };\n}\n","/**\n * How one call compares against the route's own history.\n *\n * A duration on its own says nothing. 400 ms is alarming for a cache read and\n * excellent for a report, so the only comparison worth drawing is against\n * other calls of the same route — and only when there are enough of them for\n * the comparison to be worth more than the silence it replaces.\n */\n\nimport type { DurationBaseline, RecordedRequest } from '../types.js';\nimport type { DurationSample } from './api.js';\nimport { normalizeRoute, percentile } from './routes.js';\n\n/**\n * Below this a percentile is one call wearing a statistic's name.\n *\n * Twenty is where the ninety-fifth percentile stops being the single slowest\n * sample and starts interpolating between two — the point at which \"slower\n * than 95% of calls\" is a claim about a distribution rather than about the\n * one unlucky call that happens to top the list.\n */\nconst MIN_FOR_P95 = 20;\n\n/** Below this the request would be measuring itself. */\nconst MIN_SAMPLES = 2;\n\n/** What the store is asked for when a request is judged against its route. */\nexport interface BaselineQuery {\n readonly method: string;\n /** The normalized route, as `normalizeRoute` produces it. */\n readonly route: string;\n /**\n * The request being judged — it is never part of its own baseline.\n *\n * Left out when the caller wants the route's whole history: the charts do,\n * and a chart with one call missing from it would be a different kind of\n * lie from the one this field prevents.\n */\n readonly excludeId?: string;\n /**\n * The stretch to read, epoch ms.\n *\n * Left out for the whole history. The charts pass the same window the\n * routes table was computed over: a table describing thirteen minutes above\n * a chart describing six hours is two answers to one question.\n */\n readonly from?: number;\n readonly to?: number;\n}\n\n/**\n * The verdict, or `null` when there is nothing honest to say.\n *\n * @param samples the route's other calls, as the store hands them over.\n * `undefined` is a store that cannot answer at all, and produces no verdict\n * rather than one drawn from whatever page happened to be loaded.\n */\nexport function baselineFor(\n request: RecordedRequest,\n samples: readonly DurationSample[] | undefined,\n): DurationBaseline | null {\n if (!samples || samples.length < MIN_SAMPLES) return null;\n\n const sorted = samples.map((sample) => sample.durationMs).sort((a, b) => a - b);\n const sum = sorted.reduce((total, value) => total + value, 0);\n const avgMs = sum / sorted.length;\n\n const times = samples.map((sample) => sample.startedAt);\n const windowMs = Math.max(...times) - Math.min(...times);\n\n const p95Ms = sorted.length >= MIN_FOR_P95 ? percentile(sorted, 0.95) : null;\n const p50Ms = percentile(sorted, 0.5);\n const p99Ms = sorted.length >= MIN_FOR_P95 ? percentile(sorted, 0.99) : null;\n const maxMs = sorted[sorted.length - 1] ?? 0;\n\n // Without a trustworthy p95 the strongest claim available is \"at or under\n // the mean\", which roughly half of all calls are. Calling anything slow off\n // five samples is how a tool starts crying wolf.\n const verdict =\n p95Ms !== null && request.durationMs >= p95Ms\n ? 'slower'\n : request.durationMs <= avgMs\n ? 'faster'\n : 'typical';\n\n return {\n method: request.method,\n route: normalizeRoute(request.path),\n samples: sorted.length,\n windowMs,\n avgMs,\n p95Ms,\n p50Ms,\n p99Ms,\n maxMs,\n verdict,\n };\n}\n","/**\n * Grouping of exceptions by normalised stack.\n *\n * The same error raised three hundred times is one row in the panel with a\n * repeat count, not three hundred rows. Normalisation drops everything that\n * varies between calls and keeps the shape of the stack.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { ExceptionFrame, ExceptionGroup } from '@reqray/protocol';\nimport { isProjectFrame, parseStackFrame } from '../callsite.js';\nimport type { ResolvedStackOptions } from '../config.js';\nimport type { RecordedRequest, SpanError } from '../types.js';\n\nexport type { ExceptionFrame, ExceptionGroup };\n\n/** Buckets in the sparkline — as many as there are bars in the mockup. */\nconst BUCKET_COUNT = 12;\n\n/** Frames taken into the fingerprint: deeper than this stacks stop differing. */\nconst SIGNIFICANT_FRAMES = 8;\n\nfunction framesOf(error: SpanError, options: ResolvedStackOptions): ExceptionFrame[] {\n if (!error.stack) return [];\n\n const frames: ExceptionFrame[] = [];\n for (const line of error.stack.split('\\n')) {\n if (!line.trim().startsWith('at ')) continue;\n const parsed = parseStackFrame(line);\n frames.push({\n raw: line.trim(),\n file: parsed?.file ?? null,\n line: parsed?.line ?? null,\n project: parsed ? isProjectFrame(parsed.file, options) : false,\n });\n }\n return frames;\n}\n\n/**\n * Stack fingerprint.\n *\n * It takes the exception type and the positions of the first frames — without\n * columns and without the message: the message usually carries varying values\n * (`id 8812`), which would split identical errors into separate groups.\n */\nfunction fingerprintStack(error: SpanError, frames: readonly ExceptionFrame[]): string {\n const parts = [error.name];\n for (const frame of frames.slice(0, SIGNIFICANT_FRAMES)) {\n parts.push(frame.file ? `${frame.file}:${frame.line ?? 0}` : frame.raw);\n }\n // There may be no stack at all — then the message is the only thing that\n // tells errors apart.\n if (frames.length === 0) parts.push(error.message);\n\n return createHash('sha1').update(parts.join('\\n')).digest('hex').slice(0, 12);\n}\n\ninterface Accumulator {\n readonly id: string;\n readonly type: string;\n message: string;\n readonly frames: ExceptionFrame[];\n readonly origin: string | null;\n where: string | null;\n count: number;\n lastSeenAt: number;\n readonly requestIds: string[];\n readonly times: number[];\n test: string | null;\n}\n\nfunction originOf(frames: readonly ExceptionFrame[], options: ResolvedStackOptions): string | null {\n const projectFrame = frames.find((frame) => frame.project && frame.file);\n if (!projectFrame?.file) return null;\n const relative = projectFrame.file.startsWith(options.projectRoot)\n ? projectFrame.file.slice(options.projectRoot.length + 1)\n : projectFrame.file;\n return `${relative}:${projectFrame.line ?? 0}`;\n}\n\nfunction bucketize(times: readonly number[], now: number, windowMs: number): number[] {\n const buckets = new Array<number>(BUCKET_COUNT).fill(0);\n if (windowMs <= 0) return buckets;\n\n const from = now - windowMs;\n for (const time of times) {\n const position = Math.floor(((time - from) / windowMs) * BUCKET_COUNT);\n const index = Math.min(BUCKET_COUNT - 1, Math.max(0, position));\n buckets[index] = (buckets[index] ?? 0) + 1;\n }\n return buckets;\n}\n\n/**\n * Builds exception groups from recorded requests.\n *\n * Requests are expected newest first, the order the store returns them in.\n * Groups come back by descending occurrence count.\n */\nexport function groupExceptions(\n requests: readonly RecordedRequest[],\n options: ResolvedStackOptions,\n now = Date.now(),\n): ExceptionGroup[] {\n const groups = new Map<string, Accumulator>();\n let oldest = now;\n\n for (const request of requests) {\n if (request.startedAt < oldest) oldest = request.startedAt;\n\n const error = request.error;\n if (!error) continue;\n\n const frames = framesOf(error, options);\n const id = fingerprintStack(error, frames);\n\n let group = groups.get(id);\n if (!group) {\n group = {\n id,\n type: error.name,\n message: error.message,\n frames,\n origin: originOf(frames, options),\n where: `${request.method} ${request.path}`,\n count: 0,\n lastSeenAt: request.startedAt,\n requestIds: [],\n times: [],\n test: null,\n };\n groups.set(id, group);\n }\n\n group.count++;\n group.times.push(request.startedAt);\n if (request.startedAt > group.lastSeenAt) {\n group.lastSeenAt = request.startedAt;\n group.message = error.message;\n group.where = `${request.method} ${request.path}`;\n }\n // Records arrive newest first, so the first test name seen is the latest.\n if (group.test === null && request.test !== null) group.test = request.test;\n // The request list is capped: the panel needs the latest ones, not all.\n if (group.requestIds.length < 50) group.requestIds.push(request.id);\n }\n\n const windowMs = Math.max(1, now - oldest);\n\n return [...groups.values()]\n .map(\n (group): ExceptionGroup => ({\n id: group.id,\n type: group.type,\n message: group.message,\n origin: group.origin,\n where: group.where,\n count: group.count,\n lastSeenAt: group.lastSeenAt,\n requestIds: group.requestIds,\n frames: group.frames,\n buckets: bucketize(group.times, now, windowMs),\n test: group.test,\n }),\n )\n .sort((a, b) => b.count - a.count || b.lastSeenAt - a.lastSeenAt);\n}\n","/**\n * EXPLAIN of a recorded query, straight from the panel.\n *\n * Safety comes from three rules that are not options:\n * - the SQL is taken from the record — the panel client sends only ids and\n * can never inject a statement;\n * - `ANALYZE` is never used: it executes the query, and an executed\n * INSERT is a write. Plain EXPLAIN plans without running anything;\n * - the query goes to the same pool that ran the original (see\n * `explain-targets.ts`), so \"which database\" is never a guess.\n *\n * Parameterized queries have no recorded values (values are deliberately not\n * collected), so they are planned with `GENERIC_PLAN` — PostgreSQL 16+.\n */\n\nimport type { ExplainNote, ExplainPlanNode, ExplainResult } from '@reqray/protocol';\nimport { explainTarget } from '../explain-targets.js';\nimport type { RecordedRequest } from '../types.js';\n\nexport type { ExplainNote, ExplainPlanNode, ExplainResult };\n\nconst PLACEHOLDER = /\\$\\d+/;\nconst EXPLAIN_TIMEOUT_MS = 5_000;\n\ninterface PlanJson {\n readonly [key: string]: unknown;\n readonly Plans?: readonly PlanJson[];\n}\n\nfunction numberOf(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\nfunction labelOf(node: PlanJson): string {\n const type = typeof node['Node Type'] === 'string' ? (node['Node Type'] as string) : 'node';\n const relation = node['Relation Name'];\n const index = node['Index Name'];\n if (typeof index === 'string' && typeof relation === 'string') {\n return `${type} using ${index} on ${relation}`;\n }\n if (typeof relation === 'string') return `${type} on ${relation}`;\n return type;\n}\n\n/** Flattens the plan tree and derives the warnings. */\nexport function analyzePlan(plan: PlanJson): {\n nodes: ExplainPlanNode[];\n notes: ExplainNote[];\n} {\n const nodes: ExplainPlanNode[] = [];\n const notes: ExplainNote[] = [];\n\n const walk = (node: PlanJson, depth: number): void => {\n nodes.push({\n depth,\n label: labelOf(node),\n rows: numberOf(node['Plan Rows']),\n cost: numberOf(node['Total Cost']),\n });\n\n if (node['Node Type'] === 'Seq Scan' && typeof node['Filter'] === 'string') {\n const relation = typeof node['Relation Name'] === 'string' ? node['Relation Name'] : '?';\n notes.push({\n severity: 'warn',\n message:\n `Seq Scan over \"${relation}\" with filter ${node['Filter']} — ` +\n 'the whole table is read for a fraction of its rows. An index on the filtered column may help.',\n });\n }\n if (node['Node Type'] === 'Sort' && Array.isArray(node['Sort Key'])) {\n notes.push({\n severity: 'info',\n message:\n `Sorting by ${(node['Sort Key'] as unknown[]).join(', ')} happens in memory — ` +\n 'an index in the sort order would remove it entirely.',\n });\n }\n\n for (const child of node.Plans ?? []) walk(child, depth + 1);\n };\n\n walk(node0(plan), 0);\n return { nodes, notes };\n\n function node0(root: PlanJson): PlanJson {\n // `EXPLAIN (FORMAT JSON)` wraps the tree as [{ \"Plan\": {...} }].\n const inner = (root as { Plan?: PlanJson }).Plan;\n return inner ?? root;\n }\n}\n\n/**\n * Whether anything follows the statement's own terminator.\n *\n * A semicolon inside a literal or a comment is not a terminator —\n * `WHERE note = 'a;b'` is one perfectly ordinary statement, and refusing to\n * plan it would be this check crying wolf. So quotes and comments are skipped\n * rather than searched: single quotes with their doubled-quote escape, dollar\n * quoting with its tag, double-quoted identifiers, and both comment forms.\n */\nfunction hasSecondStatement(sql: string): boolean {\n for (let i = 0; i < sql.length; i++) {\n const ch = sql[i];\n\n if (ch === \"'\" || ch === '\"') {\n const quote = ch;\n i++;\n while (i < sql.length) {\n if (sql[i] === quote) {\n // A doubled quote is an escaped one and the literal continues.\n if (sql[i + 1] === quote) i++;\n else break;\n }\n i++;\n }\n continue;\n }\n\n if (ch === '$') {\n const tag = /^\\$[A-Za-z_]\\w*\\$|^\\$\\$/.exec(sql.slice(i));\n if (tag) {\n const close = sql.indexOf(tag[0], i + tag[0].length);\n // An unterminated dollar quote swallows the rest: nothing follows it.\n if (close === -1) return false;\n i = close + tag[0].length - 1;\n continue;\n }\n }\n\n if (ch === '-' && sql[i + 1] === '-') {\n const end = sql.indexOf('\\n', i);\n if (end === -1) return false;\n i = end;\n continue;\n }\n\n if (ch === '/' && sql[i + 1] === '*') {\n const end = sql.indexOf('*/', i + 2);\n if (end === -1) return false;\n i = end + 1;\n continue;\n }\n\n if (ch === ';') return sql.slice(i + 1).trim() !== '';\n }\n return false;\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error(`EXPLAIN did not answer within ${ms} ms`)), ms);\n timer.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n },\n );\n });\n}\n\n/** A user-facing failure: the message is shown in the panel as-is. */\nexport class ExplainError extends Error {\n override readonly name = 'ExplainError';\n constructor(\n message: string,\n readonly status = 400,\n ) {\n super(message);\n }\n}\n\n/**\n * Runs EXPLAIN for one recorded span.\n *\n * @throws ExplainError with a message meant for the panel.\n */\nexport async function runExplain(record: RecordedRequest, spanId: number): Promise<ExplainResult> {\n const span = record.spans.find((candidate) => candidate.id === spanId);\n if (span?.kind !== 'db') {\n throw new ExplainError('span not found, or it is not a SQL query', 404);\n }\n if (span.source !== 'pg') {\n throw new ExplainError(\n `EXPLAIN is supported for queries made through pg; this one went through ${span.source ?? 'an unknown driver'}`,\n );\n }\n if (span.clientId === null) {\n throw new ExplainError(\n 'the executor of this query was not recorded — EXPLAIN has nowhere to go',\n );\n }\n\n const target = explainTarget(span.clientId);\n if (!target) {\n throw new ExplainError(\n 'the pool that ran this query lives inside the application process and is not reachable here — ' +\n 'EXPLAIN works in the panel mounted in the application',\n );\n }\n\n // `EXPLAIN <sql>` is concatenation: a second statement after a semicolon\n // would be planned and then *run*. Reaching this needs an injection the\n // application already has, but a read-only endpoint must not be what turns\n // that into a write.\n if (hasSecondStatement(span.sql)) {\n throw new ExplainError(\n 'this record holds more than one statement, and EXPLAIN plans one — nothing was run',\n );\n }\n\n const parameterized = PLACEHOLDER.test(span.sql);\n const statement = parameterized\n ? `EXPLAIN (GENERIC_PLAN, FORMAT JSON) ${span.sql}`\n : `EXPLAIN (FORMAT JSON) ${span.sql}`;\n\n let rows: unknown;\n try {\n const result = (await withTimeout(\n Promise.resolve(target.query(statement)),\n EXPLAIN_TIMEOUT_MS,\n )) as { rows?: unknown };\n rows = result?.rows;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n if (parameterized && /GENERIC_PLAN|generic_plan|syntax error/i.test(reason)) {\n throw new ExplainError(\n `EXPLAIN of a parameterized query needs PostgreSQL 16+ (GENERIC_PLAN). The database said: ${reason}`,\n );\n }\n throw new ExplainError(`the database rejected EXPLAIN: ${reason}`);\n }\n\n const first = Array.isArray(rows) ? (rows[0] as Record<string, unknown> | undefined) : undefined;\n const planColumn = first?.['QUERY PLAN'];\n const plan = Array.isArray(planColumn) ? planColumn[0] : planColumn;\n if (!plan || typeof plan !== 'object') {\n throw new ExplainError('the database returned the plan in an unexpected shape');\n }\n\n const { nodes, notes } = analyzePlan(plan as PlanJson);\n return { sql: span.sql, nodes, notes, plan };\n}\n","/**\n * Exports: taking a session out of the panel.\n *\n * HAR and cURL are built here rather than in the browser because the panel\n * only ever receives list rows — bodies and headers live in the records, and\n * an export that quietly dropped them would be worse than no export.\n *\n * Both formats are for handing a request to something else: a HAR to a\n * browser's network panel or a colleague's viewer, a curl script to a\n * terminal. Neither is a backup format, and neither promises to round-trip.\n */\n\nimport type { RecordedRequest } from '../types.js';\n\n/** Reqray's own additions to a HAR entry, under the extension prefix HAR reserves. */\ninterface ReqrayHarExtension {\n readonly sqlQueries: number;\n readonly nPlusOne: boolean;\n readonly test: string | null;\n}\n\nfunction headerList(headers: Readonly<Record<string, string>>): Array<{\n name: string;\n value: string;\n}> {\n return Object.entries(headers).map(([name, value]) => ({ name, value }));\n}\n\n/** HAR 1.2. Times are milliseconds, as the format requires. */\nexport function toHar(\n requests: readonly RecordedRequest[],\n now = new Date(0),\n note: string | null = null,\n): Record<string, unknown> {\n return {\n log: {\n version: '1.2',\n creator: { name: 'reqray', version: '0.1' },\n pages: [],\n entries: requests.map((request) => {\n const extension: ReqrayHarExtension = {\n sqlQueries: request.spans.filter((span) => span.kind === 'db').length,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n test: request.test,\n };\n\n return {\n startedDateTime: new Date(request.startedAt).toISOString(),\n time: request.durationMs,\n request: {\n method: request.method,\n url: `${request.path}${request.query ? `?${request.query}` : ''}`,\n httpVersion: 'HTTP/1.1',\n headers: headerList(request.requestHeaders),\n queryString: [],\n cookies: [],\n headersSize: -1,\n bodySize: request.requestBody?.text.length ?? 0,\n ...(request.requestBody\n ? {\n postData: {\n mimeType: request.requestHeaders['content-type'] ?? 'application/json',\n text: request.requestBody.text,\n },\n }\n : {}),\n },\n response: {\n status: request.status,\n statusText: '',\n httpVersion: 'HTTP/1.1',\n headers: headerList(request.responseHeaders),\n cookies: [],\n content: {\n size: request.responseBody?.text.length ?? 0,\n mimeType: request.responseHeaders['content-type'] ?? 'application/json',\n ...(request.responseBody ? { text: request.responseBody.text } : {}),\n },\n redirectURL: '',\n headersSize: -1,\n bodySize: request.responseBody?.text.length ?? 0,\n },\n cache: {},\n // Everything Reqray knows lands in `wait`: the breakdown it has is by\n // span, not by the connection phases HAR describes.\n timings: { send: 0, wait: request.durationMs, receive: 0 },\n _reqray: extension,\n };\n }),\n // Kept out of the entries so a diff of two exports stays readable.\n _exportedAt: now.toISOString(),\n // HAR's own field for this, so a viewer that knows nothing of Reqray\n // still shows it. An export that was cut has to say so: it is evidence,\n // and evidence presented as complete is worse than none.\n ...(note ? { comment: note } : {}),\n },\n };\n}\n\n/** Escapes a value for single-quoted shell. */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * A runnable `.sh`: one curl per request.\n *\n * Masked headers and bodies are exported as they were stored — with the\n * masking. A script that leaked the authorization header of every recorded\n * request would undo the one guarantee the buffer makes.\n */\nexport function toCurlScript(\n requests: readonly RecordedRequest[],\n origin: string,\n note: string | null = null,\n): string {\n const lines = [\n '#!/bin/sh',\n '# Exported from reqray. Sensitive headers and fields are masked, so a',\n '# request that needed them will not authenticate as it did.',\n // At the top rather than the bottom: a script is read from the first line,\n // and \"this is not all of them\" belongs where reading starts.\n ...(note ? [`# ${note}`] : []),\n '',\n ];\n\n for (const request of requests) {\n const url = `${origin}${request.path}${request.query ? `?${request.query}` : ''}`;\n const parts = [`curl -i -X ${request.method} ${shellQuote(url)}`];\n for (const [name, value] of Object.entries(request.requestHeaders)) {\n // Hop-by-hop and length headers are curl's business, not the script's.\n if (name === 'host' || name === 'content-length' || name === 'connection') continue;\n parts.push(` -H ${shellQuote(`${name}: ${value}`)}`);\n }\n if (request.requestBody) parts.push(` --data ${shellQuote(request.requestBody.text)}`);\n\n lines.push(\n // One line, whatever the name holds: a record can come off the wire, and\n // a line break here would end the comment and start a command.\n `# ${request.status} · ${Math.round(request.durationMs)} ms${request.test ? ` · ${request.test.replace(/\\p{Cc}/gu, ' ')}` : ''}`,\n parts.join(' \\\\\\n'),\n '',\n );\n }\n\n return lines.join('\\n');\n}\n","/**\n * Filtering and summary over the request list.\n *\n * Pure functions: the panel runs them on every keystroke in the search box,\n * and tests run them without standing up a server.\n */\n\nimport type { RequestSummary } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { normalizeRoute } from './routes.js';\n\nexport type { RequestSummary } from '@reqray/protocol';\n\n/** The panel's filter set. Empty fields exclude nothing. */\nexport interface RequestFilter {\n /** Substring of the path, method or status. Case-insensitive. */\n readonly query?: string | undefined;\n /** Methods: `GET`, `POST`. An empty list means all. */\n readonly methods?: readonly string[] | undefined;\n /** Status classes: 2, 3, 4, 5. An empty list means all. */\n readonly statusClasses?: readonly number[] | undefined;\n /** Only requests no faster than the given duration. */\n readonly minDurationMs?: number | undefined;\n /** Not before this moment, epoch ms. Inclusive. */\n readonly from?: number | undefined;\n /** Not after this moment, epoch ms. Inclusive. */\n readonly to?: number | undefined;\n /** Only requests where the detectors found something. */\n readonly onlyFindings?: boolean | undefined;\n /** Only requests with an N+1 — a narrower question than \"any finding\". */\n readonly onlyNPlusOne?: boolean | undefined;\n /** Only requests a test issued. */\n readonly onlyTests?: boolean | undefined;\n /**\n * Only requests that failed.\n *\n * Wider than the 5xx class: a handler that threw and still answered 200 is\n * a failure, and it is the one worth finding.\n */\n readonly onlyErrors?: boolean | undefined;\n /**\n * One endpoint, as the Routes screen names it: the normalized path and the\n * method that go with it.\n */\n readonly route?: { readonly method: string; readonly route: string } | undefined;\n /** Substring of the path alone — narrower than `query`, which matches four fields. */\n readonly path?: string | undefined;\n /** Exactly this status code — `404`, not the whole 4xx class. */\n readonly status?: number | undefined;\n /** At least this many SQL queries. */\n readonly minSql?: number | undefined;\n /**\n * Rows the list flags with one of these detectors.\n *\n * The *flag* — the costliest finding — not \"any finding of this kind\":\n * both stores can answer that question identically (SQLite keeps the flag\n * as a column), and it is the badge the reader is pointing at anyway.\n */\n readonly flagged?: readonly string[] | undefined;\n /** Requests issued by a test whose name contains this. Case-insensitive. */\n readonly test?: string | undefined;\n}\n\nfunction matchesQuery(request: RecordedRequest, needle: string): boolean {\n if (request.method.toLowerCase().includes(needle)) return true;\n if (request.path.toLowerCase().includes(needle)) return true;\n if (String(request.status).includes(needle)) return true;\n return request.query ? request.query.toLowerCase().includes(needle) : false;\n}\n\n/** Selects requests matching the filter, keeping the original order (newest first). */\nexport function filterRequests(\n requests: readonly RecordedRequest[],\n filter: RequestFilter = {},\n): RecordedRequest[] {\n const needle = filter.query?.trim().toLowerCase();\n const methods = filter.methods?.length\n ? new Set(filter.methods.map((m) => m.toUpperCase()))\n : null;\n const classes = filter.statusClasses?.length ? new Set(filter.statusClasses) : null;\n\n return requests.filter((request) => {\n if (filter.from !== undefined && request.startedAt < filter.from) return false;\n if (filter.to !== undefined && request.startedAt > filter.to) return false;\n if (needle && !matchesQuery(request, needle)) return false;\n if (methods && !methods.has(request.method.toUpperCase())) return false;\n if (classes && !classes.has(Math.floor(request.status / 100))) return false;\n if (filter.minDurationMs !== undefined && request.durationMs < filter.minDurationMs)\n return false;\n if (filter.onlyFindings && request.findings.length === 0) return false;\n if (filter.onlyNPlusOne && !request.findings.some((f) => f.detector === 'n_plus_one'))\n return false;\n if (filter.onlyTests && request.test === null) return false;\n if (filter.path && !request.path.toLowerCase().includes(filter.path.toLowerCase())) {\n return false;\n }\n if (filter.status !== undefined && request.status !== filter.status) return false;\n if (filter.minSql !== undefined) {\n let sql = 0;\n for (const span of request.spans) if (span.kind === 'db') sql++;\n if (sql < filter.minSql) return false;\n }\n if (filter.flagged?.length) {\n // The same rule the list flags a row by: the costliest finding names it.\n const flag = [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector;\n if (!flag || !filter.flagged.includes(flag)) return false;\n }\n if (filter.test !== undefined) {\n if (request.test === null || !request.test.toLowerCase().includes(filter.test.toLowerCase()))\n return false;\n }\n if (filter.onlyErrors && request.error === null && request.status < 500) return false;\n if (filter.route) {\n if (request.method.toUpperCase() !== filter.route.method.toUpperCase()) return false;\n if (normalizeRoute(request.path) !== filter.route.route) return false;\n }\n return true;\n });\n}\n\n/**\n * Summary over the buffer.\n *\n * `slowMs` is the \"slow\" threshold for the status bar, 500 ms by default, as\n * in the panel mockup.\n */\nexport function summarize(\n all: readonly RecordedRequest[],\n shown: readonly RecordedRequest[],\n slowMs = 500,\n): RequestSummary {\n let slow = 0;\n let errors = 0;\n let withFindings = 0;\n\n for (const request of all) {\n if (request.durationMs >= slowMs) slow++;\n if (request.status >= 500 || request.error) errors++;\n if (request.findings.length > 0) withFindings++;\n }\n\n return { shown: shown.length, total: all.length, slow, errors, withFindings };\n}\n","/**\n * The shape of the traffic over time, for the strip above the list.\n *\n * The panel used to draw this from the rows it had loaded, which was fine\n * while a store held five hundred requests and everything was on screen. With\n * a history behind it, \"the rows I have\" is the last page — a few minutes —\n * and a strip that only spans a few minutes cannot be dragged back to\n * yesterday. So the store answers for its whole range instead.\n *\n * Three numbers per request go into it — when, how long, and whether it\n * failed — and the bucketing happens here, once, for every store. Two\n * implementations of \"which bucket does this fall into\" would drift, and the\n * drift would be a strip that disagrees with the list under it.\n */\n\n/** What the timeline needs to know about one request. */\nexport interface TimePoint {\n readonly startedAt: number;\n readonly durationMs: number;\n readonly hasError: boolean;\n}\n\nimport type { TimelineBucket, TimelineReport } from '@reqray/protocol';\n\nexport type { TimelineBucket, TimelineReport };\n\n/** How many columns the strip is drawn with, unless asked otherwise. */\nexport const TIMELINE_BUCKETS = 64;\n/** Above this, a request is drawn as slow — the panel's own threshold. */\nconst SLOW_MS = 500;\n\n/**\n * Which column a moment falls into.\n *\n * Shared with the per-route charts on purpose: two implementations of \"which\n * bucket is this\" drift, and the drift is a strip that disagrees with the\n * chart under it about when something happened. Everything inside a single\n * millisecond lands in the first column rather than dividing by a zero span.\n */\nexport function bucketIndex(at: number, from: number, to: number, count: number): number {\n const span = to - from;\n const fraction = span > 0 ? (at - from) / span : 0;\n return Math.max(0, Math.min(count - 1, Math.floor(fraction * count)));\n}\n\n/**\n * Buckets a set of points into a strip.\n *\n * `null` when there is nothing to draw: an empty store has no range, and a\n * strip with invented ends would be a lie about what is recorded.\n */\nexport function buildTimeline(\n points: readonly TimePoint[],\n bucketCount: number = TIMELINE_BUCKETS,\n): TimelineReport | null {\n if (points.length === 0 || bucketCount <= 0) return null;\n\n let from = Number.POSITIVE_INFINITY;\n let to = Number.NEGATIVE_INFINITY;\n for (const point of points) {\n if (point.startedAt < from) from = point.startedAt;\n if (point.startedAt > to) to = point.startedAt;\n }\n\n const buckets: TimelineBucket[] = Array.from({ length: bucketCount }, () => ({\n err: 0,\n slow: 0,\n rest: 0,\n total: 0,\n }));\n\n for (const point of points) {\n const index = bucketIndex(point.startedAt, from, to, bucketCount);\n const bucket = buckets[index] as {\n err: number;\n slow: number;\n rest: number;\n total: number;\n };\n if (point.hasError) bucket.err++;\n else if (point.durationMs >= SLOW_MS) bucket.slow++;\n else bucket.rest++;\n bucket.total++;\n }\n\n return { from, to, buckets };\n}\n","/**\n * One metric over one period, and what the period adds up to.\n *\n * Everything else the panel draws is scoped to something: the strip above the\n * list counts requests and nothing else, and stage 41's charts cover one route\n * at a time. This is the screen that answers \"what did latency do this week\",\n * and the arithmetic behind it lives here — once, for every store.\n *\n * **Why the store hands over rows rather than answers.** The obvious division\n * of labour is to let SQLite compute percentiles in SQL, and the obvious cost\n * is two implementations of the same statistic that quietly disagree: one\n * interpolating between neighbouring samples, the other picking the nearest\n * rank. So a store hands back a few numbers per request — the shape below,\n * never the payloads — and the bucketing and the percentiles happen here. The\n * rule the plan actually cares about still holds: a week of rows must never\n * reach the browser to have a median taken at the other end.\n *\n * What a store *is* responsible for is not reading its whole history into\n * memory. It reads a bounded number of rows and says when it stopped, and\n * this file passes that admission on rather than presenting a truncated total\n * as a complete one.\n */\n\nimport type { MetricSeries, SeriesMetric, SeriesResponse, SeriesTotals } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport type { RequestFilter } from './filters.js';\nimport { normalizeRoute, percentile } from './routes.js';\nimport { bucketIndex } from './timeline.js';\n\n/**\n * One request, as a history reading needs it.\n *\n * Ten numbers rather than a record: a period is tens of thousands of requests,\n * and parsing that many JSON documents to look at one field in each is how a\n * screen becomes slower than the question it answers.\n */\nexport interface HistorySample {\n readonly startedAt: number;\n readonly durationMs: number;\n readonly hasError: boolean;\n readonly sqlCount: number;\n readonly httpCount: number;\n readonly bytes: number;\n /** Mean event-loop delay while it ran, or `null` when nothing measured it. */\n readonly loopDelayMs: number | null;\n readonly findingCount: number;\n /** Time inside queries, ms. `null` for requests stored before it was kept. */\n readonly sqlMs: number | null;\n /** Time covered by no instrumented work, ms. `null` as above. */\n readonly selfMs: number | null;\n readonly method: string;\n readonly route: string;\n /** The detector the list flags this request with, when one fired. */\n readonly flag: string | null;\n}\n\n/**\n * One request, reduced to what a history reading needs.\n *\n * For every store that keeps whole records — the in-memory ring, and any\n * store answering from `list()` — so that what the screen shows does not\n * depend on which one is behind it.\n */\nexport function historySampleOf(request: RecordedRequest): HistorySample {\n let sqlCount = 0;\n let httpCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n else if (span.kind === 'http') httpCount++;\n }\n\n return {\n startedAt: request.startedAt,\n durationMs: request.durationMs,\n hasError: request.error !== null || request.status >= 500,\n sqlCount,\n httpCount,\n bytes: request.weight?.bytesOut ?? 0,\n loopDelayMs: request.host?.loopDelayMs ?? null,\n findingCount: request.findings.length,\n sqlMs: request.timing?.sqlMs ?? null,\n selfMs: request.timing?.selfMs ?? null,\n method: request.method,\n route: normalizeRoute(request.path),\n // The same rule the list flags a row by: the costliest finding names it.\n flag: [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null,\n };\n}\n\n/** What a store is asked for. */\nexport interface HistoryQuery {\n /** Epoch ms, inclusive. */\n readonly from: number;\n /** Epoch ms, inclusive. */\n readonly to: number;\n /** The same filter the list uses, so a metric can be asked about one route. */\n readonly filter: RequestFilter;\n}\n\n/** What a store answers with. */\nexport interface HistorySamples {\n readonly samples: readonly HistorySample[];\n /** The store stopped reading before the period ended. */\n readonly truncated: boolean;\n}\n\n/** Columns the chart is drawn with, unless the caller asks for fewer. */\nexport const SERIES_COLUMNS = 48;\n\n/**\n * Below this many requests per column a percentile is not a statistic.\n *\n * The same figure stage 41 settled on for a route's charts: a p95 over three\n * samples is the slowest of three, and a chart of those jumps about saying\n * nothing.\n */\nconst MIN_PER_COLUMN = 6;\n\n/** Below this the chart stops being a shape and becomes a row of bars. */\nconst MIN_COLUMNS = 8;\n\n/** A column of the chart, while it is being filled. */\ninterface Column {\n readonly durations: number[];\n errors: number;\n sqlCount: number;\n httpCount: number;\n bytes: number;\n findings: number;\n loopTotal: number;\n loopSamples: number;\n}\n\nfunction emptyColumn(): Column {\n return {\n durations: [],\n errors: 0,\n sqlCount: 0,\n httpCount: 0,\n bytes: 0,\n findings: 0,\n loopTotal: 0,\n loopSamples: 0,\n };\n}\n\n/** The value of one metric in one column, or `null` when it cannot say. */\nfunction metricValue(metric: SeriesMetric, column: Column, bucketMs: number): number | null {\n const calls = column.durations.length;\n // Nothing ran here. Every metric returns a void rather than a zero: a\n // stretch nobody called did not have an error rate of nought.\n if (calls === 0) return null;\n\n switch (metric) {\n case 'p50':\n case 'p95':\n case 'p99': {\n const sorted = [...column.durations].sort((a, b) => a - b);\n const p = metric === 'p50' ? 0.5 : metric === 'p95' ? 0.95 : 0.99;\n return percentile(sorted, p);\n }\n case 'throughput':\n return bucketMs > 0 ? (calls / bucketMs) * 60_000 : null;\n case 'errorRate':\n return column.errors / calls;\n case 'sqlPerRequest':\n return column.sqlCount / calls;\n case 'httpPerRequest':\n return column.httpCount / calls;\n case 'bytes':\n return column.bytes / calls;\n case 'loopDelay':\n // Only the requests that carried a reading. A process that was never\n // measured must not average in as calm.\n return column.loopSamples > 0 ? column.loopTotal / column.loopSamples : null;\n case 'findingsPerRequest':\n return column.findings / calls;\n default:\n return null;\n }\n}\n\n/** Everything a period adds up to. */\nexport function totalsOf(samples: readonly HistorySample[]): SeriesTotals {\n if (samples.length === 0) {\n return {\n calls: 0,\n errorRate: 0,\n p50: 0,\n p95: 0,\n p99: 0,\n sqlMs: null,\n appMs: null,\n busiest: null,\n topFinding: null,\n };\n }\n\n const durations: number[] = [];\n let errors = 0;\n let sqlMs = 0;\n let appMs = 0;\n let timed = 0;\n const routes = new Map<string, { method: string; route: string; calls: number }>();\n const findings = new Map<string, number>();\n\n for (const sample of samples) {\n durations.push(sample.durationMs);\n if (sample.hasError) errors++;\n if (sample.sqlMs !== null && sample.selfMs !== null) {\n sqlMs += sample.sqlMs;\n appMs += sample.selfMs;\n timed++;\n }\n\n const key = `${sample.method} ${sample.route}`;\n const seen = routes.get(key);\n if (seen) seen.calls++;\n else routes.set(key, { method: sample.method, route: sample.route, calls: 1 });\n\n if (sample.flag) findings.set(sample.flag, (findings.get(sample.flag) ?? 0) + 1);\n }\n\n durations.sort((a, b) => a - b);\n\n let busiest: SeriesTotals['busiest'] = null;\n for (const entry of routes.values()) {\n if (!busiest || entry.calls > busiest.calls) busiest = { ...entry };\n }\n\n let topFinding: SeriesTotals['topFinding'] = null;\n for (const [detector, calls] of findings) {\n if (!topFinding || calls > topFinding.calls) topFinding = { detector, calls };\n }\n\n return {\n calls: samples.length,\n errorRate: errors / samples.length,\n p50: percentile(durations, 0.5),\n p95: percentile(durations, 0.95),\n p99: percentile(durations, 0.99),\n // Reported only when something recorded it. A period half of whose\n // requests predate the figure would otherwise show a share of SQL time\n // that is half of the truth and looks like a fall.\n sqlMs: timed > 0 ? sqlMs : null,\n appMs: timed > 0 ? appMs : null,\n busiest,\n topFinding,\n };\n}\n\n/**\n * How many columns a period's traffic can support.\n *\n * Never more than asked for, never so many that each holds a handful of\n * requests — see {@link MIN_PER_COLUMN}.\n */\nexport function columnsFor(sampleCount: number, asked: number): number {\n if (asked <= 0) return 0;\n return Math.max(\n Math.min(MIN_COLUMNS, asked),\n Math.min(asked, Math.ceil(sampleCount / MIN_PER_COLUMN)),\n );\n}\n\nexport interface HistoryOptions {\n /** The period, as the caller chose it — not as the data happens to fall. */\n readonly from: number;\n readonly to: number;\n readonly metrics: readonly SeriesMetric[];\n readonly columns?: number;\n}\n\n/**\n * Builds the answer for one reading of the screen.\n *\n * The period comes from the caller rather than from the samples: a week with\n * traffic in one hour of it must draw a week with one column in it, not an\n * hour stretched across the screen.\n */\n/** Samples into columns of one window — the same cut for a period and its ghost. */\nfunction bucketize(\n samples: readonly HistorySample[],\n from: number,\n to: number,\n count: number,\n): Column[] {\n const columns: Column[] = Array.from({ length: count }, emptyColumn);\n for (const sample of samples) {\n const column = columns[bucketIndex(sample.startedAt, from, to, count)];\n if (!column) continue;\n column.durations.push(sample.durationMs);\n if (sample.hasError) column.errors++;\n column.sqlCount += sample.sqlCount;\n column.httpCount += sample.httpCount;\n column.bytes += sample.bytes;\n column.findings += sample.findingCount;\n if (sample.loopDelayMs !== null) {\n column.loopTotal += sample.loopDelayMs;\n column.loopSamples++;\n }\n }\n return columns;\n}\n\nexport function historyOf(\n current: HistorySamples,\n previous: readonly HistorySample[],\n options: HistoryOptions,\n): SeriesResponse {\n const samples = current.samples;\n const asked = options.columns ?? SERIES_COLUMNS;\n const count = Math.max(1, columnsFor(samples.length, asked));\n\n const columns = bucketize(samples, options.from, options.to, count);\n\n // A period of no width would divide by zero and a chart of it would be a\n // single column claiming to be a stretch of time.\n const span = Math.max(1, options.to - options.from);\n const bucketMs = span / count;\n\n // The period immediately before, cut into the same number of columns, so\n // the ghost lines up with the line it sits behind.\n const ghostColumns =\n previous.length > 0 ? bucketize(previous, options.from - span, options.from - 1, count) : null;\n const primary = options.metrics[0];\n\n const series: MetricSeries[] = options.metrics.map((metric) => ({\n metric,\n values: columns.map((column) => metricValue(metric, column, bucketMs)),\n }));\n\n return {\n from: options.from,\n to: options.to,\n bucketMs,\n calls: columns.map((column) => column.durations.length),\n series,\n totals: totalsOf(samples),\n // No traffic before the period is not a period of zeroes; it is nothing\n // to compare against, and the screen says so instead of inventing a\n // hundred-percent rise.\n previous: previous.length > 0 ? totalsOf(previous) : null,\n ghost:\n ghostColumns && primary\n ? ghostColumns.map((column) => metricValue(primary, column, bucketMs))\n : null,\n truncated: current.truncated,\n };\n}\n","/**\n * Where a page of the request list stopped.\n *\n * The cursor is part of the panel's API, not of any one store: the in-memory\n * ring and the SQLite history hand out cursors the browser cannot tell apart,\n * and both continue from one the other could have written.\n *\n * The key is whatever the page is ordered by — the start time for the list as\n * it is normally read, the duration when the question is \"what was slowest\".\n * It is not a position on its own, because several requests can share a\n * millisecond and plenty share a duration, so the id rides along and breaks\n * the tie exactly the way the ordering does: largest first, among equals the\n * larger id first.\n */\n\n/** A decoded cursor. */\nexport interface Cursor {\n /** Value of the column the page is ordered by. */\n readonly key: number;\n readonly id: string;\n}\n\n/** Writes the position of the last row on a page. */\nexport function encodeCursor(key: number, id: string): string {\n return `${key}.${id}`;\n}\n\n/**\n * Reads a cursor back.\n *\n * Split at the last dot rather than the first: a duration key is fractional,\n * and request ids are base36 with no dot in them.\n *\n * Anything unparseable means \"start from the newest\" rather than an error: a\n * stale link is a thing that happens, and answering it with a 400 helps\n * nobody.\n */\nexport function decodeCursor(raw: string | null | undefined): Cursor | null {\n if (!raw) return null;\n const dot = raw.lastIndexOf('.');\n if (dot <= 0) return null;\n const key = Number(raw.slice(0, dot));\n const id = raw.slice(dot + 1);\n if (!Number.isFinite(key) || id === '') return null;\n return { key, id };\n}\n\n/**\n * Whether a row belongs on a page continuing from `cursor`.\n *\n * Strictly past it, so a row is never served twice and never skipped.\n */\nexport function isAfterCursor(cursor: Cursor, key: number, id: string): boolean {\n if (key !== cursor.key) return key < cursor.key;\n return id < cursor.id;\n}\n","/**\n * One page of a list, from records held in memory.\n *\n * The paging rule, in one place: the router's fallback calls it, and so does\n * any store that holds its records in memory. Two implementations of it would\n * mean one panel giving two answers depending on the store behind it.\n *\n * A store that pages in its own query language cannot use this and should not\n * — pushing the work down is why it has a `page()`. What it owes is the same\n * behaviour, which is what the parity test checks.\n */\n\nimport type { RecordedRequest } from '../types.js';\nimport type { PageQuery, RequestPage } from './api.js';\nimport { toRow } from './api.js';\nimport { filterRequests, summarize } from './filters.js';\nimport { decodeCursor, encodeCursor, isAfterCursor } from './paging.js';\n\n/** What the caller knows that the records do not. */\nexport interface PageContext {\n /** Ids currently pinned. Exempt from the filter, and flagged on the row. */\n readonly pinned?: ReadonlySet<string> | undefined;\n /** Above this a request counts as slow in the summary. */\n readonly slowMs?: number | undefined;\n}\n\n/**\n * Pages `records` — newest first — according to `query`.\n *\n * `records` is the store's whole contents: the summary is over all of them,\n * which is what makes the status bar a statement about the store rather than\n * about the page.\n */\nexport function pageFromList(\n records: readonly RecordedRequest[],\n query: PageQuery,\n context: PageContext = {},\n): RequestPage {\n const pinned = context.pinned ?? new Set<string>();\n\n // A pinned request is one the reader deliberately set aside: it stays\n // through a filter that would otherwise exclude it.\n const matched = new Set(filterRequests(records, query.filter).map((item) => item.id));\n const shown = records.filter((item) => matched.has(item.id) || pinned.has(item.id));\n\n // What the page is ordered by, and therefore what the cursor counts in.\n const slowest = query.sort === 'slowest';\n const keyOf = (item: RecordedRequest): number => (slowest ? item.durationMs : item.startedAt);\n // Sorted in both cases: the cursor counts in this order, and a list handed\n // over in arrival order is not in it — a slow request starts early and\n // lands late, and a page boundary beside it would skip or repeat rows.\n const ordered = [...shown].sort((a, b) => keyOf(b) - keyOf(a) || (a.id < b.id ? 1 : -1));\n\n const cursor = decodeCursor(query.cursor);\n const after = cursor\n ? ordered.filter((item) => isAfterCursor(cursor, keyOf(item), item.id))\n : ordered;\n\n const rows = after.slice(0, query.limit);\n const last = rows[rows.length - 1];\n const nextCursor = after.length > rows.length && last ? encodeCursor(keyOf(last), last.id) : null;\n\n return {\n rows: rows.map((item) => toRow(item, pinned.has(item.id))),\n nextCursor,\n summary: summarize(records, shown, context.slowMs),\n };\n}\n","/**\n * Was the process to blame?\n *\n * Knowing an operation is slow does not say why, and often the code did not\n * change at all — the loop fell behind, and every callback waited before it\n * even started. That is invisible in a waterfall: the spans are each fast and\n * the time is between them.\n *\n * The comparison here is a route against itself. Its calls are split by\n * whether the loop was in its *own* top quartile at the time, and the two\n * halves are compared. Elevated is never a fixed threshold: a delay that is\n * alarming for one service is idle for the next, and the only baseline worth\n * comparing a process against is the same process.\n *\n * It is evidence, not proof, and the panel says so. A batch job hammering the\n * same process explains the shape as well as this route being its victim.\n */\n\nimport type { HostPressure, HostPressureSide } from '../types.js';\nimport type { DurationSample } from './api.js';\nimport { percentile } from './routes.js';\n\n/**\n * Calls needed on each side of the split.\n *\n * Twenty is where a ninety-fifth percentile stops being the single slowest\n * call and starts describing a distribution. Below it the comparison is\n * between two anecdotes.\n */\nconst MIN_PER_SIDE = 20;\n\n/**\n * How much slower the bad half has to be before it is worth a word.\n *\n * Under half again, the difference is inside the noise of a sample this size,\n * and a card that fires there is a card that fires always.\n */\nconst MIN_RATIO = 1.5;\n\n/**\n * How much the loop has to have varied for \"elevated\" to mean anything.\n *\n * A host that was flat has no elevated state to compare against: splitting it\n * at its own quartile would sort calls by a millisecond of jitter and then\n * report whatever the two halves happened to differ by.\n */\nconst MIN_SPREAD_MS = 1;\n\nfunction sideOf(durations: readonly number[]): HostPressureSide {\n const sorted = [...durations].sort((a, b) => a - b);\n const sum = sorted.reduce((total, value) => total + value, 0);\n return {\n calls: sorted.length,\n p95Ms: percentile(sorted, 0.95),\n avgMs: sorted.length === 0 ? 0 : sum / sorted.length,\n };\n}\n\n/**\n * The finding, or `null` — which is the answer far more often, and by design.\n *\n * @param samples every other call of the route, as the store hands them over.\n */\nexport function pressureFor(samples: readonly DurationSample[]): HostPressure | null {\n const measured = samples.filter(\n (sample): sample is DurationSample & { loopDelayMs: number } => sample.loopDelayMs !== null,\n );\n if (measured.length < MIN_PER_SIDE * 2) return null;\n\n const delays = measured.map((sample) => sample.loopDelayMs).sort((a, b) => a - b);\n const cutoffMs = percentile(delays, 0.75);\n // Did the loop actually move? Comparing the top quartile against the bottom\n // one answers it without a threshold of its own.\n if (cutoffMs - percentile(delays, 0.25) < MIN_SPREAD_MS) return null;\n\n const elevated = sideOf(\n measured.filter((sample) => sample.loopDelayMs >= cutoffMs).map((sample) => sample.durationMs),\n );\n const normal = sideOf(\n measured.filter((sample) => sample.loopDelayMs < cutoffMs).map((sample) => sample.durationMs),\n );\n if (elevated.calls < MIN_PER_SIDE || normal.calls < MIN_PER_SIDE) return null;\n // Nothing to be slower than: a route where the good half is instant would\n // report a ratio of infinity and mean nothing by it.\n if (normal.p95Ms <= 0) return null;\n\n const ratio = elevated.p95Ms / normal.p95Ms;\n if (ratio < MIN_RATIO) return null;\n\n return {\n metric: 'loop',\n cutoffMs,\n ratio,\n share: (elevated.calls / measured.length) * 100,\n elevated,\n normal,\n };\n}\n","/**\n * Request replay from the panel.\n *\n * The request is replayed through the same application — with its full\n * middleware stack — so this is a real run, not a simulation. Hence the\n * restriction: a replay in production means a second card charge and a second\n * email, so outside development it is enabled only by an explicit flag.\n *\n * A replayed request must not show up in the shared list: it is marked by a\n * header, and its record goes not to the transport but to whoever started the\n * replay.\n */\n\nimport type { ReplayComparison, ReplayInput, ReplayMetrics } from '@reqray/protocol';\nimport { runOutsideScope } from '../context.js';\nimport { awaitReplay } from '../replay-waiters.js';\nimport { REPLAY_HEADER } from '../reqray.js';\nimport type { RecordedRequest } from '../types.js';\n\nexport type { ReplayComparison, ReplayInput, ReplayMetrics };\n\nfunction numberOrNull(value: string | undefined): number | null {\n if (value === undefined) return null;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/** Reduces a request record to the comparison metrics. */\nexport function metricsOf(request: RecordedRequest): ReplayMetrics {\n let sqlCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n }\n\n return {\n status: request.status,\n durationMs: request.durationMs,\n sqlCount,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n bytes: numberOrNull(request.responseHeaders['content-length']),\n etag: request.responseHeaders['etag'] ?? null,\n };\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | null> {\n return new Promise<T | null>((resolve) => {\n const timer = setTimeout(() => resolve(null), ms);\n timer.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n () => {\n clearTimeout(timer);\n resolve(null);\n },\n );\n });\n}\n\nlet counter = 0;\n\nfunction nextReplayId(): string {\n counter = (counter + 1) % 0xffffff;\n return `r${counter.toString(36)}${Math.random().toString(36).slice(2, 8)}`;\n}\n\n/**\n * Runs the request again and returns a comparison against the original.\n *\n * @param origin the application's own address, e.g. `http://127.0.0.1:3000`.\n * @param recordTimeoutMs how long to wait for the replay's record before\n * returning a partial comparison.\n */\nexport async function runReplay(\n origin: string,\n input: ReplayInput,\n original: RecordedRequest,\n recordTimeoutMs = 2_000,\n): Promise<ReplayComparison> {\n const replayId = nextReplayId();\n\n let stopWaiting = (): void => {};\n const recorded = new Promise<RecordedRequest>((resolve) => {\n stopWaiting = awaitReplay(replayId, resolve);\n });\n\n const startedAt = performance.now();\n try {\n // Outside the scope: Reqray's own HTTP call must not become a span of the\n // request that opened the panel.\n const response = await runOutsideScope(() =>\n fetch(`${origin}${input.path}`, {\n method: input.method,\n headers: { ...input.headers, [REPLAY_HEADER]: replayId },\n ...(input.body === undefined ? {} : { body: input.body }),\n }),\n );\n\n const text = await response.text();\n const durationMs = performance.now() - startedAt;\n const record = await withTimeout(recorded, recordTimeoutMs);\n\n const replay: ReplayMetrics = record\n ? metricsOf(record)\n : {\n status: response.status,\n durationMs,\n sqlCount: 0,\n nPlusOne: false,\n bytes: Buffer.byteLength(text),\n etag: response.headers.get('etag'),\n };\n\n return { original: metricsOf(original), replay, partial: record === null };\n } finally {\n stopWaiting();\n }\n}\n","/**\n * Three charts for one endpoint, and nothing beyond them.\n *\n * Latency over time, the share that failed, and how often it was called —\n * enough to see \"it got slower at 14:20, after the deploy\" and to stop there.\n * Not a dashboard builder, not alerting, not aggregates over arbitrary\n * dimensions: that is the line where this becomes a worse Datadog, and it is\n * written down in the plan so that nobody crosses it by inertia.\n *\n * The bucketing is the strip's own, so a chart and the strip above it cannot\n * disagree about when something happened.\n */\n\nimport type { RouteSeries, SeriesBucket } from '@reqray/protocol';\nimport type { DurationSample } from './api.js';\nimport { percentile } from './routes.js';\nimport { bucketIndex } from './timeline.js';\n\nexport type { RouteSeries, SeriesBucket };\n\n/** Columns a route's charts are drawn with, unless asked otherwise. */\nexport const SERIES_BUCKETS = 48;\n\n/**\n * Calls a column should hold before it is worth drawing as one.\n *\n * A percentile over three samples is the slowest of three, which is why a\n * chart drawn at full resolution over a quiet route shows a p95 and a p99\n * that are the same number and jump about together. Fewer, fuller columns say\n * less about *when* and much more about *what*, and the resolution should\n * follow how much there is to draw rather than the width of the box.\n */\nconst MIN_PER_COLUMN = 6;\n\n/** Below this the chart stops being a shape and becomes a bar. */\nconst MIN_BUCKETS = 12;\n\n/**\n * Buckets one route's calls.\n *\n * `null` when the store holds nothing for it: a chart with invented ends\n * would be a claim about a stretch of time nobody recorded.\n */\nexport function routeSeries(\n method: string,\n route: string,\n samples: readonly DurationSample[],\n bucketCount: number = SERIES_BUCKETS,\n): RouteSeries | null {\n if (samples.length === 0 || bucketCount <= 0) return null;\n\n let from = Number.POSITIVE_INFINITY;\n let to = Number.NEGATIVE_INFINITY;\n for (const sample of samples) {\n if (sample.startedAt < from) from = sample.startedAt;\n if (sample.startedAt > to) to = sample.startedAt;\n }\n\n // As many columns as the traffic supports, and never more than asked for.\n const count = Math.max(\n Math.min(MIN_BUCKETS, bucketCount),\n Math.min(bucketCount, Math.ceil(samples.length / MIN_PER_COLUMN)),\n );\n\n const columns: Array<{ durations: number[]; errors: number }> = Array.from(\n { length: count },\n () => ({ durations: [], errors: 0 }),\n );\n\n for (const sample of samples) {\n const column = columns[bucketIndex(sample.startedAt, from, to, count)];\n if (!column) continue;\n column.durations.push(sample.durationMs);\n if (sample.hasError) column.errors++;\n }\n\n // A single call spans no time; a second keeps throughput finite and honest.\n const span = Math.max(1_000, to - from);\n const bucketMs = span / count;\n\n return {\n method,\n route,\n from,\n to,\n bucketMs,\n calls: samples.length,\n buckets: columns.map((column, index) => {\n const sorted = column.durations.sort((a, b) => a - b);\n return {\n at: from + index * bucketMs,\n calls: sorted.length,\n errors: column.errors,\n p50: sorted.length > 0 ? percentile(sorted, 0.5) : 0,\n p95: sorted.length > 0 ? percentile(sorted, 0.95) : 0,\n p99: sorted.length > 0 ? percentile(sorted, 0.99) : 0,\n };\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAM,YAAY;AASlB,IAAM,YAAY;AAUlB,IAAM,mBAAmB;AASzB,IAAM,gBAAgB;AASf,SAAS,UACd,QACA,SACA,QACgB;AAChB,QAAM,SAAS,IAAI,IAAI,QAAQ,IAAI,CAAC,UAAU,CAAC,GAAG,MAAM,MAAM,IAAI,MAAM,KAAK,IAAI,KAAK,CAAC,CAAC;AACxF,QAAM,WAAW,KAAK,IAAI,GAAG,OAAO,KAAK,OAAO,IAAI;AAGpD,QAAM,SAAS,KAAK,IAAI,GAAG,OAAO,YAAY,QAAQ;AAKtD,QAAM,cAAc,OAAO,OAAO,CAAC,OAAO,UAAU,QAAQ,MAAM,OAAO,CAAC;AAC1E,QAAM,eAAe,QAAQ,OAAO,CAAC,OAAO,UAAU,QAAQ,MAAM,OAAO,CAAC;AAC5E,QAAM,cAAc,KAAK,IAAI,GAAG,eAAe,WAAW;AAC1D,QAAM,eAAe,cAAc,IAAI,cAAc,YAAY,cAAc,UAAU;AAUzF,QAAM,eAAe,CAAC,OAAoB,cAAqC;AAC7E,UAAM,cAAc,c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EA,SAAS,aACP,QACA,SACA,UACM;AACN,QAAM,YAAY;AAChB,QAAI;AACF,YAAM,UAAW,MAAM,SAAS,OAAO;AAQvC,YAAM,WAAW,OAAO,QAAQ,OAAO,WAAW,OAAO,IAAI,QAAQ,EAAE,IAAI;AAC3E,UAAI,CAAC,UAAU;AACb,iBAAS,UAAU,KAAK,EAAE,OAAO,6BAA6B,CAAC;AAC/D;AAAA,MACF;AAEA,YAAM,QAAqB;AAAA,QACzB,QAAQ,OAAO,QAAQ,WAAW,WAAW,QAAQ,SAAS,SAAS;AAAA,QACvE,MAAM,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO,SAAS;AAAA,QACjE,SACE,QAAQ,WAAW,OAAO,QAAQ,YAAY,WACzC,QAAQ,UACT,CAAC;AAAA,QACP,MAAM,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO;AAAA,MAC1D;AAEA,eAAS,UAAU,KAAK,MAAM,UAAUA,UAAS,OAAO,GAAG,OAAO,QAAQ,CAAC;AAAA,IAC7E,SAAS,OAAO;AACd,YAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACpE,eAAS,gBAAgB,kBAAkB,MAAM,EAAE;AACnD,eAAS,UAAU,KAAK,EAAE,OAAO,kBAAkB,MAAM,GAAG,CAAC;AAAA,IAC/D;AAAA,EACF,GAAG;AACL;","names":["resolve","bucketize","MIN_RATIO","withTimeout","resolve","MIN_PER_COLUMN","originOf","page"]}
|
|
1
|
+
{"version":3,"sources":["../../src/panel/activity.ts","../../src/panel/api.ts","../../src/panel/findings.ts","../../src/panel/routes.ts","../../src/panel/baseline.ts","../../src/panel/exceptions.ts","../../src/panel/explain.ts","../../src/panel/export.ts","../../src/panel/filters.ts","../../src/panel/timeline.ts","../../src/panel/history.ts","../../src/panel/paging.ts","../../src/panel/page-from-list.ts","../../src/panel/pressure.ts","../../src/panel/replay.ts","../../src/panel/series.ts"],"sourcesContent":["/**\n * What ran here.\n *\n * A chart nobody can click is decoration. Clicking a moment on one should\n * answer the only question worth asking of it — what was different then —\n * and the answer has to be ranked by *how far each route strayed from its own\n * behaviour*, not by how much traffic it had. Ranked by volume, the busiest\n * endpoint tops every list and the moment explains nothing.\n *\n * Every route is compared against itself over the rest of the window, so a\n * spike does not inflate the baseline it is being measured against. When\n * nothing stands out, the answer is that nothing did: whatever moved the\n * chart came from garbage collection, a neighbour on the box, or the host —\n * and a list of ordinary routes presented as an explanation is worse than a\n * sentence admitting there is none.\n */\n\nimport type { ActivityReport, Outlier } from '@reqray/protocol';\n\nexport type { ActivityReport, Outlier };\n\n/** One route's traffic over a stretch of time, as the store groups it. */\nexport interface RouteWindow {\n readonly method: string;\n readonly route: string;\n readonly calls: number;\n /** Mean duration over those calls, ms. */\n readonly avgMs: number;\n}\n\n/**\n * Calls a route needs in the moment before it can be called unusual.\n *\n * Two calls that happened to be slow are two calls that happened to be slow.\n */\nconst MIN_CALLS = 3;\n\n/**\n * How far from its own baseline a route has to be.\n *\n * Half again, on either rate or duration. Below that the difference is inside\n * the noise of a handful of calls, and a list that includes it is a list of\n * everything that ran.\n */\nconst MIN_RATIO = 1.5;\n\n/**\n * How many calls above its usual count a route has to be.\n *\n * A ratio alone is not enough at low rates: a route called twice a minute\n * that happens to be called three times has run at 1.5× its rate and nothing\n * has happened. Three extra calls is the smallest excess that is a count\n * rather than a rounding of one.\n */\nconst MIN_EXCESS_CALLS = 3;\n\n/**\n * How much slower, in milliseconds, before a ratio means anything.\n *\n * A route that goes from 0.2 ms to 0.4 ms has doubled and nobody has noticed.\n * Five milliseconds is the smallest difference somebody could experience, and\n * below it a ratio is reporting the jitter of the clock.\n */\nconst MIN_EXCESS_MS = 5;\n\n/**\n * What stood out in one stretch of time.\n *\n * @param moment routes grouped over the clicked stretch.\n * @param overall the same, over the whole window the chart covers — the\n * moment included, and subtracted here so a spike is not its own baseline.\n */\nexport function whatRanAt(\n moment: readonly RouteWindow[],\n overall: readonly RouteWindow[],\n window: { from: number; to: number; overallMs: number },\n): ActivityReport {\n const before = new Map(overall.map((entry) => [`${entry.method} ${entry.route}`, entry]));\n const momentMs = Math.max(1, window.to - window.from);\n // The rest of the window: what the route usually does, with the moment\n // taken out of it. Never negative, and never zero as a divisor.\n const restMs = Math.max(1, window.overallMs - momentMs);\n\n // How the moment compares as a whole. Bursty traffic — a demo restarting, a\n // cron waking up, a deploy draining a queue — lifts every route at once, and\n // without this every route is an outlier in every burst.\n const momentCalls = moment.reduce((total, entry) => total + entry.calls, 0);\n const overallCalls = overall.reduce((total, entry) => total + entry.calls, 0);\n const restOverall = Math.max(0, overallCalls - momentCalls);\n const overallRatio = restOverall > 0 ? momentCalls / momentMs / (restOverall / restMs) : null;\n\n /**\n * How much busier the moment was for everything *except* this route.\n *\n * Each route is judged against how the rest of the traffic moved, not\n * against the total it is part of — otherwise a route that is the only\n * thing running compares against itself and can never stand out, which is\n * exactly the case where it obviously does.\n */\n const withoutRatio = (entry: RouteWindow, restCalls: number): number | null => {\n const otherMoment = momentCalls - entry.calls;\n const otherRest = restOverall - restCalls;\n if (otherMoment <= 0 || otherRest <= 0) return null;\n return otherMoment / momentMs / (otherRest / restMs);\n };\n\n const outliers: Outlier[] = [];\n for (const entry of moment) {\n if (entry.calls < MIN_CALLS) continue;\n\n const all = before.get(`${entry.method} ${entry.route}`);\n const restCalls = Math.max(0, (all?.calls ?? 0) - entry.calls);\n\n // Never ran outside this moment: not a ratio, a fact.\n if (restCalls === 0) {\n outliers.push({\n method: entry.method,\n route: entry.route,\n calls: entry.calls,\n avgMs: entry.avgMs,\n rateRatio: null,\n slowerRatio: null,\n firstSeen: true,\n });\n continue;\n }\n\n const rate = restCalls / restMs;\n const rateRatio = entry.calls / momentMs / rate;\n // What this moment would have held if the route had simply grown with\n // everything else. The excess over *that* is the part worth reporting,\n // and at low rates it is what tells a burst from a coin toss.\n const others = withoutRatio(entry, restCalls);\n const expected = rate * momentMs * (others ?? 1);\n // The route against how the rest of the traffic moved: one means it rose\n // exactly as much as everything around it, which is not an answer to\n // \"what was different here\".\n const shareRatio = others === null ? rateRatio : rateRatio / others;\n // The mean over the rest, recovered from the totals: the store grouped\n // once, and asking it twice for overlapping ranges would cost a scan to\n // learn something arithmetic already knows.\n const restAvg =\n all && all.calls > 0\n ? Math.max(0, (all.avgMs * all.calls - entry.avgMs * entry.calls) / restCalls)\n : 0;\n const slowerRatio = restAvg > 0 ? entry.avgMs / restAvg : null;\n\n const busier = shareRatio >= MIN_RATIO && entry.calls - expected >= MIN_EXCESS_CALLS;\n const slower =\n slowerRatio !== null && slowerRatio >= MIN_RATIO && entry.avgMs - restAvg >= MIN_EXCESS_MS;\n if (!busier && !slower) continue;\n\n outliers.push({\n method: entry.method,\n route: entry.route,\n calls: entry.calls,\n avgMs: entry.avgMs,\n rateRatio,\n slowerRatio,\n firstSeen: false,\n });\n }\n\n const strength = (outlier: Outlier): number =>\n outlier.firstSeen\n ? Number.POSITIVE_INFINITY\n : Math.max(outlier.rateRatio ?? 0, outlier.slowerRatio ?? 0);\n\n return {\n from: window.from,\n to: window.to,\n calls: momentCalls,\n rateRatio: overallRatio,\n outliers: outliers.sort((a, b) => strength(b) - strength(a)),\n };\n}\n","/**\n * Panel HTTP API.\n *\n * The handler is written against raw `IncomingMessage`/`ServerResponse`, so\n * Express and Fastify mount the very same code — no need to duplicate the API\n * in each adapter.\n */\n\nimport { createReadStream, statSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { extname, resolve, sep } from 'node:path';\nimport type {\n FiledPatternState,\n PanelMeta,\n RequestRow,\n RequestSort,\n RequestSummary,\n SeriesMetric,\n StoredPatternState,\n} from '@reqray/protocol';\nimport type { ResolvedOptions } from '../config.js';\nimport { detectorSettings } from '../detectors/index.js';\nimport { warnOnce } from '../logger.js';\nimport { isPanelRequestAllowed } from '../panel.js';\nimport type { RetentionLimits } from '../retention.js';\nimport { ensureTiming } from '../timing.js';\nimport type { RecordedRequest } from '../types.js';\nimport { type RouteWindow, whatRanAt } from './activity.js';\nimport { type BaselineQuery, baselineFor } from './baseline.js';\nimport { blameLine } from './blame.js';\nimport { groupExceptions } from './exceptions.js';\nimport { ExplainError, runExplain } from './explain.js';\nimport { toCurlScript, toHar } from './export.js';\nimport { filterRequests, type RequestFilter } from './filters.js';\nimport { type FindingSamples, type FindingsQuery, flagWithMutes, patternsOf } from './findings.js';\nimport { type HistoryQuery, type HistorySamples, historyOf, SERIES_COLUMNS } from './history.js';\nimport { pageFromList } from './page-from-list.js';\nimport { pressureFor } from './pressure.js';\nimport { logOf, projectReport, retentionOf } from './project.js';\nimport { type ReplayInput, runReplay } from './replay.js';\nimport { normalizeRoute, routeStats } from './routes.js';\nimport { routeSeries, SERIES_BUCKETS } from './series.js';\nimport { buildTimeline, TIMELINE_BUCKETS, type TimePoint } from './timeline.js';\n\nexport type { RequestRow } from '@reqray/protocol';\n\n/** One page of the request list, newest first. */\nexport interface RequestPage {\n readonly rows: readonly RequestRow[];\n /** Feed back as `cursor` to get the next, older page. `null` — the end. */\n readonly nextCursor: string | null;\n /** Numbers for the status bar, over the whole store rather than the page. */\n readonly summary: RequestSummary;\n}\n\n/** What the panel asks a store for when it wants a page. */\nexport interface PageQuery {\n readonly filter: RequestFilter;\n readonly limit: number;\n /** Where to continue from. Absent or `null` — start at the beginning. */\n readonly cursor?: string | null | undefined;\n /**\n * What \"the beginning\" means: the newest requests, or the slowest.\n *\n * Defaults to `recent`. Sorting is the store's job rather than the\n * caller's — \"the slowest request\" over a history on disk cannot be found\n * by reading a page of it and comparing.\n */\n readonly sort?: RequestSort | undefined;\n}\n\n/** Where the panel gets its data. Implemented by the transport store. */\nexport interface PanelSource {\n /** Requests from newest to oldest. */\n list(): readonly RecordedRequest[];\n get(id: string): RecordedRequest | undefined;\n clear(): void;\n subscribe(listener: (request: RecordedRequest) => void): () => void;\n /**\n * Keeps a request past its turn in the ring buffer, or lets it go again.\n *\n * Optional: a store without pinning is still a valid source, and the panel\n * answers the pin route with an explanation instead of pretending.\n *\n * @returns `false` when the request is gone or the pin limit is reached.\n */\n pin?(id: string, pinned: boolean): boolean;\n /** Ids currently pinned. */\n pinned?(): readonly string[];\n /**\n * When, how long, and whether it failed — for every request the store\n * holds.\n *\n * Optional, and cheap on purpose: three numbers per request, so the strip\n * above the list can span the whole history instead of the page that\n * happens to be loaded. A source without it leaves the panel to draw from\n * the rows it has, which is what it always did.\n */\n timeSeries?(): readonly TimePoint[];\n /**\n * One page of the list, filtered and cut by the store itself.\n *\n * Optional, and the difference between a buffer and a history: reading\n * everything into memory to filter it is what an in-memory ring can afford\n * and a store on disk cannot. A source without this method is served by\n * `list()`, whole.\n */\n page?(query: PageQuery): RequestPage;\n /**\n * Durations of other calls of one route.\n *\n * Optional, and asked for rather than derived from `list()`: judging one\n * call against its route means reading that route's whole history, which a\n * ring buffer can afford to scan and a store on disk should answer with a\n * query. A source without it leaves the detail page with no verdict, which\n * is better than a verdict drawn from the last page that happened to load.\n */\n durations?(query: BaselineQuery): readonly DurationSample[];\n /**\n * Traffic grouped by route over a stretch of time.\n *\n * Optional, and an aggregate rather than a page: answering \"what ran in\n * this moment\" by reading the moment's requests would mean loading a busy\n * minute of them to count four numbers per route.\n */\n counts?(query: { from: number; to: number }): readonly RouteWindow[];\n /**\n * A period's requests, a handful of numbers each.\n *\n * Optional, and the one method that reads a *stretch* rather than a page or\n * a route: the history screen asks what a week did, and answering that from\n * `list()` would mean holding a week of payloads in memory to look at ten\n * fields in each. A store must bound what it reads and say when it stopped\n * — a truncated total presented as a complete one is worse than no screen.\n */\n history?(query: HistoryQuery): HistorySamples;\n /**\n * Finding occurrences over a stretch of time, one row each.\n *\n * Optional, and rare rows on purpose: requests with findings are a small\n * minority, so a store answers this from them alone instead of reading the\n * window. A source without it leaves the findings tab explaining itself\n * rather than empty.\n */\n findings?(query: FindingsQuery): FindingSamples;\n /**\n * The reader's own bookkeeping per pattern: `ack` or `muted`.\n *\n * Patterns in neither state are `new` and are simply absent. A store that\n * persists (SQLite) keeps these across restarts; the in-memory ring keeps\n * them exactly as long as it keeps the requests they are about.\n */\n findingStates?(): ReadonlyMap<string, FiledPatternState>;\n /** Remembers a state; `new` forgets the pattern. */\n setFindingState?(id: string, state: StoredPatternState): void;\n}\n\n/**\n * One call of a route, as the store hands it over.\n *\n * Four numbers rather than a record: judging a call against its route, or\n * drawing the route's last hour, means reading every call of it, and parsing\n * a few thousand JSON documents to look at one field in each is how a page\n * becomes slow.\n */\nexport interface DurationSample {\n readonly durationMs: number;\n /** Epoch ms — what the window the samples cover is measured from. */\n readonly startedAt: number;\n /** Threw, or answered 5xx — what the error-rate chart counts. */\n readonly hasError: boolean;\n /**\n * Mean event-loop delay while it ran, or `null` when nothing measured it.\n *\n * What splits a route's calls into \"the host was fine\" and \"the host was\n * struggling\" — the comparison that says whether the process was to blame.\n */\n readonly loopDelayMs: number | null;\n}\n\n/** Everything the panel handler needs to serve a request. */\nexport interface PanelHandlerInit {\n readonly source: PanelSource;\n readonly options: ResolvedOptions;\n /**\n * Directory with the built dashboard.\n *\n * Left out when `@reqray/dashboard` is not installed: the API keeps working\n * and the UI route answers with an explanation instead of a blank page.\n */\n readonly assetsDir?: string | undefined;\n}\n\n/**\n * Panel request handler.\n *\n * @returns `true` if the request belonged to the panel and has been handled.\n * `false` means it is an ordinary application request and must be passed on.\n */\nexport type PanelHandler = (request: IncomingMessage, response: ServerResponse) => boolean;\n\n/**\n * The transport the panel can read from, if there is one.\n *\n * A transport is a store when it can answer the four questions the panel\n * asks. An HTTP transport to an external collector cannot — the panel then\n * runs in the collector. Neither can a log file, which is write-only by\n * design, so a fan-out is searched through rather than tested as a whole.\n *\n * Warns when the panel is configured and nothing can serve it: a panel that\n * quietly does not mount is a 404 nobody can explain.\n */\nexport function panelSourceFor(transport: unknown, options: ResolvedOptions): PanelSource | null {\n const direct = asPanelSource(transport);\n if (direct) return direct;\n\n const members = (transport as { transports?: readonly unknown[] } | null)?.transports;\n if (Array.isArray(members)) {\n for (const member of members) {\n const found = asPanelSource(member);\n if (found) return found;\n }\n }\n\n if (options.enabled && options.panel) {\n const name = (transport as { name?: unknown } | null)?.name;\n warnOnce(\n 'panel.source',\n `the panel is not mounted: ${typeof name === 'string' ? name : 'this transport'} keeps no requests to show. ` +\n 'A store — @reqray/store-memory or @reqray/store-sqlite — has to be among the transports.',\n );\n }\n return null;\n}\n\n/** Whether a transport can answer what the panel asks of a store. */\nfunction asPanelSource(transport: unknown): PanelSource | null {\n const candidate = transport as Partial<PanelSource> | null;\n if (!candidate) return null;\n const complete =\n typeof candidate.list === 'function' &&\n typeof candidate.get === 'function' &&\n typeof candidate.clear === 'function' &&\n typeof candidate.subscribe === 'function';\n return complete ? (candidate as PanelSource) : null;\n}\n\n/**\n * Projects a record into a list row.\n *\n * The whole list is served on every panel open, and full records with spans\n * and bodies would weigh megabytes. Details come from a separate request by\n * identifier.\n */\nexport function toRow(request: RecordedRequest, pinned = false): RequestRow {\n let sqlCount = 0;\n let httpCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n else if (span.kind === 'http') httpCount++;\n }\n\n return {\n id: request.id,\n method: request.method,\n path: request.path,\n query: request.query,\n route: normalizeRoute(request.path),\n status: request.status,\n durationMs: request.durationMs,\n startedAt: request.startedAt,\n sqlCount,\n httpCount,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n findingCount: request.findings.length,\n flag: [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null,\n hasError: request.error !== null || request.status >= 500,\n // Straight through, including the nulls: a row from a store written\n // before cost was measured has no cost, and inventing a zero would put a\n // cheap-looking request next to genuinely cheap ones.\n cpuMs: request.cost?.cpuMs ?? null,\n cpuShare: request.cost?.cpuShare ?? null,\n pinned,\n test: request.test,\n };\n}\n\n/** A file the browser saves rather than renders. */\nfunction sendDownload(\n response: ServerResponse,\n filename: string,\n contentType: string,\n body: string,\n): void {\n response.writeHead(200, {\n 'content-type': contentType,\n 'content-disposition': `attachment; filename=\"${filename}\"`,\n 'cache-control': 'no-store',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\nfunction sendJson(response: ServerResponse, status: number, payload: unknown): void {\n const body = JSON.stringify(payload);\n response.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\n/**\n * How many rows one page may hold.\n *\n * Capped rather than trusted: the parameter comes from a browser, and an\n * unbounded page defeats the point of having pages at all.\n */\nconst DEFAULT_PAGE_LIMIT = 100;\nconst MAX_PAGE_LIMIT = 500;\n\nfunction pageLimit(params: URLSearchParams): number {\n const asked = Number(params.get('limit'));\n if (!Number.isFinite(asked) || asked <= 0) return DEFAULT_PAGE_LIMIT;\n return Math.min(Math.floor(asked), MAX_PAGE_LIMIT);\n}\n\n/** A positive finite number from a query parameter, or `undefined`. */\nfunction positive(raw: string | null): number | undefined {\n const value = Number(raw);\n return Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\nconst HOUR_MS = 60 * 60 * 1000;\n\n/** Every metric the history screen may ask for. Nothing outside this list. */\nconst METRICS: readonly SeriesMetric[] = [\n 'p50',\n 'p95',\n 'p99',\n 'throughput',\n 'errorRate',\n 'sqlPerRequest',\n 'httpPerRequest',\n 'bytes',\n 'loopDelay',\n 'findingsPerRequest',\n];\n\n/**\n * Which metrics to draw.\n *\n * Two at most: a third line is a dashboard, and a chart nobody can read is\n * not a better answer than a chart with one line on it.\n */\nfunction parseMetrics(params: URLSearchParams): SeriesMetric[] {\n const asked = params\n .getAll('metric')\n .flatMap((value) => value.split(','))\n .map((value) => value.trim())\n .filter((value): value is SeriesMetric => (METRICS as readonly string[]).includes(value));\n\n const unique = [...new Set(asked)].slice(0, 2);\n return unique.length > 0 ? unique : ['p95'];\n}\n\n/**\n * The query string, as the filter the store applies.\n *\n * Exported so the panel's client-side filter is checked against this and not\n * against a second reading of the same parameters.\n */\nexport function parseFilter(params: URLSearchParams): RequestFilter {\n const methods = params\n .getAll('method')\n .flatMap((value) => value.split(','))\n .filter(Boolean);\n const statusClasses = params\n .getAll('status')\n .flatMap((value) => value.split(','))\n .map((value) => Number.parseInt(value, 10))\n .filter((value) => Number.isFinite(value));\n\n const minDuration = Number(params.get('minDurationMs'));\n const minSql = Number(params.get('minSql'));\n const status = Number(params.get('statusExact'));\n const flagged = params\n .getAll('flagged')\n .flatMap((value) => value.split(','))\n .filter(Boolean);\n const route = params.get('route');\n const routeMethod = params.get('routeMethod');\n const from = Number(params.get('from'));\n const to = Number(params.get('to'));\n\n return {\n from: Number.isFinite(from) && from > 0 ? from : undefined,\n to: Number.isFinite(to) && to > 0 ? to : undefined,\n query: params.get('q') ?? undefined,\n methods,\n statusClasses,\n minDurationMs: Number.isFinite(minDuration) && minDuration > 0 ? minDuration : undefined,\n onlyFindings: params.get('findings') === '1',\n onlyNPlusOne: params.get('nplus') === '1',\n onlyTests: params.get('tests') === '1',\n onlyErrors: params.get('errors') === '1',\n route: route && routeMethod ? { method: routeMethod, route } : undefined,\n path: params.get('path') ?? undefined,\n status: Number.isFinite(status) && status > 0 ? status : undefined,\n minSql: Number.isFinite(minSql) && minSql > 0 ? minSql : undefined,\n flagged: flagged.length > 0 ? flagged : undefined,\n test: params.get('test') ?? undefined,\n };\n}\n\n/**\n * Reads the body of a panel request.\n *\n * An already-parsed body is taken first: the application almost certainly has\n * a json parser (`express.json()`) that consumed the stream before us —\n * reading the socket a second time is pointless, it is already empty.\n */\nasync function readBody(request: IncomingMessage, limitBytes = 1_000_000): Promise<unknown> {\n const parsed = (request as IncomingMessage & { body?: unknown }).body;\n if (parsed !== undefined && parsed !== null) {\n return typeof parsed === 'string' ? JSON.parse(parsed) : parsed;\n }\n\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n const buffer = chunk as Buffer;\n size += buffer.length;\n if (size > limitBytes) throw new Error('request body too large');\n chunks.push(buffer);\n }\n const raw = Buffer.concat(chunks).toString('utf8');\n return raw ? JSON.parse(raw) : {};\n}\n\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.woff2': 'font/woff2',\n '.ico': 'image/x-icon',\n};\n\n/**\n * Serves the built dashboard.\n *\n * Anything that is not an existing file falls back to `index.html`: the panel\n * is a single-page app, and its inner screens are state, not server routes.\n */\nfunction serveAsset(assetsDir: string, route: string, response: ServerResponse): boolean {\n const root = resolve(assetsDir);\n const requested = route === '/' ? 'index.html' : route.replace(/^\\/+/, '');\n let target = resolve(root, requested);\n\n // A path escaping the assets directory can only come from a traversal attempt.\n if (target !== root && !target.startsWith(root + sep)) return false;\n\n let file = statSync(target, { throwIfNoEntry: false });\n if (!file?.isFile()) {\n target = resolve(root, 'index.html');\n file = statSync(target, { throwIfNoEntry: false });\n if (!file?.isFile()) return false;\n }\n\n response.writeHead(200, {\n 'content-type': MIME_TYPES[extname(target)] ?? 'application/octet-stream',\n 'content-length': file.size,\n // Asset names are content-hashed by the build; index.html must not be cached.\n 'cache-control': target.endsWith('index.html') ? 'no-store' : 'public, max-age=31536000',\n });\n createReadStream(target).pipe(response);\n return true;\n}\n\n/**\n * The application's own address — replay needs it to call back into itself.\n *\n * From the socket, never from `Host`. Replay follows this address carrying\n * headers the caller chose, so a forged `Host` would aim it — cookies and all\n * — at any host that resolves.\n */\nfunction originOf(request: IncomingMessage): string {\n const port = request.socket.localPort;\n const address = request.socket.localAddress ?? '127.0.0.1';\n // IPv6 literals need brackets in a URL; `::1` is the ordinary local case.\n const host = address.includes(':') ? `[${address}]` : address;\n // TLS never reaches this far: the panel is mounted inside the application,\n // and replay always goes to its own local address.\n return `http://${host}${port ? `:${port}` : ''}`;\n}\n\n/**\n * Whether a state-changing request came from the panel itself.\n *\n * The gate says who may use the panel, not what page is asking. Without this,\n * any site open in a developer's browser can POST to `/api/replay` and make\n * the application run a recorded request again — a second charge, a second\n * email. That the reply is unreadable to that page is no comfort: the effect\n * has happened.\n *\n * `Sec-Fetch-Site` is the browser's own account and cannot be set by script.\n * `same-site` is refused with `cross-site`: two ports of localhost are one\n * site, and the dev server on the other port is the neighbour in question.\n *\n * Neither header means the caller is not a browser, and CSRF is not that.\n */\nfunction isSameOrigin(request: IncomingMessage): boolean {\n const site = request.headers['sec-fetch-site'];\n if (typeof site === 'string') return site === 'same-origin' || site === 'none';\n\n const origin = request.headers.origin;\n if (typeof origin !== 'string' || origin === '') return true;\n\n const host = request.headers.host;\n if (typeof host !== 'string') return false;\n try {\n return new URL(origin).host === host;\n } catch {\n // An origin that is not a URL is not one this panel wrote.\n return false;\n }\n}\n\n/**\n * How many requests one export may carry.\n *\n * It serializes whole records into one string, synchronously, answering a GET.\n * The stores bound `list()`, but a bound living in the store is not this\n * endpoint's: a store written elsewhere would hand over its whole history.\n */\nconst EXPORT_LIMIT = 1_000;\n\n/** The newest requests matching the filter, and how many did not fit. */\nfunction forExport(\n source: PanelSource,\n params: URLSearchParams,\n): { requests: readonly RecordedRequest[]; dropped: number } {\n const matched = filterRequests(source.list(), parseFilter(params));\n if (matched.length <= EXPORT_LIMIT) return { requests: matched, dropped: 0 };\n // The newest, because a truncated export should be the recent part of the\n // story rather than an arbitrary slice of it.\n return {\n requests: matched.slice(-EXPORT_LIMIT),\n dropped: matched.length - EXPORT_LIMIT,\n };\n}\n\n/**\n * What a truncated export says about itself.\n *\n * An export is evidence: a cap nobody is told about reads as \"this is\n * everything\".\n */\nfunction exportNote(dropped: number): string | null {\n return dropped === 0\n ? null\n : `${dropped} older request${dropped === 1 ? '' : 's'} matched and were left out: an export carries at most ${EXPORT_LIMIT}.`;\n}\n\n/**\n * How many live feeds one panel may hold open at once.\n *\n * Each one is a listener on the store and a timer; nothing else bounds them,\n * and a stream is opened by a GET that anything can repeat.\n */\nconst MAX_STREAMS = 32;\n\n/**\n * How much one feed may have written that its reader has not taken.\n *\n * A tab left in the background or a proxy that stalled stops reading, and\n * every row since then sits in this process's memory, per feed, without end.\n * Past this the feed is dropped; the panel reconnects and re-reads the list,\n * which is what it does after any gap.\n */\nconst MAX_STREAM_BACKLOG_BYTES = 1024 * 1024;\n\n/**\n * How many feeds one panel is holding.\n *\n * Per handler rather than per process: two applications in one process are two\n * panels, and a cap they share is a cap that depends on a neighbour.\n */\ninterface StreamCount {\n open: number;\n}\n\nfunction streamEvents(\n source: PanelSource,\n mutes: MuteView,\n request: IncomingMessage,\n response: ServerResponse,\n streams: StreamCount,\n): void {\n if (streams.open >= MAX_STREAMS) {\n sendJson(response, 503, { error: `too many live feeds open (${MAX_STREAMS})` });\n return;\n }\n streams.open++;\n\n response.writeHead(200, {\n 'content-type': 'text/event-stream; charset=utf-8',\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n // Disables nginx buffering: without it the feed stalls.\n 'x-accel-buffering': 'no',\n });\n response.write(': reqray stream\\n\\n');\n\n const unsubscribe = source.subscribe((recorded) => {\n // The live feed obeys mutes the same way the list does.\n const [row] = mutes.silence([toRow(recorded)]);\n if (response.writableLength > MAX_STREAM_BACKLOG_BYTES) {\n response.destroy();\n return;\n }\n response.write(`data: ${JSON.stringify(row)}\\n\\n`);\n });\n\n const keepAlive = setInterval(() => response.write(': ping\\n\\n'), 20_000);\n keepAlive.unref?.();\n\n let stopped = false;\n const stop = (): void => {\n // Both `close` events fire for one disconnect; the count must move once.\n if (stopped) return;\n stopped = true;\n streams.open--;\n clearInterval(keepAlive);\n unsubscribe();\n };\n request.on('close', stop);\n response.on('close', stop);\n}\n\n/**\n * Creates the panel handler.\n *\n * Returns `null` if the panel is disabled by options: the adapter then has\n * nothing to mount.\n */\nexport function createPanelHandler(init: PanelHandlerInit): PanelHandler | null {\n const { source, options } = init;\n const panel = options.panel;\n if (!panel || !options.enabled) return null;\n\n const mount = panel.path.endsWith('/') ? panel.path.slice(0, -1) : panel.path;\n const streams: StreamCount = { open: 0 };\n const mutes = new MuteView(source);\n\n const serve: PanelHandler = (request, response) => {\n // Express strips the matched mount prefix from `url` inside `app.use`;\n // `originalUrl` keeps the full path. Anything non-Express has no such\n // property and falls back to the plain url.\n const rawUrl = (request as { originalUrl?: string }).originalUrl ?? request.url ?? '/';\n if (rawUrl !== mount && !rawUrl.startsWith(`${mount}/`) && !rawUrl.startsWith(`${mount}?`)) {\n return false;\n }\n\n const url = new URL(rawUrl, 'http://reqray.local');\n const route = url.pathname.slice(mount.length) || '/';\n\n if (\n !isPanelRequestAllowed(panel.gate, {\n headers: request.headers,\n ip: request.socket.remoteAddress ?? null,\n })\n ) {\n sendJson(response, 403, {\n error: panel.gate\n ? 'panel access denied by the gate'\n : 'without a gate the panel answers only to this machine, at a local address. ' +\n \"To open it further, set one: reqray({ panel: { gate: 'open' } }) or a function.\",\n });\n return true;\n }\n\n const method = request.method ?? 'GET';\n\n // Before anything reads a body: a refusal has to come earlier than the\n // work it refuses, and every state-changing route is behind this line.\n if (method !== 'GET' && method !== 'HEAD' && !isSameOrigin(request)) {\n sendJson(response, 403, { error: 'this request did not come from the panel' });\n return true;\n }\n\n if (route === '/api/meta' && method === 'GET') {\n // Typed rather than inline: this object is the `/api/meta` contract, and\n // the protocol is where that contract is written down.\n const meta: PanelMeta = {\n pid: process.pid,\n startedAt: Date.now() - Math.round(process.uptime() * 1000),\n mode: options.mode,\n bufferSize: options.bufferSize,\n replayEnabled: options.replay,\n blameEnabled: options.blame,\n detectors: detectorSettings(options),\n };\n sendJson(response, 200, meta);\n return true;\n }\n\n if (route === '/api/project' && method === 'GET') {\n // Async, unlike every other route here: it asks git which commit is\n // running, and a panel that lies about the build is worse than one that\n // takes a few milliseconds.\n void projectReport(options, source)\n .then((report) => sendJson(response, 200, report))\n .catch((error: unknown) => {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 500, { error: `project report unavailable: ${reason}` });\n });\n return true;\n }\n\n if (route === '/api/retention' && method === 'GET') {\n sendJson(response, 200, { retention: retentionOf(options), log: logOf(options) });\n return true;\n }\n\n if (route === '/api/retention' && method === 'POST') {\n handleRetention(options, request, response);\n return true;\n }\n\n if (route === '/api/timeline' && method === 'GET') {\n if (!source.timeSeries) {\n sendJson(response, 200, { timeline: null });\n return true;\n }\n const asked = Number(url.searchParams.get('buckets'));\n const buckets =\n Number.isFinite(asked) && asked > 0 ? Math.min(Math.floor(asked), 512) : TIMELINE_BUCKETS;\n // A stretch, when the caller names one. A store with days of history\n // and an hour of traffic draws a strip that is empty but for two\n // columns; being able to ask for the part worth looking at is what\n // makes the strip readable without making it lie about the rest.\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const points =\n Number.isFinite(from) && Number.isFinite(to) && to > from\n ? source.timeSeries().filter((point) => point.startedAt >= from && point.startedAt <= to)\n : source.timeSeries();\n sendJson(response, 200, { timeline: buildTimeline(points, buckets) });\n return true;\n }\n\n if (route === '/api/requests' && method === 'GET') {\n const filter = parseFilter(url.searchParams);\n const limit = pageLimit(url.searchParams);\n const sort: RequestSort = url.searchParams.get('sort') === 'slowest' ? 'slowest' : 'recent';\n\n // A store that can page does its own filtering: a history on disk must\n // not be read into memory to answer one screenful.\n if (source.page) {\n const page = source.page({\n filter,\n limit,\n sort,\n cursor: url.searchParams.get('cursor'),\n });\n sendJson(response, 200, {\n requests: mutes.silence(page.rows),\n summary: page.summary,\n nextCursor: page.nextCursor,\n });\n return true;\n }\n\n // No `page()`: the same rule, applied here over everything the store\n // holds, rather than a second implementation of it.\n const page = pageFromList(\n source.list(),\n { filter, limit, sort, cursor: url.searchParams.get('cursor') },\n {\n pinned: new Set(source.pinned?.() ?? []),\n slowMs: options.sampling.slowMs || 500,\n },\n );\n sendJson(response, 200, {\n requests: mutes.silence(page.rows),\n summary: page.summary,\n nextCursor: page.nextCursor,\n });\n return true;\n }\n\n if (route === '/api/export/har' && method === 'GET') {\n const { requests: shown, dropped } = forExport(source, url.searchParams);\n sendDownload(\n response,\n 'reqray.har',\n 'application/json; charset=utf-8',\n JSON.stringify(toHar(shown, new Date(), exportNote(dropped)), null, 2),\n );\n return true;\n }\n\n if (route === '/api/export/curl' && method === 'GET') {\n const { requests: shown, dropped } = forExport(source, url.searchParams);\n sendDownload(\n response,\n 'reqray-requests.sh',\n 'text/x-shellscript; charset=utf-8',\n toCurlScript(shown, originOf(request), exportNote(dropped)),\n );\n return true;\n }\n\n if (route === '/api/blame' && method === 'POST') {\n if (!options.blame) {\n sendJson(response, 403, {\n error:\n 'git blame from the panel is off. Outside local development it is enabled explicitly: reqray({ blame: true }).',\n });\n return true;\n }\n handleBlame(options, request, response);\n return true;\n }\n\n if (route === '/api/routes' && method === 'GET') {\n sendJson(response, 200, routeStats(source.list(), mutes.set()));\n return true;\n }\n\n if (route === '/api/series' && method === 'GET') {\n if (!source.history) {\n // The store cannot read a stretch. Said plainly rather than drawn as\n // an empty chart, which would be a claim about a quiet week.\n sendJson(response, 200, { series: null });\n return true;\n }\n\n const now = Date.now();\n const to = positive(url.searchParams.get('to')) ?? now;\n const from = positive(url.searchParams.get('from')) ?? to - HOUR_MS;\n if (to <= from) {\n sendJson(response, 400, { error: 'the period must end after it starts' });\n return true;\n }\n\n const askedColumns = positive(url.searchParams.get('buckets'));\n const columns = askedColumns ? Math.min(Math.floor(askedColumns), 512) : SERIES_COLUMNS;\n const metrics = parseMetrics(url.searchParams);\n const filter = parseFilter(url.searchParams);\n\n const query = (span: { from: number; to: number }): HistoryQuery => ({\n ...span,\n // The period is the period, whatever the filter's own range says: the\n // screen owns the window, and a stale `from` in the filter would\n // silently narrow it.\n filter: { ...filter, from: span.from, to: span.to },\n });\n\n const current: HistorySamples = source.history(query({ from, to }));\n // The same length again, immediately before. Only ever used for a\n // comparison, so a truncated reading of it changes nothing that is\n // presented as complete.\n const before = source.history(query({ from: from - (to - from), to: from - 1 }));\n\n sendJson(response, 200, {\n series: historyOf(current, before.samples, { from, to, metrics, columns }),\n });\n return true;\n }\n\n if (route === '/api/findings' && method === 'GET') {\n if (!source.findings) {\n // The store cannot read its findings back. Said plainly rather than\n // rendered as an empty work list, which would be a claim about the\n // code being clean.\n sendJson(response, 200, { findings: null });\n return true;\n }\n const read = source.findings({\n from: positive(url.searchParams.get('from')),\n to: positive(url.searchParams.get('to')),\n });\n sendJson(response, 200, {\n findings: patternsOf(read, {\n states: source.findingStates?.(),\n changedAt: fileChangedAt,\n }),\n });\n return true;\n }\n\n if (route === '/api/findings/state' && method === 'POST') {\n handleFindingState(source, mutes, request, response);\n return true;\n }\n\n if (route === '/api/routes/series' && method === 'GET') {\n const wanted = url.searchParams.get('route');\n const verb = url.searchParams.get('method');\n if (!wanted || !verb) {\n sendJson(response, 400, { error: 'a route and a method are needed to draw one' });\n return true;\n }\n // A store that cannot answer draws nothing, rather than a chart of\n // whatever page the browser happened to be holding.\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const samples = source.durations?.({\n method: verb,\n route: wanted,\n // A chart is drawn over the stretch the caller names, so that it\n // covers the same traffic the table beside it describes.\n ...(Number.isFinite(from) && Number.isFinite(to) && to > from ? { from, to } : {}),\n });\n const asked = Number(url.searchParams.get('buckets'));\n const buckets =\n Number.isFinite(asked) && asked > 0 ? Math.min(Math.floor(asked), 256) : SERIES_BUCKETS;\n sendJson(response, 200, {\n series: samples ? routeSeries(verb, wanted, samples, buckets) : null,\n });\n return true;\n }\n\n if (route === '/api/timeline/at' && method === 'GET') {\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const overallFrom = Number(url.searchParams.get('overallFrom'));\n const overallTo = Number(url.searchParams.get('overallTo'));\n if (![from, to, overallFrom, overallTo].every(Number.isFinite) || to <= from) {\n sendJson(response, 400, { error: 'a moment needs a start and an end, in epoch ms' });\n return true;\n }\n if (!source.counts) {\n sendJson(response, 200, { activity: null });\n return true;\n }\n sendJson(response, 200, {\n activity: whatRanAt(\n source.counts({ from, to }),\n source.counts({ from: overallFrom, to: overallTo }),\n { from, to, overallMs: overallTo - overallFrom },\n ),\n });\n return true;\n }\n\n if (route === '/api/pin' && method === 'POST') {\n handlePin(source, request, response);\n return true;\n }\n\n if (route === '/api/requests' && method === 'DELETE') {\n source.clear();\n sendJson(response, 200, { cleared: true });\n return true;\n }\n\n // ORDER MATTERS from here to the end of the `/api/requests/` group: these\n // are prefix matches, not exact ones, and `/api/requests/:id` below would\n // swallow `/api/requests/:id/baseline` if it came first. The chain has no\n // way to say so structurally, so it says so here.\n if (route.startsWith('/api/requests/') && route.endsWith('/baseline') && method === 'GET') {\n const id = decodeURIComponent(route.slice('/api/requests/'.length, -'/baseline'.length));\n const found = source.get(id);\n if (!found) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return true;\n }\n // A store that cannot answer produces no baseline, and the panel shows\n // no card: an absent comparison is an ordinary answer here.\n const samples = source.durations?.({\n method: found.method,\n route: normalizeRoute(found.path),\n excludeId: found.id,\n });\n sendJson(response, 200, {\n baseline: baselineFor(found, samples),\n pressure: samples ? pressureFor(samples) : null,\n });\n return true;\n }\n\n if (route.startsWith('/api/requests/') && method === 'GET') {\n const id = decodeURIComponent(route.slice('/api/requests/'.length));\n const found = source.get(id);\n if (!found) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return true;\n }\n // The row fields travel with the record: the panel's detail type\n // extends its row type, and a payload missing half of it is a contract\n // that silently reads `undefined`.\n sendJson(response, 200, {\n ...toRow(found, (source.pinned?.() ?? []).includes(id)),\n ...ensureTiming(found),\n });\n return true;\n }\n\n if (route === '/api/exceptions' && method === 'GET') {\n sendJson(response, 200, { groups: groupExceptions(source.list(), options.stack) });\n return true;\n }\n\n if (route === '/api/stream' && method === 'GET') {\n streamEvents(source, mutes, request, response, streams);\n return true;\n }\n\n if (route === '/api/explain' && method === 'POST') {\n if (!options.explain) {\n sendJson(response, 403, {\n error:\n 'EXPLAIN from the panel is off. Outside local development it is enabled explicitly: reqray({ explain: true }).',\n });\n return true;\n }\n handleExplain(source, request, response);\n return true;\n }\n\n if (route === '/api/replay' && method === 'POST') {\n if (!options.replay) {\n sendJson(response, 403, {\n error:\n 'replay is off. Outside local development it is enabled only explicitly: reqray({ replay: true }) — a replay in production means a second charge and a second email.',\n });\n return true;\n }\n handleReplay(source, request, response);\n return true;\n }\n\n if (route.startsWith('/api/')) {\n sendJson(response, 404, { error: 'no such panel endpoint' });\n return true;\n }\n\n if (method === 'GET' && init.assetsDir && serveAsset(init.assetsDir, route, response)) {\n return true;\n }\n\n sendJson(response, 404, {\n error: init.assetsDir\n ? 'panel asset not found'\n : 'the panel UI is not installed: add @reqray/dashboard. The API keeps working.',\n });\n return true;\n };\n\n return function handlePanelRequest(request, response): boolean {\n try {\n return serve(request, response);\n } catch (error) {\n // Only a panel request gets this far before anything can throw — a\n // malformed `%` in an id, say — and it must end here: on a bare\n // `node:http` server an exception in the listener takes the process,\n // which is the application's.\n const reason = error instanceof Error ? error.message : String(error);\n if (response.headersSent) response.destroy();\n else sendJson(response, 400, { error: `bad panel request: ${reason}` });\n return true;\n }\n };\n}\n\n/**\n * Changes how long requests are kept.\n *\n * The only setting the panel can write, and it deletes data on the way down,\n * so it is refused unless the application handed the panel a policy and said\n * it may be changed. Values are checked here rather than trusted: the panel\n * is a client like any other.\n */\nfunction handleRetention(\n options: ResolvedOptions,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n const policy = options.retention;\n if (!policy) {\n sendJson(response, 501, {\n error:\n 'this application keeps to fixed limits: pass reqray({ retention: retentionPolicy({ … }) }) to make them changeable.',\n });\n return;\n }\n if (!policy.writable) {\n sendJson(response, 403, {\n error: 'retention is read-only here: the policy was created with writable: false.',\n });\n return;\n }\n\n try {\n const payload = (await readBody(request)) as Partial<RetentionLimits>;\n const patch: Record<string, unknown> = {};\n for (const key of ['days', 'maxBytes', 'maxRequests'] as const) {\n if (key in payload) patch[key] = payload[key];\n }\n if (Object.keys(patch).length === 0) {\n sendJson(response, 400, { error: 'nothing to change: days, maxBytes or maxRequests' });\n return;\n }\n\n const limits = policy.update(patch as Partial<RetentionLimits>);\n // The stores sweep on their own schedule; what is reported back is the\n // policy, not a promise that the disk is already smaller.\n sendJson(response, 200, { retention: retentionOf(options), limits });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `retention unchanged: ${reason}` });\n }\n })();\n}\n\nfunction handleBlame(\n options: ResolvedOptions,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as {\n frames?: Array<{ file?: unknown; line?: unknown }>;\n };\n const frames = Array.isArray(payload.frames) ? payload.frames.slice(0, 30) : [];\n\n const blamed = await Promise.all(\n frames.map(async (frame) => {\n if (typeof frame.file !== 'string' || typeof frame.line !== 'number') return null;\n return blameLine(frame.file, frame.line, options.stack.projectRoot);\n }),\n );\n sendJson(response, 200, { frames: blamed });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `blame failed: ${reason}` });\n }\n })();\n}\n\n/**\n * When a file last changed, epoch ms — what `fixed?` is guessed from.\n *\n * The file's mtime rather than git: honest enough for a guess drawn with a\n * question mark, and free. Unreadable files answer \"nobody knows\".\n */\nfunction fileChangedAt(file: string): number | null {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return null;\n }\n}\n\n/**\n * What is muted, remembered between changes.\n *\n * Muting is presentation, not detection: the record keeps its findings, but a\n * muted pattern must stop flagging the list, the live feed and the routes\n * table alike — one that flashes amber on arrival and goes grey on reload is a\n * haunting.\n *\n * Held rather than rebuilt per call: it changes only when somebody mutes\n * something, and the live feed would otherwise walk the whole state map once\n * per request delivered.\n */\nclass MuteView {\n #muted: Set<string> | null = null;\n\n constructor(private readonly source: PanelSource) {}\n\n /** Pattern ids the reader muted, or an empty set when nothing is. */\n set(): ReadonlySet<string> {\n if (this.#muted) return this.#muted;\n\n const muted = new Set<string>();\n const states = this.source.findingStates?.();\n if (states) {\n for (const [id, state] of states) if (state === 'muted') muted.add(id);\n }\n this.#muted = muted;\n return muted;\n }\n\n /** Called when a state changes; the next read rebuilds. */\n forget(): void {\n this.#muted = null;\n }\n\n /**\n * Rows with muted patterns silenced.\n *\n * Only flagged rows are looked up — they are the rare ones — and a record\n * the store has already dropped keeps the flag it had.\n */\n silence(rows: readonly RequestRow[]): readonly RequestRow[] {\n const muted = this.set();\n if (muted.size === 0) return rows;\n return rows.map((row) => {\n if (row.flag === null) return row;\n const record = this.source.get(row.id);\n if (!record) return row;\n const flag = flagWithMutes(record, muted);\n return flag === row.flag ? row : { ...row, flag };\n });\n }\n}\n\n/**\n * The states a client may set.\n *\n * `fixed` is deliberately absent: it is a computed guess, and a stored one\n * would outlive the change it guessed about. The list is what both the check\n * and the refusal message are built from, so they cannot drift apart.\n */\nconst SETTABLE_STATES: readonly StoredPatternState[] = ['new', 'ack', 'muted'];\n\nfunction isSettable(value: unknown): value is StoredPatternState {\n return (SETTABLE_STATES as readonly unknown[]).includes(value);\n}\n\nfunction handleFindingState(\n source: PanelSource,\n mutes: MuteView,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n if (!source.setFindingState) {\n sendJson(response, 501, { error: 'this store cannot remember finding states' });\n return;\n }\n try {\n const payload = (await readBody(request)) as { id?: unknown; state?: unknown };\n if (typeof payload.id !== 'string' || payload.id.length === 0 || !isSettable(payload.state)) {\n sendJson(response, 400, {\n error: `a pattern id and a state (${SETTABLE_STATES.join(', ')}) are needed`,\n });\n return;\n }\n const state = payload.state;\n source.setFindingState(payload.id, state);\n // The only moment what is muted can change.\n mutes.forget();\n sendJson(response, 200, { ok: true });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `state change failed: ${reason}` });\n }\n })();\n}\n\nfunction handlePin(source: PanelSource, request: IncomingMessage, response: ServerResponse): void {\n void (async () => {\n if (!source.pin) {\n sendJson(response, 501, { error: 'this store cannot pin requests' });\n return;\n }\n try {\n const payload = (await readBody(request)) as { id?: unknown; pinned?: unknown };\n if (typeof payload.id !== 'string') {\n sendJson(response, 400, { error: 'id is required' });\n return;\n }\n const wanted = payload.pinned !== false;\n const ok = source.pin(payload.id, wanted);\n if (!ok && wanted) {\n // Either the record is already gone, or the pin board is full — both\n // are worth saying out loud rather than silently doing nothing.\n sendJson(response, 409, {\n error: 'could not pin: the request is gone, or too many are pinned already',\n });\n return;\n }\n sendJson(response, 200, { id: payload.id, pinned: wanted && ok });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `pin failed: ${reason}` });\n }\n })();\n}\n\nfunction handleExplain(\n source: PanelSource,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as { id?: unknown; spanId?: unknown };\n const record = typeof payload.id === 'string' ? source.get(payload.id) : undefined;\n if (!record) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return;\n }\n const spanId = typeof payload.spanId === 'number' ? payload.spanId : Number.NaN;\n\n sendJson(response, 200, await runExplain(record, spanId));\n } catch (error) {\n if (error instanceof ExplainError) {\n sendJson(response, error.status, { error: error.message });\n return;\n }\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('panel.explain', `EXPLAIN failed: ${reason}`);\n sendJson(response, 500, { error: `EXPLAIN failed: ${reason}` });\n }\n })();\n}\n\nfunction handleReplay(\n source: PanelSource,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as {\n id?: unknown;\n method?: unknown;\n path?: unknown;\n headers?: unknown;\n body?: unknown;\n };\n\n const original = typeof payload.id === 'string' ? source.get(payload.id) : undefined;\n if (!original) {\n sendJson(response, 404, { error: 'original request not found' });\n return;\n }\n\n const input: ReplayInput = {\n method: typeof payload.method === 'string' ? payload.method : original.method,\n path: typeof payload.path === 'string' ? payload.path : original.path,\n headers:\n payload.headers && typeof payload.headers === 'object'\n ? (payload.headers as Record<string, string>)\n : {},\n body: typeof payload.body === 'string' ? payload.body : undefined,\n };\n\n sendJson(response, 200, await runReplay(originOf(request), input, original));\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('panel.replay', `replay failed: ${reason}`);\n sendJson(response, 500, { error: `replay failed: ${reason}` });\n }\n })();\n}\n","/**\n * Occurrences into patterns — the arithmetic behind the findings tab.\n *\n * The grouping happens here, once, for every store: a store hands over one\n * row per occurrence and says when it stopped reading, the same division of\n * labour the history screen uses. Grouping is by detector plus code\n * location, not by request — `GET /api/orders` and `GET /api/orders/flaky`\n * both firing N+1 at the same line are one problem — and falls back to the\n * route when a finding carries no location, because \"somewhere on this\n * endpoint\" is still one somewhere.\n */\n\nimport type {\n Callsite,\n FindingPattern,\n FindingSeverity,\n FindingsResponse,\n PatternExample,\n StoredPatternState,\n} from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { normalizeRoute } from './routes.js';\n\n/**\n * One finding occurrence, as the tab needs it.\n *\n * A dozen fields rather than a record: the requests that carry findings are\n * a small minority, but a window of them is still not something to hold as\n * payloads to look at one finding in each.\n */\nexport interface FindingSample {\n readonly requestId: string;\n readonly startedAt: number;\n readonly method: string;\n readonly route: string;\n readonly status: number;\n readonly durationMs: number;\n readonly detector: string;\n readonly severity: FindingSeverity;\n readonly title: string;\n readonly costMs: number;\n readonly callsite: Callsite | null;\n readonly hint: string;\n}\n\n/** What a store hands back, and whether it read the whole window. */\nexport interface FindingSamples {\n readonly samples: readonly FindingSample[];\n readonly truncated: boolean;\n}\n\n/** The stretch of time a findings reading covers. Absent bounds mean all. */\nexport interface FindingsQuery {\n readonly from?: number | undefined;\n readonly to?: number | undefined;\n}\n\n/**\n * A request's findings, reduced to occurrence rows.\n *\n * For every store that keeps whole records, so the tab does not depend on\n * which store is behind it.\n */\nexport function findingSamplesOf(request: RecordedRequest): FindingSample[] {\n return request.findings.map((finding) => ({\n requestId: request.id,\n startedAt: request.startedAt,\n method: request.method,\n route: normalizeRoute(request.path),\n status: request.status,\n durationMs: request.durationMs,\n detector: finding.detector,\n severity: finding.severity,\n title: finding.title,\n costMs: finding.costMs,\n callsite: finding.callsite,\n hint: finding.hint,\n }));\n}\n\n/**\n * The pattern a finding belongs to.\n *\n * The code location when there is one — the same problem fires from the same\n * line whatever route reached it — and the route otherwise, so locationless\n * findings (a blown budget, a heavy response) still group by where they live.\n */\nexport function patternKey(sample: {\n readonly detector: string;\n readonly callsite: Callsite | null;\n readonly method: string;\n readonly route: string;\n}): string {\n return sample.callsite\n ? `${sample.detector}@${sample.callsite.relative}:${sample.callsite.line}`\n : `${sample.detector}@${sample.method} ${sample.route}`;\n}\n\n/** How many example requests a pattern carries. */\nconst EXAMPLE_LIMIT = 3;\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = { info: 0, warn: 1, critical: 2 };\n\nexport interface PatternsOptions {\n /** `ack`/`muted` per pattern id, as the store remembered them. */\n readonly states?: ReadonlyMap<string, StoredPatternState> | undefined;\n /**\n * When a file last changed, epoch ms, or `null` when nobody knows.\n *\n * Injected rather than read here: the aggregation stays pure, and what\n * \"changed\" means (mtime, a commit) is the caller's business.\n */\n readonly changedAt?: ((file: string) => number | null) | undefined;\n}\n\n/** Groups occurrences into the tab's patterns, costliest first. */\nexport function patternsOf(read: FindingSamples, options: PatternsOptions = {}): FindingsResponse {\n interface Bucket {\n latest: FindingSample;\n occurrences: number;\n recoverableMs: number;\n firstSeen: number;\n lastSeen: number;\n severity: FindingSeverity;\n routes: Map<string, { method: string; route: string; calls: number }>;\n /** Worst occurrence per request — five findings in one request are one way in. */\n examples: Map<string, PatternExample>;\n }\n\n const buckets = new Map<string, Bucket>();\n for (const sample of read.samples) {\n const key = patternKey(sample);\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = {\n latest: sample,\n occurrences: 0,\n recoverableMs: 0,\n firstSeen: sample.startedAt,\n lastSeen: sample.startedAt,\n severity: sample.severity,\n routes: new Map(),\n examples: new Map(),\n };\n buckets.set(key, bucket);\n }\n\n bucket.occurrences++;\n bucket.recoverableMs += sample.costMs;\n if (sample.startedAt < bucket.firstSeen) bucket.firstSeen = sample.startedAt;\n if (sample.startedAt >= bucket.lastSeen) {\n bucket.lastSeen = sample.startedAt;\n // The sentence and the hint follow the freshest occurrence: \"150\n // identical queries\" must not describe last week's count.\n bucket.latest = sample;\n }\n if (SEVERITY_RANK[sample.severity] > SEVERITY_RANK[bucket.severity]) {\n bucket.severity = sample.severity;\n }\n\n const routeKey = `${sample.method} ${sample.route}`;\n const route = bucket.routes.get(routeKey);\n if (route) route.calls++;\n else bucket.routes.set(routeKey, { method: sample.method, route: sample.route, calls: 1 });\n\n const example = bucket.examples.get(sample.requestId);\n if (!example || sample.costMs > example.costMs) {\n bucket.examples.set(sample.requestId, {\n requestId: sample.requestId,\n startedAt: sample.startedAt,\n method: sample.method,\n route: sample.route,\n status: sample.status,\n durationMs: sample.durationMs,\n costMs: sample.costMs,\n });\n }\n }\n\n const patterns: FindingPattern[] = [...buckets.entries()].map(([id, bucket]) => ({\n id,\n detector: bucket.latest.detector,\n severity: bucket.severity,\n title: bucket.latest.title,\n hint: bucket.latest.hint,\n callsite: bucket.latest.callsite,\n occurrences: bucket.occurrences,\n recoverableMs: bucket.recoverableMs,\n routes: [...bucket.routes.values()].sort((a, b) => b.calls - a.calls),\n firstSeen: bucket.firstSeen,\n lastSeen: bucket.lastSeen,\n state: stateOf(id, bucket, options),\n examples: [...bucket.examples.values()]\n .sort((a, b) => b.costMs - a.costMs)\n .slice(0, EXAMPLE_LIMIT),\n }));\n\n patterns.sort((a, b) => b.recoverableMs - a.recoverableMs || b.occurrences - a.occurrences);\n\n return {\n patterns,\n occurrences: read.samples.length,\n recoverableMs: patterns.reduce(\n (sum, pattern) => (pattern.state === 'muted' ? sum : sum + pattern.recoverableMs),\n 0,\n ),\n truncated: read.truncated,\n };\n}\n\n/**\n * What a pattern's state is, muted winning over everything.\n *\n * `fixed` outranks `ack` because it says more: the pattern has been silent\n * since the file it points at changed. It is only ever a guess — hence the\n * question mark a client draws — and only claimed when somebody did change\n * the file after the last occurrence.\n */\nfunction stateOf(\n id: string,\n bucket: { latest: FindingSample; lastSeen: number },\n options: PatternsOptions,\n): FindingPattern['state'] {\n const stored = options.states?.get(id);\n if (stored === 'muted') return 'muted';\n\n const file = bucket.latest.callsite?.file;\n if (file && options.changedAt) {\n const changed = options.changedAt(file);\n if (changed !== null && changed > bucket.lastSeen) return 'fixed';\n }\n\n return stored === 'ack' ? 'ack' : 'new';\n}\n\n/**\n * The row's flag, with muted patterns silenced.\n *\n * Muting is presentation, not detection: the detector keeps running and the\n * findings stay on the record, but a muted pattern must stop shouting from\n * the list. The flag falls back to the costliest finding that is not muted,\n * and to nothing when they all are.\n */\nexport function flagWithMutes(request: RecordedRequest, muted: ReadonlySet<string>): string | null {\n if (muted.size === 0 || request.findings.length === 0) {\n return [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null;\n }\n const audible = request.findings.filter(\n (finding) =>\n !muted.has(\n patternKey({\n detector: finding.detector,\n callsite: finding.callsite,\n method: request.method,\n route: normalizeRoute(request.path),\n }),\n ),\n );\n return [...audible].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null;\n}\n","/**\n * Per-route aggregates.\n *\n * The request list answers \"what happened just now\"; this answers \"which\n * endpoint is expensive\". It is computed over whatever the store still holds,\n * which is a dev session rather than a statistically sound window — the\n * numbers are for spotting the obvious offender, not for a capacity plan, and\n * the screen says as much by showing the sample count next to them.\n */\n\nimport type { Callsite, RouteFinding, RouteStats, RoutesReport } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { patternKey } from './findings.js';\n\nexport type { RouteFinding, RouteStats, RoutesReport };\n\n/**\n * How many columns a route's sparkline is cut into.\n *\n * Ten: enough to see a shape, few enough that one column of a short window\n * still holds calls rather than drawing a comb of ones and zeroes.\n */\nexport const TREND_BUCKETS = 10;\n\n/**\n * Collapses the variable parts of a path.\n *\n * Per segment rather than by regex over the whole path, so that a route with\n * several ids normalizes cleanly. A hex token must contain a digit to count\n * as an id: otherwise ordinary words like `feed` or `cafe` would normalize\n * away and two unrelated routes would merge into one row.\n */\nexport function normalizeRoute(path: string): string {\n return path\n .split('?')[0]\n ?.split('/')\n .map((segment) => {\n if (/^\\d+$/.test(segment)) return ':id';\n if (/^\\d{4}-\\d{2}/.test(segment)) return ':date';\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment)) {\n return ':id';\n }\n if (/^[0-9a-f]{4,}$/i.test(segment) && /\\d/.test(segment)) return ':id';\n return segment;\n })\n .join('/') as string;\n}\n\n/**\n * A percentile with linear interpolation between neighbouring samples.\n *\n * Index-based selection would collapse p95 and p99 onto the same sample at\n * the sample counts a dev session produces, and two columns showing the same\n * number are worse than one.\n *\n * @param sorted values in ascending order.\n */\nexport function percentile(sorted: readonly number[], p: number): number {\n if (sorted.length === 0) return 0;\n if (sorted.length === 1) return sorted[0] as number;\n\n const position = p * (sorted.length - 1);\n const lower = Math.floor(position);\n const upper = Math.ceil(position);\n const low = sorted[lower] as number;\n if (lower === upper) return low;\n const high = sorted[upper] as number;\n return low + (high - low) * (position - lower);\n}\n\n/** One detector's tally on one route, while it is being accumulated. */\ninterface FoundHere {\n calls: number;\n recoverableMs: number;\n /** When the occurrence that supplied the words happened. */\n at: number;\n title: string;\n hint: string;\n callsite: Callsite | null;\n}\n\ninterface Accumulator {\n method: string;\n route: string;\n durations: number[];\n errors: number;\n sql: number;\n totalMs: number;\n bytes: number;\n /** Calls that reported a size — the divisor for the average. */\n weighed: number;\n /** Per detector, accumulated across the route's calls. */\n findings: Map<string, FoundHere>;\n /** When each call started — bucketed into the trend once the window is known. */\n starts: number[];\n}\n\n/**\n * Aggregates the retained requests by normalized route.\n *\n * @param muted pattern ids the reader silenced, as {@link patternKey} spells\n * them. Their findings stay on the records and out of this table: the column\n * is a shout, and a muted pattern has been told to stop shouting.\n */\nexport function routeStats(\n requests: readonly RecordedRequest[],\n muted: ReadonlySet<string> = new Set(),\n): RoutesReport {\n if (requests.length === 0) {\n return { routes: [], samples: 0, windowMs: 0, from: 0, to: 0 };\n }\n\n const byRoute = new Map<string, Accumulator>();\n let overallMs = 0;\n let oldest = Number.POSITIVE_INFINITY;\n let newest = Number.NEGATIVE_INFINITY;\n\n for (const request of requests) {\n const route = normalizeRoute(request.path);\n const key = `${request.method} ${route}`;\n let bucket = byRoute.get(key);\n if (!bucket) {\n bucket = {\n method: request.method,\n route,\n durations: [],\n errors: 0,\n sql: 0,\n totalMs: 0,\n bytes: 0,\n weighed: 0,\n findings: new Map(),\n starts: [],\n };\n byRoute.set(key, bucket);\n }\n\n bucket.durations.push(request.durationMs);\n bucket.starts.push(request.startedAt);\n\n for (const finding of request.findings) {\n if (\n muted.has(\n patternKey({\n detector: finding.detector,\n callsite: finding.callsite,\n method: request.method,\n route,\n }),\n )\n ) {\n continue;\n }\n const seen = bucket.findings.get(finding.detector);\n if (seen) {\n seen.calls++;\n seen.recoverableMs += finding.costMs;\n // The freshest occurrence speaks: \"150 identical queries\" must not be\n // last week's count.\n if (request.startedAt >= seen.at) {\n seen.at = request.startedAt;\n seen.title = finding.title;\n seen.hint = finding.hint;\n seen.callsite = finding.callsite;\n }\n continue;\n }\n bucket.findings.set(finding.detector, {\n calls: 1,\n recoverableMs: finding.costMs,\n at: request.startedAt,\n title: finding.title,\n hint: finding.hint,\n callsite: finding.callsite,\n });\n }\n bucket.totalMs += request.durationMs;\n const bytesOut = request.weight?.bytesOut ?? null;\n if (bytesOut !== null) {\n bucket.bytes += bytesOut;\n bucket.weighed++;\n }\n if (request.error !== null || request.status >= 500) bucket.errors++;\n for (const span of request.spans) {\n if (span.kind === 'db') bucket.sql++;\n }\n\n overallMs += request.durationMs;\n if (request.startedAt < oldest) oldest = request.startedAt;\n if (request.startedAt > newest) newest = request.startedAt;\n }\n\n // A single request spans no time; one second keeps rps finite and honest.\n const windowMs = Math.max(1_000, newest - oldest);\n\n const routes = [...byRoute.values()].map((bucket): RouteStats => {\n const sorted = [...bucket.durations].sort((a, b) => a - b);\n const calls = sorted.length;\n\n // The shape of the traffic, over the same window every other row uses —\n // so two sparklines on this screen are comparable by eye.\n const trend = new Array<number>(TREND_BUCKETS).fill(0);\n const span = Math.max(1, newest - oldest);\n for (const at of bucket.starts) {\n const index = Math.min(TREND_BUCKETS - 1, Math.floor(((at - oldest) / span) * TREND_BUCKETS));\n trend[index] = (trend[index] ?? 0) + 1;\n }\n\n return {\n method: bucket.method,\n route: bucket.route,\n calls,\n rps: calls / (windowMs / 1_000),\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n errorRate: (bucket.errors / calls) * 100,\n sqlAvg: bucket.sql / calls,\n bytesAvg: bucket.weighed > 0 ? bucket.bytes / bucket.weighed : null,\n timeShare: overallMs > 0 ? (bucket.totalMs / overallMs) * 100 : 0,\n findings: [...bucket.findings.entries()]\n .map(([detector, found]) => ({\n detector,\n calls: found.calls,\n recoverableMs: found.recoverableMs,\n title: found.title,\n hint: found.hint,\n callsite: found.callsite,\n }))\n .sort((a, b) => b.recoverableMs - a.recoverableMs || b.calls - a.calls),\n trend,\n };\n });\n\n // Most expensive first — the order the screen opens in.\n routes.sort((a, b) => b.timeShare - a.timeShare);\n return { routes, samples: requests.length, windowMs, from: oldest, to: newest };\n}\n","/**\n * How one call compares against the route's own history.\n *\n * A duration on its own says nothing. 400 ms is alarming for a cache read and\n * excellent for a report, so the only comparison worth drawing is against\n * other calls of the same route — and only when there are enough of them for\n * the comparison to be worth more than the silence it replaces.\n */\n\nimport type { DurationBaseline, RecordedRequest } from '../types.js';\nimport type { DurationSample } from './api.js';\nimport { normalizeRoute, percentile } from './routes.js';\n\n/**\n * Below this a percentile is one call wearing a statistic's name.\n *\n * Twenty is where the ninety-fifth percentile stops being the single slowest\n * sample and starts interpolating between two — the point at which \"slower\n * than 95% of calls\" is a claim about a distribution rather than about the\n * one unlucky call that happens to top the list.\n */\nconst MIN_FOR_P95 = 20;\n\n/** Below this the request would be measuring itself. */\nconst MIN_SAMPLES = 2;\n\n/** What the store is asked for when a request is judged against its route. */\nexport interface BaselineQuery {\n readonly method: string;\n /** The normalized route, as `normalizeRoute` produces it. */\n readonly route: string;\n /**\n * The request being judged — it is never part of its own baseline.\n *\n * Left out when the caller wants the route's whole history: the charts do,\n * and a chart with one call missing from it would be a different kind of\n * lie from the one this field prevents.\n */\n readonly excludeId?: string;\n /**\n * The stretch to read, epoch ms.\n *\n * Left out for the whole history. The charts pass the same window the\n * routes table was computed over: a table describing thirteen minutes above\n * a chart describing six hours is two answers to one question.\n */\n readonly from?: number;\n readonly to?: number;\n}\n\n/**\n * The verdict, or `null` when there is nothing honest to say.\n *\n * @param samples the route's other calls, as the store hands them over.\n * `undefined` is a store that cannot answer at all, and produces no verdict\n * rather than one drawn from whatever page happened to be loaded.\n */\nexport function baselineFor(\n request: RecordedRequest,\n samples: readonly DurationSample[] | undefined,\n): DurationBaseline | null {\n if (!samples || samples.length < MIN_SAMPLES) return null;\n\n const sorted = samples.map((sample) => sample.durationMs).sort((a, b) => a - b);\n const sum = sorted.reduce((total, value) => total + value, 0);\n const avgMs = sum / sorted.length;\n\n const times = samples.map((sample) => sample.startedAt);\n const windowMs = Math.max(...times) - Math.min(...times);\n\n const p95Ms = sorted.length >= MIN_FOR_P95 ? percentile(sorted, 0.95) : null;\n const p50Ms = percentile(sorted, 0.5);\n const p99Ms = sorted.length >= MIN_FOR_P95 ? percentile(sorted, 0.99) : null;\n const maxMs = sorted[sorted.length - 1] ?? 0;\n\n // Without a trustworthy p95 the strongest claim available is \"at or under\n // the mean\", which roughly half of all calls are. Calling anything slow off\n // five samples is how a tool starts crying wolf.\n const verdict =\n p95Ms !== null && request.durationMs >= p95Ms\n ? 'slower'\n : request.durationMs <= avgMs\n ? 'faster'\n : 'typical';\n\n return {\n method: request.method,\n route: normalizeRoute(request.path),\n samples: sorted.length,\n windowMs,\n avgMs,\n p95Ms,\n p50Ms,\n p99Ms,\n maxMs,\n verdict,\n };\n}\n","/**\n * Grouping of exceptions by normalised stack.\n *\n * The same error raised three hundred times is one row in the panel with a\n * repeat count, not three hundred rows. Normalisation drops everything that\n * varies between calls and keeps the shape of the stack.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { ExceptionFrame, ExceptionGroup } from '@reqray/protocol';\nimport { isProjectFrame, parseStackFrame } from '../callsite.js';\nimport type { ResolvedStackOptions } from '../config.js';\nimport type { RecordedRequest, SpanError } from '../types.js';\n\nexport type { ExceptionFrame, ExceptionGroup };\n\n/** Buckets in the sparkline — as many as there are bars in the mockup. */\nconst BUCKET_COUNT = 12;\n\n/** Frames taken into the fingerprint: deeper than this stacks stop differing. */\nconst SIGNIFICANT_FRAMES = 8;\n\nfunction framesOf(error: SpanError, options: ResolvedStackOptions): ExceptionFrame[] {\n if (!error.stack) return [];\n\n const frames: ExceptionFrame[] = [];\n for (const line of error.stack.split('\\n')) {\n if (!line.trim().startsWith('at ')) continue;\n const parsed = parseStackFrame(line);\n frames.push({\n raw: line.trim(),\n file: parsed?.file ?? null,\n line: parsed?.line ?? null,\n project: parsed ? isProjectFrame(parsed.file, options) : false,\n });\n }\n return frames;\n}\n\n/**\n * Stack fingerprint.\n *\n * It takes the exception type and the positions of the first frames — without\n * columns and without the message: the message usually carries varying values\n * (`id 8812`), which would split identical errors into separate groups.\n */\nfunction fingerprintStack(error: SpanError, frames: readonly ExceptionFrame[]): string {\n const parts = [error.name];\n for (const frame of frames.slice(0, SIGNIFICANT_FRAMES)) {\n parts.push(frame.file ? `${frame.file}:${frame.line ?? 0}` : frame.raw);\n }\n // There may be no stack at all — then the message is the only thing that\n // tells errors apart.\n if (frames.length === 0) parts.push(error.message);\n\n return createHash('sha1').update(parts.join('\\n')).digest('hex').slice(0, 12);\n}\n\ninterface Accumulator {\n readonly id: string;\n readonly type: string;\n message: string;\n readonly frames: ExceptionFrame[];\n readonly origin: string | null;\n where: string | null;\n count: number;\n lastSeenAt: number;\n readonly requestIds: string[];\n readonly times: number[];\n test: string | null;\n}\n\nfunction originOf(frames: readonly ExceptionFrame[], options: ResolvedStackOptions): string | null {\n const projectFrame = frames.find((frame) => frame.project && frame.file);\n if (!projectFrame?.file) return null;\n const relative = projectFrame.file.startsWith(options.projectRoot)\n ? projectFrame.file.slice(options.projectRoot.length + 1)\n : projectFrame.file;\n return `${relative}:${projectFrame.line ?? 0}`;\n}\n\nfunction bucketize(times: readonly number[], now: number, windowMs: number): number[] {\n const buckets = new Array<number>(BUCKET_COUNT).fill(0);\n if (windowMs <= 0) return buckets;\n\n const from = now - windowMs;\n for (const time of times) {\n const position = Math.floor(((time - from) / windowMs) * BUCKET_COUNT);\n const index = Math.min(BUCKET_COUNT - 1, Math.max(0, position));\n buckets[index] = (buckets[index] ?? 0) + 1;\n }\n return buckets;\n}\n\n/**\n * Builds exception groups from recorded requests.\n *\n * Requests are expected newest first, the order the store returns them in.\n * Groups come back by descending occurrence count.\n */\nexport function groupExceptions(\n requests: readonly RecordedRequest[],\n options: ResolvedStackOptions,\n now = Date.now(),\n): ExceptionGroup[] {\n const groups = new Map<string, Accumulator>();\n let oldest = now;\n\n for (const request of requests) {\n if (request.startedAt < oldest) oldest = request.startedAt;\n\n const error = request.error;\n if (!error) continue;\n\n const frames = framesOf(error, options);\n const id = fingerprintStack(error, frames);\n\n let group = groups.get(id);\n if (!group) {\n group = {\n id,\n type: error.name,\n message: error.message,\n frames,\n origin: originOf(frames, options),\n where: `${request.method} ${request.path}`,\n count: 0,\n lastSeenAt: request.startedAt,\n requestIds: [],\n times: [],\n test: null,\n };\n groups.set(id, group);\n }\n\n group.count++;\n group.times.push(request.startedAt);\n if (request.startedAt > group.lastSeenAt) {\n group.lastSeenAt = request.startedAt;\n group.message = error.message;\n group.where = `${request.method} ${request.path}`;\n }\n // Records arrive newest first, so the first test name seen is the latest.\n if (group.test === null && request.test !== null) group.test = request.test;\n // The request list is capped: the panel needs the latest ones, not all.\n if (group.requestIds.length < 50) group.requestIds.push(request.id);\n }\n\n const windowMs = Math.max(1, now - oldest);\n\n return [...groups.values()]\n .map(\n (group): ExceptionGroup => ({\n id: group.id,\n type: group.type,\n message: group.message,\n origin: group.origin,\n where: group.where,\n count: group.count,\n lastSeenAt: group.lastSeenAt,\n requestIds: group.requestIds,\n frames: group.frames,\n buckets: bucketize(group.times, now, windowMs),\n test: group.test,\n }),\n )\n .sort((a, b) => b.count - a.count || b.lastSeenAt - a.lastSeenAt);\n}\n","/**\n * EXPLAIN of a recorded query, straight from the panel.\n *\n * Safety comes from three rules that are not options:\n * - the SQL is taken from the record — the panel client sends only ids and\n * can never inject a statement;\n * - `ANALYZE` is never used: it executes the query, and an executed\n * INSERT is a write. Plain EXPLAIN plans without running anything;\n * - the query goes to the same pool that ran the original (see\n * `explain-targets.ts`), so \"which database\" is never a guess.\n *\n * Parameterized queries have no recorded values (values are deliberately not\n * collected), so they are planned with `GENERIC_PLAN` — PostgreSQL 16+.\n */\n\nimport type { ExplainNote, ExplainPlanNode, ExplainResult } from '@reqray/protocol';\nimport { explainTarget } from '../explain-targets.js';\nimport type { RecordedRequest } from '../types.js';\n\nexport type { ExplainNote, ExplainPlanNode, ExplainResult };\n\nconst PLACEHOLDER = /\\$\\d+/;\nconst EXPLAIN_TIMEOUT_MS = 5_000;\n\ninterface PlanJson {\n readonly [key: string]: unknown;\n readonly Plans?: readonly PlanJson[];\n}\n\nfunction numberOf(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\nfunction labelOf(node: PlanJson): string {\n const type = typeof node['Node Type'] === 'string' ? (node['Node Type'] as string) : 'node';\n const relation = node['Relation Name'];\n const index = node['Index Name'];\n if (typeof index === 'string' && typeof relation === 'string') {\n return `${type} using ${index} on ${relation}`;\n }\n if (typeof relation === 'string') return `${type} on ${relation}`;\n return type;\n}\n\n/** Flattens the plan tree and derives the warnings. */\nexport function analyzePlan(plan: PlanJson): {\n nodes: ExplainPlanNode[];\n notes: ExplainNote[];\n} {\n const nodes: ExplainPlanNode[] = [];\n const notes: ExplainNote[] = [];\n\n const walk = (node: PlanJson, depth: number): void => {\n nodes.push({\n depth,\n label: labelOf(node),\n rows: numberOf(node['Plan Rows']),\n cost: numberOf(node['Total Cost']),\n });\n\n if (node['Node Type'] === 'Seq Scan' && typeof node['Filter'] === 'string') {\n const relation = typeof node['Relation Name'] === 'string' ? node['Relation Name'] : '?';\n notes.push({\n severity: 'warn',\n message:\n `Seq Scan over \"${relation}\" with filter ${node['Filter']} — ` +\n 'the whole table is read for a fraction of its rows. An index on the filtered column may help.',\n });\n }\n if (node['Node Type'] === 'Sort' && Array.isArray(node['Sort Key'])) {\n notes.push({\n severity: 'info',\n message:\n `Sorting by ${(node['Sort Key'] as unknown[]).join(', ')} happens in memory — ` +\n 'an index in the sort order would remove it entirely.',\n });\n }\n\n for (const child of node.Plans ?? []) walk(child, depth + 1);\n };\n\n walk(node0(plan), 0);\n return { nodes, notes };\n\n function node0(root: PlanJson): PlanJson {\n // `EXPLAIN (FORMAT JSON)` wraps the tree as [{ \"Plan\": {...} }].\n const inner = (root as { Plan?: PlanJson }).Plan;\n return inner ?? root;\n }\n}\n\n/**\n * Whether anything follows the statement's own terminator.\n *\n * A semicolon inside a literal or a comment is not a terminator —\n * `WHERE note = 'a;b'` is one perfectly ordinary statement, and refusing to\n * plan it would be this check crying wolf. So quotes and comments are skipped\n * rather than searched: single quotes with their doubled-quote escape, dollar\n * quoting with its tag, double-quoted identifiers, and both comment forms.\n */\nfunction hasSecondStatement(sql: string): boolean {\n for (let i = 0; i < sql.length; i++) {\n const ch = sql[i];\n\n if (ch === \"'\" || ch === '\"') {\n const quote = ch;\n i++;\n while (i < sql.length) {\n if (sql[i] === quote) {\n // A doubled quote is an escaped one and the literal continues.\n if (sql[i + 1] === quote) i++;\n else break;\n }\n i++;\n }\n continue;\n }\n\n if (ch === '$') {\n const tag = /^\\$[A-Za-z_]\\w*\\$|^\\$\\$/.exec(sql.slice(i));\n if (tag) {\n const close = sql.indexOf(tag[0], i + tag[0].length);\n // An unterminated dollar quote swallows the rest: nothing follows it.\n if (close === -1) return false;\n i = close + tag[0].length - 1;\n continue;\n }\n }\n\n if (ch === '-' && sql[i + 1] === '-') {\n const end = sql.indexOf('\\n', i);\n if (end === -1) return false;\n i = end;\n continue;\n }\n\n if (ch === '/' && sql[i + 1] === '*') {\n const end = sql.indexOf('*/', i + 2);\n if (end === -1) return false;\n i = end + 1;\n continue;\n }\n\n if (ch === ';') return sql.slice(i + 1).trim() !== '';\n }\n return false;\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error(`EXPLAIN did not answer within ${ms} ms`)), ms);\n timer.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n },\n );\n });\n}\n\n/** A user-facing failure: the message is shown in the panel as-is. */\nexport class ExplainError extends Error {\n override readonly name = 'ExplainError';\n constructor(\n message: string,\n readonly status = 400,\n ) {\n super(message);\n }\n}\n\n/**\n * Runs EXPLAIN for one recorded span.\n *\n * @throws ExplainError with a message meant for the panel.\n */\nexport async function runExplain(record: RecordedRequest, spanId: number): Promise<ExplainResult> {\n const span = record.spans.find((candidate) => candidate.id === spanId);\n if (span?.kind !== 'db') {\n throw new ExplainError('span not found, or it is not a SQL query', 404);\n }\n if (span.source !== 'pg') {\n throw new ExplainError(\n `EXPLAIN is supported for queries made through pg; this one went through ${span.source ?? 'an unknown driver'}`,\n );\n }\n if (span.clientId === null) {\n throw new ExplainError(\n 'the executor of this query was not recorded — EXPLAIN has nowhere to go',\n );\n }\n\n const target = explainTarget(span.clientId);\n if (!target) {\n throw new ExplainError(\n 'the pool that ran this query lives inside the application process and is not reachable here — ' +\n 'EXPLAIN works in the panel mounted in the application',\n );\n }\n\n // `EXPLAIN <sql>` is concatenation: a second statement after a semicolon\n // would be planned and then *run*. Reaching this needs an injection the\n // application already has, but a read-only endpoint must not be what turns\n // that into a write.\n if (hasSecondStatement(span.sql)) {\n throw new ExplainError(\n 'this record holds more than one statement, and EXPLAIN plans one — nothing was run',\n );\n }\n\n const parameterized = PLACEHOLDER.test(span.sql);\n const statement = parameterized\n ? `EXPLAIN (GENERIC_PLAN, FORMAT JSON) ${span.sql}`\n : `EXPLAIN (FORMAT JSON) ${span.sql}`;\n\n let rows: unknown;\n try {\n const result = (await withTimeout(\n Promise.resolve(target.query(statement)),\n EXPLAIN_TIMEOUT_MS,\n )) as { rows?: unknown };\n rows = result?.rows;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n if (parameterized && /GENERIC_PLAN|generic_plan|syntax error/i.test(reason)) {\n throw new ExplainError(\n `EXPLAIN of a parameterized query needs PostgreSQL 16+ (GENERIC_PLAN). The database said: ${reason}`,\n );\n }\n throw new ExplainError(`the database rejected EXPLAIN: ${reason}`);\n }\n\n const first = Array.isArray(rows) ? (rows[0] as Record<string, unknown> | undefined) : undefined;\n const planColumn = first?.['QUERY PLAN'];\n const plan = Array.isArray(planColumn) ? planColumn[0] : planColumn;\n if (!plan || typeof plan !== 'object') {\n throw new ExplainError('the database returned the plan in an unexpected shape');\n }\n\n const { nodes, notes } = analyzePlan(plan as PlanJson);\n return { sql: span.sql, nodes, notes, plan };\n}\n","/**\n * Exports: taking a session out of the panel.\n *\n * HAR and cURL are built here rather than in the browser because the panel\n * only ever receives list rows — bodies and headers live in the records, and\n * an export that quietly dropped them would be worse than no export.\n *\n * Both formats are for handing a request to something else: a HAR to a\n * browser's network panel or a colleague's viewer, a curl script to a\n * terminal. Neither is a backup format, and neither promises to round-trip.\n */\n\nimport type { RecordedRequest } from '../types.js';\n\n/** Reqray's own additions to a HAR entry, under the extension prefix HAR reserves. */\ninterface ReqrayHarExtension {\n readonly sqlQueries: number;\n readonly nPlusOne: boolean;\n readonly test: string | null;\n}\n\nfunction headerList(headers: Readonly<Record<string, string>>): Array<{\n name: string;\n value: string;\n}> {\n return Object.entries(headers).map(([name, value]) => ({ name, value }));\n}\n\n/** HAR 1.2. Times are milliseconds, as the format requires. */\nexport function toHar(\n requests: readonly RecordedRequest[],\n now = new Date(0),\n note: string | null = null,\n): Record<string, unknown> {\n return {\n log: {\n version: '1.2',\n creator: { name: 'reqray', version: '0.1' },\n pages: [],\n entries: requests.map((request) => {\n const extension: ReqrayHarExtension = {\n sqlQueries: request.spans.filter((span) => span.kind === 'db').length,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n test: request.test,\n };\n\n return {\n startedDateTime: new Date(request.startedAt).toISOString(),\n time: request.durationMs,\n request: {\n method: request.method,\n url: `${request.path}${request.query ? `?${request.query}` : ''}`,\n httpVersion: 'HTTP/1.1',\n headers: headerList(request.requestHeaders),\n queryString: [],\n cookies: [],\n headersSize: -1,\n bodySize: request.requestBody?.text.length ?? 0,\n ...(request.requestBody\n ? {\n postData: {\n mimeType: request.requestHeaders['content-type'] ?? 'application/json',\n text: request.requestBody.text,\n },\n }\n : {}),\n },\n response: {\n status: request.status,\n statusText: '',\n httpVersion: 'HTTP/1.1',\n headers: headerList(request.responseHeaders),\n cookies: [],\n content: {\n size: request.responseBody?.text.length ?? 0,\n mimeType: request.responseHeaders['content-type'] ?? 'application/json',\n ...(request.responseBody ? { text: request.responseBody.text } : {}),\n },\n redirectURL: '',\n headersSize: -1,\n bodySize: request.responseBody?.text.length ?? 0,\n },\n cache: {},\n // Everything Reqray knows lands in `wait`: the breakdown it has is by\n // span, not by the connection phases HAR describes.\n timings: { send: 0, wait: request.durationMs, receive: 0 },\n _reqray: extension,\n };\n }),\n // Kept out of the entries so a diff of two exports stays readable.\n _exportedAt: now.toISOString(),\n // HAR's own field for this, so a viewer that knows nothing of Reqray\n // still shows it. An export that was cut has to say so: it is evidence,\n // and evidence presented as complete is worse than none.\n ...(note ? { comment: note } : {}),\n },\n };\n}\n\n/** Escapes a value for single-quoted shell. */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * A runnable `.sh`: one curl per request.\n *\n * Masked headers and bodies are exported as they were stored — with the\n * masking. A script that leaked the authorization header of every recorded\n * request would undo the one guarantee the buffer makes.\n */\nexport function toCurlScript(\n requests: readonly RecordedRequest[],\n origin: string,\n note: string | null = null,\n): string {\n const lines = [\n '#!/bin/sh',\n '# Exported from reqray. Sensitive headers and fields are masked, so a',\n '# request that needed them will not authenticate as it did.',\n // At the top rather than the bottom: a script is read from the first line,\n // and \"this is not all of them\" belongs where reading starts.\n ...(note ? [`# ${note}`] : []),\n '',\n ];\n\n for (const request of requests) {\n const url = `${origin}${request.path}${request.query ? `?${request.query}` : ''}`;\n const parts = [`curl -i -X ${request.method} ${shellQuote(url)}`];\n for (const [name, value] of Object.entries(request.requestHeaders)) {\n // Hop-by-hop and length headers are curl's business, not the script's.\n if (name === 'host' || name === 'content-length' || name === 'connection') continue;\n parts.push(` -H ${shellQuote(`${name}: ${value}`)}`);\n }\n if (request.requestBody) parts.push(` --data ${shellQuote(request.requestBody.text)}`);\n\n lines.push(\n // One line, whatever the name holds: a record can come off the wire, and\n // a line break here would end the comment and start a command.\n `# ${request.status} · ${Math.round(request.durationMs)} ms${request.test ? ` · ${request.test.replace(/\\p{Cc}/gu, ' ')}` : ''}`,\n parts.join(' \\\\\\n'),\n '',\n );\n }\n\n return lines.join('\\n');\n}\n","/**\n * Filtering and summary over the request list.\n *\n * Pure functions: the panel runs them on every keystroke in the search box,\n * and tests run them without standing up a server.\n */\n\nimport type { RequestSummary } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { normalizeRoute } from './routes.js';\n\nexport type { RequestSummary } from '@reqray/protocol';\n\n/** The panel's filter set. Empty fields exclude nothing. */\nexport interface RequestFilter {\n /** Substring of the path, method or status. Case-insensitive. */\n readonly query?: string | undefined;\n /** Methods: `GET`, `POST`. An empty list means all. */\n readonly methods?: readonly string[] | undefined;\n /** Status classes: 2, 3, 4, 5. An empty list means all. */\n readonly statusClasses?: readonly number[] | undefined;\n /** Only requests no faster than the given duration. */\n readonly minDurationMs?: number | undefined;\n /** Not before this moment, epoch ms. Inclusive. */\n readonly from?: number | undefined;\n /** Not after this moment, epoch ms. Inclusive. */\n readonly to?: number | undefined;\n /** Only requests where the detectors found something. */\n readonly onlyFindings?: boolean | undefined;\n /** Only requests with an N+1 — a narrower question than \"any finding\". */\n readonly onlyNPlusOne?: boolean | undefined;\n /** Only requests a test issued. */\n readonly onlyTests?: boolean | undefined;\n /**\n * Only requests that failed.\n *\n * Wider than the 5xx class: a handler that threw and still answered 200 is\n * a failure, and it is the one worth finding.\n */\n readonly onlyErrors?: boolean | undefined;\n /**\n * One endpoint, as the Routes screen names it: the normalized path and the\n * method that go with it.\n */\n readonly route?: { readonly method: string; readonly route: string } | undefined;\n /** Substring of the path alone — narrower than `query`, which matches four fields. */\n readonly path?: string | undefined;\n /** Exactly this status code — `404`, not the whole 4xx class. */\n readonly status?: number | undefined;\n /** At least this many SQL queries. */\n readonly minSql?: number | undefined;\n /**\n * Rows the list flags with one of these detectors.\n *\n * The *flag* — the costliest finding — not \"any finding of this kind\":\n * both stores can answer that question identically (SQLite keeps the flag\n * as a column), and it is the badge the reader is pointing at anyway.\n */\n readonly flagged?: readonly string[] | undefined;\n /** Requests issued by a test whose name contains this. Case-insensitive. */\n readonly test?: string | undefined;\n}\n\nfunction matchesQuery(request: RecordedRequest, needle: string): boolean {\n if (request.method.toLowerCase().includes(needle)) return true;\n if (request.path.toLowerCase().includes(needle)) return true;\n if (String(request.status).includes(needle)) return true;\n return request.query ? request.query.toLowerCase().includes(needle) : false;\n}\n\n/** Selects requests matching the filter, keeping the original order (newest first). */\nexport function filterRequests(\n requests: readonly RecordedRequest[],\n filter: RequestFilter = {},\n): RecordedRequest[] {\n const needle = filter.query?.trim().toLowerCase();\n const methods = filter.methods?.length\n ? new Set(filter.methods.map((m) => m.toUpperCase()))\n : null;\n const classes = filter.statusClasses?.length ? new Set(filter.statusClasses) : null;\n\n return requests.filter((request) => {\n if (filter.from !== undefined && request.startedAt < filter.from) return false;\n if (filter.to !== undefined && request.startedAt > filter.to) return false;\n if (needle && !matchesQuery(request, needle)) return false;\n if (methods && !methods.has(request.method.toUpperCase())) return false;\n if (classes && !classes.has(Math.floor(request.status / 100))) return false;\n if (filter.minDurationMs !== undefined && request.durationMs < filter.minDurationMs)\n return false;\n if (filter.onlyFindings && request.findings.length === 0) return false;\n if (filter.onlyNPlusOne && !request.findings.some((f) => f.detector === 'n_plus_one'))\n return false;\n if (filter.onlyTests && request.test === null) return false;\n if (filter.path && !request.path.toLowerCase().includes(filter.path.toLowerCase())) {\n return false;\n }\n if (filter.status !== undefined && request.status !== filter.status) return false;\n if (filter.minSql !== undefined) {\n let sql = 0;\n for (const span of request.spans) if (span.kind === 'db') sql++;\n if (sql < filter.minSql) return false;\n }\n if (filter.flagged?.length) {\n // The same rule the list flags a row by: the costliest finding names it.\n const flag = [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector;\n if (!flag || !filter.flagged.includes(flag)) return false;\n }\n if (filter.test !== undefined) {\n if (request.test === null || !request.test.toLowerCase().includes(filter.test.toLowerCase()))\n return false;\n }\n if (filter.onlyErrors && request.error === null && request.status < 500) return false;\n if (filter.route) {\n if (request.method.toUpperCase() !== filter.route.method.toUpperCase()) return false;\n if (normalizeRoute(request.path) !== filter.route.route) return false;\n }\n return true;\n });\n}\n\n/**\n * Summary over the buffer.\n *\n * `slowMs` is the \"slow\" threshold for the status bar, 500 ms by default, as\n * in the panel mockup.\n */\nexport function summarize(\n all: readonly RecordedRequest[],\n shown: readonly RecordedRequest[],\n slowMs = 500,\n): RequestSummary {\n let slow = 0;\n let errors = 0;\n let withFindings = 0;\n\n for (const request of all) {\n if (request.durationMs >= slowMs) slow++;\n if (request.status >= 500 || request.error) errors++;\n if (request.findings.length > 0) withFindings++;\n }\n\n return { shown: shown.length, total: all.length, slow, errors, withFindings };\n}\n","/**\n * The shape of the traffic over time, for the strip above the list.\n *\n * The panel used to draw this from the rows it had loaded, which was fine\n * while a store held five hundred requests and everything was on screen. With\n * a history behind it, \"the rows I have\" is the last page — a few minutes —\n * and a strip that only spans a few minutes cannot be dragged back to\n * yesterday. So the store answers for its whole range instead.\n *\n * Three numbers per request go into it — when, how long, and whether it\n * failed — and the bucketing happens here, once, for every store. Two\n * implementations of \"which bucket does this fall into\" would drift, and the\n * drift would be a strip that disagrees with the list under it.\n */\n\n/** What the timeline needs to know about one request. */\nexport interface TimePoint {\n readonly startedAt: number;\n readonly durationMs: number;\n readonly hasError: boolean;\n}\n\nimport type { TimelineBucket, TimelineReport } from '@reqray/protocol';\n\nexport type { TimelineBucket, TimelineReport };\n\n/** How many columns the strip is drawn with, unless asked otherwise. */\nexport const TIMELINE_BUCKETS = 64;\n/** Above this, a request is drawn as slow — the panel's own threshold. */\nconst SLOW_MS = 500;\n\n/**\n * Which column a moment falls into.\n *\n * Shared with the per-route charts on purpose: two implementations of \"which\n * bucket is this\" drift, and the drift is a strip that disagrees with the\n * chart under it about when something happened. Everything inside a single\n * millisecond lands in the first column rather than dividing by a zero span.\n */\nexport function bucketIndex(at: number, from: number, to: number, count: number): number {\n const span = to - from;\n const fraction = span > 0 ? (at - from) / span : 0;\n return Math.max(0, Math.min(count - 1, Math.floor(fraction * count)));\n}\n\n/**\n * Buckets a set of points into a strip.\n *\n * `null` when there is nothing to draw: an empty store has no range, and a\n * strip with invented ends would be a lie about what is recorded.\n */\nexport function buildTimeline(\n points: readonly TimePoint[],\n bucketCount: number = TIMELINE_BUCKETS,\n): TimelineReport | null {\n if (points.length === 0 || bucketCount <= 0) return null;\n\n let from = Number.POSITIVE_INFINITY;\n let to = Number.NEGATIVE_INFINITY;\n for (const point of points) {\n if (point.startedAt < from) from = point.startedAt;\n if (point.startedAt > to) to = point.startedAt;\n }\n\n const buckets: TimelineBucket[] = Array.from({ length: bucketCount }, () => ({\n err: 0,\n slow: 0,\n rest: 0,\n total: 0,\n }));\n\n for (const point of points) {\n const index = bucketIndex(point.startedAt, from, to, bucketCount);\n const bucket = buckets[index] as {\n err: number;\n slow: number;\n rest: number;\n total: number;\n };\n if (point.hasError) bucket.err++;\n else if (point.durationMs >= SLOW_MS) bucket.slow++;\n else bucket.rest++;\n bucket.total++;\n }\n\n return { from, to, buckets };\n}\n","/**\n * One metric over one period, and what the period adds up to.\n *\n * Everything else the panel draws is scoped to something: the strip above the\n * list counts requests and nothing else, and the route charts cover one route\n * at a time. This is the screen that answers \"what did latency do this week\",\n * and the arithmetic behind it lives here — once, for every store.\n *\n * **Why the store hands over rows rather than answers.** The obvious division\n * of labour is to let SQLite compute percentiles in SQL, and the obvious cost\n * is two implementations of the same statistic that quietly disagree: one\n * interpolating between neighbouring samples, the other picking the nearest\n * rank. So a store hands back a few numbers per request — the shape below,\n * never the payloads — and the bucketing and the percentiles happen here. The\n * rule the plan actually cares about still holds: a week of rows must never\n * reach the browser to have a median taken at the other end.\n *\n * What a store *is* responsible for is not reading its whole history into\n * memory. It reads a bounded number of rows and says when it stopped, and\n * this file passes that admission on rather than presenting a truncated total\n * as a complete one.\n */\n\nimport type { MetricSeries, SeriesMetric, SeriesResponse, SeriesTotals } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport type { RequestFilter } from './filters.js';\nimport { normalizeRoute, percentile } from './routes.js';\nimport { bucketIndex } from './timeline.js';\n\n/**\n * One request, as a history reading needs it.\n *\n * Ten numbers rather than a record: a period is tens of thousands of requests,\n * and parsing that many JSON documents to look at one field in each is how a\n * screen becomes slower than the question it answers.\n */\nexport interface HistorySample {\n readonly startedAt: number;\n readonly durationMs: number;\n readonly hasError: boolean;\n readonly sqlCount: number;\n readonly httpCount: number;\n readonly bytes: number;\n /** Mean event-loop delay while it ran, or `null` when nothing measured it. */\n readonly loopDelayMs: number | null;\n readonly findingCount: number;\n /** Time inside queries, ms. `null` for requests stored before it was kept. */\n readonly sqlMs: number | null;\n /** Time covered by no instrumented work, ms. `null` as above. */\n readonly selfMs: number | null;\n readonly method: string;\n readonly route: string;\n /** The detector the list flags this request with, when one fired. */\n readonly flag: string | null;\n}\n\n/**\n * One request, reduced to what a history reading needs.\n *\n * For every store that keeps whole records — the in-memory ring, and any\n * store answering from `list()` — so that what the screen shows does not\n * depend on which one is behind it.\n */\nexport function historySampleOf(request: RecordedRequest): HistorySample {\n let sqlCount = 0;\n let httpCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n else if (span.kind === 'http') httpCount++;\n }\n\n return {\n startedAt: request.startedAt,\n durationMs: request.durationMs,\n hasError: request.error !== null || request.status >= 500,\n sqlCount,\n httpCount,\n bytes: request.weight?.bytesOut ?? 0,\n loopDelayMs: request.host?.loopDelayMs ?? null,\n findingCount: request.findings.length,\n sqlMs: request.timing?.sqlMs ?? null,\n selfMs: request.timing?.selfMs ?? null,\n method: request.method,\n route: normalizeRoute(request.path),\n // The same rule the list flags a row by: the costliest finding names it.\n flag: [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null,\n };\n}\n\n/** What a store is asked for. */\nexport interface HistoryQuery {\n /** Epoch ms, inclusive. */\n readonly from: number;\n /** Epoch ms, inclusive. */\n readonly to: number;\n /** The same filter the list uses, so a metric can be asked about one route. */\n readonly filter: RequestFilter;\n}\n\n/** What a store answers with. */\nexport interface HistorySamples {\n readonly samples: readonly HistorySample[];\n /** The store stopped reading before the period ended. */\n readonly truncated: boolean;\n}\n\n/** Columns the chart is drawn with, unless the caller asks for fewer. */\nexport const SERIES_COLUMNS = 48;\n\n/**\n * Below this many requests per column a percentile is not a statistic.\n *\n * The same figure a route's charts use: a p95 over three\n * samples is the slowest of three, and a chart of those jumps about saying\n * nothing.\n */\nconst MIN_PER_COLUMN = 6;\n\n/** Below this the chart stops being a shape and becomes a row of bars. */\nconst MIN_COLUMNS = 8;\n\n/** A column of the chart, while it is being filled. */\ninterface Column {\n readonly durations: number[];\n errors: number;\n sqlCount: number;\n httpCount: number;\n bytes: number;\n findings: number;\n loopTotal: number;\n loopSamples: number;\n}\n\nfunction emptyColumn(): Column {\n return {\n durations: [],\n errors: 0,\n sqlCount: 0,\n httpCount: 0,\n bytes: 0,\n findings: 0,\n loopTotal: 0,\n loopSamples: 0,\n };\n}\n\n/** The value of one metric in one column, or `null` when it cannot say. */\nfunction metricValue(metric: SeriesMetric, column: Column, bucketMs: number): number | null {\n const calls = column.durations.length;\n // Nothing ran here. Every metric returns a void rather than a zero: a\n // stretch nobody called did not have an error rate of nought.\n if (calls === 0) return null;\n\n switch (metric) {\n case 'p50':\n case 'p95':\n case 'p99': {\n const sorted = [...column.durations].sort((a, b) => a - b);\n const p = metric === 'p50' ? 0.5 : metric === 'p95' ? 0.95 : 0.99;\n return percentile(sorted, p);\n }\n case 'throughput':\n return bucketMs > 0 ? (calls / bucketMs) * 60_000 : null;\n case 'errorRate':\n return column.errors / calls;\n case 'sqlPerRequest':\n return column.sqlCount / calls;\n case 'httpPerRequest':\n return column.httpCount / calls;\n case 'bytes':\n return column.bytes / calls;\n case 'loopDelay':\n // Only the requests that carried a reading. A process that was never\n // measured must not average in as calm.\n return column.loopSamples > 0 ? column.loopTotal / column.loopSamples : null;\n case 'findingsPerRequest':\n return column.findings / calls;\n default:\n return null;\n }\n}\n\n/** Everything a period adds up to. */\nexport function totalsOf(samples: readonly HistorySample[]): SeriesTotals {\n if (samples.length === 0) {\n return {\n calls: 0,\n errorRate: 0,\n p50: 0,\n p95: 0,\n p99: 0,\n sqlMs: null,\n appMs: null,\n busiest: null,\n topFinding: null,\n };\n }\n\n const durations: number[] = [];\n let errors = 0;\n let sqlMs = 0;\n let appMs = 0;\n let timed = 0;\n const routes = new Map<string, { method: string; route: string; calls: number }>();\n const findings = new Map<string, number>();\n\n for (const sample of samples) {\n durations.push(sample.durationMs);\n if (sample.hasError) errors++;\n if (sample.sqlMs !== null && sample.selfMs !== null) {\n sqlMs += sample.sqlMs;\n appMs += sample.selfMs;\n timed++;\n }\n\n const key = `${sample.method} ${sample.route}`;\n const seen = routes.get(key);\n if (seen) seen.calls++;\n else routes.set(key, { method: sample.method, route: sample.route, calls: 1 });\n\n if (sample.flag) findings.set(sample.flag, (findings.get(sample.flag) ?? 0) + 1);\n }\n\n durations.sort((a, b) => a - b);\n\n let busiest: SeriesTotals['busiest'] = null;\n for (const entry of routes.values()) {\n if (!busiest || entry.calls > busiest.calls) busiest = { ...entry };\n }\n\n let topFinding: SeriesTotals['topFinding'] = null;\n for (const [detector, calls] of findings) {\n if (!topFinding || calls > topFinding.calls) topFinding = { detector, calls };\n }\n\n return {\n calls: samples.length,\n errorRate: errors / samples.length,\n p50: percentile(durations, 0.5),\n p95: percentile(durations, 0.95),\n p99: percentile(durations, 0.99),\n // Reported only when something recorded it. A period half of whose\n // requests predate the figure would otherwise show a share of SQL time\n // that is half of the truth and looks like a fall.\n sqlMs: timed > 0 ? sqlMs : null,\n appMs: timed > 0 ? appMs : null,\n busiest,\n topFinding,\n };\n}\n\n/**\n * How many columns a period's traffic can support.\n *\n * Never more than asked for, never so many that each holds a handful of\n * requests — see {@link MIN_PER_COLUMN}.\n */\nexport function columnsFor(sampleCount: number, asked: number): number {\n if (asked <= 0) return 0;\n return Math.max(\n Math.min(MIN_COLUMNS, asked),\n Math.min(asked, Math.ceil(sampleCount / MIN_PER_COLUMN)),\n );\n}\n\nexport interface HistoryOptions {\n /** The period, as the caller chose it — not as the data happens to fall. */\n readonly from: number;\n readonly to: number;\n readonly metrics: readonly SeriesMetric[];\n readonly columns?: number;\n}\n\n/**\n * Builds the answer for one reading of the screen.\n *\n * The period comes from the caller rather than from the samples: a week with\n * traffic in one hour of it must draw a week with one column in it, not an\n * hour stretched across the screen.\n */\n/** Samples into columns of one window — the same cut for a period and its ghost. */\nfunction bucketize(\n samples: readonly HistorySample[],\n from: number,\n to: number,\n count: number,\n): Column[] {\n const columns: Column[] = Array.from({ length: count }, emptyColumn);\n for (const sample of samples) {\n const column = columns[bucketIndex(sample.startedAt, from, to, count)];\n if (!column) continue;\n column.durations.push(sample.durationMs);\n if (sample.hasError) column.errors++;\n column.sqlCount += sample.sqlCount;\n column.httpCount += sample.httpCount;\n column.bytes += sample.bytes;\n column.findings += sample.findingCount;\n if (sample.loopDelayMs !== null) {\n column.loopTotal += sample.loopDelayMs;\n column.loopSamples++;\n }\n }\n return columns;\n}\n\nexport function historyOf(\n current: HistorySamples,\n previous: readonly HistorySample[],\n options: HistoryOptions,\n): SeriesResponse {\n const samples = current.samples;\n const asked = options.columns ?? SERIES_COLUMNS;\n const count = Math.max(1, columnsFor(samples.length, asked));\n\n const columns = bucketize(samples, options.from, options.to, count);\n\n // A period of no width would divide by zero and a chart of it would be a\n // single column claiming to be a stretch of time.\n const span = Math.max(1, options.to - options.from);\n const bucketMs = span / count;\n\n // The period immediately before, cut into the same number of columns, so\n // the ghost lines up with the line it sits behind.\n const ghostColumns =\n previous.length > 0 ? bucketize(previous, options.from - span, options.from - 1, count) : null;\n const primary = options.metrics[0];\n\n const series: MetricSeries[] = options.metrics.map((metric) => ({\n metric,\n values: columns.map((column) => metricValue(metric, column, bucketMs)),\n }));\n\n return {\n from: options.from,\n to: options.to,\n bucketMs,\n calls: columns.map((column) => column.durations.length),\n series,\n totals: totalsOf(samples),\n // No traffic before the period is not a period of zeroes; it is nothing\n // to compare against, and the screen says so instead of inventing a\n // hundred-percent rise.\n previous: previous.length > 0 ? totalsOf(previous) : null,\n ghost:\n ghostColumns && primary\n ? ghostColumns.map((column) => metricValue(primary, column, bucketMs))\n : null,\n truncated: current.truncated,\n };\n}\n","/**\n * Where a page of the request list stopped.\n *\n * The cursor is part of the panel's API, not of any one store: the in-memory\n * ring and the SQLite history hand out cursors the browser cannot tell apart,\n * and both continue from one the other could have written.\n *\n * The key is whatever the page is ordered by — the start time for the list as\n * it is normally read, the duration when the question is \"what was slowest\".\n * It is not a position on its own, because several requests can share a\n * millisecond and plenty share a duration, so the id rides along and breaks\n * the tie exactly the way the ordering does: largest first, among equals the\n * larger id first.\n */\n\n/** A decoded cursor. */\nexport interface Cursor {\n /** Value of the column the page is ordered by. */\n readonly key: number;\n readonly id: string;\n}\n\n/** Writes the position of the last row on a page. */\nexport function encodeCursor(key: number, id: string): string {\n return `${key}.${id}`;\n}\n\n/**\n * Reads a cursor back.\n *\n * Split at the last dot rather than the first: a duration key is fractional,\n * and request ids are base36 with no dot in them.\n *\n * Anything unparseable means \"start from the newest\" rather than an error: a\n * stale link is a thing that happens, and answering it with a 400 helps\n * nobody.\n */\nexport function decodeCursor(raw: string | null | undefined): Cursor | null {\n if (!raw) return null;\n const dot = raw.lastIndexOf('.');\n if (dot <= 0) return null;\n const key = Number(raw.slice(0, dot));\n const id = raw.slice(dot + 1);\n if (!Number.isFinite(key) || id === '') return null;\n return { key, id };\n}\n\n/**\n * Whether a row belongs on a page continuing from `cursor`.\n *\n * Strictly past it, so a row is never served twice and never skipped.\n */\nexport function isAfterCursor(cursor: Cursor, key: number, id: string): boolean {\n if (key !== cursor.key) return key < cursor.key;\n return id < cursor.id;\n}\n","/**\n * One page of a list, from records held in memory.\n *\n * The paging rule, in one place: the router's fallback calls it, and so does\n * any store that holds its records in memory. Two implementations of it would\n * mean one panel giving two answers depending on the store behind it.\n *\n * A store that pages in its own query language cannot use this and should not\n * — pushing the work down is why it has a `page()`. What it owes is the same\n * behaviour, which is what the parity test checks.\n */\n\nimport type { RecordedRequest } from '../types.js';\nimport type { PageQuery, RequestPage } from './api.js';\nimport { toRow } from './api.js';\nimport { filterRequests, summarize } from './filters.js';\nimport { decodeCursor, encodeCursor, isAfterCursor } from './paging.js';\n\n/** What the caller knows that the records do not. */\nexport interface PageContext {\n /** Ids currently pinned. Exempt from the filter, and flagged on the row. */\n readonly pinned?: ReadonlySet<string> | undefined;\n /** Above this a request counts as slow in the summary. */\n readonly slowMs?: number | undefined;\n}\n\n/**\n * Pages `records` — newest first — according to `query`.\n *\n * `records` is the store's whole contents: the summary is over all of them,\n * which is what makes the status bar a statement about the store rather than\n * about the page.\n */\nexport function pageFromList(\n records: readonly RecordedRequest[],\n query: PageQuery,\n context: PageContext = {},\n): RequestPage {\n const pinned = context.pinned ?? new Set<string>();\n\n // A pinned request is one the reader deliberately set aside: it stays\n // through a filter that would otherwise exclude it.\n const matched = new Set(filterRequests(records, query.filter).map((item) => item.id));\n const shown = records.filter((item) => matched.has(item.id) || pinned.has(item.id));\n\n // What the page is ordered by, and therefore what the cursor counts in.\n const slowest = query.sort === 'slowest';\n const keyOf = (item: RecordedRequest): number => (slowest ? item.durationMs : item.startedAt);\n // Sorted in both cases: the cursor counts in this order, and a list handed\n // over in arrival order is not in it — a slow request starts early and\n // lands late, and a page boundary beside it would skip or repeat rows.\n const ordered = [...shown].sort((a, b) => keyOf(b) - keyOf(a) || (a.id < b.id ? 1 : -1));\n\n const cursor = decodeCursor(query.cursor);\n const after = cursor\n ? ordered.filter((item) => isAfterCursor(cursor, keyOf(item), item.id))\n : ordered;\n\n const rows = after.slice(0, query.limit);\n const last = rows[rows.length - 1];\n const nextCursor = after.length > rows.length && last ? encodeCursor(keyOf(last), last.id) : null;\n\n return {\n rows: rows.map((item) => toRow(item, pinned.has(item.id))),\n nextCursor,\n summary: summarize(records, shown, context.slowMs),\n };\n}\n","/**\n * Was the process to blame?\n *\n * Knowing an operation is slow does not say why, and often the code did not\n * change at all — the loop fell behind, and every callback waited before it\n * even started. That is invisible in a waterfall: the spans are each fast and\n * the time is between them.\n *\n * The comparison here is a route against itself. Its calls are split by\n * whether the loop was in its *own* top quartile at the time, and the two\n * halves are compared. Elevated is never a fixed threshold: a delay that is\n * alarming for one service is idle for the next, and the only baseline worth\n * comparing a process against is the same process.\n *\n * It is evidence, not proof, and the panel says so. A batch job hammering the\n * same process explains the shape as well as this route being its victim.\n */\n\nimport type { HostPressure, HostPressureSide } from '../types.js';\nimport type { DurationSample } from './api.js';\nimport { percentile } from './routes.js';\n\n/**\n * Calls needed on each side of the split.\n *\n * Twenty is where a ninety-fifth percentile stops being the single slowest\n * call and starts describing a distribution. Below it the comparison is\n * between two anecdotes.\n */\nconst MIN_PER_SIDE = 20;\n\n/**\n * How much slower the bad half has to be before it is worth a word.\n *\n * Under half again, the difference is inside the noise of a sample this size,\n * and a card that fires there is a card that fires always.\n */\nconst MIN_RATIO = 1.5;\n\n/**\n * How much the loop has to have varied for \"elevated\" to mean anything.\n *\n * A host that was flat has no elevated state to compare against: splitting it\n * at its own quartile would sort calls by a millisecond of jitter and then\n * report whatever the two halves happened to differ by.\n */\nconst MIN_SPREAD_MS = 1;\n\nfunction sideOf(durations: readonly number[]): HostPressureSide {\n const sorted = [...durations].sort((a, b) => a - b);\n const sum = sorted.reduce((total, value) => total + value, 0);\n return {\n calls: sorted.length,\n p95Ms: percentile(sorted, 0.95),\n avgMs: sorted.length === 0 ? 0 : sum / sorted.length,\n };\n}\n\n/**\n * The finding, or `null` — which is the answer far more often, and by design.\n *\n * @param samples every other call of the route, as the store hands them over.\n */\nexport function pressureFor(samples: readonly DurationSample[]): HostPressure | null {\n const measured = samples.filter(\n (sample): sample is DurationSample & { loopDelayMs: number } => sample.loopDelayMs !== null,\n );\n if (measured.length < MIN_PER_SIDE * 2) return null;\n\n const delays = measured.map((sample) => sample.loopDelayMs).sort((a, b) => a - b);\n const cutoffMs = percentile(delays, 0.75);\n // Did the loop actually move? Comparing the top quartile against the bottom\n // one answers it without a threshold of its own.\n if (cutoffMs - percentile(delays, 0.25) < MIN_SPREAD_MS) return null;\n\n const elevated = sideOf(\n measured.filter((sample) => sample.loopDelayMs >= cutoffMs).map((sample) => sample.durationMs),\n );\n const normal = sideOf(\n measured.filter((sample) => sample.loopDelayMs < cutoffMs).map((sample) => sample.durationMs),\n );\n if (elevated.calls < MIN_PER_SIDE || normal.calls < MIN_PER_SIDE) return null;\n // Nothing to be slower than: a route where the good half is instant would\n // report a ratio of infinity and mean nothing by it.\n if (normal.p95Ms <= 0) return null;\n\n const ratio = elevated.p95Ms / normal.p95Ms;\n if (ratio < MIN_RATIO) return null;\n\n return {\n metric: 'loop',\n cutoffMs,\n ratio,\n share: (elevated.calls / measured.length) * 100,\n elevated,\n normal,\n };\n}\n","/**\n * Request replay from the panel.\n *\n * The request is replayed through the same application — with its full\n * middleware stack — so this is a real run, not a simulation. Hence the\n * restriction: a replay in production means a second card charge and a second\n * email, so outside development it is enabled only by an explicit flag.\n *\n * A replayed request must not show up in the shared list: it is marked by a\n * header, and its record goes not to the transport but to whoever started the\n * replay.\n */\n\nimport type { ReplayComparison, ReplayInput, ReplayMetrics } from '@reqray/protocol';\nimport { runOutsideScope } from '../context.js';\nimport { awaitReplay } from '../replay-waiters.js';\nimport { REPLAY_HEADER } from '../reqray.js';\nimport type { RecordedRequest } from '../types.js';\n\nexport type { ReplayComparison, ReplayInput, ReplayMetrics };\n\nfunction numberOrNull(value: string | undefined): number | null {\n if (value === undefined) return null;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/** Reduces a request record to the comparison metrics. */\nexport function metricsOf(request: RecordedRequest): ReplayMetrics {\n let sqlCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n }\n\n return {\n status: request.status,\n durationMs: request.durationMs,\n sqlCount,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n bytes: numberOrNull(request.responseHeaders['content-length']),\n etag: request.responseHeaders['etag'] ?? null,\n };\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | null> {\n return new Promise<T | null>((resolve) => {\n const timer = setTimeout(() => resolve(null), ms);\n timer.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n () => {\n clearTimeout(timer);\n resolve(null);\n },\n );\n });\n}\n\nlet counter = 0;\n\nfunction nextReplayId(): string {\n counter = (counter + 1) % 0xffffff;\n return `r${counter.toString(36)}${Math.random().toString(36).slice(2, 8)}`;\n}\n\n/**\n * Runs the request again and returns a comparison against the original.\n *\n * @param origin the application's own address, e.g. `http://127.0.0.1:3000`.\n * @param recordTimeoutMs how long to wait for the replay's record before\n * returning a partial comparison.\n */\nexport async function runReplay(\n origin: string,\n input: ReplayInput,\n original: RecordedRequest,\n recordTimeoutMs = 2_000,\n): Promise<ReplayComparison> {\n const replayId = nextReplayId();\n\n let stopWaiting = (): void => {};\n const recorded = new Promise<RecordedRequest>((resolve) => {\n stopWaiting = awaitReplay(replayId, resolve);\n });\n\n const startedAt = performance.now();\n try {\n // Outside the scope: Reqray's own HTTP call must not become a span of the\n // request that opened the panel.\n const response = await runOutsideScope(() =>\n fetch(`${origin}${input.path}`, {\n method: input.method,\n headers: { ...input.headers, [REPLAY_HEADER]: replayId },\n ...(input.body === undefined ? {} : { body: input.body }),\n }),\n );\n\n const text = await response.text();\n const durationMs = performance.now() - startedAt;\n const record = await withTimeout(recorded, recordTimeoutMs);\n\n const replay: ReplayMetrics = record\n ? metricsOf(record)\n : {\n status: response.status,\n durationMs,\n sqlCount: 0,\n nPlusOne: false,\n bytes: Buffer.byteLength(text),\n etag: response.headers.get('etag'),\n };\n\n return { original: metricsOf(original), replay, partial: record === null };\n } finally {\n stopWaiting();\n }\n}\n","/**\n * Three charts for one endpoint, and nothing beyond them.\n *\n * Latency over time, the share that failed, and how often it was called —\n * enough to see \"it got slower at 14:20, after the deploy\" and to stop there.\n * Not a dashboard builder, not alerting, not aggregates over arbitrary\n * dimensions: that is the line where this becomes a worse Datadog, and it is\n * written down in the plan so that nobody crosses it by inertia.\n *\n * The bucketing is the strip's own, so a chart and the strip above it cannot\n * disagree about when something happened.\n */\n\nimport type { RouteSeries, SeriesBucket } from '@reqray/protocol';\nimport type { DurationSample } from './api.js';\nimport { percentile } from './routes.js';\nimport { bucketIndex } from './timeline.js';\n\nexport type { RouteSeries, SeriesBucket };\n\n/** Columns a route's charts are drawn with, unless asked otherwise. */\nexport const SERIES_BUCKETS = 48;\n\n/**\n * Calls a column should hold before it is worth drawing as one.\n *\n * A percentile over three samples is the slowest of three, which is why a\n * chart drawn at full resolution over a quiet route shows a p95 and a p99\n * that are the same number and jump about together. Fewer, fuller columns say\n * less about *when* and much more about *what*, and the resolution should\n * follow how much there is to draw rather than the width of the box.\n */\nconst MIN_PER_COLUMN = 6;\n\n/** Below this the chart stops being a shape and becomes a bar. */\nconst MIN_BUCKETS = 12;\n\n/**\n * Buckets one route's calls.\n *\n * `null` when the store holds nothing for it: a chart with invented ends\n * would be a claim about a stretch of time nobody recorded.\n */\nexport function routeSeries(\n method: string,\n route: string,\n samples: readonly DurationSample[],\n bucketCount: number = SERIES_BUCKETS,\n): RouteSeries | null {\n if (samples.length === 0 || bucketCount <= 0) return null;\n\n let from = Number.POSITIVE_INFINITY;\n let to = Number.NEGATIVE_INFINITY;\n for (const sample of samples) {\n if (sample.startedAt < from) from = sample.startedAt;\n if (sample.startedAt > to) to = sample.startedAt;\n }\n\n // As many columns as the traffic supports, and never more than asked for.\n const count = Math.max(\n Math.min(MIN_BUCKETS, bucketCount),\n Math.min(bucketCount, Math.ceil(samples.length / MIN_PER_COLUMN)),\n );\n\n const columns: Array<{ durations: number[]; errors: number }> = Array.from(\n { length: count },\n () => ({ durations: [], errors: 0 }),\n );\n\n for (const sample of samples) {\n const column = columns[bucketIndex(sample.startedAt, from, to, count)];\n if (!column) continue;\n column.durations.push(sample.durationMs);\n if (sample.hasError) column.errors++;\n }\n\n // A single call spans no time; a second keeps throughput finite and honest.\n const span = Math.max(1_000, to - from);\n const bucketMs = span / count;\n\n return {\n method,\n route,\n from,\n to,\n bucketMs,\n calls: samples.length,\n buckets: columns.map((column, index) => {\n const sorted = column.durations.sort((a, b) => a - b);\n return {\n at: from + index * bucketMs,\n calls: sorted.length,\n errors: column.errors,\n p50: sorted.length > 0 ? percentile(sorted, 0.5) : 0,\n p95: sorted.length > 0 ? percentile(sorted, 0.95) : 0,\n p99: sorted.length > 0 ? percentile(sorted, 0.99) : 0,\n };\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAM,YAAY;AASlB,IAAM,YAAY;AAUlB,IAAM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