1use std::collections::{BTreeMap, HashMap};
20use std::ffi::{OsStr, OsString};
21use std::path::{Component, Path, PathBuf};
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::sync::{Arc, OnceLock, RwLock};
24
25pub const CHOSEN_ROOT: &str = "/run/tilo/chosen";
28
29const RECORDS: &str = "records";
31
32pub const RECORD: &str = "chosen.files";
34
35#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37pub struct Kept {
38 pub workspace: String,
39 pub app: String,
40 pub kind: String,
41 pub host: PathBuf,
42}
43
44pub trait Store: Send + Sync {
47 fn load(&self) -> Vec<Kept>;
49 fn keep(&self, kept: Vec<Kept>);
51 fn follow(&self, _changed: Arc<dyn Fn(Vec<Kept>) + Send + Sync>) -> bool {
55 false
56 }
57}
58
59#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
62pub struct AppKey {
63 workspace: String,
64 app: String,
65}
66
67impl AppKey {
68 #[must_use]
72 pub fn new(workspace: &str, app: &str) -> Option<Self> {
73 (is_workspace(workspace) && is_app(app)).then(|| Self {
74 workspace: workspace.to_owned(),
75 app: app.to_owned(),
76 })
77 }
78
79 #[must_use]
80 pub fn workspace(&self) -> &str {
81 &self.workspace
82 }
83
84 #[must_use]
85 pub fn app(&self) -> &str {
86 &self.app
87 }
88}
89
90pub(crate) fn is_workspace(name: &str) -> bool {
91 !name.is_empty()
92 && name.len() <= 64
93 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
94}
95
96pub(crate) fn is_app(name: &str) -> bool {
97 !name.is_empty()
98 && name.len() <= 255
99 && !name.starts_with('.')
100 && name
101 .bytes()
102 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
107pub enum Kind {
108 Read,
109 Save,
113 Folder {
114 write: bool,
115 },
116}
117
118impl Kind {
119 fn of_tag(tag: &str) -> Option<Self> {
120 Some(match tag {
121 "read" => Self::Read,
122 "save" => Self::Save,
123 "folder" => Self::Folder { write: false },
124 "folder-write" => Self::Folder { write: true },
125 _ => return None,
126 })
127 }
128
129 fn tag(self) -> &'static str {
130 match self {
131 Self::Read => "read",
132 Self::Save => "save",
133 Self::Folder { write: false } => "folder",
134 Self::Folder { write: true } => "folder-write",
135 }
136 }
137
138 #[must_use]
140 pub fn writes(self) -> bool {
141 matches!(self, Self::Save | Self::Folder { write: true })
142 }
143}
144
145#[derive(Clone, Debug, PartialEq, Eq)]
147pub struct Document {
148 pub host: PathBuf,
151 pub kind: Kind,
152}
153
154impl Document {
155 #[must_use]
156 pub fn name(&self) -> &OsStr {
157 self.host
158 .file_name()
159 .unwrap_or_else(|| OsStr::new("document"))
160 }
161
162 #[must_use]
164 pub fn save_sibling(&self) -> Option<OsString> {
165 (self.kind == Kind::Save).then(|| {
166 let mut sibling = OsString::from(".");
167 sibling.push(self.name());
168 sibling.push(".tilo-save");
169 sibling
170 })
171 }
172}
173
174#[derive(Clone, Debug)]
176pub struct Chosen {
177 pub reference: PathBuf,
179 pub name: String,
181 pub host: PathBuf,
183 pub kind: Kind,
185 pub save_sibling: Option<OsString>,
187}
188
189#[derive(Debug)]
190pub enum GrantError {
191 NotThatKind,
194 Io(std::io::Error),
196}
197
198impl std::fmt::Display for GrantError {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 match self {
201 Self::NotThatKind => f.write_str("the chosen item is not what was asked for"),
202 Self::Io(error) => write!(f, "the chosen item cannot be reached: {error}"),
203 }
204 }
205}
206
207impl std::error::Error for GrantError {}
208
209#[derive(Default, PartialEq)]
211struct View {
212 documents: BTreeMap<String, Document>,
213 recent: Vec<String>,
214}
215
216impl View {
217 fn choose(&mut self, token: String, document: Document) -> bool {
218 if self.recent.first() == Some(&token) {
219 return false;
220 }
221 self.recent.retain(|kept| *kept != token);
222 self.recent.insert(0, token.clone());
223 self.documents.insert(token, document);
224 true
225 }
226
227 fn keep_older(&mut self, token: String, document: Document) {
230 if let Some(held) = self.documents.get_mut(&token) {
231 *held = document;
232 return;
233 }
234 self.documents.insert(token.clone(), document);
235 self.recent.push(token);
236 }
237
238 fn by_recency(&self) -> impl Iterator<Item = (&String, &Document)> {
239 self.recent
240 .iter()
241 .filter_map(|token| self.documents.get_key_value(token))
242 }
243}
244
245type Views = HashMap<AppKey, View>;
246
247#[derive(Clone, Default)]
249pub struct ChosenTable {
250 views: Arc<RwLock<Views>>,
251 store: Arc<OnceLock<Arc<dyn Store>>>,
252 revision: Arc<AtomicU64>,
255}
256
257impl ChosenTable {
258 #[must_use]
259 pub fn new() -> Self {
260 Self::default()
261 }
262
263 #[must_use]
266 pub fn revision(&self) -> u64 {
267 self.revision.load(Ordering::Acquire)
268 }
269
270 fn changed(&self) {
271 self.revision.fetch_add(1, Ordering::AcqRel);
272 }
273
274 pub fn bind(&self, store: Arc<dyn Store>) {
281 if self.store.set(store).is_err() {
282 return;
283 }
284 let table = self.clone();
285 let loaded = std::thread::Builder::new()
286 .name("tilo-chosen-load".into())
287 .spawn(move || {
288 table.load();
289 table.follow();
290 });
291 if let Err(error) = loaded {
292 tracing::warn!(%error, "the files people chose earlier are not read");
293 }
294 }
295
296 fn follow(&self) {
299 let Some(store) = self.store.get().cloned() else {
300 return;
301 };
302 let table = self.clone();
303 store.follow(Arc::new(move |kept| table.replace(kept)));
305 }
306
307 fn load(&self) {
308 let Some(store) = self.store.get().cloned() else {
309 return;
310 };
311 self.replace(store.load());
312 }
313
314 fn replace(&self, kept: Vec<Kept>) {
317 let mut views: Views = HashMap::new();
318 for kept in kept {
319 let (Some(key), Some(kind)) = (
320 AppKey::new(&kept.workspace, &kept.app),
321 Kind::of_tag(&kept.kind),
322 ) else {
323 continue;
324 };
325 let Ok(host) = resolve_choice(&kept.host, kind) else {
326 continue;
327 };
328 let document = Document { host, kind };
329 let token = token(&key, &document);
330 views.entry(key).or_default().keep_older(token, document);
331 }
332 let changed = self.views.write().is_ok_and(|mut held| {
333 if *held == views {
334 return false;
335 }
336 *held = views;
337 true
338 });
339 if changed {
340 self.changed();
341 }
342 }
343
344 fn keep(&self) {
345 let Some(store) = self.store.get() else {
346 return;
347 };
348 let Some(snapshot) = self.views.read().ok().map(|views| {
349 views
350 .iter()
351 .flat_map(|(key, view)| {
352 view.by_recency().map(|(_, document)| Kept {
353 workspace: key.workspace.clone(),
354 app: key.app.clone(),
355 kind: document.kind.tag().to_owned(),
356 host: document.host.clone(),
357 })
358 })
359 .collect::<Vec<_>>()
360 }) else {
361 return;
362 };
363 store.keep(snapshot);
364 }
365
366 pub fn grant(&self, key: &AppKey, chosen: &Path, kind: Kind) -> Result<Chosen, GrantError> {
375 let host = resolve_choice(chosen, kind)?;
376 let document = Document { host, kind };
377 let token = token(key, &document);
378 let changed = self.views.write().is_ok_and(|mut views| {
379 views
380 .entry(key.clone())
381 .or_default()
382 .choose(token.clone(), document.clone())
383 });
384 if changed {
385 self.keep();
386 self.changed();
387 }
388 Ok(entry(&token, document))
389 }
390
391 #[must_use]
393 pub fn document(&self, key: &AppKey, token: &str) -> Option<Document> {
394 self.views
395 .read()
396 .ok()?
397 .get(key)
398 .and_then(|view| view.documents.get(token).cloned())
399 }
400
401 #[must_use]
407 pub fn looked_up(&self, key: &AppKey, reference: &Path) -> Option<Chosen> {
408 let (token, _) = split_reference(reference)?;
409 let document = self.document(key, &token)?;
410 Some(entry(&token, document))
411 }
412
413 #[must_use]
415 pub fn entries(&self, key: &AppKey) -> Vec<Chosen> {
416 self.views
417 .read()
418 .ok()
419 .and_then(|views| {
420 views.get(key).map(|view| {
421 view.by_recency()
422 .map(|(token, document)| entry(token, document.clone()))
423 .collect()
424 })
425 })
426 .unwrap_or_default()
427 }
428
429 #[must_use]
431 pub fn chosen(&self, key: &AppKey) -> Vec<PathBuf> {
432 self.views
433 .read()
434 .ok()
435 .and_then(|views| {
436 views
437 .get(key)
438 .map(|view| view.by_recency().map(|(_, d)| d.host.clone()).collect())
439 })
440 .unwrap_or_default()
441 }
442
443 #[must_use]
444 pub fn tokens(&self, key: &AppKey) -> Vec<String> {
445 self.views
446 .read()
447 .ok()
448 .and_then(|views| {
449 views
450 .get(key)
451 .map(|view| view.documents.keys().cloned().collect())
452 })
453 .unwrap_or_default()
454 }
455
456 pub fn revoke(&self, key: &AppKey) {
458 let removed = self
459 .views
460 .write()
461 .is_ok_and(|mut views| views.remove(key).is_some());
462 if removed {
463 self.keep();
464 self.changed();
465 }
466 }
467
468 #[must_use]
471 pub fn all(&self) -> Vec<(AppKey, String, Chosen)> {
472 self.views
473 .read()
474 .ok()
475 .map(|views| {
476 views
477 .iter()
478 .flat_map(|(key, view)| {
479 view.by_recency().map(move |(token, document)| {
480 (key.clone(), token.clone(), entry(token, document.clone()))
481 })
482 })
483 .collect()
484 })
485 .unwrap_or_default()
486 }
487
488 pub fn forget(&self, key: &AppKey, token: &str) -> bool {
491 let removed = self.views.write().is_ok_and(|mut views| {
492 let Some(view) = views.get_mut(key) else {
493 return false;
494 };
495 let removed = view.documents.remove(token).is_some();
496 if removed {
497 view.recent.retain(|held| held != token);
498 if view.documents.is_empty() {
499 views.remove(key);
500 }
501 }
502 removed
503 });
504 if removed {
505 self.keep();
506 self.changed();
507 }
508 removed
509 }
510}
511
512fn entry(token: &str, document: Document) -> Chosen {
514 let name = document.name().to_string_lossy().into_owned();
515 let reference = Path::new(CHOSEN_ROOT).join(RECORDS).join(token).join(&name);
516 Chosen {
517 reference,
518 name,
519 save_sibling: document.save_sibling(),
520 host: document.host,
521 kind: document.kind,
522 }
523}
524
525fn resolve_choice(chosen: &Path, kind: Kind) -> Result<PathBuf, GrantError> {
526 match kind {
527 Kind::Read => {
528 let host = chosen.canonicalize().map_err(GrantError::Io)?;
529 let meta = std::fs::metadata(&host).map_err(GrantError::Io)?;
530 if meta.is_file() {
531 Ok(host)
532 } else {
533 Err(GrantError::NotThatKind)
534 }
535 }
536 Kind::Folder { .. } => {
537 let host = chosen.canonicalize().map_err(GrantError::Io)?;
538 if std::fs::metadata(&host).map_err(GrantError::Io)?.is_dir() {
539 Ok(host)
540 } else {
541 Err(GrantError::NotThatKind)
542 }
543 }
544 Kind::Save => {
545 let name = plain_name(chosen).ok_or(GrantError::NotThatKind)?;
546 let parent = chosen
547 .parent()
548 .filter(|parent| !parent.as_os_str().is_empty())
549 .ok_or(GrantError::NotThatKind)?
550 .canonicalize()
551 .map_err(GrantError::Io)?;
552 if !std::fs::metadata(&parent).map_err(GrantError::Io)?.is_dir() {
553 return Err(GrantError::NotThatKind);
554 }
555 let host = parent.join(name);
556 match std::fs::symlink_metadata(&host) {
557 Ok(meta) if meta.is_file() => Ok(host),
558 Ok(_) => Err(GrantError::NotThatKind),
559 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(host),
560 Err(error) => Err(GrantError::Io(error)),
561 }
562 }
563 }
564}
565
566fn plain_name(path: &Path) -> Option<&OsStr> {
567 match path.components().next_back()? {
568 Component::Normal(name) => Some(name),
569 _ => None,
570 }
571}
572
573fn token(key: &AppKey, document: &Document) -> String {
576 let mut hasher = blake3::Hasher::new();
577 hasher.update(b"tilo-chosen/1\0");
578 hasher.update(key.workspace.as_bytes());
579 hasher.update(b"\0");
580 hasher.update(key.app.as_bytes());
581 hasher.update(b"\0");
582 hasher.update(document.kind.tag().as_bytes());
583 hasher.update(b"\0");
584 hasher.update(document.host.as_os_str().as_encoded_bytes());
585 let hex = hasher.finalize().to_hex();
586 hex.chars().take(24).collect()
587}
588
589#[must_use]
591pub fn split_reference(path: &Path) -> Option<(String, PathBuf)> {
592 let rest = path.strip_prefix(CHOSEN_ROOT).ok()?;
593 let mut components = rest.components();
594 let Component::Normal(first) = components.next()? else {
595 return None;
596 };
597 if first != RECORDS {
598 return None;
599 }
600 let Component::Normal(token) = components.next()? else {
601 return None;
602 };
603 let inner: PathBuf = components.collect();
604 let token = token.to_str()?.to_owned();
605 Some((token, inner))
606}
607
608#[must_use]
611pub fn chosen_table() -> Arc<ChosenTable> {
612 static TABLE: OnceLock<Arc<ChosenTable>> = OnceLock::new();
613 Arc::clone(TABLE.get_or_init(|| Arc::new(ChosenTable::new())))
614}
615
616pub fn bind_store(store: Arc<dyn Store>) {
618 chosen_table().bind(store);
619}
620
621#[cfg(test)]
622mod tests {
623 use std::sync::Mutex;
624
625 use super::*;
626
627 fn key() -> AppKey {
628 AppKey::new("5ba25f73-87c5-447f-a5a6-880dc4249a81", "so.tilo.totp").unwrap()
629 }
630
631 #[derive(Default)]
633 struct Held(Mutex<Vec<Kept>>);
634
635 impl Store for Held {
636 fn load(&self) -> Vec<Kept> {
637 self.0.lock().unwrap().clone()
638 }
639
640 fn keep(&self, kept: Vec<Kept>) {
641 *self.0.lock().unwrap() = kept;
642 }
643 }
644
645 fn wait_for(table: &ChosenTable, key: &AppKey, tokens: usize) {
646 tilo_test_env::wait_until("the kept table is read", || {
647 table.tokens(key).len() == tokens
648 });
649 }
650
651 #[test]
652 fn keys_carry_only_names_one_path_component_can_hold() {
653 assert!(AppKey::new("workspace-1", "so.tilo.files").is_some());
654 for (workspace, app) in [
655 ("", "so.tilo.files"),
656 ("../x", "so.tilo.files"),
657 ("workspace", ".."),
658 ("workspace", "a/b"),
659 ("workspace", ".hidden"),
660 ] {
661 assert!(
662 AppKey::new(workspace, app).is_none(),
663 "{workspace:?} {app:?}"
664 );
665 }
666 }
667
668 #[test]
669 fn a_choice_answers_a_stable_reference_in_the_chosen_root() {
670 let dir = tempfile::tempdir().unwrap();
671 let file = dir.path().join("report.pdf");
672 std::fs::write(&file, b"pdf").unwrap();
673 let table = ChosenTable::new();
674 let chosen = table.grant(&key(), &file, Kind::Read).unwrap();
675 assert_eq!(
676 table.grant(&key(), &file, Kind::Read).unwrap().reference,
677 chosen.reference
678 );
679 assert_eq!(table.entries(&key())[0].reference, chosen.reference);
680 assert!(chosen.reference.starts_with(CHOSEN_ROOT));
681 assert_eq!(chosen.name, "report.pdf");
682 assert_eq!(
683 table.looked_up(&key(), &chosen.reference).unwrap().host,
684 file.canonicalize().unwrap()
685 );
686 let other = AppKey::new("other-workspace", "so.tilo.totp").unwrap();
687 assert!(table.looked_up(&other, &chosen.reference).is_none());
688 assert_ne!(
689 table.grant(&other, &file, Kind::Read).unwrap().reference,
690 chosen.reference
691 );
692 assert!(
693 table
694 .looked_up(
695 &key(),
696 Path::new("/run/tilo/chosen/records/nope/report.pdf")
697 )
698 .is_none()
699 );
700 }
701
702 #[test]
703 fn a_kept_table_reopens_a_choice_where_it_was_and_forgets_what_is_gone() {
704 let dir = tempfile::tempdir().unwrap();
705 let kept = dir.path().join("kept.pdf");
706 let gone = dir.path().join("gone.pdf");
707 std::fs::write(&kept, b"kept").unwrap();
708 std::fs::write(&gone, b"gone").unwrap();
709 let store = Arc::new(Held::default());
710 let table = ChosenTable::new();
711 table.bind(store.clone());
712 let reference = table.grant(&key(), &kept, Kind::Read).unwrap().reference;
713 table.grant(&key(), &gone, Kind::Read).unwrap();
714 std::fs::remove_file(&gone).unwrap();
715
716 let next = ChosenTable::new();
717 next.bind(store);
718 wait_for(&next, &key(), 1);
719 assert!(
720 next.looked_up(&key(), &reference).is_some(),
721 "what was kept is served once the record is read"
722 );
723 }
724
725 #[test]
726 fn recent_lists_choices_newest_first_and_keeps_the_order() {
727 let dir = tempfile::tempdir().unwrap();
728 let [a, b, c] = ["a.txt", "b.txt", "c.txt"].map(|name| {
729 let path = dir.path().join(name);
730 std::fs::write(&path, name).unwrap();
731 path.canonicalize().unwrap()
732 });
733 let table = ChosenTable::new();
734 for path in [&a, &b, &c, &a] {
735 table.grant(&key(), path, Kind::Read).unwrap();
736 }
737 assert_eq!(
738 table.chosen(&key()),
739 [a, c, b],
740 "choosing again makes it the newest"
741 );
742 let other = AppKey::new("other-workspace", "so.tilo.totp").unwrap();
743 assert!(table.chosen(&other).is_empty(), "each app has its own");
744 }
745
746 #[test]
747 fn a_choice_must_be_what_the_chooser_asked_for() {
748 let dir = tempfile::tempdir().unwrap();
749 let table = ChosenTable::new();
750 assert!(matches!(
751 table.grant(&key(), dir.path(), Kind::Read),
752 Err(GrantError::NotThatKind)
753 ));
754 let file = dir.path().join("a.txt");
755 std::fs::write(&file, b"a").unwrap();
756 assert!(matches!(
757 table.grant(&key(), &file, Kind::Folder { write: false }),
758 Err(GrantError::NotThatKind)
759 ));
760 assert!(
761 table
762 .grant(&key(), &dir.path().join("new.txt"), Kind::Save)
763 .is_ok()
764 );
765 assert!(matches!(
766 table.grant(&key(), &dir.path().join("missing.txt"), Kind::Read),
767 Err(GrantError::Io(_))
768 ));
769 }
770}