1use std::path::{Path, PathBuf};
11use std::sync::Mutex;
12use std::sync::atomic::{AtomicU64, Ordering};
13
14use serde::{Deserialize, Serialize};
15
16pub const GUEST: &str = "guest";
18
19#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(default)]
22pub struct Person {
23 pub name: String,
25 #[serde(skip_serializing_if = "String::is_empty")]
27 pub affiliation: String,
28 #[serde(skip_serializing_if = "String::is_empty")]
30 pub orcid: String,
31}
32
33#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(default)]
36struct Book {
37 people: Vec<Person>,
38 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
56fn 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
79pub 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
101pub fn generation() -> u64 {
103 GENERATION.load(Ordering::Relaxed)
104}
105
106pub fn people() -> Vec<Person> {
108 with(|s| s.book.people.clone())
109}
110
111pub 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
116pub fn who() -> String {
118 current().map_or_else(|| GUEST.to_string(), |p| p.name)
119}
120
121pub 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
134fn 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
150pub 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
168pub 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
188pub 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 #[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}