import type {LogContext} from '@rocicorp/logger'; import {unreachable} from '../../../../shared/src/asserts.ts'; import {must} from '../../../../shared/src/must.ts'; import {TDigest} from '../../../../shared/src/tdigest.ts'; import * as v from '../../../../shared/src/valita.ts'; import type {AnalyzeQueryResult} from '../../../../zero-protocol/src/analyze-query-result.ts'; import type { QueryServerMetrics, ServerMetrics, } from '../../../../zero-protocol/src/inspect-down.ts'; import { inspectAnalyzeQueryUpSchema, unparsedInspectUpBodySchema, type UnparsedInspectUpMessage, } from '../../../../zero-protocol/src/inspect-up.ts'; import {Database} from '../../../../zqlite/src/db.ts'; import {loadPermissions} from '../../auth/load-permissions.ts'; import { isDevelopmentMode, type NormalizedZeroConfig, } from '../../config/normalize.ts'; import { getServerVersion, isAdminPasswordValid, } from '../../config/zero-config.ts'; import {StatementRunner} from '../../db/statements.ts'; import type {InspectorDelegate} from '../../server/inspector-delegate.ts'; import {analyzeQuery} from '../analyze.ts'; import type {ClientHandler} from './client-handler.ts'; import type {ConnectionContext} from './connection-context-manager.ts'; import type {CVRStore} from './cvr-store.ts'; import type {CVRSnapshot} from './cvr.ts'; export async function handleInspect( lc: LogContext, body: UnparsedInspectUpMessage[1], cvr: CVRSnapshot, client: ClientHandler, inspectorDelegate: InspectorDelegate, clientGroupID: string, cvrStore: CVRStore, config: NormalizedZeroConfig, ctx: ConnectionContext, ): Promise { if (!unparsedInspectUpBodySchema.isKnown(body)) { // An op from a newer client. Answer this request only, so the connection // stays up. Nothing is computed for it, so it needs no authentication. const {id} = body; if (typeof id === 'string') { client.sendInspectResponse(lc, { op: 'error', id, value: `Unknown inspector op: ${String(body.op)}`, }); } return; } // Authentication is per connection. In development mode the password is // not required unless one is configured. if ( body.op !== 'authenticate' && !(isDevelopmentMode() && !config.adminPassword) && !client.isInspectorAuthenticated() ) { lc.info?.( 'Client not authenticated to access the inspector protocol. Sending authentication challenge', ); client.sendInspectResponse(lc, { op: 'authenticated', id: body.id, value: false, }); return; } try { switch (body.op) { case 'queries': { const queryRows = await cvrStore.inspectQueries( lc, cvr.ttlClock, body.clientID, ); // Enhance query rows with server-side materialization metrics const enhancedRows = queryRows.map(row => ({ ...row, ast: row.ast ?? inspectorDelegate.getASTForQuery(row.queryID) ?? null, metrics: metricsForProtocol( inspectorDelegate.getMetricsJSONForQuery(row.queryID), ctx.protocolVersion, ), })); client.sendInspectResponse(lc, { op: 'queries', id: body.id, value: enhancedRows, }); break; } case 'metrics': { client.sendInspectResponse(lc, { op: 'metrics', id: body.id, value: inspectorDelegate.getMetricsJSON(), }); break; } case 'version': client.sendInspectResponse(lc, { op: 'version', id: body.id, value: getServerVersion(config), }); break; case 'authenticate': { const {authLimiter} = inspectorDelegate; // A blocked attempt is not checked against the password, so that the // block cannot be ended by guessing right. const ok = !authLimiter.isBlocked(clientGroupID, client) && isAdminPasswordValid(lc, config, body.value); if (ok) { authLimiter.recordSuccess(clientGroupID, client); } client.setInspectorAuthenticated(ok); client.sendInspectResponse(lc, { op: 'authenticated', id: body.id, value: ok, }); if (!ok && authLimiter.recordFailure(clientGroupID, client)) { lc.warn?.( 'Closing connection after repeated failed inspector authentication', ); client.close('too many failed inspector authentication attempts'); } break; } case 'analyze-query': { const parsedBody = v.parse(body, inspectAnalyzeQueryUpSchema, 'strip'); let ast = parsedBody.ast ?? parsedBody.value; let legacyQuery = true; if (parsedBody.name && parsedBody.args) { // Get the AST from the API server by transforming the named query ast = await inspectorDelegate.transformCustomQuery( parsedBody.name, parsedBody.args, ctx, ); legacyQuery = false; } if (ast === undefined) { throw new Error( 'AST is required for analyze-query operation. Either provide an AST directly or ensure custom query transformation is configured.', ); } let permissions; if (legacyQuery) { using db = new Database(lc, config.replica.file); const dbRunner = new StatementRunner(db); const loaded = loadPermissions(lc, dbRunner, config.app.id, config); if (loaded.permissions) { permissions = loaded.permissions; } else { lc.info?.( 'No permissions loaded; analyze-query will run without applying permissions.', ); } } const result = await analyzeQuery( lc, config, must(cvr.clientSchema), ast, parsedBody.options?.syncedRows, parsedBody.options?.vendedRows, permissions, ctx.auth?.type === 'jwt' ? ctx.auth : undefined, parsedBody.options?.joinPlans, ); client.sendInspectResponse(lc, { op: 'analyze-query', id: body.id, value: analyzeResultForProtocol(result, ctx.protocolVersion), }); break; } default: unreachable(body); } } catch (e) { lc.warn?.('Error handling inspect message', e); client.sendInspectResponse(lc, { op: 'error', id: body.id, value: (e as Error).message, }); } } /** * Removes the planner's `filter` nodes from `joinPlans` for clients before * protocol 53, which added that node type. 1.9 and 1.10 clients fail to parse * a node type they don't know, and the failed parse puts the client in its * error state. * * @visibleForTesting */ export function analyzeResultForProtocol( result: AnalyzeQueryResult, protocolVersion: number, ): AnalyzeQueryResult { if (protocolVersion >= 53 || result.joinPlans === undefined) { return result; } return { ...result, joinPlans: result.joinPlans.filter( event => !('nodeType' in event && event.nodeType === 'filter'), ), }; } /** * Converts per-query server metrics to the appropriate wire format based on the * client's protocol version. * * Protocol >= 51: new format — `query-hydration-server-ms` (plain number) + * `query-update-server` (TDigest). * Protocol < 51: old format — `query-materialization-server` (TDigest) + * `query-update-server` (TDigest). The scalar hydration time is wrapped into a * one-point TDigest for backward compatibility. * * @visibleForTesting */ export function metricsForProtocol( metrics: QueryServerMetrics | null, protocolVersion: number, ): QueryServerMetrics | null { if (protocolVersion >= 51 || metrics === null) { return metrics; } // Backward compat: wrap the scalar hydration ms into a one-point TDigest // under the old field name so that 1.5 clients can parse the response. const hydrateDigest = new TDigest(); const hydrateMs = metrics['query-hydration-server-ms']; if (hydrateMs !== undefined) { hydrateDigest.add(hydrateMs); } const legacyMetrics: ServerMetrics = { 'query-materialization-server': hydrateDigest.toJSON(), 'query-update-server': metrics['query-update-server'], }; // Cast to QueryServerMetrics: this is intentional — for old-protocol clients // we send the legacy ServerMetrics wire shape under the QueryServerMetrics type // to satisfy TypeScript while preserving backward compatibility. return legacyMetrics as unknown as QueryServerMetrics; }