From ae309a0af696dea29a84768862bc21674d8f790d Mon Sep 17 00:00:00 2001 From: Muneerali199 Date: Thu, 19 Nov 2026 00:52:15 +0530 Subject: [PATCH] feat: add opt-in send retries Add retrySend client option so send() can use the existing retry/backoff policy for 5xx and network errors while keeping the default non-retry behavior and fast failure for 4xx responses. Signed-off-by: Muneerali199 --- README.md | 5 ++- src/client.ts | 9 +++-- src/types.ts | 2 ++ tests/client.test.ts | 85 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e5dfb7c..d9cb957 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ A **zero-dependency** TypeScript SDK for the [ThruBox Server](https://github.com - **Zero Runtime Dependencies**: Only devDependencies for build/test - **Typed Errors**: Specific error classes for rate limiting, payload size, not found, etc. -- **Automatic Retry**: Exponential backoff on 5xx and network errors +- **Automatic Retry**: Exponential backoff on 5xx and network errors, with opt-in retries for `send()` - **Polling**: Built-in `poll()` helper with a stop function - **Dual Format**: Ships ESM + CJS with TypeScript declarations - **Tiny**: ~2.5 KB minified @@ -144,11 +144,14 @@ npm run lint # ESLint | `apiKey` | `string` | — | API key for authenticated servers | | `timeout` | `number` | `10000` | Request timeout in ms | | `retries` | `number` | `3` | Retry attempts on network errors / 5xx | +| `retrySend` | `boolean` | `false` | Retry `send()` (POST) on 5xx / network errors; 401/413/429 still fail fast | ### `relay.send(params): Promise` Send an encrypted message to the relay. The returned message carries the server-assigned `id` and, on ThruBox Server 1.0 or later, its `seq`. On those servers sending an identical message twice is safe: it is stored once and the existing message is returned. +`send()` is not retried by default. Set `retrySend: true` to use the client's standard exponential backoff for 5xx and network/timeout errors; 401, 413, 429 and other 4xx responses still fail immediately. Pre-1.0 servers may not deduplicate messages, so leave this disabled when duplicate sends are a concern. + ### `relay.receive(address, options?): Promise` Fetch messages for a wallet address, oldest first. diff --git a/src/client.ts b/src/client.ts index af7a994..6ce4e7d 100644 --- a/src/client.ts +++ b/src/client.ts @@ -42,6 +42,7 @@ export class RelayClient { private readonly apiKey: string | undefined; private readonly timeout: number; private readonly retries: number; + private readonly retrySend: boolean; /** * Create a new RelayClient pointing to any relay server. @@ -57,12 +58,15 @@ export class RelayClient { } this.baseUrl = parsedUrl.toString().replace(/\/+$/, ""); } catch (err) { - throw new Error(`Invalid base URL: ${err instanceof Error ? err.message : String(err)}`); + throw new Error(`Invalid base URL: ${err instanceof Error ? err.message : String(err)}`, { + cause: err, + }); } this.apiKey = options?.apiKey; this.timeout = options?.timeout ?? DEFAULT_TIMEOUT; this.retries = options?.retries ?? DEFAULT_RETRIES; + this.retrySend = options?.retrySend ?? false; if (this.timeout <= 0 || !Number.isFinite(this.timeout)) { throw new Error("Timeout must be a positive finite number"); @@ -247,7 +251,8 @@ export class RelayClient { headers["X-API-Key"] = this.apiKey; } - const maxRetries = init?.method === "POST" ? 0 : this.retries; + const maxRetries = + init?.method === "POST" && !this.retrySend ? 0 : this.retries; let lastError: Error | undefined; for (let attempt = 0; attempt <= maxRetries; attempt++) { diff --git a/src/types.ts b/src/types.ts index 1975bbb..98e1163 100644 --- a/src/types.ts +++ b/src/types.ts @@ -60,6 +60,8 @@ export interface ClientOptions { timeout?: number; /** Number of retry attempts on network errors / 5xx responses. Default: 3 */ retries?: number; + /** Retry POST sends on network errors / 5xx responses. Default: false */ + retrySend?: boolean; } /** diff --git a/tests/client.test.ts b/tests/client.test.ts index 97cb06c..9307451 100644 --- a/tests/client.test.ts +++ b/tests/client.test.ts @@ -256,6 +256,91 @@ describe("RelayClient", () => { }); }); + // --- send() retries (opt-in) --- + + describe("send() retries (retrySend)", () => { + const params = { to: "0x1", from: "0x2", payload: "p" }; + + it("should retry a 503 response when retrySend is enabled", async () => { + vi.useFakeTimers(); + const mathRandomSpy = vi.spyOn(Math, "random").mockReturnValue(0.5); + try { + const retryClient = new RelayClient("http://localhost:3000", { + retries: 1, + retrySend: true, + }); + const stored = message("msg-1", 1); + + mockFetch + .mockResolvedValueOnce(textResponse("server error", 503)) + .mockResolvedValueOnce(jsonResponse(stored, 201)); + + const promise = retryClient.send(params); + await vi.advanceTimersByTimeAsync(1550); + + await expect(promise).resolves.toEqual(stored); + expect(mockFetch).toHaveBeenCalledTimes(2); + } finally { + mathRandomSpy.mockRestore(); + vi.useRealTimers(); + } + }); + + it("should retry a timeout when retrySend is enabled", async () => { + vi.useFakeTimers(); + const mathRandomSpy = vi.spyOn(Math, "random").mockReturnValue(0.5); + try { + const retryClient = new RelayClient("http://localhost:3000", { + retries: 1, + retrySend: true, + }); + const stored = message("msg-2", 2); + + mockFetch + .mockRejectedValueOnce(new DOMException("Aborted", "AbortError")) + .mockResolvedValueOnce(jsonResponse(stored, 201)); + + const promise = retryClient.send(params); + await vi.advanceTimersByTimeAsync(1550); + + await expect(promise).resolves.toEqual(stored); + expect(mockFetch).toHaveBeenCalledTimes(2); + } finally { + mathRandomSpy.mockRestore(); + vi.useRealTimers(); + } + }); + + it.each([ + [401, RelayUnauthorizedError], + [413, RelayPayloadTooLargeError], + [429, RelayRateLimitError], + ])("should not retry a %i response when retrySend is enabled", async (status, ErrorClass) => { + const retryClient = new RelayClient("http://localhost:3000", { + retries: 2, + retrySend: true, + }); + + mockFetch.mockResolvedValueOnce( + textResponse("request rejected", status, { "Retry-After": "1" }), + ); + + await expect(retryClient.send(params)).rejects.toThrow(ErrorClass); + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + + it("should not retry by default", async () => { + const retryClient = new RelayClient("http://localhost:3000", { + retries: 2, + }); + + mockFetch.mockResolvedValueOnce(textResponse("server error", 503)); + + await expect(retryClient.send(params)).rejects.toThrow(RelayError); + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + }); + // --- API Key --- describe("API key", () => {