Skip to main content

kute_cli/
peer_status.rs

1//! What a running `kute peer serve` says about itself, for someone at the
2//! same machine to read.
3//!
4//! The peer and the HTTP service are separate processes, and the peer
5//! opens no second port for this. With `--status-file` it writes a small
6//! JSON file: when it starts listening, when a connection is refused,
7//! when an exchange begins, once a second while it runs, and when it
8//! ends. `kute serve --peer-status FILE` reads that file when asked
9//! (`GET /v1/peer`), and Studio shows it.
10//!
11//! A file cannot say that its writer is alive. What it can say is when it
12//! was last written, and a peer that is running writes every second, so
13//! a file that has not been written for several seconds while claiming
14//! to be running is reported as stale and not as running.
15
16use serde_json::{Value, json};
17use std::path::{Path, PathBuf};
18use std::sync::{Arc, Mutex, OnceLock};
19use std::time::{Duration, SystemTime, UNIX_EPOCH};
20
21/// The number in `kute_peer_status`. A reader refuses any other.
22pub const FORMAT: u64 = 1;
23/// How often a running peer rewrites the file.
24pub const HEARTBEAT: Duration = Duration::from_secs(1);
25/// The largest status file a reader takes.
26pub 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    /// Held for the whole of a write. The beat and a change of state
40    /// write from two threads to one temporary name: without this, one
41    /// renames the other's file away, and the write that fails may be
42    /// the one saying the peer ended, which nothing writes again.
43    writing: Mutex<()>,
44}
45
46static WRITER: OnceLock<Arc<Writer>> = OnceLock::new();
47
48impl Writer {
49    /// Write the whole file beside the old one, then put it in its place,
50    /// so a reader sees one state or the next and never half of one.
51    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
66/// Begin writing status to `path`, starting with `first`. A path that
67/// cannot be written is the operator's mistake, told now.
68pub 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                // A write that fails (the file is open elsewhere, the disk
80                // is full) is tried again at the next beat.
81                let _ = writer.write();
82            }
83        });
84    }
85    Ok(())
86}
87
88/// Change what the next write says. Nothing is written now: counts that
89/// move with every message are picked up by the next beat.
90pub 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
96/// Change the state and write at once.
97pub 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
109/// The peer is ending, this way.
110pub 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
119/// Read a status file for the HTTP service. Never an error: a file that
120/// is missing, too large or not a status is an answer about the peer.
121pub 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    // Writer and reader share a clock. A time of writing later than now
138    // by more than a beat is not a fresh file but one whose time cannot
139    // be believed, and it is not taken as proof of a running peer.
140    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    /// The beat and a change of state write from two threads. Whatever
165    /// order they finish in, a reader finds a whole status, and the file
166    /// left at the end is the last state entered.
167    #[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        // Large enough that a write takes long enough to be met halfway.
174        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}