Skip to content

feat: add retry logic #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 27, 2023
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
53 changes: 53 additions & 0 deletions src/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,59 @@ describe('set', () => {
`The blob store is unavailable because it's missing required configuration properties`,
)
})

test('Retries failed operations', async () => {
let attempts = 0

const fetcher = async (...args: Parameters<typeof globalThis.fetch>) => {
const [url, options] = args
const headers = options?.headers as Record<string, string>

expect(options?.method).toBe('put')

if (url === `https://api.netlify.com/api/v1/sites/${siteID}/blobs/${key}?context=production`) {
const data = JSON.stringify({ url: signedURL })

expect(headers.authorization).toBe(`Bearer ${apiToken}`)

return new Response(data)
}

if (url === signedURL) {
attempts += 1

expect(options?.body).toBe(value)

if (attempts === 1) {
return new Response(null, { status: 500 })
}

if (attempts === 2) {
throw new Error('Some network problem')
}

if (attempts === 3) {
return new Response(null, { headers: { 'X-RateLimit-Reset': '10' }, status: 429 })
}

return new Response(value)
}

throw new Error(`Unexpected fetch call: ${url}`)
}

const blobs = new Blobs({
authentication: {
token: apiToken,
},
fetcher,
siteID,
})

await blobs.set(key, value)

expect(attempts).toBe(4)
})
})

describe('setJSON', () => {
Expand Down
4 changes: 3 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { fetchAndRetry } from './retry.ts'

interface APICredentials {
apiURL?: string
token: string
Expand Down Expand Up @@ -127,7 +129,7 @@ export class Blobs {
headers['cache-control'] = 'max-age=0, stale-while-revalidate=60'
}

const res = await this.fetcher(url, { body, headers, method })
const res = await fetchAndRetry(this.fetcher, url, { body, method, headers })

if (res.status === 404 && method === HTTPMethod.Get) {
return null
Expand Down
48 changes: 48 additions & 0 deletions src/retry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const DEFAULT_RETRY_DELAY = 5000
const MIN_RETRY_DELAY = 1000
const MAX_RETRY = 5
const RATE_LIMIT_HEADER = 'X-RateLimit-Reset'

export const fetchAndRetry = async (
fetcher: typeof globalThis.fetch,
url: string,
options: RequestInit,
attemptsLeft = MAX_RETRY,
): ReturnType<typeof globalThis.fetch> => {
try {
const res = await fetcher(url, options)

if (attemptsLeft > 0 && (res.status === 429 || res.status >= 500)) {
const delay = getDelay(res.headers.get(RATE_LIMIT_HEADER))
Copy link
Contributor

Choose a reason for hiding this comment

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

this is cool!


await sleep(delay)

return fetchAndRetry(fetcher, url, options, attemptsLeft - 1)
}

return res
} catch (error) {
if (attemptsLeft === 0) {
throw error
}

const delay = getDelay()

await sleep(delay)

return fetchAndRetry(fetcher, url, options, attemptsLeft - 1)
}
}

const getDelay = (rateLimitReset?: string | null) => {
if (!rateLimitReset) {
return DEFAULT_RETRY_DELAY
}

return Math.max(Number(rateLimitReset) * 1000 - Date.now(), MIN_RETRY_DELAY)
}

const sleep = (ms: number) =>
new Promise((resolve) => {
setTimeout(resolve, ms)
})