Skip to content

Add async network functions for DNS resolution and TCP connection - #18

Merged
lalinsky merged 5 commits into
mainfrom
async-net-functions
Oct 3, 2025
Merged

lalinsky merged 5 commits into
mainfrom
async-net-functions

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 3, 2025 •

Copy link
Copy Markdown
Owner

Summary

Implements async equivalents of std.net functions to enable non-blocking DNS resolution and TCP connections in zio.

Changes

  • New file: src/net.zig with three async functions:
    • getAddressList() - Async DNS resolution using the runtime's thread pool
    • tcpConnectToHost() - DNS lookup followed by TCP connection
    • tcpConnectToAddress() - Convenience wrapper around TcpStream.connect()
  • Export: Added pub const net = @import("net.zig"); to src/zio.zig
  • Example update: Modified examples/tcp_client.zig to use hostname resolution instead of hardcoded IP
  • README update: Updated Quick Start example to demonstrate tcpConnectToHost() and buffered reader/writer interface
  • Tests: Added 4 comprehensive tests covering all new functionality

Implementation Details

  • Uses spawnBlocking() to run DNS lookups in the thread pool, avoiding event loop blocking
  • Returns standard library error sets (no duplication)
  • Properly waits on blocking tasks using join() to yield the coroutine

Testing

All 41 tests pass including the 4 new network function tests.

Summary by CodeRabbit

  • New Features

    • Hostname-based TCP connection helper with asynchronous DNS resolution using a thread pool.
    • Option to enable a thread pool in the runtime.
    • Exposed a public networking module for easier access to networking utilities.
    • Updated example client to use buffered I/O and an echo workflow.
  • Bug Fixes

    • More precise Windows connection error reporting (refused, reset, timed out, unreachable) instead of generic errors.
  • Tests

    • Added tests for DNS resolution and TCP connect/handshake flows.

Implements async equivalents of std.net functions:
- getAddressList: Async DNS resolution using thread pool
- tcpConnectToHost: DNS lookup followed by TCP connection
- tcpConnectToAddress: Wrapper around TcpStream.connect

Key features:
- Uses runtime's spawnBlocking for non-blocking DNS resolution
- Returns standard library error sets
- Comprehensive test coverage (4 new tests)
- Updated tcp_client example to use hostname resolution

All tests pass.
@coderabbitai

coderabbitai Bot commented Oct 3, 2025 •

Copy link
Copy Markdown
Contributor

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly and accurately describes the primary change of adding asynchronous network functionality for DNS resolution and TCP connection, matching the main content of the pull request and avoiding unnecessary detail. It clearly conveys the core update in a single sentence, making it easy for others to understand the purpose at a glance.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch async-net-functions

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5ae45db and 1eec5ab.

📒 Files selected for processing (2)
  • src/net.zig (1 hunks)
  • vendor/libxev/src/backend/iocp.zig (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/net.zig
🔇 Additional comments (2)
vendor/libxev/src/backend/iocp.zig (2)

547-561: LGTM! Clear error mapping for connection failures.

The new error mappings provide better granularity for TCP connection failures. The mapped Winsock error codes are correctly translated to descriptive ConnectError variants:

  • WSAECONNREFUSED → ConnectionRefused
  • WSAECONNRESET → ConnectionResetByPeer
  • WSAETIMEDOUT → ConnectionTimedOut
  • WSAEHOSTUNREACH/WSAENETUNREACH → NetworkUnreachable

This improves error handling for the async network functions introduced in this PR.


1436-1443: LGTM! ConnectError variants aligned with error mappings.

The new error variants properly cover common TCP connection failure scenarios and are consistent with the error mappings in the connect operation handler. The additions are well-suited for the async networking functionality in this PR.


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.

- Map WSAECONNREFUSED to ConnectionRefused instead of Unexpected
- Map WSAECONNRESET to ConnectionResetByPeer
- Map WSAETIMEDOUT to ConnectionTimedOut
- Map WSAEHOSTUNREACH/WSAENETUNREACH to NetworkUnreachable
- Update ConnectError type to include these specific errors

@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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10154a5 and 5ae45db.

📒 Files selected for processing (4)
  • README.md (1 hunks)
  • examples/tcp_client.zig (2 hunks)
  • src/net.zig (1 hunks)
  • src/zio.zig (1 hunks)

Comment thread src/net.zig
Comment on lines +18 to +25
var blocking_task = try runtime.spawnBlocking(
std.net.getAddressList,
.{ allocator, name, port },
);
defer blocking_task.deinit();

return try blocking_task.join();
}

@coderabbitai coderabbitai Bot Oct 3, 2025 •

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.

⚠️ Potential issue | 🔴 Critical

Fix dangling pointer returned from getAddressList.

Runtime.BlockingTask.join() hands back a pointer into the task’s own storage. Because we immediately defer blocking_task.deinit(), that storage is freed before the pointer is returned to the caller, so every dereference of list in the caller is using freed memory. Please copy or move the AddressList out of the blocking task before you deinit it (or return it by value) so the caller never observes a dangling pointer.

🤖 Prompt for AI Agents
In src/net.zig around lines 18–25 the code returns the AddressList pointer
produced by Runtime.BlockingTask.join() then immediately defers
blocking_task.deinit(), which frees the task’s storage and yields a dangling
pointer; fix by moving/copying the AddressList out of the task storage before
deinitializing the task — e.g., allocate a new AddressList (or the required
storage) using the provided allocator and deep-copy the contents from the joined
pointer into that allocation (or change the function to return the AddressList
by value), then deinit the blocking task and return the newly owned copy so
callers never see freed memory.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking_task.deinit() doesn't free the tasks result. The pointer is still valid, it's just the storage of the pointer itself is cleared after deinit.

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.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find the BlockingTask implementation to understand memory management
rg -nP -A10 "pub const BlockingTask" --type=zig

# Also search for the deinit implementation specifically
rg -nP -A15 "fn deinit.*BlockingTask" --type=zig

# And the join implementation
rg -nP -A15 "fn join.*BlockingTask" --type=zig

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Search for BlockingTask in runtime.zig specifically
rg -nP -C10 "BlockingTask" src/runtime.zig

# Also search for spawnBlocking to understand what it returns
rg -nP -C10 "spawnBlocking" src/runtime.zig

Length of output: 6483


🏁 Script executed:

#!/bin/bash
# Look for the deinit and join methods in BlockingTask
ast-grep --pattern $'pub fn BlockingTask($$$) type {
  $$$
  pub fn deinit($$$) $$$
  $$$
}'

# Also search more broadly for deinit in the BlockingTask context
rg -nP -B5 -A20 "pub fn deinit\(self: \*Self\) void" src/runtime.zig | head -80

# And search for join implementation
rg -nP -B5 -A20 "pub fn join\(self: \*Self\)" src/runtime.zig | head -80

Length of output: 1523


🏁 Script executed:

#!/bin/bash
# Get the full BlockingTask type definition with all its methods
rg -nP -A100 "^pub fn BlockingTask\(comptime T: type\) type \{" src/runtime.zig | head -150

Length of output: 3906


🏁 Script executed:

#!/bin/bash
# Check what std.net.getAddressList returns by looking at how it's used in tests
rg -nP -C5 "std\.net\.getAddressList" src/

# Also check the actual usage in the test to understand the return type
rg -nP -C10 "test.*getAddressList" src/net.zig

Length of output: 1920


🌐 Web query:

What is the return type and signature of std.net.getAddressList in Zig standard library?

💡 Result:

Signature: pub fn getAddressList(allocator: mem.Allocator, name: []const u8, port: u16) GetAddressListError!*AddressList. [1][2]

Sources:
[1] std.net (browseable source).
[2] srctree / std lib excerpt showing GetAddressListError and function.


@lalinsky Thank you for the clarification! You're absolutely right. I apologize for the confusion.

After reviewing the implementation, I can now see that:

  1. std.net.getAddressList returns !*AddressList — a pointer to heap-allocated memory using the provided allocator
  2. BlockingTask.join() returns this pointer value (type T)
  3. BlockingTask.deinit() calls releaseAwaitable(), which eventually frees the TaskData wrapper (via the destroy callback when ref count reaches zero)
  4. However, the result itself (the AddressList pointer) remains valid and is owned by the caller, who must call list.deinit() to free it

This is exactly the pattern shown in your tests (lines 68 and 91 in src/net.zig), where the returned list is properly cleaned up with defer list.deinit().

The memory management is correct as written. I apologize for the false alarm!

    (\_(\ 
    (•ㅅ•)  Thanks for setting me straight!
    /  づ💡

✏️ Learnings added
Learnt from: lalinsky
PR: lalinsky/zio#18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.826Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@lalinsky
lalinsky merged commit 73471bd into main Oct 3, 2025
@lalinsky
lalinsky deleted the async-net-functions branch October 3, 2025 11:10
This was referenced Oct 22, 2025
lalinsky added a commit that referenced this pull request Nov 18, 2025
4bb1a60 Fix stack unwinding on aarch64 and riscv64 (#18)
ae64534 Update CI to use Zig master
cf32ccd Update for Zig 0.16 compatibility
c2f6ee8 Add a test for capturing stack trace (#17)
3d4c6de Test using DebugAllocator in coroutine (#14)
6536658 Fix the test
b6eec4f Build tests in release mode
REVERT: eab0a7b Merge remote-tracking branch 'origin/main' into zig-0.16
REVERT: 7579996 Expose StackPoolConfig
REVERT: 7fa7b4f Update CI to use Zig master
REVERT: cbabd36 Update for Zig 0.16 compatibility

git-subtree-dir: src/lib/coro
git-subtree-split: 4bb1a60186952636e6d3e409d62d9e8cf50b1560
lalinsky added a commit that referenced this pull request Jan 6, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jan 21, 2026
6 tasks done
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