Skip to content
3 changes: 3 additions & 0 deletions packages/bun-uws/src/App.h
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,9 @@ struct TemplatedApp {
void setOnSocketData(HttpContextData<SSL>::OnSocketDataCallback onData) {
httpContext->getSocketContextData()->onSocketData = onData;
}
void setOnSocketActivity(HttpContextData<SSL>::OnSocketActivityCallback onActivity) {
httpContext->getSocketContextData()->onSocketActivity = onActivity;
}

void setOnClientError(HttpContextData<SSL>::OnClientErrorCallback onClientError) {
httpContext->getSocketContextData()->onClientError = std::move(onClientError);
Expand Down
21 changes: 21 additions & 0 deletions packages/bun-uws/src/HttpContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,7 @@ struct HttpContext {
nodeHttpResponseData->lastMessageStartMs = nodeCompatMonotonicMs();
}
nodeHttpResponseData->headersCompleted = true;
nodeHttpResponseData->readDelivered = true;
}

/* Are we not ready for another request yet? Terminate the connection.
Expand Down Expand Up @@ -614,6 +615,9 @@ struct HttpContext {
}

if (httpResponseData->isConnectRequest && httpResponseData->socketData && httpContextData->onSocketData) {
if constexpr (IsNodeHttp) {
((HttpResponseData<SSL, true> *) httpResponseData)->readDelivered = true;
}
httpContextData->onSocketData(httpResponseData->socketData, SSL, (struct us_socket_t *) user, data.data(), data.length(), fin);
}

Expand All @@ -623,6 +627,9 @@ struct HttpContext {
}
/* We always get an empty chunk even if there is no data */
if (httpResponseData->inStream) {
if constexpr (IsNodeHttp) {
((HttpResponseData<SSL, true> *) httpResponseData)->readDelivered = true;
}

/* Todo: can this handle timeout for non-post as well? */
if (fin) {
Expand Down Expand Up @@ -705,6 +712,7 @@ struct HttpContext {
/* We don't want open sockets to keep the event loop alive between HTTP requests */
us_socket_unref((us_socket_t *) returnedData);

[[maybe_unused]] bool readGaveJsNothing = false;
/* node:http compat: a partial request head was left in the fallback
* buffer by this read (either fresh bytes on an idle connection or a
* pipelined request after the previous message completed) - its
Expand All @@ -716,6 +724,7 @@ struct HttpContext {
nodeHttpResponseData->lastMessageStartMs = nodeCompatMonotonicMs();
nodeHttpResponseData->headersCompleted = false;
}
readGaveJsNothing = !std::exchange(nodeHttpResponseData->readDelivered, false);
}

/* Timeout on uncork failure */
Expand All @@ -736,6 +745,18 @@ struct HttpContext {
}
}
}

/* node:http compat: this read gave JS nothing (a partial head, chunk
* framing, trailers, a body that nothing reads), so nothing there
* refreshed the socket's inactivity timer. Node does that on every
* read. The hook runs JS, so it comes last: nothing below it may
* touch the socket. */
if constexpr (IsNodeHttp) {
if (readGaveJsNothing && !us_socket_is_closed(s)
&& httpResponseData->socketData && httpContextData->onSocketActivity) {
httpContextData->onSocketActivity(httpResponseData->socketData, SSL, s);
}
}
return (us_socket_t *) returnedData;
}

Expand Down
2 changes: 2 additions & 0 deletions packages/bun-uws/src/HttpContextData.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ struct alignas(16) HttpContextData {
std::vector<MoveOnlyFunction<void(HttpResponse<SSL> *, int)>> filterHandlers;
using OnSocketDataCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket, const char *data, int length, bool last);
using OnSocketDrainCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket);
using OnSocketActivityCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket);
using OnSocketUpgradedCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket);
using OnClientErrorCallback = MoveOnlyFunction<void(int is_ssl, struct us_socket_t *rawSocket, uWS::HttpParserError errorCode, char *rawPacket, int rawPacketLength)>;
using OnSocketClosedCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket);
Expand Down Expand Up @@ -83,6 +84,7 @@ struct alignas(16) HttpContextData {
/* Used to simulate Node.js socket events. */
OnSocketClosedCallback onSocketClosed = nullptr;
OnSocketDrainCallback onSocketDrain = nullptr;
OnSocketActivityCallback onSocketActivity = nullptr;
OnSocketDataCallback onSocketData = nullptr;
OnSocketUpgradedCallback onSocketUpgraded = nullptr;
OnClientErrorCallback onClientError = nullptr;
Expand Down
2 changes: 2 additions & 0 deletions packages/bun-uws/src/HttpResponseData.h
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,8 @@ struct HttpResponseData<SSL, true> : HttpResponseData<SSL, false> {
bool headersCompleted = false;
/* Timeout sweep already reported this message; reset when it completes. */
bool requestTimeoutReported = false;
/* The current read dispatched a request or delivered body bytes, so JS saw it. */
bool readDelivered = false;
};

/* Readable name for the IsNodeHttp=true specialization (used by the node:http
Expand Down
13 changes: 6 additions & 7 deletions src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1452,13 +1452,12 @@ function onSocketTimeoutTimerExpired(socket) {
const idleStart = socket[kKeepAliveIdleStart];
if (idleStart !== undefined && socket[kKeepAliveTimeoutSet]) {
socket[kKeepAliveIdleStart] = undefined;
const remaining = socket.timeout - (DateNow() - idleStart);
if (remaining > 0) {
const existingTimer = socket[kSocketTimeoutTimer];
if (existingTimer !== undefined) clearTimeout(existingTimer);
const timer = setTimeout(onSocketTimeoutTimerExpired, remaining, socket);
timer.unref();
socket[kSocketTimeoutTimer] = timer;
const idleFor = DateNow() - idleStart;
const timer = socket[kSocketTimeoutTimer];
if (idleFor < socket.timeout && timer !== undefined) {
// The timer keeps its full interval for the next refresh(). Moving _idleStart back moves only this deadline.
timer.refresh();
timer._idleStart -= idleFor;
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
return;
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/jsc/bindings/NodeHTTP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,11 @@ static void assignOnNodeJSCompat(uWS::TemplatedApp<isSSL>* app)
ASSERT(rawSocket == socket->socket || socket->socket == nullptr);
socket->onData(data, length, last);
});
app->setOnSocketActivity([](void* socketData, int is_ssl, struct us_socket_t* rawSocket) -> void {
auto* socket = reinterpret_cast<JSNodeHTTPServerSocket*>(socketData);
ASSERT(rawSocket == socket->socket || socket->socket == nullptr);
socket->onActivity();
});
app->setOnSocketUpgraded([](void* socketData, int is_ssl, struct us_socket_t* rawSocket) -> void {
auto* socket = reinterpret_cast<JSNodeHTTPServerSocket*>(socketData);
// the socket is adopted and might not be the same as the rawSocket
Expand Down
21 changes: 21 additions & 0 deletions src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -797,6 +797,27 @@ void JSNodeHTTPServerSocket::onData(const char* data, int length, bool last)
}
}

void JSNodeHTTPServerSocket::onActivity()
{
auto* duplex = m_duplex.get();
auto* globalObject = defaultGlobalObject(this->globalObject());
if (!duplex || globalObject->scriptExecutionStatus(globalObject, this) != ScriptExecutionStatus::Running) {
return;
}
auto& vm = globalObject->vm();
EnsureStillAliveScope ensureStillAlive(this);
auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
JSValue unrefTimer = duplex->get(globalObject, JSC::Identifier::fromString(vm, "_unrefTimer"_s));
if (auto* exception = scope.exception()) {
(void)scope.tryClearException();
globalObject->reportUncaughtExceptionAtEventLoop(globalObject, exception);
return;
}
if (unrefTimer.isCallable()) {
Bun__EventLoop__runCallback2(globalObject, JSValue::encode(unrefTimer), JSValue::encode(duplex), JSValue::encode(jsUndefined()), JSValue::encode(jsUndefined()));
}
}
Comment thread
robobun marked this conversation as resolved.
Resolved

JSC::Structure* JSNodeHTTPServerSocket::createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject)
{
auto* structure = JSC::Structure::create(vm, globalObject, globalObject->objectPrototype(), JSC::TypeInfo(JSC::ObjectType, StructureFlags), JSNodeHTTPServerSocketPrototype::info());
Expand Down
2 changes: 2 additions & 0 deletions src/jsc/bindings/node/JSNodeHTTPServerSocket.h
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ class JSNodeHTTPServerSocket : public JSC::JSDestructibleObject {
void onClose();
void onDrain();
void onData(const char* data, int length, bool last);
/* A read gave JS nothing: calls the duplex's _unrefTimer(), as Node does on every socket read. */
void onActivity();

static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject);
void finishCreation(JSC::VM& vm);
Expand Down
Loading
Loading