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
2 changes: 1 addition & 1 deletion .codegen.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{ "engineHash": "bfb97cc", "specHash": "77eac4b", "version": "4.4.0" }
{ "engineHash": "bc04b80", "specHash": "77eac4b", "version": "4.4.0" }
15 changes: 15 additions & 0 deletions docs/sdk-gen/client.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ divided across resource managers.
- [Custom Base URLs](#custom-base-urls)
- [Custom Agent Options](#custom-agent-options)
- [Interceptors](#interceptors)
- [Use Timeouts for API calls](#use-timeouts-for-api-calls)
- [Use Proxy for API calls](#use-proxy-for-api-calls)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->
Expand Down Expand Up @@ -181,6 +182,20 @@ const clientWithInterceptor: BoxClient = client.withInterceptors([
]);
```

# Use Timeouts for API calls

In order to configure timeout for API calls, call `client.withTimeouts(config)` to create a new client with timeout settings, leaving the original client unmodified.

`timeoutMs` is in milliseconds and is applied to each request attempt.

```js
const newClient = client.withTimeouts({
timeoutMs: 30000,
});
```

If `timeoutMs` is not provided or is less than or equal to `0`, no SDK timeout is applied.

# Use Proxy for API calls

In order to use a proxy for API calls, calling the `client.withProxy(proxyConfig)` method creates a new client, leaving the original client unmodified, with the username and password being optional.
Expand Down
169 changes: 157 additions & 12 deletions docs/sdk-gen/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,161 @@
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

- [Max retry attempts](#max-retry-attempts)
- [Custom retry strategy](#custom-retry-strategy)
- [Retry Strategy](#retry-strategy)
- [Overview](#overview)
- [Default Configuration](#default-configuration)
- [Retry Decision Flow](#retry-decision-flow)
- [Exponential Backoff Algorithm](#exponential-backoff-algorithm)
- [Example Delays (with default settings)](#example-delays-with-default-settings)
- [Retry-After Header](#retry-after-header)
- [Network Exception Handling](#network-exception-handling)
- [Customizing Retry Parameters](#customizing-retry-parameters)
- [Custom Retry Strategy](#custom-retry-strategy)
- [Timeouts](#timeouts)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

## Max retry attempts
## Retry Strategy

The default maximum number of retries in case of failed API call is 5.
To change this number you should initialize `BoxRetryStrategy` with the new value and pass it to `NetworkSession`.
### Overview

```js
The SDK ships with a built-in retry strategy (`BoxRetryStrategy`) that implements the `RetryStrategy` interface. The `BoxNetworkClient`, which serves as the default network client, uses this strategy to automatically retry failed API requests with exponential backoff.

The retry strategy exposes two methods:

- **`shouldRetry`** — Determines whether a failed request should be retried based on the HTTP status code, response headers, attempt count, and authentication state.
- **`retryAfter`** — Computes the delay (in seconds) before the next retry attempt, using either the server-provided `Retry-After` header or an exponential backoff formula.

### Default Configuration

| Parameter | Default | Description |
| -------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `maxAttempts` | `5` | Maximum number of retry attempts for HTTP error responses (status 4xx/5xx). |
| `retryBaseInterval` | `1` (second) | Base interval used in the exponential backoff calculation. |
| `retryRandomizationFactor` | `0.5` | Jitter factor applied to the backoff delay. The actual delay is multiplied by a random value between `1 - factor` and `1 + factor`. |
| `maxRetriesOnException` | `2` | Maximum number of retries for network-level exceptions (connection failures, timeouts). These are tracked by a separate counter from HTTP error retries. |

### Retry Decision Flow

The following diagram shows how `BoxRetryStrategy.shouldRetry` decides whether to retry a request:

```
shouldRetry(fetchOptions, fetchResponse, attemptNumber)
|
v
+-----------------------+
| status == 0 | Yes
| (network exception)? |----------> attemptNumber <= maxRetriesOnException?
+-----------------------+ | |
| No Yes No
v | |
+-----------------------+ [RETRY] [NO RETRY]
| attemptNumber >= |
| maxAttempts? |
+-----------------------+
| |
Yes No
| |
[NO RETRY] v
+-----------------------+
| status == 202 AND | Yes
| Retry-After header? |----------> [RETRY]
+-----------------------+
| No
v
+-----------------------+
| status >= 500 | Yes
| (server error)? |----------> [RETRY]
+-----------------------+
| No
v
+-----------------------+
| status == 429 | Yes
| (rate limited)? |----------> [RETRY]
+-----------------------+
| No
v
+-----------------------+
| status == 401 AND | Yes
| auth available? |----------> Refresh token, then [RETRY]
+-----------------------+
| No
v
[NO RETRY]
```

### Exponential Backoff Algorithm

When the response does not include a `Retry-After` header, the retry delay is computed using exponential backoff with randomized jitter:

```
delay = 2^attemptNumber * retryBaseInterval * random(1 - factor, 1 + factor)
```

Where:

- `attemptNumber` is the current attempt (1-based)
- `retryBaseInterval` defaults to `1` second
- `factor` is `retryRandomizationFactor` (default `0.5`)
- `random(min, max)` returns a uniformly distributed value in `[min, max]`

#### Example Delays (with default settings)

| Attempt | Base Delay | Min Delay (factor=0.5) | Max Delay (factor=0.5) |
| ------- | ---------- | ---------------------- | ---------------------- |
| 1 | 2s | 1.0s | 3.0s |
| 2 | 4s | 2.0s | 6.0s |
| 3 | 8s | 4.0s | 12.0s |
| 4 | 16s | 8.0s | 24.0s |

### Retry-After Header

When the server includes a `Retry-After` header in the response, the SDK uses the header value directly as the delay in seconds instead of computing an exponential backoff delay. This applies to any retryable response that includes the header, including:

- `202 Accepted` with `Retry-After` (long-running operations)
- `429 Too Many Requests` with `Retry-After`
- `5xx` server errors with `Retry-After`

The header value is parsed as a floating-point number representing seconds.

### Network Exception Handling

Network-level failures (connection refused, DNS resolution errors, timeouts, TLS errors) are represented internally as responses with status `0`. These exceptions are tracked by a **separate counter** (`maxRetriesOnException`, default `2`) from the regular HTTP error retry counter (`maxAttempts`).

This means:

- Network exception retries are tracked independently from HTTP error retries, each with their own counter and backoff progression.
- A request can fail up to `maxRetriesOnException` times due to network exceptions, but each exception retry also increments the overall attempt counter, so the total number of retries across both exception and HTTP error types is bounded by `maxAttempts`.

### Customizing Retry Parameters

You can customize all retry parameters by initializing `BoxRetryStrategy` with the desired values and passing it to `NetworkSession`:

```ts
const auth = new BoxDeveloperTokenAuth({ token: 'DEVELOPER_TOKEN_GOES_HERE' });
const networkSession = new NetworkSession({
retryStrategy: new BoxRetryStrategy({ maxAttempts: 6 }),
retryStrategy: new BoxRetryStrategy({
maxAttempts: 3,
retryBaseInterval: 2,
retryRandomizationFactor: 0.3,
maxRetriesOnException: 1,
}),
});
const client = new BoxClient({ auth, networkSession });
```

## Custom retry strategy
### Custom Retry Strategy

You can also implement your own retry strategy by subclassing `RetryStrategy` and overriding `shouldRetry` and `retryAfter` methods.
This example shows how to set custom strategy that retries on 5xx status codes and waits 1 second between retries.
You can implement your own retry strategy by implementing the `RetryStrategy` interface and overriding the `shouldRetry` and `retryAfter` methods:

```ts
export class CustomRetryStrategy implements RetryStrategy {
class CustomRetryStrategy implements RetryStrategy {
async shouldRetry(
fetchOptions: FetchOptions,
fetchResponse: FetchResponse,
attemptNumber: number
): Promise<boolean> {
return false;
return fetchResponse.status >= 500 && attemptNumber < 3;
}

retryAfter(
Expand All @@ -51,3 +175,24 @@ const networkSession = new NetworkSession({
});
const client = new BoxClient({ auth, networkSession });
```

## Timeouts

You can configure request timeout using `timeoutConfig` on `NetworkSession`.
`timeoutMs` is in milliseconds and applies to each HTTP request attempt.

```js
const auth = new BoxDeveloperTokenAuth({ token: 'DEVELOPER_TOKEN_GOES_HERE' });
const networkSession = new NetworkSession({
timeoutConfig: { timeoutMs: 30000 },
});
const client = new BoxClient({ auth, networkSession });
```

How timeout handling works:

- The SDK applies timeout only when `timeoutMs` is provided and greater than `0`.
- To disable SDK timeout handling, set `timeoutMs` to `0` (or a negative value), or omit `timeoutMs`.
- On timeout, the request is aborted and treated as a network error (`Connection timeout after <timeoutMs>ms`); if retries are exhausted, the SDK throws `BoxSdkError`.
- Timeout failures are handled as request exceptions, then retry behavior is controlled by the configured retry strategy.
- Timeout applies to a single HTTP request attempt to the Box API (not the total time across all retries).
13 changes: 13 additions & 0 deletions src/sdk-gen/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ import { BoxSdkError } from './box/errors';
import { FetchOptions } from './networking/fetchOptions';
import { FetchResponse } from './networking/fetchResponse';
import { BaseUrls } from './networking/baseUrls';
import { TimeoutConfig } from './networking/timeoutConfig';
import { ProxyConfig } from './networking/proxyConfig';
import { AgentOptions } from './internal/utils';
import { Interceptor } from './networking/interceptors';
Expand Down Expand Up @@ -279,6 +280,7 @@ export class BoxClient {
| 'withExtraHeaders'
| 'withCustomBaseUrls'
| 'withProxy'
| 'withTimeouts'
| 'withCustomAgentOptions'
| 'withInterceptors'
> &
Expand Down Expand Up @@ -739,6 +741,17 @@ export class BoxClient {
networkSession: this.networkSession.withProxy(config),
});
}
/**
* Create a new client with custom timeouts that will be used for every API call
* @param {TimeoutConfig} config Timeout configuration.
* @returns {BoxClient}
*/
withTimeouts(config: TimeoutConfig): BoxClient {
return new BoxClient({
auth: this.auth,
networkSession: this.networkSession.withTimeoutConfig(config),
});
}
/**
* Create a new client with a custom set of agent options that will be used for every API call
* @param {AgentOptions} agentOptions Custom set of agent options that will be used for every API call
Expand Down
95 changes: 82 additions & 13 deletions src/sdk-gen/networking/boxNetworkClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,55 @@ export const shouldIncludeBoxUaHeader = (options: FetchOptions) => {
);
};

function createAbortSignalWithTimeout(
baseSignal: RequestInit['signal'],
timeoutMs: number
): {
signal: AbortSignal;
clearTimeout: () => void;
didTimeout: () => boolean;
} {
const controller = new AbortController();
const upstream = baseSignal as unknown as AbortSignal | undefined;
let timedOut = false;

const abortFromUpstream = () => {
try {
(controller as any).abort((upstream as any)?.reason);
} catch {
controller.abort();
}
};

if (upstream) {
if (upstream.aborted) {
abortFromUpstream();
} else {
upstream.addEventListener('abort', abortFromUpstream, { once: true });
}
}

const timeoutId = setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs);

// Node.js timers keep the event loop alive. If the only pending work is this
// watchdog timeout, we don't want it to prevent process exit (e.g. short CLI
// runs, tests, scripts). `unref()` detaches the timer from the event loop.
// It’s a no-op in environments where `unref` isn’t available.
(timeoutId as any)?.unref?.();

return {
signal: controller.signal,
clearTimeout: () => {
clearTimeout(timeoutId);
if (upstream) upstream.removeEventListener('abort', abortFromUpstream);
},
didTimeout: () => timedOut,
};
}

type FetchOptionsExtended = FetchOptions & {
attemptNumber?: number;
numberOfRetriesOnException?: number;
Expand Down Expand Up @@ -193,19 +242,33 @@ export class BoxNetworkClient implements NetworkClient {
: void 0,
});

const timeoutConfig = fetchOptions.networkSession?.timeoutConfig;
const timeoutMs = timeoutConfig?.timeoutMs;

const requestTimeout =
timeoutMs != null && timeoutMs > 0
? createAbortSignalWithTimeout(requestInit.signal, timeoutMs)
: undefined;
const requestInitWithTimeout: RequestInit = requestTimeout
? {
...requestInit,
signal: requestTimeout.signal as unknown as RequestInit['signal'],
}
: requestInit;

try {
const response = await nodeFetch(
''.concat(
fetchOptions.url,
Object.keys(params).length === 0 || fetchOptions.url.endsWith('?')
? ''
: '?',
new URLSearchParams(params).toString()
),
{ ...requestInit, redirect: isBrowser() ? 'follow' : 'manual' }
const requestUrl = ''.concat(
fetchOptions.url,
Object.keys(params).length === 0 || fetchOptions.url.endsWith('?')
? ''
: '?',
new URLSearchParams(params).toString()
);
const response = await nodeFetch(requestUrl, {
...requestInitWithTimeout,
redirect: isBrowser() ? 'follow' : 'manual',
});

const contentType = response.headers.get('content-type') ?? '';
const ignoreResponseBody = fetchOptions.followRedirects === false;

let data: SerializedData | undefined;
Expand Down Expand Up @@ -244,8 +307,14 @@ export class BoxNetworkClient implements NetworkClient {
} catch (error) {
isExceptionCase = true;
numberOfRetriesOnException++;
caughtError = error instanceof Error ? error : new Error(String(error));
if (requestTimeout?.didTimeout()) {
caughtError = new Error(`Connection timeout after ${timeoutMs}ms`);
} else {
caughtError = error instanceof Error ? error : new Error(String(error));
}
fetchResponse = fetchResponse ?? { status: 0, headers: {} };
} finally {
requestTimeout?.clearTimeout();
}
const attemptForRetry = isExceptionCase
? numberOfRetriesOnException
Expand All @@ -263,7 +332,7 @@ export class BoxNetworkClient implements NetworkClient {
fetchResponse,
attemptForRetry
);
await new Promise((resolve) => setTimeout(resolve, retryTimeout));
await new Promise((resolve) => setTimeout(resolve, retryTimeout * 1000));
return this.fetch({
...options,
attemptNumber: attemptNumber + 1,
Expand Down Expand Up @@ -325,7 +394,7 @@ export class BoxNetworkClient implements NetworkClient {
: [];
if (fetchResponse.status === 0) {
throw new BoxSdkError({
message: `Unexpected Error occurred`,
message: caughtError?.message || `Unexpected Error occurred`,
timestamp: `${Date.now()}`,
error: caughtError,
});
Expand Down
Loading