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