Skip to content

Commit a0a3809

Browse files
committed
Add stepoff snooze in case of rates server rate limiting
1 parent 2f0fbc2 commit a0a3809

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

src/ratesEngine.ts

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ import {
1212
import { datelog, safeParseFloat, standardizeNames } from './util'
1313

1414
const nanoDb = nano(config.couchDbFullpath)
15-
const QUERY_FREQ_MS = 15000
16-
const QUERY_LIMIT = 50
15+
const QUERY_FREQ_MS = 3000
16+
const QUERY_LIMIT = 10
1717
const snooze: Function = async (ms: number) =>
1818
await new Promise((resolve: Function) => setTimeout(resolve, ms))
1919

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

210+
const RETRY_DELAY = 1500
211+
const MAX_RETRIES = 5
212+
210213
async function getExchangeRate(
211214
ca: string,
212215
cb: string,
213-
date: string
216+
date: string,
217+
retry: number = 0
214218
): Promise<number> {
215219
const hourDate = dateRoundDownHour(date)
216220
const currencyA = standardizeNames(ca)
217221
const currencyB = standardizeNames(cb)
218222
const url = `https://rates2.edge.app/v1/exchangeRate?currency_pair=${currencyA}_${currencyB}&date=${hourDate}`
219223
try {
220224
const result = await fetch(url, { method: 'GET' })
225+
if (!result.ok) {
226+
if (result.status === 429) {
227+
datelog(`Rate limit hit`)
228+
}
229+
const text = await result.text()
230+
throw new Error(`Rates error: ${text}`)
231+
}
221232
const jsonObj = await result.json()
222233
datelog(
223234
`Rate for ${currencyA} -> ${currencyB} ${date}: ${jsonObj.exchangeRate}`
224235
)
225236
return safeParseFloat(jsonObj.exchangeRate)
226237
} catch (e) {
238+
if (retry < MAX_RETRIES) {
239+
const snoozeTime = Math.pow(2, retry) * RETRY_DELAY
240+
241+
datelog(`snoozing for ${snoozeTime}ms`)
242+
await snooze(snoozeTime)
243+
return await getExchangeRate(ca, cb, date, retry + 1)
244+
}
227245
datelog(
228246
`Could not not get exchange rate for ${currencyA} and ${currencyB} at ${date}.`,
229247
e

0 commit comments

Comments
 (0)