Skip to content

Commit 0b8907c

Browse files
authored
chore: Add jittered retry on auth call (#6524)
1 parent 85a78d4 commit 0b8907c

File tree

1 file changed

+45
-18
lines changed
  • packages/service-utils/src/core

1 file changed

+45
-18
lines changed

packages/service-utils/src/core/api.ts

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ export type CoreServiceConfig = {
2222
serviceApiKey: string;
2323
serviceAction?: string;
2424
useWalletAuth?: boolean;
25+
/**
26+
* The number of times to retry the auth request. Default = 3.
27+
*/
28+
retryCount?: number;
2529
};
2630

2731
export type TeamAndProjectResponse = {
@@ -179,23 +183,46 @@ export async function fetchTeamAndProject(
179183
if (teamId) {
180184
url.searchParams.set("teamId", teamId);
181185
}
182-
const response = await fetch(url, {
183-
method: "GET",
184-
headers: {
185-
...(authData.secretKey ? { "x-secret-key": authData.secretKey } : {}),
186-
...(authData.jwt ? { Authorization: `Bearer ${authData.jwt}` } : {}),
187-
"x-service-api-key": serviceApiKey,
188-
"content-type": "application/json",
189-
},
190-
});
191-
192-
let text = "";
193-
try {
194-
text = await response.text();
195-
return JSON.parse(text);
196-
} catch {
197-
throw new Error(
198-
`Error fetching key metadata from API: ${response.status} - ${text}`,
199-
);
186+
187+
const retryCount = config.retryCount ?? 3;
188+
let error: unknown | undefined;
189+
for (let i = 0; i < retryCount; i++) {
190+
try {
191+
const response = await fetch(url, {
192+
method: "GET",
193+
headers: {
194+
...(authData.secretKey ? { "x-secret-key": authData.secretKey } : {}),
195+
...(authData.jwt ? { Authorization: `Bearer ${authData.jwt}` } : {}),
196+
"x-service-api-key": serviceApiKey,
197+
"content-type": "application/json",
198+
},
199+
});
200+
201+
let text = "";
202+
try {
203+
text = await response.text();
204+
return JSON.parse(text);
205+
} catch {
206+
throw new Error(
207+
`Error fetching key metadata from API: ${response.status} - ${text}`,
208+
);
209+
}
210+
} catch (err: unknown) {
211+
error = err;
212+
if (i < retryCount - 1) {
213+
// Add a single retry with a delay between 20ms and 400ms.
214+
await sleepRandomMs(20, 400);
215+
}
216+
}
200217
}
218+
throw error;
219+
}
220+
221+
/**
222+
* Sleeps for a random amount of time between min and max, in milliseconds.
223+
*/
224+
function sleepRandomMs(min: number, max: number) {
225+
return new Promise((resolve) =>
226+
setTimeout(resolve, Math.random() * (max - min) + min),
227+
);
201228
}

0 commit comments

Comments
 (0)