use std::collections::{BTreeMap, VecDeque};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum OutputLevel {
Trace,
Debug,
Info,
Warn,
Error,
}
impl OutputLevel {
pub fn label(self) -> &'static str {
match self {
Self::Trace => "trace",
Self::Debug => "debug",
Self::Info => "info",
Self::Warn => "warn",
Self::Error => "error",
}
}
}
pub const CHANNEL_DAP: &str = "Debug Adapter";
pub const CHANNEL_GIT: &str = "Git";
pub const CHANNEL_PROVISION: &str = "Server Provisioning";
pub const CHANNEL_TESTS: &str = "Test Runner";
pub const CHANNEL_MESSAGES: &str = "Messages";
pub const CHANNEL_FLEET: &str = "Fleet";
pub const CHANNEL_REMOTE: &str = "Remote";
pub const CHANNEL_NOTIFICATIONS: &str = "Notifications";
pub const CHANNEL_DEBUG_CONSOLE: &str = "Debug Console";
#[derive(Clone, Debug, PartialEq)]
pub struct OutputLine {
pub ts: f64,
pub level: OutputLevel,
pub text: String,
}
pub const MAX_LINES: usize = 5000;
const MAX_LINE_BYTES: usize = 16 * 1024;
fn capped_line(text: &str) -> String {
if text.len() <= MAX_LINE_BYTES {
return text.to_string();
}
let mut end = MAX_LINE_BYTES;
while !text.is_char_boundary(end) {
end -= 1;
}
format!("{}… ({} more bytes)", &text[..end], text.len() - end)
}
#[derive(Default)]
struct Channel {
lines: VecDeque<OutputLine>,
pushed: u64,
cleared: u64,
}
impl Channel {
fn mark(&self) -> ReadMark {
ReadMark {
cleared: self.cleared,
pushed: self.pushed,
}
}
}
struct Registry {
channels: BTreeMap<String, Channel>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ReadMark {
cleared: u64,
pushed: u64,
}
#[derive(Debug, PartialEq)]
pub enum Since {
Appended(Vec<OutputLine>),
Replaced(Vec<OutputLine>),
}
fn registry() -> &'static Mutex<Registry> {
static REG: OnceLock<Mutex<Registry>> = OnceLock::new();
REG.get_or_init(|| {
Mutex::new(Registry {
channels: BTreeMap::new(),
})
})
}
static GENERATION: AtomicU64 = AtomicU64::new(0);
static TRACE_ENABLED: AtomicBool = AtomicBool::new(false);
pub fn generation() -> u64 {
GENERATION.load(Ordering::Relaxed)
}
pub fn trace_enabled() -> bool {
TRACE_ENABLED.load(Ordering::Relaxed)
}
pub fn set_trace_enabled(on: bool) {
TRACE_ENABLED.store(on, Ordering::Relaxed);
}
fn now() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs_f64())
.unwrap_or(0.0)
}
pub fn push(channel: &str, level: OutputLevel, text: &str) {
let Ok(mut reg) = registry().lock() else {
return;
};
let ch = reg.channels.entry(channel.to_string()).or_default();
ch.lines.push_back(OutputLine {
ts: now(),
level,
text: capped_line(text),
});
ch.pushed += 1;
while ch.lines.len() > MAX_LINES {
ch.lines.pop_front();
}
GENERATION.fetch_add(1, Ordering::Relaxed);
}
pub fn channel_names() -> Vec<String> {
registry()
.lock()
.map(|r| r.channels.keys().cloned().collect())
.unwrap_or_default()
}
pub fn channel_sizes() -> Vec<(String, usize, usize)> {
registry()
.lock()
.map(|r| {
r.channels
.iter()
.map(|(name, ch)| {
let bytes = ch.lines.iter().map(|l| l.text.len()).sum();
(name.clone(), ch.lines.len(), bytes)
})
.collect()
})
.unwrap_or_default()
}
pub fn snapshot(channel: &str) -> Option<Vec<OutputLine>> {
let reg = registry().lock().ok()?;
reg.channels
.get(channel)
.map(|ch| ch.lines.iter().cloned().collect())
}
pub fn read_since(channel: &str, mark: Option<ReadMark>) -> Option<(ReadMark, Since)> {
let reg = registry().lock().ok()?;
let ch = reg.channels.get(channel)?;
let unseen = mark
.filter(|m| m.cleared == ch.cleared && m.pushed <= ch.pushed)
.map(|m| ch.pushed - m.pushed)
.and_then(|n| usize::try_from(n).ok())
.filter(|&n| n <= ch.lines.len());
let since = match unseen {
Some(n) => Since::Appended(ch.lines.range(ch.lines.len() - n..).cloned().collect()),
None => Since::Replaced(ch.lines.iter().cloned().collect()),
};
Some((ch.mark(), since))
}
pub fn clear(channel: &str) {
if let Ok(mut reg) = registry().lock()
&& let Some(ch) = reg.channels.get_mut(channel)
{
ch.lines.clear();
ch.pushed = 0;
ch.cleared += 1;
GENERATION.fetch_add(1, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_creates_a_channel_and_appends_in_order() {
let ch = "test-create-append";
push(ch, OutputLevel::Info, "first");
push(ch, OutputLevel::Error, "second");
let lines = snapshot(ch).expect("channel exists after push");
assert_eq!(lines.len(), 2);
assert_eq!(lines[0].text, "first");
assert_eq!(lines[1].text, "second");
assert_eq!(lines[1].level, OutputLevel::Error);
assert!(channel_names().iter().any(|c| c == ch));
}
#[test]
fn channel_sizes_count_lines_and_text_bytes() {
let ch = "test-channel-sizes";
push(ch, OutputLevel::Info, "abc");
push(ch, OutputLevel::Info, "de");
let sizes = channel_sizes();
let (_, lines, bytes) = sizes.iter().find(|(n, _, _)| n == ch).unwrap();
assert_eq!((*lines, *bytes), (2, 5));
}
#[test]
fn an_over_long_line_is_capped() {
let ch = "test-line-cap";
let body = format!(
"{}é{}",
"x".repeat(MAX_LINE_BYTES - 1),
"y".repeat(3 * 1024 * 1024)
);
push(ch, OutputLevel::Info, &body);
let line = &snapshot(ch).unwrap()[0].text;
assert!(
line.len() < MAX_LINE_BYTES + 64,
"{} bytes held",
line.len()
);
let dropped = body.len() - (MAX_LINE_BYTES - 1);
assert!(
line.ends_with(&format!("… ({dropped} more bytes)")),
"{}",
&line[line.len() - 40..]
);
assert!(line.starts_with(&"x".repeat(MAX_LINE_BYTES - 1)));
push(ch, OutputLevel::Info, "short");
assert_eq!(snapshot(ch).unwrap()[1].text, "short");
}
#[test]
fn push_bumps_the_generation() {
let before = generation();
push("test-generation", OutputLevel::Info, "x");
assert!(generation() > before, "a push must bump the generation");
}
#[test]
fn clear_empties_a_channel_but_keeps_it_listed() {
let ch = "test-clear";
push(ch, OutputLevel::Info, "a");
push(ch, OutputLevel::Info, "b");
clear(ch);
assert_eq!(snapshot(ch).map(|l| l.len()), Some(0));
assert!(
channel_names().iter().any(|c| c == ch),
"clear keeps the channel in the dropdown",
);
}
#[test]
fn levels_order_low_to_high_for_filtering() {
assert!(OutputLevel::Error > OutputLevel::Warn);
assert!(OutputLevel::Warn > OutputLevel::Info);
assert!(OutputLevel::Info > OutputLevel::Debug);
assert!(OutputLevel::Debug > OutputLevel::Trace);
}
#[test]
fn trace_toggle_round_trips() {
set_trace_enabled(true);
assert!(trace_enabled());
set_trace_enabled(false);
assert!(!trace_enabled());
}
fn texts(lines: &[OutputLine]) -> Vec<&str> {
lines.iter().map(|l| l.text.as_str()).collect()
}
#[test]
fn read_since_hands_a_reader_only_the_lines_it_has_not_seen() {
let ch = "test-read-since-appends";
push(ch, OutputLevel::Info, "one");
push(ch, OutputLevel::Info, "two");
let (mark, first) = read_since(ch, None).expect("channel exists");
assert_eq!(
first,
Since::Replaced(snapshot(ch).unwrap()),
"a reader with no mark takes every line"
);
let (same, nothing) = read_since(ch, Some(mark)).unwrap();
assert_eq!((same, nothing), (mark, Since::Appended(Vec::new())));
push(ch, OutputLevel::Warn, "three");
let (_, more) = read_since(ch, Some(mark)).unwrap();
let Since::Appended(lines) = more else {
panic!("a push since the mark is an append: {more:?}");
};
assert_eq!(texts(&lines), ["three"]);
assert!(read_since("test-read-since-no-such-channel", None).is_none());
}
#[test]
fn read_since_replaces_after_a_clear_even_when_the_counts_line_up() {
let ch = "test-read-since-clear";
push(ch, OutputLevel::Info, "old");
let (mark, _) = read_since(ch, None).unwrap();
clear(ch);
push(ch, OutputLevel::Info, "new");
let (_, after) = read_since(ch, Some(mark)).unwrap();
let Since::Replaced(lines) = after else {
panic!("a clear since the mark replaces: {after:?}");
};
assert_eq!(texts(&lines), ["new"]);
}
#[test]
fn read_since_replaces_once_a_reader_falls_further_behind_than_the_cap() {
let ch = "test-read-since-behind";
push(ch, OutputLevel::Info, "first");
let (mark, _) = read_since(ch, None).unwrap();
for i in 0..MAX_LINES + 1 {
push(ch, OutputLevel::Info, &format!("line {i}"));
}
let (_, after) = read_since(ch, Some(mark)).unwrap();
let Since::Replaced(lines) = after else {
panic!("more unseen lines than the channel keeps replaces: {after:?}");
};
assert_eq!(lines.len(), MAX_LINES);
assert_eq!(lines.last().unwrap().text, format!("line {MAX_LINES}"));
}
#[test]
fn a_reader_that_applies_each_answer_holds_the_channels_lines() {
let ch = "test-read-since-mirror";
let mut mine: Vec<OutputLine> = Vec::new();
let mut mark = None;
let mut step = |mine: &mut Vec<OutputLine>| {
let (m, since) = read_since(ch, mark).unwrap();
mark = Some(m);
match since {
Since::Appended(new) => mine.extend(new),
Since::Replaced(all) => *mine = all,
}
let over = mine.len().saturating_sub(MAX_LINES);
mine.drain(..over);
};
push(ch, OutputLevel::Info, "a");
step(&mut mine);
for i in 0..MAX_LINES + 7 {
push(ch, OutputLevel::Info, &format!("n{i}"));
if i % 1000 == 0 {
step(&mut mine);
}
}
step(&mut mine);
assert_eq!(mine, snapshot(ch).unwrap());
clear(ch);
push(ch, OutputLevel::Error, "z");
step(&mut mine);
assert_eq!(mine, snapshot(ch).unwrap());
}
}