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