Skip to content
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

add backoff and retry to fetches #17

Merged
merged 10 commits into from
Mar 18, 2024
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) {
imjasonh marked this conversation as resolved.
Show resolved Hide resolved
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}` } }, 5);
const json2 = await res2.json();

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