Skip to main content

yscv_cli/
event_log.rs

1use std::fs;
2use std::io::{BufWriter, Write};
3use std::path::{Path, PathBuf};
4
5use crate::error::AppError;
6use crate::util::ensure_parent_dir;
7
8#[derive(Debug)]
9pub struct JsonlEventWriter {
10    path: PathBuf,
11    sink: BufWriter<fs::File>,
12}
13
14impl JsonlEventWriter {
15    pub fn create(path: &Path) -> Result<Self, AppError> {
16        ensure_parent_dir(path)?;
17        let file = fs::File::create(path)?;
18        Ok(Self {
19            path: path.to_path_buf(),
20            sink: BufWriter::new(file),
21        })
22    }
23
24    pub fn write_record(&mut self, value: &serde_json::Value) -> Result<(), AppError> {
25        serde_json::to_writer(&mut self.sink, value)?;
26        self.sink.write_all(b"\n")?;
27        Ok(())
28    }
29
30    pub fn flush(&mut self) -> Result<(), std::io::Error> {
31        self.sink.flush()
32    }
33
34    pub fn path(&self) -> &Path {
35        &self.path
36    }
37}