Repository navigation
Retry without keep-alive after a premature close error - #10697
Conversation
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
There was a problem hiding this comment.
Code Review
This pull request addresses intermittent 'Premature close' errors during API requests by retrying the request once without keep-alive. It introduces helper functions to detect premature close errors and dynamically downgrade the connection to use non-keep-alive agents. Unit tests have been added to verify this retry behavior. The review feedback suggests improving type safety by explicitly declaring the return type of 'noKeepAliveAgent' as 'http.Agent | https.Agent', and avoiding potential side effects by not mutating the shared 'options.headers' directly during a retry.
| // https://github.com/node-fetch/node-fetch/issues/1767. | ||
| const httpAgentNoKeepAlive = new http.Agent({ keepAlive: false }); | ||
| const httpsAgentNoKeepAlive = new https.Agent({ keepAlive: false }); | ||
| function noKeepAliveAgent(parsedURL: URL): http.Agent { |
There was a problem hiding this comment.
The return type of noKeepAliveAgent is declared as http.Agent, but it can return an https.Agent when the protocol is HTTPS. While https.Agent is structurally compatible with http.Agent in Node.js, explicitly declaring the union type http.Agent | https.Agent is more precise and type-safe.
| function noKeepAliveAgent(parsedURL: URL): http.Agent { | |
| function noKeepAliveAgent(parsedURL: URL): http.Agent | https.Agent { |
There was a problem hiding this comment.
Good catch, done in 9cbad7a. The return type is now http.Agent | https.Agent.
| if (!disabledKeepAlive && !proxyURIFromEnv() && isPrematureCloseError(err)) { | ||
| disabledKeepAlive = true; | ||
| fetchOptions.agent = noKeepAliveAgent; | ||
| options.headers?.set("Connection", "close"); |
There was a problem hiding this comment.
Mutating the input options.headers directly can lead to unexpected side effects if the options object or its headers are reused or shared across other requests. Instead, consider creating a new Headers instance and assigning it to fetchOptions.headers to keep the retry logic pure and free of side effects.
const headers = new Headers(fetchOptions.headers);
headers.set("Connection", "close");
fetchOptions.headers = headers;There was a problem hiding this comment.
Done in 9cbad7a. The retry now copies the headers into a fresh Headers instance and sets Connection: close on the copy, so the shared options.headers is no longer mutated.
3fe5200 to
caa0c23
Compare
|
@googlebot I signed it! |
12a22db to
9cbad7a
Compare
|
cc: @joehan would be great to fix this |
|
Hey! This does seem like a relatively safe change that would address the issue on 24.17. However, Node 24.18 has already released (and it addressed the root cause of this bug), and I'm planning to migrate off of node-fetch entirely in the medium term. If anyone is still seeing this on node 24.18, please let me know here and we'll consider getting this fix in as a bandaid. Otherwise, I'm gonna push forward with getting node-fetch out of our direct deps entirely. Either way - thanks for contributing this! |
Some networks close keep-alive sockets in a way that makes node-fetch throw "Invalid response body ...: Premature close" while reading the response body, even when the response is complete. This breaks `firebase login` (the OAuth token exchange) and other API calls, especially on recent Node.js releases. Retry the request once with keep-alive turned off (Connection: close) when this happens. Only requests with a replayable body are retried: multipart FormData bodies (such as the token request) are serialized to a Buffer up front so they can be sent again, and raw streams are left untouched. The normal path still uses keep-alive. Fixes firebase#10692
9cbad7a to
d24ce7c
Compare
|
Thanks for the look @joehan, and for the 24.18 context. I'm still hitting this on Node 26.x, so newer Node releases don't avoid it on my setup. It does seem to depend on the network (it reproduces consistently on some and not at all on others, which fits a keep-alive socket-timing issue), so it likely isn't tied to a single Node version. Since it still affects users on current Node, this retry looks like a cheap, low-risk bandaid until node-fetch is gone, but I'm happy to defer to your plan. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #10697 +/- ##
=======================================
Coverage ? 57.84%
=======================================
Files ? 609
Lines ? 39205
Branches ? 7863
=======================================
Hits ? 22677
Misses ? 14705
Partials ? 1823 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Oddly enough, the latest 26.x release is older than 24.18 (https://github.com/nodejs/node/releases). Unsure if they will release a patch for this on 26.x soon. |
|
Turns out moving off of node-fetch is a bit of a messy endeavor (because nock does not work with native fetch()). Instead of rushing out a fix for that, merging this in for todays release to mitigate the issue |
Some networks close keep-alive sockets in a way that makes node-fetch throw "Invalid response body ...: Premature close" while reading the response body, even when the response is complete. This breaks `firebase login` (the OAuth token exchange) and other API calls, especially on recent Node.js releases. Retry the request once with keep-alive turned off (Connection: close) when this happens. Only requests with a replayable body are retried: multipart FormData bodies (such as the token request) are serialized to a Buffer up front so they can be sent again, and raw streams are left untouched. The normal path still uses keep-alive. Fixes #10692
Some networks close keep-alive sockets in a way that makes node-fetch throw "Invalid response body ...: Premature close" while reading the response body, even when the response is complete. This breaks `firebase login` (the OAuth token exchange) and other API calls, especially on recent Node.js releases. Retry the request once with keep-alive turned off (Connection: close) when this happens. Only requests with a replayable body are retried: multipart FormData bodies (such as the token request) are serialized to a Buffer up front so they can be sent again, and raw streams are left untouched. The normal path still uses keep-alive. Fixes #10692
Some networks close keep-alive sockets in a way that makes node-fetch throw "Invalid response body ...: Premature close" while reading the response body, even when the response is complete. This breaks `firebase login` (the OAuth token exchange) and other API calls, especially on recent Node.js releases. Retry the request once with keep-alive turned off (Connection: close) when this happens. Only requests with a replayable body are retried: multipart FormData bodies (such as the token request) are serialized to a Buffer up front so they can be sent again, and raw streams are left untouched. The normal path still uses keep-alive. Fixes firebase#10692
Description
firebase loginand other authenticated API calls can fail while exchanging the OAuth code:Root cause
apiv2sendsConnection: keep-aliveand uses Node's global HTTP agent, which defaults tokeepAlive: truesince Node 19. On some networks, and especially on recent Node.js releases that changed keep-alive socket reuse timing (nodejs/node#63989), node-fetch throws aPremature closeerror while reading the response body even though the response is complete. This is a known node-fetch bug in its chunked-response handling when an HTTP agent is involved (node-fetch/node-fetch#1767).I narrowed it down with a few probes against
https://accounts.google.com/o/oauth2/token:httpsPOST and a globalfetch(undici) POST both return the response (HTTP 401 for a dummy body)Premature closeevery timenew https.Agent({ keepAlive: false })works every timeSo the cause is not the user's clock, account, Node major version, TLS interception, or a proxy.
Fix
If a request fails with a premature close (or
ECONNRESET) error,apiv2retries it once with keep-alive turned off (Connection: closeand a non-keep-alive agent). Only requests whose body can be sent again are retried: multipartFormDatabodies, such as the OAuth token request, are serialized to a Buffer up front so the retry can replay them, and raw streams are left untouched. The normal path keeps using keep-alive, so flows likedeployare unaffected, and the fallback only runs on that error and only when no proxy is configured.Fixes #10692. Also reported in #10681.
Scenarios Tested
src/apiv2.spec.ts:Premature closeerror is retried without keep-alive and succeedsnpm run test:compile,npm run lint:ts,prettier --check, andmocha src/apiv2.spec.ts(40 passing) pass locallyfirebase loginandfirebase projects:listfailed consistently withPremature closebefore this change and work after itSample Commands
No command or flag changes. The fix lives in the HTTP client and applies to every
apiv2request, for example: