Skip to main content

syncspin_client/
client.rs

1//! Public client surface: events, handles and the connection entry point.
2
3use std::fmt;
4#[cfg(feature = "pairing-code")]
5use std::sync::atomic::AtomicU32;
6use std::sync::atomic::{AtomicU8, Ordering};
7use std::sync::Arc;
8use std::time::Duration;
9
10use anyhow::{anyhow, bail, Context, Result};
11use tokio::sync::{mpsc, oneshot};
12use tokio::task::JoinHandle;
13
14#[cfg(feature = "pairing-code")]
15use crate::config::CodeFormat;
16use crate::config::{ClientConfig, StoredPsk, VolumePolicy};
17use crate::pairing::{load_or_draw_pairing_psk, PairingPsk};
18use crate::session::{self, Carried, Transport};
19use crate::sink::{AudioFormat, Sink};
20
21/// How long the TCP and WebSocket handshake may take before it is treated as unreachable.
22const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
23
24/// Delay before the first reconnect attempt, and the value the backoff resets to.
25pub const INITIAL_BACKOFF: Duration = Duration::from_secs(1);
26
27/// How long one pairing attempt may run, measured from `client/pair-init`.
28///
29/// `pairing.md` recommends two minutes. On expiry the client sends `pair/abort` with reason
30/// `attempt_timeout` and reports [`Event::PairingFailed`]; a host that wants a tighter bound sets
31/// [`ClientConfig::pairing_timeout`].
32pub const DEFAULT_PAIRING_TIMEOUT: Duration = Duration::from_secs(120);
33
34/// Highest level the protocol defines, in its 0-100 volume range.
35pub(crate) const MAX_VOLUME: u8 = 100;
36
37/// Playback speed the protocol defines as normal, in per-mille.
38///
39/// A metadata message that carries no speed plays at this rate, so the track event always names
40/// one.
41pub const NORMAL_PLAYBACK_SPEED: u32 = 1_000;
42
43/// Returns the volume level to apply for `requested` while `current` is in force.
44///
45/// This is [`clamp_volume_with`] with [`VolumePolicy::default`]: a request to 40 or below is
46/// applied as asked, and above 40 one request may raise the level by at most 20. Both values are
47/// first limited to the protocol's 0-100 range, so the result is always a level the server
48/// accepts.
49///
50/// ```
51/// # use syncspin_client::clamp_volume;
52/// assert_eq!(clamp_volume(40, 100), 60);
53/// assert_eq!(clamp_volume(40, 10), 10);
54/// assert_eq!(clamp_volume(100, 90), 90);
55/// assert_eq!(clamp_volume(100, 150), 100);
56/// ```
57#[must_use]
58pub fn clamp_volume(current: u8, requested: u8) -> u8 {
59    clamp_volume_with(VolumePolicy::default(), current, requested)
60}
61
62/// Returns the volume level to apply for `requested` while `current` is in force, using `policy`.
63///
64/// Both values are first limited to the protocol's 0-100 range, so the result is always a level
65/// the server accepts. A request at or below [`VolumePolicy::threshold`] is applied as asked,
66/// whether it raises or lowers the level. Above the threshold, one request may raise the level by
67/// at most [`VolumePolicy::max_step`]; a lower request is applied as asked, because the limit
68/// bounds raises only. When [`VolumePolicy::threshold_floor`] is set, such a request may also rise
69/// to the threshold itself, so a player at 1 reaches 40 in one command instead of 21.
70///
71/// A `policy` whose fields exceed 100 is not rejected here, because the configuration validation
72/// rejects it before a connection exists; the values are limited to 100 so this function still
73/// returns a level the server accepts.
74///
75/// ```
76/// # use syncspin_client::{clamp_volume_with, VolumePolicy};
77/// let policy = VolumePolicy {
78///     threshold: 40,
79///     max_step: 20,
80///     threshold_floor: true,
81/// };
82/// assert_eq!(clamp_volume_with(policy, 1, 100), 40);
83/// assert_eq!(clamp_volume_with(policy, 40, 100), 60);
84/// assert_eq!(clamp_volume_with(policy, 100, 90), 90);
85/// ```
86#[must_use]
87pub fn clamp_volume_with(policy: VolumePolicy, current: u8, requested: u8) -> u8 {
88    let threshold = policy.threshold.min(MAX_VOLUME);
89    let max_step = policy.max_step.min(MAX_VOLUME);
90    let current = current.min(MAX_VOLUME);
91    let requested = requested.min(MAX_VOLUME);
92    if requested <= threshold {
93        return requested;
94    }
95    let applied = requested.min(current.saturating_add(max_step));
96    if policy.threshold_floor {
97        applied.max(threshold)
98    } else {
99        applied
100    }
101}
102
103/// Rejects a level outside the protocol's 0-100 range.
104///
105/// A reported level is not a request, so [`clamp_volume_with`] never sees it: a value the protocol
106/// cannot carry is refused instead of being capped, and nothing is recorded or sent.
107///
108/// # Errors
109/// Returns an error naming the value when it is above [`MAX_VOLUME`].
110pub(crate) fn check_reported_level(level: u8) -> Result<()> {
111    if level > MAX_VOLUME {
112        bail!(
113            "the reported level {level} is outside the 0-{MAX_VOLUME} range the protocol defines"
114        );
115    }
116    Ok(())
117}
118
119/// Returns the delay to wait before the next connection attempt.
120///
121/// The delay starts at [`INITIAL_BACKOFF`] and doubles with every attempt that never reached
122/// [`Event::Connected`], saturating at `max`. `previous` is the delay used before the failed
123/// attempt, or [`Duration::ZERO`] for the first one. A `connected` session resets the delay: the
124/// address and the handshake worked, so a later failure is retried without a growing penalty.
125///
126/// The crate keeps the sequence across the attempts it makes itself and reports each step in
127/// [`Event::Disconnected`]. A host that drives its own loop, for example because it wants to stop
128/// retrying, can use this function for the same policy.
129///
130/// ```
131/// # use std::time::Duration;
132/// # use syncspin_client::next_backoff;
133/// let max = Duration::from_secs(30);
134/// assert_eq!(next_backoff(Duration::ZERO, false, max), Duration::from_secs(1));
135/// assert_eq!(next_backoff(Duration::from_secs(1), false, max), Duration::from_secs(2));
136/// assert_eq!(next_backoff(Duration::from_secs(16), true, max), Duration::from_secs(1));
137/// ```
138#[must_use]
139pub fn next_backoff(previous: Duration, connected: bool, max: Duration) -> Duration {
140    let next = if connected || previous.is_zero() {
141        INITIAL_BACKOFF
142    } else {
143        previous.saturating_mul(2)
144    };
145    next.min(max)
146}
147
148/// Why a player stream ended.
149///
150/// A seek is not an end: the stream stays open and later chunks still belong to it, so it is
151/// reported as [`Event::StreamClear`] instead.
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153#[non_exhaustive]
154pub enum StreamEndReason {
155    /// The server sent `stream/end`, which pauses playback.
156    End,
157    /// The server removed `player@v1` from the active roles.
158    RoleRemoved,
159}
160
161/// Why a server needs a pairing this client cannot satisfy with what it holds.
162///
163/// The value is the reason field of [`Event::PairingRequired`]. The enum is non-exhaustive: a later
164/// revision may classify another situation the same way.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166#[non_exhaustive]
167pub enum PairingRequiredReason {
168    /// The server announced a `psk_id` this client does not hold, so the handshake fell back to
169    /// the Sentinel key.
170    ///
171    /// `connection.md` calls the resulting handshake the server's authenticated
172    /// credential-mismatch signal: the server still holds a record for this client, and the client
173    /// has none it can use for it. The signal alone never removes or replaces a record - not the
174    /// server's and not the client's - so the host decides whether to offer pairing again. A code
175    /// flow or the Pairing PSK flow then replaces the record on both sides.
176    CredentialMismatch,
177}
178
179/// Why a pairing attempt ended without a record.
180///
181/// Each value is the `reason` field of a `pair/abort`: the client sends the ones it causes and
182/// reports the ones it receives. The enum is non-exhaustive: a later revision defines reasons this
183/// one does not name, which arrive as [`Unrecognised`](PairingFailure::Unrecognised).
184#[derive(Debug, Clone, PartialEq, Eq)]
185#[non_exhaustive]
186pub enum PairingFailure {
187    /// The attempt did not complete within [`ClientConfig::pairing_timeout`].
188    AttemptTimeout,
189    /// The matched key and the requested method are not a permitted combination, or the client
190    /// does not currently offer the method: it has no store, or the activation names a code method
191    /// this build does not carry.
192    MethodNotSupported,
193    /// A key confirmation failed, so the code was wrong or a peer relayed between two handshakes.
194    PairingCodeMismatch,
195    /// The operator cancelled the pairing, on either side.
196    UserCancelled,
197    /// Another pairing attempt is already in progress with this client.
198    ConcurrentAttempt,
199    /// A reason this revision does not name, as it arrived on the wire.
200    Unrecognised(String),
201}
202
203impl PairingFailure {
204    /// Returns the reason as `pair/abort` spells it.
205    #[must_use]
206    pub fn as_str(&self) -> &str {
207        match self {
208            Self::AttemptTimeout => "attempt_timeout",
209            Self::MethodNotSupported => "method_not_supported",
210            Self::PairingCodeMismatch => "pairing_code_mismatch",
211            Self::UserCancelled => "user_cancelled",
212            Self::ConcurrentAttempt => "concurrent_attempt",
213            Self::Unrecognised(reason) => reason,
214        }
215    }
216
217    /// Decodes the `reason` of a received `pair/abort`.
218    ///
219    /// An unknown value is carried verbatim rather than rejected: the message is a wellformed
220    /// abort from a peer that may speak a later revision, and ending the connection over it would
221    /// be worse than reporting the reason the host cannot classify.
222    pub(crate) fn from_wire(reason: &str) -> Self {
223        match reason {
224            "attempt_timeout" => Self::AttemptTimeout,
225            "method_not_supported" => Self::MethodNotSupported,
226            "pairing_code_mismatch" => Self::PairingCodeMismatch,
227            "user_cancelled" => Self::UserCancelled,
228            "concurrent_attempt" => Self::ConcurrentAttempt,
229            other => Self::Unrecognised(other.to_owned()),
230        }
231    }
232}
233
234/// Something that happened on the connection.
235///
236/// Events are ordered as the connection produced them. A connection attempt ends with at most one
237/// [`Event::Disconnected`], and the crate then reconnects on its own, so a later event belongs to
238/// the next attempt. The enum is non-exhaustive: a later revision adds events without breaking a
239/// host's match.
240#[derive(Clone, PartialEq, Eq)]
241#[non_exhaustive]
242pub enum Event {
243    /// The Noise handshake finished and the session is ready for playback.
244    ///
245    /// Reported once per successful attempt. `encrypted` is always `true`: this client has no path
246    /// that speaks to a server without Noise, so the field documents the property rather than
247    /// hedging it.
248    Connected {
249        /// The server's static public key as 43 base64url characters.
250        server_id: String,
251        /// Whether the connection is encrypted; always `true`.
252        encrypted: bool,
253    },
254    /// The attempt ended.
255    ///
256    /// Another attempt follows unless the audio sink failed or the host dropped the connection.
257    /// `reason` is human-readable and never contains key material. `retry_in` is the delay
258    /// before the next attempt, one step of the reconnect policy: it is two seconds after an
259    /// attempt that never reached [`Event::Connected`], doubles with every further failed attempt
260    /// up to [`ClientConfig::max_backoff`], and drops to one second again after a session that
261    /// connected. It is [`Duration::ZERO`] when no attempt follows, because the audio sink failed.
262    Disconnected {
263        /// Why the attempt ended.
264        reason: String,
265        /// How long to wait before the next attempt; zero when none follows.
266        retry_in: Duration,
267    },
268    /// A stream was announced with the given format.
269    ///
270    /// The sink has been opened for this format before the event is emitted.
271    StreamStart {
272        /// Format of the new stream.
273        format: AudioFormat,
274    },
275    /// A player stream ended.
276    ///
277    /// Reported before the sink is flushed, so a host can mute or stop its output first. The
278    /// client flushes the sink itself as well, after this event. A seek does not end the stream;
279    /// it is reported as [`Event::StreamClear`], and chunks after it still belong to the open
280    /// stream.
281    StreamEnd {
282        /// Why the stream ended.
283        reason: StreamEndReason,
284    },
285    /// The server asked to drop buffered audio without ending the stream.
286    ///
287    /// Reported before the sink is flushed, so a host can restart its output or drop the matching
288    /// part of its own queue first. The announced format stays open, and chunks that follow still
289    /// belong to it.
290    StreamClear {
291        /// Server timestamp the audio should resume from, when the server named one.
292        from_timestamp: Option<i64>,
293    },
294    /// Now-playing metadata changed.
295    ///
296    /// Absent text fields are reported as empty strings, so a host can clear its display; absent
297    /// progress fields are `None`.
298    Track {
299        /// Track title.
300        title: String,
301        /// Track artist.
302        artist: String,
303        /// Album title.
304        album: String,
305        /// Album artist.
306        album_artist: String,
307        /// URL of the artwork image, empty when the server sent none.
308        artwork_url: String,
309        /// Position within the track in milliseconds, when the server reports one.
310        progress_ms: Option<u64>,
311        /// Track length in milliseconds, when the server reports one.
312        duration_ms: Option<u64>,
313        /// Playback speed per mille: `1000` is normal speed, `500` half speed and `0` paused.
314        ///
315        /// Reported as [`NORMAL_PLAYBACK_SPEED`] when the server sends no speed, because a track
316        /// without the field plays at normal speed.
317        playback_speed: u32,
318    },
319    /// The server's view of playback state changed.
320    State(PlaybackState),
321    /// The server asked this player to change its volume or mute state.
322    ///
323    /// The session applies the [`VolumePolicy`] from its configuration and reports the applied
324    /// level back to the server in `client/state`. The event carries both numbers, so a host can
325    /// see what the server asked for and what the policy allowed without repeating the policy.
326    /// `muted` is present for a mute command and absent for a volume command; a mute leaves the
327    /// level unchanged, so both numbers then name the level already in force.
328    Volume {
329        /// Level the server asked for, as it arrived on the wire.
330        ///
331        /// A non-conformant server can send a value above 100; it is reported unchanged so a host
332        /// can log it, while `applied` always stays inside the protocol's range.
333        requested: u8,
334        /// Level that was applied, always in the range 0-100.
335        applied: u8,
336        /// Mute state that was requested, absent for a volume command.
337        muted: Option<bool>,
338    },
339    /// A pairing completed and the record is stored.
340    ///
341    /// Reported after `server/pair-finalize`, once [`Storage`](crate::storage::Storage) accepted
342    /// the record. The record authenticates later connections to that server, and the server
343    /// normally rotates the live connection to it with an in-band re-handshake: the session swaps
344    /// its keys without reopening the stream, so playback continues and the next connection is
345    /// keyed by the same long-term PSK.
346    Paired {
347        /// Static public key of the server the record belongs to, as 43 base64url characters.
348        server_id: String,
349    },
350    /// The server dropped its pairing record for this client.
351    ///
352    /// Reported when a paired session receives `server/unpair`. The record is gone from
353    /// [`Storage`](crate::storage::Storage) by the time the event arrives, and the client closes
354    /// the connection: the next connection to that server lands in the Sentinel fallback unless the
355    /// host pairs again. The client does not send `client/goodbye` - the crate has no writer for it
356    /// (`docs/spec-deviations.md`, entry 9) - so the server sees the close without a reason.
357    ///
358    /// A record the host passed through
359    /// [`connect_with_psks`](crate::connect_with_psks) is not in a store the client may write, so
360    /// the client reports it and ends the connection without removing it: the host owns that
361    /// record and has to drop it.
362    Unpaired {
363        /// Static public key of the server that dropped the record, as 43 base64url characters.
364        server_id: String,
365    },
366    /// A server needs a pairing this client cannot complete with what it holds.
367    ///
368    /// Reported once per connection, never once per message: the situation is decided by the
369    /// Noise handshake, so the event fires after [`Event::Connected`] and before the session acts
370    /// on its first message, and never again while that connection lasts. A plain guest handshake -
371    /// an unpaired connection whose server announced the Sentinel key - is not a mismatch and
372    /// reports nothing.
373    ///
374    /// Nothing is removed or replaced on either side, and the session continues as an ordinary
375    /// unpaired one. A server that holds a record for this client will keep the connection in
376    /// pairing or idle until the host offers pairing again.
377    PairingRequired {
378        /// Static public key of the server that announced the unknown credential.
379        server_id: String,
380        /// What the server expects and the client cannot provide.
381        reason: PairingRequiredReason,
382    },
383    /// A pairing attempt ended without a record.
384    ///
385    /// Nothing was stored: the host has to offer pairing again, or act on the reason. The
386    /// connection itself stays open - a pairing abort is not a connection failure - so the session
387    /// keeps serving playback in the roles it had.
388    PairingFailed {
389        /// Why the attempt ended.
390        reason: PairingFailure,
391    },
392    /// A dynamic pairing code is ready for the operator.
393    ///
394    /// The code belongs to one attempt and is bound to the Noise handshake and to the two nonces
395    /// of that attempt. A client with a display or a speaker shows or speaks it; the operator then
396    /// types or scans it into the server. The code does not change across the rounds of an attempt,
397    /// so a host that already shows it can ignore a repeat with the same `code`, while `round`
398    /// tells it that another round is running.
399    ///
400    /// The value is deliberate: it is the method's whole point, and the host is expected to render
401    /// it. It is not key material, but it does authorise one pairing, so a host should not keep it
402    /// longer than the attempt.
403    #[cfg(feature = "pairing-code")]
404    PairingCode {
405        /// The code to show: six digits in the `digits` format, a version-1 token in `qr_code`.
406        code: String,
407        /// Emission format the server activated.
408        format: CodeFormat,
409        /// Round this emission belongs to, counting from one.
410        round: u32,
411    },
412}
413
414impl fmt::Debug for Event {
415    /// Formats an event, redacting the dynamic pairing code it may carry.
416    ///
417    /// A host renders that code deliberately, through the event itself; a `Debug` format is what a
418    /// panic, an assertion or a logging facade writes, and the code authorises one pairing, so it
419    /// must not appear there. Every other field is what a log line needs.
420    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
421        match self {
422            Self::Connected {
423                server_id,
424                encrypted,
425            } => formatter
426                .debug_struct("Connected")
427                .field("server_id", server_id)
428                .field("encrypted", encrypted)
429                .finish(),
430            Self::Disconnected { reason, retry_in } => formatter
431                .debug_struct("Disconnected")
432                .field("reason", reason)
433                .field("retry_in", retry_in)
434                .finish(),
435            Self::StreamStart { format } => formatter
436                .debug_struct("StreamStart")
437                .field("format", format)
438                .finish(),
439            Self::StreamEnd { reason } => formatter
440                .debug_struct("StreamEnd")
441                .field("reason", reason)
442                .finish(),
443            Self::StreamClear { from_timestamp } => formatter
444                .debug_struct("StreamClear")
445                .field("from_timestamp", from_timestamp)
446                .finish(),
447            Self::Track {
448                title,
449                artist,
450                album,
451                album_artist,
452                artwork_url,
453                progress_ms,
454                duration_ms,
455                playback_speed,
456            } => formatter
457                .debug_struct("Track")
458                .field("title", title)
459                .field("artist", artist)
460                .field("album", album)
461                .field("album_artist", album_artist)
462                .field("artwork_url", artwork_url)
463                .field("progress_ms", progress_ms)
464                .field("duration_ms", duration_ms)
465                .field("playback_speed", playback_speed)
466                .finish(),
467            Self::State(state) => formatter.debug_tuple("State").field(state).finish(),
468            Self::Volume {
469                requested,
470                applied,
471                muted,
472            } => formatter
473                .debug_struct("Volume")
474                .field("requested", requested)
475                .field("applied", applied)
476                .field("muted", muted)
477                .finish(),
478            Self::Paired { server_id } => formatter
479                .debug_struct("Paired")
480                .field("server_id", server_id)
481                .finish(),
482            Self::Unpaired { server_id } => formatter
483                .debug_struct("Unpaired")
484                .field("server_id", server_id)
485                .finish(),
486            Self::PairingRequired { server_id, reason } => formatter
487                .debug_struct("PairingRequired")
488                .field("server_id", server_id)
489                .field("reason", reason)
490                .finish(),
491            Self::PairingFailed { reason } => formatter
492                .debug_struct("PairingFailed")
493                .field("reason", reason)
494                .finish(),
495            #[cfg(feature = "pairing-code")]
496            Self::PairingCode { format, round, .. } => formatter
497                .debug_struct("PairingCode")
498                .field("code", &"<redacted>")
499                .field("format", format)
500                .field("round", round)
501                .finish(),
502        }
503    }
504}
505
506/// Playback state as the server describes it.
507#[derive(Debug, Clone, Default, PartialEq, Eq)]
508#[non_exhaustive]
509pub struct PlaybackState {
510    /// Commands the server accepts from clients in the same group.
511    pub supported_commands: Vec<String>,
512    /// Group volume in the range 0-100, when the server reports one.
513    pub volume: Option<u8>,
514    /// Group mute state, when the server reports one.
515    pub muted: Option<bool>,
516}
517
518/// A live connection.
519///
520/// The connection reconnects on its own after a drop, so the handle and the event stream outlive
521/// an individual session. Dropping the handle or the event stream ends it; [`ClientHandle::finished`]
522/// waits without ending it.
523#[derive(Debug)]
524pub struct ClientHandle {
525    task: Option<JoinHandle<Result<()>>>,
526    control: ControlHandle,
527    shutdown: Option<oneshot::Sender<()>>,
528}
529
530impl ClientHandle {
531    /// Returns a handle for the playback controls of this connection.
532    ///
533    /// The handle is a cheap clone; every copy controls the same connection.
534    #[must_use]
535    pub fn control(&self) -> ControlHandle {
536        self.control.clone()
537    }
538
539    /// Waits for the connection to end and returns its outcome.
540    ///
541    /// The connection ends when the handle or the event stream is dropped, or when the audio sink
542    /// fails; a dropped session is reconnected, not returned. Awaiting this keeps the handle alive,
543    /// so dropping the event stream is the usual way to stop.
544    pub async fn finished(mut self) -> Result<()> {
545        let task = self.task.take().expect("the handle owns its task");
546        task.await.context("the connection task panicked")?
547    }
548}
549
550impl Drop for ClientHandle {
551    fn drop(&mut self) {
552        // `finished` takes the task, so a handle that is only waiting on the connection does not
553        // stop it; a handle that is dropped asks the connection to end.
554        if self.task.is_some() {
555            if let Some(shutdown) = self.shutdown.take() {
556                let _ = shutdown.send(());
557            }
558        }
559    }
560}
561
562/// Playback controls for a live connection.
563///
564/// A call returns once the connection has handled it: a transport command has been written to the
565/// server, and a level or mute change has been recorded and included in the next state report. It
566/// is an error when the connection has ended, when no session is established at that moment, and
567/// when the server did not activate the role the command belongs to: transport commands need
568/// `controller@v1`, volume and mute state need `player@v1`. A transport command the server did not
569/// list in its controller state is refused as well, so a host can offer exactly the buttons the
570/// server accepts.
571#[derive(Debug, Clone)]
572pub struct ControlHandle {
573    commands: mpsc::UnboundedSender<ControlRequest>,
574    volume: Arc<AtomicU8>,
575}
576
577impl ControlHandle {
578    /// Resumes playback.
579    pub async fn play(&self) -> Result<()> {
580        self.transport("play").await
581    }
582
583    /// Pauses playback at the current position.
584    pub async fn pause(&self) -> Result<()> {
585        self.transport("pause").await
586    }
587
588    /// Skips to the next track.
589    pub async fn next(&self) -> Result<()> {
590        self.transport("next").await
591    }
592
593    /// Skips to the previous track.
594    pub async fn previous(&self) -> Result<()> {
595        self.transport("previous").await
596    }
597
598    /// Sets the output level, limited by [`ClientConfig::volume_policy`] against the level in
599    /// force, and returns the level that was applied.
600    ///
601    /// The level belongs to the connection: the session reports the applied value to the server
602    /// with its next state report, which is the initial report when the first clock measurement is
603    /// still pending, and every reconnect keeps it. A new connection starts from
604    /// [`ClientConfig::volume`], so a host passes the level it restored there and uses this call
605    /// for changes after that. [`ControlHandle::volume`] answers what is in force without a call.
606    pub async fn set_volume(&self, level: u8) -> Result<u8> {
607        self.send(ControlAction::Volume(level)).await
608    }
609
610    /// Reports the level the device is actually at, without applying the volume policy.
611    ///
612    /// [`ControlHandle::set_volume`] treats its argument as a request, so the policy may lower it
613    /// and above the threshold it limits one step. A host that knows the level its output is
614    /// really at - because the device applied a level at its own control, or because another
615    /// process raised it - reports that level with this call instead: it becomes the level in
616    /// force, [`ControlHandle::volume`] returns it, and the next `client/state` carries it
617    /// unchanged, so the server's view matches the output.
618    ///
619    /// The protocol's range still applies. A level above 100 is refused with an error before
620    /// anything is recorded or sent; the policy is not consulted and does not clamp the value.
621    ///
622    /// # Errors
623    /// Returns an error for a level above 100, for a connection that has ended, and when the
624    /// server did not activate `player@v1`.
625    pub async fn report_volume(&self, level: u8) -> Result<()> {
626        check_reported_level(level)?;
627        self.send(ControlAction::ReportVolume(level))
628            .await
629            .map(|_level| ())
630    }
631
632    /// Sets the mute state without changing the level.
633    ///
634    /// The reported level therefore stays what it was, and the server sees the mute in the
635    /// `muted` field alone.
636    pub async fn set_muted(&self, muted: bool) -> Result<()> {
637        self.send(ControlAction::Mute(muted)).await.map(|_level| ())
638    }
639
640    /// Returns the volume level in force.
641    ///
642    /// The value follows every change the connection made or received, including a mute, which
643    /// leaves it untouched. It is available without a call, so a host can render its slider while
644    /// the connection is reconnecting.
645    #[must_use]
646    pub fn volume(&self) -> u8 {
647        self.volume.load(Ordering::Relaxed)
648    }
649
650    /// Opens a pairing window on the live connection and starts a waiting static-code attempt.
651    ///
652    /// The pairing window is the client's half of the static code flow's operator gesture: the host
653    /// decides what the gesture is - a button press, a pinhole, a power-cycle pattern - and calls
654    /// this when it happened. The window belongs to the connection that is live now, so it is
655    /// opened there and closes when that connection ends, when the configured lifetime expires,
656    /// when a pairing completes, or after five failed key confirmations.
657    ///
658    /// # Errors
659    /// Returns an error when no connection is established at this moment. A call that arrives while
660    /// the client is reconnecting is refused rather than remembered for the next connection, which
661    /// the spec requires: a window admits attempts only on the connection that carries its gesture.
662    #[cfg(feature = "pairing-code")]
663    pub async fn open_pairing_window(&self) -> Result<()> {
664        self.send(ControlAction::OpenPairingWindow)
665            .await
666            .map(|_level| ())
667    }
668
669    /// Releases the dynamic flow's round limit: the deliberate operator action the spec requires.
670    ///
671    /// After twenty rounds without a verified `server_kc`, the client aborts the attempt and holds
672    /// further dynamic attempts back, answering their activations with `client/pair-pending`. The
673    /// counter is not partitioned by server and only this call - or a verified `server_kc` - resets
674    /// it. A host wires it to whatever gesture means "let this device try pairing again".
675    ///
676    /// Unlike a pairing window, the release needs no connection: the count belongs to the process,
677    /// and the next connection starts from a clean one. The call still answers the current level,
678    /// so it observes the same contract as the other control requests.
679    #[cfg(feature = "pairing-code")]
680    pub async fn release_holdback(&self) -> Result<()> {
681        self.send(ControlAction::ReleaseHoldback)
682            .await
683            .map(|_level| ())
684    }
685
686    /// Sends one controller command.
687    async fn transport(&self, command: &'static str) -> Result<()> {
688        self.send(ControlAction::Transport(command))
689            .await
690            .map(|_level| ())
691    }
692
693    /// Queues one request and waits for the level in force after it.
694    async fn send(&self, action: ControlAction) -> Result<u8> {
695        let (reply, response) = oneshot::channel();
696        self.commands
697            .send(ControlRequest { action, reply })
698            .map_err(|_| anyhow!("the connection has ended"))?;
699        response
700            .await
701            .map_err(|_| anyhow!("the connection ended before it answered"))?
702    }
703}
704
705/// What a [`ControlHandle`] asks the session to do.
706#[derive(Debug)]
707pub(crate) enum ControlAction {
708    /// A controller command, by wire name.
709    Transport(&'static str),
710    /// Set the output level, subject to the volume limit.
711    Volume(u8),
712    /// Record the level the output is actually at, without the volume limit.
713    ReportVolume(u8),
714    /// Set the mute state, keeping the level.
715    Mute(bool),
716    /// Open a pairing window for this connection and start a waiting static-code attempt.
717    #[cfg(feature = "pairing-code")]
718    OpenPairingWindow,
719    /// Reset the dynamic flow's round counter and start the attempt it held back.
720    #[cfg(feature = "pairing-code")]
721    ReleaseHoldback,
722}
723
724/// One request from a [`ControlHandle`], with the channel its answer travels back on.
725///
726/// The answer is the volume level in force after the request; a transport command and a mute
727/// leave it unchanged.
728pub(crate) struct ControlRequest {
729    /// Operation to perform.
730    pub(crate) action: ControlAction,
731    /// Answer for the waiting call.
732    pub(crate) reply: oneshot::Sender<Result<u8>>,
733}
734
735/// The receiving end of a session's [`Event`] stream.
736///
737/// [`EventStream::next`] returns `None` once the connection has ended. An [`Event::Disconnected`]
738/// is not necessarily the last event: the client reconnects and reports the next attempt's events
739/// on the same stream, and only a fatal audio-sink failure or a dropped handle ends the sequence.
740/// Dropping the stream ends the connection: the next time the client would emit an event, it stops
741/// instead.
742#[derive(Debug)]
743pub struct EventStream {
744    events: mpsc::UnboundedReceiver<Event>,
745}
746
747impl EventStream {
748    /// Waits for the next event.
749    pub async fn next(&mut self) -> Option<Event> {
750        self.events.recv().await
751    }
752}
753
754/// Namespaced entry point, for callers that prefer a type to the free function.
755#[derive(Debug, Clone, Copy, Default)]
756pub struct Client;
757
758impl Client {
759    /// Connects to `config.server` and returns the handle and event stream.
760    ///
761    /// See [`connect`] for the details.
762    pub async fn connect(
763        config: ClientConfig,
764        sink: Box<dyn Sink>,
765    ) -> Result<(ClientHandle, EventStream)> {
766        connect(config, sink).await
767    }
768
769    /// Connects with pairing keys the host stores for known servers.
770    ///
771    /// See [`connect_with_psks`] for the details.
772    pub async fn connect_with_psks(
773        config: ClientConfig,
774        sink: Box<dyn Sink>,
775        psks: Vec<StoredPsk>,
776    ) -> Result<(ClientHandle, EventStream)> {
777        connect_with_psks(config, sink, psks).await
778    }
779}
780
781/// Connects to a server and returns its handle and event stream.
782///
783/// The configuration is validated before this returns; the connection itself runs in a spawned
784/// task and is reported through the event stream, with [`Event::Connected`] as the first event of a
785/// successful attempt.
786///
787/// The task owns the sink and every attempt, so it reconnects after a drop with the same identity
788/// and sink and with the level, mute state and roles the previous session had. Each drop is
789/// reported as [`Event::Disconnected`] together with the delay before the next attempt. The
790/// connection ends when the sink fails, which the host has to repair, or when the handle or the
791/// event stream is dropped.
792///
793/// # Errors
794/// Returns an error for an invalid [`ClientConfig`] and for a server address this build cannot use
795/// (including a TLS URL). An unreachable server is not an error: the connection reports it as
796/// [`Event::Disconnected`] and keeps retrying.
797///
798/// # Panics
799/// Panics when called outside a Tokio runtime, because the connection is spawned.
800pub async fn connect(
801    config: ClientConfig,
802    sink: Box<dyn Sink>,
803) -> Result<(ClientHandle, EventStream)> {
804    connect_with_psks(config, sink, Vec::new()).await
805}
806
807/// Connects with pairing keys the host stores for known servers.
808///
809/// The server announces a `psk_id` and `psk_category` in Noise message 1. A candidate matches when
810/// its category and derived id both match the announcement; its `server_id` must then equal the one
811/// in `server/init`. On a lookup miss the initial handshake continues with the published Sentinel
812/// key, which is why [`connect`] is the same call with no candidates.
813///
814/// The keys are used for the handshake only; they are not stored or logged. A reconnect uses them
815/// again, so a pairing that worked keeps working. A [`Storage`](crate::storage::Storage) configured
816/// on `config` joins them: its records are read for every attempt, and on the same `server_id` the
817/// stored record wins over `explicit`, because the store is the authority for the servers it knows.
818/// The pairing PSK the store holds is always a candidate as well, whether or not a pairing is
819/// running.
820///
821/// # Errors
822/// Same as [`connect`]. A record that belongs to another server fails the handshake of that
823/// attempt and is reported as [`Event::Disconnected`]. A store that cannot be read or cannot hold
824/// the pairing PSK is reported from this call before the first attempt. A configuration with a
825/// store makes the client draw and persist its pairing PSK on a device's first run.
826pub async fn connect_with_psks(
827    config: ClientConfig,
828    sink: Box<dyn Sink>,
829    psks: Vec<StoredPsk>,
830) -> Result<(ClientHandle, EventStream)> {
831    config.validate()?;
832    let endpoint = endpoint(&config.server)?;
833    // The pairing PSK is settled before the first attempt, so a store that cannot hold it is
834    // reported to the caller instead of a connection that silently cannot pair. A restored key is
835    // used as it is; a missing one is drawn and stored once, here.
836    let pairing = match config.storage.as_deref() {
837        Some(storage) => Some(load_or_draw_pairing_psk(storage)?),
838        None => None,
839    };
840
841    let (events, receiver) = mpsc::unbounded_channel();
842    let (commands, control) = mpsc::unbounded_channel();
843    let (shutdown, shutdown_rx) = oneshot::channel();
844    let reported_volume = Arc::new(AtomicU8::new(config.volume));
845    // The dynamic flow's round counter belongs to the process, not to a connection or a server:
846    // only a verified `server_kc` or a deliberate operator action resets it.
847    #[cfg(feature = "pairing-code")]
848    let failed_rounds = Arc::new(AtomicU32::new(0));
849
850    let carried = Carried {
851        sink,
852        control: Some(control),
853        volume: config.volume,
854        muted: config.muted,
855        active_roles: Vec::new(),
856        #[cfg(feature = "pairing-code")]
857        failed_rounds: Arc::clone(&failed_rounds),
858    };
859    let connection = Connection {
860        endpoint,
861        config,
862        psks,
863        pairing,
864        events: events.clone(),
865        reported_volume: Arc::clone(&reported_volume),
866        #[cfg(feature = "pairing-code")]
867        failed_rounds,
868    };
869
870    let task = tokio::spawn(async move {
871        tokio::select! {
872            result = serve_until_dropped(connection, carried) => result,
873            _ = shutdown_rx => Ok(()),
874        }
875    });
876
877    let handle = ClientHandle {
878        task: Some(task),
879        control: ControlHandle {
880            commands,
881            volume: reported_volume,
882        },
883        shutdown: Some(shutdown),
884    };
885    Ok((handle, EventStream { events: receiver }))
886}
887
888/// Opens one WebSocket, treating an address that does not answer as an error.
889async fn open(endpoint: &str) -> Result<Transport> {
890    tokio::time::timeout(CONNECT_TIMEOUT, Transport::connect(endpoint))
891        .await
892        .with_context(|| format!("timed out connecting to {endpoint}"))?
893}
894
895/// The parts of a connection that do not change across attempts.
896struct Connection {
897    endpoint: String,
898    config: ClientConfig,
899    psks: Vec<StoredPsk>,
900    /// This client's pairing PSK, present exactly when a store is configured.
901    pairing: Option<PairingPsk>,
902    events: mpsc::UnboundedSender<Event>,
903    /// Level shared with every [`ControlHandle`].
904    reported_volume: Arc<AtomicU8>,
905    /// Failed dynamic rounds since the last verified `server_kc`, shared with every session this
906    /// connection runs and with [`ControlHandle::release_holdback`].
907    #[cfg(feature = "pairing-code")]
908    failed_rounds: Arc<AtomicU32>,
909}
910
911impl Connection {
912    /// Delivers one event, ignoring a stream the host dropped.
913    fn emit(&self, event: Event) {
914        let _ = self.events.send(event);
915    }
916}
917
918/// One wake-up while no session is established.
919enum Wakeup {
920    /// A control handle sent a request.
921    Control(Option<ControlRequest>),
922    /// The delay elapsed.
923    Deadline,
924    /// The host dropped the event stream.
925    Closed,
926}
927
928/// Answers a request that arrived while no session was established.
929///
930/// A pairing window belongs to a connection and is refused; releasing the round hold-back belongs
931/// to the process and is honoured, so an operator gesture made during a reconnect is not lost.
932#[cfg(feature = "pairing-code")]
933fn refuse(connection: &Connection, carried: &Carried, request: ControlRequest) {
934    if matches!(request.action, ControlAction::ReleaseHoldback) {
935        connection.failed_rounds.store(0, Ordering::SeqCst);
936        let _ = request.reply.send(Ok(carried.volume));
937        return;
938    }
939    let _ = request
940        .reply
941        .send(Err(anyhow!("no connection is established")));
942}
943
944/// Answers a request that arrived while no session was established.
945#[cfg(not(feature = "pairing-code"))]
946fn refuse(request: ControlRequest) {
947    let _ = request
948        .reply
949        .send(Err(anyhow!("no connection is established")));
950}
951
952/// Waits before the next attempt, refusing control requests meanwhile.
953///
954/// Returns `false` when the host dropped the event stream and the connection should end.
955async fn wait_before_retry(
956    connection: &Connection,
957    carried: &mut Carried,
958    delay: Duration,
959) -> bool {
960    let deadline = tokio::time::Instant::now() + delay;
961    loop {
962        if connection.events.is_closed() {
963            return false;
964        }
965        let control = &mut carried.control;
966        let wakeup = tokio::select! {
967            biased;
968            request = async {
969                match control {
970                    Some(receiver) => receiver.recv().await,
971                    None => std::future::pending().await,
972                }
973            } => Wakeup::Control(request),
974            () = tokio::time::sleep_until(deadline) => Wakeup::Deadline,
975            () = connection.events.closed() => Wakeup::Closed,
976        };
977        match wakeup {
978            Wakeup::Control(Some(request)) => {
979                #[cfg(feature = "pairing-code")]
980                refuse(connection, carried, request);
981                #[cfg(not(feature = "pairing-code"))]
982                refuse(request);
983            }
984            Wakeup::Control(None) => *control = None,
985            Wakeup::Deadline => return true,
986            Wakeup::Closed => return false,
987        }
988    }
989}
990
991/// Runs connection attempts until the host drops the connection or the sink fails.
992///
993/// Every attempt, including the first, is opened here. A failed one is followed by the next after
994/// the delay [`next_backoff`] computes, with the sink, the level, the mute state and the roles
995/// carried over.
996async fn serve_until_dropped(connection: Connection, mut carried: Carried) -> Result<()> {
997    // The first attempt is not preceded by a wait, but the policy starts at the initial delay, so a
998    // failure before any session connected reports two seconds: one growth step from that value.
999    let mut delay = INITIAL_BACKOFF;
1000
1001    loop {
1002        let transport = match open(&connection.endpoint).await {
1003            Ok(transport) => transport,
1004            Err(error) => {
1005                delay = next_backoff(delay, false, connection.config.max_backoff);
1006                connection.emit(Event::Disconnected {
1007                    reason: format!("cannot connect to {}: {error:#}", connection.endpoint),
1008                    retry_in: delay,
1009                });
1010                if !wait_before_retry(&connection, &mut carried, delay).await {
1011                    return Ok(());
1012                }
1013                continue;
1014            }
1015        };
1016
1017        let attempt = session::attempt(
1018            transport,
1019            &connection.config,
1020            &connection.events,
1021            &connection.psks,
1022            connection.pairing,
1023            &connection.reported_volume,
1024            carried,
1025        )
1026        .await;
1027        carried = attempt.carried;
1028
1029        // Nothing buffered for the session that ended may become audible later; the flush runs
1030        // before the host hears about the drop so the output stops even if the next attempt takes
1031        // a while.
1032        let flush_error = carried.sink.flush().err().map(|error| {
1033            error.context("the audio sink rejected a flush after the connection ended")
1034        });
1035
1036        // A broken output cannot be repaired by reconnecting, and neither can a flush that fails
1037        // after the session; both end the connection instead of scheduling another attempt.
1038        let fatal = attempt.sink_failed || flush_error.is_some();
1039        delay = if fatal {
1040            // No attempt follows, so there is no delay to recommend.
1041            Duration::ZERO
1042        } else {
1043            next_backoff(delay, attempt.connected, connection.config.max_backoff)
1044        };
1045        connection.emit(Event::Disconnected {
1046            reason: attempt.ending.reason(),
1047            retry_in: delay,
1048        });
1049
1050        if attempt.sink_failed {
1051            // The host has to fix the sink; a retry would only fail the same way.
1052            return match attempt.ending {
1053                session::Ending::Failed(error) => Err(error),
1054                session::Ending::Closed | session::Ending::Unpaired => {
1055                    Err(anyhow!("the audio sink failed"))
1056                }
1057            };
1058        }
1059        if let Some(error) = flush_error {
1060            return Err(error);
1061        }
1062
1063        if !wait_before_retry(&connection, &mut carried, delay).await {
1064            return Ok(());
1065        }
1066    }
1067}
1068
1069/// Splits a URL tail into the part before a query or fragment and the marker onward.
1070fn split_marker(value: &str) -> (&str, &str) {
1071    match value.find(['?', '#']) {
1072        Some(index) => value.split_at(index),
1073        None => (value, ""),
1074    }
1075}
1076
1077/// Builds the WebSocket URL for a configured server address.
1078///
1079/// A bare `host:port` uses the default `/sendspin` path, and so does a `ws://` URL without a path.
1080/// A URL with an explicit path is used unchanged. TLS is rejected: this build carries no TLS
1081/// stack, and pretending otherwise would end in a confusing connection error.
1082fn endpoint(server: &str) -> Result<String> {
1083    let server = server.trim();
1084    if server.is_empty() {
1085        bail!("the server address is empty");
1086    }
1087    if server.starts_with("wss://") {
1088        bail!("TLS is not supported by this build; use a ws:// address or host:port");
1089    }
1090    if let Some(rest) = server.strip_prefix("ws://") {
1091        if rest.is_empty() {
1092            bail!("the WebSocket address {server:?} names no host");
1093        }
1094        // A query or fragment belongs after the path, so the default path has to be inserted
1095        // before it rather than appended to the whole URL.
1096        let (before_marker, after_marker) = split_marker(rest);
1097        let Some((authority, path)) = before_marker.split_once('/') else {
1098            if before_marker.is_empty() {
1099                bail!("the WebSocket address {server:?} names no host");
1100            }
1101            return Ok(format!("ws://{before_marker}/sendspin{after_marker}"));
1102        };
1103        if authority.is_empty() {
1104            bail!("the WebSocket address {server:?} names no host");
1105        }
1106        if path.is_empty() {
1107            return Ok(format!("ws://{authority}/sendspin{after_marker}"));
1108        }
1109        return Ok(format!("ws://{before_marker}{after_marker}"));
1110    }
1111    if server.contains("://") {
1112        bail!("unsupported URL scheme in {server:?}; use ws:// or host:port");
1113    }
1114    let (before_marker, after_marker) = split_marker(server);
1115    if before_marker.is_empty() {
1116        bail!("the server address is empty");
1117    }
1118    Ok(format!("ws://{before_marker}/sendspin{after_marker}"))
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123    use super::*;
1124
1125    /// A pairing code is a credential for one attempt: `Debug` names it but never prints it.
1126    #[cfg(feature = "pairing-code")]
1127    #[test]
1128    fn the_pairing_code_event_formats_without_its_code() {
1129        for (code, format) in [
1130            ("482913".to_owned(), CodeFormat::Digits),
1131            (
1132                "SP:1QJOHGMGBXP55Y6KMJD3KOYR9F6OWYD6QQPIKEFY".to_owned(),
1133                CodeFormat::QrCode,
1134            ),
1135        ] {
1136            let event = Event::PairingCode {
1137                code: code.clone(),
1138                format,
1139                round: 3,
1140            };
1141            let text = format!("{event:?}");
1142            assert!(text.contains("code: \"<redacted>\""), "got: {text}");
1143            assert!(
1144                !text.contains(&code),
1145                "the code must never reach a log line: {text}"
1146            );
1147            assert!(
1148                text.contains(&format!("format: {format:?}")),
1149                "the format is not secret: {text}"
1150            );
1151            assert!(text.contains("round: 3"), "the round is not secret: {text}");
1152        }
1153    }
1154
1155    /// The record-lifecycle events name the server, which is not secret, and nothing else.
1156    #[test]
1157    fn the_record_lifecycle_events_format_their_server_id() {
1158        let server_id = "B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b".to_owned();
1159
1160        let unpaired = format!(
1161            "{:?}",
1162            Event::Unpaired {
1163                server_id: server_id.clone(),
1164            }
1165        );
1166        assert!(
1167            unpaired.contains(&format!("Unpaired {{ server_id: \"{server_id}\" }}")),
1168            "got: {unpaired}"
1169        );
1170
1171        let required = format!(
1172            "{:?}",
1173            Event::PairingRequired {
1174                server_id: server_id.clone(),
1175                reason: PairingRequiredReason::CredentialMismatch,
1176            }
1177        );
1178        assert!(required.contains(&server_id), "got: {required}");
1179        assert!(
1180            required.contains("CredentialMismatch"),
1181            "the reason is what the host acts on: {required}"
1182        );
1183        assert!(
1184            !required.contains("<redacted>"),
1185            "neither event carries a secret, so neither redacts a field: {required}"
1186        );
1187    }
1188
1189    /// Every other event keeps the fields a log line needs.
1190    #[test]
1191    fn an_event_still_formats_its_readable_fields() {
1192        let text = format!(
1193            "{:?}",
1194            Event::Disconnected {
1195                reason: "the server closed the connection".to_owned(),
1196                retry_in: Duration::from_secs(2),
1197            }
1198        );
1199        assert!(
1200            text.contains("Disconnected { reason: \"the server closed the connection\""),
1201            "got: {text}"
1202        );
1203        assert!(text.contains("retry_in: 2s"), "got: {text}");
1204    }
1205
1206    #[test]
1207    fn every_abort_reason_round_trips_through_the_wire_spelling() {
1208        for (wire, reason) in [
1209            ("attempt_timeout", PairingFailure::AttemptTimeout),
1210            ("method_not_supported", PairingFailure::MethodNotSupported),
1211            ("pairing_code_mismatch", PairingFailure::PairingCodeMismatch),
1212            ("user_cancelled", PairingFailure::UserCancelled),
1213            ("concurrent_attempt", PairingFailure::ConcurrentAttempt),
1214        ] {
1215            assert_eq!(reason.as_str(), wire);
1216            assert_eq!(PairingFailure::from_wire(wire), reason);
1217        }
1218
1219        // A reason from a later revision is carried, not rejected.
1220        assert_eq!(
1221            PairingFailure::from_wire("future_reason"),
1222            PairingFailure::Unrecognised("future_reason".to_owned())
1223        );
1224        assert_eq!(
1225            PairingFailure::Unrecognised("future_reason".to_owned()).as_str(),
1226            "future_reason"
1227        );
1228    }
1229
1230    #[test]
1231    fn a_bare_address_gets_the_default_websocket_endpoint() {
1232        assert_eq!(
1233            endpoint("192.0.2.10:8927").unwrap(),
1234            "ws://192.0.2.10:8927/sendspin"
1235        );
1236        assert_eq!(
1237            endpoint(" 192.0.2.10:8927 ").unwrap(),
1238            "ws://192.0.2.10:8927/sendspin"
1239        );
1240        assert_eq!(
1241            endpoint("ws://example.test:1").unwrap(),
1242            "ws://example.test:1/sendspin"
1243        );
1244        assert_eq!(
1245            endpoint("ws://example.test:1/").unwrap(),
1246            "ws://example.test:1/sendspin"
1247        );
1248        assert_eq!(
1249            endpoint("ws://example.test:1/player").unwrap(),
1250            "ws://example.test:1/player"
1251        );
1252    }
1253
1254    #[test]
1255    fn a_query_or_fragment_stays_after_the_default_path() {
1256        assert_eq!(
1257            endpoint("ws://example.test:1?token=1").unwrap(),
1258            "ws://example.test:1/sendspin?token=1"
1259        );
1260        assert_eq!(
1261            endpoint("ws://example.test:1#frag").unwrap(),
1262            "ws://example.test:1/sendspin#frag"
1263        );
1264        assert_eq!(
1265            endpoint("ws://example.test:1/?token=1").unwrap(),
1266            "ws://example.test:1/sendspin?token=1"
1267        );
1268        assert_eq!(
1269            endpoint("ws://example.test:1/player?token=1").unwrap(),
1270            "ws://example.test:1/player?token=1"
1271        );
1272        assert_eq!(
1273            endpoint("example.test:1?token=1").unwrap(),
1274            "ws://example.test:1/sendspin?token=1"
1275        );
1276    }
1277
1278    #[test]
1279    fn an_address_this_build_cannot_use_is_rejected() {
1280        for server in [
1281            "",
1282            "   ",
1283            "wss://example.test",
1284            "https://example.test",
1285            "ws://",
1286            "ws://?token=1",
1287            "ws://#fragment",
1288            "ws:///player",
1289            "?token=1",
1290            "#fragment",
1291        ] {
1292            assert!(
1293                endpoint(server).is_err(),
1294                "{server:?} must not be turned into a cleartext endpoint"
1295            );
1296        }
1297    }
1298
1299    use crate::test_support::NullSink;
1300
1301    /// Builds the parts of a connection that do not change across attempts.
1302    fn connection_at(endpoint: &str, events: mpsc::UnboundedSender<Event>) -> Connection {
1303        Connection {
1304            endpoint: endpoint.to_owned(),
1305            config: ClientConfig {
1306                server: endpoint.to_owned(),
1307                player_name: "Test player".to_owned(),
1308                device_info: None,
1309                identity: crate::Identity::generate(),
1310                storage: None,
1311                audio_mode: crate::AudioMode::Passthrough,
1312                volume: 42,
1313                muted: false,
1314                volume_policy: VolumePolicy::default(),
1315                max_backoff: Duration::from_secs(30),
1316                pairing_timeout: DEFAULT_PAIRING_TIMEOUT,
1317                #[cfg(feature = "pairing-code")]
1318                static_pairing_code: None,
1319                #[cfg(feature = "pairing-code")]
1320                pairing_window: crate::DEFAULT_PAIRING_WINDOW,
1321                #[cfg(feature = "pairing-code")]
1322                pairing_pending_text: None,
1323                #[cfg(feature = "pairing-code")]
1324                code_formats: Vec::new(),
1325                #[cfg(feature = "pairing-code")]
1326                code_out_channels: Vec::new(),
1327            },
1328            psks: Vec::new(),
1329            pairing: None,
1330            events,
1331            reported_volume: Arc::new(AtomicU8::new(42)),
1332            #[cfg(feature = "pairing-code")]
1333            failed_rounds: Arc::new(AtomicU32::new(0)),
1334        }
1335    }
1336
1337    fn empty_carried(control: Option<mpsc::UnboundedReceiver<ControlRequest>>) -> Carried {
1338        Carried {
1339            sink: Box::new(NullSink),
1340            control,
1341            volume: 42,
1342            muted: false,
1343            active_roles: Vec::new(),
1344            #[cfg(feature = "pairing-code")]
1345            failed_rounds: Arc::new(AtomicU32::new(0)),
1346        }
1347    }
1348
1349    #[tokio::test]
1350    async fn a_retry_wait_without_a_control_handle_still_honours_the_delay() {
1351        let (events, _receiver) = mpsc::unbounded_channel();
1352        let connection = connection_at("127.0.0.1:1", events);
1353        let (commands, control) = mpsc::unbounded_channel();
1354        drop(commands);
1355        let mut carried = empty_carried(Some(control));
1356
1357        let started = std::time::Instant::now();
1358        let retry = wait_before_retry(&connection, &mut carried, Duration::from_millis(50)).await;
1359
1360        assert!(retry, "the delay elapsed, so the next attempt must follow");
1361        assert!(
1362            started.elapsed() >= Duration::from_millis(50),
1363            "the delay must be waited out, not skipped"
1364        );
1365        assert!(
1366            carried.control.is_none(),
1367            "a control channel whose senders are gone is dropped"
1368        );
1369    }
1370
1371    #[tokio::test]
1372    async fn dropping_the_event_stream_during_a_retry_ends_the_connection() {
1373        let (events, receiver) = mpsc::unbounded_channel();
1374        let connection = connection_at("127.0.0.1:1", events);
1375        let mut carried = empty_carried(None);
1376
1377        let retry = wait_before_retry(&connection, &mut carried, Duration::from_secs(60));
1378        tokio::pin!(retry);
1379        let mut finished = false;
1380        tokio::select! {
1381            _ = &mut retry => finished = true,
1382            () = tokio::time::sleep(Duration::from_millis(50)) => {}
1383        }
1384        assert!(!finished, "the wait must not end while the stream is open");
1385
1386        drop(receiver);
1387        assert!(
1388            !retry.await,
1389            "a dropped event stream must stop the retry loop"
1390        );
1391    }
1392
1393    #[tokio::test]
1394    async fn a_failed_attempt_with_no_event_stream_ends_the_connection() {
1395        // Bind and release a loopback port, so the open fails immediately rather than timing out.
1396        let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("a loopback port");
1397        let address = listener.local_addr().expect("the bound address");
1398        drop(listener);
1399
1400        let (events, receiver) = mpsc::unbounded_channel();
1401        drop(receiver);
1402        let connection = connection_at(&address.to_string(), events);
1403
1404        let outcome = serve_until_dropped(connection, empty_carried(None)).await;
1405        assert!(
1406            outcome.is_ok(),
1407            "a host that dropped the stream ends the connection cleanly"
1408        );
1409    }
1410
1411    #[tokio::test]
1412    async fn the_namespace_entry_points_wrap_the_free_functions() {
1413        // A bad configuration is rejected by both before any socket is opened, which pins the
1414        // forwarding: a wrapper that inverted the result would not return this error.
1415        let mut config = connection_at("127.0.0.1:1", mpsc::unbounded_channel().0).config;
1416        config.player_name.clear();
1417        let error = Client::connect(config, Box::new(NullSink))
1418            .await
1419            .expect_err("an invalid configuration must be rejected");
1420        assert!(format!("{error:#}").contains("player_name"));
1421
1422        let mut config = connection_at("127.0.0.1:1", mpsc::unbounded_channel().0).config;
1423        config.server = "wss://example.test".to_owned();
1424        let error = Client::connect_with_psks(config, Box::new(NullSink), Vec::new())
1425            .await
1426            .expect_err("a TLS address must be rejected before connecting");
1427        assert!(format!("{error:#}").contains("TLS"));
1428    }
1429}