Skip to content

Commit

Permalink
Add stepoff snooze in case of rates server rate limiting
Browse files Browse the repository at this point in the history
  • Loading branch information
paullinator committed Dec 7, 2024
1 parent 2f0fbc2 commit a0a3809
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/ratesEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import {
import { datelog, safeParseFloat, standardizeNames } from './util'

const nanoDb = nano(config.couchDbFullpath)
const QUERY_FREQ_MS = 15000
const QUERY_LIMIT = 50
const QUERY_FREQ_MS = 3000
const QUERY_LIMIT = 10
const snooze: Function = async (ms: number) =>
await new Promise((resolve: Function) => setTimeout(resolve, ms))

Expand Down Expand Up @@ -207,23 +207,41 @@ const dateRoundDownHour = (dateString: string): string => {
return new Date(date).toISOString()
}

const RETRY_DELAY = 1500
const MAX_RETRIES = 5

async function getExchangeRate(
ca: string,
cb: string,
date: string
date: string,
retry: number = 0
): Promise<number> {
const hourDate = dateRoundDownHour(date)
const currencyA = standardizeNames(ca)
const currencyB = standardizeNames(cb)
const url = `https://rates2.edge.app/v1/exchangeRate?currency_pair=${currencyA}_${currencyB}&date=${hourDate}`
try {
const result = await fetch(url, { method: 'GET' })
if (!result.ok) {
if (result.status === 429) {
datelog(`Rate limit hit`)
}
const text = await result.text()
throw new Error(`Rates error: ${text}`)
}
const jsonObj = await result.json()
datelog(
`Rate for ${currencyA} -> ${currencyB} ${date}: ${jsonObj.exchangeRate}`
)
return safeParseFloat(jsonObj.exchangeRate)
} catch (e) {
if (retry < MAX_RETRIES) {
const snoozeTime = Math.pow(2, retry) * RETRY_DELAY

datelog(`snoozing for ${snoozeTime}ms`)
await snooze(snoozeTime)
return await getExchangeRate(ca, cb, date, retry + 1)
}
datelog(
`Could not not get exchange rate for ${currencyA} and ${currencyB} at ${date}.`,
e
Expand Down

0 comments on commit a0a3809

Please sign in to comment.