iroh_relay/server/
streams.rs

1//! Streams used in the server-side implementation of iroh relays.
2
3use std::{
4    pin::Pin,
5    sync::{Arc, atomic::AtomicBool},
6    task::{Context, Poll},
7};
8
9use n0_error::{ensure, stack_error};
10use n0_future::{FutureExt, Sink, Stream, ready, time};
11use tokio::{
12    io::{AsyncRead, AsyncWrite},
13    sync::watch,
14};
15use tracing::{instrument, warn};
16
17use super::{ClientRateLimit, Metrics};
18use crate::{
19    ExportKeyingMaterial, KeyCache, MAX_PACKET_SIZE,
20    protos::{
21        relay::{ClientToRelayMsg, Error as ProtoError, RelayToClientMsg},
22        streams::{StreamError, WsBytesFramed},
23    },
24};
25
26/// The relay's connection to a client.
27///
28/// This implements
29/// - a [`Stream`] of [`ClientToRelayMsg`]s that are received from the client,
30/// - a [`Sink`] of [`RelayToClientMsg`]s that can be sent to the client.
31///
32/// Generic over the inner stream type to support different WebSocket implementations.
33#[derive(Debug)]
34pub struct RelayedStream<S> {
35    pub(crate) inner: S,
36    pub(crate) key_cache: KeyCache,
37}
38
39impl<S> RelayedStream<S> {
40    /// Creates a new RelayedStream from an inner stream and key cache.
41    ///
42    /// This is the primary constructor for external integrations using custom
43    /// WebSocket implementations.
44    pub fn new(inner: S, key_cache: KeyCache) -> Self {
45        Self { inner, key_cache }
46    }
47}
48
49/// Type alias for the standard server-side relay stream
50#[allow(dead_code)]
51pub(super) type ServerRelayedStream = RelayedStream<WsBytesFramed<RateLimited<MaybeTlsStream>>>;
52
53#[cfg(test)]
54impl ServerRelayedStream {
55    pub(crate) fn test(stream: tokio::io::DuplexStream) -> Self {
56        let stream = MaybeTlsStream::Test(stream);
57        let stream = RateLimited::unlimited(stream, Arc::new(Metrics::default()));
58        Self {
59            inner: WsBytesFramed {
60                io: tokio_websockets::ServerBuilder::new()
61                    .limits(Self::limits())
62                    .serve(stream),
63            },
64            key_cache: KeyCache::test(),
65        }
66    }
67
68    pub(crate) fn test_limited(
69        stream: tokio::io::DuplexStream,
70        max_burst_bytes: u32,
71        bytes_per_second: u32,
72    ) -> Result<(Self, watch::Receiver<u64>), InvalidBucketConfig> {
73        let stream = MaybeTlsStream::Test(stream);
74        let stream = RateLimited::new(
75            stream,
76            max_burst_bytes,
77            bytes_per_second,
78            Arc::new(Metrics::default()),
79        )?;
80        let limited_watcher = stream.limited_watcher();
81        let stream = Self {
82            inner: WsBytesFramed {
83                io: tokio_websockets::ServerBuilder::new()
84                    .limits(Self::limits())
85                    .serve(stream),
86            },
87            key_cache: KeyCache::test(),
88        };
89        Ok((stream, limited_watcher))
90    }
91
92    fn limits() -> tokio_websockets::Limits {
93        tokio_websockets::Limits::default()
94            .max_payload_len(Some(crate::protos::relay::MAX_FRAME_SIZE))
95    }
96}
97
98/// Relay send errors
99#[stack_error(derive, add_meta)]
100#[non_exhaustive]
101pub enum SendError {
102    /// Error from the underlying WebSocket stream
103    #[error(transparent)]
104    StreamError {
105        #[error(from, std_err)]
106        /// The underlying stream error
107        source: StreamError,
108    },
109    /// Packet size exceeds the maximum allowed size
110    #[error("Packet exceeds max packet size")]
111    ExceedsMaxPacketSize {
112        /// The size of the packet that was too large
113        size: usize,
114    },
115    /// Attempt to send an empty packet
116    ///
117    /// Deprecated: no longer returned. Will be marked `#[deprecated]` in the next minor release.
118    #[error("Attempted to send empty packet")]
119    EmptyPacket {},
120}
121
122impl<S> Sink<RelayToClientMsg> for RelayedStream<S>
123where
124    S: Sink<bytes::Bytes, Error = StreamError> + Unpin,
125{
126    type Error = SendError;
127
128    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
129        Pin::new(&mut self.inner).poll_ready(cx).map_err(Into::into)
130    }
131
132    fn start_send(mut self: Pin<&mut Self>, item: RelayToClientMsg) -> Result<(), Self::Error> {
133        let size = item.encoded_len();
134        ensure!(
135            size <= MAX_PACKET_SIZE,
136            SendError::ExceedsMaxPacketSize { size }
137        );
138
139        Pin::new(&mut self.inner)
140            .start_send(item.to_bytes().freeze())
141            .map_err(Into::into)
142    }
143
144    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
145        Pin::new(&mut self.inner).poll_flush(cx).map_err(Into::into)
146    }
147
148    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
149        Pin::new(&mut self.inner).poll_close(cx).map_err(Into::into)
150    }
151}
152
153/// Relay receive errors
154#[stack_error(derive, add_meta, from_sources)]
155#[non_exhaustive]
156pub enum RecvError {
157    /// Error decoding the relay protocol message
158    #[error(transparent)]
159    Proto {
160        /// The protocol decoding error
161        source: ProtoError,
162    },
163    /// Error from the underlying WebSocket stream
164    #[error(transparent)]
165    StreamError {
166        #[error(std_err)]
167        /// The underlying stream error
168        source: StreamError,
169    },
170}
171
172impl<S> Stream for RelayedStream<S>
173where
174    S: Stream<Item = Result<bytes::Bytes, StreamError>> + Unpin,
175{
176    type Item = Result<ClientToRelayMsg, RecvError>;
177
178    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
179        Poll::Ready(match ready!(Pin::new(&mut self.inner).poll_next(cx)) {
180            Some(Ok(msg)) => {
181                Some(ClientToRelayMsg::from_bytes(msg, &self.key_cache).map_err(Into::into))
182            }
183            Some(Err(e)) => Some(Err(e.into())),
184            None => None,
185        })
186    }
187}
188
189/// The main underlying IO stream type used for the relay server.
190///
191/// Allows choosing whether or not the underlying [`tokio::net::TcpStream`] is served over TLS.
192#[derive(Debug)]
193#[allow(clippy::large_enum_variant)]
194#[non_exhaustive]
195pub enum MaybeTlsStream {
196    /// A plain non-Tls [`tokio::net::TcpStream`]
197    Plain(tokio::net::TcpStream),
198    /// A Tls wrapped [`tokio::net::TcpStream`]
199    Tls(tokio_rustls::server::TlsStream<tokio::net::TcpStream>),
200    /// An in-memory bidirectional pipe.
201    #[cfg(test)]
202    Test(tokio::io::DuplexStream),
203}
204
205impl MaybeTlsStream {
206    /// Tries to disable the nagle algorithm on the TCP stream.
207    ///
208    /// This sets the NO_DELAY option on the TCP stream, which turns off the
209    /// nagle algorithm for coalecing writes together.
210    ///
211    /// If this fails, this will print a warning the first time it fails.
212    pub(super) fn disable_nagle(&self) {
213        let stream = match self {
214            #[cfg(test)]
215            Self::Test(_) => return,
216            Self::Plain(stream) => stream,
217            Self::Tls(tls_stream) => tls_stream.get_ref().0,
218        };
219
220        if stream.set_nodelay(true).is_err() {
221            use std::sync::atomic::Ordering::Relaxed;
222
223            static FAILED_NO_DELAY: AtomicBool = AtomicBool::new(false);
224            if !FAILED_NO_DELAY.swap(true, Relaxed) {
225                warn!(
226                    "Failed to set TCP socket to NO_DELAY (turning off Nagle failed). This will impair relay performance."
227                );
228            }
229        }
230    }
231}
232
233impl ExportKeyingMaterial for MaybeTlsStream {
234    fn export_keying_material<T: AsMut<[u8]>>(
235        &self,
236        output: T,
237        label: &[u8],
238        context: Option<&[u8]>,
239    ) -> Option<T> {
240        let Self::Tls(tls) = self else {
241            return None;
242        };
243
244        tls.get_ref()
245            .1
246            .export_keying_material(output, label, context)
247            .ok()
248    }
249}
250
251impl AsyncRead for MaybeTlsStream {
252    fn poll_read(
253        mut self: Pin<&mut Self>,
254        cx: &mut Context<'_>,
255        buf: &mut tokio::io::ReadBuf<'_>,
256    ) -> Poll<std::io::Result<()>> {
257        match &mut *self {
258            MaybeTlsStream::Plain(s) => Pin::new(s).poll_read(cx, buf),
259            MaybeTlsStream::Tls(s) => Pin::new(s).poll_read(cx, buf),
260            #[cfg(test)]
261            MaybeTlsStream::Test(s) => Pin::new(s).poll_read(cx, buf),
262        }
263    }
264}
265
266impl AsyncWrite for MaybeTlsStream {
267    fn poll_flush(
268        mut self: Pin<&mut Self>,
269        cx: &mut Context<'_>,
270    ) -> Poll<std::result::Result<(), std::io::Error>> {
271        match &mut *self {
272            MaybeTlsStream::Plain(s) => Pin::new(s).poll_flush(cx),
273            MaybeTlsStream::Tls(s) => Pin::new(s).poll_flush(cx),
274            #[cfg(test)]
275            MaybeTlsStream::Test(s) => Pin::new(s).poll_flush(cx),
276        }
277    }
278
279    fn poll_shutdown(
280        mut self: Pin<&mut Self>,
281        cx: &mut Context<'_>,
282    ) -> Poll<std::result::Result<(), std::io::Error>> {
283        match &mut *self {
284            MaybeTlsStream::Plain(s) => Pin::new(s).poll_shutdown(cx),
285            MaybeTlsStream::Tls(s) => Pin::new(s).poll_shutdown(cx),
286            #[cfg(test)]
287            MaybeTlsStream::Test(s) => Pin::new(s).poll_shutdown(cx),
288        }
289    }
290
291    fn poll_write(
292        mut self: Pin<&mut Self>,
293        cx: &mut Context<'_>,
294        buf: &[u8],
295    ) -> Poll<std::result::Result<usize, std::io::Error>> {
296        match &mut *self {
297            MaybeTlsStream::Plain(s) => Pin::new(s).poll_write(cx, buf),
298            MaybeTlsStream::Tls(s) => Pin::new(s).poll_write(cx, buf),
299            #[cfg(test)]
300            MaybeTlsStream::Test(s) => Pin::new(s).poll_write(cx, buf),
301        }
302    }
303
304    fn poll_write_vectored(
305        mut self: Pin<&mut Self>,
306        cx: &mut Context<'_>,
307        bufs: &[std::io::IoSlice<'_>],
308    ) -> Poll<std::result::Result<usize, std::io::Error>> {
309        match &mut *self {
310            MaybeTlsStream::Plain(s) => Pin::new(s).poll_write_vectored(cx, bufs),
311            MaybeTlsStream::Tls(s) => Pin::new(s).poll_write_vectored(cx, bufs),
312            #[cfg(test)]
313            MaybeTlsStream::Test(s) => Pin::new(s).poll_write_vectored(cx, bufs),
314        }
315    }
316
317    fn is_write_vectored(&self) -> bool {
318        match self {
319            MaybeTlsStream::Plain(s) => s.is_write_vectored(),
320            MaybeTlsStream::Tls(s) => s.is_write_vectored(),
321            #[cfg(test)]
322            MaybeTlsStream::Test(s) => s.is_write_vectored(),
323        }
324    }
325}
326
327/// Rate limiter for reading from a [`RelayedStream`].
328///
329/// The writes to the sink are not rate limited.
330///
331/// This potentially buffers one frame if the rate limiter does not allow this frame.
332/// While the frame is buffered the underlying stream is no longer polled.
333#[derive(Debug)]
334pub(crate) struct RateLimited<S> {
335    inner: S,
336    bucket: Option<Bucket>,
337    bucket_refilled: Option<Pin<Box<time::Sleep>>>,
338    /// Counts how often reads from this stream have been rate-limited.
339    ///
340    /// Subscribe via [`RateLimited::limited_watcher`] to be notified about it, e.g. to
341    /// inform the client that it is being throttled.
342    limited_tx: watch::Sender<u64>,
343    /// Watcher for the per-client rate limit, if set.
344    ///
345    /// If set by constructing via [`RateLimited::from_watcher`], we check for
346    /// updates on each poll and reconfigure [`Self::bucket`] on changes.
347    ///
348    /// Uses `tokio::sync::watch` and not `n0_watcher` because in tokio's watch channel,
349    /// checking if a value changed is a cheap atomic version compare, whereas `n0_watcher`
350    /// acquires a `ReadLock` for each change check. This matters because we need to check this
351    /// on each read poll.
352    rate_limit_watcher: Option<watch::Receiver<Option<ClientRateLimit>>>,
353    metrics: Arc<Metrics>,
354}
355
356/// A token bucket used for rate-limiting.
357///
358/// The bucket holds up to `max` tokens, refilled at a fixed rate of
359/// `bytes_per_second` over `refill_period` intervals. [`Bucket::consume`] drains
360/// tokens and reports when the next attempt is allowed.
361///
362/// Exposed so that embedders mounting the relay protocol on a custom HTTP
363/// server (where the stream is already framed and the internal
364/// `RateLimited` wrapper cannot be used) can apply the same rate-limit
365/// semantics at the frame layer.
366#[derive(Debug)]
367pub struct Bucket {
368    // The current bucket fill
369    fill: i64,
370    // The maximum bucket fill
371    max: i64,
372    // The bucket's last fill time
373    last_fill: time::Instant,
374    // Interval length of one refill
375    refill_period: time::Duration,
376    // How much we re-fill per refill period
377    refill: i64,
378}
379
380#[allow(missing_docs)]
381#[stack_error(derive, add_meta)]
382pub struct InvalidBucketConfig {
383    max: i64,
384    bytes_per_second: i64,
385    refill_period: time::Duration,
386}
387
388impl Bucket {
389    /// Creates a new bucket starting full at `max` tokens, refilled at
390    /// `bytes_per_second` over `refill_period` intervals.
391    ///
392    /// # Errors
393    ///
394    /// Returns [`InvalidBucketConfig`] when `max`, `bytes_per_second`, or
395    /// `refill_period` are non-positive, or when the configuration would refill
396    /// less than one token per period.
397    pub fn new(
398        max: i64,
399        bytes_per_second: i64,
400        refill_period: time::Duration,
401    ) -> Result<Self, InvalidBucketConfig> {
402        // milliseconds is the tokio timer resolution
403        let refill = bytes_per_second.saturating_mul(refill_period.as_millis() as i64) / 1000;
404        ensure!(
405            max > 0 && bytes_per_second > 0 && refill_period.as_millis() as u32 > 0 && refill > 0,
406            InvalidBucketConfig {
407                max,
408                bytes_per_second,
409                refill_period
410            }
411        );
412        Ok(Self {
413            fill: max,
414            max,
415            last_fill: time::Instant::now(),
416            refill_period,
417            refill,
418        })
419    }
420
421    fn from_config(cfg: Option<ClientRateLimit>) -> Result<Option<Self>, InvalidBucketConfig> {
422        match cfg {
423            Some(cfg) => {
424                let bytes_per_second = u32::from(cfg.bytes_per_second);
425                let max_burst_bytes = cfg.max_burst_bytes.map_or(bytes_per_second / 10, u32::from);
426                Ok(Some(Bucket::new(
427                    max_burst_bytes as i64,
428                    bytes_per_second as i64,
429                    time::Duration::from_millis(100),
430                )?))
431            }
432            None => Ok(None),
433        }
434    }
435
436    fn update_state(&mut self) {
437        let now = time::Instant::now();
438        // div safety: self.refill_period.as_millis() is checked to be non-null in constructor
439        let refill_periods = now.saturating_duration_since(self.last_fill).as_millis() as u32
440            / self.refill_period.as_millis() as u32;
441        if refill_periods == 0 {
442            // Nothing to do - we won't refill yet
443            return;
444        }
445
446        self.fill = self
447            .fill
448            .saturating_add(refill_periods as i64 * self.refill);
449        self.fill = std::cmp::min(self.fill, self.max);
450        self.last_fill += self.refill_period * refill_periods;
451    }
452
453    /// Attempts to consume `bytes` tokens from the bucket.
454    ///
455    /// Returns `Ok(())` if enough tokens were available.
456    ///
457    /// # Errors
458    ///
459    /// Returns `Err(deadline)` with the [`time::Instant`] at which enough
460    /// tokens will have refilled to allow the request.
461    pub fn consume(&mut self, bytes: usize) -> Result<(), time::Instant> {
462        let bytes = i64::try_from(bytes).unwrap_or(i64::MAX);
463        self.update_state();
464
465        self.fill = self.fill.saturating_sub(bytes);
466
467        if self.fill > 0 {
468            return Ok(());
469        }
470
471        let missing = self.fill.saturating_neg();
472
473        let periods_needed = (missing / self.refill) + 1;
474        let periods_needed = u32::try_from(periods_needed).unwrap_or(u32::MAX);
475
476        Err(self.last_fill + periods_needed * self.refill_period)
477    }
478}
479
480impl<S> RateLimited<S> {
481    /// Wraps `io` with a live rate limit driven by `rate_limit_watcher`.
482    ///
483    /// The bucket is initialized from the watcher's current value and reconfigured
484    /// whenever it changes.
485    pub(crate) fn from_watcher(
486        io: S,
487        mut rate_limit_watcher: watch::Receiver<Option<ClientRateLimit>>,
488        metrics: Arc<Metrics>,
489    ) -> Result<Self, InvalidBucketConfig> {
490        let initial_cfg = *rate_limit_watcher.borrow_and_update();
491        let bucket = Bucket::from_config(initial_cfg)?;
492        Ok(Self {
493            inner: io,
494            bucket,
495            bucket_refilled: None,
496            limited_tx: watch::Sender::new(0),
497            rate_limit_watcher: Some(rate_limit_watcher),
498            metrics,
499        })
500    }
501
502    #[cfg(test)]
503    pub(crate) fn new(
504        inner: S,
505        max_burst_bytes: u32,
506        bytes_per_second: u32,
507        metrics: Arc<Metrics>,
508    ) -> Result<Self, InvalidBucketConfig> {
509        Ok(Self {
510            inner,
511            bucket: Some(Bucket::new(
512                max_burst_bytes as i64,
513                bytes_per_second as i64,
514                time::Duration::from_millis(100),
515            )?),
516            bucket_refilled: None,
517            limited_tx: watch::Sender::new(0),
518            rate_limit_watcher: None,
519            metrics,
520        })
521    }
522
523    #[cfg(test)]
524    pub(crate) fn unlimited(inner: S, metrics: Arc<Metrics>) -> Self {
525        Self {
526            inner,
527            bucket: None,
528            bucket_refilled: None,
529            limited_tx: watch::Sender::new(0),
530            rate_limit_watcher: None,
531            metrics,
532        }
533    }
534
535    /// Returns a watcher that counts how often reads from this stream have been rate-limited.
536    pub(crate) fn limited_watcher(&self) -> watch::Receiver<u64> {
537        self.limited_tx.subscribe()
538    }
539
540    /// Records metrics about being rate-limited.
541    fn record_rate_limited(&mut self, bytes: usize) {
542        // TODO: add a label for the frame type.
543        self.metrics.bytes_rx_ratelimited_total.inc_by(bytes as u64);
544        self.limited_tx.send_modify(|count| {
545            if *count == 0 {
546                self.metrics.conns_rx_ratelimited_total.inc();
547            }
548            *count += 1;
549        });
550    }
551}
552
553impl<S: ExportKeyingMaterial> ExportKeyingMaterial for RateLimited<S> {
554    fn export_keying_material<T: AsMut<[u8]>>(
555        &self,
556        output: T,
557        label: &[u8],
558        context: Option<&[u8]>,
559    ) -> Option<T> {
560        self.inner.export_keying_material(output, label, context)
561    }
562}
563
564impl<S: AsyncRead + Unpin> AsyncRead for RateLimited<S> {
565    #[instrument(name = "rate_limited_poll_read", skip_all)]
566    fn poll_read(
567        mut self: Pin<&mut Self>,
568        cx: &mut std::task::Context<'_>,
569        buf: &mut tokio::io::ReadBuf<'_>,
570    ) -> Poll<std::io::Result<()>> {
571        let this = &mut *self;
572
573        // Pick up a live rate change before consulting the bucket. `has_changed`
574        // is a cheap atomic version compare, so we only take the watch lock via
575        // `borrow_and_update` when the value actually changed.
576        if let Some(rate_limit_watcher) = this.rate_limit_watcher.as_mut()
577            && rate_limit_watcher.has_changed().unwrap_or(false)
578        {
579            let cfg = rate_limit_watcher.borrow_and_update();
580            match Bucket::from_config(*cfg) {
581                Ok(bucket) => {
582                    this.bucket = bucket;
583                    // The limit changed, so drop any pending refill wait: the new
584                    // bucket starts full and should be consulted immediately.
585                    this.bucket_refilled = None;
586                }
587                Err(err) => warn!(%err, "ignoring invalid live rate-limit update"),
588            }
589        }
590
591        let Some(bucket) = &mut this.bucket else {
592            // If there is no rate-limiter, then directly poll the inner.
593            return Pin::new(&mut this.inner).poll_read(cx, buf);
594        };
595
596        // If we're currently limited, wait until we've got some bucket space again
597        if let Some(bucket_refilled) = &mut this.bucket_refilled {
598            ready!(bucket_refilled.poll(cx));
599            this.bucket_refilled = None;
600        }
601
602        // We're not currently limited, let's read
603
604        // Poll inner for a new item.
605        let bytes_before = buf.remaining();
606        ready!(Pin::new(&mut this.inner).poll_read(cx, buf))?;
607        let bytes_read = bytes_before - buf.remaining();
608
609        // Record how much we've read, rate limit accordingly, if need be.
610        if let Err(refill_time) = bucket.consume(bytes_read) {
611            this.record_rate_limited(bytes_read);
612            this.bucket_refilled = Some(Box::pin(time::sleep_until(refill_time)));
613        }
614
615        Poll::Ready(Ok(()))
616    }
617}
618
619impl<S: AsyncWrite + Unpin> AsyncWrite for RateLimited<S> {
620    fn poll_write(
621        mut self: Pin<&mut Self>,
622        cx: &mut std::task::Context<'_>,
623        buf: &[u8],
624    ) -> Poll<Result<usize, std::io::Error>> {
625        Pin::new(&mut self.inner).poll_write(cx, buf)
626    }
627
628    fn poll_flush(
629        mut self: Pin<&mut Self>,
630        cx: &mut std::task::Context<'_>,
631    ) -> Poll<Result<(), std::io::Error>> {
632        Pin::new(&mut self.inner).poll_flush(cx)
633    }
634
635    fn poll_shutdown(
636        mut self: Pin<&mut Self>,
637        cx: &mut std::task::Context<'_>,
638    ) -> Poll<Result<(), std::io::Error>> {
639        Pin::new(&mut self.inner).poll_shutdown(cx)
640    }
641}
642
643#[cfg(test)]
644mod tests {
645    use std::sync::Arc;
646
647    use n0_error::{Result, StdResultExt};
648    use n0_future::time;
649    use n0_tracing_test::traced_test;
650    use tokio::io::{AsyncReadExt, AsyncWriteExt};
651
652    use super::Bucket;
653    use crate::server::{Metrics, streams::RateLimited};
654
655    #[tokio::test(start_paused = true)]
656    #[traced_test]
657    async fn test_ratelimiter() -> Result {
658        let (read, mut write) = tokio::io::duplex(4096);
659
660        let send_total = 10 * 1024 * 1024; // 10MiB
661        let send_data = vec![42u8; send_total];
662
663        let bytes_per_second = 12_345;
664
665        let mut rate_limited = RateLimited::new(
666            read,
667            bytes_per_second / 10,
668            bytes_per_second,
669            Arc::new(Metrics::default()),
670        )?;
671
672        let before = time::Instant::now();
673        n0_future::future::try_zip(
674            async {
675                let mut remaining = send_total;
676                let mut buf = [0u8; 4096];
677                while remaining > 0 {
678                    remaining -= rate_limited.read(&mut buf).await?;
679                }
680                Ok(())
681            },
682            async {
683                write.write_all(&send_data).await?;
684                write.flush().await
685            },
686        )
687        .await
688        .anyerr()?;
689
690        let duration = time::Instant::now().duration_since(before);
691        assert_ne!(duration.as_millis(), 0);
692
693        let actual_bytes_per_second = send_total as f64 / duration.as_secs_f64();
694        println!("{actual_bytes_per_second}");
695        assert_eq!(actual_bytes_per_second.round() as u32, bytes_per_second);
696
697        Ok(())
698    }
699
700    /// A rate limit installed live through the watch channel takes effect on an
701    /// existing stream without dropping it: the connection first reads a chunk
702    /// unlimited at full speed, then a limit is pushed mid-connection and the
703    /// throughput of the remainder matches the limit.
704    #[tokio::test(start_paused = true)]
705    #[traced_test]
706    async fn test_ratelimiter_live_update() -> Result {
707        use crate::server::ClientRateLimit;
708
709        let (read, mut write) = tokio::io::duplex(4096);
710
711        let bytes_per_second = 12_345u32;
712
713        // Read this much at full speed before the limit is installed, then read
714        // exactly 10MiB under the live limit and time only that second phase.
715        let unlimited_total = 1024 * 1024; // 1MiB
716        let limited_total = 10 * 1024 * 1024; // 10MiB
717        let send_data = vec![42u8; unlimited_total + limited_total];
718
719        // Start unlimited; the limit is installed mid-connection below.
720        let (rate_tx, rate_rx) = tokio::sync::watch::channel(None);
721        let mut rate_limited =
722            RateLimited::from_watcher(read, rate_rx, Arc::new(Metrics::default()))?;
723        let mut limit = ClientRateLimit::new(bytes_per_second.try_into().anyerr()?);
724        limit.max_burst_bytes = Some((bytes_per_second / 10).try_into().anyerr()?);
725
726        let mut unlimited_duration = time::Duration::ZERO;
727        let mut limited_duration = time::Duration::ZERO;
728        n0_future::future::try_zip(
729            async {
730                let mut buf = [0u8; 4096];
731
732                // Phase 1: no limit installed yet, pull bytes at full speed.
733                let before = time::Instant::now();
734                let mut remaining = unlimited_total;
735                while remaining > 0 {
736                    let len = remaining.min(buf.len());
737                    let n = rate_limited.read(&mut buf[..len]).await?;
738                    remaining -= n;
739                }
740                unlimited_duration = time::Instant::now().duration_since(before);
741
742                // Install the limit live, mid-connection, without dropping the stream.
743                rate_tx.send_replace(Some(limit));
744
745                // Phase 2: the limit is now in effect, time the remainder.
746                let before = time::Instant::now();
747                let mut remaining = limited_total;
748                while remaining > 0 {
749                    let len = remaining.min(buf.len());
750                    let n = rate_limited.read(&mut buf[..len]).await?;
751                    remaining -= n;
752                }
753                limited_duration = time::Instant::now().duration_since(before);
754                Ok(())
755            },
756            async {
757                write.write_all(&send_data).await?;
758                write.flush().await
759            },
760        )
761        .await
762        .anyerr()?;
763
764        // The unlimited phase is not throttled, so no (virtual) time passes.
765        assert_eq!(
766            unlimited_duration.as_millis(),
767            0,
768            "reading before the limit is installed runs at full speed",
769        );
770
771        let actual_bytes_per_second = limited_total as f64 / limited_duration.as_secs_f64();
772        assert_eq!(
773            actual_bytes_per_second.round() as u32,
774            bytes_per_second,
775            "the live-installed limit governs throughput once applied mid-connection",
776        );
777
778        Ok(())
779    }
780
781    #[tokio::test(start_paused = true)]
782    async fn test_bucket_high_refill() -> Result {
783        let bytes_per_second = i64::MAX;
784        let mut bucket = Bucket::new(i64::MAX, bytes_per_second, time::Duration::from_millis(100))?;
785        for _ in 0..100 {
786            time::sleep(time::Duration::from_millis(100)).await;
787            assert!(bucket.consume(1_000_000).is_ok());
788        }
789
790        Ok(())
791    }
792
793    #[tokio::test(start_paused = true)]
794    async fn smoke_test_bucket_high_consume() -> Result {
795        let bytes_per_second = 123_456;
796        let mut bucket = Bucket::new(
797            bytes_per_second / 10,
798            bytes_per_second,
799            time::Duration::from_millis(100),
800        )?;
801        for _ in 0..100 {
802            let Err(until) = bucket.consume(usize::MAX) else {
803                panic!("i64::MAX shouldn't be within limits");
804            };
805            time::sleep_until(until).await;
806        }
807
808        Ok(())
809    }
810}