From e68dbda9ada25da61a2bcdff5eb12b9bc8e0ba1e Mon Sep 17 00:00:00 2001 From: Franz Heinzmann Date: Tue, 18 Aug 2026 16:01:05 +0000 Subject: [PATCH] feat(iroh-relay, iroh): inform clients when they are rate-limited and warn log in iroh (#4455) ## Description When a relay server rate-limits a client connection, we now send a new `Status::RateLimited` message to the client, so that it can inform the user or the application. In iroh, for now we just `warn!` log this. The message is sent at most once per relay connection. Fixes #4454 ## Breaking Changes ## Notes & open questions This does not need a protocol version bump because we are using the `Status` frame which is designed to be extensible with new variants. Old clients will see a `WARN: Relay server reports problem: Unsupported health message (2)`. ## Change checklist - [x] Self-review. - [x] Documentation updates following the [style guide](https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html#appendix-a-full-conventions-text), if relevant. - [x] Tests if relevant. - [x] All breaking changes documented. - [x] This PR was created by a human that thought critically about the proposed change and wrote an as clear and concise description as they could. - [x] This PR isn't slop, and is carefully crafted to do have the intented effect. --- Cargo.lock | 16 ++--- iroh-relay/src/protos/relay.rs | 22 +++++- iroh-relay/src/server/client.rs | 87 ++++++++++++++++++++++- iroh-relay/src/server/http_server.rs | 2 + iroh-relay/src/server/streams.rs | 36 ++++++---- iroh/src/socket/transports/relay/actor.rs | 2 + 6 files changed, 142 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0093f053eb..1162334ab3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1317,7 +1317,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1646,9 +1646,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.15" +version = "0.4.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" +checksum = "a9f37a958b41b3b19ee2707c06439c0e9e547e847223eb791ecb0cb821c65e27" dependencies = [ "atomic-waker", "bytes", @@ -4088,7 +4088,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4181,7 +4181,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4286,7 +4286,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b55fb86dfd3a2f5f76ea78310a88f96c4ea21a3031f8d212443d56123fd0521" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4763,7 +4763,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5612,7 +5612,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/iroh-relay/src/protos/relay.rs b/iroh-relay/src/protos/relay.rs index f2f43052b6..2bd019b400 100644 --- a/iroh-relay/src/protos/relay.rs +++ b/iroh-relay/src/protos/relay.rs @@ -128,6 +128,15 @@ pub enum Status { "Another endpoint connected with the same endpoint id. No more messages will be received." )] SameEndpointIdConnected, + /// The relay is rate-limiting traffic received from this endpoint. + /// + /// Sent once per connection when the relay first throttles reading from the client. + #[display( + "The relay is rate-limiting this endpoint; outbound relay traffic is being throttled. \ + Send less data over the relay, or, if you operate this relay, raise Limits::client_rx. \ + Read more about rate limiting at https://docs.iroh.computer/relays/rate-limiting" + )] + RateLimited, /// Placeholder for backwards-compatibility for future new health status variants. #[display("Unsupported health message ({_0})")] Unknown(u8), @@ -139,6 +148,7 @@ impl Status { match self { Status::Healthy => dst.put_u8(0), Status::SameEndpointIdConnected => dst.put_u8(1), + Status::RateLimited => dst.put_u8(2), Status::Unknown(discriminant) => dst.put_u8(*discriminant), } dst @@ -155,6 +165,7 @@ impl Status { match discriminant { 0 => Ok(Self::Healthy), 1 => Ok(Self::SameEndpointIdConnected), + 2 => Ok(Self::RateLimited), n => Ok(Self::Unknown(n)), } } @@ -677,6 +688,10 @@ mod tests { RelayToClientMsg::Status(Status::SameEndpointIdConnected).write_to(Vec::new()), "0d 01", ), + ( + RelayToClientMsg::Status(Status::RateLimited).write_to(Vec::new()), + "0d 02", + ), ]); Ok(()) @@ -823,7 +838,12 @@ mod proptests { s.len() < MAX_PACKET_SIZE // a single unicode character can match a regex "." but take up multiple bytes }) .prop_map(|problem| RelayToClientMsg::Health { problem }); - let health = Just(Status::SameEndpointIdConnected).prop_map(RelayToClientMsg::Status); + let health = prop_oneof![ + Just(Status::Healthy), + Just(Status::SameEndpointIdConnected), + Just(Status::RateLimited), + ] + .prop_map(RelayToClientMsg::Status); let restarting = (any::(), any::()).prop_map(|(reconnect_in, try_for)| { RelayToClientMsg::Restarting { reconnect_in: Duration::from_millis(reconnect_in.into()), diff --git a/iroh-relay/src/server/client.rs b/iroh-relay/src/server/client.rs index 7d59088516..32c77f7592 100644 --- a/iroh-relay/src/server/client.rs +++ b/iroh-relay/src/server/client.rs @@ -8,7 +8,10 @@ use n0_future::{SinkExt, StreamExt}; use rand::RngExt; use time::{Date, OffsetDateTime}; use tokio::{ - sync::mpsc::{self, error::TrySendError}, + sync::{ + mpsc::{self, error::TrySendError}, + watch, + }, time::MissedTickBehavior, }; use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle}; @@ -60,6 +63,12 @@ pub struct Config { pub channel_capacity: usize, /// Protocol version negotiated for this client pub protocol_version: ProtocolVersion, + /// Optional signal to inform the client when it is being rate-limited. + /// + /// When set, the connection actor notifies the client once with a + /// [`Status::RateLimited`] message when the rate-limited counter first + /// becomes non-zero. + pub(crate) rate_limited: Option>, } impl Config { @@ -77,6 +86,7 @@ impl Config { protocol_version, write_timeout: SERVER_WRITE_TIMEOUT, channel_capacity: PER_CLIENT_SEND_QUEUE_DEPTH, + rate_limited: None, } } } @@ -121,6 +131,7 @@ impl Client { write_timeout, channel_capacity, protocol_version, + rate_limited, } = config; let endpoint_id = guard.endpoint_id; let connection_id = guard.connection_id; @@ -138,6 +149,8 @@ impl Client { clients: clients.clone(), client_counter: ClientCounter::default(), ping_tracker: PingTracker::default(), + protocol_version, + rate_limited, metrics, }; @@ -212,6 +225,21 @@ impl Client { } } +/// Completes when `rx` observes the connection being rate-limited. +/// +/// Pends forever when `rx` is `None`, i.e. when no rate-limit signal is configured. +async fn rate_limited_signal(rx: &mut Option>) -> bool { + match rx { + Some(rx) => match rx.changed().await { + Ok(()) => *rx.borrow_and_update() > 0, + // The sender lives inside this actor's stream, so it cannot drop while + // the actor runs. Report not limited to be safe. + Err(_) => false, + }, + None => std::future::pending().await, + } +} + /// Error when handling an incoming frame from a client. #[stack_error(derive, add_meta, from_sources)] #[allow(missing_docs)] @@ -304,6 +332,10 @@ struct Actor { /// Statistics about the connected clients client_counter: ClientCounter, ping_tracker: PingTracker, + /// Relay protocol version negotiated for this client. + protocol_version: ProtocolVersion, + /// Optional signal counting how often the connection has been rate-limited. + rate_limited: Option>, metrics: Arc, } @@ -344,6 +376,8 @@ where ping_interval.set_missed_tick_behavior(MissedTickBehavior::Delay); ping_interval.tick().await; + let mut rate_limit_notified = false; + loop { tokio::select! { biased; @@ -354,6 +388,17 @@ where self.stream.flush().await.map_err(|_| e!(RunError::Flush))?; break; } + limited = rate_limited_signal(&mut self.rate_limited), if !rate_limit_notified => { + // Notify the client once per connection. + // V1 clients are not notified. + rate_limit_notified = true; + if limited && self.protocol_version == ProtocolVersion::V2 { + debug!("connection is rate-limited, notifying client"); + self.write_frame(RelayToClientMsg::Status(Status::RateLimited)) + .await + .map_err(|err| e!(RunError::WriteFrame, err))?; + } + } maybe_frame = self.stream.next() => { self .handle_frame(maybe_frame) @@ -602,6 +647,8 @@ mod tests { clients: clients.clone(), client_counter: ClientCounter::default(), ping_tracker: PingTracker::default(), + protocol_version: ProtocolVersion::V2, + rate_limited: None, metrics, }; @@ -813,7 +860,7 @@ mod tests { let (io_read, io_write) = tokio::io::duplex((LIMIT * MAX_FRAMES) as _); let mut frame_writer = Conn::test(io_write, Default::default()); // Rate limiter allowing LIMIT bytes/s - let mut stream = RelayedStream::test_limited(io_read, LIMIT / 10, LIMIT)?; + let (mut stream, _limited) = RelayedStream::test_limited(io_read, LIMIT / 10, LIMIT)?; // Prepare a frame to send, assert its size. let data = Datagrams::from(b"hello world!!!!!"); @@ -858,4 +905,40 @@ mod tests { Ok(()) } + + /// A client whose connection is rate-limited receives a [`Status::RateLimited`] notice. + #[tokio::test(start_paused = true)] + #[traced_test] + async fn test_rate_limit_notice() -> Result { + const LIMIT: u32 = 50; + + let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); + let key = SecretKey::from_bytes(&rng.random()).public(); + let target = SecretKey::from_bytes(&rng.random()).public(); + + let (server_io, client_io) = tokio::io::duplex(4096); + // Rate limiter allowing LIMIT bytes/s with a burst size below a single frame. + let (stream, limited) = ServerRelayedStream::test_limited(server_io, LIMIT / 10, LIMIT)?; + let mut config = Config::new(OnDisconnectGuard::empty(key), stream, ProtocolVersion::V2); + config.write_timeout = Duration::from_secs(1); + config.channel_capacity = 10; + config.rate_limited = Some(limited); + let mut conn = Conn::test(client_io, ProtocolVersion::V2); + + let clients = Clients::default(); + clients.register(config, Arc::new(Metrics::default())); + + // A single frame larger than the burst size trips the rate limiter. + conn.send(ClientToRelayMsg::Datagrams { + dst_endpoint_id: target, + datagrams: Datagrams::from(b"hello world!!!!!"), + }) + .await?; + + let frame = recv_frame(FrameType::Status, &mut conn).await?; + assert_eq!(frame, RelayToClientMsg::Status(Status::RateLimited)); + + clients.shutdown().await; + Ok(()) + } } diff --git a/iroh-relay/src/server/http_server.rs b/iroh-relay/src/server/http_server.rs index 22384ebfb0..a774bf6a3f 100644 --- a/iroh-relay/src/server/http_server.rs +++ b/iroh-relay/src/server/http_server.rs @@ -855,6 +855,7 @@ impl Inner { let io = RateLimited::from_watcher(io, self.rate_limit.subscribe(), self.metrics.clone()) .map_err(|err| e!(AcceptError::RateLimitingMisconfigured, err))?; + let limited_watcher = io.limited_watcher(); // Create a server builder with default config let websocket = tokio_websockets::ServerBuilder::new() @@ -887,6 +888,7 @@ impl Inner { trace!("accept: build client conn"); let mut client_conn_builder = Config::new(guard, io, protocol_version); client_conn_builder.write_timeout = self.write_timeout; + client_conn_builder.rate_limited = Some(limited_watcher); trace!(endpoint_id = %request.endpoint_id().fmt_short(), "create client"); // build and register client, starting up read & write loops for the client diff --git a/iroh-relay/src/server/streams.rs b/iroh-relay/src/server/streams.rs index 105ee336f0..a15710f4c5 100644 --- a/iroh-relay/src/server/streams.rs +++ b/iroh-relay/src/server/streams.rs @@ -69,7 +69,7 @@ impl ServerRelayedStream { stream: tokio::io::DuplexStream, max_burst_bytes: u32, bytes_per_second: u32, - ) -> Result { + ) -> Result<(Self, watch::Receiver), InvalidBucketConfig> { let stream = MaybeTlsStream::Test(stream); let stream = RateLimited::new( stream, @@ -77,14 +77,16 @@ impl ServerRelayedStream { bytes_per_second, Arc::new(Metrics::default()), )?; - Ok(Self { + let limited_watcher = stream.limited_watcher(); + let stream = Self { inner: WsBytesFramed { io: tokio_websockets::ServerBuilder::new() .limits(Self::limits()) .serve(stream), }, key_cache: KeyCache::test(), - }) + }; + Ok((stream, limited_watcher)) } fn limits() -> tokio_websockets::Limits { @@ -334,8 +336,11 @@ pub(crate) struct RateLimited { inner: S, bucket: Option, bucket_refilled: Option>>, - /// Keeps track if this stream was ever rate-limited. - limited_once: bool, + /// Counts how often reads from this stream have been rate-limited. + /// + /// Subscribe via [`RateLimited::limited_watcher`] to be notified about it, e.g. to + /// inform the client that it is being throttled. + limited_tx: watch::Sender, /// Watcher for the per-client rate limit, if set. /// /// If set by constructing via [`RateLimited::from_watcher`], we check for @@ -489,7 +494,7 @@ impl RateLimited { inner: io, bucket, bucket_refilled: None, - limited_once: false, + limited_tx: watch::Sender::new(0), rate_limit_watcher: Some(rate_limit_watcher), metrics, }) @@ -510,7 +515,7 @@ impl RateLimited { time::Duration::from_millis(100), )?), bucket_refilled: None, - limited_once: false, + limited_tx: watch::Sender::new(0), rate_limit_watcher: None, metrics, }) @@ -522,20 +527,27 @@ impl RateLimited { inner, bucket: None, bucket_refilled: None, - limited_once: false, + limited_tx: watch::Sender::new(0), rate_limit_watcher: None, metrics, } } + /// Returns a watcher that counts how often reads from this stream have been rate-limited. + pub(crate) fn limited_watcher(&self) -> watch::Receiver { + self.limited_tx.subscribe() + } + /// Records metrics about being rate-limited. fn record_rate_limited(&mut self, bytes: usize) { // TODO: add a label for the frame type. self.metrics.bytes_rx_ratelimited_total.inc_by(bytes as u64); - if !self.limited_once { - self.metrics.conns_rx_ratelimited_total.inc(); - self.limited_once = true; - } + self.limited_tx.send_modify(|count| { + if *count == 0 { + self.metrics.conns_rx_ratelimited_total.inc(); + } + *count += 1; + }); } } diff --git a/iroh/src/socket/transports/relay/actor.rs b/iroh/src/socket/transports/relay/actor.rs index 42c317ea58..e4f982af14 100644 --- a/iroh/src/socket/transports/relay/actor.rs +++ b/iroh/src/socket/transports/relay/actor.rs @@ -743,6 +743,8 @@ impl ActiveRelayActor { } RelayToClientMsg::Status(status) => match status { Status::Healthy => info!("Relay server reports: {status}"), + // The relay sends this at most once per connection. + Status::RateLimited => warn!("{status}"), _ => warn!("Relay server reports problem: {status}"), }, RelayToClientMsg::Restarting { .. } => {