diff --git a/.changeset/clickhouse-version-on-proxy-spans.md b/.changeset/clickhouse-version-on-proxy-spans.md new file mode 100644 index 000000000..db7d385c7 --- /dev/null +++ b/.changeset/clickhouse-version-on-proxy-spans.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': patch +--- + +feat: record the ClickHouse server version on ClickHouse proxy spans, as +`hyperdx.clickhouse_proxy.clickhouse.version`, so query errors and latency can +be compared across ClickHouse upgrades. diff --git a/packages/api/src/routers/api/__tests__/clickhouseProxy.int.test.ts b/packages/api/src/routers/api/__tests__/clickhouseProxy.int.test.ts index 9e09c5406..ce7f15cd3 100644 --- a/packages/api/src/routers/api/__tests__/clickhouseProxy.int.test.ts +++ b/packages/api/src/routers/api/__tests__/clickhouseProxy.int.test.ts @@ -38,11 +38,18 @@ describe('clickhouse-proxy forwarding', () => { const chunks: Buffer[] = []; req.on('data', chunk => chunks.push(chunk)); req.on('end', () => { + const body = Buffer.concat(chunks); + // The proxy's own version lookup, not a forwarded request. + if (body.includes('SELECT version()')) { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ data: [{ version: '26.10.3.7' }] })); + return; + } captured.push({ method: req.method, url: req.url, headers: req.headers, - body: Buffer.concat(chunks), + body, }); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: [] })); diff --git a/packages/api/src/routers/api/__tests__/clickhouseProxyOutcome.int.test.ts b/packages/api/src/routers/api/__tests__/clickhouseProxyOutcome.int.test.ts index 2e27e8ce9..90cc6337d 100644 --- a/packages/api/src/routers/api/__tests__/clickhouseProxyOutcome.int.test.ts +++ b/packages/api/src/routers/api/__tests__/clickhouseProxyOutcome.int.test.ts @@ -3,10 +3,13 @@ import http from 'http'; import { getLoggedInAgent, getServer } from '@/fixtures'; import Connection from '@/models/connection'; +import { cachedClickHouseVersion } from '@/utils/clickhouseVersion'; import * as instrumentation from '@/utils/instrumentation'; jest.unmock('http-proxy-middleware'); +const UPSTREAM_VERSION = '26.10.3.7'; + const TIMEOUT_TRAILER = 'Code: 159. DB::Exception: Timeout exceeded: elapsed 15.0 seconds, maximum: 15. (TIMEOUT_EXCEEDED) (version 25.3.1.1)\n'; @@ -69,8 +72,15 @@ describe('clickhouse-proxy outcome', () => { beforeAll(async () => { await server.start(); upstream = http.createServer((req, res) => { - req.resume(); + let body = ''; + req.on('data', (chunk: Buffer) => (body += chunk)); req.on('end', () => { + // The proxy's own version lookup, not a scripted query. + if (body.includes('SELECT version()')) { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ data: [{ version: UPSTREAM_VERSION }] })); + return; + } const id = new URL(req.url ?? '', 'http://x').searchParams.get( 'query_id', ); @@ -137,6 +147,30 @@ describe('clickhouse-proxy outcome', () => { }); }); + it('records the ClickHouse version once it has been read', async () => { + const send = await connect(); + await send('ok').expect(200); + const connection = await Connection.findOne({ host: upstreamUrl }); + const key = { + id: connection!._id.toString(), + host: upstreamUrl, + username: 'default', + }; + for (let i = 0; i < 50 && !cachedClickHouseVersion(key); i++) { + await new Promise(resolve => setTimeout(resolve, 20)); + } + recordSpy.mockClear(); + setAttributes.mockClear(); + + await send('ok').expect(200); + await proxyOutcome(); + expect(setAttributes).toHaveBeenCalledWith( + expect.objectContaining({ + 'hyperdx.clickhouse_proxy.clickhouse.version': UPSTREAM_VERSION, + }), + ); + }); + it('categorises an exception written after a 200', async () => { const send = await connect(); const res = await send('mid-stream') @@ -222,6 +256,11 @@ describe('clickhouse-proxy outcome', () => { outcome: 'error', attributes: { error_category: 'upstream_unavailable' }, }); + expect(setAttributes).toHaveBeenCalledWith( + expect.objectContaining({ + 'hyperdx.clickhouse_proxy.clickhouse.version': undefined, + }), + ); }); it('categorises a request the client abandoned', async () => { diff --git a/packages/api/src/utils/clickhouseVersion.ts b/packages/api/src/utils/clickhouseVersion.ts new file mode 100644 index 000000000..06c41040a --- /dev/null +++ b/packages/api/src/utils/clickhouseVersion.ts @@ -0,0 +1,58 @@ +import { + Metadata, + MetadataCache, +} from '@hyperdx/common-utils/dist/core/metadata'; +import type { Connection } from '@hyperdx/common-utils/dist/types'; + +import { ClickhouseClient } from '@/clickhouse'; + +// Short, because the point is to see a server change version after an upgrade. +const VERSION_TTL_MS = 60_000; +const VERSION_TIMEOUT_MS = 5_000; + +const versionCache = new MetadataCache(); + +type VersionedConnection = Pick< + Connection, + 'id' | 'host' | 'username' | 'password' +>; + +// '' marks a failed read, so an unreachable server is not asked on every request. +async function readVersion(connection: VersionedConnection): Promise { + let client: ClickhouseClient | undefined; + try { + client = new ClickhouseClient({ + host: connection.host, + username: connection.username, + password: connection.password, + requestTimeout: VERSION_TIMEOUT_MS, + }); + const version = await new Metadata( + client, + new MetadataCache(), + ).getServerVersion({ connectionId: connection.id }); + return version?.join('.') ?? ''; + } catch { + return ''; + } finally { + void client?.close(); + } +} + +/** + * The connection's ClickHouse version if it is cached, starting a lookup + * otherwise so a later call has it. Never waits on ClickHouse. + */ +export function cachedClickHouseVersion( + connection: VersionedConnection, +): string | undefined { + // Keyed on the host as well, so editing a connection's host drops the answer. + const key = `${connection.id}|${connection.host}`; + const version = versionCache.get(key); + if (version === undefined) { + void versionCache.getOrFetch(key, () => readVersion(connection), { + ttlMs: VERSION_TTL_MS, + }); + } + return version || undefined; +} diff --git a/packages/api/src/utils/proxyOutcome.ts b/packages/api/src/utils/proxyOutcome.ts index 3e38dcd8d..867a0a6db 100644 --- a/packages/api/src/utils/proxyOutcome.ts +++ b/packages/api/src/utils/proxyOutcome.ts @@ -9,6 +9,7 @@ import type { ClientRequest, IncomingMessage, ServerResponse } from 'http'; import { performance } from 'perf_hooks'; import { isClickHouseError } from '@/utils/clickhouseErrors'; +import { cachedClickHouseVersion } from '@/utils/clickhouseVersion'; import { getServerSpan, recordOperationOutcome, @@ -131,6 +132,7 @@ type ProxyState = { startedAt: number; headersAt?: number; span?: Span; + connection?: Parameters[0]; timedOut: boolean; upstreamCut: boolean; transportError?: { code?: string; message: string }; @@ -150,10 +152,15 @@ const states = new WeakMap(); * response closes, from listeners prepended so they run before the HTTP * instrumentation ends the server span. */ -export const trackProxyOutcome: RequestHandler = (_req, res, next) => { +export const trackProxyOutcome: RequestHandler = (req, res, next) => { + const connection = req._hdx_connection; + // Starts the version lookup now so it is usually cached by the time the + // response closes. + if (connection) cachedClickHouseVersion(connection); const state: ProxyState = { startedAt: performance.now(), span: getServerSpan(), + connection, timedOut: false, upstreamCut: false, done: false, @@ -252,6 +259,8 @@ function finishProxyOutcome(res: ServerResponse, state: ProxyState) { state.span?.setAttributes({ 'hyperdx.clickhouse_proxy.error.category': category, 'hyperdx.clickhouse_proxy.upstream.status_code': state.upstreamStatus, + 'hyperdx.clickhouse_proxy.clickhouse.version': + state.connection && cachedClickHouseVersion(state.connection), 'hyperdx.clickhouse_proxy.clickhouse.error_code': clickhouseErrorCode, 'hyperdx.clickhouse_proxy.clickhouse.error_type': exception?.type, 'hyperdx.clickhouse_proxy.error.message': category