11import { NextResponse } from 'next/server'
22import { type Address , type Hex , isAddress , type RpcLog } from 'viem'
33
4- import { fetchLogsByTopic } from '@/lib/blockscout/fetch-logs-by-topic'
4+ import { fetchLogsByTopic , type RpcLogWithTimestamp } from '@/lib/blockscout/fetch-logs-by-topic'
5+ import { StaleWhileRevalidateCache } from '@/lib/blockscout/stale-while-revalidate-cache'
56import { EVENTS_FROM_BLOCK } from '@/lib/constants'
67import { logger } from '@/lib/logger'
78
@@ -13,18 +14,64 @@ export const GAUGE_EVENTS_REVALIDATE_SECONDS = 25
1314 */
1415export const MAX_GAUGES_PER_REQUEST = 200
1516
17+ /**
18+ * How long a gauge's logs are served without touching Blockscout. Matches the client's own poll
19+ * interval (`AVERAGE_BLOCKTIME`), so a steady-state page costs at most one upstream call per gauge
20+ * per block instead of one per tab per block.
21+ */
22+ const GAUGE_LOGS_FRESH_MS = 60_000
23+
24+ /**
25+ * How long logs may still be served while refreshing in the background — and, if Blockscout is
26+ * failing, instead of erroring. These events are append-only history; stale is far better than 500.
27+ */
28+ const GAUGE_LOGS_STALE_MS = 15 * 60_000
29+
30+ /** ~200 gauges × 3 topics, with headroom. */
31+ const GAUGE_LOGS_MAX_ENTRIES = 750
32+
33+ /** Advertised to clients when every gauge failed, so retries are spaced instead of immediate. */
34+ const RETRY_AFTER_SECONDS = 5
35+
1636export type GaugeEventsResponse = Record < Address , RpcLog [ ] >
1737
38+ /**
39+ * Process-wide cache of gauge logs, keyed by topic + gauge + block floor.
40+ *
41+ * This is the load-bearing part of the Blockscout rate-limit mitigation: pacing alone (see
42+ * `request-throttle.ts`) only spreads the same volume of requests over time, which would make cold
43+ * responses unacceptably slow. Not asking twice is what keeps us inside the budget.
44+ */
45+ const gaugeLogsCache = new StaleWhileRevalidateCache < RpcLogWithTimestamp [ ] > ( {
46+ freshMs : GAUGE_LOGS_FRESH_MS ,
47+ staleMs : GAUGE_LOGS_STALE_MS ,
48+ maxEntries : GAUGE_LOGS_MAX_ENTRIES ,
49+ } )
50+
51+ /** Exposed for tests; production code should never need to drop the cache. */
52+ export function clearGaugeLogsCache ( ) : void {
53+ gaugeLogsCache . clear ( )
54+ }
55+
56+ function cacheKey ( topic0 : Hex , gauge : Address , fromBlock : string ) : string {
57+ return `${ topic0 . toLowerCase ( ) } |${ gauge . toLowerCase ( ) } |${ fromBlock } `
58+ }
59+
1860/**
1961 * Shared handler for `/api/gauges/<event>` route handlers.
2062 *
2163 * Query params:
2264 * - `gauges` (required): comma-separated gauge addresses.
2365 * - `fromBlock` (optional): decimal block number; defaults to `EVENTS_FROM_BLOCK`.
2466 *
25- * Fetches Blockscout `getLogs` per gauge in parallel for the given `topic0`. Each underlying
26- * `fetch` opts into Next.js Data Cache via `next.revalidate`, so concurrent requests within the
27- * window share a single Blockscout round-trip.
67+ * Fetches Blockscout `getLogs` per gauge for the given `topic0`, behind a stale-while-revalidate
68+ * cache and a process-wide paced request queue. Gauges are resolved with `allSettled` so one
69+ * failure is reported precisely instead of collapsing the whole batch into an opaque error.
70+ *
71+ * @remarks
72+ * Responses stay all-or-nothing on purpose. The client does `eventsByGauge[gauge] ?? []`, so
73+ * omitting a failed gauge would silently render it as "no rewards claimed" — wrong numbers are
74+ * worse than a retryable error here.
2875 */
2976export async function buildGaugeEventsResponse ( req : Request , topic0 : Hex , route : string ) : Promise < Response > {
3077 const url = new URL ( req . url )
@@ -52,26 +99,60 @@ export async function buildGaugeEventsResponse(req: Request, topic0: Hex, route:
5299 const fromBlock =
53100 fromBlockParam && / ^ \d + $ / . test ( fromBlockParam ) ? fromBlockParam : EVENTS_FROM_BLOCK . toString ( )
54101
55- try {
56- const results = await Promise . all (
57- gauges . map ( gauge =>
58- fetchLogsByTopic ( {
59- address : gauge ,
60- topic0,
61- fromBlock,
62- fetchInit : { next : { revalidate : GAUGE_EVENTS_REVALIDATE_SECONDS } } ,
63- } ) ,
102+ const results = await Promise . allSettled (
103+ gauges . map ( gauge =>
104+ gaugeLogsCache . getOrLoad (
105+ cacheKey ( topic0 , gauge , fromBlock ) ,
106+ async ( ) => {
107+ const { data } = await fetchLogsByTopic ( {
108+ address : gauge ,
109+ topic0,
110+ fromBlock,
111+ fetchInit : { next : { revalidate : GAUGE_EVENTS_REVALIDATE_SECONDS } } ,
112+ } )
113+ return data
114+ } ,
115+ err => logger . warn ( { err, route, topic0, gauge } , 'Background refresh of gauge logs failed' ) ,
64116 ) ,
65- )
117+ ) ,
118+ )
66119
67- const eventsByGauge : GaugeEventsResponse = { }
68- gauges . forEach ( ( gauge , i ) => {
69- eventsByGauge [ gauge ] = results [ i ] . data
70- } )
120+ const eventsByGauge : GaugeEventsResponse = { }
121+ const failures : Array < { gauge : Address ; reason : unknown } > = [ ]
71122
72- return NextResponse . json ( eventsByGauge )
73- } catch ( err ) {
74- logger . error ( { err, route, topic0 } , 'Error fetching gauge events from Blockscout' )
75- return NextResponse . json ( { error : 'Failed to fetch gauge events' } , { status : 500 } )
123+ results . forEach ( ( result , i ) => {
124+ const gauge = gauges [ i ]
125+ if ( result . status === 'fulfilled' ) {
126+ eventsByGauge [ gauge ] = result . value
127+ } else {
128+ failures . push ( { gauge, reason : result . reason } )
129+ }
130+ } )
131+
132+ if ( failures . length > 0 ) {
133+ logger . error (
134+ {
135+ route,
136+ topic0,
137+ fromBlock,
138+ failedCount : failures . length ,
139+ totalCount : gauges . length ,
140+ failures : failures . map ( ( { gauge, reason } ) => ( {
141+ gauge,
142+ err : reason instanceof Error ? reason . message : String ( reason ) ,
143+ } ) ) ,
144+ } ,
145+ 'Error fetching gauge events from Blockscout' ,
146+ )
147+
148+ return NextResponse . json (
149+ {
150+ error : 'Failed to fetch gauge events' ,
151+ failedGauges : failures . map ( ( { gauge } ) => gauge ) ,
152+ } ,
153+ { status : 503 , headers : { 'Retry-After' : String ( RETRY_AFTER_SECONDS ) } } ,
154+ )
76155 }
156+
157+ return NextResponse . json ( eventsByGauge )
77158}
0 commit comments