Skip to main content

subspace_core/log/
sink.rs

1//! Where records go: the ring buffer the viewer reads, and the bounded run-day
2//! JSON Lines file once [`init`] has opened one.
3
4use std::collections::VecDeque;
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicU8, Ordering};
7use std::sync::{Mutex, OnceLock};
8
9use chrono::Utc;
10
11use crate::run_day_log::{Limits, RunDayLog};
12
13use super::{BUFFER_RECORDS, LEVEL_ENV, Level, Record};
14
15/// The default size a log file grows to before it rotates (5 MiB).
16pub const DEFAULT_MAX_FILE_BYTES: u64 = 5 * 1024 * 1024;
17/// How many local dates with writes are kept, including the active date.
18pub const DEFAULT_MAX_FILES: usize = 5;
19
20/// Where and how much to log.
21#[derive(Debug, Clone)]
22pub struct Config {
23    pub directory: PathBuf,
24    /// `subspace` gives `subspace.log` and `subspace.log.YYYY-MM-DD`.
25    pub file_stem: String,
26    pub level: Level,
27    pub max_file_bytes: u64,
28    pub max_files: usize,
29}
30
31impl Config {
32    pub fn new(directory: PathBuf, file_stem: impl Into<String>, level: Level) -> Self {
33        Self {
34            directory,
35            file_stem: file_stem.into(),
36            level,
37            max_file_bytes: DEFAULT_MAX_FILE_BYTES,
38            max_files: DEFAULT_MAX_FILES,
39        }
40    }
41}
42
43struct Writer {
44    config: Config,
45    log: RunDayLog,
46}
47
48#[derive(Default)]
49struct Sink {
50    next_seq: u64,
51    buffer: VecDeque<Record>,
52    writer: Option<Writer>,
53}
54
55static SINK: OnceLock<Mutex<Sink>> = OnceLock::new();
56/// The level as a `u8` index into [`Level::ALL`], read on every call.
57static LEVEL: AtomicU8 = AtomicU8::new(2);
58
59fn sink() -> &'static Mutex<Sink> {
60    SINK.get_or_init(Mutex::default)
61}
62
63/// The level records must reach to be kept.
64pub fn level() -> Level {
65    let index = usize::from(LEVEL.load(Ordering::Relaxed));
66    Level::ALL.get(index).copied().unwrap_or(Level::Info)
67}
68
69pub fn set_level(level: Level) {
70    LEVEL.store(level.index() as u8, Ordering::Relaxed);
71}
72
73/// Opens the log file and starts writing records to it. `SUBSPACE_LOG` in
74/// the environment overrides `config.level`.
75pub fn init(config: Config) -> Result<(), String> {
76    let level = std::env::var(LEVEL_ENV)
77        .ok()
78        .and_then(|value| Level::parse(&value))
79        .unwrap_or(config.level);
80    set_level(level);
81    let path = live_path(&config);
82    let log = RunDayLog::open(&path, Limits::new(config.max_file_bytes, config.max_files))
83        .map_err(|error| open_error(&path, &error))?;
84    let mut sink = sink()
85        .lock()
86        .map_err(|_| "the log sink is poisoned".to_owned())?;
87    sink.writer = Some(Writer { config, log });
88    Ok(())
89}
90
91fn open_error(path: &Path, error: &std::io::Error) -> String {
92    format!("Cannot open the log file {}: {error}", path.display())
93}
94
95/// The directory the log file is in, once [`init`] ran.
96pub fn directory() -> Option<PathBuf> {
97    let sink = sink().lock().ok()?;
98    Some(sink.writer.as_ref()?.config.directory.clone())
99}
100
101/// The actual live path of the installed file writer, not a default location.
102pub fn path() -> Option<PathBuf> {
103    let sink = sink().lock().ok()?;
104    Some(sink.writer.as_ref()?.log.live_path().to_path_buf())
105}
106
107/// The buffered records, oldest first.
108pub fn recent() -> Vec<Record> {
109    sink()
110        .lock()
111        .map(|sink| sink.buffer.iter().cloned().collect())
112        .unwrap_or_default()
113}
114
115/// The buffered records after sequence `seq`, oldest first.
116pub fn recent_after(seq: u64) -> Vec<Record> {
117    sink()
118        .lock()
119        .map(|sink| {
120            sink.buffer
121                .iter()
122                .filter(|record| record.seq > seq)
123                .cloned()
124                .collect()
125        })
126        .unwrap_or_default()
127}
128
129pub(super) fn emit(level: Level, target: String, message: String, fields: Vec<(String, String)>) {
130    let Ok(mut sink) = sink().lock() else {
131        return;
132    };
133    sink.next_seq += 1;
134    let record = Record {
135        seq: sink.next_seq,
136        at: Utc::now(),
137        level,
138        target,
139        message,
140        fields,
141    };
142    if let Some(writer) = sink.writer.as_mut() {
143        write(writer, &record);
144    }
145    sink.buffer.push_back(record);
146    while sink.buffer.len() > BUFFER_RECORDS {
147        sink.buffer.pop_front();
148    }
149}
150
151/// One JSON line, rolling over first when the date's chunk is full. A write that fails
152/// is dropped: logging must never take the app down.
153fn write(writer: &mut Writer, record: &Record) {
154    let Ok(mut line) = serde_json::to_string(record) else {
155        return;
156    };
157    line.push('\n');
158    _ = writer.log.append(line.as_bytes());
159}
160
161fn live_path(config: &Config) -> PathBuf {
162    config.directory.join(format!("{}.log", config.file_stem))
163}
164
165#[cfg(test)]
166mod tests {
167    use std::fs;
168
169    use super::{Config, Writer, live_path, write};
170    use crate::log::{Level, Record};
171    use crate::run_day_log::{Limits, RunDayLog};
172
173    fn record(seq: u64, message: &str) -> Record {
174        Record {
175            seq,
176            at: chrono::Utc::now(),
177            level: Level::Info,
178            target: "test".into(),
179            message: message.into(),
180            fields: Vec::new(),
181        }
182    }
183
184    #[test]
185    fn a_full_file_rolls_over_without_numbered_archives() {
186        let dir = tempfile::tempdir().unwrap();
187        let config = Config {
188            max_file_bytes: 150,
189            max_files: 2,
190            ..Config::new(dir.path().to_owned(), "app", Level::Info)
191        };
192        let mut writer = Writer {
193            config: config.clone(),
194            log: RunDayLog::open(&live_path(&config), Limits::new(150, 2)).unwrap(),
195        };
196        for seq in 1..=12 {
197            write(&mut writer, &record(seq, "a message that is long enough"));
198        }
199        assert!(live_path(&config).exists());
200        assert!(!dir.path().join("app.log.1").exists());
201        let live = fs::read_to_string(live_path(&config)).unwrap();
202        assert!(live.len() <= 150, "the live file stays under the limit");
203        let last = live.lines().last().unwrap();
204        let parsed: Record = serde_json::from_str(last).unwrap();
205        assert_eq!(parsed.seq, 12);
206    }
207
208    #[test]
209    fn an_oversized_record_does_not_exceed_the_disk_limit() {
210        let dir = tempfile::tempdir().unwrap();
211        let config = Config {
212            max_file_bytes: 150,
213            ..Config::new(dir.path().to_owned(), "app", Level::Info)
214        };
215        let mut writer = Writer {
216            config: config.clone(),
217            log: RunDayLog::open(&live_path(&config), Limits::new(150, 5)).unwrap(),
218        };
219        write(&mut writer, &record(1, &"x".repeat(200)));
220        assert_eq!(fs::metadata(live_path(&config)).unwrap().len(), 0);
221    }
222
223    #[test]
224    fn path_reports_the_installed_writer_and_disk_failures_leave_the_ring_working() {
225        let dir = tempfile::tempdir().unwrap();
226        let config = Config::new(dir.path().to_owned(), "selected-product", Level::Info);
227        let actual = live_path(&config);
228        let log = RunDayLog::open(&actual, Limits::new(1, 5)).unwrap();
229        let previous = super::sink()
230            .lock()
231            .unwrap()
232            .writer
233            .replace(Writer { config, log });
234        assert_eq!(super::path(), Some(actual.clone()));
235        super::emit(
236            Level::Info,
237            "disk-failure-fixture".into(),
238            "retained in memory".into(),
239            Vec::new(),
240        );
241        assert!(
242            super::recent()
243                .iter()
244                .any(|record| record.target == "disk-failure-fixture")
245        );
246        assert_eq!(fs::metadata(&actual).unwrap().len(), 0);
247        super::sink().lock().unwrap().writer = None;
248        assert_eq!(super::path(), None);
249        super::sink().lock().unwrap().writer = previous;
250    }
251
252    #[test]
253    fn the_level_round_trips_through_the_atomic() {
254        super::set_level(Level::Trace);
255        assert_eq!(super::level(), Level::Trace);
256        super::set_level(Level::Info);
257        assert_eq!(super::level(), Level::Info);
258    }
259}