Skip to main content

syncspin_client/
lib.rs

1//! Client side of Sendspin.
2//!
3//! This crate owns the session: it connects to a server, runs the Noise handshake, keeps a clock
4//! estimate and feeds audio to a sink the host provides. It stays device agnostic - the
5//! application that owns the speakers implements [`Sink`] and decides what playout means.
6//!
7//! A connection always ends in Noise: the client refuses a server that does not complete the
8//! handshake and never falls back to cleartext. A successful attempt reports [`Event::Connected`]
9//! and then one event per change; an attempt that ends reports [`Event::Disconnected`] with the
10//! delay before the next one, and the crate reconnects on its own with the same sink and identity.
11//!
12//! [`connect`] validates the configuration and spawns the connection; the first attempt and every
13//! retry run in that task and reach the caller through the [`EventStream`]. Only an invalid
14//! configuration or an address this build cannot use returns an error - an unreachable server is
15//! reported as [`Event::Disconnected`]. The [`ClientHandle`] waits for the connection to end and
16//! hands out a [`ControlHandle`] for transport commands, the volume level and mute state. The level
17//! follows [`ClientConfig::volume_policy`] - see [`clamp_volume_with`], and [`clamp_volume`] for the
18//! default - and the value the server receives is the applied one. [`ClientConfig::volume`] and
19//! [`ClientConfig::muted`] are the level and mute state the first report carries, so a host passes
20//! the values it restored instead of letting the server see a baseline the output is not at.
21//! [`ControlHandle::report_volume`] is the other direction: a level the host reads from its own
22//! output is recorded and sent unchanged, because the policy limits requests rather than the level
23//! the device is at.
24//!
25//! [`ClientConfig::device_info`] describes the device the client runs on and is announced in
26//! `client/hello`; a host without an answer passes `None` and the server sees only the player name.
27//!
28//! Pairing records and the long-lived pairing PSK belong to the host: it implements
29//! [`storage::Storage`] and the client keeps what it restores, so a paired server is recognised
30//! across restarts. The crate does no file I/O of its own; `storage::FileStorage` is an optional
31//! JSON backend behind the `storage-file` feature for a host that wants one.
32//!
33//! With a store the client offers the Pairing PSK method, the one method the protocol makes
34//! mandatory, and runs it when a server admits an attempt: it draws the long-term PSK, sends
35//! `client/pair-init` and `client/pair-finalize`, and writes the record after `server/pair-finalize`.
36//! [`Event::Paired`] reports the record and [`Event::PairingFailed`] an attempt that ended without
37//! one, always with the reason `pair/abort` carries. Without a store it offers no pairing method at
38//! all: a guest connection is unchanged, and a server that picks pairing anyway is answered with
39//! `pair/abort` reason `method_not_supported`. A pairing attempt is bounded by
40//! [`ClientConfig::pairing_timeout`], [`DEFAULT_PAIRING_TIMEOUT`] by default.
41//!
42//! With the `pairing-code` feature and a code in
43//! `ClientConfig::static_pairing_code`, the client also offers the Static Pairing Code method. Every
44//! attempt is gated by an operator gesture: `ControlHandle::open_pairing_window` opens a window on
45//! the live connection, the client answers a pairing activation with `client/pair-pending` while
46//! none is open, and the fifth failed key confirmation closes the window. The round runs CPace over
47//! X25519 with SHA-512 and delivers the new long-term PSK sealed under its output; that layer has
48//! not had an external review.
49//!
50//! With the same feature and at least one entry in each of `ClientConfig::code_formats` and
51//! `ClientConfig::code_out_channels`, the client offers the Dynamic Pairing Code method instead of
52//! relying on a fixed secret. It draws a nonce per attempt, locks it with `commit_B` in
53//! `client/pair-init`, and derives the per-session code once the server's `nonce_A` arrives: six
54//! digits, or a version-1 pairing token for a QR code. `Event::PairingCode` carries the code and
55//! its round; the code stays the same across the rounds of one attempt. A failed key confirmation
56//! asks the server for another round, and the twentieth failed round ends the attempt. After the
57//! limit the client holds dynamic attempts back - answering them with `client/pair-pending` - until
58//! `ControlHandle::release_holdback` is called, the deliberate operator action the spec requires.
59//!
60//! A pairing record can also be dropped from the server's side. `server/unpair` removes it, reports
61//! [`Event::Unpaired`] and closes the connection after `client/goodbye` with reason `unpaired`; a
62//! server that announces a `psk_id` the client does not hold is reported once per connection as
63//! [`Event::PairingRequired`] with reason [`PairingRequiredReason::CredentialMismatch`], so a host
64//! can offer pairing again instead of the lost record going unnoticed. A deliberate close -
65//! [`ClientHandle::close`] or dropping the handle - sends `client/goodbye` with its reason, so the
66//! server can tell a restart from a shutdown and does not treat the close as a dropped link.
67//!
68//! [`ControlHandle::pairing_token`] hands the operator the version-0 `SP:` token while a store is
69//! configured; it is a credential, so a host renders it only when the operator needs it.
70//!
71//! With the `discovery` feature the client can also take the other half of `connection.md`: instead
72//! of dialling a server it advertises `_sendspin._tcp` and accepts the server that connects.
73//! `Inbound` names the host's [`Discovery`] backend, the address to listen on and the path to
74//! serve; `advertise` publishes the record - the bound port and the `path` and `name` TXT
75//! records - and then serves one server at a time through the same session as a dialled connection.
76//! An upgrade that carries an `Origin` header is refused, as the spec requires, and the Noise
77//! handshake is unchanged because the server initiates it in both directions. A client uses one of
78//! the two methods at a time: while `ClientConfig::inbound` is set, [`connect`] refuses to dial.
79//! A second server that arrives while one is admitted is rejected with `client/goodbye` reason
80//! `concurrent_attempt` and closed, which is the spec's admission rule for a client that caps
81//! itself at one connection. The `mdns` feature carries the `mdns-sd` implementation of
82//! [`Discovery`]; without it the trait is the seam, so a host can supply its own backend and a
83//! fake drives the tests.
84//!
85//! A host that renders the stream sees its lifecycle as events: [`Event::StreamStart`] for a new
86//! format, [`Event::StreamEnd`] when the server pauses or removes the player role, and
87//! [`Event::StreamClear`] for a seek, plus [`Event::Track`] for the now-playing metadata with its
88//! position, duration and playback speed. The end and clear events arrive before the sink is
89//! flushed, so the host can mute, stop or restart its output first.
90//!
91//! The connection keeps running until the audio sink fails, which the host has to repair, or until
92//! the handle or the event stream is dropped.
93
94mod client;
95mod config;
96mod discovery;
97mod pairing;
98mod session;
99mod sink;
100
101pub mod storage;
102
103pub use client::{
104    clamp_volume, clamp_volume_with, connect, connect_with_psks, next_backoff, Client,
105    ClientHandle, ControlHandle, Event, EventStream, GoodbyeReason, PairingFailure,
106    PairingRequiredReason, PlaybackState, StreamEndReason, DEFAULT_PAIRING_TIMEOUT,
107    INITIAL_BACKOFF, NORMAL_PLAYBACK_SPEED,
108};
109pub use config::{
110    AudioMode, ClientConfig, DeviceInfo, PskCategory, StoredPsk, VolumePolicy, DEFAULT_MAX_BACKOFF,
111    MAX_PLAYER_NAME_LEN,
112};
113#[cfg(feature = "pairing-code")]
114pub use config::{
115    CodeFormat, CodeOutChannel, DEFAULT_PAIRING_WINDOW, MAX_PAIRING_PENDING_TEXT_LEN,
116    STATIC_PAIRING_CODE_LEN,
117};
118#[cfg(feature = "mdns")]
119pub use discovery::MdnsDiscovery;
120#[cfg(feature = "discovery")]
121pub use discovery::{advertise, Inbound, DEFAULT_INBOUND_ADDR, DEFAULT_INBOUND_PORT};
122pub use discovery::{
123    discover_servers, DiscoveredServer, Discovery, ServiceAdvertisement, CLIENT_SERVICE_TYPE,
124    DEFAULT_SENDSPIN_PATH, SERVER_SERVICE_TYPE,
125};
126pub use sink::{AudioFormat, AudioFrame, Codec, Sink};
127
128// The identity is part of [`ClientConfig`], so a host that builds a configuration needs it. A
129// re-export keeps a consumer from having to depend on the protocol crate directly.
130pub use syncspin_core::noise::Identity;
131
132/// Returns the version of this crate as recorded in its manifest.
133pub fn version() -> &'static str {
134    env!("CARGO_PKG_VERSION")
135}
136
137#[cfg(test)]
138pub(crate) mod test_support {
139    //! Shared test doubles for the unit tests in this crate.
140
141    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
142    use std::sync::{Mutex, MutexGuard};
143    use std::time::Instant;
144
145    use anyhow::{bail, Result};
146
147    use crate::config::StoredPsk;
148    use crate::sink::{AudioFormat, AudioFrame, Sink};
149    use crate::storage::Storage;
150
151    /// A sink that accepts every call and keeps the trait's default latency and underrun count.
152    pub(crate) struct NullSink;
153
154    impl Sink for NullSink {
155        fn open(&mut self, _format: AudioFormat) -> anyhow::Result<()> {
156            Ok(())
157        }
158
159        fn write(&mut self, _frame: AudioFrame<'_>, _due: Instant) -> anyhow::Result<()> {
160            Ok(())
161        }
162
163        fn flush(&mut self) -> anyhow::Result<()> {
164            Ok(())
165        }
166    }
167
168    #[test]
169    fn the_test_sink_reports_the_trait_defaults() {
170        let mut sink = NullSink;
171        sink.open(AudioFormat {
172            codec: crate::Codec::Pcm,
173            sample_rate: 48_000,
174            channels: 2,
175            bit_depth: 16,
176            codec_header: None,
177        })
178        .expect("the test sink accepts a format");
179        sink.write(AudioFrame::Pcm(&[1, 2]), Instant::now())
180            .expect("the test sink accepts a frame");
181        sink.flush().expect("the test sink flushes");
182        assert_eq!(
183            sink.latency(),
184            None,
185            "a sink that does not report a delay adds none"
186        );
187        assert_eq!(
188            sink.underruns(),
189            0,
190            "a sink that does not count underruns reports none"
191        );
192    }
193
194    /// A [`Storage`] that keeps everything in memory, optionally failing its calls.
195    ///
196    /// The crate's own tests need a store that answers instantly and one that fails a read or a
197    /// write, so a single double carries both. It applies no rule of its own: the record ordering,
198    /// the capacity and the live-record pin belong to [`persist_pairing`](crate::storage::persist_pairing).
199    #[derive(Debug, Default)]
200    pub(crate) struct MemoryStore {
201        pairing: Mutex<Option<[u8; 32]>>,
202        records: Mutex<Vec<StoredPsk>>,
203        read_fails: AtomicBool,
204        write_fails: AtomicBool,
205        stored_pairing_psks: AtomicUsize,
206    }
207
208    impl MemoryStore {
209        /// A store that already holds `pairing`.
210        pub(crate) fn holding(pairing: [u8; 32]) -> MemoryStore {
211            MemoryStore {
212                pairing: Mutex::new(Some(pairing)),
213                ..MemoryStore::default()
214            }
215        }
216
217        /// A store whose reads fail.
218        pub(crate) fn failing_reads() -> MemoryStore {
219            MemoryStore {
220                read_fails: AtomicBool::new(true),
221                ..MemoryStore::default()
222            }
223        }
224
225        /// A store whose writes fail.
226        pub(crate) fn failing_writes() -> MemoryStore {
227            MemoryStore {
228                write_fails: AtomicBool::new(true),
229                ..MemoryStore::default()
230            }
231        }
232
233        /// The pairing PSK the store holds.
234        pub(crate) fn pairing_psk_value(&self) -> Option<[u8; 32]> {
235            *self.pairing.lock().expect("the store lock is not poisoned")
236        }
237
238        /// The records the store holds, oldest first.
239        pub(crate) fn records(&self) -> Vec<StoredPsk> {
240            self.records
241                .lock()
242                .expect("the store lock is not poisoned")
243                .clone()
244        }
245
246        /// How often the client handed back a drawn pairing PSK.
247        pub(crate) fn stored_pairing_psks(&self) -> usize {
248            self.stored_pairing_psks.load(Ordering::SeqCst)
249        }
250
251        /// Puts a record into the store without going through the trait.
252        pub(crate) fn preload(&self, record: StoredPsk) {
253            self.records
254                .lock()
255                .expect("the store lock is not poisoned")
256                .push(record);
257        }
258
259        /// The record list, for a caller that has to hold the lock across a change.
260        fn records_lock(&self) -> MutexGuard<'_, Vec<StoredPsk>> {
261            self.records.lock().expect("the store lock is not poisoned")
262        }
263    }
264
265    impl Storage for MemoryStore {
266        fn pairing_psk(&self) -> Result<Option<[u8; 32]>> {
267            if self.read_fails.load(Ordering::SeqCst) {
268                bail!("the test store was told to fail its reads");
269            }
270            Ok(self.pairing_psk_value())
271        }
272
273        fn store_pairing_psk(&self, psk: &[u8; 32]) -> Result<()> {
274            if self.write_fails.load(Ordering::SeqCst) {
275                bail!("the test store was told to fail its writes");
276            }
277            *self.pairing.lock().expect("the store lock is not poisoned") = Some(*psk);
278            self.stored_pairing_psks.fetch_add(1, Ordering::SeqCst);
279            Ok(())
280        }
281
282        fn load_pairings(&self) -> Result<Vec<StoredPsk>> {
283            if self.read_fails.load(Ordering::SeqCst) {
284                bail!("the test store was told to fail its reads");
285            }
286            Ok(self.records())
287        }
288
289        fn store_pairing(&self, record: StoredPsk) -> Result<()> {
290            if self.write_fails.load(Ordering::SeqCst) {
291                bail!("the test store was told to fail its writes");
292            }
293            let mut records = self.records_lock();
294            records.retain(|held| held.server_id != record.server_id);
295            records.push(record);
296            Ok(())
297        }
298
299        fn remove_pairing(&self, server_id: &str) -> Result<()> {
300            if self.write_fails.load(Ordering::SeqCst) {
301                bail!("the test store was told to fail its writes");
302            }
303            self.records_lock()
304                .retain(|record| record.server_id != server_id);
305            Ok(())
306        }
307    }
308
309    #[test]
310    fn the_test_store_implements_the_storage_surface() {
311        let store = MemoryStore::holding([7u8; 32]);
312        assert_eq!(store.pairing_psk().unwrap(), Some([7u8; 32]));
313        assert_eq!(store.pairing_psk_value(), Some([7u8; 32]));
314        store.store_pairing_psk(&[8u8; 32]).unwrap();
315        assert_eq!(store.pairing_psk().unwrap(), Some([8u8; 32]));
316        assert_eq!(store.stored_pairing_psks(), 1);
317
318        let record = StoredPsk {
319            category: crate::PskCategory::LongTerm,
320            psk: [9u8; 32],
321            server_id: "a-server".to_owned(),
322        };
323        store.store_pairing(record.clone()).unwrap();
324        store.preload(StoredPsk {
325            server_id: "an-older-server".to_owned(),
326            ..record.clone()
327        });
328        assert_eq!(store.records().len(), 2, "the older record stays");
329        store.store_pairing(record.clone()).unwrap();
330        assert_eq!(
331            store.records().len(),
332            2,
333            "a record stored again replaces the one it replaces"
334        );
335        assert_eq!(store.load_pairings().unwrap().len(), 2);
336        store.remove_pairing("a-server").unwrap();
337        assert_eq!(store.load_pairings().unwrap().len(), 1);
338
339        let reads = MemoryStore::failing_reads();
340        assert!(reads.pairing_psk().is_err());
341        assert!(reads.load_pairings().is_err());
342        let writes = MemoryStore::failing_writes();
343        assert!(writes.store_pairing_psk(&[0u8; 32]).is_err());
344        assert!(writes.store_pairing(record).is_err());
345        assert!(writes.remove_pairing("a-server").is_err());
346    }
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352
353    #[test]
354    fn version_is_the_workspace_version() {
355        assert_eq!(version(), "0.2.0");
356    }
357}