diff --git a/src/client/http.test.ts b/src/client/http.test.ts new file mode 100644 index 0000000..9cf79ff --- /dev/null +++ b/src/client/http.test.ts @@ -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?"); + }); +}); diff --git a/src/client/http.ts b/src/client/http.ts index b15b655..193f810 100644 --- a/src/client/http.ts +++ b/src/client/http.ts @@ -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), }; } @@ -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) {