Skip to main content

syncspin_client/
discovery.rs

1//! Discovery-facing side of the client: the trait a host implements, and the server-initiated
2//! connection mode.
3//!
4//! `connection.md` lets a client establish connections in exactly one of two ways. In the
5//! client-initiated way it dials the address of a server it found; in the server-initiated way it
6//! advertises `_sendspin._tcp` over mDNS and accepts the server that connects to it. This module
7//! holds the seam for both: the [`Discovery`] trait, the records it carries, and - behind the
8//! `discovery` feature - the inbound listener that serves the WebSocket the advertisement leads to.
9//! Without that feature the module is the trait and the records alone: nothing listens.
10//!
11//! The mDNS backend lives behind the `mdns` feature; without it, [`Discovery`] is the seam and the
12//! host supplies the implementation. No protocol logic here opens a socket or joins a multicast
13//! group, and the tests drive the advertising with a fake instead of a network. The listener itself
14//! binds a real address, because it has to: it is the endpoint the advertisement names.
15//!
16//! The inbound connection runs the same session as a dialled one. Only the WebSocket is different:
17//! the server opened it, so the client answers the upgrade instead of sending it, and it rejects
18//! every request that carries an `Origin` header. `connection.md`: a client that advertises
19//! "MUST reject a WebSocket upgrade request to its Sendspin endpoint that carries an `Origin`
20//! header"; a server that dials in knows the address it dialled, and the header is the browser's
21//! cross-origin authorisation, not the protocol's. The Noise handshake is unchanged, because the
22//! server is its initiator in both directions.
23
24use anyhow::Result;
25
26/// Service type a client publishes when it waits for a server to connect.
27///
28/// `connection.md`, _Server Initiated Connections_: the port, the `path` TXT record and the
29/// optional `name` TXT record travel with it.
30pub const CLIENT_SERVICE_TYPE: &str = "_sendspin._tcp.local.";
31
32/// Service type a server publishes for client-initiated connections.
33pub const SERVER_SERVICE_TYPE: &str = "_sendspin-server._tcp.local.";
34
35/// WebSocket endpoint `connection.md` recommends for both directions.
36pub const DEFAULT_SENDSPIN_PATH: &str = "/sendspin";
37
38/// One service to publish over mDNS.
39///
40/// The record is what a peer needs to reach the endpoint: the service type, the port, and the
41/// `path` TXT record the WebSocket lives on. `name` is the optional friendly-name hint; it is not
42/// an identity and a peer that has the connection takes the name from `client/hello`
43/// (`server/hello` in the other direction) instead.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct ServiceAdvertisement {
46    /// Service type the record is published under, for example [`CLIENT_SERVICE_TYPE`].
47    pub service_type: String,
48    /// Port the endpoint listens on.
49    pub port: u16,
50    /// The `path` TXT record: the WebSocket endpoint, an absolute path such as `/sendspin`.
51    pub path: String,
52    /// The `name` TXT record, when the advertiser sets one.
53    pub name: Option<String>,
54}
55
56impl ServiceAdvertisement {
57    /// Returns the record a client publishes: `_sendspin._tcp`, its port, `path` and `name`.
58    ///
59    /// The name is the player's, which is the value `client/hello` repeats; the spec only asks it to
60    /// match, and calls the `client/hello` value authoritative when the two differ.
61    #[must_use]
62    pub fn client(
63        port: u16,
64        path: impl Into<String>,
65        name: impl Into<String>,
66    ) -> ServiceAdvertisement {
67        ServiceAdvertisement {
68            service_type: CLIENT_SERVICE_TYPE.to_owned(),
69            port,
70            path: path.into(),
71            name: Some(name.into()),
72        }
73    }
74}
75
76/// One server a browser reported.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct DiscoveredServer {
79    /// `host:port` addresses the browser resolved for the service, most suitable first.
80    pub addresses: Vec<String>,
81    /// The `path` TXT record the service published.
82    pub path: String,
83    /// The `name` TXT record, when the service published one.
84    pub name: Option<String>,
85}
86
87impl DiscoveredServer {
88    /// Returns the `ws://` endpoint to dial, or `None` when the record cannot name one.
89    ///
90    /// The scheme is `ws://` even though the path is advertised: `connection.md` requires a
91    /// connection to an advertised address to use plain `ws://`, with confidentiality and integrity
92    /// provided by the Noise layer inside the payloads. An address that carries a scheme already,
93    /// a missing address and a path that is not `path-absolute` (RFC 3986) all yield `None`,
94    /// because dialling them would mean guessing what the advertiser meant.
95    #[must_use]
96    pub fn endpoint(&self) -> Option<String> {
97        let address = self.addresses.first()?;
98        if address.contains("://") {
99            return None;
100        }
101        if !self.path.starts_with('/') || self.path.starts_with("//") {
102            return None;
103        }
104        Some(format!("ws://{address}{}", self.path))
105    }
106}
107
108/// How a service is published and how remote ones are found.
109///
110/// A host implements this over its mDNS library of choice; the crate decides what the record
111/// contains and what an announcement obliges it to do, so the two stay in one place. The trait never
112/// reports a record it has not published: [`advertise`](Discovery::advertise) returning `Ok` means
113/// a server can find the endpoint, and the whole server-initiated mode rests on that.
114///
115/// A client that advertises must not dial a server itself (`connection.md`, _Server Initiated
116/// Connections_). This crate enforces that: [`connect`](crate::connect) refuses a configuration
117/// that advertises.
118pub trait Discovery: Send + Sync {
119    /// Publishes `service` until its service type is withdrawn.
120    ///
121    /// # Errors
122    /// Returns an error when the record could not be published. The client then refuses to start,
123    /// because accepting connections nobody can find is not the mode it was asked for.
124    fn advertise(&self, service: ServiceAdvertisement) -> Result<()>;
125
126    /// Withdraws the advertisement of `service_type`.
127    ///
128    /// Called when the inbound listener closes: a record that outlives its listener points at a
129    /// closed port. Withdrawing a type that was never advertised is not an error.
130    fn withdraw(&self, service_type: &str) -> Result<()>;
131
132    /// Returns the services currently advertised under `service_type`.
133    fn browse(&self, service_type: &str) -> Result<Vec<DiscoveredServer>>;
134}
135
136/// Returns the servers `discovery` currently reports.
137///
138/// This is the browsing half of the client-initiated mode: the caller picks one
139/// [`DiscoveredServer::endpoint`] and passes it to [`connect`](crate::connect). Browsing is a
140/// client-initiated act, so a host that browses must not advertise at the same time; a
141/// configuration with [`ClientConfig::inbound`](crate::ClientConfig) set cannot dial at all.
142///
143/// # Errors
144/// Returns the backend's error, and nothing when it cannot browse at all; an empty list means no
145/// server is advertising.
146pub fn discover_servers(discovery: &dyn Discovery) -> Result<Vec<DiscoveredServer>> {
147    discovery.browse(SERVER_SERVICE_TYPE)
148}
149
150#[cfg(feature = "discovery")]
151pub use inbound::{advertise, Inbound, DEFAULT_INBOUND_ADDR, DEFAULT_INBOUND_PORT};
152
153#[cfg(feature = "mdns")]
154mod mdns;
155
156#[cfg(feature = "mdns")]
157pub use mdns::MdnsDiscovery;
158
159#[cfg(feature = "discovery")]
160mod inbound {
161    use std::fmt;
162    use std::net::{IpAddr, Ipv4Addr, SocketAddr};
163    use std::sync::atomic::AtomicU8;
164    use std::sync::Arc;
165    use std::time::Duration;
166
167    use anyhow::{anyhow, Context, Result};
168    use syncspin_core::pairing::token::encode_v0;
169    use tokio::net::{TcpListener, TcpStream};
170    use tokio::sync::{mpsc, oneshot};
171    use tokio::task::JoinSet;
172    use tokio_tungstenite::accept_hdr_async;
173    use tokio_tungstenite::tungstenite::handshake::server::{ErrorResponse, Request, Response};
174    use tokio_tungstenite::tungstenite::http::header::ORIGIN;
175    use tokio_tungstenite::tungstenite::http::StatusCode;
176    use tokio_tungstenite::tungstenite::Error as WsError;
177
178    use super::{ServiceAdvertisement, DEFAULT_SENDSPIN_PATH};
179    use crate::client::{
180        answer_without_session, ClientHandle, ControlHandle, ControlRequest, Event, EventStream,
181        GoodbyeReason, PairingToken,
182    };
183    use crate::config::ClientConfig;
184    use crate::pairing::{load_or_draw_pairing_psk, PairingPsk};
185    use crate::session::{self, Carried, Transport};
186    use crate::sink::Sink;
187    use crate::Discovery;
188
189    /// Port `connection.md` recommends for a client's Sendspin endpoint.
190    pub const DEFAULT_INBOUND_PORT: u16 = 8928;
191
192    /// Address the inbound listener binds unless the host narrows it.
193    ///
194    /// Encryption is the boundary, not the bind address: a peer that cannot complete the Noise
195    /// handshake is refused whatever interface it reached.
196    pub const DEFAULT_INBOUND_ADDR: SocketAddr =
197        SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), DEFAULT_INBOUND_PORT);
198
199    /// How long the rejection of a second server may take before its socket is dropped.
200    ///
201    /// The provisional connection has to reach its first `server/activate` before admission can be
202    /// applied. A server that never gets there is not worth keeping: the cap already rejected it,
203    /// and the spec's own provisional timeout is 30 seconds.
204    const REJECT_TIMEOUT: Duration = Duration::from_secs(30);
205
206    /// The server-initiated half of the connection mode.
207    ///
208    /// Setting [`ClientConfig::inbound`] puts the client in this mode: [`advertise`] publishes
209    /// [`CLIENT_SERVICE_TYPE`](super::CLIENT_SERVICE_TYPE) with the bound port, the configured path
210    /// and the player name, and then accepts the servers that connect. A manual
211    /// [`connect`](crate::connect) is refused while this is set, because `connection.md` lets a
212    /// client use one of the two methods at a time.
213    #[derive(Clone)]
214    pub struct Inbound {
215        /// Backend that publishes the record and browses for servers.
216        pub discovery: Arc<dyn Discovery>,
217        /// Address the listener binds.
218        pub listen: SocketAddr,
219        /// WebSocket path the listener serves, as the `path` TXT record states it.
220        pub path: String,
221    }
222
223    impl Inbound {
224        /// Returns the server-initiated mode for `discovery`, with the spec's defaults.
225        ///
226        /// The listener binds [`DEFAULT_INBOUND_ADDR`] - every interface on
227        /// [`DEFAULT_INBOUND_PORT`] - and serves `/sendspin`. A host that narrows the address or
228        /// moves the path sets the fields before placing the value in [`ClientConfig::inbound`].
229        #[must_use]
230        pub fn new(discovery: Arc<dyn Discovery>) -> Inbound {
231            Inbound {
232                discovery,
233                listen: DEFAULT_INBOUND_ADDR,
234                path: DEFAULT_SENDSPIN_PATH.to_owned(),
235            }
236        }
237    }
238
239    impl fmt::Debug for Inbound {
240        /// Names the backend without delegating to it: its `Debug` belongs to the host.
241        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
242            formatter
243                .debug_struct("Inbound")
244                .field("discovery", &"<host discovery>")
245                .field("listen", &self.listen)
246                .field("path", &self.path)
247                .finish()
248        }
249    }
250
251    /// Advertises this client and serves the servers that connect to it.
252    ///
253    /// The advertisement is published before this returns, so a caller learns about a backend that
254    /// cannot publish instead of running a listener nobody can find. The port in the record is the
255    /// one that was actually bound, which is how a listen address with port zero becomes reachable.
256    ///
257    /// One server is admitted at a time: while a session is live the loop runs it, and when it ends
258    /// the client reports [`Event::Disconnected`] with a `retry_in` of zero - it schedules nothing,
259    /// because the next connection is the server's decision - and accepts the next one. The
260    /// advertisement is withdrawn when the handle or the event stream is dropped, when
261    /// [`ClientHandle::close`] is called, or when the audio sink fails.
262    ///
263    /// # Errors
264    /// Returns an error for an invalid configuration, for a configuration without
265    /// [`ClientConfig::inbound`], for a [`Storage`](crate::storage::Storage) that cannot hold the
266    /// pairing PSK, for a listen address this build cannot bind, and for a backend that refuses the
267    /// advertisement.
268    ///
269    /// # Panics
270    /// Panics when called outside a Tokio runtime, because the listener is spawned.
271    ///
272    /// Pairing records come from [`ClientConfig::storage`]; this revision has no advertising
273    /// counterpart to [`connect_with_psks`](crate::connect_with_psks).
274    pub async fn advertise(
275        config: ClientConfig,
276        sink: Box<dyn Sink>,
277    ) -> Result<(ClientHandle, EventStream)> {
278        let inbound = config.inbound.clone().ok_or_else(|| {
279            anyhow!(
280                "this configuration has no ClientConfig::inbound, so there is nothing to \
281                 advertise and no address to accept a server on"
282            )
283        })?;
284        // An advertising client names no server address, so only the shared fields are checked.
285        config.validate_common()?;
286
287        // The pairing PSK is settled before anything is published, so a store that cannot hold it
288        // is reported here rather than to whichever server happens to connect first.
289        let (pairing, pairing_token) = match config.storage.as_deref() {
290            Some(storage) => {
291                let psk = load_or_draw_pairing_psk(storage)?;
292                let token = PairingToken(encode_v0(&config.identity.public, psk.as_bytes()));
293                (Some(psk), Some(token))
294            }
295            None => (None, None),
296        };
297
298        // The listener comes next: a record that names a port nothing accepts on is a record a
299        // server dials into a closed socket. Nothing after the advertisement can fail, so a client
300        // never stays advertised without a listener behind it.
301        let listener = TcpListener::bind(inbound.listen).await.with_context(|| {
302            format!("failed to bind the inbound listener on {}", inbound.listen)
303        })?;
304        let port = listener
305            .local_addr()
306            .context("failed to read the inbound listener's address")?
307            .port();
308        let record = ServiceAdvertisement::client(port, inbound.path.clone(), &config.player_name);
309        inbound
310            .discovery
311            .advertise(record.clone())
312            .context("the discovery backend refused to advertise this client")?;
313
314        let (events, receiver) = mpsc::unbounded_channel();
315        let (commands, control) = mpsc::unbounded_channel();
316        let (shutdown, shutdown_rx) = oneshot::channel();
317        let reported_volume = Arc::new(AtomicU8::new(config.volume));
318        // The dynamic flow's round counter belongs to the process, not to a connection: it starts
319        // clean here and is carried across every inbound session.
320        #[cfg(feature = "pairing-code")]
321        let failed_rounds = Arc::new(std::sync::atomic::AtomicU32::new(0));
322
323        let carried = Carried {
324            sink,
325            control: Some(control),
326            volume: config.volume,
327            muted: config.muted,
328            active_roles: Vec::new(),
329            #[cfg(feature = "pairing-code")]
330            failed_rounds,
331        };
332
333        let task = tokio::spawn(serve(
334            listener,
335            config,
336            inbound,
337            record,
338            pairing,
339            carried,
340            events,
341            Arc::clone(&reported_volume),
342            shutdown_rx,
343        ));
344
345        let handle = ClientHandle {
346            task: Some(task),
347            control: ControlHandle {
348                commands,
349                volume: reported_volume,
350                pairing_token,
351            },
352            shutdown: Some(shutdown),
353        };
354        Ok((handle, EventStream { events: receiver }))
355    }
356
357    /// Runs the listener until the host is done, then withdraws the advertisement.
358    #[allow(clippy::too_many_arguments)]
359    async fn serve(
360        listener: TcpListener,
361        config: ClientConfig,
362        inbound: Inbound,
363        record: ServiceAdvertisement,
364        pairing: Option<PairingPsk>,
365        carried: Carried,
366        events: mpsc::UnboundedSender<Event>,
367        reported_volume: Arc<AtomicU8>,
368        mut shutdown: oneshot::Receiver<GoodbyeReason>,
369    ) -> Result<()> {
370        let outcome = accept_loop(
371            &listener,
372            &config,
373            &inbound.path,
374            pairing,
375            carried,
376            &events,
377            &reported_volume,
378            &mut shutdown,
379        )
380        .await;
381        // An advertisement that outlives the listener points a server at a closed port, so it goes
382        // away whatever ended the loop.
383        let withdrawn = inbound
384            .discovery
385            .withdraw(&record.service_type)
386            .context("the discovery backend refused to withdraw the advertisement");
387        match outcome {
388            Ok(()) => withdrawn,
389            Err(error) => Err(error),
390        }
391    }
392
393    /// Accepts and serves one connection at a time until the host ends the client.
394    #[allow(clippy::too_many_arguments)]
395    async fn accept_loop(
396        listener: &TcpListener,
397        config: &ClientConfig,
398        path: &str,
399        pairing: Option<PairingPsk>,
400        mut carried: Carried,
401        events: &mpsc::UnboundedSender<Event>,
402        reported_volume: &AtomicU8,
403        shutdown: &mut oneshot::Receiver<GoodbyeReason>,
404    ) -> Result<()> {
405        loop {
406            let Some(stream) =
407                wait_for_connection(listener, &mut carried, events, shutdown).await?
408            else {
409                return Ok(());
410            };
411            // The upgrade answers every request it refuses, so neither a wrong path nor a rejected
412            // `Origin` reaches the protocol. A peer that breaks the upgrade itself - a truncated
413            // request, a hello for another protocol - is equally not a connection, and neither
414            // stops the listener for the servers that follow.
415            let transport = match upgrade(stream, path).await {
416                Ok(Some(transport)) => transport,
417                Ok(None) | Err(_) => continue,
418            };
419
420            // The server-initiated mode admits one server at a time. A second one that arrives
421            // while this session runs is not left in the listen backlog: its handshake is completed
422            // in a task of its own and it is rejected with `concurrent_attempt`, as `connection.md`
423            // requires. The task owns no state of the admitted session, so a slow rejection cannot
424            // hold up playback.
425            let mut rejections = JoinSet::new();
426            let mut attempt = Box::pin(session::attempt(
427                transport,
428                config,
429                events,
430                &[],
431                pairing,
432                reported_volume,
433                carried,
434                shutdown,
435            ));
436            let attempt = loop {
437                tokio::select! {
438                    attempt = &mut attempt => break attempt,
439                    // Accepting is cancel-safe: a connection that arrives while another branch is
440                    // busy waits in the backlog for the next round.
441                    accepted = listener.accept() => {
442                        let (stream, _address) =
443                            accepted.context("failed to accept an inbound connection")?;
444                        rejections.spawn(reject_connection(
445                            stream,
446                            config.clone(),
447                            path.to_owned(),
448                            pairing,
449                        ));
450                    }
451                    joined = rejections.join_next(), if !rejections.is_empty() => {
452                        // A rejection that failed changed nothing: the admitted session is the one
453                        // the host hears about.
454                        let _ = joined;
455                    }
456                }
457            };
458            // A rejection that has not finished belongs to a client that is already ending; it is
459            // dropped with the set, which closes its socket.
460            drop(rejections);
461            carried = attempt.carried;
462
463            // Nothing buffered for the session that ended may become audible later; the flush runs
464            // before the host hears about the drop. A deliberate close is not a drop.
465            let flush_error = carried.sink.flush().err().map(|error| {
466                error.context("the audio sink rejected a flush after the connection ended")
467            });
468            if matches!(&attempt.ending, session::Ending::Shutdown) {
469                return Ok(());
470            }
471            // No attempt follows: the next connection is the server's decision, not the client's,
472            // so there is no delay to recommend.
473            let _ = events.send(Event::Disconnected {
474                reason: attempt.ending.reason(),
475                retry_in: Duration::ZERO,
476            });
477
478            // A broken output cannot be repaired by another connection, and neither can a flush
479            // that fails after the session; both end the client so the host can repair it.
480            if attempt.sink_failed {
481                return match attempt.ending {
482                    session::Ending::Failed(error) => Err(error),
483                    session::Ending::Closed
484                    | session::Ending::Unpaired
485                    | session::Ending::Shutdown => Err(anyhow!("the audio sink failed")),
486                };
487            }
488            if let Some(error) = flush_error {
489                return Err(error);
490            }
491        }
492    }
493
494    /// Rejects one connection that arrived while another server is admitted.
495    ///
496    /// The upgrade rules are the same as for the admitted connection - the path must match and an
497    /// `Origin` header is refused - because a rejected server learns nothing a browser could use.
498    async fn reject_connection(
499        stream: TcpStream,
500        config: ClientConfig,
501        path: String,
502        pairing: Option<PairingPsk>,
503    ) {
504        let Ok(Some(transport)) = upgrade(stream, &path).await else {
505            return;
506        };
507        let _ = tokio::time::timeout(
508            REJECT_TIMEOUT,
509            session::reject_concurrent(transport, &config, pairing, &[]),
510        )
511        .await;
512    }
513
514    /// Waits for the next inbound connection, answering control requests meanwhile.
515    ///
516    /// Returns `None` when the host ended the client: the handle was closed or the event stream was
517    /// dropped. There is no session to say goodbye on while the listener waits, exactly as in the
518    /// reconnect wait of a dialling client.
519    async fn wait_for_connection(
520        listener: &TcpListener,
521        carried: &mut Carried,
522        events: &mpsc::UnboundedSender<Event>,
523        shutdown: &mut oneshot::Receiver<GoodbyeReason>,
524    ) -> Result<Option<TcpStream>> {
525        loop {
526            if events.is_closed() {
527                return Ok(None);
528            }
529            let control = &mut carried.control;
530            let wakeup = tokio::select! {
531                biased;
532                request = async {
533                    match control {
534                        Some(receiver) => receiver.recv().await,
535                        None => std::future::pending().await,
536                    }
537                } => Wakeup::Control(request),
538                // Accepting is cancel-safe: a connection that arrives while this select is busy
539                // waits in the backlog.
540                accepted = listener.accept() => Wakeup::Accepted(accepted),
541                reason = &mut *shutdown => {
542                    let _ = reason;
543                    return Ok(None);
544                }
545                () = events.closed() => Wakeup::Closed,
546            };
547            match wakeup {
548                Wakeup::Control(Some(request)) => answer_without_session(carried, request),
549                Wakeup::Control(None) => *control = None,
550                Wakeup::Accepted(Ok((stream, _address))) => return Ok(Some(stream)),
551                Wakeup::Accepted(Err(error)) => {
552                    return Err(anyhow!(error).context("failed to accept an inbound connection"))
553                }
554                Wakeup::Closed => return Ok(None),
555            }
556        }
557    }
558
559    /// One wake-up while the listener waits for a server.
560    enum Wakeup {
561        /// A control handle sent a request, or every handle was dropped.
562        Control(Option<ControlRequest>),
563        /// The listener accepted a TCP connection.
564        Accepted(std::io::Result<(TcpStream, SocketAddr)>),
565        /// The host dropped the event stream.
566        Closed,
567    }
568
569    /// Serves `stream` if it asks for `path` and carries no `Origin` header.
570    ///
571    /// `Ok(None)` means the request was refused with an HTTP answer and its socket is closed; the
572    /// caller keeps listening.
573    // Error responses are the handshake crate's large `http::Response` type; a rejection happens
574    // once per refused upgrade, so boxing it would buy nothing.
575    #[allow(clippy::result_large_err)]
576    async fn upgrade(stream: TcpStream, path: &str) -> Result<Option<Transport>> {
577        let expected = path.to_owned();
578        let callback = move |request: &Request, response: Response| {
579            // `connection.md`: a client must reject an upgrade that carries an `Origin` header. A
580            // server that dials in knows the address it dialled, so the header can only come from
581            // something acting for a page - which is what the rule exists to refuse.
582            if request.headers().contains_key(ORIGIN) {
583                let mut error = ErrorResponse::new(Some(
584                    "a server-initiated Sendspin upgrade must not carry an Origin header"
585                        .to_owned(),
586                ));
587                *error.status_mut() = StatusCode::FORBIDDEN;
588                return Err(error);
589            }
590            if request.uri().path() == expected {
591                return Ok(response);
592            }
593            let mut error =
594                ErrorResponse::new(Some("this endpoint is not a Sendspin endpoint".to_owned()));
595            *error.status_mut() = StatusCode::NOT_FOUND;
596            Err(error)
597        };
598        match accept_hdr_async(stream, callback).await {
599            Ok(socket) => Ok(Some(Transport::accept(socket))),
600            // The two answers above: the peer was told why and the socket is closed.
601            Err(WsError::Http(response))
602                if response.status() == StatusCode::FORBIDDEN
603                    || response.status() == StatusCode::NOT_FOUND =>
604            {
605                Ok(None)
606            }
607            Err(error) => Err(error).context("the WebSocket upgrade failed"),
608        }
609    }
610}
611
612#[cfg(test)]
613mod tests {
614    use super::*;
615
616    /// A [`Discovery`] that answers from memory, so the record shape is tested without a network.
617    #[derive(Default)]
618    struct MemoryDiscovery {
619        browsed: std::sync::Mutex<Vec<String>>,
620        servers: Vec<DiscoveredServer>,
621    }
622
623    impl Discovery for MemoryDiscovery {
624        fn advertise(&self, _service: ServiceAdvertisement) -> Result<()> {
625            Ok(())
626        }
627
628        fn withdraw(&self, _service_type: &str) -> Result<()> {
629            Ok(())
630        }
631
632        fn browse(&self, service_type: &str) -> Result<Vec<DiscoveredServer>> {
633            self.browsed
634                .lock()
635                .expect("the query list is not poisoned")
636                .push(service_type.to_owned());
637            Ok(self.servers.clone())
638        }
639    }
640
641    /// The record a client publishes carries the three things a server dials with, plus its name.
642    #[test]
643    fn a_client_record_names_the_service_the_port_the_path_and_the_player() {
644        let record = ServiceAdvertisement::client(8928, DEFAULT_SENDSPIN_PATH, "Test player");
645        assert_eq!(record.service_type, CLIENT_SERVICE_TYPE);
646        assert_eq!(record.port, 8928);
647        assert_eq!(record.path, "/sendspin");
648        assert_eq!(record.name.as_deref(), Some("Test player"));
649        assert_ne!(
650            CLIENT_SERVICE_TYPE, SERVER_SERVICE_TYPE,
651            "the two directions use two service types"
652        );
653    }
654
655    /// A discovered record becomes a plain `ws://` endpoint, and nothing else.
656    #[test]
657    fn a_discovered_server_builds_a_plain_ws_endpoint() {
658        let server = DiscoveredServer {
659            addresses: vec!["192.0.2.7:8927".to_owned()],
660            path: "/sendspin".to_owned(),
661            name: Some("A server".to_owned()),
662        };
663        assert_eq!(
664            server.endpoint().as_deref(),
665            Some("ws://192.0.2.7:8927/sendspin"),
666            "connection.md requires plain ws:// to an advertised address"
667        );
668
669        // A record that cannot name an endpoint is refused here rather than guessed at later.
670        for broken in [
671            DiscoveredServer {
672                addresses: Vec::new(),
673                ..server.clone()
674            },
675            DiscoveredServer {
676                path: "sendspin".to_owned(),
677                ..server.clone()
678            },
679            DiscoveredServer {
680                path: "//sendspin".to_owned(),
681                ..server.clone()
682            },
683            DiscoveredServer {
684                addresses: vec!["wss://192.0.2.7:8927".to_owned()],
685                ..server
686            },
687        ] {
688            assert_eq!(
689                broken.endpoint(),
690                None,
691                "a record that does not name a ws:// endpoint is not dialled"
692            );
693        }
694    }
695
696    /// Browsing always asks for the server service type; the client never looks for clients.
697    #[test]
698    fn browsing_asks_the_backend_for_servers() {
699        let discovery = MemoryDiscovery::default();
700        let servers = discover_servers(&discovery).expect("the backend answers");
701        assert!(servers.is_empty());
702        assert_eq!(
703            discovery
704                .browsed
705                .lock()
706                .expect("the query list is not poisoned")
707                .as_slice(),
708            &[SERVER_SERVICE_TYPE.to_owned()]
709        );
710    }
711}