Repository navigation
Add blocking I/O support for socket and pipe operations - #308
Conversation
📝 WalkthroughWalkthroughAdds blocking support for pipes and sockets in non-async contexts by implementing per-operation Net* handlers, POSIX poll-based readiness loops, and Windows-specific blocking paths; includes a new blocking socket smoke test. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Implements support for socket read/write operations in blocking mode (when no async runtime is available). Implementation follows the same approach as blocking pipe operations: - POSIX: Polls for readiness (POLLIN/POLLOUT) with infinite timeout, then performs the I/O operation using recv/send/recvfrom/sendto/recvmsg/sendmsg - Windows: Directly performs I/O which blocks automatically This enables socket I/O without requiring the async runtime, while safely handling non-blocking sockets by polling first. Operations implemented: - recv/send for stream sockets - recvfrom/sendto for datagram sockets - recvmsg/sendmsg for advanced message operations - close and shutdown for connection management Co-authored-by: Lukáš Lalinský <[email protected]>
These operations are naturally blocking (just call net.socket() and net.bind()) so they fit perfectly into the blocking execution model. Co-authored-by: Lukáš Lalinský <[email protected]>
Refactors blocking.zig by extracting the repeated poll-then-operate pattern into a single pollForReady() helper function. This eliminates ~60 lines of duplicated code across pipe and socket handlers. All 355 unit tests pass successfully. Co-authored-by: Lukáš Lalinský <[email protected]>
Co-authored-by: Lukáš Lalinský <[email protected]>
The Windows check needs to be at call sites, not inside pollForReady, because the function body references net.pollfd which doesn't compile on Windows. Co-authored-by: Lukáš Lalinský <[email protected]>
…eout support All socket recv/send operations now use polling on both POSIX and Windows: - pollForReady now works on all platforms (uses WSAPoll on Windows) - handleNetRecv, handleNetRecvFrom, handleNetRecvMsg poll before receiving - handleNetSend, handleNetSendTo, handleNetSendMsg poll before sending This change enables future timeout support by allowing poll timeout parameter to be configurable instead of using infinite timeout (-1). Co-authored-by: Lukáš Lalinský <[email protected]>
Implements blocking execution for socket connection operations: - listen: Direct synchronous call (no polling needed) - connect: Poll for write readiness + SO_ERROR checking - accept: Poll for incoming connections Follows the same pattern as existing recv/send operations. All 355 unit tests pass. Co-authored-by: Lukáš Lalinský <[email protected]>
Tests listen, accept, connect, send, and recv using two threads (server and client) with ResetEvent synchronization.
On Windows, blocking sockets and pipes naturally block, so polling is unnecessary overhead. This commit removes polling on Windows for all blocking I/O operations (recv, send, accept, read, write, etc). On POSIX, adds retry loop to handle the race condition where multiple threads access the same file descriptor. The poll+I/O pattern has a TOCTOU race: if thread A polls (ready) but thread B completes the I/O first, thread A gets WouldBlock. The retry loop handles this correctly. All functions now follow a consistent pattern: handle Windows first (simple blocking I/O), then POSIX (poll+I/O retry loop).
1bfdafa to
837ce29
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/ev/test/blocking_sockets.zig`:
- Around line 148-154: The server can block forever on accept if the client
fails; to fix, join the client_thread before server_thread, then check
state.client_err and if non-null signal the server to stop waiting (e.g., close
the listening socket from the main thread or set a recv timeout on the listener
socket using SO_RCVTIMEO) so server_thread.accept() unblocks; adjust the
shutdown logic around server_thread, client_thread, state.client_err, and the
listener socket to ensure the test fails fast instead of hanging.
🧹 Nitpick comments (2)
src/ev/blocking.zig (2)
361-425:unreachableafternet.recvmsg/net.sendmsgsuccess on Windows is fragile.If
net.recvmsg/net.sendmsgcurrently always panic or error on Windows, theunreachableon lines 371 and 404 works today. But if someone later adds Windows support for these calls (e.g., viaWSARecvMsg), this becomes undefined behavior in release builds with no compile-time safety net.Consider replacing the Windows branch with a
@compileErrorif Windows is truly never expected to support these, or handle the success case normally:Option A: compile-time guard
fn handleNetRecvMsg(c: *Completion) void { const data = c.cast(NetRecvMsg); - // Windows: not supported (recvmsg is POSIX-only, will panic in net.recvmsg) - if (builtin.os.tag == .windows) { - _ = net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control) catch |err| { - c.setError(err); - return; - }; - unreachable; - } + if (builtin.os.tag == .windows) { + `@compileError`("recvmsg is not supported on Windows"); + }Option B: handle success defensively
- if (builtin.os.tag == .windows) { - _ = net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control) catch |err| { - c.setError(err); - return; - }; - unreachable; - } + if (builtin.os.tag == .windows) { + if (net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control)) |result| { + c.setResult(.net_recvmsg, result); + } else |err| { + c.setError(err); + } + return; + }Same applies to
handleNetSendMsg.
225-291: Nine copies of the poll-then-retry loop.The POSIX poll+retry pattern (poll → syscall → retry on WouldBlock) is duplicated across
handlePipeRead,handlePipeWrite,handleNetRecv,handleNetSend,handleNetRecvFrom,handleNetSendTo,handleNetRecvMsg,handleNetSendMsg, andhandleNetAccept. Each differs only in poll direction, syscall call, result tag, and argument set.A comptime helper could collapse these — something like:
fn blockingPollLoop( comptime tag: Completion.Op, fd: net.fd_t, poll_events: i16, doOp: anytype, // fn returning error union ) void { ... }Not urgent — the current code is clear and each function is self-contained. But if you add more operations later, the boilerplate will keep growing.
| // Wait for both threads to complete | ||
| server_thread.join(); | ||
| client_thread.join(); | ||
|
|
||
| // Check for errors | ||
| try std.testing.expectEqual(null, state.server_err); | ||
| try std.testing.expectEqual(null, state.client_err); |
There was a problem hiding this comment.
If the client dies before connecting, the server blocks on accept forever — test hangs.
If client socket open or connect fails, the server thread is stuck in the blocking accept call with no timeout, and server_thread.join() on line 149 will never return. Unlikely on localhost, but if it ever happens in CI, you'll get a hung test with no useful error output.
One option: join client first, then if client_err is set, you know the server might be stuck. Or set a socket timeout on the server's listening socket. Not a must-fix for a smoke test, just something to keep in mind.
🤖 Prompt for AI Agents
In `@src/ev/test/blocking_sockets.zig` around lines 148 - 154, The server can
block forever on accept if the client fails; to fix, join the client_thread
before server_thread, then check state.client_err and if non-null signal the
server to stop waiting (e.g., close the listening socket from the main thread or
set a recv timeout on the listener socket using SO_RCVTIMEO) so
server_thread.accept() unblocks; adjust the shutdown logic around server_thread,
client_thread, state.client_err, and the listener socket to ensure the test
fails fast instead of hanging.
There was a problem hiding this comment.
this is reasonable for the test, it would get very complex to handle it properly
There was a problem hiding this comment.
@lalinsky, fair enough — for a smoke test on localhost the odds are low enough that the extra complexity isn't worth it. If you ever see a hang in CI, you'll know where to look.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/ev/blocking.zig`:
- Around line 362-392: The Windows branch in handleNetRecvMsg (and likewise in
handleNetSendMsg) calls net.recvmsg/net.sendmsg then hits unreachable, which is
unsafe if those functions later gain non-panicking implementations; replace that
pattern with a clear compile-time or explicit runtime failure: use a comptime
guard (comptime if (builtin.os.tag == .windows) `@compileError`("recvmsg/sendmsg
not supported on Windows")) to fail builds on Windows, or if you must allow
runtime builds, replace the call+unreachable with an immediate `@panic`("recvmsg
not supported on Windows") (and do the analogous change in handleNetSendMsg) so
there is no path that falls through to unreachable.
🧹 Nitpick comments (1)
src/ev/blocking.zig (1)
140-206: Every poll+retry handler is copy-pasted with minor parameter differences.
handlePipeRead,handlePipeWrite,handleNetRecv,handleNetSend,handleNetRecvFrom,handleNetSendTo,handleNetRecvMsg,handleNetSendMsg— eight functions, same skeleton: Windows direct call, POSIXwhile(true) { pollForReady; try op; WouldBlock → continue; else → error }.It works, it's readable, but when you need to change the retry logic (e.g., add a timeout, add logging, handle EINTR), you'll be touching eight places. Something like a generic
blockingPollLoop(fd, poll_events, doOp)helper taking a function pointer or inline callback would cut the surface area down. Not urgent, but worth a TODO.Also applies to: 226-291
| fn handleNetRecvMsg(c: *Completion) void { | ||
| const data = c.cast(NetRecvMsg); | ||
|
|
||
| // Windows: not supported (recvmsg is POSIX-only, will panic in net.recvmsg) | ||
| if (builtin.os.tag == .windows) { | ||
| _ = net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control) catch |err| { | ||
| c.setError(err); | ||
| return; | ||
| }; | ||
| unreachable; | ||
| } | ||
|
|
||
| // POSIX: poll+recvmsg loop to handle race if multiple threads access same socket | ||
| while (true) { | ||
| pollForReady(data.handle, net.POLL.IN) catch |err| { | ||
| c.setError(err); | ||
| return; | ||
| }; | ||
|
|
||
| if (net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control)) |result| { | ||
| c.setResult(.net_recvmsg, result); | ||
| return; | ||
| } else |err| switch (err) { | ||
| error.WouldBlock => continue, // Another thread consumed data, retry | ||
| else => { | ||
| c.setError(err); | ||
| return; | ||
| }, | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
unreachable after a potentially-succeeding call on Windows is risky.
If net.recvmsg / net.sendmsg ever stops panicking on Windows (e.g., someone adds a WSA-based implementation), the success path silently falls through to unreachable, which is undefined behavior in ReleaseFast/ReleaseSmall. A compile-time guard is safer:
Proposed fix
// Windows: not supported (recvmsg is POSIX-only, will panic in net.recvmsg)
if (builtin.os.tag == .windows) {
- _ = net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control) catch |err| {
- c.setError(err);
- return;
- };
- unreachable;
+ `@compileError`("recvmsg is not supported on Windows");
}Same for handleNetSendMsg.
If for some reason you need the Windows branch to compile but fail at runtime, at minimum use @panic("recvmsg not supported on Windows") instead of relying on the downstream panic + unreachable combo.
Also applies to: 394-425
🤖 Prompt for AI Agents
In `@src/ev/blocking.zig` around lines 362 - 392, The Windows branch in
handleNetRecvMsg (and likewise in handleNetSendMsg) calls
net.recvmsg/net.sendmsg then hits unreachable, which is unsafe if those
functions later gain non-panicking implementations; replace that pattern with a
clear compile-time or explicit runtime failure: use a comptime guard (comptime
if (builtin.os.tag == .windows) `@compileError`("recvmsg/sendmsg not supported on
Windows")) to fail builds on Windows, or if you must allow runtime builds,
replace the call+unreachable with an immediate `@panic`("recvmsg not supported on
Windows") (and do the analogous change in handleNetSendMsg) so there is no path
that falls through to unreachable.
Windows doesn't have native recvmsg/sendmsg support. This implements emulation in the net layer that falls back to recvfrom/recv and sendto/send when control messages (ancillary data) are not used. Control messages are POSIX-specific and return OperationNotSupported on Windows when requested. This removes the unreachable statements from blocking handlers and enables full socket operation support in blocking mode on Windows.
Summary
Extends blocking mode to support socket and pipe I/O operations, enabling ZIO to work in synchronous contexts without an event loop.
Changes
pollForReady()helper for waiting on fd readinessImplementation Details
On POSIX systems, uses a poll+I/O retry loop to handle races where multiple threads access the same fd:
On Windows, blocking I/O works correctly without polling, so operations are direct system calls.
Closes #288