Skip to content

Rust Fed Client: Resolve and connect to federation addresses in rust - #20577

Open
devonh wants to merge 19 commits into
developfrom
fed-client/pr03a-transport-and-tcp
Open

devonh wants to merge 19 commits into
developfrom
fed-client/pr03a-transport-and-tcp

Conversation

@devonh

@devonh devonh commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

See #20600 for a different approach using hickory.

This ports address lookup, the IP blocklist check on resolved addresses, and Twisted HostnameEndpoint's connection attempts to rust, for use by the future rust federation HTTP client. Nothing calls it yet.

Lookups run on one gai_resolver threadpool per process, just like today except today's reactor wide name resolver means the last homeserver started in a process serves every lookup (synapse/app/_base.py:665-682).

Another difference is that the python version starts with 5 threads, then ramps up to 20 as demand is high. We could do that here, but I don't know if the additional complexity is worth it given the overhead is already so tiny. (Measured at ~1MiB for 20 threads)
The 0.3 s and 30 s are HostnameEndpoint's defaults.

Alternatives not taken:

  • not doing a threadpool, which would require calling spawn_blocking ourselves
  • tokio::net::lookup_host calls spawn_blocking itself, so it would hide this from the lint rather than solve it.
  • hyper-util's HttpConnector reorders addresses by IPv4/IPv6 family, splits the timeout across addresses, and doesn't limit concurrent lookups.
  • hickory for A/AAAA lookups would mean not using the system resolver.

Pull Request Checklist

  • Pull request is based on the develop branch
  • Pull request includes a changelog file. The entry should:
    • Be a short description of your change which makes sense to users. "Fixed a bug that prevented receiving messages from other servers." instead of "Moved X method from EventStore to EventWorkerStore.".
    • Use markdown where necessary, mostly for code blocks.
    • End with either a period (.) or an exclamation mark (!).
    • Start with a capital letter.
    • Feel free to credit yourself, by adding a sentence "Contributed by @github_username." or "Contributed by [Your Name]." to the end of the entry.
  • Code style is correct (run the linters)

devonh added a commit that referenced this pull request Nov 27, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbR1WYYduJ2wZuhKwz
Comment thread rust/src/federation_client/dns/addr.rs Resolved
devonh added a commit that referenced this pull request Nov 30, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbR1WYYduJ2wZuhKwz
@devonh
devonh force-pushed the fed-client/pr03a-transport-and-tcp branch from 15c0f9b to d2e174a Compare November 30, 2026 21:06
@devonh
devonh marked this pull request as ready for review November 30, 2026 21:55
@devonh
devonh requested a review from a team as a code owner November 30, 2026 21:55
@devonh
devonh requested review from sandhose and removed request for a team November 30, 2026 21:55
/// Every homeserver in the process shares the one pool, so a process
/// hosting many homeservers may need more than the default 20 threads to
/// keep one homeserver's slow lookups from delaying the others.
pub fn new(threads: usize) -> io::Result<Self> {

@devonh devonh Nov 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

When this gets wired in, the threads count will come from a new config option.
This will allow for more flexibility in resolver pool size, which will be particularly useful for running multiple-tenants.

This is an improvement over today where we only have a single 20 thread pool, no matter how many tenants are running.

@devonh
devonh requested review from erikjohnston and removed request for sandhose November 30, 2026 22:00

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What's the reasoning for having a dedicated threadpool just for this instead of reusing the blocking pool we already have? Tokio's tokio::net::lookup_host is essentially just doing spawn_blocking with std::net::ToSocketAddrs (https://docs.rs/tokio/latest/src/tokio/net/addr.rs.html#219-221)

This has the advantage of reusing Tokio's blocking pool, which is already used for all sorts of I/O. And if you want to do some limiting, add a semaphore to limit the number of concurrent requests. That semaphore is fair, so it has the same FIFO property as the queue here

The implementation essentially becomes

struct GaiLookup {
    semaphore: Arc<tokio::sync::Semaphore>,
}

impl GaiLookup {
    pub fn new(concurrency: usize) -> Self {
        Self {
            semaphore: tokio::sync::Semaphore::new(concurrency),
        }
    }
}

impl AddrLookup for GaiLookup {
    async fn lookup(&self, host: &str, port: u16) -> io::Result<Vec<SocketAddr>> {
        let host = host.to_owned();
        let _permit = self.semaphore.acquire().await?;
        tokio::task::spawn_blocking(move || (host.as_str(), port).to_socket_addrs().map(Vec::from_iter))
            .await?
    }
}

which feels significantly simpler :D

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hmm, we could probably use tokio::net::lookup_host if that gives us the right features. What we wanted to avoid is directly using Runtime::spawn_blocking.

The issue is the the tokio runtime is tied to a homeserver, and when we shut down a homeserver we want everything associated with it torn down as well. This makes using Runtime::spawn_blocking potentially problematic, as there is no way for those threads to be torn down with the server. For short-lived work that is fine (like DNS lookup), but there is nothing preventing someone from doing longer lived work on them. This is why we have added Runtime::spawn_blocking to the clippy denylist.

Which basically puts us in an awkward spot where it's kinda fine to use spawn_blocking so long as the work is short-lived. That is tricky to encode though, which lead to the question of whether it'd be better to have a global thread pool for work that is homeserver agnostic.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

+1 to what Erik said.
The semaphore design you mention is very close to what this was before I switched it over to a dedicated thread pool.

tokio::net::lookup_host is spawn_blocking under the hood. https://github.com/tokio-rs/tokio/blob/bc38d827d2c0745120683e5e6a4e7fa2c4d32f98/tokio/src/net/addr.rs#L159-L223
So it would appease the linter, but result in the same behaviour as us calling spawn_blocking ourselves, which we are trying to avoid. So I don't see that as being much better.

The pool right now is specifically for DNS and not general Synapse work so that large numbers of DNS requests don't starve out other users of the threadpool. We could go for a more generic design, but until we have another use case for it it would be premature optimization.

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.

This is why we have added Runtime::spawn_blocking to the clippy denylist.

More context: #20011 (comment)


(I haven't evaluated the solution but doing work outside of the homeserver is fishy and the exception should be explained well and why)

devonh and others added 15 commits December 4, 2026 18:38
The transport trait and a TCP transport with TCP_NODELAY; getaddrinfo with
today's hints behind 20 permits; the block and allow sets on resolved
answers, with the blocked-address log line returned as an event; and the
address loop that HostnameEndpoint runs: one attempt every 0.3 s, 30 s
each, the last failure returned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJZTZVDGHBk6dbBWMqn
…ailed at the tick; re-raise lookup panics

FuturesUnordered again, so a large answer only polls the attempt that woke.
LookupFailure implements Display and Error. The permit test also covers a
waiting caller that is dropped. Comments state current facts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJZTZVDGHBk6dbBWMqn
…cy from IpSet

Event already means a Matrix event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJZTZVDGHBk6dbBWMqn
…d the stagger sleep do

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbb1GgsgJv3YKaJJFG
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbb1GgsgJv3YKaJJFG
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbR1WYYduJ2wZuhKwz
…order-independent permit test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbR1WYYduJ2wZuhKwz
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbRPaEDMPdRpb5jKCi
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbRPaEDMPdRpb5jKCi
devonh and others added 4 commits December 4, 2026 18:38
Back to one pool per process, as today (D57).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbRPaEDMPdRpb5jKCi
…n thread spawn errors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbRPaEDMPdRpb5jKCi
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbRPaEDMPdRpb5jKCi
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqDpJbRPaEDMPdRpb5jKCi

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants