Skip to main content

kumo_jsonl/
writer.rs

1use crate::registry::WriterRegistration;
2use camino::Utf8PathBuf;
3use chrono::Utc;
4use chrono_tz::Tz;
5use kumo_chrono_helper::{DateTime, Instant};
6use serde::{Deserialize, Serialize};
7use std::io::Write;
8use std::time::Duration;
9use zstd::stream::write::Encoder;
10
11/// Configuration for constructing a [`LogWriter`].
12#[derive(Deserialize, Serialize)]
13pub struct LogWriterConfig {
14    /// Directory where log segment files will be created.
15    pub log_dir: Utf8PathBuf,
16    /// Maximum number of uncompressed bytes written per segment
17    /// before rolling to a new file.
18    #[serde(default = "default_max_file_size")]
19    pub max_file_size: u64,
20    /// Zstd compression level.
21    #[serde(default = "default_compression_level")]
22    pub compression_level: i32,
23    /// The largest a record and its newline separator may be, in bytes. A
24    /// record that does not fit within it is rejected with an error. Defaults
25    /// to [`DEFAULT_MAX_LINE_SIZE`](crate::DEFAULT_MAX_LINE_SIZE).
26    #[serde(default = "default_max_record_size")]
27    pub max_record_size: usize,
28    /// If set, the segment will be closed after this duration
29    /// even if max_file_size has not been reached.
30    #[serde(
31        default,
32        with = "duration_serde",
33        skip_serializing_if = "Option::is_none"
34    )]
35    pub max_segment_duration: Option<Duration>,
36    /// Optional suffix appended to segment file names.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub suffix: Option<String>,
39    /// Timezone used when computing the segment file name.
40    /// Defaults to UTC.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub tz: Option<Tz>,
43}
44
45fn default_max_file_size() -> u64 {
46    128 * 1024 * 1024
47}
48
49fn default_compression_level() -> i32 {
50    3
51}
52
53fn default_max_record_size() -> usize {
54    crate::decompress::DEFAULT_MAX_LINE_SIZE
55}
56
57impl LogWriterConfig {
58    pub fn new(log_dir: Utf8PathBuf) -> Self {
59        Self {
60            log_dir,
61            max_file_size: default_max_file_size(),
62            compression_level: default_compression_level(),
63            max_record_size: default_max_record_size(),
64            max_segment_duration: None,
65            suffix: None,
66            tz: None,
67        }
68    }
69
70    pub fn max_file_size(mut self, size: u64) -> Self {
71        self.max_file_size = size;
72        self
73    }
74
75    pub fn compression_level(mut self, level: i32) -> Self {
76        self.compression_level = level;
77        self
78    }
79
80    pub fn max_record_size(mut self, size: usize) -> Self {
81        self.max_record_size = size;
82        self
83    }
84
85    pub fn max_segment_duration(mut self, duration: Duration) -> Self {
86        self.max_segment_duration = Some(duration);
87        self
88    }
89
90    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
91        self.suffix = Some(suffix.into());
92        self
93    }
94
95    pub fn tz(mut self, tz: Tz) -> Self {
96        self.tz = Some(tz);
97        self
98    }
99
100    /// Build the [`LogWriter`].
101    pub fn build(self) -> LogWriter {
102        let registration = WriterRegistration::new(self.log_dir.clone(), self.suffix.as_deref());
103        LogWriter {
104            log_dir: self.log_dir,
105            max_file_size: self.max_file_size,
106            compression_level: self.compression_level,
107            max_record_size: self.max_record_size,
108            max_segment_duration: self.max_segment_duration,
109            suffix: self.suffix,
110            tz: self.tz,
111            current: None,
112            _registration: registration,
113        }
114    }
115}
116
117/// State for the currently open segment file.
118struct OpenSegment {
119    encoder: Encoder<'static, std::fs::File>,
120    path: Utf8PathBuf,
121    bytes_written: u64,
122    opened_at: Instant,
123}
124
125/// A log writer that produces zstd-compressed JSONL segment files
126/// in a directory, compatible with [`LogTailer`](crate::LogTailer).
127pub struct LogWriter {
128    log_dir: Utf8PathBuf,
129    max_file_size: u64,
130    compression_level: i32,
131    max_record_size: usize,
132    max_segment_duration: Option<Duration>,
133    suffix: Option<String>,
134    tz: Option<Tz>,
135    current: Option<OpenSegment>,
136    // `_` because we don't use it directly, but need to keep it
137    // alive until we Drop
138    _registration: WriterRegistration,
139}
140
141impl LogWriter {
142    /// Write a JSONL line (record) to the current segment.
143    ///
144    /// If no segment is open, one will be created.  After writing,
145    /// if the segment has exceeded `max_file_size` or
146    /// `max_segment_duration` it will be closed and a new segment
147    /// will be opened on the next write.
148    pub fn write_line(&mut self, line: &str) -> anyhow::Result<()> {
149        // A reader buffer holds at most `max_record_size` bytes, but a complete
150        // line needs the record content plus a one-byte newline separator.
151        // Content of exactly `max_record_size` bytes doesn't leave room for
152        // that newline, so it is refused along with anything larger.
153        let max = self.max_record_size;
154        let len = line.strip_suffix('\n').unwrap_or(line).len();
155        if len >= max {
156            anyhow::bail!(
157                "record of {len} bytes plus its newline separator does not fit \
158                 within max_record_size of {max} bytes"
159            );
160        }
161
162        if self.current.is_none() {
163            self.open_segment()?;
164        }
165
166        let seg = self.current.as_mut().expect("just opened");
167
168        seg.encoder.write_all(line.as_bytes())?;
169        seg.bytes_written += line.len() as u64;
170
171        // Ensure the record ends with a newline
172        if !line.ends_with('\n') {
173            seg.encoder.write_all(b"\n")?;
174            seg.bytes_written += 1;
175        }
176
177        // Check if we need to roll to a new segment
178        if self.should_roll() {
179            self.close_segment()?;
180        }
181
182        Ok(())
183    }
184
185    /// Serialize `value` to JSON and write it as a JSONL line.
186    pub fn write_value<S: serde::Serialize>(&mut self, value: &S) -> anyhow::Result<()> {
187        let json = serde_json::to_string(value)?;
188        self.write_line(&json)
189    }
190
191    /// Flush and close the current segment if it has exceeded
192    /// `max_segment_duration`.  This is a no-op if no segment is
193    /// open or if the duration has not been exceeded.
194    pub fn maintain(&mut self) -> anyhow::Result<()> {
195        if self.current.is_some() && self.duration_exceeded() {
196            self.close_segment()?;
197        }
198        Ok(())
199    }
200
201    /// Flush and close the current segment, regardless of whether
202    /// it has exceeded any configured constraints.
203    pub fn close(&mut self) -> anyhow::Result<()> {
204        if self.current.is_some() {
205            self.close_segment()?;
206        }
207        Ok(())
208    }
209
210    /// Finish the zstd stream so the data is readable, but do NOT
211    /// mark the file as done (readonly).  This is useful for tests
212    /// that need to simulate an in-progress segment.
213    pub fn flush_without_marking_done(&mut self) -> anyhow::Result<()> {
214        if let Some(seg) = self.current.take() {
215            seg.encoder.finish()?;
216        }
217        Ok(())
218    }
219
220    fn should_roll(&self) -> bool {
221        let Some(seg) = &self.current else {
222            return false;
223        };
224        if seg.bytes_written >= self.max_file_size {
225            return true;
226        }
227        self.duration_exceeded()
228    }
229
230    fn duration_exceeded(&self) -> bool {
231        let Some(seg) = &self.current else {
232            return false;
233        };
234        if let Some(max_dur) = self.max_segment_duration {
235            if seg.opened_at.saturating_elapsed() >= max_dur {
236                return true;
237            }
238        }
239        false
240    }
241
242    fn open_segment(&mut self) -> anyhow::Result<()> {
243        let now: DateTime<Utc> = DateTime::now();
244        let mut base_name = match &self.tz {
245            Some(tz) => now.with_timezone(tz).format("%Y%m%d-%H%M%S%.f").to_string(),
246            None => now.format("%Y%m%d-%H%M%S%.f").to_string(),
247        };
248        if let Some(suffix) = &self.suffix {
249            base_name.push_str(suffix);
250        }
251        let path = self.log_dir.join(base_name);
252
253        std::fs::create_dir_all(&self.log_dir)?;
254
255        let file = std::fs::File::create(path.as_std_path())?;
256        let encoder = Encoder::new(file, self.compression_level)?;
257
258        self.current = Some(OpenSegment {
259            encoder,
260            path,
261            bytes_written: 0,
262            opened_at: Instant::now(),
263        });
264
265        Ok(())
266    }
267
268    fn close_segment(&mut self) -> anyhow::Result<()> {
269        if let Some(seg) = self.current.take() {
270            // Finish the zstd stream (flushes and writes the end frame)
271            seg.encoder.finish()?;
272            // Mark the file as done (readonly) to signal to the tailer
273            // that this segment is complete
274            mark_segment_done(&seg.path)?;
275        }
276        Ok(())
277    }
278}
279
280impl Drop for LogWriter {
281    fn drop(&mut self) {
282        // Best-effort close on drop
283        let _ = self.close();
284    }
285}
286
287/// Mark a segment file as done by removing write permissions.
288fn mark_segment_done(path: &Utf8PathBuf) -> std::io::Result<()> {
289    let meta = std::fs::metadata(path.as_std_path())?;
290    let mut perms = meta.permissions();
291    perms.set_readonly(true);
292    std::fs::set_permissions(path.as_std_path(), perms)
293}
294
295#[cfg(test)]
296mod test {
297    use super::*;
298
299    fn writer(dir: &tempfile::TempDir, max_record_size: usize) -> LogWriter {
300        LogWriterConfig::new(Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).unwrap())
301            .max_record_size(max_record_size)
302            .build()
303    }
304
305    #[test]
306    fn record_within_limit_is_written() {
307        let dir = tempfile::tempdir().unwrap();
308        let mut w = writer(&dir, 32);
309        w.write_line("small").unwrap();
310        w.close().unwrap();
311    }
312
313    /// Verifies the writer and a tailer configured with the same limit agree at
314    /// the boundary: a record one byte inside the limit is written and read
315    /// back unchanged, and a record at the limit is refused by the writer
316    /// before it can produce a segment the tailer would reject as corrupt.
317    #[test]
318    fn writer_and_tailer_limits_match() {
319        use crate::decompress::{FileDecompressor, NextLine};
320
321        let max = 64 * 1024;
322        let dir = tempfile::tempdir().unwrap();
323
324        let mut w = writer(&dir, max);
325        let largest = "z".repeat(max - 1);
326        w.write_line(&largest).unwrap();
327        w.write_line(&"z".repeat(max)).unwrap_err();
328        w.close().unwrap();
329
330        let seg = std::fs::read_dir(dir.path())
331            .unwrap()
332            .next()
333            .unwrap()
334            .unwrap()
335            .path();
336        let mut d = FileDecompressor::open_with_max_line_size(&seg, max).unwrap();
337        match d.next_line(0).unwrap() {
338            NextLine::Line(line) => {
339                k9::assert_equal!(line.text, largest);
340            }
341            other => panic!("expected a line, got {other:?}"),
342        }
343        assert!(matches!(d.next_line(0).unwrap(), NextLine::None));
344    }
345
346    /// Rejects a record whose content reaches the limit (its newline would not
347    /// fit): nothing is written, and the segment is not left open.
348    #[test]
349    fn record_at_limit_is_rejected() {
350        let dir = tempfile::tempdir().unwrap();
351        let mut w = writer(&dir, 8);
352        let err = w.write_line(&"x".repeat(8)).unwrap_err();
353        k9::assert_equal!(
354            err.to_string(),
355            "record of 8 bytes plus its newline separator does not fit \
356             within max_record_size of 8 bytes"
357        );
358        assert!(w.current.is_none());
359    }
360
361    /// The trailing newline of the record is not counted against the limit: a
362    /// record whose content is below the limit is accepted even when the input
363    /// already ends in a newline.
364    #[test]
365    fn trailing_newline_excluded_from_limit() {
366        let dir = tempfile::tempdir().unwrap();
367        let mut w = writer(&dir, 8);
368        w.write_line(&format!("{}\n", "x".repeat(7))).unwrap();
369        w.close().unwrap();
370    }
371}