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::{AtomicBool, 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 buffered audio is discarded or flushed, so a host can restart its
367 /// output or drop the matching part of its own queue first. The announced format stays open,
368 /// and chunks that follow still 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: unpaired access is off and the server sent a
471 /// `server/activate` that would be admissible if it were on. The value is
472 /// [`ClientConfig::unpaired_access`] unless [`ControlHandle::set_unpaired_access`] changed it on
473 /// this connection. That report fires at most once, immediately before the client closes the
474 /// connection with `client/goodbye` reason `pairing_required`, and never for a session whose
475 /// setting admits unpaired access. A connection the host closes because it turned the setting
476 /// off reports no such event: that is a host choice, not a refused activation. One connection
477 /// can therefore report this event twice, once per reason, when the handshake found a
478 /// credential mismatch and the activation is then refused.
479 ///
480 /// In the credential-mismatch case nothing is removed or replaced on either side, and the
481 /// session continues as an ordinary unpaired one. A server that holds a record for this client
482 /// will keep the connection in pairing or idle until the host offers pairing again.
483 PairingRequired {
484 /// Static public key of the server this requirement concerns, as 43 base64url characters.
485 server_id: String,
486 /// Which situation produced the requirement: a credential mismatch, or a refused
487 /// unpaired session.
488 reason: PairingRequiredReason,
489 },
490 /// A pairing attempt ended without a record.
491 ///
492 /// Nothing was stored: the host has to offer pairing again, or act on the reason. The
493 /// connection itself stays open - a pairing abort is not a connection failure - so the session
494 /// keeps serving playback in the roles it had.
495 PairingFailed {
496 /// Why the attempt ended.
497 reason: PairingFailure,
498 },
499 /// A dynamic pairing code is ready for the operator.
500 ///
501 /// The code belongs to one attempt and is bound to the Noise handshake and to the two nonces
502 /// of that attempt. A client with a display or a speaker shows or speaks it; the operator then
503 /// types or scans it into the server. The code does not change across the rounds of an attempt,
504 /// so a host that already shows it can ignore a repeat with the same `code`, while `round`
505 /// tells it that another round is running.
506 ///
507 /// The value is deliberate: it is the method's whole point, and the host is expected to render
508 /// it. It is not key material, but it does authorise one pairing, so a host should not keep it
509 /// longer than the attempt.
510 #[cfg(feature = "pairing-code")]
511 PairingCode {
512 /// The code to show: six digits in the `digits` format, a version-1 token in `qr_code`.
513 code: String,
514 /// Emission format the server activated.
515 format: CodeFormat,
516 /// Round this emission belongs to, counting from one.
517 round: u32,
518 },
519}
520
521impl fmt::Debug for Event {
522 /// Formats an event, redacting the dynamic pairing code it may carry.
523 ///
524 /// A host renders that code deliberately, through the event itself; a `Debug` format is what a
525 /// panic, an assertion or a logging facade writes, and the code authorises one pairing, so it
526 /// must not appear there. Every other field is what a log line needs.
527 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
528 match self {
529 Self::Connected {
530 server_id,
531 encrypted,
532 } => formatter
533 .debug_struct("Connected")
534 .field("server_id", server_id)
535 .field("encrypted", encrypted)
536 .finish(),
537 Self::Disconnected { reason, retry_in } => formatter
538 .debug_struct("Disconnected")
539 .field("reason", reason)
540 .field("retry_in", retry_in)
541 .finish(),
542 Self::ServerError { reason } => formatter
543 .debug_struct("ServerError")
544 .field("reason", reason)
545 .finish(),
546 Self::StreamStart { format } => formatter
547 .debug_struct("StreamStart")
548 .field("format", format)
549 .finish(),
550 Self::StreamEnd { reason } => formatter
551 .debug_struct("StreamEnd")
552 .field("reason", reason)
553 .finish(),
554 Self::StreamClear { from_timestamp } => formatter
555 .debug_struct("StreamClear")
556 .field("from_timestamp", from_timestamp)
557 .finish(),
558 Self::Track {
559 title,
560 artist,
561 album,
562 album_artist,
563 artwork_url,
564 progress_ms,
565 duration_ms,
566 playback_speed,
567 } => formatter
568 .debug_struct("Track")
569 .field("title", title)
570 .field("artist", artist)
571 .field("album", album)
572 .field("album_artist", album_artist)
573 .field("artwork_url", artwork_url)
574 .field("progress_ms", progress_ms)
575 .field("duration_ms", duration_ms)
576 .field("playback_speed", playback_speed)
577 .finish(),
578 Self::State(state) => formatter.debug_tuple("State").field(state).finish(),
579 Self::GroupIdNotCanonical { len } => formatter
580 .debug_struct("GroupIdNotCanonical")
581 .field("len", len)
582 .finish(),
583 Self::Volume {
584 requested,
585 applied,
586 muted,
587 } => formatter
588 .debug_struct("Volume")
589 .field("requested", requested)
590 .field("applied", applied)
591 .field("muted", muted)
592 .finish(),
593 Self::Paired { server_id } => formatter
594 .debug_struct("Paired")
595 .field("server_id", server_id)
596 .finish(),
597 Self::Unpaired { server_id } => formatter
598 .debug_struct("Unpaired")
599 .field("server_id", server_id)
600 .finish(),
601 Self::PairingRequired { server_id, reason } => formatter
602 .debug_struct("PairingRequired")
603 .field("server_id", server_id)
604 .field("reason", reason)
605 .finish(),
606 Self::PairingFailed { reason } => formatter
607 .debug_struct("PairingFailed")
608 .field("reason", reason)
609 .finish(),
610 #[cfg(feature = "pairing-code")]
611 Self::PairingCode { format, round, .. } => formatter
612 .debug_struct("PairingCode")
613 .field("code", &"<redacted>")
614 .field("format", format)
615 .field("round", round)
616 .finish(),
617 }
618 }
619}
620
621/// Playback state as the server describes it.
622///
623/// The group fields come from `group/update`, which is the authoritative source: every message
624/// carries all three, so the latest one is the group's identity and playback state. The controller
625/// fields come from `server/state` and stay part of the picture when a group update arrives.
626#[derive(Debug, Clone, Default, PartialEq, Eq)]
627#[non_exhaustive]
628pub struct PlaybackState {
629 /// Commands the server accepts from clients in the same group.
630 pub supported_commands: Vec<String>,
631 /// Group volume in the range 0-100, when the server reports one.
632 pub volume: Option<u8>,
633 /// Group mute state, when the server reports one.
634 pub muted: Option<bool>,
635 /// Highest absolute position [`ControlHandle::seek`] may target, in milliseconds.
636 ///
637 /// [`supported_commands`](PlaybackState::supported_commands) says whether the server offers
638 /// absolute or relative seek; this says how far an absolute target may go. It is `None`
639 /// before the first controller state and when the server advertised `seek` without naming a
640 /// range, and in both cases [`ControlHandle::seek`] refuses rather than sending a target it
641 /// cannot check. A `group/update` leaves it alone, because it belongs to the controller state.
642 pub seek_max_ms: Option<u64>,
643 /// Playback state of the group, once a `group/update` arrived.
644 ///
645 /// `playing` and `stopped` are the values this revision defines; a paused group reports
646 /// `stopped`. A value this revision does not name is carried verbatim.
647 pub playback_state: Option<String>,
648 /// Identifier of the group, once a `group/update` arrived.
649 ///
650 /// The spec gives it as 43 unpadded base64url characters; the default configuration also
651 /// carries a well-formed foreign value such as a UUID, because a real server sends one. See
652 /// [`ClientConfig::strict_group_id`] and [`Event::GroupIdNotCanonical`].
653 pub group_id: Option<String>,
654 /// Friendly name of the group, once a `group/update` arrived.
655 pub group_name: Option<String>,
656}
657
658/// A live connection.
659///
660/// The connection reconnects on its own after a drop, so the handle and the event stream outlive
661/// an individual session. Dropping the handle or the event stream ends it; [`ClientHandle::finished`]
662/// waits without ending it.
663#[derive(Debug)]
664pub struct ClientHandle {
665 pub(crate) task: Option<JoinHandle<Result<()>>>,
666 pub(crate) control: ControlHandle,
667 pub(crate) shutdown: Option<oneshot::Sender<GoodbyeReason>>,
668}
669
670impl ClientHandle {
671 /// Returns a handle for the playback controls of this connection.
672 ///
673 /// The handle is a cheap clone; every copy controls the same connection.
674 #[must_use]
675 pub fn control(&self) -> ControlHandle {
676 self.control.clone()
677 }
678
679 /// Stops the connection after telling the server why.
680 ///
681 /// The reason is sent as `client/goodbye` on the live connection before it closes; a client
682 /// that is reconnecting has no connection to say it on. The goodbye is best effort: a write
683 /// that fails neither turns the close into an error nor schedules another attempt. Dropping
684 /// the handle does the same with [`GoodbyeReason::Shutdown`].
685 pub fn close(&mut self, reason: GoodbyeReason) {
686 if let Some(shutdown) = self.shutdown.take() {
687 let _ = shutdown.send(reason);
688 }
689 }
690
691 /// Waits for the connection to end and returns its outcome.
692 ///
693 /// The connection ends when the handle or the event stream is dropped, when
694 /// [`ClientHandle::close`] is called, or when the audio sink fails; a dropped session is
695 /// reconnected, not returned. Awaiting this keeps the handle alive, so dropping the event
696 /// stream is the usual way to stop.
697 pub async fn finished(mut self) -> Result<()> {
698 let task = self.task.take().expect("the handle owns its task");
699 task.await.context("the connection task panicked")?
700 }
701}
702
703impl Drop for ClientHandle {
704 fn drop(&mut self) {
705 // `finished` takes the task, so a handle that is only waiting on the connection does not
706 // stop it; a handle that is dropped asks the connection to end and says why.
707 if self.task.is_some() {
708 if let Some(shutdown) = self.shutdown.take() {
709 let _ = shutdown.send(GoodbyeReason::Shutdown);
710 }
711 }
712 }
713}
714
715/// Playback controls for a live connection.
716///
717/// A call returns once the connection has handled it: a transport command or a seek has been
718/// written to the server, and a level or mute change has been recorded and included in the next
719/// state report. It is an error when the connection has ended, when no session is established at
720/// that moment, and when the server did not activate the role the command belongs to: transport
721/// commands and seeks need `controller@v1`, volume and mute state need `player@v1`. A transport
722/// command or seek the server did not list in its controller state is refused as well, so a host
723/// can offer exactly the buttons the server accepts. An absolute seek needs the reported range on
724/// top of that, so it is refused before the first controller state.
725#[derive(Debug, Clone)]
726pub struct ControlHandle {
727 pub(crate) commands: mpsc::UnboundedSender<ControlRequest>,
728 pub(crate) volume: Arc<AtomicU8>,
729 pub(crate) pairing_token: Option<PairingToken>,
730}
731
732/// The version-0 pairing token, held as the credential it is.
733///
734/// [`Debug`] prints `<redacted>`, so a log line that formats a [`ControlHandle`] never carries the
735/// token, which would let anyone holding that line pair a server with this client.
736#[derive(Clone)]
737pub(crate) struct PairingToken(pub(crate) String);
738
739impl fmt::Debug for PairingToken {
740 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
741 formatter.write_str("<redacted>")
742 }
743}
744
745impl ControlHandle {
746 /// Resumes playback.
747 pub async fn play(&self) -> Result<()> {
748 self.transport("play").await
749 }
750
751 /// Pauses playback at the current position.
752 pub async fn pause(&self) -> Result<()> {
753 self.transport("pause").await
754 }
755
756 /// Skips to the next track.
757 pub async fn next(&self) -> Result<()> {
758 self.transport("next").await
759 }
760
761 /// Skips to the previous track.
762 pub async fn previous(&self) -> Result<()> {
763 self.transport("previous").await
764 }
765
766 /// Seeks to an absolute position in milliseconds.
767 ///
768 /// The server must offer `seek` and report a range: the target is checked against
769 /// [`PlaybackState::seek_max_ms`], so a position beyond it is refused and nothing is sent.
770 /// Before the first controller state neither the command nor the range is known, so an
771 /// absolute seek is refused; [`ControlHandle::seek_relative`] follows the open-window rule of
772 /// the other transport commands instead, because an offset needs no range.
773 ///
774 /// # Errors
775 /// Returns an error when the connection has ended, when no session is established, when the
776 /// server did not activate `controller@v1`, when it did not offer `seek`, when it reported no
777 /// seekable range, and when `position_ms` is beyond that range. The last error names both the
778 /// target and the range.
779 pub async fn seek(&self, position_ms: u64) -> Result<()> {
780 self.send(ControlAction::Seek(position_ms))
781 .await
782 .map(|_level| ())
783 }
784
785 /// Seeks by an offset in milliseconds from the current position; a negative offset rewinds.
786 ///
787 /// The server must offer `seek_relative`. The window before its first controller state is
788 /// open, as it is for the other transport commands: an offset needs no known range, so there
789 /// is nothing to check it against. An absolute [`ControlHandle::seek`] is different and is
790 /// refused until the range is known.
791 ///
792 /// # Errors
793 /// Returns an error when the connection has ended, when no session is established, when the
794 /// server did not activate `controller@v1`, and when it did not offer `seek_relative`.
795 pub async fn seek_relative(&self, offset_ms: i64) -> Result<()> {
796 self.send(ControlAction::SeekRelative(offset_ms))
797 .await
798 .map(|_level| ())
799 }
800
801 /// Sets the output level, limited by [`ClientConfig::volume_policy`] against the level in
802 /// force, and returns the level that was applied.
803 ///
804 /// The level belongs to the connection: the session reports the applied value to the server
805 /// with its next state report, which is the initial report when the first clock measurement is
806 /// still pending, and every reconnect keeps it. A new connection starts from
807 /// [`ClientConfig::volume`], so a host passes the level it restored there and uses this call
808 /// for changes after that. [`ControlHandle::volume`] answers what is in force without a call.
809 pub async fn set_volume(&self, level: u8) -> Result<u8> {
810 self.send(ControlAction::Volume(level)).await
811 }
812
813 /// Reports the level the device is actually at, without applying the volume policy.
814 ///
815 /// [`ControlHandle::set_volume`] treats its argument as a request, so the policy may lower it
816 /// and above the threshold it limits one step. A host that knows the level its output is
817 /// really at - because the device applied a level at its own control, or because another
818 /// process raised it - reports that level with this call instead: it becomes the level in
819 /// force, [`ControlHandle::volume`] returns it, and the next `client/state` carries it
820 /// unchanged, so the server's view matches the output.
821 ///
822 /// The protocol's range still applies. A level above 100 is refused with an error before
823 /// anything is recorded or sent; the policy is not consulted and does not clamp the value.
824 ///
825 /// # Errors
826 /// Returns an error for a level above 100, for a connection that has ended, and when the
827 /// server did not activate `player@v1`.
828 pub async fn report_volume(&self, level: u8) -> Result<()> {
829 check_reported_level(level)?;
830 self.send(ControlAction::ReportVolume(level))
831 .await
832 .map(|_level| ())
833 }
834
835 /// Sets the mute state without changing the level.
836 ///
837 /// The reported level therefore stays what it was, and the server sees the mute in the
838 /// `muted` field alone.
839 pub async fn set_muted(&self, muted: bool) -> Result<()> {
840 self.send(ControlAction::Mute(muted)).await.map(|_level| ())
841 }
842
843 /// Enables or disables unpaired access on the live connection.
844 ///
845 /// The value is what `client/hello` advertises and what the activation guard enforces.
846 /// [`ClientConfig::unpaired_access`] is the value a `connect` call starts from. A live change is
847 /// carried for the rest of that call - the next `client/hello` advertises it - and a new
848 /// `connect` starts from the configuration again.
849 ///
850 /// Turning it off closes a connection that relies on it - an unpaired session with active roles
851 /// or with the `playback` activity declared by an accepted activation - after saying goodbye
852 /// with [`GoodbyeReason::PairingRequired`]. An unpaired session that relies on nothing yet stays
853 /// open, and the existing activation guard refuses the next activation that would need unpaired
854 /// access. A paired session is never closed by the setting, because the setting never applied to
855 /// it. Turning it on stores the value and restarts an unpaired session with `client/goodbye`
856 /// reason [`GoodbyeReason::Restart`]: `client/hello` is the only carrier of the advertisement,
857 /// so a live connection cannot advertise the new value without a new one. A paired session is
858 /// neither closed nor restarted, because the setting never applied to it. Pairing stays
859 /// admissible in both directions, because the setting gates only roles and the `playback`
860 /// activity, never pairing.
861 ///
862 /// # Errors
863 /// Returns an error when the connection has ended, and when the connection is switching keys at
864 /// that moment: the request is refused then, before anything is written, and the host can retry.
865 /// A change made while the client is between connections is stored, not refused: it is what the
866 /// next `client/hello` advertises.
867 pub async fn set_unpaired_access(&self, enabled: bool) -> Result<()> {
868 self.send(ControlAction::SetUnpairedAccess(enabled))
869 .await
870 .map(|_level| ())
871 }
872
873 /// Returns the volume level in force.
874 ///
875 /// The value follows every change the connection made or received, including a mute, which
876 /// leaves it untouched. It is available without a call, so a host can render its slider while
877 /// the connection is reconnecting.
878 #[must_use]
879 pub fn volume(&self) -> u8 {
880 self.volume.load(Ordering::Relaxed)
881 }
882
883 /// The version-0 pairing token for this client, or `None` when no
884 /// [`Storage`](crate::storage::Storage) is configured.
885 ///
886 /// The token is `SP:0` plus the base32 body of the identity's public key and the pairing PSK
887 /// that was drawn or restored when the client started, so it is fixed for the client's
888 /// lifetime and survives a reconnect. A token is a credential: anyone holding it can pair a
889 /// server with this client, so a host renders it only while the operator needs it and never
890 /// writes it into a log.
891 #[must_use]
892 pub fn pairing_token(&self) -> Option<String> {
893 self.pairing_token.as_ref().map(|token| token.0.clone())
894 }
895
896 /// Opens a pairing window on the live connection and starts a waiting static-code attempt.
897 ///
898 /// The pairing window is the client's half of the static code flow's operator gesture: the host
899 /// decides what the gesture is - a button press, a pinhole, a power-cycle pattern - and calls
900 /// this when it happened. The window belongs to the connection that is live now, so it is
901 /// opened there and closes when that connection ends, when the configured lifetime expires,
902 /// when a pairing completes, or after five failed key confirmations.
903 ///
904 /// # Errors
905 /// Returns an error when no connection is established at this moment. A call that arrives while
906 /// the client is reconnecting is refused rather than remembered for the next connection, which
907 /// the spec requires: a window admits attempts only on the connection that carries its gesture.
908 #[cfg(feature = "pairing-code")]
909 pub async fn open_pairing_window(&self) -> Result<()> {
910 self.send(ControlAction::OpenPairingWindow)
911 .await
912 .map(|_level| ())
913 }
914
915 /// Releases the dynamic flow's round limit: the deliberate operator action the spec requires.
916 ///
917 /// After twenty rounds without a verified `server_kc`, the client aborts the attempt and holds
918 /// further dynamic attempts back, answering their activations with `client/pair-pending`. The
919 /// counter is not partitioned by server and only this call - or a verified `server_kc` - resets
920 /// it. A host wires it to whatever gesture means "let this device try pairing again".
921 ///
922 /// Unlike a pairing window, the release needs no connection: the count belongs to the process,
923 /// and the next connection starts from a clean one. The call still answers the current level,
924 /// so it observes the same contract as the other control requests.
925 #[cfg(feature = "pairing-code")]
926 pub async fn release_holdback(&self) -> Result<()> {
927 self.send(ControlAction::ReleaseHoldback)
928 .await
929 .map(|_level| ())
930 }
931
932 /// Sends one controller command.
933 async fn transport(&self, command: &'static str) -> Result<()> {
934 self.send(ControlAction::Transport(command))
935 .await
936 .map(|_level| ())
937 }
938
939 /// Queues one request and waits for the level in force after it.
940 async fn send(&self, action: ControlAction) -> Result<u8> {
941 let (reply, response) = oneshot::channel();
942 self.commands
943 .send(ControlRequest { action, reply })
944 .map_err(|_| anyhow!("the connection has ended"))?;
945 response
946 .await
947 .map_err(|_| anyhow!("the connection ended before it answered"))?
948 }
949}
950
951/// What a [`ControlHandle`] asks the session to do.
952#[derive(Debug)]
953pub(crate) enum ControlAction {
954 /// A controller command, by wire name.
955 Transport(&'static str),
956 /// Seek to an absolute position in milliseconds.
957 Seek(u64),
958 /// Seek by an offset in milliseconds; negative rewinds.
959 SeekRelative(i64),
960 /// Set the output level, subject to the volume limit.
961 Volume(u8),
962 /// Record the level the output is actually at, without the volume limit.
963 ReportVolume(u8),
964 /// Set the mute state, keeping the level.
965 Mute(bool),
966 /// Whether the connection admits an unpaired session, applied to the shared value.
967 SetUnpairedAccess(bool),
968 /// Open a pairing window for this connection and start a waiting static-code attempt.
969 #[cfg(feature = "pairing-code")]
970 OpenPairingWindow,
971 /// Reset the dynamic flow's round counter and start the attempt it held back.
972 #[cfg(feature = "pairing-code")]
973 ReleaseHoldback,
974}
975
976/// One request from a [`ControlHandle`], with the channel its answer travels back on.
977///
978/// The answer is the volume level in force after the request; a transport command and a mute
979/// leave it unchanged.
980pub(crate) struct ControlRequest {
981 /// Operation to perform.
982 pub(crate) action: ControlAction,
983 /// Answer for the waiting call.
984 pub(crate) reply: oneshot::Sender<Result<u8>>,
985}
986
987/// The receiving end of a session's [`Event`] stream.
988///
989/// [`EventStream::next`] returns `None` once the connection has ended. An [`Event::Disconnected`]
990/// is not necessarily the last event: the client reconnects and reports the next attempt's events
991/// on the same stream, and only a fatal audio-sink failure or a dropped handle ends the sequence.
992/// Dropping the stream ends the connection: the next time the client would emit an event, it stops
993/// instead.
994#[derive(Debug)]
995pub struct EventStream {
996 pub(crate) events: mpsc::UnboundedReceiver<Event>,
997}
998
999impl EventStream {
1000 /// Waits for the next event.
1001 pub async fn next(&mut self) -> Option<Event> {
1002 self.events.recv().await
1003 }
1004}
1005
1006/// Namespaced entry point, for callers that prefer a type to the free function.
1007#[derive(Debug, Clone, Copy, Default)]
1008pub struct Client;
1009
1010impl Client {
1011 /// Connects to `config.server` and returns the handle and event stream.
1012 ///
1013 /// See [`connect`] for the details.
1014 pub async fn connect(
1015 config: ClientConfig,
1016 sink: Box<dyn Sink>,
1017 ) -> Result<(ClientHandle, EventStream)> {
1018 connect(config, sink).await
1019 }
1020
1021 /// Connects with pairing keys the host stores for known servers.
1022 ///
1023 /// See [`connect_with_psks`] for the details.
1024 pub async fn connect_with_psks(
1025 config: ClientConfig,
1026 sink: Box<dyn Sink>,
1027 psks: Vec<StoredPsk>,
1028 ) -> Result<(ClientHandle, EventStream)> {
1029 connect_with_psks(config, sink, psks).await
1030 }
1031
1032 /// Advertises this client and serves the servers that connect to it.
1033 ///
1034 /// See [`advertise`](crate::advertise) for the details.
1035 #[cfg(feature = "discovery")]
1036 pub async fn advertise(
1037 config: ClientConfig,
1038 sink: Box<dyn Sink>,
1039 ) -> Result<(ClientHandle, EventStream)> {
1040 crate::advertise(config, sink).await
1041 }
1042}
1043
1044/// Connects to a server and returns its handle and event stream.
1045///
1046/// The configuration is validated before this returns; the connection itself runs in a spawned
1047/// task and is reported through the event stream, with [`Event::Connected`] as the first event of a
1048/// successful attempt.
1049///
1050/// The task owns the sink and every attempt, so it reconnects after a drop with the same identity
1051/// and sink and with the level, mute state and roles the previous session had. Each drop is
1052/// reported as [`Event::Disconnected`] together with the delay before the next attempt. The
1053/// connection ends when the sink fails, which the host has to repair, or when the handle or the
1054/// event stream is dropped.
1055///
1056/// # Errors
1057/// Returns an error for an invalid [`ClientConfig`] and for a server address this build cannot use
1058/// (including a TLS URL). An unreachable server is not an error: the connection reports it as
1059/// [`Event::Disconnected`] and keeps retrying.
1060///
1061/// # Panics
1062/// Panics when called outside a Tokio runtime, because the connection is spawned.
1063pub async fn connect(
1064 config: ClientConfig,
1065 sink: Box<dyn Sink>,
1066) -> Result<(ClientHandle, EventStream)> {
1067 connect_with_psks(config, sink, Vec::new()).await
1068}
1069
1070/// Connects with pairing keys the host stores for known servers.
1071///
1072/// The server announces a `psk_id` and `psk_category` in Noise message 1. A candidate matches when
1073/// its category and derived id both match the announcement; its `server_id` must then equal the one
1074/// in `server/init`. On a lookup miss the initial handshake continues with the published Sentinel
1075/// key, which is why [`connect`] is the same call with no candidates.
1076///
1077/// The keys are used for the handshake only; they are not stored or logged. A reconnect uses them
1078/// again, so a pairing that worked keeps working. A [`Storage`](crate::storage::Storage) configured
1079/// on `config` joins them: its records are read for every attempt, and on the same `server_id` the
1080/// stored record wins over `explicit`, because the store is the authority for the servers it knows.
1081/// The pairing PSK the store holds is always a candidate as well, whether or not a pairing is
1082/// running.
1083///
1084/// # Errors
1085/// Same as [`connect`]. A record that belongs to another server fails the handshake of that
1086/// attempt and is reported as [`Event::Disconnected`]. A store that cannot be read or cannot hold
1087/// the pairing PSK is reported from this call before the first attempt. A configuration with a
1088/// store makes the client draw and persist its pairing PSK on a device's first run.
1089pub async fn connect_with_psks(
1090 config: ClientConfig,
1091 sink: Box<dyn Sink>,
1092 psks: Vec<StoredPsk>,
1093) -> Result<(ClientHandle, EventStream)> {
1094 // connection.md, _Server Initiated Connections_: "Clients MUST NOT manually connect to servers
1095 // while advertising `_sendspin._tcp`." A client uses one of the two methods at a time, so a
1096 // configuration that advertises is refused here rather than connected on the side.
1097 #[cfg(feature = "discovery")]
1098 if config.inbound.is_some() {
1099 bail!(
1100 "this configuration advertises _sendspin._tcp, so it waits for a server to connect; \
1101 a manual connection is refused while advertising, as connection.md requires. Clear \
1102 ClientConfig::inbound to dial a server instead"
1103 );
1104 }
1105 config.validate()?;
1106 let endpoint = endpoint(&config.server)?;
1107 // The pairing PSK is settled before the first attempt, so a store that cannot hold it is
1108 // reported to the caller instead of a connection that silently cannot pair. A restored key is
1109 // used as it is; a missing one is drawn and stored once, here.
1110 let pairing = match config.storage.as_deref() {
1111 Some(storage) => Some(load_or_draw_pairing_psk(storage)?),
1112 None => None,
1113 };
1114 // The token is fixed once the key is settled: the identity and the pairing PSK do not change
1115 // while the client runs, so it is built here and carried by every control handle.
1116 let pairing_token = pairing
1117 .as_ref()
1118 .map(|psk| PairingToken(encode_v0(&config.identity.public, psk.as_bytes())));
1119
1120 let (events, receiver) = mpsc::unbounded_channel();
1121 let (commands, control) = mpsc::unbounded_channel();
1122 let (shutdown, shutdown_rx) = oneshot::channel();
1123 let reported_volume = Arc::new(AtomicU8::new(config.volume));
1124 // The dynamic flow's round counter belongs to the process, not to a connection or a server:
1125 // only a verified `server_kc` or a deliberate operator action resets it.
1126 #[cfg(feature = "pairing-code")]
1127 let failed_rounds = Arc::new(AtomicU32::new(0));
1128
1129 let carried = Carried {
1130 sink,
1131 control: Some(control),
1132 volume: config.volume,
1133 muted: config.muted,
1134 active_roles: Vec::new(),
1135 unpaired_access: Arc::new(AtomicBool::new(config.unpaired_access)),
1136 #[cfg(feature = "pairing-code")]
1137 failed_rounds,
1138 };
1139 let connection = Connection {
1140 endpoint,
1141 config,
1142 psks,
1143 pairing,
1144 events: events.clone(),
1145 reported_volume: Arc::clone(&reported_volume),
1146 };
1147
1148 let task = tokio::spawn(serve_until_dropped(connection, carried, shutdown_rx));
1149
1150 let handle = ClientHandle {
1151 task: Some(task),
1152 control: ControlHandle {
1153 commands,
1154 volume: reported_volume,
1155 pairing_token,
1156 },
1157 shutdown: Some(shutdown),
1158 };
1159 Ok((handle, EventStream { events: receiver }))
1160}
1161
1162/// Opens one WebSocket, treating an address that does not answer as an error.
1163async fn open(endpoint: &str) -> Result<Transport> {
1164 tokio::time::timeout(CONNECT_TIMEOUT, Transport::connect(endpoint))
1165 .await
1166 .with_context(|| format!("timed out connecting to {endpoint}"))?
1167}
1168
1169/// The parts of a connection that do not change across attempts.
1170struct Connection {
1171 endpoint: String,
1172 config: ClientConfig,
1173 psks: Vec<StoredPsk>,
1174 /// This client's pairing PSK, present exactly when a store is configured.
1175 pairing: Option<PairingPsk>,
1176 events: mpsc::UnboundedSender<Event>,
1177 /// Level shared with every [`ControlHandle`].
1178 reported_volume: Arc<AtomicU8>,
1179}
1180
1181impl Connection {
1182 /// Delivers one event, ignoring a stream the host dropped.
1183 fn emit(&self, event: Event) {
1184 let _ = self.events.send(event);
1185 }
1186}
1187
1188/// One wake-up while no session is established.
1189enum Wakeup {
1190 /// A control handle sent a request.
1191 Control(Option<ControlRequest>),
1192 /// The delay elapsed.
1193 Deadline,
1194 /// The host dropped the event stream.
1195 Closed,
1196}
1197
1198/// Answers a request that arrived while no session was established.
1199///
1200/// A pairing window belongs to a connection and is refused; releasing the round hold-back belongs
1201/// to the process and is honoured, and a change of the unpaired-access setting is stored for the
1202/// next `client/hello`, so an operator gesture made between connections is not lost.
1203pub(crate) fn answer_without_session(carried: &Carried, request: ControlRequest) {
1204 if let ControlAction::SetUnpairedAccess(enabled) = &request.action {
1205 carried.unpaired_access.store(*enabled, Ordering::Relaxed);
1206 let _ = request.reply.send(Ok(carried.volume));
1207 return;
1208 }
1209 #[cfg(feature = "pairing-code")]
1210 if matches!(request.action, ControlAction::ReleaseHoldback) {
1211 carried.failed_rounds.store(0, Ordering::SeqCst);
1212 let _ = request.reply.send(Ok(carried.volume));
1213 return;
1214 }
1215 let _ = request
1216 .reply
1217 .send(Err(anyhow!("no connection is established")));
1218}
1219
1220/// Waits before the next attempt, answering control requests meanwhile.
1221///
1222/// Returns `false` when the host dropped the event stream and the connection should end.
1223async fn wait_before_retry(
1224 connection: &Connection,
1225 carried: &mut Carried,
1226 delay: Duration,
1227 shutdown: &mut oneshot::Receiver<GoodbyeReason>,
1228) -> bool {
1229 let deadline = tokio::time::Instant::now() + delay;
1230 loop {
1231 if connection.events.is_closed() {
1232 return false;
1233 }
1234 let control = &mut carried.control;
1235 let wakeup = tokio::select! {
1236 biased;
1237 request = async {
1238 match control {
1239 Some(receiver) => receiver.recv().await,
1240 None => std::future::pending().await,
1241 }
1242 } => Wakeup::Control(request),
1243 // No connection is open, so there is nothing to say goodbye on; the loop just ends.
1244 reason = &mut *shutdown => {
1245 let _ = reason;
1246 return false;
1247 }
1248 () = tokio::time::sleep_until(deadline) => Wakeup::Deadline,
1249 () = connection.events.closed() => Wakeup::Closed,
1250 };
1251 match wakeup {
1252 Wakeup::Control(Some(request)) => answer_without_session(carried, request),
1253 Wakeup::Control(None) => *control = None,
1254 Wakeup::Deadline => return true,
1255 Wakeup::Closed => return false,
1256 }
1257 }
1258}
1259
1260/// Runs connection attempts until the host drops the connection or the sink fails.
1261///
1262/// Every attempt, including the first, is opened here. A failed one is followed by the next after
1263/// the delay [`next_backoff`] computes, with the sink, the level, the mute state and the roles
1264/// carried over. A [`ClientHandle::close`] or a dropped handle stops the loop after the live
1265/// session has had its chance to say goodbye.
1266async fn serve_until_dropped(
1267 connection: Connection,
1268 mut carried: Carried,
1269 mut shutdown: oneshot::Receiver<GoodbyeReason>,
1270) -> Result<()> {
1271 // The first attempt is not preceded by a wait, but the policy starts at the initial delay, so a
1272 // failure before any session connected reports two seconds: one growth step from that value.
1273 let mut delay = INITIAL_BACKOFF;
1274
1275 loop {
1276 // A close that arrives while the attempt is still connecting has no session to say
1277 // goodbye on, so the loop ends as soon as it fires instead of waiting out the connect
1278 // timeout and reporting a failure the host did not cause.
1279 let transport = tokio::select! {
1280 result = open(&connection.endpoint) => result,
1281 reason = &mut shutdown => {
1282 let _ = reason;
1283 return Ok(());
1284 }
1285 };
1286 let transport = match transport {
1287 Ok(transport) => transport,
1288 Err(error) => {
1289 delay = next_backoff(delay, false, connection.config.max_backoff);
1290 connection.emit(Event::Disconnected {
1291 reason: format!("cannot connect to {}: {error:#}", connection.endpoint),
1292 retry_in: delay,
1293 });
1294 if !wait_before_retry(&connection, &mut carried, delay, &mut shutdown).await {
1295 return Ok(());
1296 }
1297 continue;
1298 }
1299 };
1300
1301 let attempt = session::attempt(
1302 transport,
1303 &connection.config,
1304 &connection.events,
1305 &connection.psks,
1306 connection.pairing,
1307 &connection.reported_volume,
1308 carried,
1309 &mut shutdown,
1310 )
1311 .await;
1312 carried = attempt.carried;
1313
1314 // Nothing buffered for the session that ended may become audible later; the flush runs
1315 // before the host hears about the drop so the output stops even if the next attempt takes
1316 // a while.
1317 let flush_error = carried.sink.flush().err().map(|error| {
1318 error.context("the audio sink rejected a flush after the connection ended")
1319 });
1320
1321 // A deliberate close is not a drop: nothing is reported and no attempt follows. The
1322 // goodbye was best effort, so neither its send nor the flush can turn it into an error.
1323 if matches!(&attempt.ending, session::Ending::Shutdown) {
1324 return Ok(());
1325 }
1326
1327 // A broken output cannot be repaired by reconnecting, and neither can a flush that fails
1328 // after the session; both end the connection instead of scheduling another attempt.
1329 let fatal = attempt.sink_failed || flush_error.is_some();
1330 delay = if fatal {
1331 // No attempt follows, so there is no delay to recommend.
1332 Duration::ZERO
1333 } else {
1334 next_backoff(delay, attempt.connected, connection.config.max_backoff)
1335 };
1336 connection.emit(Event::Disconnected {
1337 reason: attempt.ending.reason(),
1338 retry_in: delay,
1339 });
1340
1341 if attempt.sink_failed {
1342 // The host has to fix the sink; a retry would only fail the same way.
1343 return match attempt.ending {
1344 session::Ending::Failed(error) => Err(error),
1345 session::Ending::Closed
1346 | session::Ending::Unpaired
1347 | session::Ending::PairingRequired
1348 | session::Ending::UnpairedAccessOff
1349 | session::Ending::Restart
1350 | session::Ending::Unauthorized
1351 | session::Ending::Shutdown => Err(anyhow!("the audio sink failed")),
1352 };
1353 }
1354 if let Some(error) = flush_error {
1355 return Err(error);
1356 }
1357
1358 if !wait_before_retry(&connection, &mut carried, delay, &mut shutdown).await {
1359 return Ok(());
1360 }
1361 }
1362}
1363
1364/// Splits a URL tail into the part before a query or fragment and the marker onward.
1365fn split_marker(value: &str) -> (&str, &str) {
1366 match value.find(['?', '#']) {
1367 Some(index) => value.split_at(index),
1368 None => (value, ""),
1369 }
1370}
1371
1372/// Builds the WebSocket URL for a configured server address.
1373///
1374/// A bare `host:port` uses the default `/sendspin` path, and so does a `ws://` URL without a path.
1375/// A URL with an explicit path is used unchanged. TLS is rejected: this build carries no TLS
1376/// stack, and pretending otherwise would end in a confusing connection error.
1377fn endpoint(server: &str) -> Result<String> {
1378 let server = server.trim();
1379 if server.is_empty() {
1380 bail!("the server address is empty");
1381 }
1382 if server.starts_with("wss://") {
1383 bail!("TLS is not supported by this build; use a ws:// address or host:port");
1384 }
1385 if let Some(rest) = server.strip_prefix("ws://") {
1386 if rest.is_empty() {
1387 bail!("the WebSocket address {server:?} names no host");
1388 }
1389 // A query or fragment belongs after the path, so the default path has to be inserted
1390 // before it rather than appended to the whole URL.
1391 let (before_marker, after_marker) = split_marker(rest);
1392 let Some((authority, path)) = before_marker.split_once('/') else {
1393 if before_marker.is_empty() {
1394 bail!("the WebSocket address {server:?} names no host");
1395 }
1396 return Ok(format!("ws://{before_marker}/sendspin{after_marker}"));
1397 };
1398 if authority.is_empty() {
1399 bail!("the WebSocket address {server:?} names no host");
1400 }
1401 if path.is_empty() {
1402 return Ok(format!("ws://{authority}/sendspin{after_marker}"));
1403 }
1404 return Ok(format!("ws://{before_marker}{after_marker}"));
1405 }
1406 if server.contains("://") {
1407 bail!("unsupported URL scheme in {server:?}; use ws:// or host:port");
1408 }
1409 let (before_marker, after_marker) = split_marker(server);
1410 if before_marker.is_empty() {
1411 bail!("the server address is empty");
1412 }
1413 Ok(format!("ws://{before_marker}/sendspin{after_marker}"))
1414}
1415
1416#[cfg(test)]
1417mod tests {
1418 use super::*;
1419
1420 #[test]
1421 fn the_new_goodbye_reasons_use_the_wire_spelling() {
1422 assert_eq!(GoodbyeReason::PairingRequired.as_str(), "pairing_required");
1423 assert_eq!(GoodbyeReason::Unauthorized.as_str(), "unauthorized");
1424 }
1425
1426 /// A pairing code is a credential for one attempt: `Debug` names it but never prints it.
1427 #[cfg(feature = "pairing-code")]
1428 #[test]
1429 fn the_pairing_code_event_formats_without_its_code() {
1430 for (code, format) in [
1431 ("482913".to_owned(), CodeFormat::Digits),
1432 (
1433 "SP:1QJOHGMGBXP55Y6KMJD3KOYR9F6OWYD6QQPIKEFY".to_owned(),
1434 CodeFormat::QrCode,
1435 ),
1436 ] {
1437 let event = Event::PairingCode {
1438 code: code.clone(),
1439 format,
1440 round: 3,
1441 };
1442 let text = format!("{event:?}");
1443 assert!(text.contains("code: \"<redacted>\""), "got: {text}");
1444 assert!(
1445 !text.contains(&code),
1446 "the code must never reach a log line: {text}"
1447 );
1448 assert!(
1449 text.contains(&format!("format: {format:?}")),
1450 "the format is not secret: {text}"
1451 );
1452 assert!(text.contains("round: 3"), "the round is not secret: {text}");
1453 }
1454 }
1455
1456 /// The record-lifecycle events name the server, which is not secret, and nothing else.
1457 #[test]
1458 fn the_record_lifecycle_events_format_their_server_id() {
1459 let server_id = "B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b".to_owned();
1460
1461 let unpaired = format!(
1462 "{:?}",
1463 Event::Unpaired {
1464 server_id: server_id.clone(),
1465 }
1466 );
1467 assert!(
1468 unpaired.contains(&format!("Unpaired {{ server_id: \"{server_id}\" }}")),
1469 "got: {unpaired}"
1470 );
1471
1472 let required = format!(
1473 "{:?}",
1474 Event::PairingRequired {
1475 server_id: server_id.clone(),
1476 reason: PairingRequiredReason::CredentialMismatch,
1477 }
1478 );
1479 assert!(required.contains(&server_id), "got: {required}");
1480 assert!(
1481 required.contains("CredentialMismatch"),
1482 "the reason is what the host acts on: {required}"
1483 );
1484 assert!(
1485 !required.contains("<redacted>"),
1486 "neither event carries a secret, so neither redacts a field: {required}"
1487 );
1488 }
1489
1490 /// The tolerance event reports the length and never the identifier itself.
1491 #[test]
1492 fn the_group_id_tolerance_event_formats_its_length() {
1493 let text = format!("{:?}", Event::GroupIdNotCanonical { len: 36 });
1494 assert_eq!(text, "GroupIdNotCanonical { len: 36 }");
1495 }
1496
1497 /// Every other event keeps the fields a log line needs.
1498 #[test]
1499 fn an_event_still_formats_its_readable_fields() {
1500 let text = format!(
1501 "{:?}",
1502 Event::Disconnected {
1503 reason: "the server closed the connection".to_owned(),
1504 retry_in: Duration::from_secs(2),
1505 }
1506 );
1507 assert!(
1508 text.contains("Disconnected { reason: \"the server closed the connection\""),
1509 "got: {text}"
1510 );
1511 assert!(text.contains("retry_in: 2s"), "got: {text}");
1512 }
1513
1514 #[test]
1515 fn every_abort_reason_round_trips_through_the_wire_spelling() {
1516 for (wire, reason) in [
1517 ("attempt_timeout", PairingFailure::AttemptTimeout),
1518 ("method_not_supported", PairingFailure::MethodNotSupported),
1519 ("pairing_code_mismatch", PairingFailure::PairingCodeMismatch),
1520 ("user_cancelled", PairingFailure::UserCancelled),
1521 ("concurrent_attempt", PairingFailure::ConcurrentAttempt),
1522 ] {
1523 assert_eq!(reason.as_str(), wire);
1524 assert_eq!(PairingFailure::from_wire(wire), reason);
1525 }
1526
1527 // A reason from a later revision is carried, not rejected.
1528 assert_eq!(
1529 PairingFailure::from_wire("future_reason"),
1530 PairingFailure::Unrecognised("future_reason".to_owned())
1531 );
1532 assert_eq!(
1533 PairingFailure::Unrecognised("future_reason".to_owned()).as_str(),
1534 "future_reason"
1535 );
1536 }
1537
1538 #[test]
1539 fn a_bare_address_gets_the_default_websocket_endpoint() {
1540 assert_eq!(
1541 endpoint("192.0.2.10:8927").unwrap(),
1542 "ws://192.0.2.10:8927/sendspin"
1543 );
1544 assert_eq!(
1545 endpoint(" 192.0.2.10:8927 ").unwrap(),
1546 "ws://192.0.2.10:8927/sendspin"
1547 );
1548 assert_eq!(
1549 endpoint("ws://example.test:1").unwrap(),
1550 "ws://example.test:1/sendspin"
1551 );
1552 assert_eq!(
1553 endpoint("ws://example.test:1/").unwrap(),
1554 "ws://example.test:1/sendspin"
1555 );
1556 assert_eq!(
1557 endpoint("ws://example.test:1/player").unwrap(),
1558 "ws://example.test:1/player"
1559 );
1560 }
1561
1562 #[test]
1563 fn a_query_or_fragment_stays_after_the_default_path() {
1564 assert_eq!(
1565 endpoint("ws://example.test:1?token=1").unwrap(),
1566 "ws://example.test:1/sendspin?token=1"
1567 );
1568 assert_eq!(
1569 endpoint("ws://example.test:1#frag").unwrap(),
1570 "ws://example.test:1/sendspin#frag"
1571 );
1572 assert_eq!(
1573 endpoint("ws://example.test:1/?token=1").unwrap(),
1574 "ws://example.test:1/sendspin?token=1"
1575 );
1576 assert_eq!(
1577 endpoint("ws://example.test:1/player?token=1").unwrap(),
1578 "ws://example.test:1/player?token=1"
1579 );
1580 assert_eq!(
1581 endpoint("example.test:1?token=1").unwrap(),
1582 "ws://example.test:1/sendspin?token=1"
1583 );
1584 }
1585
1586 #[test]
1587 fn an_address_this_build_cannot_use_is_rejected() {
1588 for server in [
1589 "",
1590 " ",
1591 "wss://example.test",
1592 "https://example.test",
1593 "ws://",
1594 "ws://?token=1",
1595 "ws://#fragment",
1596 "ws:///player",
1597 "?token=1",
1598 "#fragment",
1599 ] {
1600 assert!(
1601 endpoint(server).is_err(),
1602 "{server:?} must not be turned into a cleartext endpoint"
1603 );
1604 }
1605 }
1606
1607 use crate::test_support::NullSink;
1608
1609 /// Builds the parts of a connection that do not change across attempts.
1610 fn connection_at(endpoint: &str, events: mpsc::UnboundedSender<Event>) -> Connection {
1611 Connection {
1612 endpoint: endpoint.to_owned(),
1613 config: ClientConfig {
1614 server: endpoint.to_owned(),
1615 player_name: "Test player".to_owned(),
1616 device_info: None,
1617 identity: crate::Identity::generate(),
1618 storage: None,
1619 audio_mode: crate::AudioMode::Passthrough,
1620 volume: 42,
1621 muted: false,
1622 volume_policy: VolumePolicy::default(),
1623 max_backoff: Duration::from_secs(30),
1624 strict_group_id: false,
1625 unpaired_access: true,
1626 required_lead_time_ms: 250,
1627 min_buffer_ms: None,
1628 pairing_timeout: DEFAULT_PAIRING_TIMEOUT,
1629 #[cfg(feature = "discovery")]
1630 inbound: None,
1631 #[cfg(feature = "pairing-code")]
1632 static_pairing_code: None,
1633 #[cfg(feature = "pairing-code")]
1634 pairing_window: crate::DEFAULT_PAIRING_WINDOW,
1635 #[cfg(feature = "pairing-code")]
1636 pairing_pending_text: None,
1637 #[cfg(feature = "pairing-code")]
1638 code_formats: Vec::new(),
1639 #[cfg(feature = "pairing-code")]
1640 code_out_channels: Vec::new(),
1641 },
1642 psks: Vec::new(),
1643 pairing: None,
1644 events,
1645 reported_volume: Arc::new(AtomicU8::new(42)),
1646 }
1647 }
1648
1649 fn empty_carried(control: Option<mpsc::UnboundedReceiver<ControlRequest>>) -> Carried {
1650 Carried {
1651 sink: Box::new(NullSink),
1652 control,
1653 volume: 42,
1654 muted: false,
1655 active_roles: Vec::new(),
1656 unpaired_access: Arc::new(AtomicBool::new(true)),
1657 #[cfg(feature = "pairing-code")]
1658 failed_rounds: Arc::new(AtomicU32::new(0)),
1659 }
1660 }
1661
1662 /// A shutdown receiver the test never fires; its sender is leaked so the receiver stays open.
1663 fn idle_shutdown() -> oneshot::Receiver<GoodbyeReason> {
1664 let (sender, receiver) = oneshot::channel();
1665 Box::leak(Box::new(sender));
1666 receiver
1667 }
1668
1669 #[tokio::test]
1670 async fn a_retry_wait_without_a_control_handle_still_honours_the_delay() {
1671 let (events, _receiver) = mpsc::unbounded_channel();
1672 let connection = connection_at("127.0.0.1:1", events);
1673 let (commands, control) = mpsc::unbounded_channel();
1674 drop(commands);
1675 let mut carried = empty_carried(Some(control));
1676 let mut shutdown = idle_shutdown();
1677
1678 let started = std::time::Instant::now();
1679 let retry = wait_before_retry(
1680 &connection,
1681 &mut carried,
1682 Duration::from_millis(50),
1683 &mut shutdown,
1684 )
1685 .await;
1686
1687 assert!(retry, "the delay elapsed, so the next attempt must follow");
1688 assert!(
1689 started.elapsed() >= Duration::from_millis(50),
1690 "the delay must be waited out, not skipped"
1691 );
1692 assert!(
1693 carried.control.is_none(),
1694 "a control channel whose senders are gone is dropped"
1695 );
1696 }
1697
1698 #[tokio::test]
1699 async fn dropping_the_event_stream_during_a_retry_ends_the_connection() {
1700 let (events, receiver) = mpsc::unbounded_channel();
1701 let connection = connection_at("127.0.0.1:1", events);
1702 let mut carried = empty_carried(None);
1703 let mut shutdown = idle_shutdown();
1704
1705 let retry = wait_before_retry(
1706 &connection,
1707 &mut carried,
1708 Duration::from_secs(60),
1709 &mut shutdown,
1710 );
1711 tokio::pin!(retry);
1712 let mut finished = false;
1713 tokio::select! {
1714 _ = &mut retry => finished = true,
1715 () = tokio::time::sleep(Duration::from_millis(50)) => {}
1716 }
1717 assert!(!finished, "the wait must not end while the stream is open");
1718
1719 drop(receiver);
1720 assert!(
1721 !retry.await,
1722 "a dropped event stream must stop the retry loop"
1723 );
1724 }
1725
1726 #[tokio::test]
1727 async fn a_failed_attempt_with_no_event_stream_ends_the_connection() {
1728 // Bind and release a loopback port, so the open fails immediately rather than timing out.
1729 let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("a loopback port");
1730 let address = listener.local_addr().expect("the bound address");
1731 drop(listener);
1732
1733 let (events, receiver) = mpsc::unbounded_channel();
1734 drop(receiver);
1735 let connection = connection_at(&address.to_string(), events);
1736
1737 let outcome = serve_until_dropped(connection, empty_carried(None), idle_shutdown()).await;
1738 assert!(
1739 outcome.is_ok(),
1740 "a host that dropped the stream ends the connection cleanly"
1741 );
1742 }
1743
1744 /// A close that arrives while the socket is still opening ends the loop at once, without an
1745 /// `Event::Disconnected` for a failure the host did not cause.
1746 #[tokio::test]
1747 async fn a_close_during_the_connect_ends_without_a_disconnected_event() {
1748 // A loopback listener that never accepts: the TCP connection is queued by the kernel and
1749 // the WebSocket handshake answers nothing, so the open stays in flight.
1750 let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
1751 .await
1752 .expect("a loopback port");
1753 let address = listener.local_addr().expect("the bound address");
1754 let url = format!("ws://{address}/sendspin");
1755
1756 let (events, mut receiver) = mpsc::unbounded_channel();
1757 let connection = connection_at(&url, events);
1758 let (shutdown, shutdown_rx) = oneshot::channel();
1759 let task = tokio::spawn(serve_until_dropped(
1760 connection,
1761 empty_carried(None),
1762 shutdown_rx,
1763 ));
1764
1765 tokio::time::sleep(Duration::from_millis(100)).await;
1766 shutdown
1767 .send(GoodbyeReason::UserRequest)
1768 .expect("the connection loop is still waiting");
1769
1770 let outcome = tokio::time::timeout(Duration::from_secs(2), task)
1771 .await
1772 .expect("the close must not wait out the connect timeout")
1773 .expect("the connection task panicked");
1774 assert!(
1775 outcome.is_ok(),
1776 "a close during the connect is clean: {outcome:?}"
1777 );
1778 if let Ok(event) = receiver.try_recv() {
1779 panic!(
1780 "no failure event may be reported for a close the host asked for, got {event:?}"
1781 );
1782 }
1783 }
1784
1785 #[tokio::test]
1786 async fn the_namespace_entry_points_wrap_the_free_functions() {
1787 // A bad configuration is rejected by both before any socket is opened, which pins the
1788 // forwarding: a wrapper that inverted the result would not return this error.
1789 let mut config = connection_at("127.0.0.1:1", mpsc::unbounded_channel().0).config;
1790 config.player_name.clear();
1791 let error = Client::connect(config, Box::new(NullSink))
1792 .await
1793 .expect_err("an invalid configuration must be rejected");
1794 assert!(format!("{error:#}").contains("player_name"));
1795
1796 let mut config = connection_at("127.0.0.1:1", mpsc::unbounded_channel().0).config;
1797 config.server = "wss://example.test".to_owned();
1798 let error = Client::connect_with_psks(config, Box::new(NullSink), Vec::new())
1799 .await
1800 .expect_err("a TLS address must be rejected before connecting");
1801 assert!(format!("{error:#}").contains("TLS"));
1802 }
1803}