Skip to content

Refactor networking to use unified Socket type - #72

Merged
lalinsky merged 12 commits into
mainfrom
refactor-socket-type
Oct 24, 2025
Merged

lalinsky merged 12 commits into
mainfrom
refactor-socket-type

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 24, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR refactors the networking layer to use a unified Socket type for both TCP and UDP operations, replacing the separate UdpSocket implementation with low-level socket methods.

Key Changes

  • Unified Socket API: Socket now serves as the core low-level networking primitive for both stream (TCP) and datagram (UDP) sockets
  • Low-level socket methods: Added bind(), listen(), connect(), setOption(), send(), receive(), sendTo(), receiveFrom() to Socket
  • Higher-level wrappers: Server and Stream now wrap Socket for TCP operations
  • UDP support: Full UDP functionality through Socket API with bind(), sendTo(), receiveFrom()
  • Proper ephemeral port handling: Moved getsockname() from listen() to bind() where port assignment occurs
  • Removed deprecated code: Deleted src/udp.zig and removed UdpSocket/UdpRecvResult from public API

Benefits

  • Simpler API: One socket type instead of multiple
  • Better code reuse: Stream and datagram operations share common infrastructure
  • More flexible: Direct socket access allows fine-grained control
  • Smaller codebase: 308 lines deleted, 379 lines added (net reduction after removing old UDP)

Test Coverage

  • All existing TCP tests still pass
  • New UDP tests for IPv4, IPv6, and Unix domain sockets
  • Tests follow consistent pattern (checkBind mirrors checkListen)
  • All 123 tests passing

Test plan

  • Run ./check.sh - all tests pass
  • Verify TCP functionality with existing tests
  • Verify UDP functionality with new bind/sendTo/receiveFrom tests
  • Test IPv4, IPv6, and Unix domain sockets
  • Confirm old UdpSocket removed and no longer exported

Summary by CodeRabbit

  • Breaking Changes

    • Dedicated UDP module and its public types removed; use the unified socket API instead.
    • Two previously re-exported UDP types removed.
  • New Features

    • Unified Socket API: bind, listen, connect, send/receive, sendTo/receiveFrom, shutdown; IP and Unix bind support and std-lib address conversions.
    • Public Socket exported from the networking module.
  • Refactor

    • Server and Stream now delegate through the unified Socket.
  • Tests

    • Added bind/sendTo/receiveFrom tests for IPv4, IPv6, and Unix sockets.
  • Bug Fixes

    • Logging updated to reference socket-backed addresses.
  • Chores

    • Platform IO backend adjusted to use storage-based address buffers.

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.
@coderabbitai

coderabbitai Bot commented Oct 24, 2025 •

Copy link
Copy Markdown
Contributor

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 646c65c and 50abb99.

📒 Files selected for processing (4)
  • src/io/net.zig (13 hunks)
  • src/io/test/net.zig (4 hunks)
  • vendor/libxev/src/backend/kqueue.zig (3 hunks)
  • vendor/libxev/src/watcher/udp.zig (2 hunks)

Walkthrough

Introduces a unified Socket abstraction in src/io/net.zig, migrates Server/Stream to use Socket, adds datagram bind/receiveFrom/sendTo APIs, removes the standalone src/udp.zig module and its re-exports, updates tests and examples, and adjusts IOCP recvfrom storage handling.

Changes

Cohort / File(s) Summary
Core Socket API & Refactor
src/io/net.zig
Adds Socket (handle + address) and methods (setOption, bind, listen, connect, receive, send, receiveFrom, sendTo, shutdown, close), ReceiveFromResult, Address ⇄ std.net.Address conversions, IpAddress/UnixAddress. Reworks Server and Stream to use Socket, moves many net* functions to return/consume Socket.
UDP Module Removal
src/udp.zig
Removes entire UDP module: UdpSocket, UdpReadResult, datagram helpers (createDatagramSocket, address parsing), I/O helpers (recvfrom/recvmsg/sendto/sendmsg), and the UDP test.
Public API Surface
src/zio.zig, src/net.zig
src/zio.zig drops re-exports UdpSocket and UdpRecvResult. src/net.zig adds pub const Socket = io_net.Socket; and updates tests to reference server.socket.address....
Tests — net
src/io/test/net.zig
Imports Socket, adds pub fn checkBind(server_addr: anytype, client_addr: anytype) !void and bind-based UDP-like tests (IPv4/IPv6/Unix) that use Socket with receiveFrom/sendTo. Updates other tests to use server.socket.address.
Examples
examples/tcp_echo_server.zig
Updates logging to reference stream.socket.address and server.socket.address instead of prior address fields.
Backend IOCP Adjustment
vendor/libxev/src/backend/iocp.zig
Changes Operation.recvfrom to use posix.sockaddr.storage for addr and updates addr_size to storage size; adjusts pointer usage in WSARecvFrom invocation.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I hopped through sockets, light and quick,

Bound ports met packets, clever trick,
Streams now borrow one warm hole,
Datagrams dance and find their goal,
A carrot for each byte — hop, click! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "Refactor networking to use unified Socket type" directly and accurately reflects the primary change in the changeset. The core objective is to consolidate networking operations onto a single Socket primitive that handles both TCP (stream) and UDP (datagram) operations, replacing the previous separate UdpSocket implementation. This is evidenced by the extensive refactoring in src/io/net.zig introducing the new Socket public API, the deletion of src/udp.zig, and the reworking of Server and Stream to wrap Socket. The title is concise, specific, and clearly conveys the main architectural change without unnecessary verbosity or vague terminology.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

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.

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 methods

On .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 flakiness

checkBind 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 handshake

Sleeping 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 explicit

Minor 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 good

from 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 sockets

Docstring 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 handling

You’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

📥 Commits

Reviewing files that changed from the base of the PR and between 4654a0d and 885066e.

📒 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 Socket

Switching 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 good

pub const Socket = io_net.Socket cleanly exposes the unified type to users/tests.


125-125: Correct source of the ephemeral port

Reading 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 API

The added import aligns tests with the unified type.


93-95: Client connect via server.socket.address is correct

Using server.socket.address.connect(rt) reflects the new Server wrapping.


189-195: IPv6 bind test skip logic is good

Gracefully skipping on error.AddressNotAvailable keeps the suite portable.


197-209: Unix datagram test is tidy

Paths are cleaned up; using separate server/client sockets is correct for DGRAM.

src/io/net.zig (2)

596-609: Reuse-addr placement looks right

Setting SO_REUSEADDR before bind and moving getsockname into bind is correct and fixes ephemeral port reporting.


646-659: Datagram bind helpers are solid

Creating 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant