Skip to main content

aria_kit/speaker/
store.rs

1//! The speakers directory: enrolled voices read back, stored, and forgotten.
2//!
3//! One document per person, named for them. The engine that measured a
4//! profile is recorded with it, because two engines put a voice in different
5//! places and comparing across them is meaningless.
6
7use std::path::{Path, PathBuf};
8use std::time::UNIX_EPOCH;
9
10use serde::{Deserialize, Serialize};
11
12use crate::primitives::private_document::{DocumentError, PrivateDocument};
13
14use super::{Profile, Role, SpeakerName, SpeakerNameError};
15
16/// A profile is a name, a role, and a few hundred floats. Anything larger is
17/// not one.
18const MAX_PROFILE_BYTES: u64 = 64 * 1024;
19
20/// The directory of enrolled voices.
21pub struct ProfileStore {
22    directory: PathBuf,
23}
24
25impl ProfileStore {
26    pub fn open(directory: impl Into<PathBuf>) -> Self {
27        Self {
28            directory: directory.into(),
29        }
30    }
31
32    /// Every profile in the directory. One unreadable file does not hide the
33    /// others; it comes back in [`StoredProfiles::unreadable`]. A directory
34    /// that does not exist means nobody has enrolled, which is ordinary.
35    pub fn read_all(&self) -> Result<StoredProfiles, ProfileError> {
36        let entries = match std::fs::read_dir(&self.directory) {
37            Ok(entries) => entries,
38            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
39                return Ok(StoredProfiles::default());
40            }
41            Err(error) => return Err(ProfileError::List(error)),
42        };
43        let mut stored = StoredProfiles::default();
44        for entry in entries {
45            let path = entry.map_err(ProfileError::List)?.path();
46            // Hidden files such as `.DS_Store` are the system's.
47            if path
48                .file_name()
49                .is_some_and(|name| name.as_encoded_bytes().starts_with(b"."))
50            {
51                continue;
52            }
53            if path.extension().is_none_or(|extension| extension != "json") {
54                // The path stays out of the log: its stem is a person's name.
55                tracing::warn!(
56                    "a file in the speakers directory is not a profile this build reads"
57                );
58                continue;
59            }
60            match self.read(&path) {
61                Ok(Some(profile)) => stored.profiles.push(profile),
62                Ok(None) => {}
63                Err(error) => stored.unreadable.push(error),
64            }
65        }
66        stored.profiles.sort_by(|a, b| a.name.cmp(&b.name));
67        Ok(stored)
68    }
69
70    /// The profiles `engine` measured, at the width it produces. Everything
71    /// else was made by a different model and cannot be compared.
72    pub fn read_for(&self, engine: &str, dimension: usize) -> Result<StoredProfiles, ProfileError> {
73        let mut stored = self.read_all()?;
74        stored
75            .profiles
76            .retain(|profile| profile.engine == engine && profile.vector.len() == dimension);
77        Ok(stored)
78    }
79
80    /// Stores a profile. `Replace::Never` refuses when a profile is already
81    /// there, judged by the filesystem rather than by comparing names: a name
82    /// that folds onto an existing one would otherwise overwrite it.
83    ///
84    /// [`ProfileError::DurabilityUnconfirmed`] means the profile is stored
85    /// and live; only whether it survives a power cut is unknown.
86    pub fn save(&self, profile: &Profile, replace: Replace) -> Result<(), ProfileError> {
87        let document = self.document(&profile.name);
88        if replace == Replace::Never && !document.claim().map_err(ProfileError::Write)? {
89            return Err(ProfileError::AlreadyStored);
90        }
91        document
92            .prepare(&StoredProfile::from(profile))
93            .map_err(ProfileError::Write)?
94            .commit()
95            .map_err(ProfileError::Write)?
96            .confirm_durability()
97            .map_err(ProfileError::DurabilityUnconfirmed)
98    }
99
100    /// `false` when nobody by that name was enrolled.
101    pub fn remove(&self, name: &SpeakerName) -> Result<bool, ProfileError> {
102        self.document(name).remove().map_err(ProfileError::Write)
103    }
104
105    fn document(&self, name: &SpeakerName) -> PrivateDocument {
106        PrivateDocument::new(
107            self.directory.join(format!("{name}.json")),
108            MAX_PROFILE_BYTES,
109        )
110    }
111
112    fn read(&self, path: &Path) -> Result<Option<Profile>, ProfileError> {
113        let name = path
114            .file_stem()
115            .and_then(|stem| stem.to_str())
116            .ok_or(ProfileError::UnnamedFile)?;
117        let name = SpeakerName::new(name).map_err(ProfileError::Name)?;
118
119        let document = PrivateDocument::new(path, MAX_PROFILE_BYTES);
120        let Some(stored) = document
121            .read::<StoredProfile>()
122            .map_err(ProfileError::Read)?
123        else {
124            return Ok(None);
125        };
126
127        let vector = super::normalized(stored.vector).ok_or(ProfileError::NoDirection)?;
128        Ok(Some(Profile {
129            name,
130            role: stored.role,
131            engine: stored.engine,
132            // A stored moment far enough in the future to overflow is a
133            // tampered file, not a profile: it joins the skipped ones.
134            enrolled_at: UNIX_EPOCH
135                .checked_add(std::time::Duration::from_secs(stored.enrolled_at))
136                .ok_or(ProfileError::UnreadableMoment)?,
137            vector,
138        }))
139    }
140}
141
142#[derive(Debug, Default)]
143pub struct StoredProfiles {
144    /// Sorted by name.
145    pub profiles: Vec<Profile>,
146    /// Each one is a person no session recognizes until the file is fixed or
147    /// they enroll again. The path is withheld: its stem is their name.
148    pub unreadable: Vec<ProfileError>,
149}
150
151/// The on-disk shape. Unknown fields are refused: a profile written by a
152/// newer Aria is not one this build can judge a voice with.
153#[derive(Serialize, Deserialize)]
154#[serde(deny_unknown_fields)]
155struct StoredProfile {
156    role: Role,
157    engine: String,
158    /// Seconds since the Unix epoch.
159    enrolled_at: u64,
160    vector: Vec<f32>,
161}
162
163impl From<&Profile> for StoredProfile {
164    fn from(profile: &Profile) -> Self {
165        Self {
166            role: profile.role,
167            engine: profile.engine.clone(),
168            enrolled_at: profile
169                .enrolled_at
170                .duration_since(UNIX_EPOCH)
171                .unwrap_or_default()
172                .as_secs(),
173            vector: profile.vector.clone(),
174        }
175    }
176}
177
178/// Whether storing a profile may overwrite one already there.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum Replace {
181    Never,
182    Allowed,
183}
184
185#[derive(Debug, thiserror::Error)]
186pub enum ProfileError {
187    #[error("the speakers directory could not be listed")]
188    List(#[source] std::io::Error),
189
190    #[error("the profile could not be read")]
191    Read(#[source] DocumentError),
192
193    #[error("the profile could not be written")]
194    Write(#[source] DocumentError),
195
196    #[error("the profile is stored, but its durability could not be confirmed")]
197    DurabilityUnconfirmed(#[source] DocumentError),
198
199    #[error("a profile of that name is already stored")]
200    AlreadyStored,
201
202    #[error("the profile records a moment outside any calendar")]
203    UnreadableMoment,
204
205    #[error("the profile filename is not a usable speaker name")]
206    Name(#[source] SpeakerNameError),
207
208    #[error("the profile filename has no name in it")]
209    UnnamedFile,
210
211    #[error("the profile embedding has no direction")]
212    NoDirection,
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use std::os::unix::fs::PermissionsExt;
219
220    fn profiles(store: &ProfileStore) -> Vec<Profile> {
221        store.read_all().expect("the directory lists").profiles
222    }
223
224    fn names(store: &ProfileStore) -> Vec<String> {
225        profiles(store)
226            .iter()
227            .map(|profile| profile.name.to_string())
228            .collect()
229    }
230
231    /// A store in a directory that lives as long as the test holds the pair.
232    fn store() -> (tempfile::TempDir, ProfileStore) {
233        let home = tempfile::tempdir().expect("a temporary directory");
234        let store = ProfileStore::open(home.path());
235        (home, store)
236    }
237
238    fn profile(name: &str, role: Role, engine: &str, vector: Vec<f32>) -> Profile {
239        Profile {
240            name: SpeakerName::new(name).expect("the name is usable"),
241            role,
242            engine: engine.to_owned(),
243            enrolled_at: UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000),
244            vector,
245        }
246    }
247
248    #[test]
249    fn a_saved_profile_reads_back() {
250        let (_home, store) = store();
251        let alex = profile("alex", Role::Owner, "wespeaker", vec![1.0, 0.0]);
252        store
253            .save(&alex, Replace::Never)
254            .expect("the profile is written");
255
256        assert_eq!(profiles(&store), vec![alex]);
257    }
258
259    #[test]
260    fn profiles_come_back_sorted_by_name() {
261        let (_home, store) = store();
262        for name in ["zoe", "ada"] {
263            store
264                .save(
265                    &profile(name, Role::Guest, "wespeaker", vec![0.0, 1.0]),
266                    Replace::Never,
267                )
268                .expect("the profile is written");
269        }
270
271        let names = names(&store);
272        assert_eq!(names, ["ada", "zoe"]);
273    }
274
275    #[test]
276    fn a_profile_from_another_engine_is_not_offered_to_this_one() {
277        let (_home, store) = store();
278        store
279            .save(
280                &profile("ada", Role::Owner, "wespeaker", vec![1.0, 0.0]),
281                Replace::Never,
282            )
283            .expect("the profile is written");
284        store
285            .save(
286                &profile("zoe", Role::Owner, "other", vec![1.0, 0.0]),
287                Replace::Never,
288            )
289            .expect("the profile is written");
290
291        let usable = store
292            .read_for("wespeaker", 2)
293            .expect("the directory lists")
294            .profiles;
295        assert_eq!(usable.len(), 1);
296        assert_eq!(usable[0].name.as_str(), "ada");
297    }
298
299    #[test]
300    fn a_profile_of_another_width_is_not_offered_either() {
301        let (_home, store) = store();
302        store
303            .save(
304                &profile("ada", Role::Owner, "wespeaker", vec![1.0, 0.0, 0.0]),
305                Replace::Never,
306            )
307            .expect("the profile is written");
308
309        let stored = store.read_for("wespeaker", 2).expect("the directory lists");
310        assert!(stored.profiles.is_empty());
311    }
312
313    #[test]
314    fn one_unreadable_profile_does_not_hide_the_others() {
315        let (home, store) = store();
316        store
317            .save(
318                &profile("ada", Role::Owner, "wespeaker", vec![1.0, 0.0]),
319                Replace::Never,
320            )
321            .expect("the profile is written");
322        std::fs::write(home.path().join("broken.json"), b"{").expect("the file is written");
323
324        let stored = store.read_all().expect("the directory lists");
325        let names: Vec<&str> = stored
326            .profiles
327            .iter()
328            .map(|profile| profile.name.as_str())
329            .collect();
330        assert_eq!(names, ["ada"]);
331        assert_eq!(stored.unreadable.len(), 1);
332    }
333
334    #[test]
335    fn an_empty_speakers_directory_means_nobody_enrolled() {
336        let home = tempfile::tempdir().expect("a temporary directory");
337        assert!(profiles(&ProfileStore::open(home.path().join("absent"))).is_empty());
338    }
339
340    #[test]
341    fn removing_says_whether_anyone_was_enrolled() {
342        let (_home, store) = store();
343        let ada = SpeakerName::new("ada").expect("the name is usable");
344        store
345            .save(
346                &profile("ada", Role::Owner, "wespeaker", vec![1.0, 0.0]),
347                Replace::Never,
348            )
349            .expect("the profile is written");
350
351        assert!(store.remove(&ada).expect("the delete succeeds"));
352        assert!(!store.remove(&ada).expect("the delete succeeds"));
353        assert!(profiles(&store).is_empty());
354    }
355
356    #[test]
357    fn a_second_profile_of_the_same_name_is_refused_unless_asked() {
358        let (_home, store) = store();
359        let first = profile("ada", Role::Owner, "wespeaker", vec![1.0, 0.0]);
360        store
361            .save(&first, Replace::Never)
362            .expect("the profile is written");
363
364        let second = profile("ada", Role::Guest, "wespeaker", vec![0.0, 1.0]);
365        assert!(matches!(
366            store.save(&second, Replace::Never),
367            Err(ProfileError::AlreadyStored)
368        ));
369        assert_eq!(profiles(&store), vec![first]);
370
371        store
372            .save(&second, Replace::Allowed)
373            .expect("the profile is replaced");
374        assert_eq!(profiles(&store), vec![second]);
375    }
376
377    #[test]
378    fn a_profile_recording_an_impossible_moment_is_skipped() {
379        let (home, store) = store();
380        store
381            .save(
382                &profile("ada", Role::Owner, "wespeaker", vec![1.0, 0.0]),
383                Replace::Never,
384            )
385            .expect("the profile is written");
386        let tampered = home.path().join("zoe.json");
387        std::fs::write(
388            &tampered,
389            br#"{"role":"guest","engine":"wespeaker","enrolled_at":18446744073709551615,"vector":[1.0,0.0]}"#,
390        )
391        .expect("the file is written");
392        std::fs::set_permissions(&tampered, std::fs::Permissions::from_mode(0o600))
393            .expect("the mode is set");
394
395        let names = names(&store);
396        assert_eq!(names, ["ada"]);
397    }
398
399    #[test]
400    fn a_name_that_could_escape_the_directory_is_refused() {
401        for name in ["", " ada", "ada ", "../ada", "ada/zoe", ".hidden", "a\nb"] {
402            assert!(
403                SpeakerName::new(name).is_err(),
404                "{name:?} must not become a filename"
405            );
406        }
407    }
408
409    #[test]
410    fn a_name_that_reads_like_an_anonymous_speaker_is_refused() {
411        assert!(SpeakerName::new("Speaker 2").is_err());
412        assert!(SpeakerName::new("Speaker Two").is_ok());
413    }
414
415    #[test]
416    fn an_ordinary_name_is_accepted() {
417        assert_eq!(
418            SpeakerName::new("Alex Morgan")
419                .expect("the name is usable")
420                .as_str(),
421            "Alex Morgan"
422        );
423    }
424}