1use serde_json::{Value, json};
17use std::path::{Path, PathBuf};
18use std::sync::{Arc, Mutex, OnceLock};
19use std::time::{Duration, SystemTime, UNIX_EPOCH};
20
21pub const FORMAT: u64 = 1;
23pub const HEARTBEAT: Duration = Duration::from_secs(1);
25pub const MAX_BYTES: u64 = 65_536;
27
28pub const WAITING: &str = "waiting for a connection";
29pub const EXCHANGE: &str = "in an exchange";
30pub const ENDED: &str = "ended";
31
32pub fn now() -> u64 {
33 SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
34}
35
36struct Writer {
37 path: PathBuf,
38 value: Mutex<Value>,
39 writing: Mutex<()>,
44}
45
46static WRITER: OnceLock<Arc<Writer>> = OnceLock::new();
47
48impl Writer {
49 fn write(&self) -> std::io::Result<()> {
52 let _one_at_a_time = self.writing.lock().unwrap_or_else(|p| p.into_inner());
53 let mut value = self.value.lock().unwrap_or_else(|p| p.into_inner()).clone();
54 value["written"] = json!(now());
55 let bytes = serde_json::to_vec_pretty(&value).map_err(std::io::Error::other)?;
56 let mut name = self.path.file_name().unwrap_or_default().to_os_string();
57 name.push(format!(".writing-{}", std::process::id()));
58 let beside = self.path.with_file_name(name);
59 std::fs::write(&beside, bytes)?;
60 std::fs::rename(&beside, &self.path).inspect_err(|_| {
61 let _ = std::fs::remove_file(&beside);
62 })
63 }
64}
65
66pub fn start(path: &Path, mut first: Value) -> kute::Result<()> {
69 first["kute_peer_status"] = json!(FORMAT);
70 first["heartbeat_seconds"] = json!(HEARTBEAT.as_secs());
71 first["started"] = json!(now());
72 first["since"] = json!(now());
73 let writer = Arc::new(Writer { path: path.to_path_buf(), value: Mutex::new(first), writing: Mutex::new(()) });
74 writer.write().map_err(|e| kute::KuteError::InvalidConfig(format!("the status file {} cannot be written: {e}", path.display())))?;
75 if WRITER.set(writer.clone()).is_ok() {
76 std::thread::spawn(move || {
77 loop {
78 std::thread::sleep(HEARTBEAT);
79 let _ = writer.write();
82 }
83 });
84 }
85 Ok(())
86}
87
88pub fn set(change: impl FnOnce(&mut Value)) {
91 if let Some(writer) = WRITER.get() {
92 change(&mut writer.value.lock().unwrap_or_else(|p| p.into_inner()));
93 }
94}
95
96pub fn enter(state: &str, change: impl FnOnce(&mut Value)) {
98 if let Some(writer) = WRITER.get() {
99 {
100 let mut value = writer.value.lock().unwrap_or_else(|p| p.into_inner());
101 value["state"] = json!(state);
102 value["since"] = json!(now());
103 change(&mut value);
104 }
105 let _ = writer.write();
106 }
107}
108
109pub fn end(result: &kute::Result<()>) {
111 enter(ENDED, |value| {
112 value["ended"] = match result {
113 Ok(()) => json!({ "ok": true }),
114 Err(e) => json!({ "ok": false, "error": e.to_string() }),
115 };
116 });
117}
118
119pub fn read(path: &Path) -> Value {
122 let absent = |why: &str| json!({ "present": false, "why": why, "file": path });
123 let Ok(metadata) = std::fs::metadata(path) else {
124 return absent("no status file is there: no peer has been started with --status-file naming it, or the file was removed");
125 };
126 if !metadata.is_file() || metadata.len() > MAX_BYTES {
127 return absent("what is there is not a status file: it is not a plain file of at most 64 KiB");
128 }
129 let Some(status) = std::fs::read(path).ok().and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok()).filter(|v| v["kute_peer_status"] == json!(FORMAT) && v["state"].is_string()) else {
130 return absent("the file could not be read as a peer status of the kind this version reads");
131 };
132 let read_at = now();
133 let written = status["written"].as_u64().unwrap_or(0);
134 let age = read_at.saturating_sub(written);
135 let beat = status["heartbeat_seconds"].as_u64().unwrap_or(1).clamp(1, 60);
136 let ended = status["state"] == ENDED;
137 let from_the_future = written > read_at + beat;
141 let stale = !ended && (age > 3 * beat || from_the_future);
142 json!({
143 "present": true,
144 "file": path,
145 "read_at": read_at,
146 "age_seconds": age,
147 "written_later_than_now": from_the_future,
148 "stale": stale,
149 "status": status,
150 "means": if ended {
151 "the peer wrote that it had ended. kute peer serve answers one connection and ends; nothing is running."
152 } else if stale {
153 "the file says a peer is running, but it has not been written for longer than three of its beats, or says it was written later than now. The peer has stopped without saying so, or cannot write, or the file is not a peer's. Nothing here shows a running peer."
154 } else {
155 "a process wrote this within the last few seconds. It is that process's own account; this service did not connect to it."
156 },
157 })
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163
164 #[test]
168 fn two_writers_at_once_leave_a_whole_file_saying_the_last_state() {
169 let dir = std::env::temp_dir().join(format!("kute-peer-status-writers-{}", std::process::id()));
170 let _ = std::fs::remove_dir_all(&dir);
171 std::fs::create_dir_all(&dir).unwrap();
172 let path = dir.join("peer.json");
173 let writer = Arc::new(Writer { path: path.clone(), value: Mutex::new(json!({ "kute_peer_status": FORMAT, "state": WAITING, "pad": "x".repeat(40_000) })), writing: Mutex::new(()) });
175 writer.write().unwrap();
176 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
177 let beats: Vec<_> = (0..3)
178 .map(|_| {
179 let (writer, stop) = (writer.clone(), stop.clone());
180 std::thread::spawn(move || {
181 while !stop.load(std::sync::atomic::Ordering::Relaxed) {
182 let _ = writer.write();
183 }
184 })
185 })
186 .collect();
187 let reader = {
188 let (path, stop) = (path.clone(), stop.clone());
189 std::thread::spawn(move || {
190 let (mut whole, mut broken) = (0u64, 0u64);
191 while !stop.load(std::sync::atomic::Ordering::Relaxed) {
192 if let Ok(bytes) = std::fs::read(&path) {
193 if serde_json::from_slice::<Value>(&bytes).is_ok() { whole += 1 } else { broken += 1 }
194 }
195 }
196 (whole, broken)
197 })
198 };
199 let mut lost = 0;
200 let mut failed: Vec<String> = Vec::new();
201 for round in 0..60 {
202 let state = format!("state {round}");
203 writer.value.lock().unwrap()["state"] = json!(state);
204 if let Err(e) = writer.write() { failed.push(e.to_string()); }
205 std::thread::sleep(Duration::from_millis(1));
206 stop.store(round == 59, std::sync::atomic::Ordering::Relaxed);
207 }
208 for beat in beats {
209 beat.join().unwrap();
210 }
211 let (whole, broken) = reader.join().unwrap();
212 let last: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
213 if last["state"] != json!("state 59") {
214 lost += 1;
215 }
216 let left: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).filter(|n| n.to_string_lossy().contains("writing")).collect();
217 let _ = std::fs::remove_dir_all(&dir);
218 assert!(whole > 0);
219 assert_eq!((broken, lost, left.len(), failed.len()), (0, 0, 0, 0), "state writes that failed: {} (first: {:?}); reads that were not a whole status: {broken} of {}; last state lost: {lost}; temp files left: {left:?}", failed.len(), failed.first(), whole + broken);
220 }
221}