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//! A host that renders the stream sees its lifecycle as events: [`Event::StreamStart`] for a new
72//! format, [`Event::StreamEnd`] when the server pauses or removes the player role, and
73//! [`Event::StreamClear`] for a seek, plus [`Event::Track`] for the now-playing metadata with its
74//! position, duration and playback speed. The end and clear events arrive before the sink is
75//! flushed, so the host can mute, stop or restart its output first.
76//!
77//! The connection keeps running until the audio sink fails, which the host has to repair, or until
78//! the handle or the event stream is dropped.
79
80mod client;
81mod config;
82mod pairing;
83mod session;
84mod sink;
85
86pub mod storage;
87
88pub use client::{
89    clamp_volume, clamp_volume_with, connect, connect_with_psks, next_backoff, Client,
90    ClientHandle, ControlHandle, Event, EventStream, GoodbyeReason, PairingFailure,
91    PairingRequiredReason, PlaybackState, StreamEndReason, DEFAULT_PAIRING_TIMEOUT,
92    INITIAL_BACKOFF, NORMAL_PLAYBACK_SPEED,
93};
94pub use config::{
95    AudioMode, ClientConfig, DeviceInfo, PskCategory, StoredPsk, VolumePolicy, MAX_PLAYER_NAME_LEN,
96};
97#[cfg(feature = "pairing-code")]
98pub use config::{
99    CodeFormat, CodeOutChannel, DEFAULT_PAIRING_WINDOW, MAX_PAIRING_PENDING_TEXT_LEN,
100    STATIC_PAIRING_CODE_LEN,
101};
102pub use sink::{AudioFormat, AudioFrame, Codec, Sink};
103
104// The identity is part of [`ClientConfig`], so a host that builds a configuration needs it. A
105// re-export keeps a consumer from having to depend on the protocol crate directly.
106pub use syncspin_core::noise::Identity;
107
108/// Returns the version of this crate as recorded in its manifest.
109pub fn version() -> &'static str {
110    env!("CARGO_PKG_VERSION")
111}
112
113#[cfg(test)]
114pub(crate) mod test_support {
115    //! Shared test doubles for the unit tests in this crate.
116
117    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
118    use std::sync::{Mutex, MutexGuard};
119    use std::time::Instant;
120
121    use anyhow::{bail, Result};
122
123    use crate::config::StoredPsk;
124    use crate::sink::{AudioFormat, AudioFrame, Sink};
125    use crate::storage::Storage;
126
127    /// A sink that accepts every call and keeps the trait's default latency and underrun count.
128    pub(crate) struct NullSink;
129
130    impl Sink for NullSink {
131        fn open(&mut self, _format: AudioFormat) -> anyhow::Result<()> {
132            Ok(())
133        }
134
135        fn write(&mut self, _frame: AudioFrame<'_>, _due: Instant) -> anyhow::Result<()> {
136            Ok(())
137        }
138
139        fn flush(&mut self) -> anyhow::Result<()> {
140            Ok(())
141        }
142    }
143
144    #[test]
145    fn the_test_sink_reports_the_trait_defaults() {
146        let mut sink = NullSink;
147        sink.open(AudioFormat {
148            codec: crate::Codec::Pcm,
149            sample_rate: 48_000,
150            channels: 2,
151            bit_depth: 16,
152            codec_header: None,
153        })
154        .expect("the test sink accepts a format");
155        sink.write(AudioFrame::Pcm(&[1, 2]), Instant::now())
156            .expect("the test sink accepts a frame");
157        sink.flush().expect("the test sink flushes");
158        assert_eq!(
159            sink.latency(),
160            None,
161            "a sink that does not report a delay adds none"
162        );
163        assert_eq!(
164            sink.underruns(),
165            0,
166            "a sink that does not count underruns reports none"
167        );
168    }
169
170    /// A [`Storage`] that keeps everything in memory, optionally failing its calls.
171    ///
172    /// The crate's own tests need a store that answers instantly and one that fails a read or a
173    /// write, so a single double carries both. It applies no rule of its own: the record ordering,
174    /// the capacity and the live-record pin belong to [`persist_pairing`](crate::storage::persist_pairing).
175    #[derive(Debug, Default)]
176    pub(crate) struct MemoryStore {
177        pairing: Mutex<Option<[u8; 32]>>,
178        records: Mutex<Vec<StoredPsk>>,
179        read_fails: AtomicBool,
180        write_fails: AtomicBool,
181        stored_pairing_psks: AtomicUsize,
182    }
183
184    impl MemoryStore {
185        /// A store that already holds `pairing`.
186        pub(crate) fn holding(pairing: [u8; 32]) -> MemoryStore {
187            MemoryStore {
188                pairing: Mutex::new(Some(pairing)),
189                ..MemoryStore::default()
190            }
191        }
192
193        /// A store whose reads fail.
194        pub(crate) fn failing_reads() -> MemoryStore {
195            MemoryStore {
196                read_fails: AtomicBool::new(true),
197                ..MemoryStore::default()
198            }
199        }
200
201        /// A store whose writes fail.
202        pub(crate) fn failing_writes() -> MemoryStore {
203            MemoryStore {
204                write_fails: AtomicBool::new(true),
205                ..MemoryStore::default()
206            }
207        }
208
209        /// The pairing PSK the store holds.
210        pub(crate) fn pairing_psk_value(&self) -> Option<[u8; 32]> {
211            *self.pairing.lock().expect("the store lock is not poisoned")
212        }
213
214        /// The records the store holds, oldest first.
215        pub(crate) fn records(&self) -> Vec<StoredPsk> {
216            self.records
217                .lock()
218                .expect("the store lock is not poisoned")
219                .clone()
220        }
221
222        /// How often the client handed back a drawn pairing PSK.
223        pub(crate) fn stored_pairing_psks(&self) -> usize {
224            self.stored_pairing_psks.load(Ordering::SeqCst)
225        }
226
227        /// Puts a record into the store without going through the trait.
228        pub(crate) fn preload(&self, record: StoredPsk) {
229            self.records
230                .lock()
231                .expect("the store lock is not poisoned")
232                .push(record);
233        }
234
235        /// The record list, for a caller that has to hold the lock across a change.
236        fn records_lock(&self) -> MutexGuard<'_, Vec<StoredPsk>> {
237            self.records.lock().expect("the store lock is not poisoned")
238        }
239    }
240
241    impl Storage for MemoryStore {
242        fn pairing_psk(&self) -> Result<Option<[u8; 32]>> {
243            if self.read_fails.load(Ordering::SeqCst) {
244                bail!("the test store was told to fail its reads");
245            }
246            Ok(self.pairing_psk_value())
247        }
248
249        fn store_pairing_psk(&self, psk: &[u8; 32]) -> Result<()> {
250            if self.write_fails.load(Ordering::SeqCst) {
251                bail!("the test store was told to fail its writes");
252            }
253            *self.pairing.lock().expect("the store lock is not poisoned") = Some(*psk);
254            self.stored_pairing_psks.fetch_add(1, Ordering::SeqCst);
255            Ok(())
256        }
257
258        fn load_pairings(&self) -> Result<Vec<StoredPsk>> {
259            if self.read_fails.load(Ordering::SeqCst) {
260                bail!("the test store was told to fail its reads");
261            }
262            Ok(self.records())
263        }
264
265        fn store_pairing(&self, record: StoredPsk) -> Result<()> {
266            if self.write_fails.load(Ordering::SeqCst) {
267                bail!("the test store was told to fail its writes");
268            }
269            let mut records = self.records_lock();
270            records.retain(|held| held.server_id != record.server_id);
271            records.push(record);
272            Ok(())
273        }
274
275        fn remove_pairing(&self, server_id: &str) -> Result<()> {
276            if self.write_fails.load(Ordering::SeqCst) {
277                bail!("the test store was told to fail its writes");
278            }
279            self.records_lock()
280                .retain(|record| record.server_id != server_id);
281            Ok(())
282        }
283    }
284
285    #[test]
286    fn the_test_store_implements_the_storage_surface() {
287        let store = MemoryStore::holding([7u8; 32]);
288        assert_eq!(store.pairing_psk().unwrap(), Some([7u8; 32]));
289        assert_eq!(store.pairing_psk_value(), Some([7u8; 32]));
290        store.store_pairing_psk(&[8u8; 32]).unwrap();
291        assert_eq!(store.pairing_psk().unwrap(), Some([8u8; 32]));
292        assert_eq!(store.stored_pairing_psks(), 1);
293
294        let record = StoredPsk {
295            category: crate::PskCategory::LongTerm,
296            psk: [9u8; 32],
297            server_id: "a-server".to_owned(),
298        };
299        store.store_pairing(record.clone()).unwrap();
300        store.preload(StoredPsk {
301            server_id: "an-older-server".to_owned(),
302            ..record.clone()
303        });
304        assert_eq!(store.records().len(), 2, "the older record stays");
305        store.store_pairing(record.clone()).unwrap();
306        assert_eq!(
307            store.records().len(),
308            2,
309            "a record stored again replaces the one it replaces"
310        );
311        assert_eq!(store.load_pairings().unwrap().len(), 2);
312        store.remove_pairing("a-server").unwrap();
313        assert_eq!(store.load_pairings().unwrap().len(), 1);
314
315        let reads = MemoryStore::failing_reads();
316        assert!(reads.pairing_psk().is_err());
317        assert!(reads.load_pairings().is_err());
318        let writes = MemoryStore::failing_writes();
319        assert!(writes.store_pairing_psk(&[0u8; 32]).is_err());
320        assert!(writes.store_pairing(record).is_err());
321        assert!(writes.remove_pairing("a-server").is_err());
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn version_is_the_workspace_version() {
331        assert_eq!(version(), "0.1.1");
332    }
333}