use std::collections::{HashMap, VecDeque}; use std::sync::{Mutex, MutexGuard}; use forge_ci::proto::{RUNNER_LOG_MAX_TEXT, RunnerLogBatch, truncate_text}; const MAX_LINES: usize = 2000; const MAX_BATCH_LINES: usize = 1000; const LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"]; #[derive(Clone, Debug, PartialEq, Eq)] pub struct Line { pub at_ms: i64, pub level: String, pub text: String, pub from_forge: bool, } #[derive(Debug, Default)] struct PerRunner { boot_id: String, next_seq: u64, lines: VecDeque, last_note: Option, } #[derive(Debug, Default)] pub struct RunnerLogs { runners: Mutex>, } impl RunnerLogs { pub fn ingest(&self, runner_id: &str, batch: &RunnerLogBatch) -> u64 { let mut runners = self.lock(); let entry = runners.entry(runner_id.to_owned()).or_default(); if entry.boot_id != batch.boot_id { entry.boot_id = batch.boot_id.clone(); entry.next_seq = 0; let short: String = batch.boot_id.chars().take(8).collect(); push(entry, forge_line(format!("runner started (boot {short})"))); } if batch.first_seq > entry.next_seq { let missing = batch.first_seq - entry.next_seq; push(entry, forge_line(format!("{missing} lines missing"))); } for (i, line) in batch.lines.iter().take(MAX_BATCH_LINES).enumerate() { let seq = batch.first_seq.saturating_add(i as u64); if seq < entry.next_seq { continue; } push( entry, Line { at_ms: line.at_ms, level: level_of(&line.level), text: truncate_text(&line.text, RUNNER_LOG_MAX_TEXT).to_owned(), from_forge: false, }, ); } let taken = batch.lines.len().min(MAX_BATCH_LINES) as u64; entry.next_seq = entry.next_seq.max(batch.first_seq.saturating_add(taken)); entry.next_seq } pub fn note(&self, runner_id: &str, text: &str) -> bool { let mut runners = self.lock(); let entry = runners.entry(runner_id.to_owned()).or_default(); if entry.last_note.as_deref() == Some(text) { return false; } entry.last_note = Some(text.to_owned()); push(entry, forge_line(text.to_owned())); true } pub fn clear_note(&self, runner_id: &str) { if let Some(entry) = self.lock().get_mut(runner_id) { entry.last_note = None; } } pub fn lines(&self, runner_id: &str) -> Vec { self.lock() .get(runner_id) .map(|entry| entry.lines.iter().cloned().collect()) .unwrap_or_default() } fn lock(&self) -> MutexGuard<'_, HashMap> { self.runners.lock().unwrap_or_else(|e| e.into_inner()) } } fn push(entry: &mut PerRunner, line: Line) { entry.lines.push_back(line); while entry.lines.len() > MAX_LINES { entry.lines.pop_front(); } } fn forge_line(text: String) -> Line { let at_ms = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)); Line { at_ms, level: "info".to_owned(), text, from_forge: true, } } fn level_of(level: &str) -> String { if LEVELS.contains(&level) { level.to_owned() } else { "info".to_owned() } } #[cfg(test)] mod tests { use super::*; use forge_ci::proto::RunnerLogLine; fn batch(boot: &str, first_seq: u64, texts: &[&str]) -> RunnerLogBatch { RunnerLogBatch { boot_id: boot.to_owned(), first_seq, lines: texts .iter() .map(|t| RunnerLogLine { at_ms: 1, level: "info".to_owned(), text: (*t).to_owned(), }) .collect(), } } #[test] fn ingest_skips_what_is_known_and_marks_gaps() { let logs = RunnerLogs::default(); assert_eq!( logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b"])), 2 ); assert_eq!( logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b", "c"])), 3 ); assert_eq!(logs.ingest("r1", &batch("bootaaaaaaaaaa", 5, &["f"])), 6); let texts: Vec = logs.lines("r1").into_iter().map(|l| l.text).collect(); assert_eq!( texts, [ "runner started (boot bootaaaa)", "a", "b", "c", "2 lines missing", "f" ] ); } #[test] fn note_is_written_once_until_cleared() { let logs = RunnerLogs::default(); assert!(logs.note("r1", "a restart is pending")); assert!(!logs.note("r1", "a restart is pending")); logs.clear_note("r1"); assert!(logs.note("r1", "a restart is pending")); let lines = logs.lines("r1"); assert_eq!(lines.len(), 2); assert!(lines.iter().all(|l| l.from_forge)); } }