-
Notifications
You must be signed in to change notification settings - Fork 15
fix(api-client): fix retry failing and add a timeout of 30s #305
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| import { afterEach, describe, expect, it, vi } from "vitest"; | ||
| import { APIError, apiFetch } from "./fetch"; | ||
|
|
||
| describe("apiFetch", () => { | ||
| afterEach(() => { | ||
| vi.useRealTimers(); | ||
| vi.restoreAllMocks(); | ||
| }); | ||
|
|
||
| it("retries server errors with a fresh request and replays the body", async () => { | ||
| const cloneSpy = vi | ||
| .spyOn(Request.prototype, "clone") | ||
| .mockImplementation(() => { | ||
| throw new TypeError("unusable"); | ||
| }); | ||
| const bodies: string[] = []; | ||
| const fetchMock = vi.fn(async (input: RequestInfo | URL) => { | ||
| const request = input instanceof Request ? input : new Request(input); | ||
| bodies.push(await request.text()); | ||
|
|
||
| return new Response("{}", { | ||
| status: bodies.length === 1 ? 500 : 200, | ||
| }); | ||
| }); | ||
| const body = JSON.stringify({ commit: "abc123" }); | ||
| const request = new Request("https://api.argos-ci.test/builds", { | ||
| body, | ||
| headers: { | ||
| "content-type": "application/json", | ||
| }, | ||
| method: "POST", | ||
| }); | ||
|
|
||
| const response = await apiFetch(request, { | ||
| fetch: fetchMock as unknown as typeof fetch, | ||
| minTimeout: 0, | ||
| }); | ||
|
|
||
| expect(response.status).toBe(200); | ||
| expect(fetchMock).toHaveBeenCalledTimes(2); | ||
| expect(bodies).toEqual([body, body]); | ||
| expect(cloneSpy).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("does not retry client errors", async () => { | ||
| const fetchMock = vi.fn(async () => new Response("{}", { status: 400 })); | ||
|
|
||
| const response = await apiFetch( | ||
| new Request("https://api.argos-ci.test/builds"), | ||
| { | ||
| fetch: fetchMock as unknown as typeof fetch, | ||
| minTimeout: 0, | ||
| }, | ||
| ); | ||
|
|
||
| expect(response.status).toBe(400); | ||
| expect(fetchMock).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("throws APIError after server error retries are exhausted", async () => { | ||
| const fetchMock = vi.fn(async () => new Response("{}", { status: 503 })); | ||
|
|
||
| const promise = apiFetch(new Request("https://api.argos-ci.test/builds"), { | ||
| fetch: fetchMock as unknown as typeof fetch, | ||
| minTimeout: 0, | ||
| retries: 1, | ||
| }); | ||
|
|
||
| await expect(promise).rejects.toThrow(APIError); | ||
| await expect(promise).rejects.toThrow("Internal Server Error (503)"); | ||
|
|
||
| expect(fetchMock).toHaveBeenCalledTimes(2); | ||
| }); | ||
|
|
||
| it("aborts the request after the configured timeout", async () => { | ||
| const fetchMock = vi.fn( | ||
| async (input: RequestInfo | URL) => | ||
| new Promise<Response>((_resolve, reject) => { | ||
| const request = input instanceof Request ? input : new Request(input); | ||
| if (request.signal.aborted) { | ||
| reject(request.signal.reason); | ||
| return; | ||
| } | ||
| request.signal.addEventListener( | ||
| "abort", | ||
| () => reject(request.signal.reason), | ||
| { once: true }, | ||
| ); | ||
| }), | ||
| ); | ||
|
|
||
| await expect( | ||
| apiFetch(new Request("https://api.argos-ci.test/builds"), { | ||
| fetch: fetchMock as unknown as typeof fetch, | ||
| minTimeout: 0, | ||
| retries: 0, | ||
| timeout: 1, | ||
| }), | ||
| ).rejects.toMatchObject({ | ||
| name: "TimeoutError", | ||
| }); | ||
| expect(fetchMock).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("preserves caller cancellation signal", async () => { | ||
| const controller = new AbortController(); | ||
| const reason = new Error("cancelled by caller"); | ||
| const fetchMock = vi.fn( | ||
| async (input: RequestInfo | URL) => | ||
| new Promise<Response>((_resolve, reject) => { | ||
| const request = input instanceof Request ? input : new Request(input); | ||
| if (request.signal.aborted) { | ||
| reject(request.signal.reason); | ||
| return; | ||
| } | ||
| request.signal.addEventListener( | ||
| "abort", | ||
| () => reject(request.signal.reason), | ||
| { once: true }, | ||
| ); | ||
| }), | ||
| ); | ||
|
|
||
| const promise = apiFetch( | ||
| new Request("https://api.argos-ci.test/builds", { | ||
| signal: controller.signal, | ||
| }), | ||
| { | ||
| fetch: fetchMock as unknown as typeof fetch, | ||
| minTimeout: 0, | ||
| }, | ||
| ); | ||
| const rejection = promise.catch((error: unknown) => error); | ||
|
|
||
| controller.abort(reason); | ||
|
|
||
| await expect(rejection).resolves.toBe(reason); | ||
| expect(fetchMock).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("does not call fetch when the caller signal is already aborted", async () => { | ||
| const controller = new AbortController(); | ||
| const reason = new Error("already cancelled"); | ||
| const fetchMock = vi.fn(async () => new Response("{}")); | ||
|
|
||
| controller.abort(reason); | ||
|
|
||
| await expect( | ||
| apiFetch( | ||
| new Request("https://api.argos-ci.test/builds", { | ||
| signal: controller.signal, | ||
| }), | ||
| { | ||
| fetch: fetchMock as unknown as typeof fetch, | ||
| }, | ||
| ), | ||
| ).rejects.toBe(reason); | ||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| import pRetry from "p-retry"; | ||
| import { debug } from "./debug"; | ||
|
|
||
| const DEFAULT_TIMEOUT = 30_000; | ||
|
|
||
| export class APIError extends Error { | ||
| constructor(message: string) { | ||
| super(message); | ||
| } | ||
| } | ||
|
|
||
| interface APIFetchOptions { | ||
| fetch?: typeof fetch; | ||
| minTimeout?: number; | ||
| retries?: number; | ||
| timeout?: number; | ||
| } | ||
|
|
||
| async function createRequestFactory(request: Request, timeout: number) { | ||
| // Snapshot the body once so retries do not clone/tee the original Request. | ||
| const body = request.body ? await request.arrayBuffer() : undefined; | ||
| const headers = new Headers(request.headers); | ||
|
|
||
| return () => | ||
| new Request(request.url, { | ||
| body, | ||
| cache: request.cache, | ||
| credentials: request.credentials, | ||
| headers, | ||
| integrity: request.integrity, | ||
| keepalive: request.keepalive, | ||
| method: request.method, | ||
| mode: request.mode, | ||
| redirect: request.redirect, | ||
| referrer: request.referrer, | ||
| referrerPolicy: request.referrerPolicy, | ||
| signal: AbortSignal.any([request.signal, AbortSignal.timeout(timeout)]), | ||
| }); | ||
| } | ||
|
|
||
| export async function apiFetch(input: Request, options: APIFetchOptions = {}) { | ||
| input.signal.throwIfAborted(); | ||
|
|
||
| const fetchImpl = options.fetch ?? fetch; | ||
| const createRequest = await createRequestFactory( | ||
| input, | ||
| options.timeout ?? DEFAULT_TIMEOUT, | ||
| ); | ||
|
|
||
| return pRetry( | ||
| async () => { | ||
| const response = await fetchImpl(createRequest()); | ||
| if (response.status >= 500) { | ||
| throw new APIError(`Internal Server Error (${response.status})`); | ||
| } | ||
| return response; | ||
| }, | ||
| { | ||
| minTimeout: options.minTimeout, | ||
| retries: options.retries ?? 3, | ||
| shouldRetry: () => !input.signal.aborted, | ||
| onFailedAttempt: (context) => { | ||
| debug("API request failed", context.error.message); | ||
| if (context.retriesLeft > 0) { | ||
| debug(`Retrying API request... (${context.retriesLeft} left)`); | ||
| } | ||
| }, | ||
| }, | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.