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

Allow supplying a retry handler to generated API clients #271

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions oxide-api/src/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ export interface FullParams extends FetchParams {
method?: string;
}

export type RetryHandler = (err: any) => boolean;
export type RetryHandlerFactory = (
url: RequestInfo | URL,
init: RequestInit,
) => RetryHandler;

export interface ApiConfig {
/**
* No host means requests will be sent to the current host. This is used in
Expand All @@ -125,14 +131,21 @@ export interface ApiConfig {
host?: string;
token?: string;
baseParams?: FetchParams;
retryHandler?: RetryHandlerFactory;
}

export class HttpClient {
host: string;
token?: string;
baseParams: FetchParams;

constructor({ host = "", baseParams = {}, token }: ApiConfig = {}) {
retryHandler: RetryHandlerFactory;

constructor({
host = "",
baseParams = {},
token,
retryHandler,
}: ApiConfig = {}) {
this.host = host;
this.token = token;

Expand All @@ -141,6 +154,7 @@ export class HttpClient {
headers.append("Authorization", `Bearer ${token}`);
}
this.baseParams = mergeParams({ headers }, baseParams);
this.retryHandler = retryHandler ? retryHandler : () => () => false;
}

public async request<Data>({
Expand All @@ -155,7 +169,24 @@ export class HttpClient {
...mergeParams(this.baseParams, fetchParams),
body: JSON.stringify(snakeify(body), replacer),
};
return fetchWithRetry(fetch, url, init, this.retryHandler(url, init));
}
}

export async function fetchWithRetry<Data>(
fetch: any,
url: string,
init: RequestInit,
retry: RetryHandler,
): Promise<ApiResult<Data>> {
try {
return handleResponse(await fetch(url, init));
} catch (err) {
if (retry(err)) {
return await fetchWithRetry(fetch, url, init, retry);
}

throw err;
}
}

Expand Down
37 changes: 36 additions & 1 deletion oxide-openapi-gen-ts/src/client/static/http-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* Copyright Oxide Computer Company
*/

import { handleResponse, mergeParams } from "./http-client";
import { fetchWithRetry, handleResponse, mergeParams } from "./http-client";
import { describe, expect, it } from "vitest";

const headers = { "Content-Type": "application/json" };
Expand All @@ -17,6 +17,41 @@
const json = (body: any, status = 200) =>
new Response(JSON.stringify(body), { status, headers });

describe("fetchWithRetry", () => {
it("retries request when handler returns true", async () => {
const retryLimit = 1
let retries = 0
const retryHandler = () => {
if (retries >= retryLimit) {
return false
} else {
retries += 1
return true
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will review in more detail, but my immediate reaction is that as implemented, the retry logic is still entirely outside the client and fetchWithRetry doesn't add that much. I'll try and put together a version of this that doesn't require fetchWithRetry and we can compare.

Here's an example in the console that uses the p-retry library. It's not exactly analogous, but the mutateAsync call is very close to calling the client method directly.

https://github.com/oxidecomputer/console/blob/1625d02a540035e6b10e6222e7ef709691dda7f1/app/forms/image-upload.tsx#L424-L429

Copy link
Contributor Author

@augustuswm augustuswm Sep 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is super low priority, I'm doing something similar already where I am wrapping the client in a retry. It is certainly acceptable that we don't want this as part of the client itself. I think the only reason for it, is that it is likely almost entirely incorrect to use a generated client without a retry around it given that we are using the default node http(s) agents.


try {
await fetchWithRetry(() => { throw new Error("unimplemented") }, "empty_url", {}, retryHandler)
} catch {
// Throw away any errors we receive, we are only interested in ensuring the retry handler
// gets called and that retries terminate
}

expect(retries).toEqual(1)
});

it("rethrows error when handler returns false", async () => {
const retryHandler = () => false

try {
await fetchWithRetry(() => { throw new Error("unimplemented") }, "empty_url", {}, retryHandler)
throw new Error("Unreachable. This is a bug")
} catch (err: any) {

Check failure on line 49 in oxide-openapi-gen-ts/src/client/static/http-client.test.ts

View workflow job for this annotation

GitHub Actions / validate

Unexpected any. Specify a different type
expect(err.message).toEqual("unimplemented")
}
});
});

describe("handleResponse", () => {
it("handles success", async () => {
const { response, ...rest } = await handleResponse(json({ abc: 123 }));
Expand Down
20 changes: 19 additions & 1 deletion oxide-openapi-gen-ts/src/client/static/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@
method?: string;
}

export type RetryHandler = (err: any) => boolean;

Check failure on line 120 in oxide-openapi-gen-ts/src/client/static/http-client.ts

View workflow job for this annotation

GitHub Actions / validate

Unexpected any. Specify a different type
export type RetryHandlerFactory = (url: RequestInfo | URL, init: RequestInit) => RetryHandler;

export interface ApiConfig {
/**
* No host means requests will be sent to the current host. This is used in
Expand All @@ -125,14 +128,16 @@
host?: string;
token?: string;
baseParams?: FetchParams;
retryHandler?: RetryHandlerFactory;
}

export class HttpClient {
host: string;
token?: string;
baseParams: FetchParams;
retryHandler: RetryHandlerFactory;

constructor({ host = "", baseParams = {}, token }: ApiConfig = {}) {
constructor({ host = "", baseParams = {}, token, retryHandler }: ApiConfig = {}) {
this.host = host;
this.token = token;

Expand All @@ -141,6 +146,7 @@
headers.append("Authorization", `Bearer ${token}`);
}
this.baseParams = mergeParams({ headers }, baseParams);
this.retryHandler = retryHandler ? retryHandler : () => () => false;
}

public async request<Data>({
Expand All @@ -155,7 +161,19 @@
...mergeParams(this.baseParams, fetchParams),
body: JSON.stringify(snakeify(body), replacer),
};
return fetchWithRetry(fetch, url, init, this.retryHandler(url, init))
}
}

export async function fetchWithRetry<Data>(fetch: any, url: string, init: RequestInit, retry: RetryHandler): Promise<ApiResult<Data>> {

Check failure on line 168 in oxide-openapi-gen-ts/src/client/static/http-client.ts

View workflow job for this annotation

GitHub Actions / validate

Unexpected any. Specify a different type
try {
return handleResponse(await fetch(url, init));
} catch (err) {
if (retry(err)) {
return await fetchWithRetry(fetch, url, init, retry)
}

throw err
}
}

Expand Down
Loading