Skip to main content

thinkingdata_core/consumer/
log_consumer.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The log consumer: writes NDJSON files for later ingestion via LogBus.
16//!
17//! Internally it is a streaming pipeline: every event is pushed onto an MPSC
18//! channel and a single writer task owns all file I/O (opening, rotating,
19//! paging, syncing), executing the blocking file operations via
20//! `tokio::task::spawn_blocking`.
21
22use std::fs::{File, OpenOptions, create_dir_all, read_dir};
23use std::io::Write;
24use std::path::Path;
25use std::sync::{Arc, Mutex, OnceLock};
26
27use tokio::sync::{mpsc, oneshot};
28
29use crate::error::{Result, TDError};
30use crate::log::td_log_info;
31use crate::utils::{format_with, parse_time};
32
33#[cfg(feature = "async")]
34use crate::consumer::AsyncConsumer;
35#[cfg(feature = "blocking")]
36use crate::consumer::Consumer;
37use crate::data::Data;
38
39/// How often the log file rotates by time.
40///
41/// The Rust port of the Go SDK's `RotateMode` constants.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
43pub enum RotateMode {
44    /// Rotate once a day; file names look like `log.2026-11-17`.
45    #[default]
46    Daily,
47    /// Rotate once an hour; file names look like `log.2026-11-17-09`.
48    Hourly,
49}
50
51impl RotateMode {
52    /// The jiff `strftime` pattern used for the time part of the file name.
53    fn date_format(self) -> &'static str {
54        match self {
55            RotateMode::Daily => "%Y-%m-%d",
56            RotateMode::Hourly => "%Y-%m-%d-%H",
57        }
58    }
59
60    fn from_go(value: i32) -> Result<RotateMode> {
61        match value {
62            0 => Ok(RotateMode::Daily),
63            1 => Ok(RotateMode::Hourly),
64            _ => Err(TDError::msg("unknown rotate mode")),
65        }
66    }
67}
68
69/// Configuration for [`LogConsumer`], mirroring the Go SDK's
70/// `TDLogConsumerConfig`.
71#[derive(Debug, Clone)]
72pub struct LogConsumerConfig {
73    /// Directory the log files live in. Created when missing.
74    pub directory: String,
75    /// Time-based rotation of log files.
76    pub rotate_mode: RotateMode,
77    /// Maximum size of a single log file in megabytes; `0` disables paging.
78    pub file_size_mb: u64,
79    /// Prefix placed before `log.` in the file name.
80    pub file_name_prefix: String,
81}
82
83impl Default for LogConsumerConfig {
84    fn default() -> Self {
85        Self {
86            directory: String::new(),
87            rotate_mode: RotateMode::Daily,
88            file_size_mb: 0,
89            file_name_prefix: String::new(),
90        }
91    }
92}
93
94/// One command for the streaming writer task.
95enum LogCommand {
96    Write {
97        line: String,
98        ack: oneshot::Sender<Result<()>>,
99    },
100    Flush {
101        ack: oneshot::Sender<Result<()>>,
102    },
103    Close {
104        ack: oneshot::Sender<Result<()>>,
105    },
106}
107
108/// Immutable configuration shared with the writer task.
109struct WriterShared {
110    directory: String,
111    rotate_mode: RotateMode,
112    max_file_size: u64,
113    file_name_prefix: String,
114    state: Mutex<WriterState>,
115    /// Result of the final close, published by the writer task so repeated
116    /// `close` calls return the same result after the task exits.
117    close_result: OnceLock<Result<()>>,
118}
119
120/// File state owned by the writer task.
121struct WriterState {
122    file: Option<File>,
123    file_name: String,
124    file_index: usize,
125    write_err: Option<TDError>,
126}
127
128/// Write data to local log files, one JSON object per line, for later
129/// ingestion with LogBus or another transfer tool.
130///
131/// This is the Rust counterpart of the Go SDK's `TDLogConsumer`. Files are
132/// named `{directory}/{prefix.}log.{date}` (or `..._{n}` when size-based
133/// paging is enabled) and are opened in append mode, so restarting the
134/// process never overwrites existing data.
135///
136/// ```
137/// # use thinkingdata_core::consumer::{Consumer, LogConsumer};
138///
139/// # #[cfg(feature = "blocking")]
140/// # fn main() -> Result<(), thinkingdata_core::TDError> {
141/// # let consumer = LogConsumer::new("/tmp/thinkingdata-logs")?;
142/// # consumer.close()?;
143/// # Ok(())
144/// # }
145/// ```
146#[derive(Clone)]
147pub struct LogConsumer {
148    tx: mpsc::UnboundedSender<LogCommand>,
149    shared: Arc<WriterShared>,
150}
151
152impl std::fmt::Debug for LogConsumer {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        f.debug_struct("LogConsumer")
155            .field("directory", &self.shared.directory)
156            .field("rotate_mode", &self.shared.rotate_mode)
157            .field("max_file_size", &self.shared.max_file_size)
158            .field("file_name_prefix", &self.shared.file_name_prefix)
159            .finish_non_exhaustive()
160    }
161}
162
163impl LogConsumer {
164    /// Create a consumer writing daily-rotated logs into `directory`.
165    pub fn new(directory: &str) -> Result<Self> {
166        Self::with_config(LogConsumerConfig {
167            directory: directory.to_string(),
168            ..LogConsumerConfig::default()
169        })
170    }
171
172    /// Create a consumer with an explicit [`RotateMode`].
173    pub fn with_rotate_mode(directory: &str, rotate_mode: RotateMode) -> Result<Self> {
174        Self::with_config(LogConsumerConfig {
175            directory: directory.to_string(),
176            rotate_mode,
177            ..LogConsumerConfig::default()
178        })
179    }
180
181    /// Numeric rotate-mode constructor matching the Go SDK's
182    /// `NewLogConsumer(directory, rotateMode)`: `0` selects daily rotation,
183    /// `1` hourly rotation.
184    pub fn with_go_rotate_mode(directory: &str, rotate_mode: i32) -> Result<Self> {
185        Self::with_config(LogConsumerConfig {
186            directory: directory.to_string(),
187            rotate_mode: RotateMode::from_go(rotate_mode)?,
188            ..LogConsumerConfig::default()
189        })
190    }
191
192    /// Create a consumer from a full configuration.
193    pub fn with_config(config: LogConsumerConfig) -> Result<Self> {
194        const MAX_FILE_SIZE_MB: u64 = u64::MAX / (1024 * 1024);
195        if config.file_size_mb > MAX_FILE_SIZE_MB {
196            return Err(TDError::msg(format!(
197                "invalid FileSize {}: must be between 0 and {} MB",
198                config.file_size_mb, MAX_FILE_SIZE_MB
199            )));
200        }
201
202        create_dir_all(&config.directory).map_err(|err| {
203            TDError::msg(format!("create log directory {}: {err}", config.directory))
204        })?;
205
206        let max_file_size = config.file_size_mb.saturating_mul(1024 * 1024);
207        let mut file_index = 0usize;
208        if max_file_size > 0 {
209            let period = format_with(config.rotate_mode.date_format());
210            restore_file_index(
211                &config.directory,
212                &config.file_name_prefix,
213                &period,
214                &mut file_index,
215            )?;
216        }
217        let (file, file_name) = open_writable(
218            &config.directory,
219            &config.file_name_prefix,
220            config.rotate_mode.date_format(),
221            max_file_size,
222            &mut file_index,
223        )?;
224
225        td_log_info(&format!(
226            "Mode: log consumer, directory: {}, rotate mode: {:?}",
227            config.directory, config.rotate_mode
228        ));
229
230        let shared = Arc::new(WriterShared {
231            directory: config.directory,
232            rotate_mode: config.rotate_mode,
233            max_file_size,
234            file_name_prefix: config.file_name_prefix,
235            state: Mutex::new(WriterState {
236                file: Some(file),
237                file_name,
238                file_index,
239                write_err: None,
240            }),
241            close_result: OnceLock::new(),
242        });
243
244        let (tx, rx) = mpsc::unbounded_channel::<LogCommand>();
245        crate::consumer::shared_runtime().spawn(writer_loop(shared.clone(), rx));
246        Ok(Self { tx, shared })
247    }
248
249    /// Serialize one event into a JSON line and hand it to the writer task.
250    async fn do_add(&self, data: &Data) -> Result<()> {
251        let json = serde_json::to_string(data)?;
252        let line = parse_time(&json);
253        td_log_info(&format!("Enqueue event data: {line}"));
254        let (ack_tx, ack_rx) = oneshot::channel();
255        self.tx
256            .send(LogCommand::Write { line, ack: ack_tx })
257            .map_err(|_| TDError::msg("add event failed, SDK has been closed"))?;
258        ack_rx
259            .await
260            .map_err(|_| TDError::msg("log writer task terminated"))?
261    }
262
263    /// Sync the current file to disk and return the first retained error.
264    async fn do_flush(&self) -> Result<()> {
265        let (ack_tx, ack_rx) = oneshot::channel();
266        if self.tx.send(LogCommand::Flush { ack: ack_tx }).is_err() {
267            // The writer task has exited; report the retained close result.
268            return match self.shared.close_result.get() {
269                Some(result) => result.clone(),
270                None => Err(TDError::msg("log consumer has been closed")),
271            };
272        }
273        ack_rx
274            .await
275            .map_err(|_| TDError::msg("log writer task terminated"))?
276    }
277
278    /// Stop accepting events, sync and close the current file, and return the
279    /// first retained error. Repeated calls return the same result.
280    async fn do_close(&self) -> Result<()> {
281        if let Some(result) = self.shared.close_result.get() {
282            return result.clone();
283        }
284        let (ack_tx, ack_rx) = oneshot::channel();
285        if self.tx.send(LogCommand::Close { ack: ack_tx }).is_err() {
286            return match self.shared.close_result.get() {
287                Some(result) => result.clone(),
288                None => Err(TDError::msg("log consumer has been closed")),
289            };
290        }
291        ack_rx
292            .await
293            .map_err(|_| TDError::msg("log writer task terminated"))?
294    }
295}
296
297/// The streaming writer task: consumes commands in order and owns all file I/O.
298async fn writer_loop(shared: Arc<WriterShared>, mut rx: mpsc::UnboundedReceiver<LogCommand>) {
299    while let Some(command) = rx.recv().await {
300        match command {
301            LogCommand::Write { line, ack } => {
302                let result = write_event(&shared, &line).await;
303                let _ = ack.send(result);
304            }
305            LogCommand::Flush { ack } => {
306                let result = sync_file(&shared).await;
307                let _ = ack.send(result);
308            }
309            LogCommand::Close { ack } => {
310                let result = close_writer(&shared).await;
311                let _ = shared.close_result.set(result.clone());
312                let _ = ack.send(result);
313                return;
314            }
315        }
316    }
317}
318
319/// Append one line, rotating the file when the period changed or the size
320/// limit was exceeded. Blocking file operations run on the blocking pool.
321async fn write_event(shared: &Arc<WriterShared>, line: &str) -> Result<()> {
322    let line = line.to_string();
323    let task = shared.clone();
324    tokio::task::spawn_blocking(move || {
325        let mut state = task.state.lock().expect("ThinkingData log state poisoned");
326        let period = format_with(task.rotate_mode.date_format());
327        match write_line(&task, &mut state, &line, &period) {
328            Err(err) => {
329                remember_error(&mut state, err.clone());
330                Err(err)
331            }
332            Ok(()) => Ok(()),
333        }
334    })
335    .await
336    .map_err(|err| TDError::msg(format!("log writer failed: {err}")))?
337}
338
339/// Sync the current file; retains and returns the first remembered error.
340async fn sync_file(shared: &Arc<WriterShared>) -> Result<()> {
341    let task = shared.clone();
342    tokio::task::spawn_blocking(move || {
343        let mut state = task.state.lock().expect("ThinkingData log state poisoned");
344        if let Some(file) = &state.file
345            && let Err(err) = file.sync_all()
346        {
347            remember_error(&mut state, TDError::msg(format!("sync log file: {err}")));
348        }
349        match &state.write_err {
350            Some(err) => Err(err.clone()),
351            None => Ok(()),
352        }
353    })
354    .await
355    .map_err(|err| TDError::msg(format!("log writer failed: {err}")))?
356}
357
358/// Sync, close and seal the writer; retains and returns the first error.
359async fn close_writer(shared: &Arc<WriterShared>) -> Result<()> {
360    let task = shared.clone();
361    tokio::task::spawn_blocking(move || {
362        let mut state = task.state.lock().expect("ThinkingData log state poisoned");
363        if let Some(file) = state.file.take() {
364            if let Err(err) = file.sync_all() {
365                remember_error(&mut state, TDError::msg(format!("sync log file: {err}")));
366            }
367            drop(file);
368        }
369        match &state.write_err {
370            Some(err) => Err(err.clone()),
371            None => Ok(()),
372        }
373    })
374    .await
375    .map_err(|err| TDError::msg(format!("log writer failed: {err}")))?
376}
377
378fn remember_error(state: &mut WriterState, err: TDError) {
379    if state.write_err.is_none() {
380        state.write_err = Some(err);
381    }
382}
383
384/// Append one line, mirroring the Go writer's rotation logic.
385fn write_line(
386    shared: &WriterShared,
387    state: &mut WriterState,
388    line: &str,
389    period: &str,
390) -> Result<()> {
391    let mut file_name = construct_file_name(
392        &shared.directory,
393        &shared.file_name_prefix,
394        period,
395        shared.max_file_size,
396        state.file_index,
397    );
398    if let Some(file) = &state.file {
399        if state.file_name == file_name && shared.max_file_size > 0 {
400            let size = file
401                .metadata()
402                .map_err(|err| TDError::msg(format!("stat log file: {err}")))?
403                .len();
404            if size > shared.max_file_size {
405                if state.file_index == usize::MAX {
406                    return Err(TDError::msg("log file index overflow"));
407                }
408                state.file_index += 1;
409                file_name = construct_file_name(
410                    &shared.directory,
411                    &shared.file_name_prefix,
412                    period,
413                    shared.max_file_size,
414                    state.file_index,
415                );
416            }
417        }
418        if state.file_name != file_name {
419            let previous = state.file.take();
420            if let Some(previous) = previous {
421                previous
422                    .sync_all()
423                    .map_err(|err| TDError::msg(format!("sync rotated log file: {err}")))?;
424                drop(previous);
425            }
426        }
427    }
428    if state.file.is_none() {
429        let (file, name) = open_writable(
430            &shared.directory,
431            &shared.file_name_prefix,
432            shared.rotate_mode.date_format(),
433            shared.max_file_size,
434            &mut state.file_index,
435        )?;
436        state.file = Some(file);
437        state.file_name = name;
438    }
439    let file = state.file.as_mut().expect("log file is opened above");
440    file.write_all(line.as_bytes())
441        .and_then(|_| file.write_all(b"\n"))
442        .map_err(|err| TDError::msg(format!("write log file: {err}")))
443}
444
445/// Base file name (no directory) for a paged log file.
446fn paged_base_name(prefix: &str, period: &str, index: usize) -> String {
447    format!("{}log.{period}_{index}", dotted_prefix(prefix))
448}
449
450fn dotted_prefix(prefix: &str) -> String {
451    if prefix.is_empty() {
452        String::new()
453    } else {
454        format!("{prefix}.")
455    }
456}
457
458fn construct_file_name(
459    directory: &str,
460    prefix: &str,
461    period: &str,
462    max_file_size: u64,
463    index: usize,
464) -> String {
465    let dotted = dotted_prefix(prefix);
466    if max_file_size > 0 {
467        format!("{directory}/{dotted}log.{period}_{index}")
468    } else {
469        format!("{directory}/{dotted}log.{period}")
470    }
471}
472
473/// Resume the latest numbered file for this period and prefix on restart.
474/// Older partial files and gaps must not move the append position backwards.
475fn restore_file_index(
476    directory: &str,
477    prefix: &str,
478    period: &str,
479    file_index: &mut usize,
480) -> Result<()> {
481    let entries =
482        read_dir(directory).map_err(|err| TDError::msg(format!("read log directory: {err}")))?;
483    let name_prefix = paged_base_name(prefix, period, 0)
484        .strip_suffix('0')
485        .map(str::to_string)
486        .unwrap_or_default();
487    for entry in entries.flatten() {
488        let name = entry.file_name();
489        let Some(name) = name.to_str() else {
490            continue;
491        };
492        if !name.starts_with(&name_prefix) {
493            continue;
494        }
495        let suffix = &name[name_prefix.len()..];
496        // Only accept names generated by `construct_file_name`, not backups.
497        if let Ok(index) = suffix.parse::<usize>()
498            && index.to_string() == suffix
499            && index > *file_index
500        {
501            *file_index = index;
502        }
503    }
504    Ok(())
505}
506
507/// Open the first candidate file that still has room, including files left
508/// behind by a previous process.
509fn open_writable(
510    directory: &str,
511    prefix: &str,
512    date_format: &str,
513    max_file_size: u64,
514    file_index: &mut usize,
515) -> Result<(File, String)> {
516    let dotted = dotted_prefix(prefix);
517    loop {
518        let period = format_with(date_format);
519        let name = if max_file_size > 0 {
520            format!("{directory}/{dotted}log.{period}_{file_index}")
521        } else {
522            format!("{directory}/{dotted}log.{period}")
523        };
524        let file = open_append(Path::new(&name))?;
525        if max_file_size == 0 {
526            return Ok((file, name));
527        }
528        let size = file
529            .metadata()
530            .map_err(|err| TDError::msg(format!("stat log file: {err}")))?
531            .len();
532        if size <= max_file_size {
533            return Ok((file, name));
534        }
535        drop(file);
536        if *file_index == usize::MAX {
537            return Err(TDError::msg("log file index overflow"));
538        }
539        *file_index += 1;
540    }
541}
542
543fn open_append(path: &Path) -> Result<File> {
544    let mut options = OpenOptions::new();
545    options.append(true).create(true);
546    #[cfg(unix)]
547    {
548        use std::os::unix::fs::OpenOptionsExt;
549        options.mode(0o664);
550    }
551    options
552        .open(path)
553        .map_err(|err| TDError::msg(format!("open log file {}: {err}", path.display())))
554}
555
556#[cfg(feature = "blocking")]
557impl Consumer for LogConsumer {
558    /// Serialize and append the event, awaiting the writer task's result.
559    /// Unlike the Go SDK — which only admits events onto a channel and
560    /// reports write errors from `flush`/`close` — this port reports file
561    /// errors immediately.
562    fn add(&self, data: &Data) -> Result<()> {
563        crate::consumer::shared_runtime().block_on(self.do_add(data))
564    }
565
566    /// Sync the current file to disk and return the first retained error.
567    fn flush(&self) -> Result<()> {
568        crate::consumer::shared_runtime().block_on(self.do_flush())
569    }
570
571    /// Stop accepting events, sync and close the current file.
572    fn close(&self) -> Result<()> {
573        crate::consumer::shared_runtime().block_on(self.do_close())
574    }
575}
576
577#[cfg(feature = "async")]
578#[async_trait::async_trait]
579impl AsyncConsumer for LogConsumer {
580    /// Serialize and enqueue the event; the streaming writer task performs
581    /// the file I/O, so this method never blocks the caller's task.
582    async fn add_async(&self, data: &Data) -> Result<()> {
583        self.do_add(data).await
584    }
585
586    /// Sync the current file to disk and return the first retained error.
587    async fn flush_async(&self) -> Result<()> {
588        self.do_flush().await
589    }
590
591    /// Stop accepting events, sync and close the current file.
592    async fn close_async(&self) -> Result<()> {
593        self.do_close().await
594    }
595}
596
597#[cfg(all(test, feature = "blocking"))]
598mod tests {
599    use super::*;
600    use crate::DataType;
601    use serde_json::json;
602
603    fn temp_dir(tag: &str) -> String {
604        let dir = std::env::temp_dir().join(format!(
605            "thinkingdata-log-test-{tag}-{}",
606            std::process::id()
607        ));
608        let _ = std::fs::remove_dir_all(&dir);
609        dir.to_string_lossy().into_owned()
610    }
611
612    fn event() -> Data {
613        let mut data = Data::new(DataType::Track);
614        data.account_id = "acc".to_string();
615        data.event_name = "purchase".to_string();
616        data.properties.insert("price".to_string(), json!(9.9));
617        data
618    }
619
620    #[test]
621    fn writes_one_json_object_per_line() {
622        let dir = temp_dir("lines");
623        let consumer = LogConsumer::new(&dir).unwrap();
624        consumer.add(&event()).unwrap();
625        consumer.close().unwrap();
626
627        let mut entries: Vec<_> = std::fs::read_dir(&dir)
628            .unwrap()
629            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
630            .collect();
631        entries.sort();
632        assert_eq!(entries.len(), 1);
633        assert!(entries[0].starts_with("log.2"), "{entries:?}");
634
635        let content = std::fs::read_to_string(Path::new(&dir).join(&entries[0])).unwrap();
636        let lines: Vec<&str> = content.lines().collect();
637        assert_eq!(lines.len(), 1);
638        let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
639        assert_eq!(parsed["#type"], "track");
640        assert_eq!(parsed["properties"]["price"], 9.9);
641        let _ = std::fs::remove_dir_all(&dir);
642    }
643
644    #[test]
645    fn file_name_prefix_is_applied() {
646        let dir = temp_dir("prefix");
647        let consumer = LogConsumer::with_config(LogConsumerConfig {
648            directory: dir.clone(),
649            file_name_prefix: "ta".to_string(),
650            ..LogConsumerConfig::default()
651        })
652        .unwrap();
653        consumer.add(&event()).unwrap();
654        consumer.close().unwrap();
655
656        let entries: Vec<_> = std::fs::read_dir(&dir)
657            .unwrap()
658            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
659            .collect();
660        assert_eq!(entries.len(), 1);
661        assert!(entries[0].starts_with("ta.log."), "{entries:?}");
662        let _ = std::fs::remove_dir_all(&dir);
663    }
664
665    #[test]
666    fn size_paging_creates_indexed_files() {
667        let dir = temp_dir("paging");
668        let consumer = LogConsumer::with_config(LogConsumerConfig {
669            directory: dir.clone(),
670            file_size_mb: 1,
671            ..LogConsumerConfig::default()
672        })
673        .unwrap();
674        let mut big = event();
675        big.properties
676            .insert("padding".to_string(), json!("x".repeat(1024 * 1024 + 128)));
677        consumer.add(&big).unwrap();
678        consumer.add(&event()).unwrap();
679        consumer.close().unwrap();
680
681        let mut entries: Vec<_> = std::fs::read_dir(&dir)
682            .unwrap()
683            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
684            .collect();
685        entries.sort();
686        assert_eq!(entries.len(), 2, "{entries:?}");
687        assert!(entries[0].ends_with("_0"), "{entries:?}");
688        assert!(entries[1].ends_with("_1"), "{entries:?}");
689
690        // The second event must have landed in file _1.
691        let second = std::fs::read_to_string(Path::new(&dir).join(&entries[1])).unwrap();
692        assert!(second.contains("\"purchase\""), "{second}");
693        let _ = std::fs::remove_dir_all(&dir);
694    }
695
696    #[test]
697    fn restore_file_index_resumes_at_max() {
698        let dir = temp_dir("restore");
699        std::fs::create_dir_all(&dir).unwrap();
700        let period = format_with(RotateMode::Daily.date_format());
701        std::fs::write(Path::new(&dir).join(format!("log.{period}_0")), "old\n").unwrap();
702        std::fs::write(Path::new(&dir).join(format!("log.{period}_3")), "old\n").unwrap();
703        std::fs::write(Path::new(&dir).join(format!("log.{period}_backup")), "").unwrap();
704
705        let mut index = 0usize;
706        restore_file_index(&dir, "", &period, &mut index).unwrap();
707        assert_eq!(index, 3);
708        let _ = std::fs::remove_dir_all(&dir);
709    }
710
711    #[test]
712    fn add_after_close_fails() {
713        let dir = temp_dir("closed");
714        let consumer = LogConsumer::new(&dir).unwrap();
715        consumer.close().unwrap();
716        let err = consumer.add(&event()).unwrap_err();
717        assert!(err.to_string().contains("closed"), "{err}");
718        // close is idempotent and repeats the retained result.
719        consumer.close().unwrap();
720        let _ = std::fs::remove_dir_all(&dir);
721    }
722
723    #[test]
724    fn go_rotate_mode_validation() {
725        assert_eq!(RotateMode::from_go(0).unwrap(), RotateMode::Daily);
726        assert_eq!(RotateMode::from_go(1).unwrap(), RotateMode::Hourly);
727        assert!(RotateMode::from_go(2).is_err());
728    }
729
730    #[test]
731    fn local_time_is_used_for_period() {
732        // Sanity: the daily/hourly patterns produce the documented shapes.
733        let daily = format_with(RotateMode::Daily.date_format());
734        assert_eq!(daily.len(), 10, "{daily}");
735        let hourly = format_with(RotateMode::Hourly.date_format());
736        assert_eq!(hourly.len(), 13, "{hourly}");
737    }
738}