Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
11 changes: 11 additions & 0 deletions packages/bun-usockets/src/context.c
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,17 @@ void us_internal_socket_after_open(struct us_socket_t *s, int error) {
}
}
}
#else
/* A failed non-blocking connect() is reported as "writable" on every
* platform; the actual errno lives in SO_ERROR. epoll also sets
* EPOLLERR/EPOLLHUP so the dispatch flag was enough there, but kqueue
* signals it via EVFILT_WRITE + EV_EOF, which the dispatch loop no longer
* maps (EV_EOF on an established socket is a half-close, not an error).
* Probe SO_ERROR unconditionally — it is the portable contract for async
* connect completion and costs one getsockopt on this cold path. */
if (error == 0) {
error = us_socket_get_error(s);
}
#endif
if (error) {
if (c) {
Expand Down
51 changes: 32 additions & 19 deletions packages/bun-usockets/src/eventing/epoll_kqueue.c
Original file line number Diff line number Diff line change
Expand Up @@ -215,14 +215,27 @@ static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) {
/* Kqueue delivers each filter (READ, WRITE, TIMER, etc.) as a separate kevent,
* so the same fd/poll can appear twice in ready_polls. We coalesce them into a
* single set of flags per poll before dispatching, matching epoll's behavior
* where each fd appears once with a combined bitmask. */
* where each fd appears once with a combined bitmask.
*
* EV_EOF is intentionally NOT mapped to dispatch's `eof`. Kqueue sets EV_EOF on
* EVFILT_READ for a half-close (peer FIN — analogous to EPOLLRDHUP, which the
* epoll path also does not map) and on EVFILT_WRITE when the peer's read side is
* gone. Treating either as `eof` made loop.c close the socket before the recv
* loop had drained the kernel buffer — e.g. an EVFILT_WRITE-only event carrying
* EV_EOF skips recv entirely, and a busy-loop bail-out can leave bytes unread in
* the same tick the flag arrived. EVFILT_READ is level-triggered and keeps
* firing after a FIN, so recv()==0 (loop.c) is the single source of `eof`,
* same as Linux. RST/hard errors surface via the recv()/send() error paths;
* connect failures via getsockopt(SO_ERROR) in us_internal_socket_after_open.
* (EV_ERROR only flags changelist-processing failures — the wait kevent64
* calls below pass a NULL changelist, so `error` is effectively always 0
* here; it is kept for symmetry with the epoll path.) */
struct kevent_flags {
uint8_t readable : 1;
uint8_t writable : 1;
uint8_t error : 1;
uint8_t eof : 1;
uint8_t skip : 1;
uint8_t _pad : 3;
uint8_t _pad : 4;
};

_Static_assert(sizeof(struct kevent_flags) == 1, "kevent_flags must be 1 byte");
Expand All @@ -246,7 +259,6 @@ static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) {
#endif
.writable = (filter == EVFILT_WRITE),
.error = !!(flags & EV_ERROR),
.eof = !!(flags & EV_EOF),
};

/* Look backward for a prior entry with the same poll to coalesce into.
Expand All @@ -257,7 +269,6 @@ static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) {
coalesced[j].readable |= bits.readable;
coalesced[j].writable |= bits.writable;
coalesced[j].error |= bits.error;
coalesced[j].eof |= bits.eof;
coalesced[i] = (struct kevent_flags){ .skip = 1 };
merged = 1;
break;
Expand Down Expand Up @@ -286,8 +297,8 @@ static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) {
| (bits.writable ? LIBUS_SOCKET_WRITABLE : 0);

events &= us_poll_events(poll);
if (events || bits.error || bits.eof) {
us_internal_dispatch_ready_poll(poll, bits.error, bits.eof, events);
if (events || bits.error) {
us_internal_dispatch_ready_poll(poll, bits.error, 0, events);
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}
}
#endif
Expand Down Expand Up @@ -443,19 +454,21 @@ int kqueue_change(int kqfd, int fd, int old_events, int new_events, void *user_d
int change_length = 0;

/* Do they differ in readable? */
int is_readable = (new_events & LIBUS_SOCKET_READABLE);
int is_writable = (new_events & LIBUS_SOCKET_WRITABLE);
if ((new_events & LIBUS_SOCKET_READABLE) != (old_events & LIBUS_SOCKET_READABLE)) {
EV_SET64(&change_list[change_length++], fd, EVFILT_READ, is_readable ? EV_ADD : EV_DELETE, 0, 0, (uint64_t)(void*)user_data, 0, 0);
}

if(!is_readable && !is_writable) {
if(!(old_events & LIBUS_SOCKET_WRITABLE)) {
// if we are not reading or writing, we need to add writable to receive FIN
EV_SET64(&change_list[change_length++], fd, EVFILT_WRITE, EV_ADD | EV_ONESHOT, 0, 0, (uint64_t)(void*)user_data, 0, 0);
}
} else if ((new_events & LIBUS_SOCKET_WRITABLE) != (old_events & LIBUS_SOCKET_WRITABLE)) {
/* Do they differ in writable? */
EV_SET64(&change_list[change_length++], fd, EVFILT_READ, (new_events & LIBUS_SOCKET_READABLE) ? EV_ADD : EV_DELETE, 0, 0, (uint64_t)(void*)user_data, 0, 0);
}

/* Do they differ in writable? EVFILT_WRITE is always one-shot, so a stale
* registration self-removes; we still issue the explicit EV_DELETE so a
* pending one-shot doesn't fire after the caller asked to stop watching.
* (There used to be a `new_events == 0` branch here that armed a one-shot
* EVFILT_WRITE "to receive FIN" — that only ever worked via EV_EOF, which
* the dispatch loop no longer maps. A paused socket now watches nothing on
* kqueue, which is what it effectively did before anyway since the one-shot
* fired immediately on any idle-writable socket. EV_DELETE on an
* already-fired one-shot returns ENOENT, which KEVENT_FLAG_ERROR_EVENTS
* routes into the result list and we ignore.) */
if ((new_events & LIBUS_SOCKET_WRITABLE) != (old_events & LIBUS_SOCKET_WRITABLE)) {
EV_SET64(&change_list[change_length++], fd, EVFILT_WRITE, (new_events & LIBUS_SOCKET_WRITABLE) ? EV_ADD | EV_ONESHOT : EV_DELETE, 0, 0, (uint64_t)(void*)user_data, 0, 0);
}
int ret;
Expand Down
13 changes: 12 additions & 1 deletion packages/bun-usockets/src/socket.c
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,15 @@ void us_internal_socket_raw_shutdown(struct us_socket_t *s) {
* so far, the app has to track this and call close as needed */
if (!us_socket_is_closed(s) && us_internal_poll_type(&s->p) != POLL_TYPE_SOCKET_SHUT_DOWN) {
us_internal_poll_set_type(&s->p, POLL_TYPE_SOCKET_SHUT_DOWN);
us_poll_change(&s->p, s->group->loop, us_poll_events(&s->p) & LIBUS_SOCKET_READABLE);
/* After SHUT_WR the only way this socket terminates is recv()==0 or a
* recv() error, so READABLE must be armed even if the socket was paused
* (which had cleared it). epoll could limp by on EPOLLHUP for the
* paused case, but kqueue has no equivalent once EV_EOF is no longer
* mapped — without READABLE the socket would never wake. Pause is
* meaningless after FIN anyway: we can't write, and the on_data path
* for a SHUT_DOWN socket discards what it reads. */
s->flags.is_paused = 0;
us_poll_change(&s->p, s->group->loop, LIBUS_SOCKET_READABLE);
bsd_shutdown_socket(us_poll_fd((struct us_poll_t *) s));
}
}
Expand Down Expand Up @@ -659,6 +667,9 @@ void us_socket_pause(struct us_socket_t *s) {
if (s->flags.is_paused) return;
// closed cannot be paused because it is already closed
if (us_socket_is_closed(s)) return;
/* See us_internal_socket_raw_shutdown: dropping READABLE on a shut-down
* socket would leave it unable to observe the peer's FIN. */
if (us_socket_is_shut_down(s)) return;
// we are readable and writable so we can just pause readable side
us_poll_change(&s->p, s->group->loop, LIBUS_SOCKET_WRITABLE);
s->flags.is_paused = 1;
Expand Down
79 changes: 79 additions & 0 deletions test/js/web/fetch/fetch-chunked-fin-same-tick-fixture.ts

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

23 changes: 23 additions & 0 deletions test/js/web/fetch/fetch-chunked-fin-same-tick.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe } from "harness";
import { join } from "node:path";

// kqueue used to map EV_EOF (from either filter) straight to dispatch's `eof`,
// so an EVFILT_WRITE event carrying EV_EOF — peer fully closed while we were
// still uploading — closed the socket before the recv loop drained the response
// bytes the same FIN carried. Linux never hit this because the epoll path only
// maps EPOLLHUP and discovers half-close via recv()==0.
test("fetch() drains a chunked body when the server FINs in the same tick (kqueue EV_EOF)", async () => {
await using proc = Bun.spawn({
cmd: [bunExe(), join(import.meta.dir, "fetch-chunked-fin-same-tick-fixture.ts")],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ stdout: stdout.trim(), stderr: stderr.trim(), exitCode }).toEqual({
stdout: "OK 200",
stderr: "",
exitCode: 0,
});
});
Loading