Skip to main content

dm_database_sqllog2db/cli/watch/
state.rs

1//! Watch 主循环运行时状态(`WatchLoopState`)及两个节流/防抖常量。
2
3use crate::error::ErrorStats;
4use std::collections::HashMap;
5use std::path::PathBuf;
6use std::time::{Duration, Instant};
7
8/// macOS `FSEvents` 与 Linux inotify 同一写操作会先发 `Create(File)` 再发
9/// `Modify(Data(Content))` 两个事件。500ms 窗口内同路径第二个事件被丢弃,
10/// 确保 `handle_run` 只触发一次,消除统计虚高与 append 模式重复行。
11pub(super) const DEBOUNCE_WINDOW: Duration = Duration::from_millis(500);
12
13/// 状态行刷新节流间隔:避免频繁调用 `pb.set_message` 导致 spinner 抖动。
14/// 200ms 间隔在视觉上足够流畅,同时不引入额外 CPU 开销。
15pub(super) const STATUS_REFRESH_INTERVAL: Duration = Duration::from_millis(200);
16
17/// Watch 主循环运行时状态(合并多个可变字段,减少参数列表长度)。
18#[derive(Debug)]
19pub struct WatchLoopState {
20    pub(super) last_trigger_at: Option<Instant>,
21    pub(super) last_status_refresh: Instant,
22    pub(super) debounce_map: HashMap<PathBuf, Instant>,
23    pub(super) total_stats: ErrorStats,
24    pub(super) trigger_count: u64,
25    /// Phase 70 新增(per D-12):路径→字节偏移映射,用于增量处理。
26    pub(super) file_offsets: HashMap<PathBuf, u64>,
27    /// Phase 70 新增(per D-12):SQLite 数据库 URL,`None` 表示未使用 `SqliteExporter`。
28    pub(super) sqlite_db_url: Option<String>,
29}
30
31impl WatchLoopState {
32    /// 构造 `WatchLoopState`,接受初始偏移映射与可选 `SQLite` 数据库 URL。
33    #[must_use]
34    pub fn new(init_offsets: HashMap<PathBuf, u64>, sqlite_db_url: Option<String>) -> Self {
35        Self {
36            last_trigger_at: None,
37            last_status_refresh: Instant::now(),
38            debounce_map: HashMap::new(),
39            total_stats: ErrorStats::default(),
40            trigger_count: 0u64,
41            file_offsets: init_offsets,
42            sqlite_db_url,
43        }
44    }
45
46    /// 返回当前 `trigger_count`(全量 + 增量触发次数之和)。
47    #[must_use]
48    pub fn trigger_count(&self) -> u64 {
49        self.trigger_count
50    }
51
52    /// 返回总错误统计。
53    #[must_use]
54    pub fn total_stats(&self) -> &ErrorStats {
55        &self.total_stats
56    }
57
58    /// 返回路径→字节偏移映射(用于集成测试验证 offset 持久化)。
59    #[must_use]
60    #[allow(dead_code)]
61    pub fn file_offsets(&self) -> &HashMap<PathBuf, u64> {
62        &self.file_offsets
63    }
64}