1+ import { buildLogComment } from '@hyperdx/common-utils/dist/clickhouse' ;
2+ import { Metadata } from '@hyperdx/common-utils/dist/core/metadata' ;
3+
14import * as config from '@/config' ;
25import {
36 DEFAULT_DATABASE ,
@@ -9,6 +12,11 @@ import {
912} from '@/fixtures' ;
1013import Connection from '@/models/connection' ;
1114
15+ declare global {
16+ // Set by jest.setup.ts before it stubs `fetch`.
17+ var realFetch : typeof fetch ;
18+ }
19+
1220// Covers the wiring the unit tests can't: auth middleware opens the
1321// AsyncLocalStorage scope, and a query issued deep inside the route handler
1422// still reads it. If that scope is lost, queries fall back to hdx-unknown-*.
@@ -29,11 +37,23 @@ describe('request query attribution', () => {
2937 endSec : 1700003600 ,
3038 } ,
3139 ] ,
40+ withSamples : true ,
3241 } ) ;
3342 } ) ;
3443
44+ // jest.setup.ts installs `fetch` as a plain jest.fn(), not a spy, so
45+ // restoreAllMocks can't put it back; and restoreAllMocks would also undo
46+ // the setup's console spies. Each mock is reset by hand instead.
47+ const fetchStub = jest . mocked ( global . fetch ) . getMockImplementation ( ) ;
48+ let serverVersionSpy : jest . SpiedFunction <
49+ Metadata [ 'getServerVersion' ]
50+ > | null = null ;
51+
3552 afterEach ( async ( ) => {
3653 await server . clearDBs ( ) ;
54+ jest . mocked ( global . fetch ) . mockImplementation ( fetchStub ) ;
55+ serverVersionSpy ?. mockRestore ( ) ;
56+ serverVersionSpy = null ;
3757 } ) ;
3858
3959 afterAll ( async ( ) => {
@@ -66,6 +86,29 @@ describe('request query attribution', () => {
6686 return [ ] ;
6787 }
6888
89+ // As findRouteQueries, for the PromQL evaluation a tile's request ran.
90+ async function findTileQueries ( queryText : string , tile : string ) {
91+ const client = await getTestFixtureClickHouseClient ( ) ;
92+ for ( let attempt = 0 ; attempt < 10 ; attempt ++ ) {
93+ await client . command ( { query : 'SYSTEM FLUSH LOGS' } ) ;
94+ const result = await client . query ( {
95+ query : `
96+ SELECT query_id, log_comment
97+ FROM system.query_log
98+ WHERE type = 'QueryFinish'
99+ AND position(query, {queryText:String}) > 0
100+ AND JSONExtractString(log_comment, 'tile') = {tile:String}` ,
101+ query_params : { queryText, tile } ,
102+ format : 'JSON' ,
103+ } ) ;
104+ const { data } : { data : { query_id : string ; log_comment : string } [ ] } =
105+ await result . json ( ) ;
106+ if ( data . length > 0 ) return data ;
107+ await new Promise ( resolve => setTimeout ( resolve , 250 ) ) ;
108+ }
109+ return [ ] ;
110+ }
111+
69112 it ( 'tags queries from an authenticated route with the api surface' , async ( ) => {
70113 const { agent, team } = await getLoggedInAgent ( server ) ;
71114 const conn = await Connection . create ( {
@@ -95,4 +138,95 @@ describe('request query attribution', () => {
95138 } ) ;
96139 }
97140 } ) ;
141+
142+ it ( 'tags PromQL table-function queries with the attribution the browser sent' , async ( ) => {
143+ // Below 26.6 the router evaluates through prometheusQuery() rather than
144+ // proxying to ClickHouse's Prometheus HTTP API.
145+ serverVersionSpy = jest
146+ . spyOn ( Metadata . prototype , 'getServerVersion' )
147+ . mockResolvedValue ( [ 26 , 5 , 0 , 0 ] ) ;
148+ const { agent, team } = await getLoggedInAgent ( server ) ;
149+ const conn = await Connection . create ( {
150+ team : team . _id ,
151+ name : 'CH' ,
152+ host : config . CLICKHOUSE_HOST ,
153+ username : config . CLICKHOUSE_USER ,
154+ password : config . CLICKHOUSE_PASSWORD ,
155+ } ) ;
156+ const tile = `tile-${ Date . now ( ) } ` ;
157+
158+ await agent
159+ . get ( '/v1/prometheus/query' )
160+ . set (
161+ 'x-hyperdx-query-attribution' ,
162+ buildLogComment ( {
163+ surface : 'dashboard' ,
164+ dashboard : 'dash-1' ,
165+ tile,
166+ label : 'from-browser' ,
167+ trace : 'from-browser' ,
168+ } ) ! ,
169+ )
170+ . query ( {
171+ query : 'attribution_metric' ,
172+ time : '1700003600' ,
173+ connectionId : conn . _id . toString ( ) ,
174+ database : DEFAULT_DATABASE ,
175+ table : TABLE ,
176+ } )
177+ . expect ( 200 ) ;
178+
179+ const logged = await findTileQueries ( 'prometheusQuery(' , tile ) ;
180+
181+ expect ( logged ) . toHaveLength ( 1 ) ;
182+ expect ( logged [ 0 ] . query_id ) . toMatch ( / ^ h d x - d a s h b o a r d - / ) ;
183+ expect ( JSON . parse ( logged [ 0 ] . log_comment ) ) . toMatchObject ( {
184+ surface : 'dashboard' ,
185+ dashboard : 'dash-1' ,
186+ tile,
187+ // The server's, not the browser's.
188+ label : '/v1/prometheus' ,
189+ } ) ;
190+ expect ( JSON . parse ( logged [ 0 ] . log_comment ) . trace ) . not . toBe ( 'from-browser' ) ;
191+ } ) ;
192+
193+ // The CI ClickHouse serves prometheus_api_v1, which evaluates the PromQL
194+ // itself: this pins that it honours the log_comment and query_id we send.
195+ it ( 'tags PromQL proxied to the prometheus_api_v1 handler' , async ( ) => {
196+ jest . mocked ( global . fetch ) . mockImplementation ( globalThis . realFetch ) ;
197+ const { agent, team } = await getLoggedInAgent ( server ) ;
198+ const conn = await Connection . create ( {
199+ team : team . _id ,
200+ name : 'CH' ,
201+ host : config . CLICKHOUSE_HOST ,
202+ username : config . CLICKHOUSE_USER ,
203+ password : config . CLICKHOUSE_PASSWORD ,
204+ } ) ;
205+ const tile = `tile-${ Date . now ( ) } ` ;
206+
207+ await agent
208+ . get ( '/v1/prometheus/query' )
209+ . set (
210+ 'x-hyperdx-query-attribution' ,
211+ buildLogComment ( { surface : 'dashboard' , dashboard : 'dash-1' , tile } ) ! ,
212+ )
213+ . query ( {
214+ query : 'attribution_metric' ,
215+ time : '1700003600' ,
216+ connectionId : conn . _id . toString ( ) ,
217+ database : DEFAULT_DATABASE ,
218+ table : TABLE ,
219+ } )
220+ . expect ( 200 ) ;
221+
222+ const logged = await findTileQueries ( 'prometheus_query_step' , tile ) ;
223+ expect ( logged ) . toHaveLength ( 1 ) ;
224+ expect ( logged [ 0 ] . query_id ) . toMatch ( / ^ h d x - d a s h b o a r d - / ) ;
225+ expect ( JSON . parse ( logged [ 0 ] . log_comment ) ) . toMatchObject ( {
226+ surface : 'dashboard' ,
227+ dashboard : 'dash-1' ,
228+ tile,
229+ label : '/v1/prometheus' ,
230+ } ) ;
231+ } ) ;
98232} ) ;
0 commit comments