Skip to content

Refactor DNS resolution to use posix.getaddrinfo with IpAddressIterator - #112

Merged
lalinsky merged 4 commits into
mainfrom
refactor-getaddrinfo
Nov 1, 2025
Merged

lalinsky merged 4 commits into
mainfrom
refactor-getaddrinfo

Conversation

@lalinsky

@lalinsky lalinsky commented Nov 1, 2025

Copy link
Copy Markdown
Owner

Summary

Refactors DNS resolution to use posix.getaddrinfo directly with an iterator-based API, eliminating unnecessary allocations and improving the API ergonomics.

Changes

Core refactoring

  • IpAddressIterator: New iterator struct that wraps the addrinfo linked list

    • next() ?IpAddress for zero-allocation iteration
    • deinit() handles platform-specific cleanup (Windows ws2_32.freeaddrinfo vs POSIX system.freeaddrinfo)
    • No heap allocation needed - iterates directly over C library results
  • lookupHost: Renamed from getAddressList for better semantics

    • Removed allocator parameter - uses stack-based FixedBufferAllocator for temporary C strings
    • Returns IpAddressIterator by value instead of pointer
    • Single return statement for cleaner code flow
  • IpAddress.initPosix(): New method for safe sockaddr conversion

    • Takes *const sockaddr and socklen_t parameters
    • Uses @memcpy to handle alignment differences between sockaddr (align 2) and sockaddr_in/sockaddr_in6 (align 4)
    • Validates length in debug builds

Implementation details

  • Direct use of posix.system.getaddrinfo on POSIX systems
  • Direct use of std.os.windows.ws2_32.getaddrinfo on Windows
  • Added link_libc = true to build.zig (required for getaddrinfo)
  • Uses fully qualified names instead of aliases for clarity

API improvements

  • tcpConnectToHost no longer needs allocator parameter
  • Simpler, more idiomatic Zig iterator pattern
  • Memory efficient - no intermediate allocations

Testing

  • All 152 tests passing
  • Updated DNS lookup tests to use iterator pattern
  • Verified on Linux (Windows cross-compilation working)

Migration notes

// Before
const list = try getAddressList(rt, allocator, "example.com", 80);
defer list.deinit();
for (list.addrs) |addr| { ... }

// After  
var iter = try lookupHost(rt, "example.com", 80);
defer iter.deinit();
while (iter.next()) |addr| { ... }

- Implemented custom getAddressListBlocking() using posix.getaddrinfo
- Returns IpAddressList instead of std.net.AddressList
- Removed unused canon_name field from IpAddressList
- Added IpAddress.initPosix() method for safe sockaddr conversion
- Uses @memcpy to handle alignment differences between sockaddr types
- Added link_libc to build.zig as required for getaddrinfo
- Maintains blocking approach via thread pool (getaddrinfo_a uses threads internally anyway)
- Replace IpAddressList with IpAddressIterator for zero-allocation iteration
- Rename getAddressList to lookupHost for better semantics
- Remove allocator parameter - uses stack-based FixedBufferAllocator internally
- Update tcpConnectToHost to use iterator pattern
- Use fully qualified names instead of posix/windows aliases
- Single return statement in lookupHost
- Updated tests to use iterator pattern
@coderabbitai

coderabbitai Bot commented Nov 1, 2025 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Replaced allocator-based address-list APIs with an iterator-based lookup (IpAddressIterator), added IpAddress.initPosix to construct from POSIX sockaddr, updated tcpConnectToHost to use the new lookup, and enabled linking the C standard library for the zio build.

Changes

Cohort / File(s) Change Summary
Build Configuration
build.zig
Set .link_libc = true for the zio module to link the C standard library.
Network Address Types
src/io/net.zig
Added pub fn initPosix(addr: *const std.posix.sockaddr, len: std.posix.socklen_t) IpAddress to construct IpAddress from raw POSIX sockaddr with family checks, length assertions, and memcpy into the appropriate union member.
Network Host Resolution & APIs
src/net.zig
Replaced allocator-based getAddressList() with lookupHost() returning IpAddressIterator; added IpAddressIterator (head, current, next(), deinit()), LookupHostError, and lookupHostBlocking(); updated tcpConnectToHost() signature to remove allocator and to iterate IpAddressIterator; adjusted call sites and tests accordingly.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas needing extra attention:
    • Lifecycle and ownership in IpAddressIterator.deinit() and correct use of freeaddrinfo across platforms.
    • Correctness of IpAddress.initPosix assertions and memcpy sizes for sockaddr_in vs sockaddr_in6.
    • Call sites for tcpConnectToHost() ensuring allocator removal didn't omit necessary allocation responsibilities.

Possibly related PRs

Poem

The host list turned into a stream,
POSIX bytes boxed into a dream,
Iterators march through addrinfo rows,
TCP now follows where the iterator goes,
C linked in—small tweak, brighter beams. 🎉

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
Title Check ✅ Passed The title "Refactor DNS resolution to use posix.getaddrinfo with IpAddressIterator" directly captures the main change in the changeset. It's specific about what is being refactored (DNS resolution), the approach being adopted (posix.getaddrinfo), and the key abstraction introduced (IpAddressIterator). The title is concise, clear, and avoids vague language. When scanning the git history, this would immediately communicate the core intent of the PR.
Description Check ✅ Passed The description is well-structured and directly addresses the changeset. It explains the rationale (eliminate unnecessary allocations, improve ergonomics), breaks down concrete changes by component (IpAddressIterator, lookupHost, IpAddress.initPosix), covers implementation details across platforms, and provides concrete examples showing the before/after API usage. The description includes testing status and real implementation details like link_libc = true in build.zig, which grounds it in the actual changes rather than generic hand-waving.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-getaddrinfo

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

📜 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 5ff1962 and 7915d81.

📒 Files selected for processing (3)
  • build.zig (1 hunks)
  • src/io/net.zig (1 hunks)
  • src/net.zig (3 hunks)
⏰ 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)

Comment thread src/net.zig Resolved

@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

♻️ Duplicate comments (1)
src/net.zig (1)

101-123: WSANO_DATA still needs mapping to HostLacksNetworkAddresses.

Windows error code WSANO_DATA (11004) indicates the host has no usable network addresses but currently falls through to the else branch and surfaces as error.Unexpected. This breaks consistent handling across platforms. Add a case mapping .WSANO_DATA => return error.HostLacksNetworkAddresses to mirror the POSIX .NODATA handling at line 133.

Apply this diff:

                .WSAHOST_NOT_FOUND => return error.UnknownHostName,
                .WSATYPE_NOT_FOUND => return error.ServiceUnavailable,
+               .WSANO_DATA => return error.HostLacksNetworkAddresses,
                .WSAEINVAL => unreachable,
🧹 Nitpick comments (1)
src/net.zig (1)

81-86: Buffer size is adequate for typical use.

The 512-byte stack buffer handles hostnames up to 253 characters (DNS limit) plus port formatting. Edge cases that exceed this will return OutOfMemory, which is already in the LookupHostError set. If you expect unusually long inputs, consider bumping to 768 or 1024 bytes, but this is optional.

📜 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 7915d81 and 17327ed.

📒 Files selected for processing (1)
  • src/net.zig (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 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/net.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 (5)
src/net.zig (5)

17-41: Iterator pattern is clean.

The IpAddressIterator implementation correctly wraps the addrinfo linked list, filters unsupported address families, and handles platform-specific cleanup. The @intcast at line 27 will panic on overflow in debug/safe modes, which is the right behavior for malformed addrinfo data.


124-142: POSIX error handling is complete.

All EAI error codes are properly mapped, programmer errors correctly marked unreachable, and SYSTEM errors delegate to errno handling. The .NODATA case at line 133 correctly maps to HostLacksNetworkAddresses, which is what Windows should also do.


150-167: tcpConnectToHost refactor is solid.

Removing the allocator parameter and adopting the iterator pattern simplifies the code. The deferred cleanup ensures resources are freed, and the fallback logic correctly tries each address and returns UnknownHostName if the iterator is empty.


177-224: Tests correctly validate the iterator API.

The updated tests properly use the iterator pattern with deferred cleanup, verify that results are returned for localhost and numeric IPs, and confirm that port numbers are preserved correctly.


282-340: Integration test validates the end-to-end flow.

The tcpConnectToHost test correctly uses the updated API without the allocator parameter and confirms that the DNS lookup and connection flow works as expected.

Add error case for WSANO_DATA in Windows getaddrinfo error handling
to match the POSIX .NODATA case. This ensures consistent behavior
across platforms when a host has no usable network addresses.

Co-authored-by: Lukáš Lalinský <[email protected]>

@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 (3)
src/net.zig (3)

27-27: Consider validating the cast or using a comptime check.

The @intCast(info.addrlen) assumes that addrlen fits in the target type. While sockaddr lengths are typically small (16-28 bytes), you might want to add a debug assertion or use a safer cast pattern to catch unexpected values.

Example with debug assertion:

-            return IpAddress.initPosix(addr, @intCast(info.addrlen));
+            const len: u32 = @intCast(info.addrlen);
+            std.debug.assert(len <= 128); // sanity check
+            return IpAddress.initPosix(addr, len);

106-106: Simplify the success case comparison.

The pattern @as(std.os.windows.ws2_32.WinsockError, @enumFromInt(0)) in the switch case is unnecessarily verbose. You can simplify to just @enumFromInt(0) since the switch expression is already cast to WinsockError.

-                @as(std.os.windows.ws2_32.WinsockError, @enumFromInt(0)) => break,
+                @enumFromInt(0) => break,

167-167: Return a more accurate error when no addresses are available.

If lookupHost succeeds but iter.next() never returns an address (either because the result was empty or all addresses were filtered out), returning error.UnknownHostName is misleading. UnknownHostName implies DNS resolution failed, but here the lookup succeeded—we just have no usable addresses. Consider returning error.HostLacksNetworkAddresses instead.

-    return error.UnknownHostName;
+    return error.HostLacksNetworkAddresses;
📜 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 17327ed and 8305ff7.

📒 Files selected for processing (1)
  • src/net.zig (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 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/net.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)

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