Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
3 changes: 3 additions & 0 deletions src/js/internal/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ const kPendingCallbacks = Symbol("pendingCallbacks");
const kRequest = Symbol("request");
// Set on a server socket at the 'connect'/'upgrade' handoff: the native response of that request.
const kHandoffResponse = Symbol("kHandoffResponse");
// Server socket method: run a callback once the 'connect'/'upgrade' hand-off owns the connection.
const kOnHandoffActive = Symbol("kOnHandoffActive");
const kCloseCallback = Symbol("closeCallback");

// node:_http_server registers its pipelined-response machinery here at module
Expand Down Expand Up @@ -526,6 +528,7 @@ export {
kHandoffResponse,
kInternalSocketData,
kNeedDrain,
kOnHandoffActive,
kOutHeaders,
kPendingCallbacks,
kPerRequestCheckServerIdentity,
Expand Down
184 changes: 128 additions & 56 deletions src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const {
serverSymbol,
kHandle,
kHandoffResponse,
kOnHandoffActive,
kRealListen,
tlsSymbol,
optionsSymbol,
Expand Down Expand Up @@ -736,6 +737,26 @@ Server.prototype[kRealListen] = function (tls, port, host, socketPath, reusePort
socketParser[kParserOnTimeout] = serverParserShimOnTimeout;

const isPipelined = !!isPipelinedDispatch;
socket[kEnableStreaming](false);

// The builtin ServerResponse consumes its options synchronously, so a
// reusable scratch object avoids one allocation per request. User
// subclasses (options.ServerResponse) might retain options, so they
// keep getting a fresh object.
Comment thread
robobun marked this conversation as resolved.
Resolved
let http_res;
if (ResponseClass === ServerResponse) {
scratchResponseOptions[kHandle] = handle;
scratchResponseOptions.highWaterMark = socket.writableHighWaterMark;
scratchResponseOptions[kRejectNonStandardBodyWrites] = server.rejectNonStandardBodyWrites;
http_res = new ResponseClass(http_req, scratchResponseOptions);
scratchResponseOptions[kHandle] = undefined;
} else {
http_res = new ResponseClass(http_req, {
[kHandle]: handle,
highWaterMark: socket.writableHighWaterMark,
[kRejectNonStandardBodyWrites]: server.rejectNonStandardBodyWrites,
});
}
// Pipelined or not, like Node.js: the native parser is in tunnel mode from this request on.
if (method === "CONNECT") {
Comment thread
robobun marked this conversation as resolved.
Resolved
// Handle CONNECT method for HTTP tunneling/proxy
Expand All @@ -759,6 +780,8 @@ Server.prototype[kRealListen] = function (tls, port, host, socketPath, reusePort
http_req.upgrade = true;
// Node frees the parser before handing the raw socket to 'connect'.
releaseServerParserShim(socket, http_req);
// Behind responses in flight, the listener's writes wait for their turn in the pipeline.
if (isPipelined) queuePipelinedHandoff(server, socket, http_res, !!isAncientHTTP);
try {
server.emit("connect", http_req, socket, head);
} catch (err) {
Expand All @@ -779,26 +802,6 @@ Server.prototype[kRealListen] = function (tls, port, host, socketPath, reusePort
}
return;
}
socket[kEnableStreaming](false);

// The builtin ServerResponse consumes its options synchronously, so a
// reusable scratch object avoids one allocation per request. User
// subclasses (options.ServerResponse) might retain options, so they
// keep getting a fresh object.
let http_res;
if (ResponseClass === ServerResponse) {
scratchResponseOptions[kHandle] = handle;
scratchResponseOptions.highWaterMark = socket.writableHighWaterMark;
scratchResponseOptions[kRejectNonStandardBodyWrites] = server.rejectNonStandardBodyWrites;
http_res = new ResponseClass(http_req, scratchResponseOptions);
scratchResponseOptions[kHandle] = undefined;
} else {
http_res = new ResponseClass(http_req, {
[kHandle]: handle,
highWaterMark: socket.writableHighWaterMark,
[kRejectNonStandardBodyWrites]: server.rejectNonStandardBodyWrites,
});
}
http_res._keepAliveTimeout = server.keepAliveTimeout;
// Only stamp the symbol when the server actually set `uniqueHeaders`:
// unconditionally adding it (even as undefined) forced a hidden-class
Expand Down Expand Up @@ -883,13 +886,8 @@ Server.prototype[kRealListen] = function (tls, port, host, socketPath, reusePort
// token; the server then consults shouldUpgradeCallback (default: an
// 'upgrade' listener is installed) and otherwise dispatches the
// request normally.
// Not when pipelined: the builtin ws answers through the socket's current response, the one in flight.
let is_upgrade = false;
if (
!isPipelined &&
(dispatchBits & DISPATCH_HAS_UPGRADE) !== 0 &&
(dispatchBits & DISPATCH_CONN_UPGRADE) !== 0
) {
if ((dispatchBits & DISPATCH_HAS_UPGRADE) !== 0 && (dispatchBits & DISPATCH_CONN_UPGRADE) !== 0) {
is_upgrade = !!server.shouldUpgradeCallback(http_req);
}
// Like Node.js's parserOnIncoming: req.upgrade is true inside the
Expand All @@ -901,14 +899,18 @@ Server.prototype[kRealListen] = function (tls, port, host, socketPath, reusePort
// Node.js, this response is queued (res.socket === null) and its
// writes are buffered until the in-flight response finishes and the
// pipeline assigns it the socket (advanceResponsePipeline).
queuePipelinedResponse(socket, http_res, !!isAncientHTTP);
// A pipelined dispatch can arrive after the previous response finished and detached
// (bytes still flushing keep it pending), leaving nothing in flight to advance the
// queue. Kick the pipeline once this dispatch settles.
if (socket._httpMessage == null && !socket[kPipelineKickScheduled]) {
socket[kPipelineKickScheduled] = true;
process.nextTick(advancePipelineIfIdleNT, server, socket);
if (is_upgrade) {
// The listener gets the socket now, like Node. Its writes wait for their turn in the
// pipeline, so the 101 follows the responses ahead of it on the wire.
Comment thread
robobun marked this conversation as resolved.
Resolved
socketHandle.upgradeToTunnel(hasBody, handle);
socket[kHandoffResponse] = handle;
socket[kEnableStreaming](true);
queuePipelinedHandoff(server, socket, http_res, !!isAncientHTTP);
emitUpgradeHandoff(server, socket, http_req, !hasBody && connectHead ? connectHead : kEmptyBuffer, hasBody);
Comment thread
robobun marked this conversation as resolved.
Resolved
return;
}
queuePipelinedResponse(socket, http_res, !!isAncientHTTP);
kickPipelineIfIdle(server, socket);
// Node's parserOnIncoming stops reading the connection once the bytes
// queued on responses that do not own the socket yet reach the
// socket's high water mark, so pipelined requests cannot flood it.
Expand Down Expand Up @@ -976,28 +978,8 @@ Server.prototype[kRealListen] = function (tls, port, host, socketPath, reusePort
socketHandle.upgradeToTunnel(hasBody, handle);
socket[kHandoffResponse] = handle;
socket[kEnableStreaming](true);
detachSocketListenersForHandoff(socket);
// Node frees the parser before emitting 'upgrade' (socket.parser === null there).
releaseServerParserShim(socket, http_req);
if (hasBody) {
socket[kUpgradeIncoming] = http_req;
http_req.once("end", clearUpgradeIncoming.bind(undefined, socket));
}
const upgradeHead = !hasBody && connectHead ? connectHead : kEmptyBuffer;
let upgradeHandled;
try {
upgradeHandled = server.emit("upgrade", http_req, socket, upgradeHead);
} catch (err) {
// A throwing 'upgrade' listener surfaces as an uncaught
// exception, like Node.js (the emit happens outside any JS try
// frame there).
process.nextTick(rethrowUncaught, err);
upgradeHandled = true;
}
if (!upgradeHandled) {
// shouldUpgradeCallback accepted the upgrade but no 'upgrade'
// listener is installed: Node.js destroys the socket.
socket.destroy();
if (!emitUpgradeHandoff(server, socket, http_req, upgradeHead, hasBody)) {
return;
}
// Like CONNECT: the connection is detached from the HTTP request
Expand Down Expand Up @@ -1343,6 +1325,34 @@ function detachSocketListenersForHandoff(socket) {
function resolveHandoffPromise(promise) {
$resolvePromise(promise, undefined);
}

// Node's onParserExecuteCommon. False: no 'upgrade' listener, so the socket was destroyed.
function emitUpgradeHandoff(server, socket, req, upgradeHead, hasBody) {
detachSocketListenersForHandoff(socket);
// Node frees the parser before emitting 'upgrade' (socket.parser === null there).
releaseServerParserShim(socket, req);
// A flowing socket with no reader drops pushed bytes (Node does the same reset).
if (socket.readableFlowing === true) socket.readableFlowing = null;
Comment thread
robobun marked this conversation as resolved.
Resolved
if (hasBody && !req.complete) {
socket[kUpgradeIncoming] = req;
req.once("end", clearUpgradeIncoming.bind(undefined, socket));
}
let upgradeHandled;
try {
upgradeHandled = server.emit("upgrade", req, socket, upgradeHead);
} catch (err) {
// A throwing 'upgrade' listener surfaces as an uncaught
// exception, like Node.js (the emit happens outside any JS try
// frame there).
Comment thread
robobun marked this conversation as resolved.
Resolved
process.nextTick(rethrowUncaught, err);
upgradeHandled = true;
}
if (!upgradeHandled) {
socket.destroy();
return false;
}
return true;
}
const kSocketTimeoutTimer = Symbol("socketTimeoutTimer");
const kStreamingEnabled = Symbol("kStreamingEnabled");
// Scratch options object for the builtin ServerResponse (see the dispatcher).
Expand All @@ -1369,6 +1379,8 @@ const kPipelinedQueuedState = Symbol("kPipelinedQueuedState");
// responses. Reads are paused while it is at or above the high water mark.
const kOutgoingData = Symbol("kOutgoingData");
const kReplayingPipelinedOps = Symbol("kReplayingPipelinedOps");
// { write, final, ready } parked on a handed-off socket until the pipeline reaches it.
const kPendingHandoff = Symbol("kPendingHandoff");
const kStopParsingOnCloseListener = Symbol("kStopParsingOnCloseListener");
// Set when the dispatcher already detached a synchronously-finished response,
// so the 'finish' listener does not detach/advance the pipeline a second time.
Expand Down Expand Up @@ -1498,6 +1510,7 @@ function getNodeHTTPServerSocket() {
[kHandle];
[kUpgradeIncoming] = undefined;
[kHandoffResponse] = undefined;
[kPendingHandoff] = undefined;
server: Server;
_httpMessage;
_secureEstablished = false;
Expand Down Expand Up @@ -1753,6 +1766,11 @@ function getNodeHTTPServerSocket() {
}

_final(callback) {
const pending = this[kPendingHandoff];
if (pending !== undefined) {
pending.final = callback;
return;
}
const handle = this[kHandle];
if (!handle) {
callback();
Expand All @@ -1762,6 +1780,15 @@ function getNodeHTTPServerSocket() {
callback();
Comment thread
robobun marked this conversation as resolved.
Resolved
}

[kOnHandoffActive](callback) {
const pending = this[kPendingHandoff];
if (pending !== undefined) {
pending.ready.push(callback);
} else {
callback();
}
}

get localAddress() {
return this[kHandle]?.localAddress?.address;
}
Expand Down Expand Up @@ -1942,6 +1969,12 @@ function getNodeHTTPServerSocket() {
}

_write(_chunk, _encoding, _callback) {
const pending = this[kPendingHandoff];
if (pending !== undefined) {
// Writable issues one _write at a time: holding its callback holds everything after it.
pending.write = { chunk: _chunk, encoding: _encoding, callback: _callback };
return;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
const handle = this[kHandle];
let err;
this._unrefTimer();
Expand Down Expand Up @@ -1978,7 +2011,8 @@ function getNodeHTTPServerSocket() {
}

get [kInternalSocketData]() {
return this[kHandle]?.response;
// After a hand-off: that request's response, not the one still in flight ahead of it.
return this[kHandoffResponse] ?? this[kHandle]?.response;
}
} as unknown as typeof import("node:net").Socket;
Object.defineProperty(NodeHTTPServerSocket, "name", { value: "Socket" });
Expand Down Expand Up @@ -2532,10 +2566,40 @@ function queuePipelinedResponse(socket, res, isAncient) {
ended: false,
isAncient,
socket,
// A CONNECT/Upgrade hand-off: its turn releases the listener's parked writes.
handoff: false,
};
(socket[kPipelinedResponses] ??= []).push(res);
}

// Nothing in flight advances the queue when the previous response finished but still flushes.
function kickPipelineIfIdle(server, socket) {
if (socket._httpMessage == null && !socket[kPipelineKickScheduled]) {
socket[kPipelineKickScheduled] = true;
process.nextTick(advancePipelineIfIdleNT, server, socket);
}
}

// The socket parks its writes and kOnHandoffActive callbacks until the pipeline reaches it.
function queuePipelinedHandoff(server, socket, res, isAncient) {
queuePipelinedResponse(socket, res, isAncient);
res[kPipelinedQueuedState].handoff = true;
socket[kPendingHandoff] = { write: undefined, final: undefined, ready: [] };
kickPipelineIfIdle(server, socket);
}

function activatePipelinedHandoff(socket) {
const pending = socket[kPendingHandoff];
socket[kPendingHandoff] = undefined;
if (pending === undefined) return;
const write = pending.write;
if (write !== undefined) socket._write(write.chunk, write.encoding, write.callback);
Comment thread
robobun marked this conversation as resolved.
Resolved
const final = pending.final;
if (final !== undefined) socket._final(final);
Comment thread
robobun marked this conversation as resolved.
Resolved
const ready = pending.ready;
for (let i = 0; i < ready.length; i++) ready[i]();
}

// When the connection dies with pipelined responses still queued behind the
// in-flight one, abort them and their requests, like Node.js's socketOnClose
// (abortIncoming). Runs from the native socket's close path and from the
Expand All @@ -2547,6 +2611,8 @@ function abortQueuedPipelinedResponses(socket) {
socket[kPipelinedResponses] = undefined;
for (let i = 0; i < pipelinedLength; i++) {
const queuedRes = pipelined[i];
// The request was handed to 'connect'/'upgrade': Node's socketOnClose is gone there.
if (queuedRes[kPipelinedQueuedState]?.handoff) continue;
const queuedReq = queuedRes.req;
if (queuedReq && !queuedReq.destroyed) {
queuedReq[kHandle] = undefined;
Expand All @@ -2571,7 +2637,8 @@ function advanceResponsePipeline(server, socket) {
// the pipeline is mutually exclusive with closing the socket - the queued
// responses are aborted by the socket close path instead of being replayed
// onto a half-closed connection.
if (!socket || socket.writableEnded || socket.destroyed) {
// (A socket.end() from a 'connect'/'upgrade' listener is parked, not ended yet.)
if (!socket || socket.destroyed || (socket.writableEnded && socket[kPendingHandoff] === undefined)) {
Comment thread
robobun marked this conversation as resolved.
Resolved
return;
}
const queue = socket[kPipelinedResponses];
Expand Down Expand Up @@ -2611,6 +2678,11 @@ function advanceResponsePipeline(server, socket) {
return;
}

if (queued.handoff) {
activatePipelinedHandoff(socket);
return;
}

if (res.assignSocket === ServerResponse.prototype.assignSocket) {
assignSocketInternal(res, socket);
} else {
Expand Down
Loading
Loading