Repository navigation
Add HostName API - #224
Add HostName API#224
Conversation
- Add HostName struct with RFC 1123 validation - Add HostName.lookup() returning []LookupResult - Add HostName.connect() for sequential connection attempts - Add IpAddress.Family enum and getFamily() method - Add family filter parameter to lookupHost()
📝 WalkthroughWalkthroughAdds a new public Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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: 1
🤖 Fix all issues with AI agents
In `@src/net.zig`:
- Around line 125-132: The code is copying the input hostname (self.bytes) into
canonical_name; instead, enable AI_CANONNAME on the getaddrinfo hints and, when
walking the addrinfo chain, read the actual ai_canonname from each addrinfo and
copy that (bounded by max_len) into options.canonical_name_buffer, then assign
results[count].canonical_name from that copied slice; update the hints where
getaddrinfo is called to include AI_CANONNAME and change the copy source in the
block using options.canonical_name_buffer to use addrinfo.ai_canonname (not
self.bytes) and respect length limits.
…port - Change HostName.lookup() to return LookupResultIterator instead of slice - Add canonical_name option to request AI_CANONNAME from DNS resolver - Fix windows_addrinfo.flags to use AI type instead of i32 - Remove lookupHost() and IpAddressIterator (use HostName.lookup() instead) - Simplify tcpConnectToHost() to use HostName.connect()
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/net.zig`:
- Around line 117-126: The next method on LookupResultIterator returns a
HostName whose bytes point directly into head.canonname (addrinfo), which is
freed by deinit()/freeaddrinfo(), causing a use-after-free if the caller stores
the HostName; fix by either documenting that values from
LookupResultIterator::next are only valid for the iterator's lifetime or change
the API so the caller supplies a mutable buffer to copy the canonical name into
(mirroring the old approach): update LookupResultIterator.next (and related
types like LookupResult and HostName) to copy head.canonname into the provided
buffer or add a method parameter for destination slice, and ensure
deinit()/freeaddrinfo remains responsible for freeing addrinfo without exposing
its internal pointers to callers.
🧹 Nitpick comments (1)
src/net.zig (1)
1347-1384: Missing test coverage for canonical_name option.The lookup tests use
canonical_name => unreachable, meaning thecanonical_name: truepath isn't exercised. Given that there's a memory-lifetime subtlety with that feature, a test that actually requests and uses the canonical name would help catch regressions.💡 Example test
test "HostName: lookup with canonical name" { const rt = try Runtime.init(std.testing.allocator, .{ .thread_pool = .{} }); defer rt.deinit(); const host = try HostName.init("localhost"); var iter = try host.lookup(rt, .{ .port = 80, .canonical_name = true }); defer iter.deinit(); var saw_canonical = false; var saw_address = false; while (iter.next()) |result| { switch (result) { .address => |_| saw_address = true, .canonical_name => |cn| { saw_canonical = true; // Verify we got something back try std.testing.expect(cn.bytes.len > 0); }, } } // At minimum we should see an address (canonical may or may not be present depending on resolver) try std.testing.expect(saw_address); }
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/net.zig`:
- Around line 1386-1409: The test assumes a canonical name is always returned
for HostName.lookup; instead, make the canonical-name assertion tolerant by
treating absence of ai_canonname as acceptable: after collecting
has_canonical_name and has_address from the iterator in the test (the block
using HostName.init, host.lookup, iter.next(), and the has_canonical_name flag),
only require has_address to be true but either skip the strict
expect(has_canonical_name) or turn it into a conditional expectation (e.g.,
log/skip the canonical-name check when has_canonical_name is false) so the test
won't fail on systems/resolvers that don't populate canonical names.
🧹 Nitpick comments (2)
src/net.zig (2)
169-188: Sequential connection approach works, with a caveat.On dual-stack hosts where one address family is broken (e.g., IPv6 route exists but doesn't work), users will experience connection timeouts before the fallback kicks in. RFC 8305 "Happy Eyeballs" solves this with parallel attempts, but that's a bigger undertaking.
Worth adding a doc comment noting this is sequential, not parallel. Users with latency-sensitive needs can filter by family or implement their own connection logic using
lookup()directly.📝 Suggested documentation
/// Resolves the hostname and connects to the first successful address. + /// Attempts connections sequentially in the order returned by DNS. + /// For faster dual-stack behavior, consider filtering by family or + /// implementing parallel connection attempts using `lookup()` directly. pub fn connect(self: HostName, rt: *Runtime, port: u16) !Stream {
1411-1412: Add explanation for macOS skip.Both macOS-skipped tests in this file (
HostName: connectat line 1412 andtcpConnectToHost: basicat line 1541) follow the same pattern: they bind a server to IPv4 (127.0.0.1) and then connect via hostname. On macOS, "localhost" likely resolves to IPv6 (::1) before IPv4, causing the connection to fail against an IPv4-only listener. A one-line comment would make this clear to the next person reading the code.📝 Suggested fix
test "HostName: connect" { + // macOS: localhost resolves to IPv6 (::1) before IPv4, but this test only listens on IPv4 if (builtin.os.tag == .macos) return error.SkipZigTest;Apply the same comment to line 1541 (
tcpConnectToHost: basic).
|
@coderabbitai tell me more about RFC 8305 "Happy Eyeballs" |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🌐 Web query: 💡 Result: RFC 8305, "Happy Eyeballs Version 2: Better Connectivity Using Concurrency" (December 2017) defines a revised, standards-track Happy Eyeballs algorithm for dual‑stack clients that races connection attempts to multiple resolved addresses (preferring IPv6) to reduce user-visible delay and improve reliability. It obsoletes RFC 6555 and specifies DNS query ordering, address sorting/interleaving, staggered (but overlapping) connection attempts, handling of DNS answer changes, and support for NAT64/DNS64. Key recommended values: Resolution Delay = 50 ms, Connection Attempt Delay = 250 ms (minimum 100 ms, maximum 2 s), DNS-reply cache processing ≈ 1 s, Last‑Resort Local Synthesis Delay = 2 s. The RFC also explains how to tune delays using RTT history and lists limitations and security considerations. (rfc-editor.org) Citations:
The ProblemWhen a hostname resolves to multiple addresses (both IPv4 and IPv6), trying them one at a time creates user-visible delays. If the first IPv6 address is unreachable but IPv4 works fine, users wait for a full timeout before the connection succeeds. The SolutionHappy Eyeballs races multiple connection attempts concurrently with staggered timing:
Key Timing Parameters
Your Current ImplementationLooking at your PR,
If you wanted to implement Happy Eyeballs, you'd need concurrent I/O primitives to race multiple Worth implementing? Depends on whether your use cases hit dual-stack scenarios with flaky IPv6 often enough to justify the complexity. |
|
@coderabbitai please create issue for that |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 42
|
Summary
HostNamestruct with RFC 1123 hostname validationHostName.lookup()that resolves to[]LookupResult(addresses + canonical name)HostName.connect()for sequential connection attemptsIpAddress.Familyenum andgetFamily()methodfamilyfilter parameter tolookupHost()Test plan
HostName: validate- tests valid and invalid hostnamesHostName: eql- tests case-insensitive comparisonHostName: lookup- tests DNS resolutionHostName: lookup with family filter- tests IPv4-only filteringHostName: connect- tests connecting via hostnameIpAddress: getFamily- tests family detection