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