Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions src/data-layer/fetchers/fetchBeaconChain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import type {
MetricReturnData,
} from "@/lib/types"

import { fetchRetry } from "./fetchRetry"

export type BeaconChainData = BeaconchainEpochData & { apr: MetricReturnData }

/**
* Fetch beaconchain data from Beaconcha.in API.
* Combines epoch and ethstore endpoints (sequential to respect 1 req/sec limit).
* Combines epoch and ethstore endpoints sequentially.
*/
export async function fetchBeaconChain(): Promise<BeaconChainData> {
const base = "https://beaconcha.in"
Expand All @@ -27,31 +29,26 @@ export async function fetchBeaconChain(): Promise<BeaconChainData> {

// Fetch epoch data
const epochUrl = new URL("api/v1/epoch/latest", base).href
const epochResponse = await fetch(epochUrl, { headers })
const epochResponse = await fetchRetry(epochUrl, { headers })
if (!epochResponse.ok) {
const status = epochResponse.status
console.warn("Beaconcha.in epoch fetch non-OK", { status, url: epochUrl })
const error = `Beaconcha.in epoch responded with status ${status}`
throw new Error(error)
throw new Error(`Beaconcha.in epoch responded with status ${status}`)
}
const epochJson: EpochResponse = await epochResponse.json()
const { validatorscount, eligibleether } = epochJson.data
const totalEthStaked = Math.floor(eligibleether * 1e-9)

// Wait 1s to respect rate limit
await new Promise((r) => setTimeout(r, 1000))
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth double-checking: with this sleep removed, the ethstore fetch fires immediately after the epoch fetch. If beaconcha.in enforces 1 req/sec, the second call will routinely 429 and depend on fetchRetry backoff to recover. We sure this will work as expected?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, tested. Its already working as expected.


// Fetch ethstore data
const ethstoreUrl = new URL("api/v1/ethstore/latest", base).href
const ethstoreResponse = await fetch(ethstoreUrl, { headers })
const ethstoreResponse = await fetchRetry(ethstoreUrl, { headers })
if (!ethstoreResponse.ok) {
const status = ethstoreResponse.status
console.warn("Beaconcha.in ethstore fetch non-OK", {
status,
url: ethstoreUrl,
})
const error = `Beaconcha.in ethstore responded with status ${status}`
throw new Error(error)
throw new Error(`Beaconcha.in ethstore responded with status ${status}`)
}
const ethstoreJson: EthStoreResponse = await ethstoreResponse.json()
const apr = ethstoreJson.data.apr
Expand Down
32 changes: 32 additions & 0 deletions src/data-layer/fetchers/fetchRetry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Shared retry.fetch configuration for all data-layer fetchers.
*
* Uses Trigger.dev's built-in retry.fetch which automatically handles
* 429 (rate-limit) and 5xx (server error) responses with exponential backoff.
*/
import { retry } from "@trigger.dev/sdk/v3"

const RETRY_BY_STATUS = {
"429": {
strategy: "backoff" as const,
maxAttempts: 2,
},
"500-599": {
strategy: "backoff" as const,
maxAttempts: 2,
},
}

/**
* Drop-in replacement for `fetch()` with built-in 429 and 5xx retry.
* Delegates to Trigger.dev's `retry.fetch` under the hood.
*/
export function fetchRetry(
url: string | URL,
init?: RequestInit
): Promise<Response> {
return retry.fetch(url, {
...init,
retry: { byStatus: RETRY_BY_STATUS },
})
}
8 changes: 2 additions & 6 deletions src/data-layer/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,10 @@ const DAILY: TaskDef[] = [
[KEYS.EVENTS, fetchEvents],
[KEYS.DEVELOPER_TOOLS, fetchDeveloperTools],
[KEYS.TRANSLATION_GLOSSARY, fetchTranslationGlossary],
[KEYS.BEACONCHAIN, fetchBeaconChain],
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

most important change, from hourly to daily

]

const HOURLY: TaskDef[] = [
[KEYS.BEACONCHAIN, fetchBeaconChain],
[KEYS.BLOBSCAN_STATS, fetchBlobscanStats],
[KEYS.ETHEREUM_MARKETCAP, fetchEthereumMarketcap],
[KEYS.ETHEREUM_STABLECOINS_MCAP, fetchEthereumStablecoinsMcap],
Expand All @@ -104,11 +104,7 @@ function createDataTask([key, fetchFn]: TaskDef) {
return task({
id: key,
retry: {
maxAttempts: 3,
factor: 2,
minTimeoutInMs: 2000,
maxTimeoutInMs: 30000,
randomize: true,
maxAttempts: 2,
},
catchError: async ({ error }) => {
logger.error(`[${key}] failed`, { error })
Expand Down
4 changes: 2 additions & 2 deletions trigger.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export default defineConfig({
enabledInDev: true,
default: {
maxAttempts: 1,
minTimeoutInMs: 1000,
maxTimeoutInMs: 10000,
minTimeoutInMs: 1_000,
maxTimeoutInMs: 30_000,
factor: 2,
randomize: true,
},
Expand Down
Loading