Repository navigation
Add TCP echo server example using std.Io interface - #163
Conversation
This example demonstrates how to use the std.Io abstraction layer with zio's async runtime, including: - Using std.Io instead of direct zio.Runtime - Using std.Io.Group for concurrent client handlers - Using std.Io.net.IpAddress for network operations
WalkthroughUpdates Zig toolchain to master branch in CI, adds a TCP echo server example, updates coroutine dependency to a ref-based version, implements filesystem stat operations across file and directory APIs, refactors signal handling to use enum conversions, and reworks type-building logic in select operations. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ 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 |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/stdio.zig (1)
315-319: Limitation: only follow_symlinks=true is supported.Returning
error.Unexpectedwhen follow_symlinks is false is reasonable for now. The comment explains this is not yet implemented. If this becomes a common use case, consider returning a more specific error or adding support for lstat-style behavior.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
.github/workflows/test.yml(1 hunks)build.zig(1 hunks)build.zig.zon(1 hunks)examples/tcp_echo_server_stdio.zig(1 hunks)src/fs/dir.zig(2 hunks)src/fs/file.zig(1 hunks)src/runtime.zig(1 hunks)src/select.zig(2 hunks)src/signal.zig(10 hunks)src/stdio.zig(3 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
Use
zig envto get the path to the Zig standard library when needed
Files:
examples/tcp_echo_server_stdio.zigsrc/runtime.zigsrc/stdio.zigsrc/fs/dir.zigsrc/select.zigsrc/fs/file.zigbuild.zigsrc/signal.zig
build.zig.zon
📄 CodeRabbit inference engine (CLAUDE.md)
Update version in build.zig.zon as part of release process
Files:
build.zig.zon
build.zig
📄 CodeRabbit inference engine (CLAUDE.md)
To test Windows builds on Linux, use
zig build build-tests -Dtarget=x86_64-windows && wine zig-out/bin/test.exe
Files:
build.zig
🧠 Learnings (6)
📚 Learning: 2025-11-30T10:31:31.222Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:31.222Z
Learning: Applies to build.zig.zon : Update version in build.zig.zon as part of release process
Applied to files:
.github/workflows/test.ymlbuild.zig.zonbuild.zig
📚 Learning: 2025-11-30T10:31:31.222Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:31.222Z
Learning: Applies to build.zig : To test Windows builds on Linux, use `zig build build-tests -Dtarget=x86_64-windows && wine zig-out/bin/test.exe`
Applied to files:
.github/workflows/test.ymlsrc/runtime.zigbuild.zig
📚 Learning: 2025-11-30T10:31:31.222Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:31.222Z
Learning: Applies to **/*.zig : Use `zig env` to get the path to the Zig standard library when needed
Applied to files:
.github/workflows/test.ymlsrc/fs/dir.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/runtime.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/fs/dir.zig
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
Applied to files:
src/select.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: test (windows-latest)
🔇 Additional comments (21)
build.zig (2)
56-56: New example registered correctly.The tcp-echo-server-stdio example is properly added to the build configuration. Matches the new example file that demonstrates std.Io integration with zio.
59-59: TLS demo temporarily disabled.The tls-demo example is commented out. Since the source file likely still exists, this is a soft removal from the build rather than deletion. If this is intentional and temporary (e.g., waiting for dependency updates or fixes), that's fine. If it's permanent, consider removing the source file as well to avoid confusion.
.github/workflows/test.yml (1)
27-27: CI now tracks Zig master branch.Switching from a fixed version (0.15.2) to master means your CI will pick up the latest Zig changes automatically. This is good for catching compatibility issues early but can also introduce unexpected build failures when Zig master breaks something. Since you're already using ref=zig-0.16 for the coro dependency and implementing std.Io support (which requires Zig 0.16+), this change makes sense.
build.zig.zon (1)
18-19: Coro dependency updated to track zig-0.16 branch.The change from a fixed commit to
ref=zig-0.16means the dependency will track updates on that branch. This aligns well with your CI using Zig master and the std.Io features requiring Zig 0.16+. The new hash looks correct for the updated reference.examples/tcp_echo_server_stdio.zig (2)
7-40: Clean echo server handler implementation.The handleClient function demonstrates proper std.Io usage:
- Deferred close ensures cleanup
- Line-delimited reading using takeDelimiterInclusive
- Explicit error handling for read/write/flush operations
- Logging for connection lifecycle
The 1024-byte buffers are fine for an example. In production, you might want configurable buffer sizes, but this is clear and educational.
42-70: Main function sets up the server correctly, but Ctrl+C handling is missing.The server initialization and lifecycle management are well-structured with proper defer/errdefer usage. The std.Io.Group pattern for concurrent clients is exactly what you'd want to demonstrate here.
However, line 58 says "Press Ctrl+C to stop the server" but there's no signal handling implemented. The server will exit on Ctrl+C via the default signal handler, but it won't gracefully cancel the group or close connections. For an example, this is probably fine, but consider adding a comment that production code should use zio's Signal API to handle SIGINT gracefully.
src/signal.zig (4)
20-28: Signal constants now use explicit enum-to-int conversion.Converting from
std.posix.SIG.INTto@intFromEnum(std.posix.SIG.INT)makes the conversion explicit. Since SignalKind is defined asenum(u8), this ensures the underlying u8 values are correctly derived from the posix signal constants. The pattern is consistent across all signal types.
67-67: sigaction calls now use proper enum conversions.The
@enumFromInt(@intFromEnum(kind))pattern converts SignalKind (u8 enum) back to std.posix.SIG enum for the sigaction API. While verbose, it's type-safe and makes the conversion explicit. This is the correct way to bridge between your custom SignalKind enum and the standard library's signal types.Also applies to: 73-73, 105-105
180-184: Signal handler signature updated for type safety.Changing the parameter from
signum: c_inttosignum: std.posix.SIGaligns with the type system better. The additionalsignum_intcast on line 181 is needed because the comparison on line 184 uses the integer representation stored in the registry. This is correct.
407-407: Test signal raising updated for consistency.All test cases now use
@enumFromInt(@intFromEnum(SignalKind.*))to convert to the std.posix.SIG enum thatstd.posix.raiseexpects. This matches the pattern used elsewhere in the file and maintains type safety.Also applies to: 453-453, 523-523, 570-570, 597-597, 658-658
src/fs/file.zig (1)
136-150: File stat operation implemented correctly.The StatError type union and stat() method follow the established patterns in this file. Using
nullas the path argument to FileStat means it stats the file descriptor itself (fstat semantics), which is correct for File.stat(). The error handling and async pattern match the other IO operations (read, write, etc.).src/fs/dir.zig (3)
5-5: Cancelable import added for StatError.Required for the StatError type union defined below. Consistent with file.zig.
75-89: Dir.stat() implemented correctly.Stats the directory file descriptor itself (null path = fstat semantics). Follows the established async IO pattern and error handling used throughout the file. The StatError type matches file.zig for consistency.
91-103: Dir.statPath() implemented correctly.Stats a file within the directory using fstatat semantics (fd + relative path). Implementation follows the same pattern as stat() and other IO operations in this file. Good addition for querying file metadata without opening the file.
src/runtime.zig (1)
1145-1146: Test skipped on non-Linux platforms pending aio backend support.The Linux-only guard on this test is appropriate. The spawnBlocking implementation itself is platform-agnostic—it just wraps aio.Work and delegates to the thread pool. The restriction likely stems from aio's backend initialization or the test setup, not fundamental issues with the underlying thread pool. The build.zig shows aio supports kqueue (macOS), iocp (Windows), and other backends, so cross-platform support is achievable once the test environment properly initializes the appropriate backend for each platform.
src/stdio.zig (4)
300-312: Implementation looks good.The error mapping covers the necessary cases, and the conversion to std.Io.File.Stat is handled cleanly. The catch-all for unmapped errors is reasonable given the interface contract.
449-473: Conversion mapping is thorough.The kind enum mapping covers all file types including platform-specific ones (whiteout, door, event_port), and the timestamp conversion properly wraps nanoseconds. Clean implementation.
475-487: LGTM.Follows the same pattern as dirStatImpl with appropriate error mapping. The use of File.fromFd and subsequent stat call is straightforward.
1631-1714: Test coverage is solid.The tests verify stat functionality for files and directories, check expected sizes match actual data written, validate file kinds, and ensure timestamps are reasonable. Good coverage of the new functionality.
src/select.zig (2)
180-191: LGTM - consistent migration to @union builtin.The array-based construction mirrors the approach in
WaitContextsType. The logic correctly maps each struct field to a union field with its correspondingFuture.Resulttype. The use ofstd.meta.FieldEnum(S)for the tag type is appropriate.
125-154: Both @struct and @union use consistent parameter patterns; SelectResult test validates the pattern.The refactoring to pre-count non-void WaitContext fields and build array-based metadata is clean. The zero-field optimization at lines 133–136 efficiently handles the edge case.
Both WaitContextsType and SelectResult follow the same pattern:
.autolayout, null/enum tag, then field metadata arrays. SelectResult has a test validating the @union construction, and WaitContextsType is actively used in the publicselect()function at line 294, suggesting the @struct pattern is functional. Without access to Zig 0.16 documentation, I cannot definitively confirm the exact API signatures are correct, but the consistent usage pattern and successful integration indicate the implementation is sound.
Summary
tcp_echo_server_stdio.zigdemonstrating the use ofstd.Iointerface with ziostd.Io.Groupfor managing concurrent client connectionsChanges
examples/tcp_echo_server_stdio.zig- new example using std.Iobuild.zigto include the new example in the buildTest plan
zig build examples