11import type * as cadent from 'cadent'
2+ import * as Sentry from '@sentry/cloudflare'
23import { hc } from 'hono/client'
34import { serverEnv , tempoApiUrl } from './env.ts'
45
6+ const ALERTABLE_STATUSES = new Set ( [ 402 , 403 , 429 ] )
7+ const REPORT_THROTTLE_MS = 60_000
8+ const lastReportedAt = new Map < string , number > ( )
9+
10+ export function isAlertableTempoApiStatus ( status : number ) : boolean {
11+ return ALERTABLE_STATUSES . has ( status ) || status >= 500
12+ }
13+
14+ function reportTempoApiResponse ( response : Response , method : string ) : void {
15+ if ( ! isAlertableTempoApiStatus ( response . status ) ) return
16+
17+ const url = new URL ( response . url )
18+ const key = `${ response . status } :${ method } :${ url . pathname } `
19+ const now = Date . now ( )
20+ const previous = lastReportedAt . get ( key ) ?? 0
21+
22+ console . error ( '[tempo-api] upstream request failed' , {
23+ method,
24+ path : url . pathname ,
25+ status : response . status ,
26+ } )
27+
28+ if ( now - previous < REPORT_THROTTLE_MS ) return
29+ lastReportedAt . set ( key , now )
30+
31+ Sentry . captureMessage ( `Tempo API returned ${ response . status } ` , {
32+ level : 'error' ,
33+ tags : {
34+ component : 'tempo-api-client' ,
35+ method,
36+ path : url . pathname ,
37+ status : String ( response . status ) ,
38+ } ,
39+ } )
40+ }
41+
42+ const instrumentedFetch : typeof fetch = async ( input , init ) => {
43+ const response = await fetch ( input , init )
44+ const method =
45+ init ?. method ?? ( input instanceof Request ? input . method : 'GET' )
46+ reportTempoApiResponse ( response , method )
47+ return response
48+ }
49+
550/**
651 * Typed client for the Tempo API. Server-side only.
752 *
@@ -17,6 +62,7 @@ import { serverEnv, tempoApiUrl } from './env.ts'
1762 * (scopes: `data:read`, `indexer:query`).
1863 */
1964export const api = hc < cadent . App . App > ( tempoApiUrl , {
65+ fetch : instrumentedFetch ,
2066 headers : serverEnv . TEMPO_API_KEY
2167 ? { 'tempo-api-key' : serverEnv . TEMPO_API_KEY }
2268 : undefined ,
0 commit comments