Skip to content

Add TCP echo server example using std.Io interface - #163

Merged
lalinsky merged 1 commit into
zig-0.16from
std-io-example
Dec 16, 2025
Merged

lalinsky merged 1 commit into
zig-0.16from
std-io-example

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Adds a new example tcp_echo_server_stdio.zig demonstrating the use of std.Io interface with zio
  • Shows how to use std.Io.Group for managing concurrent client connections
  • Demonstrates the integration between Zig's standard I/O abstraction and zio's async runtime

Changes

  • Added examples/tcp_echo_server_stdio.zig - new example using std.Io
  • Updated build.zig to include the new example in the build

Test plan

  • Built the example successfully with zig build examples
  • Tested with single client - messages echoed correctly
  • Tested with concurrent clients - both clients handled simultaneously

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

coderabbitai Bot commented Dec 16, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Updates 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

Cohort / File(s) Summary
Dependency & Build Configuration
.github/workflows/test.yml, build.zig.zon, build.zig
Updated Zig toolchain from 0.15.2 to master branch. Added tcp-echo-server-stdio to examples list; commented out tls-demo. Updated coro.zig dependency from fixed commit to ref-based URL with new content hash.
File System Stat Operations
src/fs/file.zig, src/fs/dir.zig, src/stdio.zig, examples/tcp_echo_server_stdio.zig
Added StatError type alias and async stat() method to File. Added StatError type alias, stat(), and statPath() methods to Dir. Implemented dirStatImpl, dirStatPathImpl, fileStatImpl with error mapping and conversion via aioFileStatToStdIo() helper. Added TCP echo server example using ZIO runtime with concurrent client handling.
Runtime & Signal Handling
src/runtime.zig, src/signal.zig
Removed thread pool smoke test; added Linux-only platform guard to spawnBlocking test. Replaced direct integer signal constants with enum conversion helpers (@intFromEnum); updated signal handler signature to use std.posix.SIG enum; adjusted sigaction calls and internal dispatch logic to work with converted representations.
Type System Refactoring
src/select.zig
Reworked WaitContextsType to compute field metadata dynamically via separate arrays instead of in-place accumulation; builds struct via @Struct() with field names, types, and attributes. Reworked SelectResult to build union metadata dynamically using separate arrays populated in a loop, returning union via @Union().

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • src/select.zig: Type metaprogramming logic shift from static accumulation to dynamic array-based struct/union building—verify correctness of field ordering and attribute handling.
  • src/signal.zig: Enum conversion chain (@intFromEnum → @enumFromInt → comparisons)—confirm all signal dispatch paths correctly handle the new representation.
  • src/fs/file.zig & src/fs/dir.zig: Async stat method implementations follow established I/O patterns, but verify error propagation and resource cleanup under cancellation.
  • src/stdio.zig: New stat conversion logic and error mapping breadth—check coverage of filesystem error cases and aioFileStatToStdIo field translation.

Possibly related PRs

Poem

Signal handlers dancing with enums so bright,
File stats emerging from the async night,
Select unions built with metadata arrays,
Echo servers spawning their concurrent pathways,
Type systems reformed, old patterns take flight! 🚀

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly describes the main addition: a TCP echo server example demonstrating std.Io interface usage, which aligns with the primary change of adding examples/tcp_echo_server_stdio.zig.
Description check ✅ Passed The description accurately covers the PR's main contributions: the new TCP echo server example, its use of std.Io and std.Io.Group, build.zig updates, and testing performed.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch std-io-example

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

🧹 Nitpick comments (1)
src/stdio.zig (1)

315-319: Limitation: only follow_symlinks=true is supported.

Returning error.Unexpected when 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2b9e15a and 88dfb81.

📒 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 env to get the path to the Zig standard library when needed

Files:

  • examples/tcp_echo_server_stdio.zig
  • src/runtime.zig
  • src/stdio.zig
  • src/fs/dir.zig
  • src/select.zig
  • src/fs/file.zig
  • build.zig
  • src/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.yml
  • build.zig.zon
  • build.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.yml
  • src/runtime.zig
  • build.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.yml
  • src/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.16 means 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.INT to @intFromEnum(std.posix.SIG.INT) makes the conversion explicit. Since SignalKind is defined as enum(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_int to signum: std.posix.SIG aligns with the type system better. The additional signum_int cast 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 that std.posix.raise expects. 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 null as 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 corresponding Future.Result type. The use of std.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: .auto layout, null/enum tag, then field metadata arrays. SelectResult has a test validating the @union construction, and WaitContextsType is actively used in the public select() 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.

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