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