Skip to content

Commit

Permalink
Add exponential backoff to Cloudflare API calls
Browse files Browse the repository at this point in the history
  • Loading branch information
teddyphreak committed Mar 1, 2024
1 parent 64f61c7 commit 041b121
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 10 deletions.
6 changes: 4 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
.PHONY: install lint eslint prettier build webpack test version run

BUNDLE=./dist/deploy.cjs

install:
npm ci

Expand All @@ -24,10 +26,10 @@ test: build
npx vitest run

version: install build
node --no-warnings ./dist/deploy.cjs --version
node --no-warnings ${BUNDLE} --version

run:
@node --no-warnings ./dist/deploy.cjs $(filter-out run,$(MAKECMDGOALS))
@node --no-warnings ${BUNDLE} $(filter-out run,$(MAKECMDGOALS))

%:
@:
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"name": "@nephelaiio/worker-deploy",
"type": "module",
"version": "0.2.3",
"description": "",
"version": "0.2.4",
"description": "CLI helpers for Cloudflare Worker management",
"main": "dist/deploy.cjs",
"repository": {
"type": "git",
Expand All @@ -11,7 +11,7 @@
"bin": {
"worker-deploy": "./dist/deploy.cjs"
},
"author": "",
"author": "Teodoro Cook <[email protected]>",
"license": "MIT",
"devDependencies": {
"@cloudflare/workers-types": "^4.20230404.0",
Expand All @@ -35,7 +35,7 @@
"@iarna/toml": "^2.2.5",
"@nephelaiio/logger": "^0.0.5",
"commander": "^10.0.1",
"dotenv": "^16.0.3",
"dotenv": "^16.3.1",
"isomorphic-git": "^1.23.0",
"octokit": "^2.0.14",
"winston": "^3.9.0",
Expand Down
9 changes: 8 additions & 1 deletion src/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const ORIGINLESS_TYPE = 'AAAA';
const ORIGINLESS_CONTENT = '100::';
const CLOUDFLARE_TIMEOUT = 5000;
const CLOUDFLARE_RETRIES = 3;
const CLOUDFLARE_BACKOFF = 30;

type ApiMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD';
export type Route = {
Expand All @@ -15,14 +16,20 @@ export type Route = {
id?: string;
};

async function retry(fn: () => Promise<any>, times = CLOUDFLARE_RETRIES) {
const delay = (s: number) => new Promise(res => setTimeout(res, s));

async function retry(
fn: () => Promise<any>,
times = CLOUDFLARE_RETRIES,
backoff = CLOUDFLARE_BACKOFF) {
for (let i = 0; i < times; i++) {
try {
return await fn();
} catch (e) {
if (i == times - 1) {
throw e;
}
await delay(backoff * Math.pow(2, i + 1));
}
}
}
Expand Down

0 comments on commit 041b121

Please sign in to comment.