Cotton code
357 lines · 12.3 KB · RustRaw
//! The log the window shows: a bounded ring of the newest lines — and the file//! it is appended to, so the log outlives the process that wrote it.//!//! Every line goes to three places, and each answers a different question://!//! * **the event stream** (`EventKind::Log`), as it arrives — what is being//!   said NOW, so nothing polls;//! * **the ring** — what was said before anyone was looking, for a window that//!   has just opened;//! * **`<dataDir>/server.log`** — what was said on a run that has already//!   ended, read from a terminal by someone the app is not in front of.//!//! The file is the one added last, and it was a hole for a while. The Node era//! wrote `server.log` from `main/logging.ts`; that app was deleted in #395 and//! nothing in the Rust tree took the write over, so the path went on being//! ADVERTISED by `datadir.status` while the last line in it aged. Everything//! the embedded server said after that lived in this ring alone — two hundred//! lines, in memory, with no reader in the window and none outside it.use std::collections::VecDeque;use std::io::Write;use std::path::{Path, PathBuf};use std::sync::Mutex;use serde::Serialize;/// 500, so a phone report (`shell::report`) carries the last 500 lines.pub const LOG_RING_SIZE: usize = 500;/// How big `server.log` may get before the current file becomes `server.log.1`.////// One rollover, not a fleet of them. Every HTTP request is a line here, so a/// Mac serving a phone all day writes steadily, and nothing prunes a file in/// someone's home directory. Two files bound the whole thing at twice this and/// still keep more history than anyone reads.pub const LOG_FILE_MAX_BYTES: u64 = 8 * 1024 * 1024;#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "lowercase")]pub enum LogLevel {    Info,    Warn,    Error,}#[derive(Debug, Clone, PartialEq, Eq, Serialize)]#[serde(rename_all = "camelCase")]pub struct LogLine {    /// ISO-8601 UTC.    pub at: String,    pub level: LogLevel,    /// Where it came from: `server`, `request`, `client`, `ingest`…    pub source: String,    pub text: String,}#[derive(Debug)]pub struct LogRing {    size: usize,    lines: Mutex<VecDeque<LogLine>>,    /// Where the same lines are APPENDED. `None` is the pure ring a test holds.    file: Option<PathBuf>,}impl LogRing {    /// The ring alone — nothing on disk. What the tests of everything ELSE use.    pub fn new(size: usize) -> LogRing {        LogRing {            size,            lines: Mutex::new(VecDeque::with_capacity(size.min(1024))),            file: None,        }    }    /// The ring, and every line appended to `path` as well.    ///    /// `path` is `Layout::server_log()` and nothing else: the data directory is    /// the one place an operator already knows to look, and `datadir.status`    /// has been naming that file all along.    pub fn to_file(size: usize, path: impl Into<PathBuf>) -> LogRing {        LogRing {            file: Some(path.into()),            ..LogRing::new(size)        }    }    pub fn push(&self, line: LogLine) {        if let Some(path) = &self.file {            // A BAND-AID, AND HERE IS THE WHY. This write is allowed to fail            // silently, deliberately. A log cannot report its own failure to            // write through itself without recursing, and a full disk or a data            // directory someone moved out from under the process must not take            // the server down; the ring and the event stream still carry every            // line, so nothing is LOST, only undurable. A reader who finds the            // file stale checks that the directory is writable.            let _ = append(path, &line);        }        let mut lines = self.lock();        lines.push_back(line);        while lines.len() > self.size {            lines.pop_front();        }    }    /// Oldest first — a reader reverses for display.    pub fn lines(&self) -> Vec<LogLine> {        self.lock().iter().cloned().collect()    }    fn lock(&self) -> std::sync::MutexGuard<'_, VecDeque<LogLine>> {        self.lines            .lock()            .unwrap_or_else(|poisoned| poisoned.into_inner())    }}impl Default for LogRing {    fn default() -> Self {        LogRing::new(LOG_RING_SIZE)    }}/// One line, as `server.log` holds it: the timestamp the line already carries,/// its grade, where it came from, and what it said —/// `2026-09-10T04:06:03.512Z info server listening on 8790`.////// Plain text on purpose: what reads this file is a person with `tail` and/// `grep`, and the runbooks grep it by word.pub fn file_line(line: &LogLine) -> String {    let level = match line.level {        LogLevel::Info => "info",        LogLevel::Warn => "warn",        LogLevel::Error => "error",    };    format!("{} {level} {} {}", line.at, line.source, line.text)}/// Append one line, rolling the file over first if it has grown past the cap.fn append(path: &Path, line: &LogLine) -> std::io::Result<()> {    // A rename, never a truncate: a reader with the file open keeps reading the    // one it opened, and the previous run's tail stays readable as `.1`.    if std::fs::metadata(path).is_ok_and(|meta| meta.len() >= LOG_FILE_MAX_BYTES) {        // not a copy: the log ring.        std::fs::rename(path, rolled(path))?;    }    let mut file = std::fs::OpenOptions::new()        .create(true)        .append(true)        .open(path)?;    writeln!(file, "{}", file_line(line))}/// `…/server.log` → `…/server.log.1`.fn rolled(path: &Path) -> PathBuf {    let mut name = path.as_os_str().to_os_string();    name.push(".1");    PathBuf::from(name)}/// The request stream, as a line: `GET /v1/sync/pull 200 12ms`.pub fn format_request(method: &str, path: &str, status: u16, ms: u64) -> String {    format!("{method} {path} {status} {ms}ms")}/// A refused request names who asked and why after the plain line:/// `POST /v1/sync/exchange 400 0ms — device d1 app 0.29.15 (90) — bad_request: ops must be an array`.pub fn format_refused(base: String, caller: Option<&str>, code: Option<&str>, message: Option<&str>) -> String {    let mut line = base;    line.push_str(" — ");    line.push_str(caller.unwrap_or("an unsigned caller"));    if let Some(code) = code {        line.push_str(" — ");        line.push_str(code);        if let Some(message) = message.filter(|message| !message.is_empty()) {            line.push_str(": ");            line.push_str(message);        }    }    line}/// A request's own grade. A 4xx is the caller's problem and a 5xx is this/// server's, which is exactly how loudly each should read.pub fn level_for_status(status: u16) -> LogLevel {    if status >= 500 {        LogLevel::Error    } else if status >= 400 {        LogLevel::Warn    } else {        LogLevel::Info    }}/// One line into the ring AND out on the event stream. Both, always: the ring/// answers "what was said before I looked", the stream answers "what is being/// said now", and a line in one but not the other is a log that disagrees with/// itself.pub(crate) fn push_line(    log: &LogRing,    events: &crate::events::EventBus,    level: LogLevel,    source: &str,    text: &str,) {    let line = LogLine {        at: now_iso(),        level,        source: source.to_string(),        text: text.to_string(),    };    log.push(line.clone());    events.emit(        crate::events::EventKind::Log,        serde_json::to_value(&line).unwrap_or(serde_json::Value::Null),    );}fn now_iso() -> String {    chrono::Utc::now()        .to_rfc3339_opts(chrono::SecondsFormat::Millis, true)        .to_string()}#[cfg(test)]mod tests {    use super::*;    fn line(n: usize) -> LogLine {        LogLine {            at: format!("2026-09-08T00:00:{n:02}.000Z"),            level: LogLevel::Info,            source: "server".to_string(),            text: format!("l{n}"),        }    }    #[test]    fn it_keeps_only_the_newest_lines_oldest_first() {        let ring = LogRing::new(3);        for n in 0..5 {            ring.push(line(n));        }        assert_eq!(            ring.lines()                .iter()                .map(|l| l.text.clone())                .collect::<Vec<_>>(),            vec!["l2".to_string(), "l3".to_string(), "l4".to_string()]        );    }    #[test]    fn a_refused_line_says_who_asked_and_why() {        assert_eq!(            format_refused(format_request("POST", "/v1/sync/exchange", 400, 0), Some("device d1 app 0.29.15 (90)"), Some("bad_request"), Some("ops must be an array")),            "POST /v1/sync/exchange 400 0ms — device d1 app 0.29.15 (90) — bad_request: ops must be an array"        );        assert_eq!(            format_refused(format_request("GET", "/x", 404, 1), None, None, None),            "GET /x 404 1ms — an unsigned caller"        );    }    #[test]    fn an_empty_ring_is_an_empty_answer_never_a_missing_one() {        assert!(LogRing::default().lines().is_empty());    }    #[test]    fn it_writes_a_request_as_method_path_status_ms_and_grades_by_status() {        assert_eq!(            format_request("GET", "/v1/sync/pull", 200, 12),            "GET /v1/sync/pull 200 12ms"        );        assert_eq!(level_for_status(200), LogLevel::Info);        assert_eq!(level_for_status(404), LogLevel::Warn);        assert_eq!(level_for_status(500), LogLevel::Error);    }    // ── `server.log` ──────────────────────────────────────────────────────    #[test]    fn a_ring_with_no_file_writes_nothing_to_disk() {        let dir = tempfile::tempdir().expect("a temp dir");        let path = dir.path().join("server.log");        let ring = LogRing::new(3);        ring.push(line(1));        assert!(!path.exists(), "the pure ring must not invent a file");    }    #[test]    fn every_line_is_appended_to_the_file_as_well_as_kept_in_the_ring() {        let dir = tempfile::tempdir().expect("a temp dir");        let path = dir.path().join("server.log");        let ring = LogRing::to_file(2, &path);        for n in 0..3 {            ring.push(line(n));        }        // The ring dropped the oldest; the FILE is the one that did not.        assert_eq!(ring.lines().len(), 2);        let written = std::fs::read_to_string(&path).expect("the log file");        assert_eq!(            written.lines().collect::<Vec<_>>(),            vec![                "2026-09-08T00:00:00.000Z info server l0",                "2026-09-08T00:00:01.000Z info server l1",                "2026-09-08T00:00:02.000Z info server l2",            ]        );    }    #[test]    fn a_line_carries_its_grade_so_a_reader_can_grep_for_the_loud_ones() {        let mut warned = line(7);        warned.level = LogLevel::Warn;        warned.source = "request".to_string();        warned.text = "GET /v1/sync/pull 404 3ms".to_string();        assert_eq!(            file_line(&warned),            "2026-09-08T00:00:07.000Z warn request GET /v1/sync/pull 404 3ms"        );    }    #[test]    fn the_file_rolls_over_once_it_passes_the_cap_and_the_old_one_is_kept() {        let dir = tempfile::tempdir().expect("a temp dir");        let path = dir.path().join("server.log");        std::fs::write(&path, vec![b'x'; LOG_FILE_MAX_BYTES as usize]).expect("a full log");        let ring = LogRing::to_file(3, &path);        ring.push(line(4));        assert_eq!(            std::fs::read_to_string(&path).expect("the new log file"),            "2026-09-08T00:00:04.000Z info server l4\n",            "the new file holds only what was written after the rollover"        );        assert_eq!(            std::fs::metadata(dir.path().join("server.log.1"))                .expect("the rolled file")                .len(),            LOG_FILE_MAX_BYTES,            "and the previous run's lines are still on disk beside it"        );    }    #[test]    fn a_file_that_cannot_be_written_never_costs_the_ring_a_line() {        // A data directory that is not there — the shape of a disk that filled        // or a folder someone moved while the server was up.        let ring = LogRing::to_file(3, "/nonexistent-cottondb-dir/server.log");        ring.push(line(1));        assert_eq!(ring.lines().len(), 1);    }}