Repository navigation
Add async network functions for DNS resolution and TCP connection - #18
Conversation
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.
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
🔇 Additional comments (2)
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 |
…x.ConnectError.ConnectionRefused
- 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
| var blocking_task = try runtime.spawnBlocking( | ||
| std.net.getAddressList, | ||
| .{ allocator, name, port }, | ||
| ); | ||
| defer blocking_task.deinit(); | ||
|
|
||
| return try blocking_task.join(); | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🧩 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:
std.net.getAddressListreturns!*AddressList— a pointer to heap-allocated memory using the provided allocatorBlockingTask.join()returns this pointer value (typeT)BlockingTask.deinit()callsreleaseAwaitable(), which eventually frees theTaskDatawrapper (via thedestroycallback when ref count reaches zero)- However, the result itself (the
AddressListpointer) remains valid and is owned by the caller, who must calllist.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.
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
Summary
Implements async equivalents of
std.netfunctions to enable non-blocking DNS resolution and TCP connections in zio.Changes
src/net.zigwith three async functions:getAddressList()- Async DNS resolution using the runtime's thread pooltcpConnectToHost()- DNS lookup followed by TCP connectiontcpConnectToAddress()- Convenience wrapper aroundTcpStream.connect()pub const net = @import("net.zig");tosrc/zio.zigexamples/tcp_client.zigto use hostname resolution instead of hardcoded IPtcpConnectToHost()and buffered reader/writer interfaceImplementation Details
spawnBlocking()to run DNS lookups in the thread pool, avoiding event loop blockingjoin()to yield the coroutineTesting
All 41 tests pass including the 4 new network function tests.
Summary by CodeRabbit
New Features
Bug Fixes
Tests