/** * src/analytics/execution/clickhouse-process-control.ts * ====================================================== * BI-P019/BI-P021 — the ClickHouse implementation of `EngineProcessControl`. * * Three statements, each chosen for a measured reason: * * isRunning `SELECT count() FROM system.processes WHERE query_id = …` * — the authority on whether the server is still working. Note * that `KILL QUERY SYNC` returning is NOT this: a killed query * can still appear here briefly while it unwinds, which is * exactly why cancellation polls instead of trusting the kill. * * requestKill `KILL QUERY WHERE query_id = … ASYNC` — ASYNC, not SYNC, * because the verification loop is what establishes the stop and * a SYNC kill would block this call for up to the query's * remaining lifetime while providing no stronger guarantee. * * progress `read_rows`, `read_bytes` and `elapsed` from the same table — * live counters, which is what makes BI-P021's in-flight budget * enforcement possible at all. * * KILL and the system-table reads are ADMINISTRATIVE. They run on the engine's * own credential, never on the tenant's restricted user (which has no access * to system.processes — measured: ACCESS_DENIED, code 497). The tenant-scoping * check therefore happens HERE, on the query id, before any statement is sent. */ import { SiaxError } from '../../platform/errors'; import type { EngineProcessControl, QueryProgress } from './cancellation'; export interface ClickHouseProcessControlOptions { baseUrl: string; /** "user:password" for the ADMIN credential. From a secret ref. */ basicAuth?: string; timeoutMs?: number; /** * Restricts every operation to query ids carrying this prefix, so a caller * cannot kill or inspect another tenant's work through this object. */ queryIdPrefix?: string; } export class ClickHouseProcessControl implements EngineProcessControl { readonly engine = 'clickhouse'; private readonly baseUrl: string; private readonly authHeader?: string; private readonly timeoutMs: number; private readonly prefix?: string; constructor(opts: ClickHouseProcessControlOptions) { this.baseUrl = opts.baseUrl.replace(/\/+$/, ''); this.authHeader = opts.basicAuth ? `Basic ${Buffer.from(opts.basicAuth).toString('base64')}` : undefined; this.timeoutMs = opts.timeoutMs ?? 10_000; this.prefix = opts.queryIdPrefix; } private assertScoped(queryId: string): void { if (this.prefix && !queryId.startsWith(this.prefix)) { throw new SiaxError('AUTHORIZATION_DENIED', '0pt.analytics', 'query does not belong to this scope'); } if (!/^[A-Za-z0-9_-]{1,128}$/.test(queryId)) { // The id reaches ClickHouse as a bound parameter, but a malformed id is // a bug worth surfacing rather than a string worth binding. throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'malformed query id'); } } async isRunning(queryId: string): Promise { this.assertScoped(queryId); const body = await this.send( 'SELECT count() AS n FROM system.processes WHERE query_id = {qid:String} FORMAT JSON', { param_qid: queryId }, ); const n = Number((JSON.parse(body) as { data: Array<{ n: string | number }> }).data[0]?.n ?? 0); return n > 0; } async requestKill(queryId: string): Promise { this.assertScoped(queryId); await this.send( 'KILL QUERY WHERE query_id = {qid:String} ASYNC FORMAT JSON', { param_qid: queryId }, false, ); return true; } async progress(queryId: string): Promise { this.assertScoped(queryId); const body = await this.send( 'SELECT read_rows, read_bytes, toUInt64(elapsed * 1000) AS elapsed_ms FROM system.processes ' + 'WHERE query_id = {qid:String} FORMAT JSON', { param_qid: queryId }, ); const row = (JSON.parse(body) as { data: Array> }).data[0]; if (!row) return undefined; return { rows_read: Number(row.read_rows ?? 0), bytes_read: Number(row.read_bytes ?? 0), elapsed_ms: Number(row.elapsed_ms ?? 0), }; } private async send(sql: string, params: Record, expectJson = true): Promise { const url = new URL(this.baseUrl); url.searchParams.set('query', sql); for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v); // NOT readonly: KILL mutates server state. The other two would tolerate // readonly, but sharing one path keeps the credential story simple. url.searchParams.set('max_execution_time', '10'); const headers: Record = {}; if (this.authHeader) headers.Authorization = this.authHeader; let res: Response; try { res = await fetch(url.toString(), { method: 'POST', headers, body: '', signal: AbortSignal.timeout(this.timeoutMs), }); } catch (cause) { throw new SiaxError('DEPENDENCY_UNAVAILABLE', 'clickhouse', 'clickhouse unreachable', { cause }); } const text = await res.text(); if (!res.ok) { const code = /Code:\s*(\d+)/.exec(text)?.[1] ?? String(res.status); throw new SiaxError( 'PERMANENT_FAILURE', 'clickhouse', `process-control statement failed (CH code ${code})`, ); } if (expectJson && !text.trim()) { throw new SiaxError('PERMANENT_FAILURE', 'clickhouse', 'empty response from process-control statement'); } return text; } }