Repository navigation
fix(node): wrap gossip ALPN with dispatch limiter (#433) - #512
Conversation
iroh-gossip's ProtocolHandler attached directly to the Router bypassed ConnectionLimiter (#235) entirely, so a connection flood on the gossip ALPN was bounded only by iroh-gossip's internal limits — the global semaphore did not hold network-wide. Wrap it in a generic LimitedHandler<H> adapter so every ALPN attached to the Router goes through the same admission control. Probe stays on its inline limiter.acquire (defense in depth + custom per-layer close-frame timeout policy the generic adapter intentionally omits). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces LimitedHandler, a wrapper for ProtocolHandler that applies connection limiting to foreign handlers like iroh-gossip, ensuring consistent network-wide resource management. The implementation includes the wrapper, its integration into the node runtime, and new integration tests. A review comment suggests optimizing the tests by moving expensive setup operations outside of loops and avoiding unnecessary waits for connection closure to prevent task accumulation and improve performance.
Coverage reportTotal: 88.27% (was 88.28%, ▼ 0.02%) — 12333/13972 lines
History
|
There was a problem hiding this comment.
Pull request overview
This PR ensures the node’s global connection concurrency cap (ConnectionLimiter’s semaphore from #235) applies to all ALPN handlers attached to the iroh Router, by wrapping the iroh-gossip handler with a new LimitedHandler adapter (addressing #433).
Changes:
- Added
handlers::limited::LimitedHandlerto gate a foreignProtocolHandler::acceptbehindConnectionLimiter::acquire, while forwardingon_acceptingandshutdown. - Updated the runtime router wiring to wrap
iroh-gossip’s handler withLimitedHandler. - Added unit + integration tests covering global-cap rejection, per-source rejection, permit release on inner error, and shutdown forwarding.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| crates/node/src/runtime/mod.rs | Wrapes the gossip ALPN handler with LimitedHandler so gossip is subject to the global limiter. |
| crates/node/src/handlers/mod.rs | Exposes the new limited handler module. |
| crates/node/src/handlers/limited.rs | Implements the LimitedHandler ProtocolHandler adapter and a unit test for shutdown forwarding. |
| crates/node/tests/limited_handler.rs | Adds two-endpoint integration tests validating limiter behavior through the wrapper. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
- Reword "layer-label byte" → "layer-label reason bytes" in the
rejection-path comment: `RejectReason::as_str()` returns multi-byte
ASCII strings ("global-full"/"per-source"), not a single byte.
(Copilot review.)
- Hoist the `client_ep` out of the per-iteration loop in
`permit_releases_when_inner_returns_err`; endpoint construction is
the expensive part. Trims the test from ~0.82s to ~0.26s.
(gemini-code-assist review, partial — kept the conn.closed() wait
because it serializes against the server-side permit drop; without
it iteration N+1 can race iteration N's permit release. The cited
"no conn.closed() wait" guideline applies to flood scenarios on
the limiter's memory-pressure path, not this 3-iteration test.)
- Propagate the previously-discarded `tokio::time::timeout` error
inside the loop: a regression that left the connection open would
silently pass before. (Copilot review.)
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Previous wording ("the connection itself is cheap") overstated the
asymmetry — `connect` does a full QUIC+TLS handshake which is not cheap
in absolute terms. Replace with the measured speedup that motivates the
hoist, so the comment survives a future where `connect` regresses.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu
left a comment
There was a problem hiding this comment.
Reviewed locally against iroh 0.98.2 / iroh-gossip 0.98.0 (per Cargo.lock).
Significant — global-cap semantics on gossip are weaker than the PR framing
The PR description and the LimitedHandler doc-comments frame this as: gossip floods now go through ConnectionLimiter, so the global concurrency cap (#235) "holds network-wide." That holds for the per-source rate-limit layer but only weakly for the global semaphore, because of how iroh-gossip's Gossip::accept is shaped.
In iroh-gossip 0.98 (src/net.rs:130 and src/net.rs:247):
impl ProtocolHandler for Gossip {
async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
self.handle_connection(connection).await ... // enqueues into a 16-deep mpsc, returns
}
}The actor consumes the message and spawns a per-connection task that owns the Connection for its full lifetime (src/net.rs:526-562).
In LimitedHandler::accept:
let _permit = match self.limiter.acquire(&conn) { ... };
self.inner.accept(conn).await
// _permit drops here_permit is held only until inner.accept returns — i.e. until the mpsc enqueue completes. For probe (where accept runs the protocol inline) permit lifetime ≈ connection lifetime. For gossip, permit lifetime ≈ mpsc-enqueue time (microseconds). So under sustained flood the global semaphore briefly back-pressures once the gossip actor's 16-slot channel saturates, but it doesn't bound the number of in-flight gossip handler tasks the way it does for probe.
The integration tests use a ParkingHandler that artificially blocks inside accept — that validates the wrapper's bookkeeping correctly, but doesn't reflect Gossip::accept's actual return-fast shape. rejects_second_connection_past_global_cap would pass identically against probe; it does not prove the global cap is enforced on a real gossip flood.
This is strictly better than today (per-source layer is properly gated, some back-pressure once gossip's mpsc fills), but worth deciding whether to (a) accept the limitation and tighten the doc-comments / PR-description to describe what's actually enforced for gossip, (b) extend the wrapper to keep the permit live until conn.closed() (would need a spawned watcher task, with its own costs and an interaction with Router::shutdown's drain semantics), or (c) defer.
Minor
-
Copilot's "byte vs bytes" flag on
limited.rsappears stale — the wrapper's rejection-block comment already says "layer-label reason bytes" (plural), which is correct forreason.as_str().as_bytes(). The singular "reason byte" wording does live incrates/node/src/handlers/probe.rs:26("0x10 RATE_LIMITEDreason byte (and its layer label)"), where it's defensible as referring to the QUIC application-error-code byte plus a separate label payload. Either tighten that for consistency or leave it. -
Gemini's "hoist setup out of the loop" flag on
permit_releases_when_inner_returns_erris partly stale —client_epis already hoisted outside the loop; onlyclient_ep.connect(...)runs per iteration, which is the test's actual subject. Gemini's secondary concern aboutconn.closed()waits is addressed directly in the test's own inline comment: this is a 3-iteration sequencing test, not a flood, so the limiter's memory-pressure-path guideline doesn't apply. -
Coverage is 49/59 lines on
handlers/limited.rs(83%); the uncovered chunk is presumably parts of theErr(reason)rejection path. The in-crate unit test only exercisesshutdownforwarding, and the integration tests live undertests/where coverage attribution to the crate file may differ. Not worth blocking.
Verified correct
- Trait defaults for
on_accepting(awaitAccepting) andshutdown(no-op) match what the wrapper explicitly forwards (iroh-0.98.2/src/protocol.rs:249-287). Gossip::shutdowndoes sendDisconnectand stop the actor (iroh-gossip-0.98.0/src/net.rs:255-267) — the forwarding rationale onshutdownis accurate.PermitRAII drop and metrics-gauge balance preserved;_permitdrops at end of function body in the expected order relative toinner.accept.GlobalFullno-conn.closed()-wait rationale matches probe's existing reasoning (crates/node/src/handlers/probe.rs:96-106) — consistent across the two handlers.#[must_use]onLimitedHandler::new,finish_non_exhaustive()inDebug, anti-panic policy honored.
Review #4262648505 on PR #512 flagged that the wrapper's global-cap semantics were weaker than advertised for iroh-gossip. `Gossip::accept` returns after a 16-deep mpsc enqueue (iroh-gossip-0.98.0/src/net.rs:131- 136, 247-253) and the actor then spawns the long-lived per-connection task (net.rs:526-562). The original wrapper dropped the permit when `inner.accept` returned, so for gossip the permit covered enqueue time (microseconds) rather than connection lifetime — the global semaphore briefly back-pressured once the actor's mpsc filled but never bounded in-flight gossip handler tasks. Spawn a detached watcher on the Ok path that owns the Permit and awaits `Connection::closed()`. The permit now stays held until the QUIC connection actually terminates, regardless of whether the inner handler runs inline (probe-shape) or returns fast and spawns internally (gossip-shape). The spawn is detached because Router::shutdown calls endpoint.close(), which fires every pending Connection::closed() future network-wide; watchers terminate without external coordination, so LimitedHandler does not need a JoinSet field (which would force interior mutability for no real benefit). Permit safety: Permit (crates/node/src/dispatch.rs:111-127) is Send (OwnedSemaphorePermit + Arc<Metrics>); its Drop unconditionally decrements the in-flight gauge, preserving balance whether the watcher exits normally, is aborted, or panics. Connection::clone is a refcount bump that does not extend the connection's lifetime past what the inner handler keeps alive. New test rejects_second_connection_for_return_fast_inner mimics gossip's return-fast + spawn-internally shape and proves a second connection is RATE_LIMITED while the first task holds its clone. Verified to fail without the watcher. Existing tests unchanged. Module docs rewritten to describe the inline vs. return-fast handler shapes and exactly what the global semaphore now enforces for each. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Apply review feedback from the in-conversation multi-agent review on the watcher fix (commit 604b530). Changes are doc/test-tightening plus two new test assertions that catch regression classes the original new test missed: Test coverage: - rejects_second_connection_for_return_fast_inner now opens a third connection after conn1 closes and asserts inner.accepts == 2. The original test only proved client 2 was rejected while the watcher held the permit; a future `mem::forget(permit)` or detached-leak regression would have slipped through. Verified to fail when the watcher's permit is leaked. - New router_shutdown_releases_parked_watcher_permit: forces shutdown while a watcher is still parked on `closed()` and polls ConnectionLimiter::acquire_for_test until the permit becomes available. Catches the upstream-iroh-regression class where endpoint.close() stops firing pending Connection::closed() futures. Also verified to fail under a forced leak. Comment policy (CLAUDE.md): drop issue/PR refs from long-lived code. - Module-doc H2 heading: remove "(issue #433)". - ReturnFastHandler docstring: remove the "review #4262648505 on PR #512" sentence; the test name and the `accepts == 1` assertion message at the failure site capture the WHY durably. - Trim the in-test "permit held continuously" parenthetical aside to the one load-bearing sentence ("`spawned` fires after the wrapper has reached `tokio::spawn`, so the watcher owns the permit"). Comment policy (CLAUDE.md): WHY-not-WHAT. - Drop the accept-body two-shapes recap; the module doc already carries the taxonomy. - Thin the "no panicking paths" elaboration to one sentence noting `Permit::drop` is unconditional. - Tighten "(which would force interior mutability for no real benefit)" to "watchers self-terminate". - Remove the "Construction is cheap" body of LimitedHandler::new (the `#[must_use]` text already carries the load). Skipped (YAGNI per CLAUDE.md): - Adding `tracing::trace!` for the discarded ConnectionError. The wrapper's job is gauge balance, not close-reason observability; the inner handler owns that signal. - Wrapping the watcher body in `tracing::Instrument` as a guardrail for a hypothetical future panic-able call. The current body provably cannot panic. - Adding a `// moved into watcher below` comment to the `permit` binding. The move is visible on the next code block — explanatory comments for self-evident control flow rot first. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
LimitedHandler<H: ProtocolHandler>adapter so the global concurrency cap (dispatch: no per-IP or per-Nodeld connection rate limit, enabling cheap connection exhaustion #235) extends to gossip — closes runtime: there is no graceful backpressure or rejection when the iroh QUIC accept loop is saturated, meaning a burst of inbound connections can exhaust Tokio worker threads before the per-IP rate limit (issue #235) is enforced #433.inner.accept-return is sufficient because the protocol runs entirely insideaccept. For return-fast handlers (gossip-shape:iroh-gossip 0.98'sGossip::accepthands the connection to a 16-deep mpsc and returns in microseconds), the wrapper now spawns a detached watcher that holds the permit untilConnection::closed()fires, so the global semaphore actually bounds in-flight gossip connection tasks rather than just back-pressuring once the actor's mpsc saturates.Router::shutdowncallsendpoint.close(), which fires every pendingConnection::closed(), so watchers terminate without external coordination andLimitedHandlerdoes not need aJoinSetfield.Permit::dropis unconditional, so the in-flight gauge stays balanced whether the watcher exits normally, is aborted, or panics.on_acceptingandshutdownto the inner handler. iroh-gossip'sGossip::shutdownsendsDisconnectmessages and stops the actor; a wrapper that did not forward would silently break graceful drain.limiter.acquirefor its custom per-rejection-layer close-frame timeout policy that the generic adapter intentionally omits.The original framing of this PR (commit 9275194) implied the global cap held network-wide for gossip after the wrapper landed. Review #4262648505 flagged that this was overstated because the original wrapper dropped the permit at
inner.accept-return. Commit 604b530 introduces the watcher and rewrites the module docs to describe what is actually enforced for each handler shape.Test plan
cargo nextest run -p decdn-node— 88/88 pass, including 4limited_handlertests:rejects_second_connection_past_global_cap(ParkingHandler — blocks inside accept)rejects_second_connection_for_return_fast_inner(new — mimics gossip's return-fast + spawn-internally shape; verified to fail without the watcher)per_source_rejection_routes_through_wrapperpermit_releases_when_inner_returns_errcargo clippy --workspace --all-targets -- -D warnings— clean.cargo fmt -- --check— clean.cargo doc -p decdn-node --no-deps— clean (intra-doc links resolve).Closes #433.
🤖 Generated with Claude Code