1use 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#[derive(Debug)]
34pub struct RelayedStream<S> {
35 pub(crate) inner: S,
36 pub(crate) key_cache: KeyCache,
37}
38
39impl<S> RelayedStream<S> {
40 pub fn new(inner: S, key_cache: KeyCache) -> Self {
45 Self { inner, key_cache }
46 }
47}
48
49#[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::new(
60 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::new(
83 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#[stack_error(derive, add_meta)]
100#[non_exhaustive]
101pub enum SendError {
102 #[error(transparent)]
104 StreamError {
105 #[error(from, std_err)]
106 source: StreamError,
108 },
109 #[error("Packet exceeds max packet size")]
111 ExceedsMaxPacketSize {
112 size: usize,
114 },
115 #[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#[stack_error(derive, add_meta, from_sources)]
155#[non_exhaustive]
156pub enum RecvError {
157 #[error(transparent)]
159 Proto {
160 source: ProtoError,
162 },
163 #[error(transparent)]
165 StreamError {
166 #[error(std_err)]
167 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#[derive(Debug)]
193#[allow(clippy::large_enum_variant)]
194#[non_exhaustive]
195pub enum MaybeTlsStream {
196 Plain(tokio::net::TcpStream),
198 Tls(tokio_rustls::server::TlsStream<tokio::net::TcpStream>),
200 #[cfg(test)]
202 Test(tokio::io::DuplexStream),
203}
204
205impl MaybeTlsStream {
206 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#[derive(Debug)]
334pub(crate) struct RateLimited<S> {
335 inner: S,
336 bucket: Option<Bucket>,
337 bucket_refilled: Option<Pin<Box<time::Sleep>>>,
338 limited_tx: watch::Sender<u64>,
343 rate_limit_watcher: Option<watch::Receiver<Option<ClientRateLimit>>>,
353 metrics: Arc<Metrics>,
354}
355
356#[derive(Debug)]
367pub struct Bucket {
368 fill: i64,
370 max: i64,
372 last_fill: time::Instant,
374 refill_period: time::Duration,
376 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 pub fn new(
398 max: i64,
399 bytes_per_second: i64,
400 refill_period: time::Duration,
401 ) -> Result<Self, InvalidBucketConfig> {
402 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 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 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 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 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 pub(crate) fn limited_watcher(&self) -> watch::Receiver<u64> {
537 self.limited_tx.subscribe()
538 }
539
540 fn record_rate_limited(&mut self, bytes: usize) {
542 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 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 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 return Pin::new(&mut this.inner).poll_read(cx, buf);
594 };
595
596 if let Some(bucket_refilled) = &mut this.bucket_refilled {
598 ready!(bucket_refilled.poll(cx));
599 this.bucket_refilled = None;
600 }
601
602 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 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::{StreamExt, time};
649 use n0_tracing_test::traced_test;
650 use tokio::io::{AsyncReadExt, AsyncWriteExt};
651
652 use super::{Bucket, ServerRelayedStream};
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; 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 #[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 let unlimited_total = 1024 * 1024; let limited_total = 10 * 1024 * 1024; let send_data = vec![42u8; unlimited_total + limited_total];
718
719 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 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 rate_tx.send_replace(Some(limit));
744
745 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 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
811 #[tokio::test(start_paused = true)]
812 async fn unread_pongs_hold_back_further_pings() {
813 let (local, mut remote) = tokio::io::duplex(64);
814 let mut local = ServerRelayedStream::test(local);
815
816 let pings = [0x89, 0x80, 0, 0, 0, 0].repeat(10_000);
817 let timed_out = time::timeout(time::Duration::from_secs(60), async {
818 tokio::select! {
819 _ = local.next() => (),
820 _ = remote.write_all(&pings) => (),
821 }
822 })
823 .await
824 .is_err();
825 assert!(
826 timed_out,
827 "relay read or peer write completed before the timeout"
828 );
829 }
830}