Skip to content

Commit

Permalink
add handle to 429 error
Browse files Browse the repository at this point in the history
  • Loading branch information
vsseixaso committed Jul 10, 2024
1 parent 7e7a68f commit ab96396
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 8 deletions.
27 changes: 19 additions & 8 deletions node/middlewares/generateMiddlewares/generateProductRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
Message,
PRODUCT_ROUTES_INDEX,
RAW_DATA_PREFIX,
retryOn429,
SitemapEntry,
SitemapIndex,
slugify,
Expand Down Expand Up @@ -184,14 +185,24 @@ const saveRoutes = (
)
index.push(entry)
const lastUpdated = currentDate()
await vbase.saveJSON<SitemapEntry>(bucket, entry, {
lastUpdated,
routes,
})
await vbase.saveJSON<SitemapIndex>(bucket, PRODUCT_ROUTES_INDEX, {
index,
lastUpdated,
})

try {
await retryOn429(() =>
vbase.saveJSON<SitemapEntry>(bucket, entry, {
lastUpdated,
routes,
})
)

await retryOn429(() =>
vbase.saveJSON<SitemapIndex>(bucket, PRODUCT_ROUTES_INDEX, {
index,
lastUpdated,
})
)
} catch (error) {
console.error(`Failed to save data after retries: ${error.message}`)
}
}

const pageWasProcessed = async (
Expand Down
23 changes: 23 additions & 0 deletions node/middlewares/generateMiddlewares/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,26 @@ export const cleanConfigBucket = async (enabledIndexFiles: string[], vbase: VBas
])

const allTruthy = <T>(array: T[]) => !array.some(e => !e)

const delay = (ms: number) => new Promise(res => setTimeout(res, ms))

export const retryOn429 = async (
fn: () => Promise<unknown>,
maxRetries = 3,
attempt = 0
): Promise<void> => {
try {
await fn()
} catch (error) {
if (error.status === 429 && attempt < maxRetries) {
const waitTime = 2 ** (attempt + 1) * 1000
console.warn(
`HTTP 429 received, retrying in ${waitTime / 1000} seconds...`
)
await delay(waitTime)
return retryOn429(fn, maxRetries, attempt + 1)
}

throw error
}
}

0 comments on commit ab96396

Please sign in to comment.