tilo_process_services/
action_authority.rs1use std::path::{Path, PathBuf};
4use std::sync::Arc;
5
6pub type AuthoritySource = Arc<dyn Fn() -> Result<Option<Vec<u8>>, String> + Send + Sync>;
7
8pub fn source(path: PathBuf, max_bytes: usize) -> AuthoritySource {
13 #[cfg(feature = "native")]
14 {
15 Arc::new(move || read_held(&path, max_bytes))
16 }
17 #[cfg(not(feature = "native"))]
18 {
19 let _ = (path, max_bytes);
20 Arc::new(|| Ok(None))
21 }
22}
23
24pub type AuthorityWatch = Box<dyn std::any::Any + Send>;
26
27pub fn watch(path: &Path, changed: impl Fn() + Send + 'static) -> Result<AuthorityWatch, String> {
33 #[cfg(feature = "native")]
34 {
35 let directory = path.parent().ok_or("action policy has no directory")?;
36 let name = path.to_owned();
37 tilo_files::native::Watcher::entries(directory)
41 .released()
42 .on_change(move |entry| entry == name, changed)
43 .map(|watch| Box::new(watch) as AuthorityWatch)
44 .map_err(|error| format!("action policy cannot be watched: {error}"))
45 }
46 #[cfg(not(feature = "native"))]
47 {
48 let _ = (path, changed);
49 Ok(Box::new(()))
50 }
51}
52
53#[cfg(feature = "native")]
54fn read_held(path: &std::path::Path, max_bytes: usize) -> Result<Option<Vec<u8>>, String> {
55 tilo_files::native::held::read(path, max_bytes).map_err(|error| match error.kind() {
56 std::io::ErrorKind::FileTooLarge => "action policy exceeds its byte bound".into(),
57 std::io::ErrorKind::InvalidInput => "action policy bound is invalid".into(),
58 _ => "action policy is unavailable".into(),
59 })
60}
61
62#[cfg(all(test, feature = "native"))]
63mod tests {
64 #[test]
65 fn a_policy_is_read_only_while_the_host_holds_it() {
66 let unique = tilo_clock::try_unix_now_ns().unwrap();
67 let root = std::env::temp_dir().join(format!(
68 "tilo-process-authority-{}-{unique}",
69 std::process::id()
70 ));
71 std::fs::create_dir(&root).unwrap();
72 let path = root.join("current.json");
73 let source = super::source(path.clone(), 64);
74 assert_eq!(source().unwrap(), None);
75 let held = tilo_files::native::held::publish(&path, b"policy", 0o600).unwrap();
76 assert_eq!(source().unwrap().as_deref(), Some(&b"policy"[..]));
77 assert_eq!(source().unwrap().as_deref(), Some(&b"policy"[..]));
79 drop(held);
80 assert_eq!(
81 source().unwrap(),
82 None,
83 "a process that let go vouches for nothing"
84 );
85 std::fs::remove_dir_all(&root).unwrap();
86 }
87
88 #[test]
89 fn a_watch_hears_each_publication_and_the_host_letting_go() {
90 use std::sync::mpsc;
91 use std::time::Duration;
92 let unique = tilo_clock::try_unix_now_ns().unwrap();
93 let root = std::env::temp_dir().join(format!(
94 "tilo-process-authority-watch-{}-{unique}",
95 std::process::id()
96 ));
97 std::fs::create_dir(&root).unwrap();
98 let path = root.join("current.json");
99 let (told, heard) = mpsc::channel();
100 let _watch = super::watch(&path, move || {
101 let _ = told.send(());
102 })
103 .unwrap();
104 let source = super::source(path.clone(), 64);
105 let report = Duration::from_secs(10);
107 let settle = |heard: &mpsc::Receiver<()>| {
108 heard.recv_timeout(report).expect("the change was reported");
109 while heard.recv_timeout(Duration::from_millis(100)).is_ok() {}
110 };
111 let first = tilo_files::native::held::publish(&path, b"first", 0o600).unwrap();
112 settle(&heard);
113 let second = tilo_files::native::held::publish(&path, b"second", 0o600).unwrap();
114 drop(first);
115 settle(&heard);
116 assert_eq!(source().unwrap().as_deref(), Some(&b"second"[..]));
117 assert!(heard.recv_timeout(Duration::from_millis(300)).is_err());
119 drop(second);
120 settle(&heard);
121 assert_eq!(source().unwrap(), None);
122 std::fs::remove_dir_all(&root).unwrap();
123 }
124}