Mirror: A Node.js fetch shim using built-in Request, Response, and Headers (but without native fetch)
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

fix: Add limited ref lifetime of `incoming.socket` attached to `body: Readable` (#28)

authored by

Phil Pluckthun and committed by
GitHub
37ff2232 c4e43878

+24
+5
.changeset/clean-kings-like.md
··· 1 + --- 2 + 'fetch-nodeshim': patch 3 + --- 4 + 5 + Limit state in which `incoming.socket` is unrefed and instead `.ref()` it when the body is being read, and `.unref()` it again when reading stops.
+19
src/fetch.ts
··· 1 1 import { Stream, Readable, pipeline } from 'node:stream'; 2 + import { Socket } from 'node:net'; 2 3 import * as https from 'node:https'; 3 4 import * as http from 'node:http'; 4 5 import * as url from 'node:url'; ··· 110 111 if (params.redirected) 111 112 Object.defineProperty(response, 'redirected', { value: params.redirected }); 112 113 return response; 114 + } 115 + 116 + function attachRefLifetime(body: Readable, socket: Socket): void { 117 + const { _read } = body; 118 + body.on('close', () => { 119 + socket.unref(); 120 + }); 121 + body._read = function _readRef(...args: Parameters<Readable['_read']>) { 122 + body._read = _read; 123 + socket.ref(); 124 + return _read.apply(this, args); 125 + }; 113 126 } 114 127 115 128 async function _fetch( ··· 255 268 init.headers.set('Content-Encoding', encoding); 256 269 body = pipeline(body, createContentDecoder(encoding), destroy); 257 270 outgoing.on('error', destroy); 271 + } 272 + 273 + // Re-ref the socket when the body starts being consumed to prevent 274 + // early process exit, then unref when done to allow normal exit. 275 + if (body != null) { 276 + attachRefLifetime(body, incoming.socket); 258 277 } 259 278 260 279 resolve(