Skip to content

Commit 3e68d30

Browse files
committed
fix(web-incoming): pipe request without waiting for socket connect
resolves #166
1 parent b0823ee commit 3e68d30

3 files changed

Lines changed: 91 additions & 7 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ Returns Promise<Socket> (the upstream proxy socket)
8181
- `proxyRes` event fires only for the final (non-redirect) response; `proxyReq` fires for each request including redirects.
8282
- Sensitive headers (`authorization`, `cookie`) are stripped on cross-origin redirects.
8383
- When `followRedirects` is enabled, the request body is tee'd (written to proxy request and buffered simultaneously) rather than piped.
84+
- Without `followRedirects`, the incoming request is piped into the outgoing request **immediately**, without waiting for the upstream socket to emit `connect`. `ClientRequest` buffers writes issued before the socket connects, so the deferral is unnecessary — and it deadlocks with mocked sockets from request interceptors (msw/`@mswjs/interceptors`, nock), which only emit `connect` *after* the outgoing request has been fully written (unjs/httpxy#166). Regression coverage: `#stream with mocked sockets` in `test/middleware/web-incoming.test.ts`.
8485

8586
### WebSocket middleware semantics
8687

‎src/middleware/web-incoming.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -171,13 +171,12 @@ export const stream = defineProxyMiddleware((req, res, options, server, head, ca
171171
proxyReq.destroy(err);
172172
});
173173
} else {
174-
proxyReq.on("socket", (socket) => {
175-
if (socket.pending) {
176-
socket.on("connect", () => (options.buffer || req).pipe(proxyReq));
177-
} else {
178-
(options.buffer || req).pipe(proxyReq);
179-
}
180-
});
174+
// Pipe immediately, without waiting for the upstream socket to connect.
175+
// `ClientRequest` buffers writes issued before the socket is connected, and
176+
// deferring deadlocks with mocked sockets (msw / @mswjs/interceptors, nock),
177+
// which only emit "connect" *after* the outgoing request has been fully
178+
// written (unjs/httpxy#166).
179+
(options.buffer || req).pipe(proxyReq);
181180
}
182181

183182
function handleResponse(proxyRes: IncomingMessage, redirectCount: number, currentUrl: URL) {

‎test/middleware/web-incoming.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import * as webPasses from "../../src/middleware/web-incoming.ts";
44
import * as httpProxy from "../../src/index.ts";
55
import concat from "concat-stream";
66
import http from "node:http";
7+
import net from "node:net";
78
import {
89
stubIncomingMessage,
910
stubServerResponse,
@@ -1253,3 +1254,86 @@ describe("#chunked-connection-teardown", () => {
12531254
await promise;
12541255
});
12551256
});
1257+
1258+
// https://github.com/unjs/httpxy/issues/166
1259+
describe("#stream with mocked sockets", () => {
1260+
/**
1261+
* Mimics the socket used by request interceptors such as msw
1262+
* (`@mswjs/interceptors`) and nock: it stays `pending` and only emits
1263+
* "connect" *after* the outgoing request has been fully written, since that is
1264+
* when the interceptor decides how to respond.
1265+
*/
1266+
class MockSocket extends net.Socket {
1267+
#received = "";
1268+
1269+
override connect() {
1270+
return this; // never connects on its own
1271+
}
1272+
1273+
override write(chunk: any, encoding?: any, callback?: any) {
1274+
this.#received += chunk.toString();
1275+
const [head = "", body = ""] = this.#received.split("\r\n\r\n");
1276+
const contentLength = Number(/content-length: (\d+)/i.exec(head)?.[1] ?? 0);
1277+
if (this.#received.includes("\r\n\r\n") && body.length >= contentLength) {
1278+
// Request fully received: only now the interceptor "connects" and replies
1279+
queueMicrotask(() => {
1280+
(this as { connecting: boolean }).connecting = false;
1281+
this.emit("connect");
1282+
this.push(`HTTP/1.1 200 OK\r\ncontent-length: ${Buffer.byteLength(body)}\r\n\r\n${body}`);
1283+
});
1284+
}
1285+
if (typeof encoding === "function") {
1286+
encoding();
1287+
} else if (typeof callback === "function") {
1288+
callback();
1289+
}
1290+
return true;
1291+
}
1292+
1293+
override _read() {}
1294+
1295+
override end() {
1296+
return this;
1297+
}
1298+
}
1299+
1300+
class MockAgent extends http.Agent {
1301+
override createConnection() {
1302+
return new MockSocket();
1303+
}
1304+
}
1305+
1306+
async function proxyThroughMockSocket(method: string, body?: string) {
1307+
const proxy = httpProxy.createProxyServer({
1308+
target: "http://upstream.test",
1309+
agent: new MockAgent(),
1310+
});
1311+
const proxyServer = http.createServer((req, res) => {
1312+
proxy.web(req, res);
1313+
});
1314+
const proxyPort = await listenOn(proxyServer);
1315+
1316+
const { resolve, reject, promise } = Promise.withResolvers<string>();
1317+
const req = http.request(`http://127.0.0.1:${proxyPort}/ping`, { method }, (res) => {
1318+
let received = "";
1319+
res.on("data", (chunk: Buffer) => (received += chunk));
1320+
res.on("end", () => resolve(received));
1321+
});
1322+
req.on("error", reject);
1323+
req.end(body);
1324+
1325+
try {
1326+
return await promise;
1327+
} finally {
1328+
proxyServer.close();
1329+
}
1330+
}
1331+
1332+
it("should not hang when the socket connects only after the request is sent", async () => {
1333+
expect(await proxyThroughMockSocket("GET")).to.eql("");
1334+
});
1335+
1336+
it("should deliver the request body to a socket that connects late", async () => {
1337+
expect(await proxyThroughMockSocket("POST", "x".repeat(8192))).to.eql("x".repeat(8192));
1338+
});
1339+
});

0 commit comments

Comments
 (0)