iroh_relay/server/
client.rs

1//! The server-side representation of an ongoing client relaying connection.
2
3use std::{collections::HashSet, sync::Arc, time::Duration};
4
5use iroh_base::EndpointId;
6use n0_error::{e, stack_error};
7use n0_future::{SinkExt, StreamExt};
8use rand::RngExt;
9use time::{Date, OffsetDateTime};
10use tokio::{
11    sync::{
12        mpsc::{self, error::TrySendError},
13        watch,
14    },
15    time::MissedTickBehavior,
16};
17use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
18use tracing::{Instrument, debug, trace, warn};
19
20use crate::{
21    PingTracker,
22    defaults::timeouts::SERVER_WRITE_TIMEOUT,
23    http::ProtocolVersion,
24    protos::{
25        relay::{
26            ClientToRelayMsg, Datagrams, PER_CLIENT_SEND_QUEUE_DEPTH, PING_INTERVAL,
27            RelayToClientMsg, Status,
28        },
29        streams::BytesStreamSink,
30    },
31    server::{
32        ConnectionId, OnDisconnectGuard,
33        clients::Clients,
34        metrics::Metrics,
35        streams::{RecvError as RelayRecvError, RelayedStream, SendError as RelaySendError},
36    },
37};
38
39/// A request to write a dataframe to a Client
40#[derive(Debug, Clone)]
41pub(super) struct Packet {
42    /// The sender of the packet
43    src: EndpointId,
44    /// The data packet bytes.
45    data: Datagrams,
46}
47
48/// Configuration for a client connection.
49///
50/// Generic over the stream type to support different WebSocket implementations.
51#[derive(Debug)]
52#[non_exhaustive]
53pub struct Config<S> {
54    /// Reports the disconnect once the connection ends.
55    ///
56    /// Also the owner of this connection's [`EndpointId`] and [`ConnectionId`].
57    pub guard: OnDisconnectGuard,
58    /// The relayed stream connection
59    pub stream: RelayedStream<S>,
60    /// Write timeout for the client connection
61    pub write_timeout: Duration,
62    /// Channel capacity for internal message queues
63    pub channel_capacity: usize,
64    /// Protocol version negotiated for this client
65    pub protocol_version: ProtocolVersion,
66    /// Optional signal to inform the client when it is being rate-limited.
67    ///
68    /// When set, the connection actor notifies the client once with a
69    /// [`Status::RateLimited`] message when the rate-limited counter first
70    /// becomes non-zero.
71    pub(crate) rate_limited: Option<watch::Receiver<u64>>,
72}
73
74impl<S> Config<S> {
75    /// Creates a new config with sensible default values for `write_timeout` and `channel_capacity`.
76    ///
77    /// The endpoint and connection ids are taken from `guard`.
78    pub fn new(
79        guard: OnDisconnectGuard,
80        stream: RelayedStream<S>,
81        protocol_version: ProtocolVersion,
82    ) -> Self {
83        Self {
84            guard,
85            stream,
86            protocol_version,
87            write_timeout: SERVER_WRITE_TIMEOUT,
88            channel_capacity: PER_CLIENT_SEND_QUEUE_DEPTH,
89            rate_limited: None,
90        }
91    }
92}
93
94/// The [`Server`] side representation of a [`Client`]'s connection.
95///
96/// [`Server`]: crate::server::Server
97/// [`Client`]: crate::client::Client
98#[derive(Debug)]
99pub(super) struct Client {
100    /// Identity of the connected peer.
101    endpoint_id: EndpointId,
102    /// Connection identifier.
103    connection_id: ConnectionId,
104    /// Used to close the connection loop.
105    done: CancellationToken,
106    /// Actor handle.
107    handle: AbortOnDropHandle<()>,
108    /// Channel to send packets intended for the client.
109    packet_queue: mpsc::Sender<Packet>,
110    /// Channel to send non-packet messages to the client.
111    message_queue: mpsc::Sender<RelayToClientMsg>,
112    /// Relay protocol version negotiated for this client.
113    protocol_version: ProtocolVersion,
114}
115
116impl Client {
117    /// Creates a client from a connection & starts a read and write loop to handle io to and from
118    /// the client
119    ///
120    /// The `guard` is moved into the connection actor and reports the disconnect to access
121    /// control once the connection ends.
122    ///
123    /// Call [`Client::shutdown`] to close the read and write loops before dropping the [`Client`]
124    pub(super) fn new<S>(config: Config<S>, clients: &Clients, metrics: Arc<Metrics>) -> Client
125    where
126        S: BytesStreamSink + Send + 'static,
127    {
128        let Config {
129            guard,
130            stream,
131            write_timeout,
132            channel_capacity,
133            protocol_version,
134            rate_limited,
135        } = config;
136        let endpoint_id = guard.endpoint_id;
137        let connection_id = guard.connection_id;
138
139        let (packet_send_queue_s, packet_send_queue_r) = mpsc::channel(channel_capacity);
140        let (message_send_queue_s, message_send_queue_r) = mpsc::channel(channel_capacity);
141        let done = CancellationToken::new();
142
143        let actor = Actor {
144            stream,
145            timeout: write_timeout,
146            packet_send_queue: packet_send_queue_r,
147            message_send_queue: message_send_queue_r,
148            guard,
149            clients: clients.clone(),
150            client_counter: ClientCounter::default(),
151            ping_tracker: PingTracker::default(),
152            protocol_version,
153            rate_limited,
154            metrics,
155        };
156
157        // start io loop
158        let io_done = done.clone();
159        let handle = tokio::task::spawn(actor.run(io_done).instrument(tracing::info_span!(
160            "client-connection-actor",
161            remote_endpoint = %endpoint_id.fmt_short(),
162            connection_id = %connection_id
163        )));
164
165        Client {
166            endpoint_id,
167            connection_id,
168            handle: AbortOnDropHandle::new(handle),
169            done,
170            packet_queue: packet_send_queue_s,
171            message_queue: message_send_queue_s,
172            protocol_version,
173        }
174    }
175
176    pub(super) fn connection_id(&self) -> ConnectionId {
177        self.connection_id
178    }
179
180    /// Shutdown the reader and writer loops and closes the connection.
181    ///
182    /// Any shutdown errors will be logged as warnings.
183    pub(super) async fn shutdown(self) {
184        self.start_shutdown();
185        if let Err(e) = self.handle.await {
186            warn!(
187                remote_endpoint = %self.endpoint_id.fmt_short(),
188                "error closing actor loop: {e:#?}",
189            );
190        };
191    }
192
193    /// Starts the process of shutdown.
194    pub(super) fn start_shutdown(&self) {
195        self.done.cancel();
196    }
197
198    pub(super) fn try_send_packet(
199        &self,
200        src: EndpointId,
201        data: Datagrams,
202    ) -> Result<(), TrySendError<Packet>> {
203        self.packet_queue.try_send(Packet { src, data })
204    }
205
206    pub(super) fn try_send_peer_gone(
207        &self,
208        key: EndpointId,
209    ) -> Result<(), TrySendError<RelayToClientMsg>> {
210        self.message_queue
211            .try_send(RelayToClientMsg::EndpointGone(key))
212    }
213
214    pub(super) fn try_send_health(
215        &self,
216        status: Status,
217    ) -> Result<(), TrySendError<RelayToClientMsg>> {
218        let message = match self.protocol_version {
219            ProtocolVersion::V2 => RelayToClientMsg::Status(status),
220            ProtocolVersion::V1 => RelayToClientMsg::Health {
221                problem: status.to_string(),
222            },
223        };
224        self.message_queue.try_send(message)
225    }
226}
227
228/// Completes when `rx` observes the connection being rate-limited.
229///
230/// Pends forever when `rx` is `None`, i.e. when no rate-limit signal is configured.
231async fn rate_limited_signal(rx: &mut Option<watch::Receiver<u64>>) -> bool {
232    match rx {
233        Some(rx) => match rx.changed().await {
234            Ok(()) => *rx.borrow_and_update() > 0,
235            // The sender lives inside this actor's stream, so it cannot drop while
236            // the actor runs. Report not limited to be safe.
237            Err(_) => false,
238        },
239        None => std::future::pending().await,
240    }
241}
242
243/// Error when handling an incoming frame from a client.
244#[stack_error(derive, add_meta, from_sources)]
245#[allow(missing_docs)]
246#[non_exhaustive]
247pub enum HandleFrameError {
248    #[error(transparent)]
249    ForwardPacket { source: ForwardPacketError },
250    #[error("Stream terminated")]
251    StreamTerminated {},
252    #[error(transparent)]
253    Recv { source: RelayRecvError },
254    #[error(transparent)]
255    Send { source: WriteFrameError },
256}
257
258/// Error when writing a frame to a client.
259#[stack_error(derive, add_meta, from_sources)]
260#[allow(missing_docs)]
261#[non_exhaustive]
262pub enum WriteFrameError {
263    #[error(transparent)]
264    Stream { source: RelaySendError },
265    #[error(transparent)]
266    Timeout {
267        #[error(std_err)]
268        source: tokio::time::error::Elapsed,
269    },
270}
271
272/// Run error
273#[stack_error(derive, add_meta)]
274#[allow(missing_docs)]
275#[non_exhaustive]
276pub enum RunError {
277    #[error(transparent)]
278    ForwardPacket {
279        #[error(from)]
280        source: ForwardPacketError,
281    },
282    #[error("Flush")]
283    Flush {},
284    #[error(transparent)]
285    HandleFrame {
286        #[error(from)]
287        source: HandleFrameError,
288    },
289    #[error("Failed to send packet")]
290    PacketSend { source: WriteFrameError },
291    #[error("Handle was dropped")]
292    HandleDropped {},
293    #[error("Writing a frame failed")]
294    WriteFrame { source: WriteFrameError },
295    #[error("Tick flush")]
296    TickFlush {},
297}
298
299/// Manages all the reads and writes to this client. It periodically sends a `KEEP_ALIVE`
300/// message to the client to keep the connection alive.
301///
302/// Call `run` to manage the input and output to and from the connection and the server.
303/// Once it hits its first write error or error receiving off a channel,
304/// it errors on return.
305/// If writes do not complete in the given `timeout`, it will also error.
306///
307/// On the "write" side, the [`Actor`] can send the client:
308///  - a KEEP_ALIVE frame
309///  - a PEER_GONE frame to inform the client that a peer they have previously sent messages to
310///    is gone from the network
311///  - packets from other peers
312///
313/// On the "read" side, it can:
314///     - receive a ping and write a pong back
315///     to speak to the endpoint ID associated with that client.
316#[derive(Debug)]
317struct Actor<S> {
318    /// IO Stream to talk to the client
319    stream: RelayedStream<S>,
320    /// Maximum time we wait to complete a write to the client
321    timeout: Duration,
322    /// Receiver for packets to be sent to the client.
323    packet_send_queue: mpsc::Receiver<Packet>,
324    /// Receiver for non-packet messages to be sent to the client.
325    message_send_queue: mpsc::Receiver<RelayToClientMsg>,
326    /// Reports the disconnect to access control when dropped.
327    ///
328    /// Also the owner of this connection's [`EndpointId`] and [`ConnectionId`].
329    guard: OnDisconnectGuard,
330    /// Reference to the other connected clients.
331    clients: Clients,
332    /// Statistics about the connected clients
333    client_counter: ClientCounter,
334    ping_tracker: PingTracker,
335    /// Relay protocol version negotiated for this client.
336    protocol_version: ProtocolVersion,
337    /// Optional signal counting how often the connection has been rate-limited.
338    rate_limited: Option<watch::Receiver<u64>>,
339    metrics: Arc<Metrics>,
340}
341
342impl<S> Actor<S>
343where
344    S: BytesStreamSink,
345{
346    async fn run(mut self, done: CancellationToken) {
347        // Note the accept and disconnects metrics must be in a pair.  Technically the
348        // connection is accepted long before this in the HTTP server, but it is clearer to
349        // handle the metric here.
350        self.metrics.accepts.inc();
351        if self.client_counter.update(self.guard.endpoint_id()) {
352            self.metrics.unique_client_keys.inc();
353        }
354        match self.run_inner(done).await {
355            Err(e) => {
356                warn!("actor errored {e:#}, exiting");
357            }
358            Ok(()) => {
359                debug!("actor finished, exiting");
360            }
361        }
362
363        self.clients.unregister(self.guard, &self.metrics);
364        self.metrics.disconnects.inc();
365    }
366
367    async fn run_inner(&mut self, done: CancellationToken) -> Result<(), RunError> {
368        // Add some jitter to ping pong interactions, to avoid all pings being sent at the same time
369        let next_interval = || {
370            let random_secs = rand::rng().random_range(1..=5);
371            Duration::from_secs(random_secs) + PING_INTERVAL
372        };
373
374        let mut ping_interval = tokio::time::interval(next_interval());
375        // ticks immediately
376        ping_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
377        ping_interval.tick().await;
378
379        let mut rate_limit_notified = false;
380
381        loop {
382            tokio::select! {
383                biased;
384
385                _ = done.cancelled() => {
386                    trace!("actor loop cancelled, exiting");
387                    // final flush
388                    self.flush().await.map_err(|_| e!(RunError::Flush))?;
389                    break;
390                }
391                limited = rate_limited_signal(&mut self.rate_limited), if !rate_limit_notified => {
392                    // Notify the client once per connection.
393                    // V1 clients are not notified.
394                    rate_limit_notified = true;
395                    if limited && self.protocol_version == ProtocolVersion::V2 {
396                        debug!("connection is rate-limited, notifying client");
397                        self.write_frame(RelayToClientMsg::Status(Status::RateLimited))
398                            .await
399                            .map_err(|err| e!(RunError::WriteFrame, err))?;
400                    }
401                }
402                maybe_frame = self.stream.next() => {
403                    self
404                        .handle_frame(maybe_frame)
405                        .await?;
406                    // reset the ping interval, we just received a message
407                    ping_interval.reset();
408                }
409                // Second priority, sending regular packets
410                packet = self.packet_send_queue.recv() => {
411                    let packet = packet.ok_or_else(|| e!(RunError::HandleDropped))?;
412                    self.send_packet(packet)
413                        .await
414                        .map_err(|err| e!(RunError::PacketSend, err))?;
415                }
416                // Last priority, sending other message
417                message = self.message_send_queue.recv() => {
418                    let message = message.ok_or_else(|| e!(RunError::HandleDropped))?;
419                    trace!("send {message:?}");
420                    self.write_frame(message)
421                        .await
422                        .map_err(|err| e!(RunError::WriteFrame, err))?;
423                }
424                _ = self.ping_tracker.timeout() => {
425                    trace!("pong timed out");
426                    break;
427                }
428                _ = ping_interval.tick() => {
429                    trace!("keep alive ping");
430                    // new interval
431                    ping_interval.reset_after(next_interval());
432                    let data = self.ping_tracker.new_ping();
433                    self.write_frame(RelayToClientMsg::Ping(data))
434                        .await
435                        .map_err(|err| e!(RunError::WriteFrame, err))?;
436                }
437            }
438
439            self.flush().await.map_err(|_| e!(RunError::TickFlush))?;
440        }
441        Ok(())
442    }
443
444    /// Writes the given frame to the connection.
445    ///
446    /// Errors if the send does not happen within the `timeout` duration
447    async fn write_frame(&mut self, frame: RelayToClientMsg) -> Result<(), WriteFrameError> {
448        tokio::time::timeout(self.timeout, self.stream.send(frame)).await??;
449        Ok(())
450    }
451
452    /// Flushes the connection.
453    ///
454    /// Errors if the flush does not happen within the `timeout` duration
455    async fn flush(&mut self) -> Result<(), WriteFrameError> {
456        tokio::time::timeout(self.timeout, self.stream.flush()).await??;
457        Ok(())
458    }
459
460    /// Writes contents to the client in a `RECV_PACKET` frame.
461    ///
462    /// Errors if the send does not happen within the `timeout` duration
463    /// Does not flush.
464    async fn send_raw(&mut self, packet: Packet) -> Result<(), WriteFrameError> {
465        let remote_endpoint_id = packet.src;
466        let datagrams = packet.data;
467
468        if let Ok(len) = datagrams.contents.len().try_into() {
469            self.metrics.bytes_sent.inc_by(len);
470        }
471        self.write_frame(RelayToClientMsg::Datagrams {
472            remote_endpoint_id,
473            datagrams,
474        })
475        .await
476    }
477
478    async fn send_packet(&mut self, packet: Packet) -> Result<(), WriteFrameError> {
479        trace!("send packet");
480        match self.send_raw(packet).await {
481            Ok(()) => {
482                self.metrics.send_packets_sent.inc();
483                Ok(())
484            }
485            // If a packet exceeds the max packet size, that is an issue
486            // with the sender, not the receiver. Don't drop the connection
487            // to the receiver, just drop the packet.
488            Err(WriteFrameError::Stream {
489                source: RelaySendError::ExceedsMaxPacketSize { size, .. },
490                ..
491            }) => {
492                debug!(size, "dropping packet: exceeds max packet size");
493                self.metrics.send_packets_dropped.inc();
494                Ok(())
495            }
496            Err(err) => {
497                self.metrics.send_packets_dropped.inc();
498                Err(err)
499            }
500        }
501    }
502
503    /// Handles frame read results.
504    async fn handle_frame(
505        &mut self,
506        maybe_frame: Option<Result<ClientToRelayMsg, RelayRecvError>>,
507    ) -> Result<(), HandleFrameError> {
508        trace!(?maybe_frame, "handle incoming frame");
509        let frame = match maybe_frame {
510            Some(frame) => frame?,
511            None => return Err(e!(HandleFrameError::StreamTerminated)),
512        };
513
514        match frame {
515            ClientToRelayMsg::Datagrams {
516                dst_endpoint_id: dst_key,
517                datagrams,
518            } => {
519                let packet_len = datagrams.contents.len();
520                if let Err(err @ ForwardPacketError { .. }) =
521                    self.handle_frame_send_packet(dst_key, datagrams)
522                {
523                    warn!("failed to handle send packet frame: {err:#}");
524                }
525                self.metrics.bytes_recv.inc_by(packet_len as u64);
526            }
527            ClientToRelayMsg::Ping(data) => {
528                self.metrics.got_ping.inc();
529                // TODO: add rate limiter
530                self.write_frame(RelayToClientMsg::Pong(data)).await?;
531                self.metrics.sent_pong.inc();
532            }
533            ClientToRelayMsg::Pong(data) => {
534                self.ping_tracker.pong_received(data);
535            }
536        }
537        Ok(())
538    }
539
540    fn handle_frame_send_packet(
541        &self,
542        dst: EndpointId,
543        data: Datagrams,
544    ) -> Result<(), ForwardPacketError> {
545        self.metrics.send_packets_recv.inc();
546        self.clients
547            .send_packet(dst, data, self.guard.endpoint_id(), &self.metrics)?;
548
549        Ok(())
550    }
551}
552
553#[derive(Debug)]
554pub(crate) enum SendError {
555    Full,
556    Closed,
557}
558
559/// Error returned when forwarding a packet to a client fails.
560///
561/// This error occurs when the relay server cannot deliver a packet to its intended
562/// recipient, typically due to the client's send queue being full or the client
563/// disconnecting.
564#[stack_error(derive, add_meta)]
565#[error("failed to forward packet: {reason:?}")]
566pub struct ForwardPacketError {
567    reason: SendError,
568}
569
570/// Tracks how many unique endpoints have been seen during the last day.
571#[derive(Debug)]
572struct ClientCounter {
573    clients: HashSet<EndpointId>,
574    last_clear_date: Date,
575}
576
577impl Default for ClientCounter {
578    fn default() -> Self {
579        Self {
580            clients: HashSet::new(),
581            last_clear_date: OffsetDateTime::now_utc().date(),
582        }
583    }
584}
585
586impl ClientCounter {
587    fn check_and_clear(&mut self) {
588        let today = OffsetDateTime::now_utc().date();
589        if today != self.last_clear_date {
590            self.clients.clear();
591            self.last_clear_date = today;
592        }
593    }
594
595    /// Marks this endpoint as seen, returns whether it is new today or not.
596    fn update(&mut self, client: EndpointId) -> bool {
597        self.check_and_clear();
598        self.clients.insert(client)
599    }
600}
601
602#[cfg(test)]
603mod tests {
604    use iroh_base::SecretKey;
605    use n0_error::{Result, StdResultExt, bail_any};
606    use n0_future::Stream;
607    use n0_tracing_test::traced_test;
608    use rand::SeedableRng;
609    use tracing::info;
610
611    use super::*;
612    use crate::{
613        client::conn::Conn,
614        http::ProtocolVersion,
615        protos::{
616            common::FrameType,
617            relay::{MAX_PACKET_SIZE, Status},
618            streams::WsBytesFramed,
619        },
620        server::streams::{MaybeTlsStream, RateLimited, ServerRelayedStream},
621    };
622
623    async fn recv_frame<
624        E: std::error::Error + Sync + Send + 'static,
625        S: Stream<Item = Result<RelayToClientMsg, E>> + Unpin,
626    >(
627        frame_type: FrameType,
628        mut stream: S,
629    ) -> Result<RelayToClientMsg> {
630        match stream.next().await {
631            Some(Ok(frame)) => {
632                if frame_type != frame.typ() {
633                    bail_any!(
634                        "Unexpected frame, got {:?}, but expected {:?}",
635                        frame.typ(),
636                        frame_type
637                    );
638                }
639                Ok(frame)
640            }
641            Some(Err(err)) => Err(err).anyerr(),
642            None => bail_any!("Unexpected EOF, expected frame {frame_type:?}"),
643        }
644    }
645
646    #[tokio::test]
647    #[traced_test]
648    async fn test_client_actor_basic() -> Result {
649        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
650
651        let (send_queue_s, send_queue_r) = mpsc::channel(10);
652        let (message_s, message_r) = mpsc::channel(10);
653
654        let endpoint_id = SecretKey::from_bytes(&rng.random()).public();
655        let (io, io_rw) = tokio::io::duplex(1024);
656        let mut io_rw = Conn::test(io_rw, Default::default());
657        let stream = RelayedStream::test(io);
658
659        let clients = Clients::default();
660        let metrics = Arc::new(Metrics::default());
661        let actor = Actor {
662            stream,
663            timeout: Duration::from_secs(1),
664            packet_send_queue: send_queue_r,
665            message_send_queue: message_r,
666            guard: OnDisconnectGuard::empty(endpoint_id),
667            clients: clients.clone(),
668            client_counter: ClientCounter::default(),
669            ping_tracker: PingTracker::default(),
670            protocol_version: ProtocolVersion::V2,
671            rate_limited: None,
672            metrics,
673        };
674
675        let done = CancellationToken::new();
676        let io_done = done.clone();
677        let handle = tokio::task::spawn(async move { actor.run(io_done).await });
678
679        // Write tests
680        println!("-- write");
681        let data = b"hello world!";
682
683        // send packet
684        println!("  send packet");
685        let packet = Packet {
686            src: endpoint_id,
687            data: Datagrams::from(&data[..]),
688        };
689        send_queue_s
690            .send(packet.clone())
691            .await
692            .std_context("send")?;
693        let frame = recv_frame(FrameType::RelayToClientDatagram, &mut io_rw)
694            .await
695            .anyerr()?;
696        assert_eq!(
697            frame,
698            RelayToClientMsg::Datagrams {
699                remote_endpoint_id: endpoint_id,
700                datagrams: data.to_vec().into()
701            }
702        );
703
704        // send peer_gone
705        println!("send peer gone");
706        message_s
707            .send(RelayToClientMsg::EndpointGone(endpoint_id))
708            .await
709            .std_context("send")?;
710        let frame = recv_frame(FrameType::EndpointGone, &mut io_rw)
711            .await
712            .anyerr()?;
713        assert_eq!(frame, RelayToClientMsg::EndpointGone(endpoint_id));
714
715        // Read tests
716        println!("--read");
717
718        // send ping, expect pong
719        let data = b"pingpong";
720        io_rw.send(ClientToRelayMsg::Ping(*data)).await?;
721
722        // recv pong
723        println!(" recv pong");
724        let frame = recv_frame(FrameType::Pong, &mut io_rw).await?;
725        assert_eq!(frame, RelayToClientMsg::Pong(*data));
726
727        let target = SecretKey::from_bytes(&rng.random()).public();
728
729        // send packet
730        println!("  send packet");
731        let data = b"hello world!";
732        io_rw
733            .send(ClientToRelayMsg::Datagrams {
734                dst_endpoint_id: target,
735                datagrams: Datagrams::from(data),
736            })
737            .await
738            .std_context("send")?;
739
740        done.cancel();
741        handle.await.std_context("join")?;
742        Ok(())
743    }
744
745    fn test_client_builder(
746        key: EndpointId,
747        protocol_version: ProtocolVersion,
748    ) -> (Config<WsBytesFramed<RateLimited<MaybeTlsStream>>>, Conn) {
749        let (server, client) = tokio::io::duplex(1024);
750        let guard = OnDisconnectGuard::empty(key);
751        let mut config = Config::new(guard, ServerRelayedStream::test(server), protocol_version);
752        config.write_timeout = Duration::from_secs(1);
753        config.channel_capacity = 10;
754        (config, Conn::test(client, protocol_version))
755    }
756
757    #[tokio::test(start_paused = true)]
758    #[traced_test]
759    async fn actor_exits_when_client_leaves_pongs_unread() -> Result {
760        let key = SecretKey::from_bytes(&[1u8; 32]).public();
761        let (server, client) = tokio::io::duplex(1024);
762        let mut config = Config::new(
763            OnDisconnectGuard::empty(key),
764            ServerRelayedStream::test(server),
765            ProtocolVersion::V2,
766        );
767        config.write_timeout = Duration::from_secs(1);
768        let clients = Clients::default();
769        let metrics = Arc::new(Metrics::default());
770        clients.register(config, metrics.clone());
771
772        let mut ws = tokio_websockets::ClientBuilder::new().take_over(client);
773        for _ in 0..64 {
774            ws.send(tokio_websockets::Message::ping(vec![0u8; 125]))
775                .await
776                .ok();
777        }
778        let pong = ClientToRelayMsg::Pong([0u8; 8]).to_bytes().freeze();
779        ws.send(tokio_websockets::Message::binary(pong)).await.ok();
780
781        tokio::time::timeout(PING_INTERVAL - Duration::from_secs(1), async {
782            while metrics.disconnects.get() == 0 {
783                tokio::time::sleep(Duration::from_millis(100)).await;
784            }
785        })
786        .await
787        .std_context("actor still running")?;
788
789        clients.shutdown().await;
790        Ok(())
791    }
792
793    #[tokio::test(start_paused = true)]
794    #[traced_test]
795    async fn shutdown_completes_while_client_leaves_pongs_unread() -> Result {
796        let key = SecretKey::from_bytes(&[2u8; 32]).public();
797        let (server, client) = tokio::io::duplex(1024);
798        let mut config = Config::new(
799            OnDisconnectGuard::empty(key),
800            ServerRelayedStream::test(server),
801            ProtocolVersion::V2,
802        );
803        config.write_timeout = Duration::from_secs(1);
804        let clients = Clients::default();
805        let metrics = Arc::new(Metrics::default());
806        clients.register(config, metrics.clone());
807
808        let mut ws = tokio_websockets::ClientBuilder::new().take_over(client);
809        for _ in 0..12 {
810            ws.send(tokio_websockets::Message::ping(vec![0u8; 125]))
811                .await
812                .ok();
813        }
814        tokio::time::sleep(Duration::from_secs(1)).await;
815        assert_eq!(metrics.disconnects.get(), 0);
816
817        tokio::time::timeout(Duration::from_secs(10), clients.shutdown())
818            .await
819            .std_context("shutdown waits on the client")?;
820        Ok(())
821    }
822
823    #[tokio::test]
824    #[traced_test]
825    async fn test_client_v1_protocol() -> Result {
826        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42u64);
827        let a_key = SecretKey::from_bytes(&rng.random()).public();
828        let b_key = SecretKey::from_bytes(&rng.random()).public();
829
830        let (builder_a, mut a_rw) = test_client_builder(a_key, ProtocolVersion::V1);
831
832        let clients = Clients::default();
833        let metrics = Arc::new(Metrics::default());
834        clients.register(builder_a, metrics.clone());
835
836        // Verify basic packet delivery works with V1.
837        let data = b"hello world v1!";
838        clients.send_packet(a_key, Datagrams::from(&data[..]), b_key, &metrics)?;
839        let frame = recv_frame(FrameType::RelayToClientDatagram, &mut a_rw).await?;
840        assert_eq!(
841            frame,
842            RelayToClientMsg::Datagrams {
843                remote_endpoint_id: b_key,
844                datagrams: data.to_vec().into(),
845            }
846        );
847
848        clients.shutdown().await;
849        Ok(())
850    }
851
852    #[tokio::test]
853    #[traced_test]
854    async fn test_client_v2_protocol() -> Result {
855        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42u64);
856        let a_key = SecretKey::from_bytes(&rng.random()).public();
857        let b_key = SecretKey::from_bytes(&rng.random()).public();
858
859        let (builder_a, mut a_rw) = test_client_builder(a_key, ProtocolVersion::V2);
860
861        let clients = Clients::default();
862        let metrics = Arc::new(Metrics::default());
863        clients.register(builder_a, metrics.clone());
864
865        // Verify basic packet delivery works with V2.
866        let data = b"hello world v2!";
867        clients.send_packet(a_key, Datagrams::from(&data[..]), b_key, &metrics)?;
868        let frame = recv_frame(FrameType::RelayToClientDatagram, &mut a_rw).await?;
869        assert_eq!(
870            frame,
871            RelayToClientMsg::Datagrams {
872                remote_endpoint_id: b_key,
873                datagrams: data.to_vec().into(),
874            }
875        );
876
877        clients.shutdown().await;
878        Ok(())
879    }
880
881    /// A packet that cannot be encoded is dropped and the connection stays usable.
882    #[tokio::test]
883    #[traced_test]
884    async fn test_unsendable_packet_is_dropped() -> Result {
885        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42u64);
886        let a_key = SecretKey::from_bytes(&rng.random()).public();
887        let b_key = SecretKey::from_bytes(&rng.random()).public();
888
889        let (builder_a, mut a_rw) = test_client_builder(a_key, ProtocolVersion::V2);
890
891        let clients = Clients::default();
892        let metrics = Arc::new(Metrics::default());
893        clients.register(builder_a, metrics.clone());
894
895        // Does not fit into a frame once the frame header is added.
896        let too_large = vec![0u8; MAX_PACKET_SIZE];
897        clients.send_packet(a_key, Datagrams::from(&too_large[..]), b_key, &metrics)?;
898
899        // The next packet still arrives.
900        let data = b"still here";
901        clients.send_packet(a_key, Datagrams::from(&data[..]), b_key, &metrics)?;
902        let frame = recv_frame(FrameType::RelayToClientDatagram, &mut a_rw).await?;
903        assert_eq!(
904            frame,
905            RelayToClientMsg::Datagrams {
906                remote_endpoint_id: b_key,
907                datagrams: data.to_vec().into(),
908            }
909        );
910        assert_eq!(metrics.send_packets_dropped.get(), 1);
911
912        clients.shutdown().await;
913        Ok(())
914    }
915
916    /// Test for versioned protocol: v1 client should receive V1Health frame.
917    #[tokio::test]
918    #[traced_test]
919    async fn test_duplicate_endpoint_v1_receives_v1health() -> Result {
920        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42u64);
921        let key = SecretKey::from_bytes(&rng.random()).public();
922
923        let (builder_first, mut first_rw) = test_client_builder(key, ProtocolVersion::V1);
924
925        let clients = Clients::default();
926        let metrics = Arc::new(Metrics::default());
927        clients.register(builder_first, metrics.clone());
928
929        // Register a second client with the same endpoint ID.
930        // The first client should receive a V1Health message.
931        let (builder_second, _second_rw) = test_client_builder(key, ProtocolVersion::V1);
932        clients.register(builder_second, metrics.clone());
933
934        let frame = recv_frame(FrameType::Health, &mut first_rw).await?;
935        assert!(
936            matches!(frame, RelayToClientMsg::Health { .. }),
937            "expected V1Health frame for V1 client, got {frame:?}"
938        );
939
940        clients.shutdown().await;
941        Ok(())
942    }
943
944    /// Test for versioned protocol: v2 client should receive V2Health frame.
945    #[tokio::test]
946    #[traced_test]
947    async fn test_duplicate_endpoint_v2_receives_health() -> Result {
948        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42u64);
949        let key = SecretKey::from_bytes(&rng.random()).public();
950
951        let (builder_first, mut first_rw) = test_client_builder(key, ProtocolVersion::V2);
952
953        let clients = Clients::default();
954        let metrics = Arc::new(Metrics::default());
955        clients.register(builder_first, metrics.clone());
956
957        // Register a second client with the same endpoint ID.
958        // The first client should receive a Health message (V2 frame).
959        let (builder_second, _second_rw) = test_client_builder(key, ProtocolVersion::V2);
960        clients.register(builder_second, metrics.clone());
961
962        let frame = recv_frame(FrameType::Status, &mut first_rw).await?;
963        assert_eq!(
964            frame,
965            RelayToClientMsg::Status(Status::SameEndpointIdConnected)
966        );
967
968        clients.shutdown().await;
969        Ok(())
970    }
971
972    #[tokio::test(start_paused = true)]
973    #[traced_test]
974    async fn test_rate_limit() -> Result {
975        const LIMIT: u32 = 50;
976        const MAX_FRAMES: u32 = 100;
977
978        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
979
980        // Build the rate limited stream.
981        let (io_read, io_write) = tokio::io::duplex((LIMIT * MAX_FRAMES) as _);
982        let mut frame_writer = Conn::test(io_write, Default::default());
983        // Rate limiter allowing LIMIT bytes/s
984        let (mut stream, _limited) = RelayedStream::test_limited(io_read, LIMIT / 10, LIMIT)?;
985
986        // Prepare a frame to send, assert its size.
987        let data = Datagrams::from(b"hello world!!!!!");
988        let target = SecretKey::from_bytes(&rng.random()).public();
989        let frame = ClientToRelayMsg::Datagrams {
990            dst_endpoint_id: target,
991            datagrams: data.clone(),
992        };
993        let frame_len = frame.to_bytes().len();
994        assert_eq!(frame_len, LIMIT as usize);
995
996        // Send a frame, it should arrive.
997        info!("-- send packet");
998        frame_writer.send(frame.clone()).await.std_context("send")?;
999        frame_writer.flush().await.std_context("flush")?;
1000        let recv_frame = tokio::time::timeout(Duration::from_millis(500), stream.next())
1001            .await
1002            .expect("timeout")
1003            .expect("option")
1004            .expect("ok");
1005        assert_eq!(recv_frame, frame);
1006
1007        // Next frame does not arrive.
1008        info!("-- send packet");
1009        frame_writer.send(frame.clone()).await.std_context("send")?;
1010        frame_writer.flush().await.std_context("flush")?;
1011        let res = tokio::time::timeout(Duration::from_millis(100), stream.next()).await;
1012        assert!(res.is_err(), "expecting a timeout");
1013        info!("-- timeout happened");
1014
1015        // Wait long enough.
1016        info!("-- sleep");
1017        tokio::time::sleep(Duration::from_secs(1)).await;
1018
1019        // Frame arrives.
1020        let recv_frame = tokio::time::timeout(Duration::from_millis(500), stream.next())
1021            .await
1022            .expect("timeout")
1023            .expect("option")
1024            .expect("ok");
1025        assert_eq!(recv_frame, frame);
1026
1027        Ok(())
1028    }
1029
1030    /// A client whose connection is rate-limited receives a [`Status::RateLimited`] notice.
1031    #[tokio::test(start_paused = true)]
1032    #[traced_test]
1033    async fn test_rate_limit_notice() -> Result {
1034        const LIMIT: u32 = 50;
1035
1036        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
1037        let key = SecretKey::from_bytes(&rng.random()).public();
1038        let target = SecretKey::from_bytes(&rng.random()).public();
1039
1040        let (server_io, client_io) = tokio::io::duplex(4096);
1041        // Rate limiter allowing LIMIT bytes/s with a burst size below a single frame.
1042        let (stream, limited) = ServerRelayedStream::test_limited(server_io, LIMIT / 10, LIMIT)?;
1043        let mut config = Config::new(OnDisconnectGuard::empty(key), stream, ProtocolVersion::V2);
1044        config.write_timeout = Duration::from_secs(1);
1045        config.channel_capacity = 10;
1046        config.rate_limited = Some(limited);
1047        let mut conn = Conn::test(client_io, ProtocolVersion::V2);
1048
1049        let clients = Clients::default();
1050        clients.register(config, Arc::new(Metrics::default()));
1051
1052        // A single frame larger than the burst size trips the rate limiter.
1053        conn.send(ClientToRelayMsg::Datagrams {
1054            dst_endpoint_id: target,
1055            datagrams: Datagrams::from(b"hello world!!!!!"),
1056        })
1057        .await?;
1058
1059        let frame = recv_frame(FrameType::Status, &mut conn).await?;
1060        assert_eq!(frame, RelayToClientMsg::Status(Status::RateLimited));
1061
1062        clients.shutdown().await;
1063        Ok(())
1064    }
1065}