Skip to content

Commit 88d43c3

Browse files
meorphismeorphis
andauthored
retry on 401 (#209)
Co-authored-by: meorphis <eric@stainless.com>
1 parent 71d0c64 commit 88d43c3

5 files changed

Lines changed: 89 additions & 5 deletions

File tree

dist/build.js

Lines changed: 19 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

dist/merge.js

Lines changed: 19 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

dist/preview.js

Lines changed: 19 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/stainless.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,29 @@ export function createAutoRefreshFetch(
3030
};
3131
}
3232

33+
/**
34+
* adds retries to a fetch function for 401 responses, as it seems that OIDC decode on the server can
35+
* occasionally fail transiently
36+
*/
37+
export const addFetch401Retries = (
38+
fetch: typeof globalThis.fetch,
39+
{ numRetries }: { numRetries: number },
40+
): typeof globalThis.fetch => {
41+
return async (input, init) => {
42+
let attempts = 0;
43+
let response;
44+
do {
45+
response = await fetch(input, init);
46+
if (response.status !== 401) {
47+
break;
48+
}
49+
attempts++;
50+
logger.warn("Received 401 response, retrying...");
51+
} while (attempts <= numRetries);
52+
return response;
53+
};
54+
};
55+
3356
export function getStainlessClient(
3457
action: string | undefined,
3558
opts: ClientOptions,

src/wrapAction.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import Stainless from "@stainless-api/sdk";
22
import { getInput } from "./compat/input";
33
import { getStainlessAuth } from "./compat";
4-
import { createAutoRefreshFetch, getStainlessClient } from "./stainless";
4+
import {
5+
addFetch401Retries,
6+
createAutoRefreshFetch,
7+
getStainlessClient,
8+
} from "./stainless";
59
import { logger } from "./logger";
610

711
const accumulatedBuildIds = new Set<string>();
@@ -33,7 +37,10 @@ export function wrapAction(
3337
apiKey: auth.key,
3438
logLevel: "warn",
3539
logger,
36-
fetch: createAutoRefreshFetch(auth, getStainlessAuth),
40+
fetch: addFetch401Retries(
41+
createAutoRefreshFetch(auth, getStainlessAuth),
42+
{ numRetries: 2 },
43+
),
3744
});
3845
await fn(stainless);
3946
await maybeReportResult({

0 commit comments

Comments
 (0)