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