Skip to content
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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Message>`

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<Message[]>`

Fetch messages for a wallet address, oldest first.
Expand Down
9 changes: 7 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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");
Expand Down Expand Up @@ -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++) {
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
85 changes: 85 additions & 0 deletions tests/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
Loading