-
Notifications
You must be signed in to change notification settings - Fork 2
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
feat: adding exponential backoff #26
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,7 @@ import { ProviderError } from "../errors.js"; | |
import { throwErrorIfResponseNotOk } from "./fetch.js"; | ||
|
||
const CLOUDFLARE_HOST = "https://api.cloudflare.com/client/v4"; | ||
const MAX_RETRIES = 5; | ||
|
||
export function getCredentials() { | ||
const QUEUES_API_TOKEN = process.env.QUEUES_API_TOKEN; | ||
|
@@ -17,13 +18,57 @@ export function getCredentials() { | |
}; | ||
} | ||
|
||
function calculateDelay(attempt: number): number { | ||
return Math.pow(2, attempt) * 100 + Math.random() * 100; | ||
} | ||
|
||
function shouldRetry( | ||
error: unknown, | ||
attempt: number, | ||
maxRetries: number, | ||
): boolean { | ||
return ( | ||
error instanceof ProviderError && | ||
error.message.includes("429") && | ||
attempt < maxRetries | ||
); | ||
} | ||
|
||
async function exponentialBackoff<T>( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function |
||
fn: () => Promise<T>, | ||
maxRetries: number, | ||
): Promise<T> { | ||
let attempt = 0; | ||
while (attempt < maxRetries) { | ||
try { | ||
return await fn(); | ||
} catch (error) { | ||
if (shouldRetry(error, attempt, maxRetries)) { | ||
attempt++; | ||
const delay = calculateDelay(attempt); | ||
await new Promise((resolve) => setTimeout(resolve, delay)); | ||
} else { | ||
throw error; | ||
} | ||
} | ||
} | ||
throw new ProviderError("Max retries reached"); | ||
} | ||
|
||
export async function queuesClient<T = unknown>({ | ||
path, | ||
method, | ||
body, | ||
accountId, | ||
queueId, | ||
signal, | ||
}: { | ||
path: string; | ||
method: string; | ||
body?: Record<string, unknown>; | ||
accountId: string; | ||
queueId: string; | ||
signal?: AbortSignal; | ||
}): Promise<T> { | ||
const { QUEUES_API_TOKEN } = getCredentials(); | ||
|
||
|
@@ -38,15 +83,23 @@ export async function queuesClient<T = unknown>({ | |
signal, | ||
}; | ||
|
||
const response = await fetch(url, options); | ||
async function fetchWithBackoff() { | ||
const response = await fetch(url, options); | ||
|
||
if (!response) { | ||
throw new ProviderError("No response from Cloudflare Queues API"); | ||
} | ||
if (!response) { | ||
throw new ProviderError("No response from Cloudflare Queues API"); | ||
} | ||
|
||
if (response.status === 429) { | ||
throw new ProviderError("429 Too Many Requests"); | ||
} | ||
|
||
throwErrorIfResponseNotOk(response); | ||
throwErrorIfResponseNotOk(response); | ||
|
||
const data = (await response.json()) as T; | ||
const data = (await response.json()) as T; | ||
|
||
return data; | ||
} | ||
|
||
return data; | ||
return exponentialBackoff(fetchWithBackoff, MAX_RETRIES); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
import { describe, it, beforeEach, afterEach } from "node:test"; | ||
import { assert } from "chai"; | ||
import nock from "nock"; | ||
import sinon from "sinon"; | ||
|
||
import { queuesClient } from "../../../src/lib/cloudflare"; | ||
import { ProviderError } from "../../../src/errors"; | ||
|
||
const CLOUDFLARE_HOST = "https://api.cloudflare.com/client/v4"; | ||
const ACCOUNT_ID = "test-account-id"; | ||
const QUEUE_ID = "test-queue-id"; | ||
const QUEUES_API_TOKEN = "test-queues-api-token"; | ||
|
||
describe("queuesClient", () => { | ||
let sandbox: sinon.SinonSandbox; | ||
|
||
beforeEach(() => { | ||
sandbox = sinon.createSandbox(); | ||
process.env.QUEUES_API_TOKEN = QUEUES_API_TOKEN; | ||
}); | ||
|
||
afterEach(() => { | ||
sandbox.restore(); | ||
delete process.env.QUEUES_API_TOKEN; | ||
nock.cleanAll(); | ||
}); | ||
|
||
it("should successfully fetch data from Cloudflare Queues API", async () => { | ||
const path = "messages"; | ||
const method = "GET"; | ||
const responseBody = { success: true, result: [] }; | ||
|
||
nock(CLOUDFLARE_HOST) | ||
.get(`/accounts/${ACCOUNT_ID}/queues/${QUEUE_ID}/${path}`) | ||
.reply(200, responseBody); | ||
|
||
const result = await queuesClient({ | ||
path, | ||
method, | ||
accountId: ACCOUNT_ID, | ||
queueId: QUEUE_ID, | ||
}); | ||
|
||
assert.deepEqual(result, responseBody); | ||
}); | ||
|
||
it("should throw an error if the API token is missing", async () => { | ||
delete process.env.QUEUES_API_TOKEN; | ||
|
||
try { | ||
await queuesClient({ | ||
path: "messages", | ||
method: "GET", | ||
accountId: ACCOUNT_ID, | ||
queueId: QUEUE_ID, | ||
}); | ||
assert.fail("Expected error to be thrown"); | ||
} catch (error) { | ||
assert.instanceOf(error, Error); | ||
assert.equal( | ||
error.message, | ||
"Missing Cloudflare credentials, please set a QUEUES_API_TOKEN in the environment variables.", | ||
); | ||
} | ||
}); | ||
|
||
it("should retry on 429 Too Many Requests", async () => { | ||
const path = "messages"; | ||
const method = "GET"; | ||
const responseBody = { success: true, result: [] }; | ||
|
||
nock(CLOUDFLARE_HOST) | ||
.get(`/accounts/${ACCOUNT_ID}/queues/${QUEUE_ID}/${path}`) | ||
.reply(429, "Too Many Requests") | ||
.get(`/accounts/${ACCOUNT_ID}/queues/${QUEUE_ID}/${path}`) | ||
.reply(200, responseBody); | ||
|
||
const result = await queuesClient({ | ||
path, | ||
method, | ||
accountId: ACCOUNT_ID, | ||
queueId: QUEUE_ID, | ||
}); | ||
|
||
assert.deepEqual(result, responseBody); | ||
}); | ||
|
||
it("should throw ProviderError after max retries", async () => { | ||
const path = "messages"; | ||
const method = "GET"; | ||
|
||
nock(CLOUDFLARE_HOST) | ||
.get(`/accounts/${ACCOUNT_ID}/queues/${QUEUE_ID}/${path}`) | ||
.times(5) | ||
.reply(429, "Too Many Requests"); | ||
|
||
try { | ||
await queuesClient({ | ||
path, | ||
method, | ||
accountId: ACCOUNT_ID, | ||
queueId: QUEUE_ID, | ||
}); | ||
assert.fail("Expected error to be thrown"); | ||
} catch (error) { | ||
assert.instanceOf(error, ProviderError); | ||
assert.equal(error.message, "Max retries reached"); | ||
} | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function
exponentialBackoff
has a Cognitive Complexity of 8 (exceeds 5 allowed). Consider refactoring.