fsmon 0.4.8

Lightweight High-Performance File System Change Tracking Tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
use anyhow::{Context, Result, bail};
use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::os::fd::AsRawFd;
use std::path::PathBuf;
use std::time::Duration;

use lru::LruCache;
use tokio::io::AsyncBufReadExt;
use tokio::io::unix::AsyncFd;
use tokio::signal::unix::{SignalKind, signal};

use moka::sync::Cache;

use crate::FileEvent;
use crate::config::ResolvedCacheConfig;
use crate::fid_parser::FsGroup;
use crate::filters::{self, PathOptions};
use crate::metrics::MetricsRegistry;
use crate::monitored::PathEntry;
use crate::proc_cache::{self, DefaultCache as ProcCache, DefaultTree as PidTree};
use crate::watchdog::Watchdog;
use serde_json;
use slotmap::SlotMap;

/// Key type for FsGroup SlotMap lookups.
pub(crate) type FsGroupKey = slotmap::DefaultKey;

// ---- Debug logging macro ----
// Avoids format!() allocation when debug is disabled.
macro_rules! debug_log {
    ($debug:expr, $($arg:tt)*) => {
        if $debug { eprintln!("[DEBUG] {}", format!($($arg)*)); }
    };
}

// ---- Submodules ----

mod channel;
mod events;
mod file_writer;
mod filtering;
mod init;
mod live_path;
mod reader;
mod socket_handler;

pub(crate) use channel::{EventReceiver, EventSender};
pub(crate) use events::PendingEvent;
pub(crate) use file_writer::FileLogWriter;
pub(crate) use reader::ReaderState;
#[cfg(test)]
pub(crate) use socket_handler::chains_contain;
pub(crate) use socket_handler::tokio_io_oneshot;

// ---- MonitorConfig ----

/// Configuration for creating a Monitor instance.
pub struct MonitorConfig {
    pub paths_and_options: Vec<(PathBuf, PathOptions)>,
    pub log_dir: Option<PathBuf>,
    pub monitored_path: Option<PathBuf>,
    pub buffer_size: Option<usize>,
    pub socket_listener: Option<tokio::net::UnixListener>,
    pub debug: bool,
    pub cache_config: Option<ResolvedCacheConfig>,
    pub disk_min_free: Option<String>,
    pub sync_interval: Option<std::time::Duration>,
    pub subscribe_buf: Option<usize>,
    pub local_time: bool,
    pub metrics_interval: Option<u64>,
    pub watchdog_interval: Option<u64>,
}

// ---- Monitor ----

pub struct Monitor {
    pub(crate) paths: Vec<PathBuf>,
    pub(crate) canonical_paths: Vec<PathBuf>,
    /// Full list of (path, PathOptions) preserving duplicates across cmd groups.
    /// This is the single source of truth for path options.
    pub(crate) monitored_entries: Vec<(PathBuf, PathOptions)>,
    pub(crate) log_dir: Option<PathBuf>,
    pub(crate) monitored_path: Option<PathBuf>,
    pub(crate) proc_cache: Option<ProcCache>,
    pub(crate) pid_tree: Option<PidTree>,
    pub(crate) file_size_cache: LruCache<PathBuf, u64>,
    pub(crate) buffer_size: usize,
    pub(crate) socket_listener: Option<tokio::net::UnixListener>,
    /// One `FsGroup` per unique filesystem (fan_fd + mount_fd dedup'd).
    /// Uses SlotMap for stable keys — removal doesn't invalidate other keys.
    pub(crate) fs_groups: SlotMap<FsGroupKey, FsGroup>,
    /// Maps monitored path → key in fs_groups for fast lookup in remove_path
    pub(crate) path_to_group: HashMap<PathBuf, FsGroupKey>,
    pub(crate) dir_cache: Cache<fanotify_fid::types::HandleKey, PathBuf>,
    /// Shared state for spawning reader tasks during live-add (set in run())
    pub(crate) event_tx: Option<EventSender>,
    pub(crate) shared_dir_cache: Option<Cache<fanotify_fid::types::HandleKey, PathBuf>>,
    /// Paths that didn't exist at add/startup time, retried on directory creation
    pub(crate) pending_paths: Vec<(PathBuf, PathEntry)>,
    /// inotify instance watching parent dirs of pending paths
    pub(crate) inotify: Option<inotify::Inotify>,
    /// Watch descriptors kept alive so watches stay active
    /// (watched_path, watch_descriptor) — maps wd back to the directory we're watching.
    pub(crate) _inotify_watches: Vec<(PathBuf, inotify::WatchDescriptor)>,
    /// PID of the fsmon daemon itself — events from this PID (or its children)
    /// are discarded to prevent self-triggering feedback loops.
    pub(crate) daemon_pid: u32,
    /// Resolved cache configuration (capacity, TTL, buffer size).
    pub(crate) cache_config: ResolvedCacheConfig,
    /// Enable debug output
    pub(crate) debug: bool,
    /// Death notifications from reader tasks: each sends its group key on exit.
    pub(crate) reader_death_rx: tokio::sync::mpsc::UnboundedReceiver<FsGroupKey>,
    /// Cloneable sender for reader tasks to signal death.
    pub(crate) reader_death_tx: tokio::sync::mpsc::UnboundedSender<FsGroupKey>,
    /// Per-group restart tracking (keyed by FsGroupKey).
    pub(crate) reader_states: HashMap<FsGroupKey, ReaderState>,
    /// Daemon start time, set in run() for uptime calculation.
    pub(crate) started_at: std::time::Instant,
    /// Raw disk-min-free threshold string (e.g. "10%", "5GB"). None = no check.
    disk_min_free: Option<String>,
    /// Log file sync interval. None = disabled.
    sync_interval: Option<std::time::Duration>,
    /// Metrics report interval. None = disabled.
    metrics_interval: Option<std::time::Duration>,

    /// Unified event stream: broadcast channel for all consumers.
    /// Carries (FileEvent, cmd_name) — cmd_name is for file routing.
    /// Subscribe tasks extract FileEvent, file writer uses both.
    pub(crate) event_stream_tx: Option<tokio::sync::broadcast::Sender<(FileEvent, String)>>,
    /// Use local time instead of UTC in timestamp serialization.
    pub(crate) local_time: bool,
    /// Atomic metrics counters (thread-safe, cloneable).
    pub(crate) metrics: MetricsRegistry,
    /// Temporary fanotify marks on parent directories of deleted-and-pending
    /// paths, so that events during the recreate window aren't lost.
    /// Maps: target_pending_path → (parent_path, key in fs_groups)
    pub(crate) temp_parent_marks: HashMap<PathBuf, (PathBuf, FsGroupKey)>,
    /// Watchdog manager for systemd integration.
    pub(crate) watchdog: Option<Watchdog>,
}

impl Monitor {
    #[allow(clippy::too_many_arguments)]
    fn new(
        paths_and_options: Vec<(PathBuf, PathOptions)>,
        log_dir: Option<PathBuf>,
        monitored_path: Option<PathBuf>,
        buffer_size: Option<usize>,
        socket_listener: Option<tokio::net::UnixListener>,
        debug: bool,
        cache_config: Option<ResolvedCacheConfig>,
        disk_min_free: Option<String>,
        sync_interval: Option<std::time::Duration>,
        subscribe_buf: Option<usize>,
        local_time: bool,
        metrics_interval: Option<u64>,
        watchdog_interval: Option<u64>,
    ) -> Result<Self> {
        let cache_config = cache_config.unwrap_or_default();
        let buffer_size = buffer_size.unwrap_or(cache_config.buffer_size);

        if buffer_size < 4096 {
            bail!("buffer_size must be at least 4096 bytes (4KB)");
        }
        if buffer_size > 1024 * 1024 {
            bail!("buffer_size must not exceed 1048576 bytes (1MB)");
        }

        let mut paths = Vec::new();
        let mut seen = std::collections::HashSet::new();
        let mut monitored_entries = Vec::new();
        let log_dir_canonical = log_dir
            .as_ref()
            .map(|d| d.canonicalize().unwrap_or_else(|_| d.clone()));
        for (path, opts) in &paths_and_options {
            // Reject paths that overlap with the log directory.
            let resolved = filters::resolve_recursion_check(path);
            if let Some(ref log_dir) = log_dir_canonical {
                let is_exact = log_dir.as_path() == resolved;
                let is_parent_recursive = opts.recursive && log_dir.starts_with(&resolved);
                if is_exact || is_parent_recursive {
                    bail!(
                        "Cannot monitor '{}': {} — \
                         Tip: use a path outside the log directory, or use a different logging.path",
                        path.display(),
                        if is_exact {
                            "this path is the log directory itself".to_string()
                        } else {
                            format!("log directory '{}' is inside this path", log_dir.display())
                        },
                    );
                }
            }
            // Reject cmd=fsmon
            if opts.cmd.as_deref() == Some("fsmon") {
                bail!(
                    "Cannot monitor 'fsmon' process: fsmon daemon's own events \
                    are excluded from monitoring."
                );
            }
            // Same path under multiple cmd groups → fanotify dedup by path only
            if seen.insert(resolved.clone()) {
                paths.push(resolved.clone());
            }
            // Full list preserves duplicates for matching (single source of truth)
            monitored_entries.push((resolved.clone(), opts.clone()));
        }

        let (reader_death_tx, reader_death_rx) =
            tokio::sync::mpsc::unbounded_channel::<FsGroupKey>();

        let monitor = Self {
            paths,
            canonical_paths: Vec::new(),
            monitored_entries,
            log_dir,
            monitored_path,
            proc_cache: None,
            pid_tree: None,
            file_size_cache: LruCache::new(
                NonZeroUsize::new(cache_config.file_size_capacity).unwrap(),
            ),
            buffer_size,

            dir_cache: Cache::builder()
                .max_capacity(cache_config.dir_capacity)
                .time_to_live(Duration::from_secs(cache_config.dir_ttl_secs))
                .build(),
            cache_config,
            socket_listener,
            debug,
            fs_groups: SlotMap::new(),
            path_to_group: HashMap::new(),
            event_tx: None,
            shared_dir_cache: None,
            pending_paths: Vec::new(),
            inotify: None,
            _inotify_watches: Vec::new(), // (path, wd)
            daemon_pid: std::process::id(),
            reader_death_rx,
            reader_death_tx,
            reader_states: HashMap::new(),
            started_at: std::time::Instant::now(),
            disk_min_free,
            sync_interval,
            metrics_interval: metrics_interval
                .filter(|&n| n > 0)
                .map(std::time::Duration::from_secs),
            event_stream_tx: {
                let cap = subscribe_buf.unwrap_or(4096).max(1);
                let (tx, _) = tokio::sync::broadcast::channel::<(FileEvent, String)>(cap);
                Some(tx)
            },
            local_time,
            metrics: MetricsRegistry::new(metrics_interval.is_some()),
            temp_parent_marks: HashMap::new(),
            watchdog: Some(Watchdog::new(watchdog_interval)),
        };
        if debug {
            eprintln!(
                "[DEBUG] Monitor initialized with {} path entries:",
                paths_and_options.len()
            );
            for (i, (p, o)) in paths_and_options.iter().enumerate() {
                let label = o.cmd.as_deref().unwrap_or("global");
                eprintln!(
                    "[DEBUG]   [{}] {} cmd={} recursive={}",
                    i,
                    p.display(),
                    label,
                    o.recursive
                );
            }
            eprintln!("[DEBUG] log_dir: {:?}", monitor.log_dir);
            eprintln!("[DEBUG] buffer_size: {}", buffer_size);
        }
        Ok(monitor)
    }

    /// Construct a Monitor from a MonitorConfig struct.
    pub fn from_config(cfg: MonitorConfig) -> Result<Self> {
        Self::new(
            cfg.paths_and_options,
            cfg.log_dir,
            cfg.monitored_path,
            cfg.buffer_size,
            cfg.socket_listener,
            cfg.debug,
            cfg.cache_config,
            cfg.disk_min_free,
            cfg.sync_interval,
            cfg.subscribe_buf,
            cfg.local_time,
            cfg.metrics_interval,
            cfg.watchdog_interval,
        )
    }

    pub async fn run(&mut self) -> Result<()> {
        self.check_root()?;

        // Initialize process cache and pid tree
        let proc_conn = self.init_process_cache();

        // Initialize fanotify: masks, fs_groups, pending paths, inotify
        let fan_group_count = self.init_fanotify()?;

        // Initialize logging: log dir, chown, disk check
        self.init_logging()?;

        // Print startup status and metrics
        self.print_startup_status(fan_group_count);

        // Spawn reader tasks and file writer
        let (mut event_rx, dir_cache) = self.spawn_tasks();

        // --- Signal handlers ---
        let mut sigterm =
            signal(SignalKind::terminate()).context("failed to create SIGTERM signal handler")?;
        let mut sighup =
            signal(SignalKind::hangup()).context("failed to create SIGHUP signal handler")?;

        let socket_listener = self.socket_listener.take();

        // Build inotify AsyncFd for tokio event loop
        let inotify_async = self.inotify.as_ref().map(|ino| {
            let fd = ino.as_raw_fd();
            AsyncFd::new(crate::fid_parser::FanFd(fd)).expect("inotify AsyncFd")
        });

        // Build proc connector AsyncFd for tokio event loop
        let proc_afd = proc_conn.and_then(|conn| {
            let fd = conn.as_raw_fd();
            match AsyncFd::new(conn) {
                Ok(a) => Some(a),
                Err(e) => {
                    eprintln!("[ERROR] AsyncFd for proc connector fd {}: {}", fd, e);
                    None
                }
            }
        });
        let mut proc_buf = vec![0u8; 65536];

        // Clone caches for event loop use
        let proc_cache = self.proc_cache.clone().unwrap();
        let pid_tree = self.pid_tree.clone().unwrap();

        // Move the reader death receiver out of self so tokio::select! can use it.
        let mut reader_death_rx = std::mem::replace(
            &mut self.reader_death_rx,
            tokio::sync::mpsc::unbounded_channel::<FsGroupKey>().1,
        );

        // Notify systemd: READY=1
        if let Err(e) = crate::watchdog::sd_notify(libsystemd::daemon::NotifyState::Ready) {
            eprintln!("[WARNING] systemd notify READY failed: {}", e);
        }

        // Heartbeat tick: integrated into the main event loop (not a separate task).
        // If the main loop blocks, this tick won't fire → systemd times out → restart.
        let mut heartbeat_tick: Option<tokio::time::Interval> =
            self.watchdog.as_ref().and_then(|wd| {
                if !wd.is_enabled() {
                    return None;
                }
                if self.debug {
                    debug_log!(
                        self.debug,
                        "systemd watchdog enabled (interval: {}s, heartbeat in main loop)",
                        wd.interval().as_secs()
                    );
                }
                // First tick fires after one interval (not immediately).
                let start = tokio::time::Instant::now() + wd.interval();
                Some(tokio::time::interval_at(start, wd.interval()))
            });

        let mut metrics_tick: Option<tokio::time::Interval> =
            self.metrics_interval.map(tokio::time::interval);

        // --- Main event loop ---
        loop {
            tokio::select! {
                Some(events) = event_rx.recv() => {
                    self.drain_proc_events(&proc_afd, &mut proc_buf, &proc_cache, &pid_tree);
                    let mut pending = self.process_event_batch(&events);
                    self.drain_proc_events(&proc_afd, &mut proc_buf, &proc_cache, &pid_tree);
                    self.patch_pending_events(&mut pending);
                    self.send_pending_events(&pending);
                    self.check_pending();
                }
                _ = tokio::signal::ctrl_c() => {
                    self.drain_remaining_events(&mut event_rx, &proc_afd, &mut proc_buf, &proc_cache, &pid_tree);
                    break;
                }
                _ = sigterm.recv() => {
                    self.drain_remaining_events(&mut event_rx, &proc_afd, &mut proc_buf, &proc_cache, &pid_tree);
                    break;
                }
                _ = sighup.recv() => {
                    if let Err(e) = self.reload_config() {
                        eprintln!("Config reload error: {e}");
                    }
                }

                _ = async {
                    match metrics_tick.as_mut() {
                        Some(t) => t.tick().await,
                        None => std::future::pending().await,
                    }
                } => {
                    let report = self.collect_metrics(&dir_cache, &proc_cache, &pid_tree);
                    eprintln!(
                        "[metrics] uptime={}s rss={:.1}MB caches(d/p/t/f)={}/{}/{}/{} readers={}/{}/{} subs={} paths={} pending={} disk_buf={}",
                        report.uptime_secs,
                        report.rss_mb,
                        report.dir_cache_entries,
                        report.proc_cache_entries,
                        report.pid_tree_entries,
                        report.file_size_cache_entries,
                        report.reader_groups_total,
                        report.reader_groups_alive,
                        report.reader_groups_gave_up,
                        report.subscribers,
                        report.monitored_paths,
                        report.pending_paths,
                        report.disk_buffer_events,
                    );
                }

                // Watchdog heartbeat: fires only when the main event loop is responsive.
                // If any synchronous operation blocks the loop, this tick won't fire
                // and systemd will restart the service after WatchdogSec timeout.
                _ = async {
                    match heartbeat_tick.as_mut() {
                        Some(t) => t.tick().await,
                        None => std::future::pending().await,
                    }
                } => {
                    if let Some(ref wd) = self.watchdog
                        && let Err(e) = wd.send_heartbeat()
                    {
                        eprintln!("[ERROR] systemd watchdog notify failed: {}", e);
                    }
                }

                proc_readable = async {
                    match proc_afd.as_ref() {
                        Some(afd) => afd.readable().await,
                        None => std::future::pending().await,
                    }
                } => {
                    if let Ok(mut guard) = proc_readable {
                        loop {
                            match guard.get_inner().recv_raw(&mut proc_buf) {
                                Ok(n) => {
                                    proc_cache::handle_proc_events(&proc_cache, &pid_tree, &proc_buf, n);
                                }
                                Err(proc_connector::Error::WouldBlock) => break,
                                Err(proc_connector::Error::Interrupted) => continue,
                                Err(e) => {
                                    eprintln!("proc connector error: {e}");
                                    break;
                                }
                            }
                        }
                        guard.clear_ready();
                    }
                }
                inotify_ready = async {
                    match inotify_async.as_ref() {
                        Some(afd) => afd.readable().await,
                        None => std::future::pending().await,
                    }
                } => {
                    debug_log!(self.debug, "inotify fd became readable");
                    if let Ok(mut guard) = inotify_ready {
                        self.handle_inotify_events();
                        guard.clear_ready();
                    }
                }
                accept_result = async {
                    match socket_listener.as_ref() {
                        Some(listener) => Self::accept_socket_connection(listener).await,
                        None => std::future::pending().await,
                    }
                } => {
                    self.handle_socket_accept(accept_result).await;
                }
                Some(dead_idx) = reader_death_rx.recv() => {
                    self.restart_reader(dead_idx);
                }
            }
        }

        println!("\nStopping file trace monitor...");
        drop(self.event_stream_tx.take());
        Ok(())
    }

    /// Collect runtime metrics for periodic reporting.
    pub(crate) fn collect_metrics(
        &self,
        dir_cache: &moka::sync::Cache<fanotify_fid::types::HandleKey, std::path::PathBuf>,
        proc_cache: &ProcCache,
        pid_tree: &PidTree,
    ) -> MetricsReport {
        let reader_groups_alive = self.reader_states.values().filter(|s| !s.gave_up).count() as u64;
        let reader_groups_gave_up =
            self.reader_states.values().filter(|s| s.gave_up).count() as u64;

        MetricsReport {
            uptime_secs: self.started_at.elapsed().as_secs(),
            rss_mb: get_rss_mb(),
            dir_cache_entries: dir_cache.entry_count(),
            proc_cache_entries: proc_cache.len() as u64,
            pid_tree_entries: pid_tree.len() as u64,
            file_size_cache_entries: self.file_size_cache.len() as u64,
            reader_groups_total: self.fs_groups.len() as u64,
            reader_groups_alive,
            reader_groups_gave_up,
            subscribers: self.metrics.subscribers() as u64,
            monitored_paths: self.metrics.monitored_paths() as u64,
            pending_paths: self.metrics.pending_paths() as u64,
            disk_buffer_events: self.metrics.disk_buffer_events() as u64,
        }
    }

    /// Publish pending events to the broadcast stream.
    fn send_pending_events(&self, pending: &[PendingEvent]) {
        if let Some(ref tx) = self.event_stream_tx {
            for pe in pending {
                let _ = tx.send((pe.event.clone(), pe.cmd_name.clone()));
            }
        }
    }

    /// Drain all pending proc connector events into the caches.
    fn drain_proc_events(
        &self,
        proc_afd: &Option<AsyncFd<proc_connector::ProcConnector>>,
        proc_buf: &mut [u8],
        proc_cache: &ProcCache,
        pid_tree: &PidTree,
    ) {
        if let Some(afd) = proc_afd.as_ref() {
            let conn = afd.get_ref();
            loop {
                match conn.recv_raw(proc_buf) {
                    Ok(n) => {
                        proc_cache::handle_proc_events(proc_cache, pid_tree, proc_buf, n);
                    }
                    Err(proc_connector::Error::WouldBlock) => break,
                    Err(proc_connector::Error::Interrupted) => continue,
                    Err(e) => {
                        eprintln!("proc connector error: {e}");
                        break;
                    }
                }
            }
        }
    }

    /// Drain remaining events from the channel and process them before shutdown.
    fn drain_remaining_events(
        &mut self,
        event_rx: &mut EventReceiver,
        proc_afd: &Option<AsyncFd<proc_connector::ProcConnector>>,
        proc_buf: &mut [u8],
        proc_cache: &ProcCache,
        pid_tree: &PidTree,
    ) {
        while let Ok(events) = event_rx.try_recv() {
            self.drain_proc_events(proc_afd, proc_buf, proc_cache, pid_tree);
            let mut pending = self.process_event_batch(&events);
            self.patch_pending_events(&mut pending);
            self.send_pending_events(&pending);
        }
    }

    /// Accept a socket connection and read the command message.
    async fn accept_socket_connection(
        listener: &tokio::net::UnixListener,
    ) -> Result<(tokio::net::unix::OwnedWriteHalf, String), std::io::Error> {
        let (stream, _) = listener.accept().await?;
        let (reader, writer) = stream.into_split();
        let mut buf_reader = tokio::io::BufReader::new(reader);
        let mut message = String::new();
        loop {
            let mut line = String::new();
            let bytes = buf_reader.read_line(&mut line).await?;
            if bytes == 0 {
                break;
            }
            if line.trim().is_empty() && !message.is_empty() {
                break;
            }
            message.push_str(&line);
        }
        Ok((writer, message.trim().to_string()))
    }

    /// Handle an accepted socket connection: parse command and dispatch.
    async fn handle_socket_accept(
        &mut self,
        result: Result<(tokio::net::unix::OwnedWriteHalf, String), std::io::Error>,
    ) {
        match result {
            Ok((writer, cmd_str)) => {
                let cmd = match serde_json::from_str::<crate::socket::SocketCmd>(&cmd_str) {
                    Ok(c) => c,
                    Err(e) => {
                        let resp: Result<
                            crate::socket::SocketResponse,
                            crate::socket::SocketError,
                        > = Err(crate::socket::SocketError::Transient(format!(
                            "Invalid command: {e}"
                        )));
                        if let Ok(json_str) = serde_json::to_string(&resp) {
                            let _ = tokio_io_oneshot(writer, &format!("{json_str}\n")).await;
                        }
                        return;
                    }
                };
                if let crate::socket::SocketCmd::Subscribe { .. } = cmd {
                    self.handle_subscribe(writer, &cmd);
                } else {
                    let result = self.handle_socket_cmd(cmd);
                    if let Ok(json_str) = serde_json::to_string(&result) {
                        let resp_bytes = format!("{json_str}\n");
                        let _ = tokio_io_oneshot(writer, &resp_bytes).await;
                    }
                }
            }
            Err(e) => eprintln!("Socket accept error: {e}"),
        }
    }
}

/// Snapshot of daemon runtime metrics for periodic reporting.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct MetricsReport {
    pub uptime_secs: u64,
    pub rss_mb: f64,
    pub dir_cache_entries: u64,
    pub proc_cache_entries: u64,
    pub pid_tree_entries: u64,
    pub file_size_cache_entries: u64,
    pub reader_groups_total: u64,
    pub reader_groups_alive: u64,
    pub reader_groups_gave_up: u64,
    pub subscribers: u64,
    pub monitored_paths: u64,
    pub pending_paths: u64,
    pub disk_buffer_events: u64,
}

/// Read current RSS in MB from /proc/self/statm.
fn get_rss_mb() -> f64 {
    std::fs::read_to_string("/proc/self/statm")
        .ok()
        .and_then(|s| {
            let parts: Vec<&str> = s.split_whitespace().collect();
            parts.get(1).and_then(|p| p.parse::<u64>().ok())
        })
        .map(|pages| (pages * 4096) as f64 / (1024.0 * 1024.0))
        .unwrap_or(0.0)
}

#[cfg(test)]
#[path = "tests.rs"]
mod tests;