Skip to content

Commit

Permalink
fix: don't sleep after the last retry attempt (#207)
Browse files Browse the repository at this point in the history
  • Loading branch information
CahidArda authored Nov 4, 2024
1 parent 89fe537 commit 72ffdfd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
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

0 comments on commit 72ffdfd

Please sign in to comment.