1use std::collections::HashSet;
7use std::path::PathBuf;
8use std::sync::{Arc, Mutex, MutexGuard};
9
10use vitrify_core::model::UtcTime;
11
12use crate::gate;
13use crate::out::J;
14use crate::run::events::{EventLog, RunEvent};
15
16#[derive(Clone)]
19pub struct GateBoard {
20 inner: Arc<Mutex<Board>>,
21}
22
23struct Board {
26 path: Option<PathBuf>,
28 events: EventLog,
29 step: &'static str,
30 since: UtcTime,
31 batch: Vec<String>,
32 running: Vec<(String, String)>,
34 count: Option<(usize, HashSet<String>)>,
37}
38
39impl Board {
40 fn begin(&mut self, name: &'static str) {
42 self.step = name;
43 self.since = UtcTime::now();
44 self.running.clear();
45 self.count = None;
46 if name == "idle" {
47 return;
48 }
49 let mut detail = name.to_string();
50 if !self.batch.is_empty() {
51 detail = format!("{detail} · {}", self.batch.join(", "));
52 }
53 let units = self.batch.iter().map(|u| J::s(u.clone())).collect();
54 self.events.write(
55 &RunEvent::new(UtcTime::now(), "gate", None, None, detail)
56 .with("batch", J::Arr(units))
57 .with("step", J::s(name)),
58 );
59 }
60
61 fn to_json(&self) -> J {
63 let (done, total) = match &self.count {
64 Some((total, done)) => (J::Int(done.len() as i64), J::Int(*total as i64)),
65 None => (J::Null, J::Null),
66 };
67 let running = self
68 .running
69 .iter()
70 .map(|(cmd, since)| {
71 J::Obj(vec![
72 ("command".to_string(), J::s(cmd.clone())),
73 ("since".to_string(), J::s(since.clone())),
74 ])
75 })
76 .collect();
77 J::Obj(vec![
78 ("step".to_string(), J::s(self.step)),
79 ("since".to_string(), J::s(self.since.format())),
80 (
81 "batch".to_string(),
82 J::Arr(self.batch.iter().map(|u| J::s(u.clone())).collect()),
83 ),
84 ("running".to_string(), J::Arr(running)),
85 ("done".to_string(), done),
86 ("total".to_string(), total),
87 ])
88 }
89
90 fn write(&self) {
93 let Some(path) = &self.path else { return };
94 let tmp = path.with_file_name("gate.json.tmp");
95 if std::fs::write(&tmp, self.to_json().dumps_indent2()).is_ok() {
96 let _ = std::fs::rename(&tmp, path);
97 }
98 }
99}
100
101impl GateBoard {
102 fn new(path: Option<PathBuf>) -> GateBoard {
104 GateBoard {
105 inner: Arc::new(Mutex::new(Board {
106 path,
107 events: EventLog::off(),
108 step: "idle",
109 since: UtcTime::now(),
110 batch: Vec::new(),
111 running: Vec::new(),
112 count: None,
113 })),
114 }
115 }
116
117 pub fn off() -> GateBoard {
119 GateBoard::new(None)
120 }
121
122 pub fn to(path: PathBuf) -> GateBoard {
124 GateBoard::new(Some(path))
125 }
126
127 pub fn with_events(self, events: EventLog) -> GateBoard {
129 self.lock().events = events;
130 self
131 }
132
133 fn lock(&self) -> MutexGuard<'_, Board> {
136 self.inner.lock().unwrap_or_else(|p| p.into_inner())
137 }
138
139 fn change(&self, f: impl FnOnce(&mut Board)) {
142 let mut board = self.lock();
143 f(&mut board);
144 board.write();
145 }
146
147 pub fn batch(&self, units: Vec<String>) {
149 self.change(|b| b.batch = units);
150 }
151
152 pub fn step(&self, name: &'static str) {
154 self.change(|b| b.begin(name));
155 }
156
157 pub fn rows(&self, total: usize) {
159 self.change(|b| b.count = Some((total, HashSet::new())));
160 }
161
162 pub fn idle(&self) {
164 self.change(|b| {
165 b.batch.clear();
166 b.begin("idle");
167 });
168 }
169}
170
171impl gate::Watch for GateBoard {
172 fn started(&self, cmd: &str) {
173 self.change(|b| b.running.push((cmd.to_string(), UtcTime::now().format())));
174 }
175
176 fn ended(&self, cmd: &str) {
177 self.change(|b| {
178 if let Some(at) = b.running.iter().position(|(c, _)| c == cmd) {
179 b.running.remove(at);
180 }
181 if let Some((total, done)) = &mut b.count
185 && done.len() < *total
186 {
187 done.insert(cmd.to_string());
188 }
189 });
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196 use crate::gate::Watch;
197
198 fn read(path: &std::path::Path) -> serde_json::Value {
199 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
200 }
201
202 fn running(v: &serde_json::Value) -> Vec<String> {
203 v["running"]
204 .as_array()
205 .unwrap()
206 .iter()
207 .map(|r| r["command"].as_str().unwrap().to_string())
208 .collect()
209 }
210
211 #[test]
212 fn the_file_follows_each_change() {
213 let dir = tempfile::tempdir().unwrap();
214 let path = dir.path().join("gate.json");
215 let board = GateBoard::to(path.clone());
216
217 board.batch(vec!["U-002".into(), "U-005".into()]);
218 board.step("rows");
219 let v = read(&path);
220 assert_eq!(v["step"], "rows");
221 assert_eq!(v["batch"], serde_json::json!(["U-002", "U-005"]));
222 assert_eq!(v["running"], serde_json::json!([]));
223 assert!(v["done"].is_null() && v["total"].is_null());
224 assert!(UtcTime::parse(v["since"].as_str().unwrap()).is_some());
225
226 board.rows(2);
227 board.started("a");
228 board.started("b");
229 let v = read(&path);
230 assert_eq!(
231 (v["done"].as_i64(), v["total"].as_i64()),
232 (Some(0), Some(2))
233 );
234 assert_eq!(running(&v), ["a", "b"]);
235 assert!(UtcTime::parse(v["running"][0]["since"].as_str().unwrap()).is_some());
236
237 board.ended("a");
238 board.started("a"); board.ended("a");
240 let v = read(&path);
241 assert_eq!(v["done"], 1);
242 assert_eq!(running(&v), ["b"]);
243
244 board.ended("b");
246 board.started("make test");
247 board.ended("make test");
248 let v = read(&path);
249 assert_eq!(
250 (v["done"].as_i64(), v["total"].as_i64()),
251 (Some(2), Some(2))
252 );
253
254 board.step("lint");
255 let v = read(&path);
256 assert_eq!(v["running"], serde_json::json!([]));
257 assert!(v["done"].is_null() && v["total"].is_null());
258 assert_eq!(v["batch"], serde_json::json!(["U-002", "U-005"]));
259
260 board.idle();
261 let v = read(&path);
262 assert_eq!(v["step"], "idle");
263 assert_eq!(v["batch"], serde_json::json!([]));
264
265 let text = std::fs::read_to_string(&path).unwrap();
267 let at = |k: &str| text.find(&format!("\"{k}\"")).unwrap();
268 assert!(at("step") < at("since") && at("since") < at("batch"));
269 assert!(at("batch") < at("running") && at("running") < at("done"));
270 assert!(at("done") < at("total"));
271 assert!(!dir.path().join("gate.json.tmp").exists());
272 }
273
274 #[test]
275 fn commands_started_at_once_from_many_threads_are_all_running() {
276 let dir = tempfile::tempdir().unwrap();
277 let path = dir.path().join("gate.json");
278 let board = GateBoard::to(path.clone());
279 board.step("rows");
280 std::thread::scope(|s| {
281 for t in 0..8 {
282 let board = board.clone();
283 s.spawn(move || {
284 for k in 0..10 {
285 board.started(&format!("cmd {t}-{k}"));
286 }
287 });
288 }
289 });
290 let mut got = running(&read(&path));
291 got.sort();
292 let mut want: Vec<String> = (0..8)
293 .flat_map(|t| (0..10).map(move |k| format!("cmd {t}-{k}")))
294 .collect();
295 want.sort();
296 assert_eq!(got, want);
297 }
298
299 #[test]
300 fn each_step_but_idle_is_a_gate_event() {
301 let dir = tempfile::tempdir().unwrap();
302 let board =
303 GateBoard::to(dir.path().join("gate.json")).with_events(EventLog::open(dir.path()));
304 board.batch(vec!["U-002".into(), "U-005".into()]);
305 board.step("rows");
306 board.idle();
307 board.step("head-check");
308 let text = std::fs::read_to_string(dir.path().join("events.jsonl")).unwrap();
309 let events: Vec<RunEvent> = text
310 .lines()
311 .map(|l| RunEvent::from_json(&serde_json::from_str(l).unwrap()).unwrap())
312 .collect();
313 assert_eq!(events.len(), 2);
314 assert_eq!(events[0].kind, "gate");
315 assert_eq!(events[0].detail, "rows · U-002, U-005");
316 assert_eq!(events[0].field("step"), Some(&J::s("rows")));
317 assert_eq!(
318 events[0].field("batch"),
319 Some(&J::Arr(vec![J::s("U-002"), J::s("U-005")]))
320 );
321 assert_eq!(events[1].detail, "head-check");
322 assert_eq!(events[1].field("batch"), Some(&J::Arr(vec![])));
323 }
324}