use std::collections::{BTreeMap, HashMap};
use std::ffi::{OsStr, OsString};
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock, RwLock};
pub const CHOSEN_ROOT: &str = "/run/tilo/chosen";
const RECORDS: &str = "records";
pub const RECORD: &str = "chosen.files";
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Kept {
pub workspace: String,
pub app: String,
pub kind: String,
pub host: PathBuf,
}
pub trait Store: Send + Sync {
fn load(&self) -> Vec<Kept>;
fn keep(&self, kept: Vec<Kept>);
fn follow(&self, _changed: Arc<dyn Fn(Vec<Kept>) + Send + Sync>) -> bool {
false
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AppKey {
workspace: String,
app: String,
}
impl AppKey {
#[must_use]
pub fn new(workspace: &str, app: &str) -> Option<Self> {
(is_workspace(workspace) && is_app(app)).then(|| Self {
workspace: workspace.to_owned(),
app: app.to_owned(),
})
}
#[must_use]
pub fn workspace(&self) -> &str {
&self.workspace
}
#[must_use]
pub fn app(&self) -> &str {
&self.app
}
}
pub(crate) fn is_workspace(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
}
pub(crate) fn is_app(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 255
&& !name.starts_with('.')
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Kind {
Read,
Save,
Folder {
write: bool,
},
}
impl Kind {
fn of_tag(tag: &str) -> Option<Self> {
Some(match tag {
"read" => Self::Read,
"save" => Self::Save,
"folder" => Self::Folder { write: false },
"folder-write" => Self::Folder { write: true },
_ => return None,
})
}
fn tag(self) -> &'static str {
match self {
Self::Read => "read",
Self::Save => "save",
Self::Folder { write: false } => "folder",
Self::Folder { write: true } => "folder-write",
}
}
#[must_use]
pub fn writes(self) -> bool {
matches!(self, Self::Save | Self::Folder { write: true })
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Document {
pub host: PathBuf,
pub kind: Kind,
}
impl Document {
#[must_use]
pub fn name(&self) -> &OsStr {
self.host
.file_name()
.unwrap_or_else(|| OsStr::new("document"))
}
#[must_use]
pub fn save_sibling(&self) -> Option<OsString> {
(self.kind == Kind::Save).then(|| {
let mut sibling = OsString::from(".");
sibling.push(self.name());
sibling.push(".tilo-save");
sibling
})
}
}
#[derive(Clone, Debug)]
pub struct Chosen {
pub reference: PathBuf,
pub name: String,
pub host: PathBuf,
pub kind: Kind,
pub save_sibling: Option<OsString>,
}
#[derive(Debug)]
pub enum GrantError {
NotThatKind,
Io(std::io::Error),
}
impl std::fmt::Display for GrantError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotThatKind => f.write_str("the chosen item is not what was asked for"),
Self::Io(error) => write!(f, "the chosen item cannot be reached: {error}"),
}
}
}
impl std::error::Error for GrantError {}
#[derive(Default, PartialEq)]
struct View {
documents: BTreeMap<String, Document>,
recent: Vec<String>,
}
impl View {
fn choose(&mut self, token: String, document: Document) -> bool {
if self.recent.first() == Some(&token) {
return false;
}
self.recent.retain(|kept| *kept != token);
self.recent.insert(0, token.clone());
self.documents.insert(token, document);
true
}
fn keep_older(&mut self, token: String, document: Document) {
if let Some(held) = self.documents.get_mut(&token) {
*held = document;
return;
}
self.documents.insert(token.clone(), document);
self.recent.push(token);
}
fn by_recency(&self) -> impl Iterator<Item = (&String, &Document)> {
self.recent
.iter()
.filter_map(|token| self.documents.get_key_value(token))
}
}
type Views = HashMap<AppKey, View>;
#[derive(Clone, Default)]
pub struct ChosenTable {
views: Arc<RwLock<Views>>,
store: Arc<OnceLock<Arc<dyn Store>>>,
revision: Arc<AtomicU64>,
}
impl ChosenTable {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn revision(&self) -> u64 {
self.revision.load(Ordering::Acquire)
}
fn changed(&self) {
self.revision.fetch_add(1, Ordering::AcqRel);
}
pub fn bind(&self, store: Arc<dyn Store>) {
if self.store.set(store).is_err() {
return;
}
let table = self.clone();
let loaded = std::thread::Builder::new()
.name("tilo-chosen-load".into())
.spawn(move || {
table.load();
table.follow();
});
if let Err(error) = loaded {
tracing::warn!(%error, "the files people chose earlier are not read");
}
}
fn follow(&self) {
let Some(store) = self.store.get().cloned() else {
return;
};
let table = self.clone();
store.follow(Arc::new(move |kept| table.replace(kept)));
}
fn load(&self) {
let Some(store) = self.store.get().cloned() else {
return;
};
self.replace(store.load());
}
fn replace(&self, kept: Vec<Kept>) {
let mut views: Views = HashMap::new();
for kept in kept {
let (Some(key), Some(kind)) = (
AppKey::new(&kept.workspace, &kept.app),
Kind::of_tag(&kept.kind),
) else {
continue;
};
let Ok(host) = resolve_choice(&kept.host, kind) else {
continue;
};
let document = Document { host, kind };
let token = token(&key, &document);
views.entry(key).or_default().keep_older(token, document);
}
let changed = self.views.write().is_ok_and(|mut held| {
if *held == views {
return false;
}
*held = views;
true
});
if changed {
self.changed();
}
}
fn keep(&self) {
let Some(store) = self.store.get() else {
return;
};
let Some(snapshot) = self.views.read().ok().map(|views| {
views
.iter()
.flat_map(|(key, view)| {
view.by_recency().map(|(_, document)| Kept {
workspace: key.workspace.clone(),
app: key.app.clone(),
kind: document.kind.tag().to_owned(),
host: document.host.clone(),
})
})
.collect::<Vec<_>>()
}) else {
return;
};
store.keep(snapshot);
}
pub fn grant(&self, key: &AppKey, chosen: &Path, kind: Kind) -> Result<Chosen, GrantError> {
let host = resolve_choice(chosen, kind)?;
let document = Document { host, kind };
let token = token(key, &document);
let changed = self.views.write().is_ok_and(|mut views| {
views
.entry(key.clone())
.or_default()
.choose(token.clone(), document.clone())
});
if changed {
self.keep();
self.changed();
}
Ok(entry(&token, document))
}
#[must_use]
pub fn document(&self, key: &AppKey, token: &str) -> Option<Document> {
self.views
.read()
.ok()?
.get(key)
.and_then(|view| view.documents.get(token).cloned())
}
#[must_use]
pub fn looked_up(&self, key: &AppKey, reference: &Path) -> Option<Chosen> {
let (token, _) = split_reference(reference)?;
let document = self.document(key, &token)?;
Some(entry(&token, document))
}
#[must_use]
pub fn entries(&self, key: &AppKey) -> Vec<Chosen> {
self.views
.read()
.ok()
.and_then(|views| {
views.get(key).map(|view| {
view.by_recency()
.map(|(token, document)| entry(token, document.clone()))
.collect()
})
})
.unwrap_or_default()
}
#[must_use]
pub fn chosen(&self, key: &AppKey) -> Vec<PathBuf> {
self.views
.read()
.ok()
.and_then(|views| {
views
.get(key)
.map(|view| view.by_recency().map(|(_, d)| d.host.clone()).collect())
})
.unwrap_or_default()
}
#[must_use]
pub fn tokens(&self, key: &AppKey) -> Vec<String> {
self.views
.read()
.ok()
.and_then(|views| {
views
.get(key)
.map(|view| view.documents.keys().cloned().collect())
})
.unwrap_or_default()
}
pub fn revoke(&self, key: &AppKey) {
let removed = self
.views
.write()
.is_ok_and(|mut views| views.remove(key).is_some());
if removed {
self.keep();
self.changed();
}
}
#[must_use]
pub fn all(&self) -> Vec<(AppKey, String, Chosen)> {
self.views
.read()
.ok()
.map(|views| {
views
.iter()
.flat_map(|(key, view)| {
view.by_recency().map(move |(token, document)| {
(key.clone(), token.clone(), entry(token, document.clone()))
})
})
.collect()
})
.unwrap_or_default()
}
pub fn forget(&self, key: &AppKey, token: &str) -> bool {
let removed = self.views.write().is_ok_and(|mut views| {
let Some(view) = views.get_mut(key) else {
return false;
};
let removed = view.documents.remove(token).is_some();
if removed {
view.recent.retain(|held| held != token);
if view.documents.is_empty() {
views.remove(key);
}
}
removed
});
if removed {
self.keep();
self.changed();
}
removed
}
}
fn entry(token: &str, document: Document) -> Chosen {
let name = document.name().to_string_lossy().into_owned();
let reference = Path::new(CHOSEN_ROOT).join(RECORDS).join(token).join(&name);
Chosen {
reference,
name,
save_sibling: document.save_sibling(),
host: document.host,
kind: document.kind,
}
}
fn resolve_choice(chosen: &Path, kind: Kind) -> Result<PathBuf, GrantError> {
match kind {
Kind::Read => {
let host = chosen.canonicalize().map_err(GrantError::Io)?;
let meta = std::fs::metadata(&host).map_err(GrantError::Io)?;
if meta.is_file() {
Ok(host)
} else {
Err(GrantError::NotThatKind)
}
}
Kind::Folder { .. } => {
let host = chosen.canonicalize().map_err(GrantError::Io)?;
if std::fs::metadata(&host).map_err(GrantError::Io)?.is_dir() {
Ok(host)
} else {
Err(GrantError::NotThatKind)
}
}
Kind::Save => {
let name = plain_name(chosen).ok_or(GrantError::NotThatKind)?;
let parent = chosen
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.ok_or(GrantError::NotThatKind)?
.canonicalize()
.map_err(GrantError::Io)?;
if !std::fs::metadata(&parent).map_err(GrantError::Io)?.is_dir() {
return Err(GrantError::NotThatKind);
}
let host = parent.join(name);
match std::fs::symlink_metadata(&host) {
Ok(meta) if meta.is_file() => Ok(host),
Ok(_) => Err(GrantError::NotThatKind),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(host),
Err(error) => Err(GrantError::Io(error)),
}
}
}
}
fn plain_name(path: &Path) -> Option<&OsStr> {
match path.components().next_back()? {
Component::Normal(name) => Some(name),
_ => None,
}
}
fn token(key: &AppKey, document: &Document) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(b"tilo-chosen/1\0");
hasher.update(key.workspace.as_bytes());
hasher.update(b"\0");
hasher.update(key.app.as_bytes());
hasher.update(b"\0");
hasher.update(document.kind.tag().as_bytes());
hasher.update(b"\0");
hasher.update(document.host.as_os_str().as_encoded_bytes());
let hex = hasher.finalize().to_hex();
hex.chars().take(24).collect()
}
#[must_use]
pub fn split_reference(path: &Path) -> Option<(String, PathBuf)> {
let rest = path.strip_prefix(CHOSEN_ROOT).ok()?;
let mut components = rest.components();
let Component::Normal(first) = components.next()? else {
return None;
};
if first != RECORDS {
return None;
}
let Component::Normal(token) = components.next()? else {
return None;
};
let inner: PathBuf = components.collect();
let token = token.to_str()?.to_owned();
Some((token, inner))
}
#[must_use]
pub fn chosen_table() -> Arc<ChosenTable> {
static TABLE: OnceLock<Arc<ChosenTable>> = OnceLock::new();
Arc::clone(TABLE.get_or_init(|| Arc::new(ChosenTable::new())))
}
pub fn bind_store(store: Arc<dyn Store>) {
chosen_table().bind(store);
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use super::*;
fn key() -> AppKey {
AppKey::new("5ba25f73-87c5-447f-a5a6-880dc4249a81", "so.tilo.totp").unwrap()
}
#[derive(Default)]
struct Held(Mutex<Vec<Kept>>);
impl Store for Held {
fn load(&self) -> Vec<Kept> {
self.0.lock().unwrap().clone()
}
fn keep(&self, kept: Vec<Kept>) {
*self.0.lock().unwrap() = kept;
}
}
fn wait_for(table: &ChosenTable, key: &AppKey, tokens: usize) {
tilo_test_env::wait_until("the kept table is read", || {
table.tokens(key).len() == tokens
});
}
#[test]
fn keys_carry_only_names_one_path_component_can_hold() {
assert!(AppKey::new("workspace-1", "so.tilo.files").is_some());
for (workspace, app) in [
("", "so.tilo.files"),
("../x", "so.tilo.files"),
("workspace", ".."),
("workspace", "a/b"),
("workspace", ".hidden"),
] {
assert!(
AppKey::new(workspace, app).is_none(),
"{workspace:?} {app:?}"
);
}
}
#[test]
fn a_choice_answers_a_stable_reference_in_the_chosen_root() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("report.pdf");
std::fs::write(&file, b"pdf").unwrap();
let table = ChosenTable::new();
let chosen = table.grant(&key(), &file, Kind::Read).unwrap();
assert_eq!(
table.grant(&key(), &file, Kind::Read).unwrap().reference,
chosen.reference
);
assert_eq!(table.entries(&key())[0].reference, chosen.reference);
assert!(chosen.reference.starts_with(CHOSEN_ROOT));
assert_eq!(chosen.name, "report.pdf");
assert_eq!(
table.looked_up(&key(), &chosen.reference).unwrap().host,
file.canonicalize().unwrap()
);
let other = AppKey::new("other-workspace", "so.tilo.totp").unwrap();
assert!(table.looked_up(&other, &chosen.reference).is_none());
assert_ne!(
table.grant(&other, &file, Kind::Read).unwrap().reference,
chosen.reference
);
assert!(
table
.looked_up(
&key(),
Path::new("/run/tilo/chosen/records/nope/report.pdf")
)
.is_none()
);
}
#[test]
fn a_kept_table_reopens_a_choice_where_it_was_and_forgets_what_is_gone() {
let dir = tempfile::tempdir().unwrap();
let kept = dir.path().join("kept.pdf");
let gone = dir.path().join("gone.pdf");
std::fs::write(&kept, b"kept").unwrap();
std::fs::write(&gone, b"gone").unwrap();
let store = Arc::new(Held::default());
let table = ChosenTable::new();
table.bind(store.clone());
let reference = table.grant(&key(), &kept, Kind::Read).unwrap().reference;
table.grant(&key(), &gone, Kind::Read).unwrap();
std::fs::remove_file(&gone).unwrap();
let next = ChosenTable::new();
next.bind(store);
wait_for(&next, &key(), 1);
assert!(
next.looked_up(&key(), &reference).is_some(),
"what was kept is served once the record is read"
);
}
#[test]
fn recent_lists_choices_newest_first_and_keeps_the_order() {
let dir = tempfile::tempdir().unwrap();
let [a, b, c] = ["a.txt", "b.txt", "c.txt"].map(|name| {
let path = dir.path().join(name);
std::fs::write(&path, name).unwrap();
path.canonicalize().unwrap()
});
let table = ChosenTable::new();
for path in [&a, &b, &c, &a] {
table.grant(&key(), path, Kind::Read).unwrap();
}
assert_eq!(
table.chosen(&key()),
[a, c, b],
"choosing again makes it the newest"
);
let other = AppKey::new("other-workspace", "so.tilo.totp").unwrap();
assert!(table.chosen(&other).is_empty(), "each app has its own");
}
#[test]
fn a_choice_must_be_what_the_chooser_asked_for() {
let dir = tempfile::tempdir().unwrap();
let table = ChosenTable::new();
assert!(matches!(
table.grant(&key(), dir.path(), Kind::Read),
Err(GrantError::NotThatKind)
));
let file = dir.path().join("a.txt");
std::fs::write(&file, b"a").unwrap();
assert!(matches!(
table.grant(&key(), &file, Kind::Folder { write: false }),
Err(GrantError::NotThatKind)
));
assert!(
table
.grant(&key(), &dir.path().join("new.txt"), Kind::Save)
.is_ok()
);
assert!(matches!(
table.grant(&key(), &dir.path().join("missing.txt"), Kind::Read),
Err(GrantError::Io(_))
));
}
}