@reqray/store-sqlite 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/query.ts"],"sourcesContent":["/**\n * `@reqray/store-sqlite` — a request history that outlives the process.\n *\n * The in-memory ring is a buffer, not a history: it holds the last few\n * hundred requests and forgets everything when the process restarts. This\n * store writes to a file instead, so \"what happened an hour ago\" and \"what\n * did that request look like before yesterday's deploy\" have answers.\n *\n * **`node:sqlite`, not a native driver.** Storage that needs a compiler at\n * install time is storage most people will not turn on. Node ships SQLite\n * since 22.5, which is what this package requires — one version above what\n * the rest of Reqray asks for, and the reason it is a package of its own\n * rather than a branch inside the memory store.\n *\n * **Retention is a promise about disk, not a hope.** Two budgets, whichever\n * runs out first: a number of requests and a number of bytes. Beyond them the\n * oldest go, except pinned ones — the whole point of a pin is that it is the\n * request you are working on.\n *\n * Writes are synchronous and unbatched on purpose. `send()` is already called\n * outside request handling, an insert costs single-digit microseconds, and a\n * write queue would mean a request that the live feed has announced but the\n * store cannot yet hand back.\n */\n\nimport type { Transport } from '@reqray/core';\nimport { DAY_MS, type RetentionPolicy, warnOnce } from '@reqray/core';\nimport type {\n BaselineQuery,\n DurationSample,\n PageQuery,\n RequestPage,\n RouteWindow,\n TimePoint,\n} from '@reqray/core/panel';\nimport {\n decodeCursor,\n encodeCursor,\n type FindingSamples,\n type FindingsQuery,\n findingSamplesOf,\n type HistoryQuery,\n type HistorySample,\n type HistorySamples,\n toRow,\n} from '@reqray/core/panel';\nimport type {\n FiledPatternState,\n RecordedRequest,\n RequestRow,\n RequestSummary,\n StoredPatternState,\n} from '@reqray/protocol';\nimport { afterCursor, orderColumn, whereFor } from './query.js';\n\n/** Options for {@link sqliteTransport}. */\nexport interface SqliteTransportOptions {\n /**\n * Database file. `:memory:` keeps it in the process, which is for tests —\n * a history that dies with the process is what this package exists to fix.\n */\n readonly file: string;\n /** How many requests to keep. Older ones are evicted. */\n readonly maxRequests?: number;\n /**\n * The retention policy, shared with the log and with the panel.\n *\n * Given one, its limits win over the two below and a change made from the\n * panel takes effect on the next eviction. Without one the numbers here are\n * fixed for the life of the process.\n */\n readonly retention?: RetentionPolicy;\n /** How much disk the payloads may take, bytes. */\n readonly maxBytes?: number;\n /** How many requests may be pinned at once. */\n readonly pinLimit?: number;\n /**\n * How many records {@link SqliteStore.list} returns at most.\n *\n * The aggregate screens — routes, exceptions — and the exports read the\n * store whole. On a history \"whole\" is unbounded, so they see the most\n * recent slice instead, and this is its size.\n */\n readonly listLimit?: number;\n}\n\n/** Summary of what the store holds. */\nexport interface SqliteStoreStats {\n readonly size: number;\n readonly capacity: number;\n /** How many requests have been evicted since the store was opened. */\n readonly evicted: number;\n readonly oldestAt: number | null;\n readonly pinned: number;\n /** Bytes the stored payloads add up to. */\n readonly bytes: number;\n}\n\n/** Listener for the panel's live feed. */\nexport type SqliteStoreListener = (request: RecordedRequest) => void;\n\n/** A transport that is also the store the panel reads from. */\nexport interface SqliteStore extends Transport {\n list(): RecordedRequest[];\n get(id: string): RecordedRequest | undefined;\n clear(): void;\n stats(): SqliteStoreStats;\n subscribe(listener: SqliteStoreListener): () => void;\n pin(id: string, pinned: boolean): boolean;\n pinned(): string[];\n page(query: PageQuery): RequestPage;\n /** Durations of other calls of one route, for the detail page's verdict. */\n durations(query: BaselineQuery): DurationSample[];\n /** Traffic grouped by route over a stretch of time. */\n counts(query: { from: number; to: number }): RouteWindow[];\n /** Three numbers per request, for the strip above the list. */\n timeSeries(): TimePoint[];\n /** A period's requests, a handful of numbers each, for the history screen. */\n history(query: HistoryQuery): HistorySamples;\n /** Finding occurrences over a stretch, one row each, for the findings tab. */\n findings(query: FindingsQuery): FindingSamples;\n /** `ack`/`muted` per pattern id — the part of the tab that must survive a restart. */\n findingStates(): ReadonlyMap<string, FiledPatternState>;\n /** Remembers a state; `new` forgets the pattern. */\n setFindingState(id: string, state: StoredPatternState): void;\n close(): Promise<void>;\n}\n\n/** How often age is swept while requests arrive. */\nconst AGE_SWEEP_MS = 60_000;\n\n/**\n * How many flagged requests a findings reading parses at most.\n *\n * The one place this store deserializes payloads in bulk — findings live\n * inside them — bounded because \"bulk\" must never mean \"the whole file\".\n * Requests with findings are a small minority, so the ceiling is rarely met;\n * newest first, so a truncated reading is the recent part of the story.\n */\nconst FINDINGS_LIMIT = 5_000;\n\nconst DEFAULT_MAX_REQUESTS = 20_000;\nconst DEFAULT_MAX_BYTES = 256 * 1024 * 1024;\nconst DEFAULT_PIN_LIMIT = 50;\nconst DEFAULT_LIST_LIMIT = 1_000;\n/**\n * How many requests the strip above the list may be drawn from.\n *\n * Three numbers each, so this is a few megabytes at the ceiling — and beyond\n * it the strip would be carrying more detail than a screen has pixels.\n */\nconst TIME_SERIES_LIMIT = 50_000;\n/**\n * How many calls of one route a verdict rests on.\n *\n * Far more than the twenty a percentile needs, and far fewer than a busy\n * route's whole history: a detail page must open now, and the ten-thousandth\n * most recent call of the same endpoint would not move the number.\n */\nconst BASELINE_LIMIT = 10_000;\n/**\n * How many requests one reading of the history screen rests on.\n *\n * The same ceiling the strip reads under, for the same reason: a period is\n * chosen by a person looking at a chart, and the answer has to arrive while\n * they are still looking. Beyond it the screen says so rather than presenting\n * the recent part of a period as the whole of it.\n */\nconst HISTORY_LIMIT = 50_000;\n/** The slow threshold the status bar counts by, matching the panel's default. */\nconst SLOW_MS = 500;\n\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS requests (\n id TEXT PRIMARY KEY,\n started_at INTEGER NOT NULL,\n method TEXT NOT NULL,\n path TEXT NOT NULL,\n query_string TEXT,\n route TEXT NOT NULL,\n status INTEGER NOT NULL,\n duration_ms REAL NOT NULL,\n sql_count INTEGER NOT NULL,\n http_count INTEGER NOT NULL,\n n_plus_one INTEGER NOT NULL,\n has_error INTEGER NOT NULL,\n finding_count INTEGER NOT NULL,\n flag TEXT,\n test TEXT,\n loop_delay_ms REAL,\n sql_ms REAL,\n self_ms REAL,\n bytes_out INTEGER,\n cpu_ms REAL,\n cpu_share REAL,\n pinned INTEGER NOT NULL DEFAULT 0,\n bytes INTEGER NOT NULL,\n payload TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS requests_by_time ON requests (started_at DESC, id DESC);\nCREATE INDEX IF NOT EXISTS requests_pinned ON requests (pinned) WHERE pinned = 1;\nCREATE INDEX IF NOT EXISTS requests_by_duration ON requests (duration_ms DESC, id DESC);\nCREATE INDEX IF NOT EXISTS requests_by_route ON requests (route, method, started_at DESC);\nCREATE TABLE IF NOT EXISTS finding_states (\n id TEXT PRIMARY KEY,\n state TEXT NOT NULL,\n updated_at INTEGER NOT NULL\n);\n`;\n\n/** A row as the table stores it. */\ninterface StoredRow {\n id: string;\n started_at: number;\n method: string;\n path: string;\n query_string: string | null;\n route: string;\n status: number;\n duration_ms: number;\n sql_count: number;\n http_count: number;\n n_plus_one: number;\n has_error: number;\n finding_count: number;\n flag: string | null;\n test: string | null;\n cpu_ms: number | null;\n cpu_share: number | null;\n pinned: number;\n}\n\nfunction toRequestRow(stored: StoredRow): RequestRow {\n return {\n id: stored.id,\n method: stored.method,\n path: stored.path,\n query: stored.query_string,\n route: stored.route,\n status: stored.status,\n durationMs: stored.duration_ms,\n startedAt: stored.started_at,\n sqlCount: stored.sql_count,\n httpCount: stored.http_count,\n nPlusOne: stored.n_plus_one === 1,\n hasError: stored.has_error === 1,\n findingCount: stored.finding_count,\n flag: stored.flag,\n test: stored.test,\n cpuMs: stored.cpu_ms,\n cpuShare: stored.cpu_share,\n pinned: stored.pinned === 1,\n };\n}\n\ninterface SqliteModule {\n DatabaseSync: new (path: string) => Database;\n}\n\ninterface Database {\n exec(sql: string): void;\n prepare(sql: string): Statement;\n close(): void;\n}\n\ninterface Statement {\n run(...params: unknown[]): { changes: number };\n get(...params: unknown[]): Record<string, unknown> | undefined;\n all(...params: unknown[]): Record<string, unknown>[];\n}\n\n/**\n * Opens `node:sqlite`, or explains itself.\n *\n * Looked up at run time rather than imported: the module does not exist\n * before Node 22.5, and a static import would fail the whole bundle with\n * \"cannot find module node:sqlite\", which is not an explanation anybody\n * should have to decode. `getBuiltinModule` answers `undefined` instead of\n * throwing, and works the same in both the ESM and the CJS build.\n */\n/**\n * Columns added after the table existed.\n *\n * `CREATE TABLE IF NOT EXISTS` does nothing to a database that is already\n * there, so a store somebody has been filling for a week would keep its old\n * shape and every insert would fail on the new column. Checked rather than\n * versioned: there is one table, and asking it what it has is cheaper than\n * keeping a migration ledger honest.\n */\nfunction addMissingColumns(db: Database): void {\n const existing = new Set(\n db\n .prepare('PRAGMA table_info(requests)')\n .all()\n .map((row) => row['name'] as string),\n );\n const columns: Array<[name: string, definition: string]> = [\n ['loop_delay_ms', 'REAL'],\n // Where the time went and what came back. In the payload since stages 38\n // and 40, but a history screen cannot read a week of payloads to find\n // out, so they are columns from here on.\n ['sql_ms', 'REAL'],\n ['self_ms', 'REAL'],\n // Bytes sent to the client. Distinct from `bytes`, which is what the\n // stored record weighs and what the retention budget counts.\n ['bytes_out', 'INTEGER'],\n // What the request cost to run. A column rather than a payload field for\n // the same reason as the two above: the list shows it on every row, and\n // reading a week of payloads to draw a column is not a list.\n ['cpu_ms', 'REAL'],\n ['cpu_share', 'REAL'],\n ];\n for (const [name, definition] of columns) {\n if (existing.has(name)) continue;\n // No default and no backfill: a request recorded before the loop was\n // being watched has no reading, and `null` is what \"not measured\" is.\n db.exec(`ALTER TABLE requests ADD COLUMN ${name} ${definition}`);\n }\n}\n\nfunction openDatabase(file: string): Database {\n const lookup = (process as { getBuiltinModule?: (id: string) => unknown }).getBuiltinModule;\n const sqlite = lookup?.call(process, 'node:sqlite') as SqliteModule | undefined;\n if (!sqlite?.DatabaseSync) {\n throw new Error(\n `@reqray/store-sqlite needs Node 22.5 or newer for the built-in SQLite (this is ${process.version}). ` +\n 'Keep the in-memory transport, or upgrade Node.',\n );\n }\n return new sqlite.DatabaseSync(file);\n}\n\nexport function sqliteTransport(options: SqliteTransportOptions): SqliteStore {\n const own = {\n maxRequests: options.maxRequests ?? DEFAULT_MAX_REQUESTS,\n maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,\n };\n /** Read on every eviction: a change from the panel applies to the next one. */\n const limits = (): { maxRequests: number; maxBytes: number; days: number | null } => {\n const shared = options.retention?.current();\n return {\n maxRequests: shared?.maxRequests ?? own.maxRequests,\n maxBytes: shared?.maxBytes ?? own.maxBytes,\n days: shared?.days ?? null,\n };\n };\n const pinLimit = options.pinLimit ?? DEFAULT_PIN_LIMIT;\n const listLimit = options.listLimit ?? DEFAULT_LIST_LIMIT;\n\n const db = openDatabase(options.file);\n // WAL so a reader — the panel — never waits behind a writer, and NORMAL\n // because losing the last few requests to a power cut is not a data loss\n // worth an fsync per request.\n db.exec('PRAGMA journal_mode = WAL');\n db.exec('PRAGMA synchronous = NORMAL');\n db.exec(SCHEMA);\n addMissingColumns(db);\n\n const insert = db.prepare(`\n INSERT INTO requests (\n id, started_at, method, path, query_string, route, status, duration_ms,\n sql_count, http_count, n_plus_one, has_error, finding_count, flag, test,\n loop_delay_ms, sql_ms, self_ms, bytes_out, cpu_ms, cpu_share,\n pinned, bytes, payload\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)\n ON CONFLICT(id) DO NOTHING\n `);\n\n // Both budgets in one statement: the running total walks from newest to\n // oldest, and everything past either line goes. Pinned rows are not in the\n // walk at all — they are kept whatever the budget says.\n const evict = db.prepare(`\n DELETE FROM requests WHERE id IN (\n SELECT id FROM (\n SELECT id,\n SUM(bytes) OVER (ORDER BY started_at DESC, id DESC) AS running,\n ROW_NUMBER() OVER (ORDER BY started_at DESC, id DESC) AS position\n FROM requests WHERE pinned = 0\n ) WHERE running > ? OR position > ?\n )\n `);\n\n // Age is its own budget: a store nobody has written to for a week still has\n // a week-old request in it, and \"kept for three days\" has to mean that.\n const evictOld = db.prepare('DELETE FROM requests WHERE pinned = 0 AND started_at < ?');\n\n const totals = db.prepare(\n 'SELECT COUNT(*) AS size, COALESCE(SUM(bytes), 0) AS bytes, MIN(started_at) AS oldest FROM requests',\n );\n const evictable = db.prepare(\n 'SELECT COUNT(*) AS size, COALESCE(SUM(bytes), 0) AS bytes FROM requests WHERE pinned = 0',\n );\n const byId = db.prepare('SELECT payload FROM requests WHERE id = ?');\n const recent = db.prepare(\n 'SELECT payload FROM requests ORDER BY started_at DESC, id DESC LIMIT ?',\n );\n // Two columns rather than the payload: judging a call against its route\n // reads every call of that route, and parsing a few thousand JSON documents\n // to look at one number in each is how a detail page becomes slow.\n const routeDurations = db.prepare(\n `SELECT duration_ms, started_at, has_error, loop_delay_ms FROM requests\n WHERE route = ? AND method = ? AND id <> ? AND started_at >= ? AND started_at <= ?\n ORDER BY started_at DESC LIMIT ?`,\n );\n // Four numbers per route rather than the rows behind them: answering \"what\n // ran in this moment\" by loading a busy minute of requests would read\n // megabytes of JSON to count calls.\n const routeCounts = db.prepare(\n `SELECT method, route, COUNT(*) AS calls, AVG(duration_ms) AS avg_ms\n FROM requests WHERE started_at >= ? AND started_at <= ?\n GROUP BY method, route`,\n );\n const series = db.prepare(\n 'SELECT started_at, duration_ms, has_error FROM requests ORDER BY started_at DESC LIMIT ?',\n );\n const pinnedIds = db.prepare('SELECT id FROM requests WHERE pinned = 1 ORDER BY started_at DESC');\n const countPinned = db.prepare('SELECT COUNT(*) AS pinned FROM requests WHERE pinned = 1');\n const setPinned = db.prepare('UPDATE requests SET pinned = ? WHERE id = ?');\n const removeAll = db.prepare('DELETE FROM requests');\n\n /**\n * Prepared statements, kept by their SQL.\n *\n * The page query's shape changes with the filter, so it cannot be prepared\n * up front — but there are only a handful of shapes, and a reader typing in\n * the filter box would otherwise re-prepare one of them per keystroke.\n */\n const prepared = new Map<string, Statement>();\n const statement = (sql: string): Statement => {\n const existing = prepared.get(sql);\n if (existing) return existing;\n const fresh = db.prepare(sql);\n prepared.set(sql, fresh);\n return fresh;\n };\n\n const listeners = new Set<SqliteStoreListener>();\n let evicted = 0;\n\n /**\n * Live counters, so the budget check costs no query per request.\n *\n * Of what eviction can touch: pinned rows are outside the budget, and\n * counting them here would leave the store \"over\" for as long as anything\n * is pinned — evicting on every insert and never getting under.\n */\n let size = 0;\n let bytes = 0;\n\n function refreshTotals(): void {\n const current = evictable.get() as { size: number; bytes: number } | undefined;\n size = current?.size ?? 0;\n bytes = current?.bytes ?? 0;\n }\n refreshTotals();\n\n /** When age was last swept: a DELETE per request would be a query per request. */\n let sweptAt = 0;\n\n function enforceRetention(now = Date.now()): void {\n const { maxRequests, maxBytes, days } = limits();\n\n if (days !== null && now - sweptAt > AGE_SWEEP_MS) {\n sweptAt = now;\n const removed = evictOld.run(now - days * DAY_MS).changes;\n if (removed > 0) {\n evicted += removed;\n refreshTotals();\n }\n }\n\n // A fiftieth of slack before acting. Evicting the moment a limit is\n // crossed means a full store is over it on every insert, and the sweep is\n // a walk of the whole table: measured at 17–38 ms a request at the default\n // twenty thousand rows, on the thread that also serves the panel. With\n // slack it runs once per few hundred inserts and trims back to the exact\n // limits each time. Small limits get no slack at all.\n const overCount = size > maxRequests + Math.floor(maxRequests / 50);\n const overBytes = bytes > maxBytes + Math.floor(maxBytes / 50);\n if (!overCount && !overBytes) return;\n const removed = evict.run(maxBytes, maxRequests).changes;\n evicted += removed;\n refreshTotals();\n }\n\n // A change from the panel applies now rather than at the next request: a\n // store that waits for traffic to obey a new limit looks broken.\n options.retention?.subscribe(() => {\n sweptAt = 0;\n enforceRetention();\n });\n enforceRetention();\n\n return {\n name: 'sqlite',\n\n send(request: RecordedRequest) {\n try {\n // A request that is already past the policy would go on the next\n // sweep anyway; not writing it is the same answer without the write.\n // Batches from a collector arrive late, so this is not theoretical.\n const days = limits().days;\n if (days !== null && request.startedAt < Date.now() - days * DAY_MS) return;\n\n const payload = JSON.stringify(request);\n const row = toRow(request, false);\n const stored = insert.run(\n request.id,\n request.startedAt,\n request.method,\n request.path,\n request.query,\n row.route,\n request.status,\n request.durationMs,\n row.sqlCount,\n row.httpCount,\n row.nPlusOne ? 1 : 0,\n row.hasError ? 1 : 0,\n row.findingCount,\n row.flag,\n request.test,\n request.host?.loopDelayMs ?? null,\n request.timing?.sqlMs ?? null,\n request.timing?.selfMs ?? null,\n request.weight?.bytesOut ?? null,\n request.cost?.cpuMs ?? null,\n request.cost?.cpuShare ?? null,\n payload.length,\n payload,\n );\n // An id already held is a batch delivered twice, or two processes\n // that drew one prefix. Nothing was written, so nothing is counted and\n // nobody is told a request arrived that `get` would answer with\n // another one.\n if (stored.changes === 0) return;\n size++;\n bytes += payload.length;\n enforceRetention();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('transport.sqlite.write', `request not stored: ${reason}`);\n return;\n }\n\n for (const listener of listeners) {\n try {\n listener(request);\n } catch {\n // A subscriber's failure is not the store's problem.\n }\n }\n },\n\n list() {\n return recent\n .all(listLimit)\n .map((stored) => JSON.parse(stored['payload'] as string) as RecordedRequest);\n },\n\n get(id: string) {\n const found = byId.get(id);\n return found ? (JSON.parse(found['payload'] as string) as RecordedRequest) : undefined;\n },\n\n page(query: PageQuery): RequestPage {\n const where = whereFor(query.filter);\n // A pinned request is one the reader deliberately set aside: it stays on\n // screen through a filter that would otherwise exclude it, exactly as it\n // does with the in-memory store.\n const matching = `((${where.sql}) OR pinned = 1)`;\n\n const order = orderColumn(query.sort);\n const cursor = decodeCursor(query.cursor);\n const position = cursor ? afterCursor(cursor, order) : null;\n const clause = position ? `${matching} AND ${position.sql}` : matching;\n const params = [...where.params, ...(position?.params ?? [])];\n\n // One row more than asked for: whether there is a next page is a fact,\n // not a guess from a full page.\n const rows = statement(\n `SELECT id, started_at, method, path, query_string, route, status, duration_ms,\n sql_count, http_count, n_plus_one, has_error, finding_count, flag, test,\n cpu_ms, cpu_share, pinned\n FROM requests WHERE ${clause}\n ORDER BY ${order} DESC, id DESC LIMIT ?`,\n ).all(...params, query.limit + 1) as unknown as StoredRow[];\n\n const page = rows.slice(0, query.limit);\n const last = page[page.length - 1];\n const nextCursor =\n rows.length > query.limit && last\n ? encodeCursor(order === 'duration_ms' ? last.duration_ms : last.started_at, last.id)\n : null;\n\n const counts = statement(\n `SELECT COUNT(*) AS total,\n SUM(CASE WHEN duration_ms >= ? THEN 1 ELSE 0 END) AS slow,\n SUM(CASE WHEN has_error = 1 THEN 1 ELSE 0 END) AS errors,\n SUM(CASE WHEN finding_count > 0 THEN 1 ELSE 0 END) AS with_findings\n FROM requests`,\n ).get(SLOW_MS) as\n | {\n total: number;\n slow: number | null;\n errors: number | null;\n with_findings: number | null;\n }\n | undefined;\n const shown = statement(`SELECT COUNT(*) AS shown FROM requests WHERE ${matching}`).get(\n ...where.params,\n ) as { shown: number } | undefined;\n\n const summary: RequestSummary = {\n shown: shown?.shown ?? 0,\n total: counts?.total ?? 0,\n slow: counts?.slow ?? 0,\n errors: counts?.errors ?? 0,\n withFindings: counts?.with_findings ?? 0,\n };\n\n return { rows: page.map(toRequestRow), nextCursor, summary };\n },\n\n durations(query: BaselineQuery): DurationSample[] {\n // No id to exclude means the whole route, which is what a chart wants;\n // an id that cannot match is how one statement serves both.\n return routeDurations\n .all(\n query.route,\n query.method,\n query.excludeId ?? '',\n query.from ?? 0,\n query.to ?? Number.MAX_SAFE_INTEGER,\n BASELINE_LIMIT,\n )\n .map((row) => ({\n durationMs: row['duration_ms'] as number,\n startedAt: row['started_at'] as number,\n hasError: row['has_error'] === 1,\n loopDelayMs: (row['loop_delay_ms'] as number | null) ?? null,\n }));\n },\n\n counts(query: { from: number; to: number }): RouteWindow[] {\n return routeCounts.all(query.from, query.to).map((row) => ({\n method: row['method'] as string,\n route: row['route'] as string,\n calls: row['calls'] as number,\n avgMs: row['avg_ms'] as number,\n }));\n },\n\n findings(query: FindingsQuery): FindingSamples {\n const rows = statement(\n `SELECT payload FROM requests\n WHERE finding_count > 0 AND started_at >= ? AND started_at <= ?\n ORDER BY started_at DESC LIMIT ?`,\n ).all(query.from ?? 0, query.to ?? Number.MAX_SAFE_INTEGER, FINDINGS_LIMIT);\n\n const samples = rows.flatMap((row) =>\n findingSamplesOf(JSON.parse(row['payload'] as string) as RecordedRequest),\n );\n return { samples, truncated: rows.length >= FINDINGS_LIMIT };\n },\n\n findingStates(): ReadonlyMap<string, FiledPatternState> {\n const states = new Map<string, FiledPatternState>();\n for (const row of statement('SELECT id, state FROM finding_states').all()) {\n const state = row['state'] as string;\n if (state === 'ack' || state === 'muted') states.set(row['id'] as string, state);\n }\n return states;\n },\n\n setFindingState(id: string, state: StoredPatternState): void {\n if (state === 'new') {\n statement('DELETE FROM finding_states WHERE id = ?').run(id);\n return;\n }\n statement(\n `INSERT INTO finding_states (id, state, updated_at) VALUES (?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET state = excluded.state, updated_at = excluded.updated_at`,\n ).run(id, state, Date.now());\n },\n\n history(query: HistoryQuery): HistorySamples {\n const where = whereFor(query.filter);\n // Thirteen columns rather than the payloads, and never more rows than\n // the ceiling: a period is a stretch of history, and a screen that\n // parses a week of JSON to draw one line is a screen nobody opens\n // twice. Newest first, so a truncated reading is the recent part of the\n // period rather than an arbitrary slice of it.\n const rows = statement(\n `SELECT started_at, duration_ms, has_error, sql_count, http_count, bytes_out,\n loop_delay_ms, finding_count, sql_ms, self_ms, method, route, flag\n FROM requests WHERE ${where.sql}\n ORDER BY started_at DESC LIMIT ?`,\n ).all(...where.params, HISTORY_LIMIT);\n\n const samples: HistorySample[] = rows.map((row) => ({\n startedAt: row['started_at'] as number,\n durationMs: row['duration_ms'] as number,\n hasError: row['has_error'] === 1,\n sqlCount: (row['sql_count'] as number | null) ?? 0,\n httpCount: (row['http_count'] as number | null) ?? 0,\n bytes: (row['bytes_out'] as number | null) ?? 0,\n loopDelayMs: (row['loop_delay_ms'] as number | null) ?? null,\n findingCount: (row['finding_count'] as number | null) ?? 0,\n sqlMs: (row['sql_ms'] as number | null) ?? null,\n selfMs: (row['self_ms'] as number | null) ?? null,\n method: row['method'] as string,\n route: row['route'] as string,\n flag: (row['flag'] as string | null) ?? null,\n }));\n\n return { samples, truncated: samples.length >= HISTORY_LIMIT };\n },\n\n timeSeries(): TimePoint[] {\n // Three columns rather than the payloads: the strip needs when, how\n // long and whether it failed, and reading a history's worth of JSON to\n // learn that would be the reason not to keep a history.\n return series.all(TIME_SERIES_LIMIT).map((row) => ({\n startedAt: row['started_at'] as number,\n durationMs: row['duration_ms'] as number,\n hasError: row['has_error'] === 1,\n }));\n },\n\n pin(id: string, pinned: boolean) {\n if (pinned) {\n const current = (countPinned.get() as { pinned: number } | undefined)?.pinned ?? 0;\n if (current >= pinLimit) return false;\n }\n const changed = setPinned.run(pinned ? 1 : 0, id).changes > 0;\n // A pin moves a row in or out of what the budget counts.\n if (changed) refreshTotals();\n return changed;\n },\n\n pinned() {\n return pinnedIds.all().map((row) => row['id'] as string);\n },\n\n stats(): SqliteStoreStats {\n const current = totals.get() as\n | { size: number; bytes: number; oldest: number | null }\n | undefined;\n return {\n size: current?.size ?? 0,\n capacity: limits().maxRequests,\n evicted,\n oldestAt: current?.oldest ?? null,\n pinned: (countPinned.get() as { pinned: number } | undefined)?.pinned ?? 0,\n bytes: current?.bytes ?? 0,\n };\n },\n\n clear() {\n removeAll.run();\n refreshTotals();\n },\n\n subscribe(listener: SqliteStoreListener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async close() {\n listeners.clear();\n prepared.clear();\n db.close();\n },\n };\n}\n\n/**\n * The retention policy, re-exported.\n *\n * Anyone keeping requests on disk installs this package; making them add\n * `@reqray/core` as well to say how long to keep them would be a dependency\n * for one function. It is the same object either way.\n */\nexport {\n type RetentionLimits,\n type RetentionOptions,\n type RetentionPolicy,\n retentionPolicy,\n} from '@reqray/core';\n","/**\n * The panel's filter, expressed as SQL.\n *\n * There are now two places that decide what \"matching\" means — this one and\n * `filterRequests` in the core, which the in-memory store and the browser\n * both use. Two implementations of one rule drift, so they are held together\n * by a test that runs the same cases through both stores and demands the same\n * ids back. Change the rule here and that test is where it will be caught.\n */\n\nimport type { Cursor, RequestFilter } from '@reqray/core/panel';\nimport type { RequestSort } from '@reqray/protocol';\n\n/** A WHERE fragment and the values it binds. */\nexport interface Where {\n readonly sql: string;\n readonly params: (string | number)[];\n}\n\n/** Escapes what SQLite's LIKE treats as wildcards. */\nfunction likeArgument(needle: string): string {\n return `%${needle.replace(/[\\\\%_]/g, (char) => `\\\\${char}`)}%`;\n}\n\n/**\n * Builds the WHERE clause for a filter.\n *\n * Always returns a usable fragment: an empty filter excludes nothing, so the\n * caller can concatenate without special cases.\n */\nexport function whereFor(filter: RequestFilter): Where {\n const clauses: string[] = ['1 = 1'];\n const params: (string | number)[] = [];\n\n if (filter.from !== undefined) {\n clauses.push('started_at >= ?');\n params.push(filter.from);\n }\n if (filter.to !== undefined) {\n clauses.push('started_at <= ?');\n params.push(filter.to);\n }\n\n const needle = filter.query?.trim().toLowerCase();\n if (needle) {\n // The same four fields the in-memory filter searches: method, path,\n // status as text, and the query string.\n clauses.push(\n \"(lower(method) LIKE ? ESCAPE '\\\\' OR lower(path) LIKE ? ESCAPE '\\\\' \" +\n \"OR CAST(status AS TEXT) LIKE ? ESCAPE '\\\\' \" +\n \"OR (query_string IS NOT NULL AND lower(query_string) LIKE ? ESCAPE '\\\\'))\",\n );\n const like = likeArgument(needle);\n params.push(like, like, like, like);\n }\n\n const methods = filter.methods?.filter(Boolean) ?? [];\n if (methods.length > 0) {\n clauses.push(`upper(method) IN (${methods.map(() => '?').join(', ')})`);\n params.push(...methods.map((method) => method.toUpperCase()));\n }\n\n const classes = filter.statusClasses?.filter((value) => Number.isFinite(value)) ?? [];\n if (classes.length > 0) {\n clauses.push(`(status / 100) IN (${classes.map(() => '?').join(', ')})`);\n params.push(...classes.map((value) => Math.floor(value)));\n }\n\n if (filter.minDurationMs !== undefined) {\n clauses.push('duration_ms >= ?');\n params.push(filter.minDurationMs);\n }\n\n if (filter.path) {\n clauses.push(\"lower(path) LIKE ? ESCAPE '\\\\'\");\n params.push(likeArgument(filter.path.toLowerCase()));\n }\n\n if (filter.status !== undefined) {\n clauses.push('status = ?');\n params.push(filter.status);\n }\n\n if (filter.minSql !== undefined) {\n clauses.push('sql_count >= ?');\n params.push(filter.minSql);\n }\n\n const flagged = filter.flagged?.filter(Boolean) ?? [];\n if (flagged.length > 0) {\n clauses.push(`flag IN (${flagged.map(() => '?').join(', ')})`);\n params.push(...flagged);\n }\n\n if (filter.test !== undefined) {\n clauses.push(\"test IS NOT NULL AND lower(test) LIKE ? ESCAPE '\\\\'\");\n params.push(likeArgument(filter.test.toLowerCase()));\n }\n\n if (filter.onlyFindings) clauses.push('finding_count > 0');\n if (filter.onlyNPlusOne) clauses.push('n_plus_one = 1');\n if (filter.onlyTests) clauses.push('test IS NOT NULL');\n if (filter.onlyErrors) clauses.push('has_error = 1');\n\n if (filter.route) {\n // The normalized route is stored per row rather than computed here: the\n // rule lives in the core and the browser bundle does not carry a copy,\n // and neither should the SQL.\n clauses.push('route = ? AND upper(method) = ?');\n params.push(filter.route.route, filter.route.method.toUpperCase());\n }\n\n return { sql: clauses.join(' AND '), params };\n}\n\n/** The column a page is ordered by. Not user input — one of these two. */\nexport type OrderColumn = 'started_at' | 'duration_ms';\n\n/** Which column each sort order reads. */\nexport function orderColumn(sort: RequestSort | undefined): OrderColumn {\n return sort === 'slowest' ? 'duration_ms' : 'started_at';\n}\n\n/**\n * The clause that continues from a cursor.\n *\n * The same rule `isAfterCursor` applies in memory, written for SQLite:\n * strictly past the cursor, with the id breaking ties, so a row is never\n * served twice and never skipped when several share a millisecond — or, when\n * the page is ordered by duration, share a duration.\n */\nexport function afterCursor(cursor: Cursor, column: OrderColumn = 'started_at'): Where {\n return {\n sql: `(${column} < ? OR (${column} = ? AND id < ?))`,\n params: [cursor.key, cursor.key, cursor.id],\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0BA,k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f,SAAG,MAAM;AAAA,IACX;AAAA,EACF;AACF;","names":["import_core","removed"]}
@@ -0,0 +1,105 @@
1
+ import { Transport, RetentionPolicy } from '@reqray/core';
2
+ export { RetentionLimits, RetentionOptions, RetentionPolicy, retentionPolicy } from '@reqray/core';
3
+ import { PageQuery, RequestPage, BaselineQuery, DurationSample, RouteWindow, TimePoint, HistoryQuery, HistorySamples, FindingsQuery, FindingSamples } from '@reqray/core/panel';
4
+ import { RecordedRequest, FiledPatternState, StoredPatternState } from '@reqray/protocol';
5
+
6
+ /**
7
+ * `@reqray/store-sqlite` — a request history that outlives the process.
8
+ *
9
+ * The in-memory ring is a buffer, not a history: it holds the last few
10
+ * hundred requests and forgets everything when the process restarts. This
11
+ * store writes to a file instead, so "what happened an hour ago" and "what
12
+ * did that request look like before yesterday's deploy" have answers.
13
+ *
14
+ * **`node:sqlite`, not a native driver.** Storage that needs a compiler at
15
+ * install time is storage most people will not turn on. Node ships SQLite
16
+ * since 22.5, which is what this package requires — one version above what
17
+ * the rest of Reqray asks for, and the reason it is a package of its own
18
+ * rather than a branch inside the memory store.
19
+ *
20
+ * **Retention is a promise about disk, not a hope.** Two budgets, whichever
21
+ * runs out first: a number of requests and a number of bytes. Beyond them the
22
+ * oldest go, except pinned ones — the whole point of a pin is that it is the
23
+ * request you are working on.
24
+ *
25
+ * Writes are synchronous and unbatched on purpose. `send()` is already called
26
+ * outside request handling, an insert costs single-digit microseconds, and a
27
+ * write queue would mean a request that the live feed has announced but the
28
+ * store cannot yet hand back.
29
+ */
30
+
31
+ /** Options for {@link sqliteTransport}. */
32
+ interface SqliteTransportOptions {
33
+ /**
34
+ * Database file. `:memory:` keeps it in the process, which is for tests —
35
+ * a history that dies with the process is what this package exists to fix.
36
+ */
37
+ readonly file: string;
38
+ /** How many requests to keep. Older ones are evicted. */
39
+ readonly maxRequests?: number;
40
+ /**
41
+ * The retention policy, shared with the log and with the panel.
42
+ *
43
+ * Given one, its limits win over the two below and a change made from the
44
+ * panel takes effect on the next eviction. Without one the numbers here are
45
+ * fixed for the life of the process.
46
+ */
47
+ readonly retention?: RetentionPolicy;
48
+ /** How much disk the payloads may take, bytes. */
49
+ readonly maxBytes?: number;
50
+ /** How many requests may be pinned at once. */
51
+ readonly pinLimit?: number;
52
+ /**
53
+ * How many records {@link SqliteStore.list} returns at most.
54
+ *
55
+ * The aggregate screens — routes, exceptions — and the exports read the
56
+ * store whole. On a history "whole" is unbounded, so they see the most
57
+ * recent slice instead, and this is its size.
58
+ */
59
+ readonly listLimit?: number;
60
+ }
61
+ /** Summary of what the store holds. */
62
+ interface SqliteStoreStats {
63
+ readonly size: number;
64
+ readonly capacity: number;
65
+ /** How many requests have been evicted since the store was opened. */
66
+ readonly evicted: number;
67
+ readonly oldestAt: number | null;
68
+ readonly pinned: number;
69
+ /** Bytes the stored payloads add up to. */
70
+ readonly bytes: number;
71
+ }
72
+ /** Listener for the panel's live feed. */
73
+ type SqliteStoreListener = (request: RecordedRequest) => void;
74
+ /** A transport that is also the store the panel reads from. */
75
+ interface SqliteStore extends Transport {
76
+ list(): RecordedRequest[];
77
+ get(id: string): RecordedRequest | undefined;
78
+ clear(): void;
79
+ stats(): SqliteStoreStats;
80
+ subscribe(listener: SqliteStoreListener): () => void;
81
+ pin(id: string, pinned: boolean): boolean;
82
+ pinned(): string[];
83
+ page(query: PageQuery): RequestPage;
84
+ /** Durations of other calls of one route, for the detail page's verdict. */
85
+ durations(query: BaselineQuery): DurationSample[];
86
+ /** Traffic grouped by route over a stretch of time. */
87
+ counts(query: {
88
+ from: number;
89
+ to: number;
90
+ }): RouteWindow[];
91
+ /** Three numbers per request, for the strip above the list. */
92
+ timeSeries(): TimePoint[];
93
+ /** A period's requests, a handful of numbers each, for the history screen. */
94
+ history(query: HistoryQuery): HistorySamples;
95
+ /** Finding occurrences over a stretch, one row each, for the findings tab. */
96
+ findings(query: FindingsQuery): FindingSamples;
97
+ /** `ack`/`muted` per pattern id — the part of the tab that must survive a restart. */
98
+ findingStates(): ReadonlyMap<string, FiledPatternState>;
99
+ /** Remembers a state; `new` forgets the pattern. */
100
+ setFindingState(id: string, state: StoredPatternState): void;
101
+ close(): Promise<void>;
102
+ }
103
+ declare function sqliteTransport(options: SqliteTransportOptions): SqliteStore;
104
+
105
+ export { type SqliteStore, type SqliteStoreListener, type SqliteStoreStats, type SqliteTransportOptions, sqliteTransport };
@@ -0,0 +1,105 @@
1
+ import { Transport, RetentionPolicy } from '@reqray/core';
2
+ export { RetentionLimits, RetentionOptions, RetentionPolicy, retentionPolicy } from '@reqray/core';
3
+ import { PageQuery, RequestPage, BaselineQuery, DurationSample, RouteWindow, TimePoint, HistoryQuery, HistorySamples, FindingsQuery, FindingSamples } from '@reqray/core/panel';
4
+ import { RecordedRequest, FiledPatternState, StoredPatternState } from '@reqray/protocol';
5
+
6
+ /**
7
+ * `@reqray/store-sqlite` — a request history that outlives the process.
8
+ *
9
+ * The in-memory ring is a buffer, not a history: it holds the last few
10
+ * hundred requests and forgets everything when the process restarts. This
11
+ * store writes to a file instead, so "what happened an hour ago" and "what
12
+ * did that request look like before yesterday's deploy" have answers.
13
+ *
14
+ * **`node:sqlite`, not a native driver.** Storage that needs a compiler at
15
+ * install time is storage most people will not turn on. Node ships SQLite
16
+ * since 22.5, which is what this package requires — one version above what
17
+ * the rest of Reqray asks for, and the reason it is a package of its own
18
+ * rather than a branch inside the memory store.
19
+ *
20
+ * **Retention is a promise about disk, not a hope.** Two budgets, whichever
21
+ * runs out first: a number of requests and a number of bytes. Beyond them the
22
+ * oldest go, except pinned ones — the whole point of a pin is that it is the
23
+ * request you are working on.
24
+ *
25
+ * Writes are synchronous and unbatched on purpose. `send()` is already called
26
+ * outside request handling, an insert costs single-digit microseconds, and a
27
+ * write queue would mean a request that the live feed has announced but the
28
+ * store cannot yet hand back.
29
+ */
30
+
31
+ /** Options for {@link sqliteTransport}. */
32
+ interface SqliteTransportOptions {
33
+ /**
34
+ * Database file. `:memory:` keeps it in the process, which is for tests —
35
+ * a history that dies with the process is what this package exists to fix.
36
+ */
37
+ readonly file: string;
38
+ /** How many requests to keep. Older ones are evicted. */
39
+ readonly maxRequests?: number;
40
+ /**
41
+ * The retention policy, shared with the log and with the panel.
42
+ *
43
+ * Given one, its limits win over the two below and a change made from the
44
+ * panel takes effect on the next eviction. Without one the numbers here are
45
+ * fixed for the life of the process.
46
+ */
47
+ readonly retention?: RetentionPolicy;
48
+ /** How much disk the payloads may take, bytes. */
49
+ readonly maxBytes?: number;
50
+ /** How many requests may be pinned at once. */
51
+ readonly pinLimit?: number;
52
+ /**
53
+ * How many records {@link SqliteStore.list} returns at most.
54
+ *
55
+ * The aggregate screens — routes, exceptions — and the exports read the
56
+ * store whole. On a history "whole" is unbounded, so they see the most
57
+ * recent slice instead, and this is its size.
58
+ */
59
+ readonly listLimit?: number;
60
+ }
61
+ /** Summary of what the store holds. */
62
+ interface SqliteStoreStats {
63
+ readonly size: number;
64
+ readonly capacity: number;
65
+ /** How many requests have been evicted since the store was opened. */
66
+ readonly evicted: number;
67
+ readonly oldestAt: number | null;
68
+ readonly pinned: number;
69
+ /** Bytes the stored payloads add up to. */
70
+ readonly bytes: number;
71
+ }
72
+ /** Listener for the panel's live feed. */
73
+ type SqliteStoreListener = (request: RecordedRequest) => void;
74
+ /** A transport that is also the store the panel reads from. */
75
+ interface SqliteStore extends Transport {
76
+ list(): RecordedRequest[];
77
+ get(id: string): RecordedRequest | undefined;
78
+ clear(): void;
79
+ stats(): SqliteStoreStats;
80
+ subscribe(listener: SqliteStoreListener): () => void;
81
+ pin(id: string, pinned: boolean): boolean;
82
+ pinned(): string[];
83
+ page(query: PageQuery): RequestPage;
84
+ /** Durations of other calls of one route, for the detail page's verdict. */
85
+ durations(query: BaselineQuery): DurationSample[];
86
+ /** Traffic grouped by route over a stretch of time. */
87
+ counts(query: {
88
+ from: number;
89
+ to: number;
90
+ }): RouteWindow[];
91
+ /** Three numbers per request, for the strip above the list. */
92
+ timeSeries(): TimePoint[];
93
+ /** A period's requests, a handful of numbers each, for the history screen. */
94
+ history(query: HistoryQuery): HistorySamples;
95
+ /** Finding occurrences over a stretch, one row each, for the findings tab. */
96
+ findings(query: FindingsQuery): FindingSamples;
97
+ /** `ack`/`muted` per pattern id — the part of the tab that must survive a restart. */
98
+ findingStates(): ReadonlyMap<string, FiledPatternState>;
99
+ /** Remembers a state; `new` forgets the pattern. */
100
+ setFindingState(id: string, state: StoredPatternState): void;
101
+ close(): Promise<void>;
102
+ }
103
+ declare function sqliteTransport(options: SqliteTransportOptions): SqliteStore;
104
+
105
+ export { type SqliteStore, type SqliteStoreListener, type SqliteStoreStats, type SqliteTransportOptions, sqliteTransport };