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
21 changes: 19 additions & 2 deletions docs/api/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,29 @@

## Automatic Retry for Transient Network Errors

Use `withRetry` to automatically retry operations that fail with retryable errors (`NetworkTimeoutError`, `NetworkConnectionError`):
Use `withRetry` to automatically retry operations that fail with retryable errors (`ToolkitError` instances where `error.retryable === true`, such as `NetworkTimeoutError` and `NetworkConnectionError`). Non-retryable `ToolkitError` instances and standard `Error` values are rethrown immediately without waiting or retrying.

### Retry Contract & Exponential Backoff Schedule

- **Schedule**: After failed attempt `k` (`1 <= k < maxAttempts`), `withRetry` waits `min(maxDelayMs, MAX_TIMER_DELAY_MS, baseDelayMs * 2^(k - 1))` milliseconds (deterministic, jitter-free).
- **Defaults**: `maxAttempts = 3`, `baseDelayMs = 50`, `maxDelayMs = 30_000` (30 seconds).
- **Validation & overflow safety**:
- `maxAttempts` must be a safe integer `>= 1` (`ValidationError` otherwise).
- `baseDelayMs` and `maxDelayMs` must be finite numbers `>= 0`, with `maxDelayMs >= baseDelayMs` when explicitly supplied (`ValidationError` otherwise).
- Delays exceeding `MAX_TIMER_DELAY_MS` (`2_147_483_647` ms, Node.js `setTimeout` signed 32-bit ceiling) or large exponents are safely clamped so timers never overflow to `1ms` or `Infinity`.

```typescript
import { StellarToolkit, withRetry } from '@hyperdevtools/stellar-toolkit';

const toolkit = new StellarToolkit({ network: 'testnet' });

const balances = await withRetry(() => toolkit.getBalances(publicKey), 3, 200);
// Positional arguments: (operation, maxAttempts?, baseDelayMs?, maxDelayMs?)
const balances = await withRetry(() => toolkit.getBalances(publicKey), 4, 200, 2_000);

// Options object overload
const account = await withRetry(() => toolkit.getAccount(publicKey), {
maxAttempts: 4,
baseDelayMs: 200,
maxDelayMs: 2_000,
});
```
185 changes: 185 additions & 0 deletions src/__tests__/errors.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Keypair } from 'stellar-sdk';
import {
AccountNotFoundError,
calculateRetryDelayMs,
ErrorCode,
InsufficientBalanceError,
MAX_TIMER_DELAY_MS,
NetworkConnectionError,
NetworkTimeoutError,
StellarToolkit,
Expand Down Expand Up @@ -101,4 +103,187 @@ describe('StellarToolkit - Structured Error System & Recovery', () => {
const unique = new Set(codes);
expect(unique.size).toBe(codes.length);
});

describe('withRetry bounded exponential backoff (#30)', () => {
afterEach(() => {
jest.restoreAllMocks();
jest.useRealTimers();
});

it('uses deterministic exponential backoff capped by maxDelayMs without wall-clock sleeps', async () => {
jest.useFakeTimers();
const recordedDelays: number[] = [];
const realSetTimeout = global.setTimeout;
jest.spyOn(global, 'setTimeout').mockImplementation(((
handler: (...args: unknown[]) => void,
timeout?: number,
...args: unknown[]
) => {
recordedDelays.push(timeout ?? 0);
return realSetTimeout(handler, timeout, ...args);
}) as typeof setTimeout);

let attempts = 0;
const promise = withRetry(
async () => {
attempts += 1;
if (attempts < 5) {
throw new NetworkConnectionError('https://horizon-testnet.stellar.org', 'ECONNRESET');
}
return 'ok';
},
5,
100,
250,
);

// Schedule for attempts 1..4 with base=100, max=250: 100, 200, 250, 250
await jest.advanceTimersByTimeAsync(100);
expect(attempts).toBe(2);

await jest.advanceTimersByTimeAsync(200);
expect(attempts).toBe(3);

await jest.advanceTimersByTimeAsync(250);
expect(attempts).toBe(4);

await jest.advanceTimersByTimeAsync(250);
await expect(promise).resolves.toBe('ok');
expect(attempts).toBe(5);
expect(recordedDelays).toEqual([100, 200, 250, 250]);
});

it('supports the RetryOptions object overload and rethrows after exhausting maxAttempts', async () => {
jest.useFakeTimers();
const recordedDelays: number[] = [];
const realSetTimeout = global.setTimeout;
jest.spyOn(global, 'setTimeout').mockImplementation(((
handler: (...args: unknown[]) => void,
timeout?: number,
...args: unknown[]
) => {
recordedDelays.push(timeout ?? 0);
return realSetTimeout(handler, timeout, ...args);
}) as typeof setTimeout);

let attempts = 0;
const promise = withRetry(
async () => {
attempts += 1;
throw new NetworkTimeoutError('https://horizon-testnet.stellar.org', 3000);
},
{ maxAttempts: 4, baseDelayMs: 25, maxDelayMs: 60 },
);
const assertion = expect(promise).rejects.toThrow(NetworkTimeoutError);

await jest.advanceTimersByTimeAsync(25 + 50 + 60);
await assertion;
expect(attempts).toBe(4);
expect(recordedDelays).toEqual([25, 50, 60]);
});

it('rethrows non-retryable ToolkitErrors and standard Errors immediately without retrying', async () => {
jest.useFakeTimers();
const timeoutSpy = jest.spyOn(global, 'setTimeout');

let toolkitCalls = 0;
await expect(
withRetry(
async () => {
toolkitCalls += 1;
throw new AccountNotFoundError('GABC');
},
5,
100,
),
).rejects.toThrow(AccountNotFoundError);
expect(toolkitCalls).toBe(1);

let genericCalls = 0;
await expect(
withRetry(
async () => {
genericCalls += 1;
throw new Error('programmer error');
},
5,
100,
),
).rejects.toThrow('programmer error');
expect(genericCalls).toBe(1);
expect(timeoutSpy).not.toHaveBeenCalled();
});

it('rejects invalid attempt counts, negative or non-finite delays, and inverted delay bounds before calling operation', async () => {
let called = false;
const op = async () => {
called = true;
return 'never';
};

const invalidConfigs: Array<() => Promise<unknown>> = [
() => withRetry(null as unknown as () => Promise<string>),
() => withRetry(op, [] as unknown as never),
() => withRetry(op, 0),
() => withRetry(op, -2),
() => withRetry(op, 1.5),
() => withRetry(op, Number.NaN),
() => withRetry(op, Number.POSITIVE_INFINITY),
() => withRetry(op, 3, -1),
() => withRetry(op, 3, Number.NaN),
() => withRetry(op, 3, Number.POSITIVE_INFINITY),
() => withRetry(op, 3, 50, -5),
() => withRetry(op, 3, 50, Number.NaN),
() => withRetry(op, 3, 50, Number.POSITIVE_INFINITY),
() => withRetry(op, 3, 200, 100),
() => withRetry(op, { maxAttempts: 0 }),
() => withRetry(op, { baseDelayMs: -10 }),
() => withRetry(op, { baseDelayMs: 500, maxDelayMs: 100 }),
];

for (const invoke of invalidConfigs) {
await expect(invoke()).rejects.toThrow(ValidationError);
}
expect(called).toBe(false);
});

it('safely bounds overflow-sized delays and zero delays without producing Infinity, NaN, or 32-bit timer overflow', async () => {
expect(calculateRetryDelayMs(1, 0, 1000)).toBe(0);
expect(calculateRetryDelayMs(200, 0, 1000)).toBe(0);
expect(calculateRetryDelayMs(1, 100, 0)).toBe(0);
expect(calculateRetryDelayMs(80, 100, 5_000)).toBe(5_000);
expect(calculateRetryDelayMs(1200, 1e300, Number.MAX_VALUE)).toBe(MAX_TIMER_DELAY_MS);
expect(calculateRetryDelayMs(1, MAX_TIMER_DELAY_MS * 4, Number.MAX_VALUE)).toBe(
MAX_TIMER_DELAY_MS,
);

jest.useFakeTimers();
const recordedDelays: number[] = [];
const realSetTimeout = global.setTimeout;
jest.spyOn(global, 'setTimeout').mockImplementation(((
handler: (...args: unknown[]) => void,
timeout?: number,
...args: unknown[]
) => {
recordedDelays.push(timeout ?? 0);
return realSetTimeout(handler, 0, ...args);
}) as typeof setTimeout);

let attempts = 0;
const promise = withRetry(
async () => {
attempts += 1;
if (attempts < 3) {
throw new NetworkTimeoutError('https://horizon-testnet.stellar.org');
}
return 'bounded';
},
{ maxAttempts: 3, baseDelayMs: MAX_TIMER_DELAY_MS * 2, maxDelayMs: Number.MAX_VALUE },
);

await jest.runAllTimersAsync();
await expect(promise).resolves.toBe('bounded');
expect(recordedDelays).toEqual([MAX_TIMER_DELAY_MS, MAX_TIMER_DELAY_MS]);
});
});
});
112 changes: 104 additions & 8 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,23 +106,119 @@ export class ValidationError extends ToolkitError {
}
}

export const DEFAULT_MAX_RETRY_ATTEMPTS = 3;
export const DEFAULT_BASE_RETRY_DELAY_MS = 50;
export const DEFAULT_MAX_RETRY_DELAY_MS = 30_000;
/** Maximum 32-bit signed integer timer delay supported by Node.js `setTimeout` (~24.8 days). */
export const MAX_TIMER_DELAY_MS = 2_147_483_647;

export interface RetryOptions {
maxAttempts?: number;
baseDelayMs?: number;
maxDelayMs?: number;
}

/**
* Compute bounded deterministic exponential backoff delay for 1-indexed failed `attempt`:
* `min(maxDelayMs, MAX_TIMER_DELAY_MS, baseDelayMs * 2^(attempt - 1))`.
*/
export function calculateRetryDelayMs(
attempt: number,
baseDelayMs: number,
maxDelayMs = DEFAULT_MAX_RETRY_DELAY_MS,
): number {
const ceilingMs = Math.min(maxDelayMs, MAX_TIMER_DELAY_MS);
if (baseDelayMs === 0 || ceilingMs === 0) {
return 0;
}
const boundedBase = Math.min(baseDelayMs, ceilingMs);
const exponent = attempt - 1;
if (exponent >= 53) {
return ceilingMs;
}
const rawDelay = boundedBase * 2 ** exponent;
if (!Number.isFinite(rawDelay) || rawDelay > ceilingMs) {
return ceilingMs;
}
return rawDelay;
}

export async function withRetry<T>(operation: () => Promise<T>, options?: RetryOptions): Promise<T>;
export async function withRetry<T>(
operation: () => Promise<T>,
maxAttempts?: number,
baseDelayMs?: number,
maxDelayMs?: number,
): Promise<T>;
export async function withRetry<T>(
operation: () => Promise<T>,
maxAttempts = 3,
baseDelayMs = 50,
optionsOrMaxAttempts: number | RetryOptions = DEFAULT_MAX_RETRY_ATTEMPTS,
baseDelayMsArg = DEFAULT_BASE_RETRY_DELAY_MS,
maxDelayMsArg?: number,
): Promise<T> {
let lastError: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
if (typeof operation !== 'function') {
throw new ValidationError('operation', 'Retry operation must be a function');
}

let maxAttempts: number;
let baseDelayMs: number;
let explicitMaxDelayMs: number | undefined;

if (typeof optionsOrMaxAttempts === 'object' && optionsOrMaxAttempts !== null) {
if (Array.isArray(optionsOrMaxAttempts)) {
throw new ValidationError('options', 'Retry options must be a plain object');
}
maxAttempts = optionsOrMaxAttempts.maxAttempts ?? DEFAULT_MAX_RETRY_ATTEMPTS;
baseDelayMs = optionsOrMaxAttempts.baseDelayMs ?? DEFAULT_BASE_RETRY_DELAY_MS;
explicitMaxDelayMs = optionsOrMaxAttempts.maxDelayMs;
} else {
maxAttempts = optionsOrMaxAttempts;
baseDelayMs = baseDelayMsArg;
explicitMaxDelayMs = maxDelayMsArg;
}

if (typeof maxAttempts !== 'number' || !Number.isSafeInteger(maxAttempts) || maxAttempts < 1) {
throw new ValidationError(
'maxAttempts',
'maxAttempts must be a safe integer greater than or equal to 1',
);
}

if (typeof baseDelayMs !== 'number' || !Number.isFinite(baseDelayMs) || baseDelayMs < 0) {
throw new ValidationError('baseDelayMs', 'baseDelayMs must be a finite non-negative number');
}

if (explicitMaxDelayMs !== undefined) {
if (
typeof explicitMaxDelayMs !== 'number' ||
!Number.isFinite(explicitMaxDelayMs) ||
explicitMaxDelayMs < 0
) {
throw new ValidationError('maxDelayMs', 'maxDelayMs must be a finite non-negative number');
}
if (explicitMaxDelayMs < baseDelayMs) {
throw new ValidationError(
'maxDelayMs',
`maxDelayMs (${explicitMaxDelayMs}) must be greater than or equal to baseDelayMs (${baseDelayMs})`,
);
}
}

const resolvedMaxDelayMs =
explicitMaxDelayMs !== undefined
? explicitMaxDelayMs
: Math.max(DEFAULT_MAX_RETRY_DELAY_MS, Math.min(baseDelayMs, MAX_TIMER_DELAY_MS));

for (let attempt = 1; ; attempt += 1) {
try {
return await operation();
} catch (error) {
lastError = error;
const isRetryable = error instanceof ToolkitError && error.retryable;
if (!isRetryable || attempt === maxAttempts) {
if (!isRetryable || attempt >= maxAttempts) {
throw error;
}
await new Promise((resolve) => setTimeout(resolve, baseDelayMs * attempt));
const delayMs = calculateRetryDelayMs(attempt, baseDelayMs, resolvedMaxDelayMs);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
throw lastError;
}