Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
9f849eb
structured clone: check the range of a view
claude Nov 11, 2026
b35c1a2
node:crypto: keep the CryptoKey of a key argument alive across its de…
claude Nov 11, 2026
9eafece
X509Certificate: report all of a certificate of 64 KiB or more to the GC
claude Nov 11, 2026
9b6abb5
webcrypto: report the native memory of a CryptoKey to the GC
claude Nov 11, 2026
2930928
bindgen: fence the members of a returned dictionary before it is publ…
claude Nov 11, 2026
e9c733a
WebIDL: return after the TypeError
claude Nov 11, 2026
ff70857
usockets: give a nested tick its own receive buffers
claude Nov 11, 2026
24e421e
uws: keep the state of a parse that has another parse under it
claude Nov 11, 2026
73a5c3c
sqlite: let the database cell mark the accumulators of aggregates
claude Nov 11, 2026
ed8fe62
webview: read the receive buffer again after each reply was handled
claude Nov 11, 2026
46b61d4
webview: close the WKWebView when its view is closed
claude Nov 11, 2026
004a8b2
webview: unlink the screenshot of a view that was closed meanwhile
claude Nov 11, 2026
2d5f0c2
ipc: keep the SendQueue alive while a read is decoded
claude Nov 11, 2026
c794a99
timers: do not keep the object of a timer that ended itself
claude Nov 11, 2026
c924d30
transpiler: give each pool thread job its own list of require.extensions
claude Nov 11, 2026
de62cfc
macros: copy the env map of the JS thread under a lock
claude Nov 11, 2026
dbe0884
node:stream: release the names that pipe() keeps on a Worker's thread
claude Nov 11, 2026
17b3de7
ipc: do not decode a message from a buffer that other sockets read into
claude Nov 11, 2026
5c56433
streams: keep byobRequest in step with the pull-into descriptors
claude Nov 11, 2026
335eb8c
streams: do not respond on a byte tee branch that addAbortSignal() er…
claude Nov 11, 2026
4319b8f
streams: decode a copy of a single SharedArrayBuffer chunk in text()
claude Nov 11, 2026
cd703ca
Bun.ModuleGraph: move only a CommonJS wrapper that nothing else can c…
claude Nov 11, 2026
105d45b
Bun.ModuleGraph: stop the context of a graph whose realm was collecte…
claude Nov 11, 2026
466bfaa
bun test: root the settled promise that ranks waiting module mocks again
claude Nov 11, 2026
c6aaec1
Bun.plugin: let the garbage collector take a ShadowRealm that registe…
claude Nov 11, 2026
a8e52d8
bun test --isolate: drop the jobs in the own queue of a node:vm conte…
claude Nov 11, 2026
b2bc2f9
node:vm: return undefined from evaluate() of a module that its cycle …
claude Nov 11, 2026
3d585c0
--hot, --watch: release the source of a module that require() loaded
claude Nov 11, 2026
66331e3
napi: keep the property key alive in napi_has_property and napi_delet…
claude Nov 11, 2026
8ed56a4
napi: take the wrap off a Proxy in napi_remove_wrap
claude Nov 11, 2026
32580a7
napi: run the napi_set_instance_data finalizer inside a handle scope
claude Nov 11, 2026
5df639b
v8: destroy collected templates, and check at compile time that cells…
claude Nov 11, 2026
b2d51bb
Bun.serve: check route parameters for duplicates by the name they get
claude Nov 12, 2026
fc50aa5
streams: do not start a codec chunk while the step of an abandoned on…
claude Nov 12, 2026
c9dd893
napi: open the handle scope at env teardown only for an instance data…
claude Nov 12, 2026
e290317
uws: do not defer a close to the end of a parse that another one inte…
claude Nov 12, 2026
580bdeb
timers: root an interval again that a nested run of its callback ended
claude Nov 12, 2026
8805848
webcrypto: count only keys of 4 KiB or more, and a shared key not at all
claude Nov 12, 2026
06e7538
streams: run a codec chunk behind an abandoned step when that is done
claude Nov 12, 2026
e771f04
streams: drop the descriptor of each read that the queue answers
claude Nov 12, 2026
7c9b284
Bun.ModuleGraph: accept a CommonJS wrapper that is a whole statement
claude Nov 12, 2026
1aec13e
Bun.serve: check the names of parameters only where a handler reads them
claude Nov 12, 2026
3e17cd2
ipc: decode the messages of a read in place again
claude Nov 12, 2026
acccdfa
macros: read NODE_PATH under the lock of the env map
claude Nov 12, 2026
88f2684
Throw ERR_STRING_TOO_LONG for a module only with --hot or --watch, as…
claude Nov 12, 2026
33d1e00
test: cover view records, the package.json type under --hot, and a lo…
claude Nov 12, 2026
8304f60
[autofix.ci] apply automated fixes
autofix-ci[bot] Nov 12, 2026
81c3aa4
jsc_hooks: put the safety comment in front of the unsafe block
claude Nov 13, 2026
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
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions packages/bun-usockets/src/crypto/openssl.c
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@

struct loop_ssl_data {
char *ssl_read_input, *ssl_read_output;
/* Kept from the last nested tick for the next one. NULL until there was one. */
char *spare_read_output;
unsigned int ssl_read_input_length;
unsigned int ssl_read_input_offset;

Expand Down Expand Up @@ -770,10 +772,29 @@ void us_internal_init_loop_ssl_data(struct us_loop_t *loop) {
}
}

char *us_internal_ssl_replace_read_output(struct us_loop_t *loop) {
struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *)loop->data.ssl_data;
if (!loop_ssl_data) return NULL;
char *outer = loop_ssl_data->ssl_read_output;
loop_ssl_data->ssl_read_output = loop_ssl_data->spare_read_output ? loop_ssl_data->spare_read_output : ssl_alloc_read_output();
if (!loop_ssl_data->ssl_read_output) Bun__outOfMemory();
loop_ssl_data->spare_read_output = NULL;
return outer;
}

void us_internal_ssl_restore_read_output(struct us_loop_t *loop, char *outer) {
if (!outer) return;
struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *)loop->data.ssl_data;
if (!loop_ssl_data->spare_read_output) loop_ssl_data->spare_read_output = loop_ssl_data->ssl_read_output;
else us_free(loop_ssl_data->ssl_read_output);
loop_ssl_data->ssl_read_output = outer;
}

void us_internal_free_loop_ssl_data(struct us_loop_t *loop) {
struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *)loop->data.ssl_data;
if (loop_ssl_data) {
us_free(loop_ssl_data->ssl_read_output);
us_free(loop_ssl_data->spare_read_output);
us_free(loop_ssl_data->ssl_write_batch);
BIO_free(loop_ssl_data->shared_rbio);
BIO_free(loop_ssl_data->shared_wbio);
Expand Down
12 changes: 6 additions & 6 deletions packages/bun-usockets/src/eventing/epoll_kqueue.c
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout
/* Pointer tags are used to indicate a Bun pointer versus a uSockets pointer */
#define UNSET_BITS_49_UNTIL_64 0x0000FFFFFFFFFFFF
#define CLEAR_POINTER_TAG(p) ((void *) ((uintptr_t) (p) & UNSET_BITS_49_UNTIL_64))
#define LIKELY(cond) __builtin_expect((_Bool)(cond), 1)
#define UNLIKELY(cond) __builtin_expect((_Bool)(cond), 0)

#ifdef LIBUS_USE_EPOLL
#define GET_READY_POLL(loop, index) (struct us_poll_t *) loop->ready_polls[index].data.ptr
Expand Down Expand Up @@ -448,7 +446,8 @@ static const struct timespec *us_internal_clamp_to_sweep(struct us_loop_t *loop,
void us_loop_run(struct us_loop_t *loop) {
/* While we have non-fallthrough polls we shouldn't fall through */
while (loop->num_polls) {
loop->data.tick_depth++;
struct us_internal_outer_recv_bufs outer;
us_internal_loop_enter_tick(loop, &outer);
/* Emit pre callback */
us_internal_loop_pre(loop);

Expand All @@ -468,7 +467,7 @@ void us_loop_run(struct us_loop_t *loop) {

/* Emit post callback */
us_internal_loop_post(loop);
loop->data.tick_depth--;
us_internal_loop_leave_tick(loop, &outer);
}
}

Expand All @@ -479,7 +478,8 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout
if (loop->num_polls == 0)
return;

loop->data.tick_depth++;
struct us_internal_outer_recv_bufs outer;
us_internal_loop_enter_tick(loop, &outer);
Comment on lines +481 to +482

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: Pre-existing, left by this hunk: a poll callback that ticks the loop makes the outer tick drop the rest of its ready batch, so one-shot fds such as Bun.spawn pipes or a macOS child's exit are never serviced again. The nested us_loop_run_bun_tick overwrites loop->ready_polls, num_ready_polls and current_ready_poll at epoll_kqueue.c:536-558, and the outer for loop at :258 (epoll) or :350 (kqueue) then ends. Fix: have us_internal_loop_enter_tick/leave_tick (internal.h:245-251) save and restore the batch count, index and undispatched entries as they now do for recv_buf, for epoll, kqueue and us_internal_drain_ready_polls. EPOLLONESHOT/EV_DISPATCH polls are disarmed by the kernel and have no re-arm path.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

The outer tick in us_loop_run_bun_tick fetches a batch into loop->ready_polls (epoll_kqueue.c:536-538) and dispatches it with the for loop at epoll_kqueue.c:258 (kqueue: :350). A callback of entry k runs the event loop again. The nested us_loop_run_bun_tick refills loop->ready_polls and num_ready_polls, sets current_ready_poll = 0 (:550) and its dispatch leaves current_ready_poll == its own num_ready_polls. Back in the outer for loop the ++ makes the bound fail, so outer entries k+1.. are never dispatched. us_internal_loop_enter_tick (internal.h:245-251) saves only recv_buf and the SSL read output, not the batch. FilePolls registered with OneShotFlag::Dispatch (io/lib.rs:1927) get EPOLLONESHOT at posix_event_loop.rs:591-595 and EV_DISPATCH on macOS at :645-651, and the EVFILT_PROC exit watch keeps EV_ONESHOT on macOS (process.rs:90): the kernel disarmed them when it reported them, Bun re-arms only on dispatch, so the pipe is never read or drained again and 'exit' never arrives. The base branch behaves the same.

Verification: A nested us_loop_run_bun_tick overwrites loop->ready_polls, num_ready_polls and current_ready_poll (packages/bun-usockets/src/eventing/epoll_kqueue.c:536-538, :550), so every outer entry after the re-entering one is never dispatched. us_internal_loop_enter_tick/leave_tick (internal.h:245-251) only swap recv_buf/ssl_read_output. The base branch has the identical dispatch loop.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not in this PR. The base loses the same events. Restoring the batch is not a small fix: us_internal_loop_update_pending_ready_polls() would have to look through the saved batches too, or a poll that the nested tick closed would be dispatched after it was freed. That is worse than the lost event, so it needs its own change.


Generated by Claude Code


/* Emit pre callback */
us_internal_loop_pre(loop);
Expand Down Expand Up @@ -561,7 +561,7 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout

/* Emit post callback */
us_internal_loop_post(loop);
loop->data.tick_depth--;
us_internal_loop_leave_tick(loop, &outer);
}

void us_internal_loop_update_pending_ready_polls(struct us_loop_t *loop, struct us_poll_t *old_poll, struct us_poll_t *new_poll, int old_events, int new_events) {
Expand Down
10 changes: 6 additions & 4 deletions packages/bun-usockets/src/eventing/libuv.c
Original file line number Diff line number Diff line change
Expand Up @@ -336,11 +336,12 @@ void us_loop_pump(struct us_loop_t *loop) {
* timers are never processed. Bun's outer drive loops (wait_for_promise,
* bun:test) supply their own keep-going predicate, so force exactly one
* non-blocking iteration; UV_RUN_NOWAIT keeps the poll timeout at 0. */
loop->data.tick_depth++;
struct us_internal_outer_recv_bufs outer;
us_internal_loop_enter_tick(loop, &outer);
loop->uv_loop->active_handles++;
uv_run(loop->uv_loop, UV_RUN_NOWAIT);
loop->uv_loop->active_handles--;
loop->data.tick_depth--;
us_internal_loop_leave_tick(loop, &outer);
}

struct us_loop_t *us_create_loop(void *hint,
Expand Down Expand Up @@ -473,9 +474,10 @@ void us_loop_run(struct us_loop_t *loop) {
/* us_internal_loop_post only frees closed sockets at depth 1. A poll callback
* that waits for a promise re-enters here while the outer dispatch is still
* using its socket. us_loop_run_bun_tick does the same on POSIX. */
loop->data.tick_depth++;
struct us_internal_outer_recv_bufs outer;
us_internal_loop_enter_tick(loop, &outer);
uv_run(loop->uv_loop, UV_RUN_ONCE);
loop->data.tick_depth--;
us_internal_loop_leave_tick(loop, &outer);
}

struct us_poll_t *us_create_poll(struct us_loop_t *loop, int fallthrough,
Expand Down
22 changes: 20 additions & 2 deletions packages/bun-usockets/src/internal/internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ void us_internal_loop_update_pending_ready_polls(struct us_loop_t *loop,
#endif

#ifndef LIKELY
#define LIKELY(cond) __builtin_expect((_Bool)(cond), 1)
#define UNLIKELY(cond) __builtin_expect((_Bool)(cond), 0)
#define LIKELY(cond) __builtin_expect(!!(cond), 1)
#define UNLIKELY(cond) __builtin_expect(!!(cond), 0)
#endif

extern void __attribute__((__noreturn__)) Bun__panic(const char *message, size_t length);
Expand Down Expand Up @@ -235,6 +235,21 @@ void us_internal_loop_data_free(us_loop_r loop);
void us_internal_loop_pre(us_loop_r loop);
void us_internal_loop_post(us_loop_r loop);

/* The receive buffers that a dispatch below a nested tick still reads. */
struct us_internal_outer_recv_bufs {
char *recv_buf;
char *ssl_read_output;
};
void us_internal_loop_replace_recv_bufs(us_loop_r loop, struct us_internal_outer_recv_bufs *outer);
void us_internal_loop_restore_recv_bufs(us_loop_r loop, struct us_internal_outer_recv_bufs *outer);
static inline void us_internal_loop_enter_tick(us_loop_r loop, struct us_internal_outer_recv_bufs *outer) {
if (UNLIKELY(++loop->data.tick_depth > 1)) us_internal_loop_replace_recv_bufs(loop, outer);
}
static inline void us_internal_loop_leave_tick(us_loop_r loop, struct us_internal_outer_recv_bufs *outer) {
if (UNLIKELY(loop->data.tick_depth > 1)) us_internal_loop_restore_recv_bufs(loop, outer);
loop->data.tick_depth--;
}

/* node:quic loop driver (node_quic_shim.c): per-turn engine pass. */
struct us_nq_driver_s;
void us_nq_loop_flush_if_pending(struct us_loop_t *loop);
Expand Down Expand Up @@ -262,6 +277,9 @@ void us_internal_poll_close_fd(struct us_poll_t *p);

/* SSL loop data */
void us_internal_init_loop_ssl_data(us_loop_r loop);
/* Both return NULL, and the second does nothing, for a loop that had no TLS yet. */
char *us_internal_ssl_replace_read_output(us_loop_r loop);
void us_internal_ssl_restore_read_output(us_loop_r loop, char *outer);
void us_internal_free_loop_ssl_data(us_loop_r loop);

/* Socket context related */
Expand Down
2 changes: 2 additions & 0 deletions packages/bun-usockets/src/internal/loop_data.h
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ struct us_internal_loop_data_t {
#endif
struct us_socket_group_t *iterator;
char *recv_buf;
/* Kept from the last nested tick for the next one. NULL until there was one. */
char *spare_recv_buf;
char *send_buf;
void *ssl_data;
void (*pre_cb)(struct us_loop_t *);
Expand Down
33 changes: 29 additions & 4 deletions packages/bun-usockets/src/loop.c
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,14 @@ void us_internal_sweep_if_due(struct us_loop_t *loop) {
#endif


static char *us_internal_alloc_recv_buf(void) {
char *recv_buf = us_malloc(LIBUS_RECV_BUFFER_LENGTH + LIBUS_RECV_BUFFER_PADDING * 2);
/* Every read on this loop writes into recv_buf; a NULL here makes each one
* fail with EFAULT for the life of the process. */
if (!recv_buf) Bun__outOfMemory();
return recv_buf;
}

/* -1 if the wakeup async cannot be created; nothing is left allocated in loop->data. */
int us_internal_loop_data_init(struct us_loop_t *loop, void (*wakeup_cb)(struct us_loop_t *loop),
void (*pre_cb)(struct us_loop_t *loop), void (*post_cb)(struct us_loop_t *loop)) {
Expand All @@ -131,11 +139,9 @@ int us_internal_loop_data_init(struct us_loop_t *loop, void (*wakeup_cb)(struct
loop->data.sweep_next_tick_ns = -1;
#endif
loop->data.sweep_timer_count = 0;
loop->data.recv_buf = us_malloc(LIBUS_RECV_BUFFER_LENGTH + LIBUS_RECV_BUFFER_PADDING * 2);
loop->data.recv_buf = us_internal_alloc_recv_buf();
loop->data.send_buf = us_malloc(LIBUS_SEND_BUFFER_LENGTH);
/* Every read on this loop writes into recv_buf; a NULL here makes each one
* fail with EFAULT for the life of the process. */
if (!loop->data.recv_buf || !loop->data.send_buf) Bun__outOfMemory();
if (!loop->data.send_buf) Bun__outOfMemory();
loop->data.pre_cb = pre_cb;
loop->data.post_cb = post_cb;
loop->data.wakeup_async = us_internal_create_async(loop, 1, 0);
Expand All @@ -162,6 +168,7 @@ void us_internal_loop_data_free(struct us_loop_t *loop) {
#endif

us_free(loop->data.recv_buf);
us_free(loop->data.spare_recv_buf);
us_free(loop->data.send_buf);
us_free(loop->data.unresumable_sockets);

Expand All @@ -172,6 +179,24 @@ void us_internal_loop_data_free(struct us_loop_t *loop) {
us_internal_async_close(loop->data.wakeup_async);
}

void us_internal_loop_replace_recv_bufs(struct us_loop_t *loop, struct us_internal_outer_recv_bufs *outer) {
outer->recv_buf = loop->data.recv_buf;
loop->data.recv_buf = loop->data.spare_recv_buf ? loop->data.spare_recv_buf : us_internal_alloc_recv_buf();
loop->data.spare_recv_buf = NULL;
#ifndef LIBUS_NO_SSL
outer->ssl_read_output = us_internal_ssl_replace_read_output(loop);
#endif
}

void us_internal_loop_restore_recv_bufs(struct us_loop_t *loop, struct us_internal_outer_recv_bufs *outer) {
if (!loop->data.spare_recv_buf) loop->data.spare_recv_buf = loop->data.recv_buf;
else us_free(loop->data.recv_buf);
loop->data.recv_buf = outer->recv_buf;
#ifndef LIBUS_NO_SSL
us_internal_ssl_restore_read_output(loop, outer->ssl_read_output);
#endif
}

__attribute__((always_inline)) void us_wakeup_loop(struct us_loop_t *loop) {
#ifndef LIBUS_USE_LIBUV
__atomic_fetch_add(&loop->pending_wakeups, 1, __ATOMIC_RELEASE);
Expand Down
31 changes: 13 additions & 18 deletions packages/bun-uws/src/HttpContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -432,9 +432,11 @@ struct HttpContext {
((AsyncSocket<SSL> *) s)->cork();

/* Mark that we are inside the parser now */
httpContextData->flags.isParsingHttp = true;
struct us_socket_t *prevParsingSocket = httpContextData->parsingSocket;
httpContextData->parsingSocket = s;
typename HttpContextData<SSL>::Parse parse{s, httpContextData->innermostParse};
if (parse.outer) [[unlikely]] {
parse.outer->interrupted = true;
}
httpContextData->innermostParse = &parse;
Comment on lines +435 to +439

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: pre-existing, left by this hunk: a node:http handler that destroys its own connection and then waits in a nested event loop for its 'close' still hangs, as on the base. HttpContext.h:437 sets interrupted only when another onData() of this context starts under the parse, not when the handler ticks the loop, so closeAfterMessageIfParsing() (HttpResponse.h:149) still defers the close to the end of a parse the handler never lets end. Fix: isParsing() must be false for a parse whose handler has entered a nested tick, whatever that tick reads, e.g. record the loop's tick_depth in Parse at HttpContext.h:435 and compare it in isParsing(), which also covers closeAllConnections() and the serve.test.ts cases.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

A node:http request handler calls req.socket.destroy() while uws is still inside the parse of that socket's read, then runs the event loop (Bun.build() with an async plugin setup()) until the socket's 'close' fires, with no other request of that server read during the wait. JSNodeHTTPServerSocket::close at src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp:106-112 asks closeAfterMessageIfParsing(), which at packages/bun-uws/src/HttpResponse.h:149 checks isParsing(); HttpContextData.h:121 returns true because interrupted is only set at HttpContext.h:437 when a nested onData() begins, and no nested onData() happens here. HTTP_NODE_CLOSE_AFTER_MESSAGE is then honored only at HttpContext.h:793 after the parse returns, which waits for the handler, which waits for the close: the request hangs until the test or client times out. The base behaves the same. The new test "socket.destroy() after another request" in test/js/bun/http/serve.test.ts passes only because its nested wait first parses other's request, which sets interrupted.

Verification: HttpContextData.h:121 isParsing(s) is isInnermostParse(s) && !innermostParse->interrupted, and interrupted is set only at HttpContext.h:436-438 when ANOTHER onData() begins under the parse — never when the handler itself ticks the loop. The base gate flags.isParsingHttp && parsingSocket == s (old HttpContextData.h:112) gives the identical deferral, so this is not a regression.

const bool wasIdle = httpResponseData->isIdle;
httpResponseData->isIdle = false;

Expand Down Expand Up @@ -598,7 +600,7 @@ struct HttpContext {
}

/* First of all we need to check if this socket was deleted due to upgrade */
if (httpContextData->upgradedWebSocket) {
if (httpContextData->innermostParse->upgradedWebSocket) {
/* We differ between closed and upgraded below */
return nullptr;
}
Expand Down Expand Up @@ -691,7 +693,7 @@ struct HttpContext {
httpResponseData->inStream(static_cast<HttpResponse<SSL>*>(user), data.data(), data.length(), fin, httpResponseData->userData);

/* The body handler upgraded this socket (ws.handleUpgrade in req 'end'): upgrade() destroyed httpResponseData, so stop here. */
if (httpContextData->upgradedWebSocket) {
if (httpContextData->innermostParse->upgradedWebSocket) {
return nullptr;
}

Expand Down Expand Up @@ -740,8 +742,7 @@ struct HttpContext {
auto httpErrorStatusCode = result.httpErrorStatusCode();

/* Mark that we are no longer parsing Http */
httpContextData->flags.isParsingHttp = false;
httpContextData->parsingSocket = prevParsingSocket;
httpContextData->innermostParse = parse.outer;
/* If we got fullptr that means the parser wants us to close the socket from error (same as calling the errorHandler) */
if (httpErrorStatusCode) {
/* node:http compat: parse errors surface as the server's 'clientError'
Expand Down Expand Up @@ -789,7 +790,7 @@ struct HttpContext {

/* JavaScript destroyed the socket and its message did not complete in this read: close now, unless the read made this socket a WebSocket. */
if constexpr (IsNodeHttp) {
if (httpContextData->upgradedWebSocket != s && !us_socket_is_closed(s)
if (parse.upgradedWebSocket != s && !us_socket_is_closed(s)
&& (httpResponseData->state & HttpResponseData<SSL>::HTTP_NODE_CLOSE_AFTER_MESSAGE)) {
closeDestroyedNodeHttpSocket(s, httpResponseData);
returnedData = nullptr;
Expand Down Expand Up @@ -854,26 +855,20 @@ struct HttpContext {
}

/* If we upgraded, check here (differ between nullptr close and nullptr upgrade) */
if (httpContextData->upgradedWebSocket) {
if (parse.upgradedWebSocket) {
/* This path is only for upgraded websockets */
AsyncSocket<SSL> *asyncSocket = (AsyncSocket<SSL> *) httpContextData->upgradedWebSocket;
AsyncSocket<SSL> *asyncSocket = (AsyncSocket<SSL> *) parse.upgradedWebSocket;

/* Uncork here as well (note: what if we failed to uncork and we then pub/sub before we even upgraded?) */
asyncSocket->uncork();

/* Reset upgradedWebSocket before we return */
httpContextData->upgradedWebSocket = nullptr;

/* Frames that a client sent without waiting for the 101 (RFC 6455 4.1) follow the
* request head in this read, and the HTTP parser stopped there. Give them to the
* WebSocket now, as the loop would have for a read of its own. If the request declared
* a body, the parser counts the whole read as consumed, so what this read holds of the
* body is not taken for frames. Nothing remembers the rest: a later read is all frames.
* Not when upgradedWebSocket names another connection (upgrade() adopts in place,
* so ours is s): the field is per context, and a microtask of this dispatch, or an
* earlier upgrade from a request body handler, can set it. */
* body is not taken for frames. Nothing remembers the rest: a later read is all frames. */
unsigned int consumed = result.consumedBytes();
if (consumed < (unsigned int) length && (us_socket_t *) asyncSocket == s
if (parse.readHoldsUpgrade && consumed < (unsigned int) length && (us_socket_t *) asyncSocket == s /* upgrade() adopts in place */
&& !us_socket_is_closed(s) && !us_socket_is_shut_down(s)) {
return us_dispatch_data(s, data + consumed, (int) ((unsigned int) length - consumed));
}
Expand Down
29 changes: 19 additions & 10 deletions packages/bun-uws/src/HttpContextData.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ struct HttpRequest;
struct Http2Context;

struct HttpFlags {
bool isParsingHttp: 1 = false;
bool rejectUnauthorized: 1 = false;
bool usingCustomExpectHandler: 1 = false;
bool requireHostHeader: 1 = true;
Expand Down Expand Up @@ -67,16 +66,25 @@ struct alignas(16) HttpContextData {
HttpRequest *httpRequest;
};

/* The socket onData is currently parsing, nullptr outside a parse. The
* close gates in internalEnd need the per-socket identity: a DIFFERENT
* socket's response can complete inside this window (a microtask drained
* during a request dispatch), and the context-wide isParsingHttp bit
* alone would wrongly defer its close to a post-parse gate that only
* checks the parsed socket. */
struct us_socket_t *parsingSocket = nullptr;
/* An onData() that is parsing, on its stack. A handler that runs the event
* loop puts another parse, rarely one of the same socket, on top of it. The close gates
* in internalEnd need the per-socket identity: a DIFFERENT socket's response
* can complete inside this window (a microtask drained during a request
* dispatch), and its close must not be deferred to a post-parse gate that
* only checks the parsed socket. */
struct Parse {
struct us_socket_t *socket;
Parse *outer;
/* Set by upgrade() of the socket. */
void *upgradedWebSocket = nullptr;
/* Its read holds the request that upgraded. */
bool readHoldsUpgrade = false;
/* Its handler has run the event loop, and may be waiting there for a close: nothing is deferred to its end any more. */
bool interrupted = false;
};
Parse *innermostParse = nullptr;

HttpRouter<RouterData> router;
void *upgradedWebSocket = nullptr;
/* Used to simulate Node.js socket events. */
OnSocketClosedCallback onSocketClosed = nullptr;
OnSocketDrainCallback onSocketDrain = nullptr;
Expand Down Expand Up @@ -109,7 +117,8 @@ struct alignas(16) HttpContextData {

HttpFlags flags;

bool isParsing(struct us_socket_t *s) const { return flags.isParsingHttp && parsingSocket == s; }
bool isInnermostParse(struct us_socket_t *s) const { return innermostParse && innermostParse->socket == s; }
bool isParsing(struct us_socket_t *s) const { return isInnermostParse(s) && !innermostParse->interrupted; }
};

}
Expand Down
Loading
Loading