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/// # fn main() -> Result<(), thinkingdata_core::TDError> {
138/// # #[cfg(feature = "blocking")]
139/// # {
140/// # use thinkingdata_core::consumer::{Consumer, LogConsumer};
141/// # let consumer = LogConsumer::new("/tmp/thinkingdata-logs")?;
142/// # consumer.close()?;
143/// # }
144/// # Ok(())
145/// # }
146/// ```
147#[derive(Clone)]
148pub struct LogConsumer {
149    tx: mpsc::UnboundedSender<LogCommand>,
150    shared: Arc<WriterShared>,
151}
152
153impl std::fmt::Debug for LogConsumer {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        f.debug_struct("LogConsumer")
156            .field("directory", &self.shared.directory)
157            .field("rotate_mode", &self.shared.rotate_mode)
158            .field("max_file_size", &self.shared.max_file_size)
159            .field("file_name_prefix", &self.shared.file_name_prefix)
160            .finish_non_exhaustive()
161    }
162}
163
164impl LogConsumer {
165    /// Create a consumer writing daily-rotated logs into `directory`.
166    pub fn new(directory: &str) -> Result<Self> {
167        Self::with_config(LogConsumerConfig {
168            directory: directory.to_string(),
169            ..LogConsumerConfig::default()
170        })
171    }
172
173    /// Create a consumer with an explicit [`RotateMode`].
174    pub fn with_rotate_mode(directory: &str, rotate_mode: RotateMode) -> Result<Self> {
175        Self::with_config(LogConsumerConfig {
176            directory: directory.to_string(),
177            rotate_mode,
178            ..LogConsumerConfig::default()
179        })
180    }
181
182    /// Numeric rotate-mode constructor matching the Go SDK's
183    /// `NewLogConsumer(directory, rotateMode)`: `0` selects daily rotation,
184    /// `1` hourly rotation.
185    pub fn with_go_rotate_mode(directory: &str, rotate_mode: i32) -> Result<Self> {
186        Self::with_config(LogConsumerConfig {
187            directory: directory.to_string(),
188            rotate_mode: RotateMode::from_go(rotate_mode)?,
189            ..LogConsumerConfig::default()
190        })
191    }
192
193    /// Create a consumer from a full configuration.
194    pub fn with_config(config: LogConsumerConfig) -> Result<Self> {
195        const MAX_FILE_SIZE_MB: u64 = u64::MAX / (1024 * 1024);
196        if config.file_size_mb > MAX_FILE_SIZE_MB {
197            return Err(TDError::msg(format!(
198                "invalid FileSize {}: must be between 0 and {} MB",
199                config.file_size_mb, MAX_FILE_SIZE_MB
200            )));
201        }
202
203        create_dir_all(&config.directory).map_err(|err| {
204            TDError::msg(format!("create log directory {}: {err}", config.directory))
205        })?;
206
207        let max_file_size = config.file_size_mb.saturating_mul(1024 * 1024);
208        let mut file_index = 0usize;
209        if max_file_size > 0 {
210            let period = format_with(config.rotate_mode.date_format());
211            restore_file_index(
212                &config.directory,
213                &config.file_name_prefix,
214                &period,
215                &mut file_index,
216            )?;
217        }
218        let (file, file_name) = open_writable(
219            &config.directory,
220            &config.file_name_prefix,
221            config.rotate_mode.date_format(),
222            max_file_size,
223            &mut file_index,
224        )?;
225
226        td_log_info(&format!(
227            "Mode: log consumer, directory: {}, rotate mode: {:?}",
228            config.directory, config.rotate_mode
229        ));
230
231        let shared = Arc::new(WriterShared {
232            directory: config.directory,
233            rotate_mode: config.rotate_mode,
234            max_file_size,
235            file_name_prefix: config.file_name_prefix,
236            state: Mutex::new(WriterState {
237                file: Some(file),
238                file_name,
239                file_index,
240                write_err: None,
241            }),
242            close_result: OnceLock::new(),
243        });
244
245        let (tx, rx) = mpsc::unbounded_channel::<LogCommand>();
246        crate::consumer::shared_runtime().spawn(writer_loop(shared.clone(), rx));
247        Ok(Self { tx, shared })
248    }
249
250    /// Serialize one event into a JSON line and hand it to the writer task.
251    async fn do_add(&self, data: &Data) -> Result<()> {
252        let json = serde_json::to_string(data)?;
253        let line = parse_time(&json);
254        td_log_info(&format!("Enqueue event data: {line}"));
255        let (ack_tx, ack_rx) = oneshot::channel();
256        self.tx
257            .send(LogCommand::Write { line, ack: ack_tx })
258            .map_err(|_| TDError::msg("add event failed, SDK has been closed"))?;
259        match ack_rx.await {
260            Ok(result) => result,
261            // The writer task exited while this command was queued. If a
262            // concurrent `close` won the race, the event was not delivered
263            // because the consumer closed; otherwise the task is gone.
264            Err(_) if self.shared.close_result.get().is_some() => {
265                Err(TDError::msg("add event failed, SDK has been closed"))
266            }
267            Err(_) => Err(TDError::msg("log writer task terminated")),
268        }
269    }
270
271    /// Sync the current file to disk and return the first retained error.
272    async fn do_flush(&self) -> Result<()> {
273        let (ack_tx, ack_rx) = oneshot::channel();
274        if self.tx.send(LogCommand::Flush { ack: ack_tx }).is_err() {
275            // The writer task has exited; report the retained close result.
276            return match self.shared.close_result.get() {
277                Some(result) => result.clone(),
278                None => Err(TDError::msg("log consumer has been closed")),
279            };
280        }
281        match ack_rx.await {
282            Ok(result) => result,
283            // A concurrent `close` won the race and terminated the writer task
284            // before this command was served; report its retained result.
285            Err(_) => match self.shared.close_result.get() {
286                Some(result) => result.clone(),
287                None => Err(TDError::msg("log writer task terminated")),
288            },
289        }
290    }
291
292    /// Stop accepting events, sync and close the current file, and return the
293    /// first retained error. Repeated calls return the same result.
294    async fn do_close(&self) -> Result<()> {
295        if let Some(result) = self.shared.close_result.get() {
296            return result.clone();
297        }
298        let (ack_tx, ack_rx) = oneshot::channel();
299        if self.tx.send(LogCommand::Close { ack: ack_tx }).is_err() {
300            return match self.shared.close_result.get() {
301                Some(result) => result.clone(),
302                None => Err(TDError::msg("log consumer has been closed")),
303            };
304        }
305        match ack_rx.await {
306            Ok(result) => result,
307            // A concurrent `close` won the race and terminated the writer task
308            // before this command was served; report its retained result.
309            Err(_) => match self.shared.close_result.get() {
310                Some(result) => result.clone(),
311                None => Err(TDError::msg("log writer task terminated")),
312            },
313        }
314    }
315}
316
317/// The streaming writer task: consumes commands in order and owns all file I/O.
318async fn writer_loop(shared: Arc<WriterShared>, mut rx: mpsc::UnboundedReceiver<LogCommand>) {
319    while let Some(command) = rx.recv().await {
320        match command {
321            LogCommand::Write { line, ack } => {
322                let result = write_event(&shared, line).await;
323                let _ = ack.send(result);
324            }
325            LogCommand::Flush { ack } => {
326                let result = sync_file(&shared).await;
327                let _ = ack.send(result);
328            }
329            LogCommand::Close { ack } => {
330                let result = close_writer(&shared).await;
331                let _ = shared.close_result.set(result.clone());
332                let _ = ack.send(result);
333                return;
334            }
335        }
336    }
337}
338
339/// Append one line, rotating the file when the period changed or the size
340/// limit was exceeded. Blocking file operations run on the blocking pool; the
341/// line is moved into the task so the (potentially large) payload is written
342/// without an extra copy.
343async fn write_event(shared: &Arc<WriterShared>, line: String) -> Result<()> {
344    let task = shared.clone();
345    tokio::task::spawn_blocking(move || {
346        let mut state = task.state.lock().expect("ThinkingData log state poisoned");
347        let period = format_with(task.rotate_mode.date_format());
348        match write_line(&task, &mut state, &line, &period) {
349            Err(err) => {
350                remember_error(&mut state, err.clone());
351                Err(err)
352            }
353            Ok(()) => Ok(()),
354        }
355    })
356    .await
357    .map_err(|err| TDError::msg(format!("log writer failed: {err}")))?
358}
359
360/// Sync the current file; retains and returns the first remembered error.
361async fn sync_file(shared: &Arc<WriterShared>) -> Result<()> {
362    let task = shared.clone();
363    tokio::task::spawn_blocking(move || {
364        let mut state = task.state.lock().expect("ThinkingData log state poisoned");
365        if let Some(file) = &state.file
366            && let Err(err) = file.sync_all()
367        {
368            remember_error(&mut state, TDError::msg(format!("sync log file: {err}")));
369        }
370        match &state.write_err {
371            Some(err) => Err(err.clone()),
372            None => Ok(()),
373        }
374    })
375    .await
376    .map_err(|err| TDError::msg(format!("log writer failed: {err}")))?
377}
378
379/// Sync, close and seal the writer; retains and returns the first error.
380async fn close_writer(shared: &Arc<WriterShared>) -> Result<()> {
381    let task = shared.clone();
382    tokio::task::spawn_blocking(move || {
383        let mut state = task.state.lock().expect("ThinkingData log state poisoned");
384        if let Some(file) = state.file.take() {
385            if let Err(err) = file.sync_all() {
386                remember_error(&mut state, TDError::msg(format!("sync log file: {err}")));
387            }
388            drop(file);
389        }
390        match &state.write_err {
391            Some(err) => Err(err.clone()),
392            None => Ok(()),
393        }
394    })
395    .await
396    .map_err(|err| TDError::msg(format!("log writer failed: {err}")))?
397}
398
399fn remember_error(state: &mut WriterState, err: TDError) {
400    if state.write_err.is_none() {
401        state.write_err = Some(err);
402    }
403}
404
405/// Append one line, mirroring the Go writer's rotation logic.
406fn write_line(
407    shared: &WriterShared,
408    state: &mut WriterState,
409    line: &str,
410    period: &str,
411) -> Result<()> {
412    let mut file_name = construct_file_name(
413        &shared.directory,
414        &shared.file_name_prefix,
415        period,
416        shared.max_file_size,
417        state.file_index,
418    );
419    if let Some(file) = &state.file {
420        if state.file_name == file_name && shared.max_file_size > 0 {
421            let size = file
422                .metadata()
423                .map_err(|err| TDError::msg(format!("stat log file: {err}")))?
424                .len();
425            if size > shared.max_file_size {
426                if state.file_index == usize::MAX {
427                    return Err(TDError::msg("log file index overflow"));
428                }
429                state.file_index += 1;
430                file_name = construct_file_name(
431                    &shared.directory,
432                    &shared.file_name_prefix,
433                    period,
434                    shared.max_file_size,
435                    state.file_index,
436                );
437            }
438        }
439        if state.file_name != file_name {
440            let previous = state.file.take();
441            if let Some(previous) = previous {
442                previous
443                    .sync_all()
444                    .map_err(|err| TDError::msg(format!("sync rotated log file: {err}")))?;
445                drop(previous);
446            }
447        }
448    }
449    if state.file.is_none() {
450        let (file, name) = open_writable(
451            &shared.directory,
452            &shared.file_name_prefix,
453            shared.rotate_mode.date_format(),
454            shared.max_file_size,
455            &mut state.file_index,
456        )?;
457        state.file = Some(file);
458        state.file_name = name;
459    }
460    let file = state.file.as_mut().expect("log file is opened above");
461    file.write_all(line.as_bytes())
462        .and_then(|_| file.write_all(b"\n"))
463        .map_err(|err| TDError::msg(format!("write log file: {err}")))
464}
465
466/// Base file name (no directory) for a paged log file.
467fn paged_base_name(prefix: &str, period: &str, index: usize) -> String {
468    format!("{}log.{period}_{index}", dotted_prefix(prefix))
469}
470
471fn dotted_prefix(prefix: &str) -> String {
472    if prefix.is_empty() {
473        String::new()
474    } else {
475        format!("{prefix}.")
476    }
477}
478
479fn construct_file_name(
480    directory: &str,
481    prefix: &str,
482    period: &str,
483    max_file_size: u64,
484    index: usize,
485) -> String {
486    let dotted = dotted_prefix(prefix);
487    if max_file_size > 0 {
488        format!("{directory}/{dotted}log.{period}_{index}")
489    } else {
490        format!("{directory}/{dotted}log.{period}")
491    }
492}
493
494/// Resume the latest numbered file for this period and prefix on restart.
495/// Older partial files and gaps must not move the append position backwards.
496fn restore_file_index(
497    directory: &str,
498    prefix: &str,
499    period: &str,
500    file_index: &mut usize,
501) -> Result<()> {
502    let entries =
503        read_dir(directory).map_err(|err| TDError::msg(format!("read log directory: {err}")))?;
504    let name_prefix = paged_base_name(prefix, period, 0)
505        .strip_suffix('0')
506        .map(str::to_string)
507        .unwrap_or_default();
508    for entry in entries.flatten() {
509        let name = entry.file_name();
510        let Some(name) = name.to_str() else {
511            continue;
512        };
513        if !name.starts_with(&name_prefix) {
514            continue;
515        }
516        let suffix = &name[name_prefix.len()..];
517        // Only accept names generated by `construct_file_name`, not backups.
518        if let Ok(index) = suffix.parse::<usize>()
519            && index.to_string() == suffix
520            && index > *file_index
521        {
522            *file_index = index;
523        }
524    }
525    Ok(())
526}
527
528/// Open the first candidate file that still has room, including files left
529/// behind by a previous process.
530fn open_writable(
531    directory: &str,
532    prefix: &str,
533    date_format: &str,
534    max_file_size: u64,
535    file_index: &mut usize,
536) -> Result<(File, String)> {
537    let dotted = dotted_prefix(prefix);
538    loop {
539        let period = format_with(date_format);
540        let name = if max_file_size > 0 {
541            format!("{directory}/{dotted}log.{period}_{file_index}")
542        } else {
543            format!("{directory}/{dotted}log.{period}")
544        };
545        let file = open_append(Path::new(&name))?;
546        if max_file_size == 0 {
547            return Ok((file, name));
548        }
549        let size = file
550            .metadata()
551            .map_err(|err| TDError::msg(format!("stat log file: {err}")))?
552            .len();
553        if size <= max_file_size {
554            return Ok((file, name));
555        }
556        drop(file);
557        if *file_index == usize::MAX {
558            return Err(TDError::msg("log file index overflow"));
559        }
560        *file_index += 1;
561    }
562}
563
564fn open_append(path: &Path) -> Result<File> {
565    let mut options = OpenOptions::new();
566    options.append(true).create(true);
567    #[cfg(unix)]
568    {
569        use std::os::unix::fs::OpenOptionsExt;
570        options.mode(0o664);
571    }
572    options
573        .open(path)
574        .map_err(|err| TDError::msg(format!("open log file {}: {err}", path.display())))
575}
576
577#[cfg(feature = "blocking")]
578impl Consumer for LogConsumer {
579    /// Serialize and append the event, awaiting the writer task's result.
580    /// Unlike the Go SDK — which only admits events onto a channel and
581    /// reports write errors from `flush`/`close` — this port reports file
582    /// errors immediately.
583    fn add(&self, data: &Data) -> Result<()> {
584        crate::consumer::shared_runtime().block_on(self.do_add(data))
585    }
586
587    /// Sync the current file to disk and return the first retained error.
588    fn flush(&self) -> Result<()> {
589        crate::consumer::shared_runtime().block_on(self.do_flush())
590    }
591
592    /// Stop accepting events, sync and close the current file.
593    fn close(&self) -> Result<()> {
594        crate::consumer::shared_runtime().block_on(self.do_close())
595    }
596}
597
598#[cfg(feature = "async")]
599#[async_trait::async_trait]
600impl AsyncConsumer for LogConsumer {
601    /// Serialize and enqueue the event; the streaming writer task performs
602    /// the file I/O, so this method never blocks the caller's task.
603    async fn add_async(&self, data: &Data) -> Result<()> {
604        self.do_add(data).await
605    }
606
607    /// Sync the current file to disk and return the first retained error.
608    async fn flush_async(&self) -> Result<()> {
609        self.do_flush().await
610    }
611
612    /// Stop accepting events, sync and close the current file.
613    async fn close_async(&self) -> Result<()> {
614        self.do_close().await
615    }
616}
617
618#[cfg(all(test, feature = "blocking"))]
619mod tests {
620    use super::*;
621    use crate::DataType;
622    use serde_json::json;
623
624    fn temp_dir(tag: &str) -> String {
625        let dir = std::env::temp_dir().join(format!(
626            "thinkingdata-log-test-{tag}-{}",
627            std::process::id()
628        ));
629        let _ = std::fs::remove_dir_all(&dir);
630        dir.to_string_lossy().into_owned()
631    }
632
633    fn event() -> Data {
634        let mut data = Data::new(DataType::Track);
635        data.account_id = "acc".to_string();
636        data.event_name = "purchase".to_string();
637        data.properties.insert("price".to_string(), json!(9.9));
638        data
639    }
640
641    #[test]
642    fn writes_one_json_object_per_line() {
643        let dir = temp_dir("lines");
644        let consumer = LogConsumer::new(&dir).unwrap();
645        consumer.add(&event()).unwrap();
646        consumer.close().unwrap();
647
648        let mut entries: Vec<_> = std::fs::read_dir(&dir)
649            .unwrap()
650            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
651            .collect();
652        entries.sort();
653        assert_eq!(entries.len(), 1);
654        assert!(entries[0].starts_with("log.2"), "{entries:?}");
655
656        let content = std::fs::read_to_string(Path::new(&dir).join(&entries[0])).unwrap();
657        let lines: Vec<&str> = content.lines().collect();
658        assert_eq!(lines.len(), 1);
659        let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
660        assert_eq!(parsed["#type"], "track");
661        assert_eq!(parsed["properties"]["price"], 9.9);
662        let _ = std::fs::remove_dir_all(&dir);
663    }
664
665    #[test]
666    fn file_name_prefix_is_applied() {
667        let dir = temp_dir("prefix");
668        let consumer = LogConsumer::with_config(LogConsumerConfig {
669            directory: dir.clone(),
670            file_name_prefix: "ta".to_string(),
671            ..LogConsumerConfig::default()
672        })
673        .unwrap();
674        consumer.add(&event()).unwrap();
675        consumer.close().unwrap();
676
677        let entries: Vec<_> = std::fs::read_dir(&dir)
678            .unwrap()
679            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
680            .collect();
681        assert_eq!(entries.len(), 1);
682        assert!(entries[0].starts_with("ta.log."), "{entries:?}");
683        let _ = std::fs::remove_dir_all(&dir);
684    }
685
686    #[test]
687    fn size_paging_creates_indexed_files() {
688        let dir = temp_dir("paging");
689        let consumer = LogConsumer::with_config(LogConsumerConfig {
690            directory: dir.clone(),
691            file_size_mb: 1,
692            ..LogConsumerConfig::default()
693        })
694        .unwrap();
695        let mut big = event();
696        big.properties
697            .insert("padding".to_string(), json!("x".repeat(1024 * 1024 + 128)));
698        consumer.add(&big).unwrap();
699        consumer.add(&event()).unwrap();
700        consumer.close().unwrap();
701
702        let mut entries: Vec<_> = std::fs::read_dir(&dir)
703            .unwrap()
704            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
705            .collect();
706        entries.sort();
707        assert_eq!(entries.len(), 2, "{entries:?}");
708        assert!(entries[0].ends_with("_0"), "{entries:?}");
709        assert!(entries[1].ends_with("_1"), "{entries:?}");
710
711        // The second event must have landed in file _1.
712        let second = std::fs::read_to_string(Path::new(&dir).join(&entries[1])).unwrap();
713        assert!(second.contains("\"purchase\""), "{second}");
714        let _ = std::fs::remove_dir_all(&dir);
715    }
716
717    #[test]
718    fn restore_file_index_resumes_at_max() {
719        let dir = temp_dir("restore");
720        std::fs::create_dir_all(&dir).unwrap();
721        let period = format_with(RotateMode::Daily.date_format());
722        std::fs::write(Path::new(&dir).join(format!("log.{period}_0")), "old\n").unwrap();
723        std::fs::write(Path::new(&dir).join(format!("log.{period}_3")), "old\n").unwrap();
724        std::fs::write(Path::new(&dir).join(format!("log.{period}_backup")), "").unwrap();
725
726        let mut index = 0usize;
727        restore_file_index(&dir, "", &period, &mut index).unwrap();
728        assert_eq!(index, 3);
729        let _ = std::fs::remove_dir_all(&dir);
730    }
731
732    #[test]
733    fn add_after_close_fails() {
734        let dir = temp_dir("closed");
735        let consumer = LogConsumer::new(&dir).unwrap();
736        consumer.close().unwrap();
737        let err = consumer.add(&event()).unwrap_err();
738        assert!(err.to_string().contains("closed"), "{err}");
739        // close is idempotent and repeats the retained result.
740        consumer.close().unwrap();
741        let _ = std::fs::remove_dir_all(&dir);
742    }
743
744    #[test]
745    fn go_rotate_mode_validation() {
746        assert_eq!(RotateMode::from_go(0).unwrap(), RotateMode::Daily);
747        assert_eq!(RotateMode::from_go(1).unwrap(), RotateMode::Hourly);
748        assert!(RotateMode::from_go(2).is_err());
749    }
750
751    #[test]
752    fn local_time_is_used_for_period() {
753        // Sanity: the daily/hourly patterns produce the documented shapes.
754        let daily = format_with(RotateMode::Daily.date_format());
755        assert_eq!(daily.len(), 10, "{daily}");
756        let hourly = format_with(RotateMode::Hourly.date_format());
757        assert_eq!(hourly.len(), 13, "{hourly}");
758    }
759}