Repository navigation
Refactor networking to use unified Socket type - #72
Conversation
Introduce a Socket type to unify handle and address management across Server and Stream types. This provides a foundation for adding UDP datagram socket support. Changes: - Add Socket struct with handle, address, shutdown(), and close() - Refactor Server and Stream to contain a socket field - Update all access to handle/address to go through socket field - Update tests and examples to use server.socket.address pattern - Export Socket from zio.net module This is a breaking change for code that directly accesses .address or .handle fields on Server/Stream. Code should now use .socket.address and .socket.handle instead.
Refactors Socket into a full low-level socket primitive with methods for common socket operations: - bind(): Bind socket to an address - listen(): Mark socket as listening and update address via getsockname - connect(): Connect socket to remote address - setOption(): Set socket options (e.g., SO_REUSEADDR) Refactored netListenIp and netListenUnix to use these new Socket methods, eliminating duplicate code and making the implementation cleaner. The listen() method now automatically calls getsockname to update the socket's address, which is important for ephemeral ports.
Adds basic send/receive methods to Socket for sending and receiving data on connected sockets. These methods are simple wrappers around netRead/netWrite, similar to how Stream.read/write work. - receive(): Receive data into a buffer - send(): Send data from a buffer Both methods may transfer fewer bytes than requested and return the actual number of bytes transferred.
Adds datagram socket support to Socket with platform-specific backends: - ReceiveFromResult struct to return sender address and byte count - Address.fromStd() helper to convert from std.net.Address - Socket.receiveFrom(): Receive datagrams with sender address - Uses recvfrom for iocp/kqueue backends - Uses recvmsg for io_uring/epoll backends - Socket.sendTo(): Send datagrams to specific address - Uses sendto for iocp/kqueue backends - Uses sendmsg for io_uring/epoll backends Implementation ported from src/udp.zig but adapted to use the unified Address type instead of std.net.Address. Socket now supports both stream-oriented (TCP) and datagram-oriented (UDP) operations.
- Add Socket.bind() method with getsockname to handle ephemeral ports - Move getsockname from Socket.listen() to Socket.bind() - Add IpAddress.bind() and UnixAddress.bind() convenience methods - Add netBindIp() and netBindUnix() helper functions - Add createDatagramSocket() helper for UDP socket creation - Fix Address.fromStorage() to handle variable-length Unix addresses - Add checkBind() test helper following checkListen() pattern - Add UDP tests for IPv4, IPv6, and Unix domain sockets - Remove deprecated UdpSocket and UdpRecvResult from public API - Delete src/udp.zig - all functionality now available via Socket API All 123 tests passing.
|
Warning Rate limit exceeded@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 14 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (4)
WalkthroughIntroduces a unified Socket abstraction in Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Stream
participant Socket
participant Handle
User->>Socket: bind(rt, addr)
Socket->>Handle: bind syscall
Handle-->>Socket: success
Socket-->>User: bound Socket
User->>Socket: receiveFrom(rt, buf)
Socket->>Handle: recvfrom/recvmsg
Handle-->>Socket: data + sender addr
Socket-->>User: ReceiveFromResult{from, len}
User->>Socket: sendTo(rt, addr, data)
Socket->>Handle: sendto/sendmsg
Handle-->>Socket: bytes sent
Socket-->>User: usize
rect rgb(240,250,240)
note over Stream,Socket: Stream delegates I/O through Socket.handle
User->>Stream: read(rt, buf)
Stream->>Socket: use .handle -> read
Socket->>Handle: read syscall
Handle-->>Socket: bytes
Socket-->>Stream: usize
Stream-->>User: usize
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
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 |
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/io/net.zig (1)
7-7: Fix Windows handle type and invalid casts in Socket methodsOn .iocp you define Handle as std.os.windows.HANDLE, then cast it to ws2_32.SOCKET with @ptrCast; HANDLE and SOCKET are unrelated (pointer vs integer) and @ptrCast on a value is invalid. This will break on Windows and risks UB. Use the actual socket type as the Handle on Windows and drop the casts.
-const Handle = if (xev.backend == .iocp) std.os.windows.HANDLE else std.posix.socket_t; +const Handle = if (xev.backend == .iocp) std.os.windows.ws2_32.SOCKET else std.posix.socket_t; @@ - pub fn setOption(self: Socket, level: i32, optname: u32, value: anytype) !void { - const sock = if (xev.backend == .iocp) - @as(std.os.windows.ws2_32.SOCKET, @ptrCast(self.handle)) - else - self.handle; + pub fn setOption(self: Socket, level: i32, optname: u32, value: anytype) !void { + const sock: Handle = self.handle; const bytes = std.mem.asBytes(&value); try std.posix.setsockopt(sock, level, optname, bytes); } @@ - pub fn bind(self: *Socket, rt: *Runtime, addr: Address) !void { - _ = rt; - const sock = if (xev.backend == .iocp) - @as(std.os.windows.ws2_32.SOCKET, @ptrCast(self.handle)) - else - self.handle; + pub fn bind(self: *Socket, rt: *Runtime, addr: Address) !void { + _ = rt; + const sock: Handle = self.handle; const addr_len = switch (addr.any.family) { std.posix.AF.INET => addr.ip.in.getOsSockLen(), std.posix.AF.INET6 => addr.ip.in6.getOsSockLen(), std.posix.AF.UNIX => @sizeOf(std.posix.sockaddr.un), else => unreachable, }; try std.posix.bind(sock, &addr.any, addr_len); var actual_len: std.posix.socklen_t = @sizeOf(Address); try std.posix.getsockname(sock, &self.address.any, &actual_len); } @@ - pub fn listen(self: *Socket, rt: *Runtime, backlog: u31) !void { - _ = rt; - const sock = if (xev.backend == .iocp) - @as(std.os.windows.ws2_32.SOCKET, @ptrCast(self.handle)) - else - self.handle; - try std.posix.listen(sock, backlog); - } + pub fn listen(self: *Socket, rt: *Runtime, backlog: u31) !void { + _ = rt; + const sock: Handle = self.handle; + try std.posix.listen(sock, backlog); + }If xev expects a specific type for its .fd/.socket fields, keep Handle in sync with that as well.
Also applies to: 224-233, 235-267
🧹 Nitpick comments (6)
src/io/test/net.zig (2)
113-159: Nice UDP-style bind/sendTo/receiveFrom coverage; avoid flakinesscheckBind exercises both directions well. One concern: passing Socket by value is fine (no double-close), but the client readiness relies on sleep (see below). Prefer an explicit readiness signal (Channel or a one-shot) from serverFn before clientFn sends, to avoid timing races on slower VMs.
139-147: Replace rt.sleep(10) with a readiness handshakeSleeping for 10 units is brittle and can race. Suggest a simple Channel(bool) handshake:
- pub fn clientFn(rt: *Runtime, server_socket: Socket, client_addr_inner: @TypeOf(client_addr)) !void { - try rt.sleep(10); + pub fn clientFn(rt: *Runtime, server_socket: Socket, client_addr_inner: @TypeOf(client_addr), ready: *Channel(u8)) !void { + // wait until server is ready to recv + _ = try ready.receive(rt); const client_socket = try client_addr_inner.bind(rt); defer client_socket.close(rt); const test_data = "hello"; const bytes_sent = try client_socket.sendTo(rt, server_socket.address, test_data); try std.testing.expectEqual(test_data.len, bytes_sent); var buf: [1024]u8 = undefined; const result = try client_socket.receiveFrom(rt, &buf); try std.testing.expectEqualStrings(test_data, buf[0..result.len]); }And in mainFn/serverFn, create Channel(u8), send a byte just before the recv starts, and pass it to clientFn. This removes timing sensitivity.
src/io/net.zig (4)
143-151: Make Address.toStd more explicitMinor readability: pass &self.any instead of casting the union pointer.
- pub fn toStd(self: *const Address) std.net.Address { - return switch (self.any.family) { - std.posix.AF.INET, std.posix.AF.INET6 => std.net.Address.initPosix(@ptrCast(self)), + pub fn toStd(self: *const Address) std.net.Address { + return switch (self.any.family) { + std.posix.AF.INET, std.posix.AF.INET6 => std.net.Address.initPosix(@ptrCast(&self.any)), std.posix.AF.UNIX => if (std.net.has_unix_sockets) std.net.Address{ .un = self.unix.un } else unreachable, else => unreachable, }; }
215-219: ReceiveFromResult shape is goodfrom plus len is sufficient; consider documenting that len is the number of bytes copied into the caller-provided buffer.
276-286: Clarify receive() semantics on datagram socketsDocstring says “0 indicates the socket has been shut down,” which is true for streams but UDP can legitimately receive 0‑length datagrams. Consider clarifying it as “connected stream” vs “connected datagram”.
296-314: recvfrom path: length handlingYou’re ignoring the returned address length here. It’s probably fine for std.net.Address.initPosix, but capturing the actual length (if xev exposes it) would be more robust, mirroring the recvmsg path.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
examples/tcp_echo_server.zig(2 hunks)src/io/net.zig(13 hunks)src/io/test/net.zig(4 hunks)src/net.zig(3 hunks)src/udp.zig(0 hunks)src/zio.zig(0 hunks)
💤 Files with no reviewable changes (2)
- src/zio.zig
- src/udp.zig
🔇 Additional comments (9)
examples/tcp_echo_server.zig (1)
11-11: LGTM: address access via SocketSwitching logs to stream.socket.address and server.socket.address is correct with the new API; Address.format handles {f}.
Also applies to: 40-40
src/net.zig (2)
10-10: Public re‑export looks goodpub const Socket = io_net.Socket cleanly exposes the unified type to users/tests.
125-125: Correct source of the ephemeral portReading the port from server.socket.address after bind/listen matches the refactor (getsockname now in bind). Good adjustment in tests.
Also applies to: 178-181
src/io/test/net.zig (4)
6-6: Importing Socket is consistent with the new APIThe added import aligns tests with the unified type.
93-95: Client connect via server.socket.address is correctUsing server.socket.address.connect(rt) reflects the new Server wrapping.
189-195: IPv6 bind test skip logic is goodGracefully skipping on error.AddressNotAvailable keeps the suite portable.
197-209: Unix datagram test is tidyPaths are cleaned up; using separate server/client sockets is correct for DGRAM.
src/io/net.zig (2)
596-609: Reuse-addr placement looks rightSetting SO_REUSEADDR before bind and moving getsockname into bind is correct and fixes ephemeral port reporting.
646-659: Datagram bind helpers are solidCreating DGRAM sockets and reusing Socket.bind to update the bound address is clean.
Also applies to: 660-675
The recvfrom operation was using posix.sockaddr (16 bytes) instead of posix.sockaddr.storage, causing buffer overflow when receiving IPv6 datagrams (which need 28 bytes for sockaddr_in6). Changed to use sockaddr.storage to match the sendto implementation.
The recvfrom operation was using posix.sockaddr (16 bytes) instead of posix.sockaddr.storage, causing buffer overflow when receiving IPv6 datagrams (which need 28 bytes for sockaddr_in6). Changed to use sockaddr.storage to match the sendto implementation. Added necessary pointer casts for Windows API compatibility.
Windows supports Unix domain sockets for TCP (stream) connections but not for UDP (datagram) connections. This change adds a platform check to skip the UDP Unix socket test on Windows to prevent AddressFamilyNotSupported errors.
The recvfrom operation in kqueue backend was using posix.sockaddr (16 bytes) instead of posix.sockaddr.storage, causing buffer overflow when receiving IPv6 datagrams (which need 28 bytes for sockaddr_in6). This is the same bug that was fixed for IOCP in the previous commit. Changed to use sockaddr.storage and added necessary pointer casts. Affected platforms: macOS, iOS, FreeBSD (all kqueue-based systems)
Add @ptrCast when accessing recvfrom.addr in UDP watcher to handle the sockaddr.storage type after fixing the buffer overflow bugs.
The Completion struct size increased from 256 to 280 bytes after changing recvfrom.addr from posix.sockaddr to posix.sockaddr.storage to properly handle all address families.
Use Address.fromStorage instead of std.net.Address.initPosix to properly handle all address families including AF.UNIX. The initPosix function only supports AF.INET and AF.INET6, causing unreachable code to be hit when receiving from Unix domain sockets.
Summary
This PR refactors the networking layer to use a unified
Sockettype for both TCP and UDP operations, replacing the separateUdpSocketimplementation with low-level socket methods.Key Changes
Socketnow serves as the core low-level networking primitive for both stream (TCP) and datagram (UDP) socketsbind(),listen(),connect(),setOption(),send(),receive(),sendTo(),receiveFrom()toSocketServerandStreamnow wrapSocketfor TCP operationsSocketAPI withbind(),sendTo(),receiveFrom()getsockname()fromlisten()tobind()where port assignment occurssrc/udp.zigand removedUdpSocket/UdpRecvResultfrom public APIBenefits
Test Coverage
checkBindmirrorscheckListen)Test plan
./check.sh- all tests passUdpSocketremoved and no longer exportedSummary by CodeRabbit
Breaking Changes
New Features
Refactor
Tests
Bug Fixes
Chores