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