Skip to content

Commit

Permalink
Clear fetch abort timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
dlarocque committed Dec 3, 2024
1 parent ffbf5a6 commit e9ae353
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 19 deletions.
5 changes: 5 additions & 0 deletions .changeset/four-baboons-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@firebase/vertexai': patch
---

Clear fetch timeout after request completion. Fixes an issue that caused Node scripts to hang due to a pending timeout.
33 changes: 14 additions & 19 deletions packages/vertexai/src/requests/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,6 @@ export async function constructRequest(
return {
url: url.toString(),
fetchOptions: {
...buildFetchOptions(requestOptions),
method: 'POST',
headers: await getHeaders(url),
body
Expand All @@ -134,6 +133,7 @@ export async function makeRequest(
): Promise<Response> {
const url = new RequestUrl(model, task, apiSettings, stream, requestOptions);
let response;
let fetchTimeoutId: string | number | NodeJS.Timeout | undefined;
try {
const request = await constructRequest(
model,
Expand All @@ -143,6 +143,15 @@ export async function makeRequest(
body,
requestOptions
);
// Timeout is 180s by default
const timeoutMillis =
requestOptions?.timeout !== undefined
? requestOptions.timeout
: 180 * 1000;
const abortController = new AbortController();
fetchTimeoutId = setTimeout(() => abortController.abort(), timeoutMillis);
request.fetchOptions.signal = abortController.signal;

response = await fetch(request.url, request.fetchOptions);
if (!response.ok) {
let message = '';
Expand Down Expand Up @@ -211,24 +220,10 @@ export async function makeRequest(
}

throw err;
} finally {
if (fetchTimeoutId) {
clearTimeout(fetchTimeoutId);
}
}
return response;
}

/**
* Generates the request options to be passed to the fetch API.
* @param requestOptions - The user-defined request options.
* @returns The generated request options.
*/
function buildFetchOptions(requestOptions?: RequestOptions): RequestInit {
const fetchOptions = {} as RequestInit;
let timeoutMillis = 180 * 1000; // default: 180 s
if (requestOptions?.timeout && requestOptions?.timeout >= 0) {
timeoutMillis = requestOptions.timeout;
}
const abortController = new AbortController();
const signal = abortController.signal;
setTimeout(() => abortController.abort(), timeoutMillis);
fetchOptions.signal = signal;
return fetchOptions;
}

0 comments on commit e9ae353

Please sign in to comment.