Skip to content

Commit

Permalink
add backoff and retry to fetches (#17)
Browse files Browse the repository at this point in the history
Signed-off-by: Jason Hall <[email protected]>
  • Loading branch information
imjasonh authored Mar 18, 2024
1 parent 9e4cb10 commit 60c0a50
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,32 @@ if (!scope || !identity) {
process.exit(1);
}

async function fetchWithRetry(url, options = {}, retries = 3, initialDelay = 1000) {
let attempt = 1;
while (retries > 0) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response;
} catch (error) {
console.warn(`Attempt ${attempt} failed. Error: ${error.message}`);
const delay = Math.min(2 ** attempt * initialDelay, 10000); // Limit max delay to 10 seconds
await new Promise(resolve => setTimeout(resolve, delay));
attempt++;
retries--;
}
}
throw new Error(`Fetch failed after ${attempt} attempts.`);
}

(async function main() {
// You can use await inside this function block
try {
const res = await fetch(`${actionsUrl}&audience=octo-sts.dev`, { headers: { 'Authorization': `Bearer ${actionsToken}` } });
const res = await fetchWithRetry(`${actionsUrl}&audience=octo-sts.dev`, { headers: { 'Authorization': `Bearer ${actionsToken}` } }, 5);
const json = await res.json();
const res2 = await fetch(`https://octo-sts.dev/sts/exchange?scope=${scope}&identity=${identity}`, { headers: { 'Authorization': `Bearer ${json.value}` } });
const res2 = await fetchWithRetry(`https://octo-sts.dev/sts/exchange?scope=${scope}&identity=${identity}`, { headers: { 'Authorization': `Bearer ${json.value}` } });
const json2 = await res2.json();

if (!json2.token) { console.log(`::error::${json2.message}`); process.exit(1); }
Expand Down

0 comments on commit 60c0a50

Please sign in to comment.