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

Remove sleep after the last retry attempt #207

Merged
merged 1 commit into from
Nov 4, 2024
Merged
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
25 changes: 25 additions & 0 deletions src/client/http.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/* eslint-disable @typescript-eslint/no-magic-numbers */
import { describe, test, expect } from "bun:test";
import { Client } from "./client";

describe("http", () => {
test("should terminate after sleeping 5 times", () => {
// init a cient which will always get errors
const client = new Client({
baseUrl: "https:/",
token: "",
// set retry explicitly
retry: {
retries: 5,
backoff: (retryCount) => Math.exp(retryCount) * 50,
},
});

// get should take 4.287 seconds and terminate before the timeout.
const throws = () =>
Promise.race([client.dlq.listMessages(), new Promise((r) => setTimeout(r, 4500))]);

// if the Promise.race doesn't throw, that means the retries took longer than 4.5s
expect(throws).toThrow("Was there a typo in the url or port?");
});
});
10 changes: 7 additions & 3 deletions src/client/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export class HttpClient implements Requester {
backoff: () => 0,
}
: {
attempts: config.retry?.retries ? config.retry.retries + 1 : 5,
attempts: config.retry?.retries ?? 5,
backoff: config.retry?.backoff ?? ((retryCount) => Math.exp(retryCount) * 50),
};
}
Expand Down Expand Up @@ -172,13 +172,17 @@ export class HttpClient implements Requester {

let response: Response | undefined = undefined;
let error: Error | undefined = undefined;
for (let index = 0; index < this.retry.attempts; index++) {
for (let index = 0; index <= this.retry.attempts; index++) {
try {
response = await fetch(url.toString(), requestOptions);
break;
} catch (error_) {
error = error_ as Error;
await new Promise((r) => setTimeout(r, this.retry.backoff(index)));

// Only sleep if this is not the last attempt
if (index < this.retry.attempts) {
await new Promise((r) => setTimeout(r, this.retry.backoff(index)));
}
}
}
if (!response) {
Expand Down
Loading