From 9ce9b1e2e4bc216e622d4cd333f84049c06a917f Mon Sep 17 00:00:00 2001 From: IVANLI2412 Date: Tue, 24 Nov 2026 03:36:58 -0300 Subject: [PATCH] feat(db): add per-tenant SQL query budget with slow-query classification (fixes #2270) --- backend/src/lib/__tests__/db.test.ts | 155 +++++ backend/src/lib/__tests__/queryBudget.test.ts | 280 +++++++++ backend/src/lib/db.ts | 188 ++++++ backend/src/lib/queryBudget.ts | 570 ++++++++++++++++++ 4 files changed, 1193 insertions(+) create mode 100644 backend/src/lib/__tests__/db.test.ts create mode 100644 backend/src/lib/__tests__/queryBudget.test.ts create mode 100644 backend/src/lib/db.ts create mode 100644 backend/src/lib/queryBudget.ts diff --git a/backend/src/lib/__tests__/db.test.ts b/backend/src/lib/__tests__/db.test.ts new file mode 100644 index 00000000..2851119a --- /dev/null +++ b/backend/src/lib/__tests__/db.test.ts @@ -0,0 +1,155 @@ +/** + * backend/src/lib/__tests__/db.test.ts + * + * Integration tests for the budgeted query runner adapter (issue #2270). + * The executor is injected, so these tests need no database and remain fully + * deterministic via the budget's injected clock. + */ + +import { createQueryBudget, QueryBudgetError } from '../queryBudget'; +import { createBudgetedQueryRunner } from '../db'; + +describe('createBudgetedQueryRunner options', () => { + it('rejects a missing budget controller', () => { + expect(() => createBudgetedQueryRunner({} as any)).toThrow(QueryBudgetError); + }); + + it('rejects a missing executor', () => { + const budget = createQueryBudget(); + expect(() => createBudgetedQueryRunner({ budget } as any)).toThrow(QueryBudgetError); + }); +}); + +describe('budgeted query execution', () => { + let clock = 2000; + let calls = 0; + let receivedSql = ''; + let receivedParams: readonly unknown[] | undefined; + const budget = createQueryBudget({ + maxQueriesPerWindow: 1, + windowMs: 100, + slowQueryThresholdMs: 20, + criticalQueryThresholdMs: 100, + nowMs: () => clock, + }); + const executed: string[] = []; + const failed: string[] = []; + const runner = createBudgetedQueryRunner({ + budget, + execute: async (sql, params) => { + calls++; + receivedSql = sql; + receivedParams = params; + return { rows: [{ id: 1 }, { id: 2 }], rowCount: 2 }; + }, + metrics: { + recordQueryExecuted: () => { executed.push('done'); }, + recordQueryFailed: () => { failed.push('failed'); }, + }, + }); + + it('exposes the underlying budget controller', () => { + expect(runner.budget).toBe(budget); + }); + + it('executes the query and returns the driver result', async () => { + const result = await runner.run<{ rowCount: number }>('t1', 'SELECT * FROM t', [42]); + expect(result.rowCount).toBe(2); + expect(calls).toBe(1); + expect(receivedSql).toBe('SELECT * FROM t'); + expect(receivedParams[0]).toBe(42); + }); + + it('emits execution metrics and records the classified query', () => { + expect(executed).toContain('done'); + expect(budget.snapshot('t1').used).toBe(1); + expect(budget.snapshot('t1').records[0].rowsScanned).toBe(2); + }); + + it('throws BUDGET_EXCEEDED before executing another query for the tenant', async () => { + await expect(runner.run('t1', 'SELECT 2')).rejects.toThrow(QueryBudgetError); + expect(calls).toBe(1); + }); + + it('rejects invalid tenants and SQL before executing', async () => { + await expect(runner.run('', 'SELECT 1')).rejects.toThrow(QueryBudgetError); + await expect(runner.run('t2', ' ')).rejects.toThrow(QueryBudgetError); + expect(calls).toBe(1); + }); + + it('allows a fresh tenant after the window expires', async () => { + clock = 2200; + await runner.run('t3', 'SELECT 3'); + expect(calls).toBe(2); + }); + + it('reset returns void', async () => { + await expect(runner.budget.reset('t3')).resolves.toBeUndefined(); + }); +}); + +describe('adapter failure modes', () => { + it('propagates executor errors without recording a query', async () => { + let clock = 100; + let calls = 0; + const budget = createQueryBudget({ maxQueriesPerWindow: 5, nowMs: () => clock }); + const failures: string[] = []; + const runner = createBudgetedQueryRunner({ + budget, + execute: async () => { + calls++; + throw new Error('db down'); + }, + metrics: { + recordQueryFailed: (_tenantId, _sql, code) => { failures.push(code); }, + }, + }); + + await expect(runner.run('t4', 'SELECT 1')).rejects.toThrow(Error); + expect(calls).toBe(1); + expect(failures).toContain('EXECUTION_ERROR'); + expect(budget.snapshot('t4').used).toBe(0); + }); + + it('uses the injected clock for query duration and classification', async () => { + let clock = 10; + const budget = createQueryBudget({ + maxQueriesPerWindow: 5, + slowQueryThresholdMs: 5, + criticalQueryThresholdMs: 50, + nowMs: () => clock, + }); + const runner = createBudgetedQueryRunner({ + budget, + execute: async () => { + clock += 100; + return []; + }, + }); + await runner.run('t5', 'SELECT 1'); + const record = budget.snapshot('t5').records[0]; + expect(record.durationMs).toBe(100); + expect(record.classification).toBe('CRITICAL'); + }); + + it('honours a custom rows-scanned extractor', async () => { + const budget = createQueryBudget({ maxQueriesPerWindow: 5, nowMs: () => 1 }); + const runner = createBudgetedQueryRunner({ + budget, + execute: async () => ({ scanned: 77 }), + extractRowsScanned: (result) => (result as { scanned: number }).scanned, + }); + await runner.run('t6', 'SELECT 1'); + expect(budget.snapshot('t6').records[0].rowsScanned).toBe(77); + }); + + it('falls back to rowCount when no custom extractor is supplied', async () => { + const budget = createQueryBudget({ maxQueriesPerWindow: 5, nowMs: () => 1 }); + const runner = createBudgetedQueryRunner({ + budget, + execute: async () => ({ rowCount: 9 }), + }); + await runner.run('t7', 'SELECT 1'); + expect(budget.snapshot('t7').records[0].rowsScanned).toBe(9); + }); +}); diff --git a/backend/src/lib/__tests__/queryBudget.test.ts b/backend/src/lib/__tests__/queryBudget.test.ts new file mode 100644 index 00000000..7870ccf0 --- /dev/null +++ b/backend/src/lib/__tests__/queryBudget.test.ts @@ -0,0 +1,280 @@ +/** + * backend/src/lib/__tests__/queryBudget.test.ts + * + * Unit tests for the per-tenant SQL query budget engine (issue #2270). + * Every documented behaviour — defaults, validation, classification, sliding + * window, per-tenant isolation, failure modes and observability — is pinned. + */ + +import { + QueryBudgetErrorCode, + QueryClassification, + QueryBudgetError, + DEFAULT_QUERY_BUDGET_CONFIG, + validateQueryBudgetConfig, + classifyQuery, + createQueryBudget, +} from '../queryBudget'; + +/** Assert that `fn` throws a QueryBudgetError carrying the expected stable code. */ +function expectCode(fn: () => unknown, code: string): void { + try { + fn(); + throw new Error('expected function to throw'); + } catch (error) { + expect((error as { code?: string }).code).toBe(code); + } +} + +describe('error surface and constants', () => { + it('exposes stable error codes', () => { + expect(QueryBudgetErrorCode.INVALID_CONFIG).toBe('INVALID_CONFIG'); + expect(QueryBudgetErrorCode.INVALID_TENANT).toBe('INVALID_TENANT'); + expect(QueryBudgetErrorCode.INVALID_QUERY).toBe('INVALID_QUERY'); + expect(QueryBudgetErrorCode.BUDGET_EXCEEDED).toBe('BUDGET_EXCEEDED'); + }); + + it('exposes stable classification values', () => { + expect(QueryClassification.FAST).toBe('FAST'); + expect(QueryClassification.SLOW).toBe('SLOW'); + expect(QueryClassification.CRITICAL).toBe('CRITICAL'); + }); + + it('builds a typed QueryBudgetError with code and details', () => { + const error = new QueryBudgetError( + QueryBudgetErrorCode.BUDGET_EXCEEDED, + 'over budget', + { tenantId: 'acme' } + ); + expect(error instanceof Error).toBe(true); + expect(error.name).toBe('QueryBudgetError'); + expect(error.code).toBe('BUDGET_EXCEEDED'); + expect(error.message).toBe('over budget'); + expect(error.details).toEqual({ tenantId: 'acme' }); + }); +}); + +describe('validateQueryBudgetConfig', () => { + it('fills in documented defaults', () => { + const config = validateQueryBudgetConfig({}); + expect(config.maxQueriesPerWindow).toBe(100); + expect(config.windowMs).toBe(60000); + expect(config.slowQueryThresholdMs).toBe(200); + expect(config.criticalQueryThresholdMs).toBe(1000); + expect(config.slowRowThreshold).toBe(10000); + expect(config.criticalRowThreshold).toBe(100000); + expect(typeof config.nowMs).toBe('function'); + expect(DEFAULT_QUERY_BUDGET_CONFIG.maxQueriesPerWindow).toBe(100); + }); + + it('preserves valid overrides and a custom clock', () => { + const clock = () => 42; + const config = validateQueryBudgetConfig({ + maxQueriesPerWindow: 3, + windowMs: 500, + nowMs: clock, + }); + expect(config.maxQueriesPerWindow).toBe(3); + expect(config.windowMs).toBe(500); + expect(config.nowMs()).toBe(42); + }); + + it('rejects a non-positive or fractional max', () => { + expectCode(() => validateQueryBudgetConfig({ maxQueriesPerWindow: 0 }), 'INVALID_CONFIG'); + expectCode(() => validateQueryBudgetConfig({ maxQueriesPerWindow: 1.5 }), 'INVALID_CONFIG'); + }); + + it('rejects an invalid window', () => { + expectCode(() => validateQueryBudgetConfig({ windowMs: -5 }), 'INVALID_CONFIG'); + }); + + it('requires critical thresholds to exceed slow thresholds', () => { + expectCode( + () => validateQueryBudgetConfig({ slowQueryThresholdMs: 500, criticalQueryThresholdMs: 300 }), + 'INVALID_CONFIG' + ); + expectCode( + () => validateQueryBudgetConfig({ slowRowThreshold: 10, criticalRowThreshold: 10 }), + 'INVALID_CONFIG' + ); + }); + + it('rejects non-finite thresholds and non-object configs', () => { + expectCode(() => validateQueryBudgetConfig({ slowQueryThresholdMs: NaN }), 'INVALID_CONFIG'); + expectCode(() => validateQueryBudgetConfig(null), 'INVALID_CONFIG'); + }); +}); + +describe('classifyQuery', () => { + const config = { + slowQueryThresholdMs: 100, + criticalQueryThresholdMs: 500, + slowRowThreshold: 1000, + criticalRowThreshold: 5000, + }; + + it('classifies cheap queries as FAST', () => { + expect(classifyQuery(10, 10, config)).toBe('FAST'); + expect(classifyQuery(99, 999, config)).toBe('FAST'); + }); + + it('classifies at the duration boundaries', () => { + expect(classifyQuery(100, 0, config)).toBe('SLOW'); + expect(classifyQuery(500, 0, config)).toBe('CRITICAL'); + }); + + it('classifies at the rows-scanned boundaries', () => { + expect(classifyQuery(0, 1000, config)).toBe('SLOW'); + expect(classifyQuery(0, 5000, config)).toBe('CRITICAL'); + }); + + it('lets the most severe signal win', () => { + expect(classifyQuery(200, 6000, config)).toBe('CRITICAL'); + }); + + it('defaults rowsScanned to zero', () => { + expect(classifyQuery(5)).toBe('FAST'); + }); + + it('rejects invalid measurements', () => { + expectCode(() => classifyQuery(-1, 0, config), 'INVALID_QUERY'); + expectCode(() => classifyQuery(NaN, 0, config), 'INVALID_QUERY'); + expectCode(() => classifyQuery(1, -5, config), 'INVALID_QUERY'); + }); +}); + +describe('createQueryBudget', () => { + let clock = 1000; + const config = { + maxQueriesPerWindow: 2, + windowMs: 100, + slowQueryThresholdMs: 50, + criticalQueryThresholdMs: 200, + nowMs: () => clock, + }; + const budget = createQueryBudget(config); + + it('reports the initial window state', () => { + const result = budget.check('tenant-a'); + expect(result.allowed).toBe(true); + expect(result.used).toBe(0); + expect(result.limit).toBe(2); + expect(result.remaining).toBe(2); + expect(result.windowResetAtMs).toBe(1100); + expect(budget.now()).toBe(1000); + }); + + it('records and classifies a query sample', () => { + clock = 1010; + const record = budget.record('tenant-a', { + sql: 'SELECT 1', + durationMs: 60, + rowsScanned: 5, + }); + expect(record.tenantId).toBe('tenant-a'); + expect(record.timestampMs).toBe(1010); + expect(record.classification).toBe('SLOW'); + expect(record.rowsScanned).toBe(5); + }); + + it('exposes classified counts via snapshot', () => { + clock = 1020; + budget.record('tenant-a', { durationMs: 300, rowsScanned: 2000 }); + const state = budget.snapshot('tenant-a'); + expect(state.used).toBe(2); + expect(state.slowCount).toBe(1); + expect(state.criticalCount).toBe(1); + expect(state.fastCount).toBe(0); + expect(state.records).toContain(state.records[0]); + }); + + it('isolates tenants from each other', () => { + expect(budget.check('tenant-b').used).toBe(0); + expect(budget.snapshot('tenant-a').used).toBe(2); + }); + + it('denies a check once the window is full', () => { + const denied = budget.check('tenant-a'); + expect(denied.allowed).toBe(false); + expect(denied.reason).toBe('BUDGET_EXCEEDED'); + expect(denied.remaining).toBe(0); + }); + + it('leaves enforcement to the caller (record does not self-enforce)', () => { + budget.record('tenant-a', { durationMs: 1 }); + expect(budget.snapshot('tenant-a').used).toBe(3); + }); + + it('prunes expired samples and re-allows the tenant', () => { + expect(budget.prune()).toBe(0); + clock = 1200; + expect(budget.prune()).toBe(3); + expect(budget.check('tenant-a').allowed).toBe(true); + expect(budget.prune(5000)).toBe(0); + }); + + it('resets one tenant without touching others', () => { + budget.record('tenant-a', { durationMs: 1 }); + budget.record('tenant-b', { durationMs: 1 }); + budget.reset('tenant-a'); + expect(budget.snapshot('tenant-a').used).toBe(0); + expect(budget.snapshot('tenant-b').used).toBe(1); + }); + + it('rejects invalid tenants and samples', () => { + expectCode(() => budget.check(''), 'INVALID_TENANT'); + expectCode(() => budget.check(' '), 'INVALID_TENANT'); + expectCode(() => budget.record('tenant-a', {}), 'INVALID_QUERY'); + expectCode(() => budget.record('tenant-a', { durationMs: 1, rowsScanned: -1 }), 'INVALID_QUERY'); + expectCode(() => budget.record('tenant-a', { durationMs: 1, sql: 123 }), 'INVALID_QUERY'); + expectCode(() => createQueryBudget({ maxQueriesPerWindow: 0 }), 'INVALID_CONFIG'); + }); +}); + +describe('observability hooks', () => { + it('emits metrics and warnings for budget decisions and classifications', () => { + const counts = { + accepted: 0, rejected: 0, recorded: 0, slow: 0, + critical: 0, reset: 0, pruned: 0, + }; + const warnings: string[] = []; + let clock = 500; + const budget = createQueryBudget( + { + maxQueriesPerWindow: 1, + windowMs: 10, + slowQueryThresholdMs: 10, + criticalQueryThresholdMs: 100, + nowMs: () => clock, + }, + { + recordQueryAccepted: () => { counts.accepted++; }, + recordQueryRejected: () => { counts.rejected++; }, + recordQueryRecorded: () => { counts.recorded++; }, + recordSlowQuery: () => { counts.slow++; }, + recordCriticalQuery: () => { counts.critical++; }, + recordBudgetReset: () => { counts.reset++; }, + recordBudgetPruned: () => { counts.pruned++; }, + }, + { warn: (message) => { warnings.push(message); } } + ); + + budget.check('obs'); + expect(counts.accepted).toBe(1); + budget.record('obs', { durationMs: 20 }); + budget.record('obs', { durationMs: 200 }); + expect(counts.recorded).toBe(2); + expect(counts.slow).toBe(1); + expect(counts.critical).toBe(1); + expect(warnings.length).toBe(2); + expect(warnings[1]).toContain('critical'); + budget.check('obs'); + expect(counts.rejected).toBe(1); + expect(warnings.length).toBe(3); + clock = 600; + budget.prune(); + expect(counts.pruned).toBe(1); + budget.reset('obs'); + expect(counts.reset).toBe(1); + }); +}); diff --git a/backend/src/lib/db.ts b/backend/src/lib/db.ts new file mode 100644 index 00000000..a7cf0623 --- /dev/null +++ b/backend/src/lib/db.ts @@ -0,0 +1,188 @@ +/** + * backend/src/lib/db.ts + * + * Thin database adapter that wires the pure per-tenant budget engine + * (`queryBudget.ts`) into a query runner (issue #2270). + * + * This module deliberately imports no database driver. It accepts an injected + * `execute` function, so the same policy works for Postgres, SQLite, a mock or + * any future transport. Ordering is strict: + * + * 1. validate tenant + SQL + * 2. `budget.check(tenantId)` — reject before touching the database + * 3. time `execute(sql, params)` + * 4. `budget.record(...)` — classify and store the completed sample + * 5. emit adapter-level metrics/logs for the user-visible execution + * + * Usage: + * const runner = createBudgetedQueryRunner({ budget, execute: pool.query }); + * const rows = await runner.run('tenant-a', 'SELECT * FROM subscriptions'); + */ + +import { + QueryBudgetError, + QueryBudgetErrorCode, + noopQueryBudgetMetrics, + noopQueryBudgetLogger, + type QueryBudgetController, + type QueryBudgetMetrics, + type QueryBudgetLogger, + type QueryClassification, +} from './queryBudget.ts'; + +/** Options for {@link createBudgetedQueryRunner}. */ +export interface BudgetedQueryRunnerOptions { + /** Budget controller used for pre-flight checks and post-execution recording. */ + budget: QueryBudgetController; + /** Injected query executor. Receives SQL and optional bind parameters. */ + execute: (sql: string, params?: readonly unknown[]) => Promise; + /** Optional metrics sink; missing methods fall back to no-ops. */ + metrics?: Partial; + /** Optional logger sink; missing methods fall back to no-ops. */ + logger?: Partial; + /** + * Optional extractor for the rows-scanned signal. When omitted, common result + * shapes (`rowsScanned`, `rowCount`, `rows[]`, plain arrays) are inspected. + */ + extractRowsScanned?: (result: unknown) => number; +} + +/** Budgeted query runner returned by {@link createBudgetedQueryRunner}. */ +export interface BudgetedQueryRunner { + /** Run one query for a tenant, enforcing the budget before execution. */ + run(tenantId: string, sql: string, params?: readonly unknown[]): Promise; + /** The underlying budget controller (useful for snapshots / reset in tests). */ + readonly budget: QueryBudgetController; +} + +/** Best-effort extraction of a rows-scanned count from a driver result. */ +function defaultExtractRowsScanned(result: unknown): number { + if (Array.isArray(result)) { + return result.length; + } + if (result !== null && typeof result === 'object') { + const candidate = result as { + rowsScanned?: unknown; + rowCount?: unknown; + rows?: unknown; + }; + if (typeof candidate.rowsScanned === 'number' && Number.isFinite(candidate.rowsScanned)) { + return Math.max(0, candidate.rowsScanned); + } + if (typeof candidate.rowCount === 'number' && Number.isFinite(candidate.rowCount)) { + return Math.max(0, candidate.rowCount); + } + if (Array.isArray(candidate.rows)) { + return candidate.rows.length; + } + } + return 0; +} + +/** + * Create a budgeted query runner around an injected executor. + * + * @throws `QueryBudgetError(INVALID_CONFIG)` if the runner options are invalid. + */ +export function createBudgetedQueryRunner( + options: BudgetedQueryRunnerOptions +): BudgetedQueryRunner { + if ( + options === null || + typeof options !== 'object' || + !options.budget || + typeof options.budget.check !== 'function' || + typeof options.budget.record !== 'function' || + typeof options.budget.now !== 'function' + ) { + throw new QueryBudgetError( + QueryBudgetErrorCode.INVALID_CONFIG, + 'a valid budget controller is required', + { option: 'budget' } + ); + } + if (typeof options.execute !== 'function') { + throw new QueryBudgetError( + QueryBudgetErrorCode.INVALID_CONFIG, + 'execute must be a function', + { option: 'execute' } + ); + } + + const budget = options.budget; + const execute = options.execute; + const extract = options.extractRowsScanned ?? defaultExtractRowsScanned; + const metrics: QueryBudgetMetrics = { + ...noopQueryBudgetMetrics, + ...(options.metrics ?? {}), + }; + const logger: QueryBudgetLogger = { + ...noopQueryBudgetLogger, + ...(options.logger ?? {}), + }; + + async function run( + tenantId: string, + sql: string, + params?: readonly unknown[] + ): Promise { + if (typeof sql !== 'string' || sql.trim().length === 0) { + throw new QueryBudgetError( + QueryBudgetErrorCode.INVALID_QUERY, + 'sql must be a non-empty string', + { tenantId, sql } + ); + } + + // Budget gate — check validates the tenant id and emits its own hooks. + const decision = budget.check(tenantId); + if (!decision.allowed) { + throw new QueryBudgetError( + QueryBudgetErrorCode.BUDGET_EXCEEDED, + `SQL query budget exceeded for tenant "${tenantId}"`, + { + tenantId, + used: decision.used, + limit: decision.limit, + windowResetAtMs: decision.windowResetAtMs, + reason: decision.reason, + } + ); + } + + const startedAt = budget.now(); + let result: unknown; + try { + result = await execute(sql, params); + } catch (error) { + const code = + error instanceof QueryBudgetError ? error.code : 'EXECUTION_ERROR'; + metrics.recordQueryFailed(tenantId, sql, code); + logger.warn('budgeted query execution failed', { tenantId, sql, code }); + throw error; + } + + const durationMs = Math.max(0, budget.now() - startedAt); + const rowsScanned = extract(result); + const entry = budget.record(tenantId, { sql, durationMs, rowsScanned }); + const classification: QueryClassification = entry.classification; + + metrics.recordQueryExecuted( + tenantId, + sql, + durationMs, + classification, + rowsScanned + ); + logger.info('budgeted query executed', { + tenantId, + classification, + durationMs, + rowsScanned, + }); + + return result as T; + } + + return Object.freeze({ run, budget }); +} diff --git a/backend/src/lib/queryBudget.ts b/backend/src/lib/queryBudget.ts new file mode 100644 index 00000000..5720827c --- /dev/null +++ b/backend/src/lib/queryBudget.ts @@ -0,0 +1,570 @@ +/** + * backend/src/lib/queryBudget.ts + * + * Per-tenant SQL query budget with slow-query auto-classification (issue #2270). + * + * This module is a zero-dependency, side-effect-free budget engine. It performs + * no I/O, opens no connections and reads no ambient state other than an + * injectable clock. Its purpose is to make the *policy* decision — "may this + * tenant run another query right now, and how expensive was the last one?" — + * fully deterministic and unit-testable without a database. + * + * Design rules: + * - Pure data in, pure data out. The controller keeps state in memory only. + * - Every rejection is a typed `QueryBudgetError` with a stable `code`. + * - A fixed-size sliding window is tracked per tenant; expired samples are + * pruned lazily on check/record/snapshot and can be pruned eagerly. + * - Queries are auto-classified as FAST / SLOW / CRITICAL from duration and + * rows-scanned thresholds. + * - Metrics and logger hooks are optional; no-op defaults are provided. + * + * Usage: + * const budget = createQueryBudget({ maxQueriesPerWindow: 10, windowMs: 60_000 }); + * const decision = budget.check('tenant-a'); + * if (!decision.allowed) throw new QueryBudgetError('BUDGET_EXCEEDED', '...'); + * budget.record('tenant-a', { sql: 'SELECT 1', durationMs: 12, rowsScanned: 1 }); + */ + +// --------------------------------------------------------------------------- +// Error surface +// --------------------------------------------------------------------------- + +/** Stable machine-readable codes emitted by this module. */ +export const QueryBudgetErrorCode = { + INVALID_CONFIG: 'INVALID_CONFIG', + INVALID_TENANT: 'INVALID_TENANT', + INVALID_QUERY: 'INVALID_QUERY', + BUDGET_EXCEEDED: 'BUDGET_EXCEEDED', +} as const; + +/** Union of every stable error code emitted by this module. */ +export type QueryBudgetErrorCode = + (typeof QueryBudgetErrorCode)[keyof typeof QueryBudgetErrorCode]; + +/** Typed error thrown for invalid configuration, invalid input and budget denial. */ +export class QueryBudgetError extends Error { + readonly code: QueryBudgetErrorCode; + readonly details: Readonly>; + + constructor( + code: QueryBudgetErrorCode, + message: string, + details: Readonly> = {} + ) { + super(message); + this.name = 'QueryBudgetError'; + this.code = code; + this.details = details; + } +} + +// --------------------------------------------------------------------------- +// Classification +// --------------------------------------------------------------------------- + +/** Query cost classes, ordered from cheapest to most expensive. */ +export const QueryClassification = { + FAST: 'FAST', + SLOW: 'SLOW', + CRITICAL: 'CRITICAL', +} as const; + +/** Union of the supported query cost classes. */ +export type QueryClassification = + (typeof QueryClassification)[keyof typeof QueryClassification]; + +// --------------------------------------------------------------------------- +// Configuration and data types +// --------------------------------------------------------------------------- + +/** + * Fully resolved budget configuration. Callers normally supply a `Partial` of + * this shape to {@link createQueryBudget}; defaults are filled in by + * {@link validateQueryBudgetConfig}. + */ +export interface QueryBudgetConfig { + /** Maximum number of recorded queries allowed per tenant inside one window. */ + maxQueriesPerWindow: number; + /** Length of the sliding window in milliseconds. */ + windowMs: number; + /** Duration at or above which a query is SLOW (ms). */ + slowQueryThresholdMs: number; + /** Duration at or above which a query is CRITICAL (ms). */ + criticalQueryThresholdMs: number; + /** Rows scanned at or above which a query is SLOW. */ + slowRowThreshold: number; + /** Rows scanned at or above which a query is CRITICAL. */ + criticalRowThreshold: number; + /** Injectable clock; defaults to `Date.now`. Enables deterministic tests. */ + nowMs: () => number; +} + +/** Input sample describing a single executed query. */ +export interface QuerySample { + /** Optional SQL text, kept for observability only (never executed here). */ + readonly sql?: string; + /** Wall-clock duration of the query in milliseconds. */ + readonly durationMs: number; + /** Number of rows examined by the query. Defaults to 0. */ + readonly rowsScanned?: number; +} + +/** Immutable record stored in a tenant's sliding window. */ +export interface QueryRecord { + readonly tenantId: string; + readonly sql?: string; + readonly timestampMs: number; + readonly durationMs: number; + readonly rowsScanned: number; + readonly classification: QueryClassification; +} + +/** Read-only view of a tenant's current budget state. */ +export interface TenantBudgetState { + readonly tenantId: string; + readonly records: readonly QueryRecord[]; + readonly used: number; + readonly limit: number; + readonly fastCount: number; + readonly slowCount: number; + readonly criticalCount: number; + readonly windowStartMs: number; + readonly windowEndMs: number; +} + +/** Result of a pre-flight budget check for one tenant. */ +export interface BudgetCheckResult { + readonly allowed: boolean; + readonly tenantId: string; + readonly used: number; + readonly limit: number; + readonly remaining: number; + /** Earliest timestamp at which a currently-recorded sample leaves the window. */ + readonly windowResetAtMs: number; + /** Set to `BUDGET_EXCEEDED` when `allowed` is false. */ + readonly reason?: QueryBudgetErrorCode; +} + +/** Optional observability hook for budget decisions and query classification. */ +export interface QueryBudgetMetrics { + recordQueryAccepted(tenantId: string, used: number, limit: number): void; + recordQueryRejected(tenantId: string, used: number, limit: number, reason: QueryBudgetErrorCode): void; + recordQueryRecorded(tenantId: string, classification: QueryClassification, durationMs: number, rowsScanned: number): void; + recordSlowQuery(tenantId: string, durationMs: number, rowsScanned: number): void; + recordCriticalQuery(tenantId: string, durationMs: number, rowsScanned: number): void; + recordBudgetReset(tenantId: string): void; + recordBudgetPruned(tenantCount: number, recordCount: number): void; + /** Emitted by the database adapter layer (see `db.ts`). */ + recordQueryExecuted(tenantId: string, sql: string, durationMs: number, classification: QueryClassification, rowsScanned: number): void; + /** Emitted by the database adapter layer when the underlying runner throws. */ + recordQueryFailed(tenantId: string, sql: string, errorCode: string): void; +} + +/** Optional logging hook for user-visible budget and slow-query events. */ +export interface QueryBudgetLogger { + warn(message: string, details: Record): void; + info(message: string, details: Record): void; +} + +/** Default thresholds used when a caller omits configuration values. */ +export const DEFAULT_QUERY_BUDGET_CONFIG: QueryBudgetConfig = Object.freeze({ + maxQueriesPerWindow: 100, + windowMs: 60_000, + slowQueryThresholdMs: 200, + criticalQueryThresholdMs: 1_000, + slowRowThreshold: 10_000, + criticalRowThreshold: 100_000, + nowMs: Date.now, +}); + +/** No-op metrics implementation, safe to use in tests and development. */ +export const noopQueryBudgetMetrics: QueryBudgetMetrics = Object.freeze({ + recordQueryAccepted: () => {}, + recordQueryRejected: () => {}, + recordQueryRecorded: () => {}, + recordSlowQuery: () => {}, + recordCriticalQuery: () => {}, + recordBudgetReset: () => {}, + recordBudgetPruned: () => {}, + recordQueryExecuted: () => {}, + recordQueryFailed: () => {}, +}); + +/** No-op logger implementation. */ +export const noopQueryBudgetLogger: QueryBudgetLogger = Object.freeze({ + warn: () => {}, + info: () => {}, +}); + +// --------------------------------------------------------------------------- +// Validation helpers +// --------------------------------------------------------------------------- + +function assertPositiveInteger(value: unknown, field: string): number { + if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) { + throw new QueryBudgetError( + QueryBudgetErrorCode.INVALID_CONFIG, + `${field} must be a positive integer`, + { field, value } + ); + } + return value; +} + +function assertNonNegativeFinite(value: unknown, field: string, code: QueryBudgetErrorCode): number { + if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) { + throw new QueryBudgetError( + code, + `${field} must be a finite non-negative number`, + { field, value } + ); + } + return value; +} + +function assertTenantId(tenantId: unknown): string { + if (typeof tenantId !== 'string' || tenantId.trim().length === 0) { + throw new QueryBudgetError( + QueryBudgetErrorCode.INVALID_TENANT, + 'tenantId must be a non-empty string', + { tenantId } + ); + } + return tenantId; +} + +/** + * Validate and resolve a partial configuration into a complete, frozen + * `QueryBudgetConfig`. Throws `QueryBudgetError(INVALID_CONFIG)` on bad values. + */ +export function validateQueryBudgetConfig( + config: Partial = {} +): QueryBudgetConfig { + if (config === null || typeof config !== 'object' || Array.isArray(config)) { + throw new QueryBudgetError( + QueryBudgetErrorCode.INVALID_CONFIG, + 'config must be an object', + { config } + ); + } + + const resolved: QueryBudgetConfig = { + maxQueriesPerWindow: assertPositiveInteger( + config.maxQueriesPerWindow ?? DEFAULT_QUERY_BUDGET_CONFIG.maxQueriesPerWindow, + 'maxQueriesPerWindow' + ), + windowMs: assertPositiveInteger( + config.windowMs ?? DEFAULT_QUERY_BUDGET_CONFIG.windowMs, + 'windowMs' + ), + slowQueryThresholdMs: assertNonNegativeFinite( + config.slowQueryThresholdMs ?? DEFAULT_QUERY_BUDGET_CONFIG.slowQueryThresholdMs, + 'slowQueryThresholdMs', + QueryBudgetErrorCode.INVALID_CONFIG + ), + criticalQueryThresholdMs: assertNonNegativeFinite( + config.criticalQueryThresholdMs ?? DEFAULT_QUERY_BUDGET_CONFIG.criticalQueryThresholdMs, + 'criticalQueryThresholdMs', + QueryBudgetErrorCode.INVALID_CONFIG + ), + slowRowThreshold: assertNonNegativeFinite( + config.slowRowThreshold ?? DEFAULT_QUERY_BUDGET_CONFIG.slowRowThreshold, + 'slowRowThreshold', + QueryBudgetErrorCode.INVALID_CONFIG + ), + criticalRowThreshold: assertNonNegativeFinite( + config.criticalRowThreshold ?? DEFAULT_QUERY_BUDGET_CONFIG.criticalRowThreshold, + 'criticalRowThreshold', + QueryBudgetErrorCode.INVALID_CONFIG + ), + nowMs: + typeof config.nowMs === 'function' + ? config.nowMs + : DEFAULT_QUERY_BUDGET_CONFIG.nowMs, + }; + + if (resolved.criticalQueryThresholdMs <= resolved.slowQueryThresholdMs) { + throw new QueryBudgetError( + QueryBudgetErrorCode.INVALID_CONFIG, + 'criticalQueryThresholdMs must be greater than slowQueryThresholdMs', + { + slowQueryThresholdMs: resolved.slowQueryThresholdMs, + criticalQueryThresholdMs: resolved.criticalQueryThresholdMs, + } + ); + } + if (resolved.criticalRowThreshold <= resolved.slowRowThreshold) { + throw new QueryBudgetError( + QueryBudgetErrorCode.INVALID_CONFIG, + 'criticalRowThreshold must be greater than slowRowThreshold', + { + slowRowThreshold: resolved.slowRowThreshold, + criticalRowThreshold: resolved.criticalRowThreshold, + } + ); + } + + return Object.freeze(resolved); +} + +function severityFor(value: number, slow: number, critical: number): number { + if (value >= critical) return 2; + if (value >= slow) return 1; + return 0; +} + +/** + * Classify a query from its duration and rows-scanned count. The more severe + * of the two signals wins. Throws `QueryBudgetError(INVALID_QUERY)` for + * non-finite or negative inputs. + */ +export function classifyQuery( + durationMs: number, + rowsScanned: number = 0, + config: Partial = {} +): QueryClassification { + const duration = assertNonNegativeFinite( + durationMs, + 'durationMs', + QueryBudgetErrorCode.INVALID_QUERY + ); + const rows = assertNonNegativeFinite( + rowsScanned, + 'rowsScanned', + QueryBudgetErrorCode.INVALID_QUERY + ); + const cfg = validateQueryBudgetConfig(config); + + const severity = Math.max( + severityFor(duration, cfg.slowQueryThresholdMs, cfg.criticalQueryThresholdMs), + severityFor(rows, cfg.slowRowThreshold, cfg.criticalRowThreshold) + ); + + if (severity === 2) return QueryClassification.CRITICAL; + if (severity === 1) return QueryClassification.SLOW; + return QueryClassification.FAST; +} + +// --------------------------------------------------------------------------- +// Controller +// --------------------------------------------------------------------------- + +/** In-memory controller returned by {@link createQueryBudget}. */ +export interface QueryBudgetController { + /** Pre-flight check; does not mutate the window beyond lazy pruning. */ + check(tenantId: string): BudgetCheckResult; + /** Record an executed query and classify it. Returns the stored record. */ + record(tenantId: string, sample: QuerySample): QueryRecord; + /** Discard all recorded samples for a tenant. */ + reset(tenantId: string): void; + /** Read-only snapshot of a tenant's current state (prunes expired samples). */ + snapshot(tenantId: string): TenantBudgetState; + /** Eagerly prune expired samples across all tenants; returns records removed. */ + prune(nowMs?: number): number; + /** Read the injected clock. Used by the DB adapter for timing. */ + now(): number; + /** The fully resolved, frozen configuration. */ + readonly config: QueryBudgetConfig; +} + +interface MutableTenantState { + records: QueryRecord[]; +} + +function validateSample(sample: QuerySample): { sql?: string; durationMs: number; rowsScanned: number } { + if (sample === null || typeof sample !== 'object' || Array.isArray(sample)) { + throw new QueryBudgetError( + QueryBudgetErrorCode.INVALID_QUERY, + 'query sample must be an object', + { sample } + ); + } + if (sample.sql !== undefined && typeof sample.sql !== 'string') { + throw new QueryBudgetError( + QueryBudgetErrorCode.INVALID_QUERY, + 'sql must be a string when provided', + { sql: sample.sql } + ); + } + return { + sql: sample.sql, + durationMs: assertNonNegativeFinite( + sample.durationMs, + 'durationMs', + QueryBudgetErrorCode.INVALID_QUERY + ), + rowsScanned: assertNonNegativeFinite( + sample.rowsScanned ?? 0, + 'rowsScanned', + QueryBudgetErrorCode.INVALID_QUERY + ), + }; +} + +/** + * Create a per-tenant query budget controller. + * + * @param config Partial configuration; see {@link DEFAULT_QUERY_BUDGET_CONFIG}. + * @param metrics Optional observability sink (partial implementations allowed). + * @param logger Optional logging sink (partial implementations allowed). + */ +export function createQueryBudget( + config: Partial = {}, + metrics: Partial = {}, + logger: Partial = {} +): QueryBudgetController { + const cfg = validateQueryBudgetConfig(config); + const m: QueryBudgetMetrics = { ...noopQueryBudgetMetrics, ...metrics }; + const l: QueryBudgetLogger = { ...noopQueryBudgetLogger, ...logger }; + const states = new Map(); + const clock = cfg.nowMs; + + function now(): number { + return clock(); + } + + function getState(tenantId: string): MutableTenantState { + let state = states.get(tenantId); + if (!state) { + state = { records: [] }; + states.set(tenantId, state); + } + return state; + } + + function prune(atMs?: number): number { + const t = typeof atMs === 'number' ? atMs : now(); + if (!Number.isFinite(t)) return 0; + const cutoff = t - cfg.windowMs; + let removed = 0; + let affected = 0; + for (const [tenantId, state] of states) { + const kept = state.records.filter((record) => record.timestampMs >= cutoff); + const diff = state.records.length - kept.length; + if (diff > 0) { + state.records = kept; + removed += diff; + affected += 1; + } + if (state.records.length === 0) { + states.delete(tenantId); + } + } + if (removed > 0) { + m.recordBudgetPruned(affected, removed); + } + return removed; + } + + function check(tenantId: string): BudgetCheckResult { + const id = assertTenantId(tenantId); + prune(); + const state = getState(id); + const used = state.records.length; + const limit = cfg.maxQueriesPerWindow; + const allowed = used < limit; + const oldest = state.records[0]; + const result: BudgetCheckResult = { + allowed, + tenantId: id, + used, + limit, + remaining: Math.max(0, limit - used), + windowResetAtMs: oldest + ? oldest.timestampMs + cfg.windowMs + : now() + cfg.windowMs, + }; + if (allowed) { + m.recordQueryAccepted(id, used, limit); + } else { + const reason = QueryBudgetErrorCode.BUDGET_EXCEEDED; + m.recordQueryRejected(id, used, limit, reason); + l.warn('SQL query budget exceeded', { + tenantId: id, + used, + limit, + windowResetAtMs: result.windowResetAtMs, + }); + return { ...result, reason }; + } + return result; + } + + function record(tenantId: string, sample: QuerySample): QueryRecord { + const id = assertTenantId(tenantId); + const normalized = validateSample(sample); + prune(); + const classification = classifyQuery( + normalized.durationMs, + normalized.rowsScanned, + cfg + ); + const entry: QueryRecord = Object.freeze({ + tenantId: id, + sql: normalized.sql, + timestampMs: now(), + durationMs: normalized.durationMs, + rowsScanned: normalized.rowsScanned, + classification, + }); + getState(id).records.push(entry); + + m.recordQueryRecorded( + id, + classification, + normalized.durationMs, + normalized.rowsScanned + ); + if (classification === QueryClassification.SLOW) { + m.recordSlowQuery(id, normalized.durationMs, normalized.rowsScanned); + l.warn('slow SQL query classified', { + tenantId: id, + durationMs: normalized.durationMs, + rowsScanned: normalized.rowsScanned, + }); + } else if (classification === QueryClassification.CRITICAL) { + m.recordCriticalQuery(id, normalized.durationMs, normalized.rowsScanned); + l.warn('critical SQL query classified', { + tenantId: id, + durationMs: normalized.durationMs, + rowsScanned: normalized.rowsScanned, + }); + } + return entry; + } + + function reset(tenantId: string): void { + const id = assertTenantId(tenantId); + states.delete(id); + m.recordBudgetReset(id); + } + + function snapshot(tenantId: string): TenantBudgetState { + const id = assertTenantId(tenantId); + prune(); + const state = getState(id); + const records = state.records.slice(); + const current = now(); + return Object.freeze({ + tenantId: id, + records: Object.freeze(records), + used: records.length, + limit: cfg.maxQueriesPerWindow, + fastCount: records.filter((r) => r.classification === QueryClassification.FAST).length, + slowCount: records.filter((r) => r.classification === QueryClassification.SLOW).length, + criticalCount: records.filter((r) => r.classification === QueryClassification.CRITICAL).length, + windowStartMs: current - cfg.windowMs, + windowEndMs: current, + }); + } + + return Object.freeze({ + check, + record, + reset, + snapshot, + prune, + now, + config: cfg, + }); +}