Skip to main content

kitchen_services/
people.rs

1//! Who works in the app: people (a name, and optionally an affiliation and an ORCID iD), the one
2//! working now, or a guest. What a person does is recorded under their name (the activity log,
3//! an app's own records such as a curation log), so the name may end up in files that are shared:
4//! a guest leaves no name (`guest`).
5//!
6//! No passwords: this names who did what on one computer; servers keep their own pairing. The
7//! people are kept in a file the app names ([`load`]), JSON, read and written whole; in a browser,
8//! where there is no file, for the page's life.
9
10use std::path::{Path, PathBuf};
11use std::sync::Mutex;
12use std::sync::atomic::{AtomicU64, Ordering};
13
14use serde::{Deserialize, Serialize};
15
16/// What a guest is recorded as.
17pub const GUEST: &str = "guest";
18
19/// One person.
20#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(default)]
22pub struct Person {
23    /// As recorded ("Ada Lovelace"); unique among the people.
24    pub name: String,
25    /// Lab or institution (optional).
26    #[serde(skip_serializing_if = "String::is_empty")]
27    pub affiliation: String,
28    /// ORCID iD, `0000-0000-0000-0000` (optional).
29    #[serde(skip_serializing_if = "String::is_empty")]
30    pub orcid: String,
31}
32
33/// The people file.
34#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(default)]
36struct Book {
37    people: Vec<Person>,
38    /// The person working now, by name; `None`: a guest.
39    current: Option<String>,
40}
41
42#[derive(Default)]
43struct State {
44    book: Book,
45    path: Option<PathBuf>,
46}
47
48static STATE: Mutex<Option<State>> = Mutex::new(None);
49static GENERATION: AtomicU64 = AtomicU64::new(0);
50
51fn with<T>(f: impl FnOnce(&mut State) -> T) -> T {
52    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
53    f(g.get_or_insert_with(State::default))
54}
55
56/// Writes the people file (when there is one); a failure is returned, the change is kept.
57fn changed(s: &State) -> Result<(), String> {
58    GENERATION.fetch_add(1, Ordering::Relaxed);
59    let Some(path) = &s.path else { return Ok(()) };
60    write(path, &s.book)
61}
62
63#[cfg(not(target_family = "wasm"))]
64fn write(path: &Path, book: &Book) -> Result<(), String> {
65    let text = serde_json::to_string_pretty(book).map_err(|e| e.to_string())?;
66    if let Some(dir) = path.parent() {
67        std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
68    }
69    let tmp = path.with_extension("json.tmp");
70    std::fs::write(&tmp, text).map_err(|e| format!("{}: {e}", tmp.display()))?;
71    std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
72}
73
74#[cfg(target_family = "wasm")]
75fn write(_: &Path, _: &Book) -> Result<(), String> {
76    Ok(())
77}
78
79/// Reads the people from `path` (none yet: no one, a guest working) and keeps them there.
80/// Returns a notice when the file could not be read (it is then left as it is until a change).
81pub fn load(path: impl Into<PathBuf>) -> Option<String> {
82    let path = path.into();
83    #[cfg(not(target_family = "wasm"))]
84    let (book, notice) = match std::fs::read_to_string(&path) {
85        Ok(text) => match serde_json::from_str::<Book>(&text) {
86            Ok(b) => (b, None),
87            Err(e) => (Book::default(), Some(format!("{}: {e}", path.display()))),
88        },
89        Err(_) => (Book::default(), None),
90    };
91    #[cfg(target_family = "wasm")]
92    let (book, notice) = (Book::default(), None);
93    with(|s| {
94        s.book = book;
95        s.path = Some(path);
96    });
97    GENERATION.fetch_add(1, Ordering::Relaxed);
98    notice
99}
100
101/// Bumped on every change (redraw when it moves).
102pub fn generation() -> u64 {
103    GENERATION.load(Ordering::Relaxed)
104}
105
106/// Everyone, in the order added.
107pub fn people() -> Vec<Person> {
108    with(|s| s.book.people.clone())
109}
110
111/// The person working now; `None`: a guest.
112pub fn current() -> Option<Person> {
113    with(|s| s.book.current.as_ref().and_then(|n| s.book.people.iter().find(|p| &p.name == n).cloned()))
114}
115
116/// The name things are recorded under now: the person's, or [`GUEST`].
117pub fn who() -> String {
118    current().map_or_else(|| GUEST.to_string(), |p| p.name)
119}
120
121/// `name` works now (`None`: a guest). An unknown name is refused.
122pub fn use_person(name: Option<&str>) -> Result<(), String> {
123    with(|s| {
124        if let Some(n) = name
125            && !s.book.people.iter().any(|p| p.name == n)
126        {
127            return Err(format!("no one named {n:?}"));
128        }
129        s.book.current = name.map(str::to_string);
130        changed(s)
131    })
132}
133
134/// Checks a person before adding or changing one: a name, not the guest's, an ORCID iD as
135/// `0000-0000-0000-000X` when given.
136fn check(p: &Person) -> Result<(), String> {
137    let name = p.name.trim();
138    if name.is_empty() {
139        return Err("a person needs a name".into());
140    }
141    if name.eq_ignore_ascii_case(GUEST) {
142        return Err(format!("{GUEST:?} is what no one named is recorded as"));
143    }
144    if !p.orcid.is_empty() && !orcid_ok(&p.orcid) {
145        return Err(format!("{:?} is not an ORCID iD (0000-0000-0000-000X)", p.orcid));
146    }
147    Ok(())
148}
149
150/// `0000-0000-0000-000X`: four groups of four digits, the last character a digit or X, with the
151/// ISO 7064 11-2 check digit right.
152pub fn orcid_ok(id: &str) -> bool {
153    let groups: Vec<&str> = id.split('-').collect();
154    if groups.len() != 4 || groups.iter().any(|g| g.len() != 4) {
155        return false;
156    }
157    let chars: Vec<char> = groups.concat().chars().collect();
158    let (body, last) = chars.split_at(15);
159    if !body.iter().all(char::is_ascii_digit) {
160        return false;
161    }
162    let total = body.iter().fold(0u32, |t, c| (t + c.to_digit(10).unwrap_or(0)) * 2);
163    let check = (12 - total % 11) % 11;
164    let want = if check == 10 { 'X' } else { char::from_digit(check, 10).unwrap_or('?') };
165    last[0].to_ascii_uppercase() == want
166}
167
168/// Adds `person` (trimmed), working now when `use_now`. A name already taken is refused.
169pub fn add(person: Person, use_now: bool) -> Result<(), String> {
170    let person = Person {
171        name: person.name.trim().to_string(),
172        affiliation: person.affiliation.trim().to_string(),
173        orcid: person.orcid.trim().to_uppercase(),
174    };
175    check(&person)?;
176    with(|s| {
177        if s.book.people.iter().any(|p| p.name == person.name) {
178            return Err(format!("{:?} is there already", person.name));
179        }
180        if use_now {
181            s.book.current = Some(person.name.clone());
182        }
183        s.book.people.push(person);
184        changed(s)
185    })
186}
187
188/// Forgets `name` (working now: a guest works then). What was recorded under the name stays.
189pub fn remove(name: &str) -> Result<(), String> {
190    with(|s| {
191        s.book.people.retain(|p| p.name != name);
192        if s.book.current.as_deref() == Some(name) {
193            s.book.current = None;
194        }
195        changed(s)
196    })
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    /// People are added, picked, written and read back; the guest is no one; names are unique and
204    /// an ORCID iD is checked.
205    #[test]
206    fn people_are_kept_and_one_works_at_a_time() {
207        let dir = std::env::temp_dir().join(format!("kitchen_people_{}", std::process::id()));
208        let path = dir.join("people.json");
209        let _ = std::fs::remove_file(&path);
210        assert_eq!(load(&path), None);
211        assert_eq!((who(), current()), (GUEST.to_string(), None));
212        add(
213            Person {
214                name: " Ada ".into(),
215                affiliation: "Analytical Engines".into(),
216                orcid: "0000-0002-1825-0097".into(),
217            },
218            true,
219        )
220        .unwrap();
221        add(Person { name: "Grace".into(), ..Default::default() }, false).unwrap();
222        assert_eq!(who(), "Ada");
223        assert!(add(Person { name: "Ada".into(), ..Default::default() }, false).is_err(), "names are unique");
224        assert!(add(Person { name: "Guest".into(), ..Default::default() }, false).is_err());
225        assert!(
226            add(Person { name: "Bob".into(), orcid: "0000-0002-1825-0098".into(), ..Default::default() }, false)
227                .is_err(),
228            "a wrong check digit"
229        );
230        assert!(orcid_ok("0000-0002-9079-593X"));
231        use_person(Some("Grace")).unwrap();
232        assert!(use_person(Some("Nobody")).is_err());
233        assert_eq!(load(&path), None, "read back");
234        assert_eq!((who(), people().len()), ("Grace".to_string(), 2));
235        remove("Grace").unwrap();
236        assert_eq!(who(), GUEST, "the one removed was working: a guest is");
237        use_person(None).unwrap();
238        let _ = std::fs::remove_dir_all(&dir);
239    }
240}