Skip to content
Draft
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
16 changes: 15 additions & 1 deletion src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ type APIResponseProps = {
response: Response;
options: FinalRequestOptions;
controller: AbortController;
timeout: number;
};

async function defaultParseResponse<T>(props: APIResponseProps): Promise<T> {
Expand All @@ -67,6 +68,19 @@ async function defaultParseResponse<T>(props: APIResponseProps): Promise<T> {
return response as unknown as T;
}

const timeout = setTimeout(() => props.controller.abort(), props.timeout);
try {
return await parseBody<T>(response);
} catch (err) {
if (props.controller.signal.aborted && !props.options.signal?.aborted)
throw new APIConnectionTimeoutError();
throw err;
} finally {
clearTimeout(timeout);
}
}

async function parseBody<T>(response: Response): Promise<T> {
const contentType = response.headers.get('content-type');
const mediaType = contentType?.split(';')[0]?.trim();
const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');
Expand Down Expand Up @@ -510,7 +524,7 @@ export abstract class APIClient {
throw err;
}

return { response, options, controller };
return { response, options, controller, timeout };
}

requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(
Expand Down
28 changes: 27 additions & 1 deletion tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

import Browserbase from '@browserbasehq/sdk';
import { APIUserAbortError } from '@browserbasehq/sdk';
import { APIConnectionTimeoutError, APIUserAbortError } from '@browserbasehq/sdk';
import { Headers } from '@browserbasehq/sdk/core';
import defaultFetch, { Response, type RequestInit, type RequestInfo } from 'node-fetch';
import http from 'node:http';
import { type AddressInfo } from 'node:net';

describe('instantiate client', () => {
const env = process.env;
Expand Down Expand Up @@ -505,4 +507,28 @@ describe('retries', () => {
).toEqual(JSON.stringify({ a: 1 }));
expect(count).toEqual(3);
});

test.each([
['native fetch', undefined],
['node-fetch', defaultFetch],
])('timeout covers a stalled response body with %s', async (_, fetch) => {
const server = http.createServer((req, res) =>
res.writeHead(200, { 'content-type': 'application/json' }).write('{'),
);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
const client = new Browserbase({
apiKey: 'My API Key',
baseURL: `http://127.0.0.1:${port}`,
fetch,
timeout: 50,
maxRetries: 0,
});
try {
await expect(client.get('/foo')).rejects.toThrow(APIConnectionTimeoutError);
} finally {
server.closeAllConnections();
server.close();
}
});
});
Loading