Skip to content

Add HostName API - #224

Merged
lalinsky merged 3 commits into
mainfrom
hostname-api
Jan 21, 2026
Merged

lalinsky merged 3 commits into
mainfrom
hostname-api

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Add HostName struct with RFC 1123 hostname validation
  • Add HostName.lookup() that resolves to []LookupResult (addresses + canonical name)
  • Add HostName.connect() for sequential connection attempts
  • Add IpAddress.Family enum and getFamily() method
  • Add optional family filter parameter to lookupHost()

Test plan

  • HostName: validate - tests valid and invalid hostnames
  • HostName: eql - tests case-insensitive comparison
  • HostName: lookup - tests DNS resolution
  • HostName: lookup with family filter - tests IPv4-only filtering
  • HostName: connect - tests connecting via hostname
  • IpAddress: getFamily - tests family detection

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

coderabbitai Bot commented Jan 21, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a new public HostName type with RFC‑1123 validation, lookup and connect APIs; extends IpAddress with a Family enum and getFamily(); reworks DNS/lookup internals to support family filtering and canonical names; updates tcp connect flow to use HostName; removes legacy iterator/lookupHost API and updates tests.

Changes

Cohort / File(s) Summary
HostName type & DNS APIs
src/net.zig
Adds pub const HostName with bytes, max_len, ValidateError, validate(), init(), eql(), lookup() (with LookupOptions, LookupResult, LookupError, LookupResultIterator) and connect(). Replaces public lookupHost/iterator API and adjusts lookup call sites.
IpAddress extensions
src/net.zig
Adds pub const Family = enum { ipv4, ipv6 } and pub fn getFamily(self) -> Family. Propagates optional family through lookup options and internal calls.
tcp connect & lookup internals
src/net.zig
tcpConnectToHost(rt, name, port) now constructs a HostName and delegates to HostName.connect(). Internal blocking lookup signature updated to accept ?IpAddress.Family and canonical_name: bool, returning addrinfo accordingly.
Tests and harness
src/... (tests)
Adds HostName tests (validation, equality, lookup, family-filtered lookup, canonical name, connect), updates tests to new API shapes, and removes tests dependent on the old iterator/API.
OS-level addrinfo / flags
src/os/net.zig
Introduces an AI alias and changes Windows addrinfo flags field type to use AI mapping to align with platform differences.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

A hostname learns its rules by rhyme,
Picks IPv4 or IPv6 in time,
DNS returns a canonical name,
A connection opens — same game, new frame,
Cheers to nets that now resolve in prime. 🛰️

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add HostName API' directly matches the main change: a new HostName struct with validation, lookup, and connect methods.
Description check ✅ Passed The description clearly outlines the changes (HostName struct, lookup/connect methods, IpAddress.Family) and includes a complete test plan matching the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch hostname-api

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

🤖 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.

Comment thread src/net.zig Resolved
…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()

@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

🤖 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 the canonical_name: true path 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);
}

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: 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: connect at line 1412 and tcpConnectToHost: basic at 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).

Comment thread src/net.zig Resolved
@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai tell me more about RFC 8305 "Happy Eyeballs"

@coderabbitai

coderabbitai Bot commented Jan 21, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🌐 Web query:

RFC 8305 Happy Eyeballs Version 2

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


@lalinsky, RFC 8305 "Happy Eyeballs Version 2" addresses the problem your HostName.connect() currently faces with sequential connection attempts.

The Problem

When 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 Solution

Happy Eyeballs races multiple connection attempts concurrently with staggered timing:

  1. Dual DNS queries: Issue A and AAAA queries in parallel (AAAA first, A after 50ms if no answer yet)
  2. Address interleaving: Sort results preferring IPv6, but interleave address families so you don't try 5 broken IPv6 addresses before attempting IPv4
  3. Staggered connections: Start connecting to the first address, then initiate the next attempt after 250ms if the first hasn't completed (this is the "Connection Attempt Delay")
  4. First wins: Use whichever connection succeeds first, cancel the rest

Key Timing Parameters

  • Resolution Delay: 50ms between AAAA and A queries
  • Connection Attempt Delay: 250ms between starting each connection attempt (min 100ms, max 2s)
  • Can be tuned based on RTT history for that destination

Your Current Implementation

Looking at your PR, HostName.connect() tries addresses sequentially. This is simpler and more predictable, but slower when early addresses are unreachable. You already have the building blocks:

  • HostName.lookup() with family filtering
  • LookupResult iteration
  • Sequential connection logic

If you wanted to implement Happy Eyeballs, you'd need concurrent I/O primitives to race multiple tcpConnect() calls with proper staggering and cancellation.

Worth implementing? Depends on whether your use cases hit dual-stack scenarios with flaky IPv6 often enough to justify the complexity.

@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai please create issue for that

@coderabbitai

coderabbitai Bot commented Jan 21, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Create a GitHub issue for implementing RFC 8305 Happy Eyeballs

gh issue create \
  --title "Implement RFC 8305 Happy Eyeballs for concurrent connection attempts" \
  --body "Currently, \`HostName.connect()\` tries resolved addresses sequentially. When a hostname resolves to multiple addresses (IPv4 and IPv6), this creates user-visible delays if early addresses are unreachable.

RFC 8305 \"Happy Eyeballs Version 2\" defines an algorithm to race multiple connection attempts concurrently with staggered timing:
- Dual DNS queries (AAAA and A) with 50ms resolution delay
- Address interleaving to avoid trying all IPv6 before IPv4
- Staggered connections with 250ms delay between attempts
- First successful connection wins, others are cancelled

This would require concurrent I/O primitives to race multiple connection attempts with proper staggering and cancellation.

Related to PR `#224` and discussion: https://github.com/lalinsky/zio/pull/224

Requested by: `@lalinsky`" \
  --assignee lalinsky

Length of output: 42


@lalinsky, created issue #225 for tracking the Happy Eyeballs implementation: #225

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