denet 0.7.0

a simple process monitor
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
//! Monitoring utilities for common monitoring loop patterns
//!
//! This module provides reusable monitoring functionality to eliminate
//! code duplication across the codebase.

use crate::core::constants::{sampling, timeouts};
use crate::core::process_monitor::ProcessMonitor;
use crate::monitor::Metrics;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Configuration for monitoring loops
#[derive(Debug, Clone)]
pub struct MonitoringConfig {
    /// Interval between samples
    pub sample_interval: Duration,
    /// Optional timeout for the monitoring loop
    pub timeout: Option<Duration>,
    /// Whether to continue monitoring after process exits
    pub monitor_after_exit: bool,
    /// Additional samples to collect after process exits
    pub final_sample_count: u32,
    /// Delay between final samples
    pub final_sample_delay: Duration,
}

impl Default for MonitoringConfig {
    fn default() -> Self {
        Self {
            sample_interval: sampling::STANDARD,
            timeout: None,
            monitor_after_exit: false,
            final_sample_count: 0,
            final_sample_delay: crate::core::constants::delays::STANDARD,
        }
    }
}

impl MonitoringConfig {
    /// Create a new monitoring configuration
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the sample interval
    pub fn with_sample_interval(mut self, interval: Duration) -> Self {
        self.sample_interval = interval;
        self
    }

    /// Set the timeout
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Enable monitoring after process exit with specified sample count
    pub fn with_final_samples(mut self, count: u32, delay: Duration) -> Self {
        self.monitor_after_exit = true;
        self.final_sample_count = count;
        self.final_sample_delay = delay;
        self
    }

    /// Quick configuration for fast sampling
    pub fn fast_sampling() -> Self {
        Self::new().with_sample_interval(sampling::FAST)
    }

    /// Quick configuration for test scenarios
    pub fn for_tests() -> Self {
        Self::new()
            .with_sample_interval(sampling::FAST)
            .with_timeout(timeouts::TEST)
            .with_final_samples(5, crate::core::constants::delays::STANDARD)
    }
}

/// Result of a monitoring session
#[derive(Debug)]
pub struct MonitoringResult {
    /// All collected metrics samples
    pub samples: Vec<Metrics>,
    /// Total monitoring duration
    pub duration: Duration,
    /// Whether monitoring was stopped due to timeout
    pub timed_out: bool,
    /// Whether monitoring was interrupted by signal
    pub interrupted: bool,
}

impl MonitoringResult {
    /// Get the last sample if available
    pub fn last_sample(&self) -> Option<&Metrics> {
        self.samples.last()
    }

    /// Get the first sample if available
    pub fn first_sample(&self) -> Option<&Metrics> {
        self.samples.first()
    }

    /// Check if any samples were collected
    pub fn has_samples(&self) -> bool {
        !self.samples.is_empty()
    }

    /// Get sample count
    pub fn sample_count(&self) -> usize {
        self.samples.len()
    }
}

/// A reusable monitoring loop that eliminates common duplication
pub struct MonitoringLoop {
    config: MonitoringConfig,
    interrupt_signal: Option<Arc<AtomicBool>>,
}

impl MonitoringLoop {
    /// Create a new monitoring loop with default configuration
    pub fn new() -> Self {
        Self {
            config: MonitoringConfig::default(),
            interrupt_signal: None,
        }
    }

    /// Create a monitoring loop with specific configuration
    pub fn with_config(config: MonitoringConfig) -> Self {
        Self {
            config,
            interrupt_signal: None,
        }
    }

    /// Set an interrupt signal (e.g., for Ctrl+C handling)
    pub fn with_interrupt_signal(mut self, signal: Arc<AtomicBool>) -> Self {
        self.interrupt_signal = Some(signal);
        self
    }

    /// Run the monitoring loop with a custom processor function
    pub fn run_with_processor<F>(
        &self,
        mut monitor: ProcessMonitor,
        mut processor: F,
    ) -> MonitoringResult
    where
        F: FnMut(&Metrics),
    {
        let mut samples = Vec::new();
        let start_time = Instant::now();
        let mut timed_out = false;
        let mut interrupted = false;

        // Main monitoring loop
        while monitor.is_running() {
            // Check for timeout
            if let Some(timeout) = self.config.timeout {
                if start_time.elapsed() >= timeout {
                    timed_out = true;
                    break;
                }
            }

            // Check for interrupt signal
            if let Some(ref signal) = self.interrupt_signal {
                if !signal.load(Ordering::SeqCst) {
                    interrupted = true;
                    break;
                }
            }

            // Sample metrics
            if let Some(metrics) = monitor.sample_metrics() {
                processor(&metrics);
                samples.push(metrics);
            }

            // Sleep between samples
            std::thread::sleep(self.config.sample_interval);
        }

        // Collect final samples if configured
        if self.config.monitor_after_exit && self.config.final_sample_count > 0 {
            for _ in 0..self.config.final_sample_count {
                std::thread::sleep(self.config.final_sample_delay);
                if let Some(metrics) = monitor.sample_metrics() {
                    processor(&metrics);
                    samples.push(metrics);
                }
            }
        }

        MonitoringResult {
            samples,
            duration: start_time.elapsed(),
            timed_out,
            interrupted,
        }
    }

    /// Run the monitoring loop and collect all samples
    pub fn run(&self, monitor: ProcessMonitor) -> MonitoringResult {
        self.run_with_processor(monitor, |_| {})
    }

    /// Run the monitoring loop with progress callback
    pub fn run_with_progress<F>(
        &self,
        monitor: ProcessMonitor,
        progress_callback: F,
    ) -> MonitoringResult
    where
        F: Fn(usize, &Metrics),
    {
        let mut sample_count = 0;
        self.run_with_processor(monitor, |metrics| {
            sample_count += 1;
            progress_callback(sample_count, metrics);
        })
    }
}

impl Default for MonitoringLoop {
    fn default() -> Self {
        Self::new()
    }
}

/// Quick function for simple monitoring scenarios
pub fn monitor_until_completion(
    monitor: ProcessMonitor,
    sample_interval: Duration,
    timeout: Option<Duration>,
) -> MonitoringResult {
    let config = MonitoringConfig::new().with_sample_interval(sample_interval);

    let config = if let Some(timeout) = timeout {
        config.with_timeout(timeout)
    } else {
        config
    };

    MonitoringLoop::with_config(config).run(monitor)
}

/// Quick function for test monitoring scenarios
pub fn monitor_for_test(monitor: ProcessMonitor) -> MonitoringResult {
    MonitoringLoop::with_config(MonitoringConfig::for_tests()).run(monitor)
}

/// Quick function for monitoring with progress output
pub fn monitor_with_progress<F>(
    monitor: ProcessMonitor,
    sample_interval: Duration,
    progress_callback: F,
) -> MonitoringResult
where
    F: Fn(usize, &Metrics),
{
    let config = MonitoringConfig::new().with_sample_interval(sample_interval);
    MonitoringLoop::with_config(config).run_with_progress(monitor, progress_callback)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::constants::delays;

    #[test]
    fn test_monitoring_config_builder() {
        let config = MonitoringConfig::new()
            .with_sample_interval(sampling::FAST)
            .with_timeout(timeouts::SHORT)
            .with_final_samples(3, delays::STANDARD);

        assert_eq!(config.sample_interval, sampling::FAST);
        assert_eq!(config.timeout, Some(timeouts::SHORT));
        assert_eq!(config.final_sample_count, 3);
        assert!(config.monitor_after_exit);
    }

    #[test]
    fn test_monitoring_config_presets() {
        let fast_config = MonitoringConfig::fast_sampling();
        assert_eq!(fast_config.sample_interval, sampling::FAST);

        let test_config = MonitoringConfig::for_tests();
        assert_eq!(test_config.sample_interval, sampling::FAST);
        assert_eq!(test_config.timeout, Some(timeouts::TEST));
        assert_eq!(test_config.final_sample_count, 5);
    }

    #[test]
    fn test_monitoring_result_methods() {
        let samples = vec![Metrics::default(), Metrics::default()];

        let result = MonitoringResult {
            samples,
            duration: Duration::from_secs(1),
            timed_out: false,
            interrupted: false,
        };

        assert!(result.has_samples());
        assert_eq!(result.sample_count(), 2);
        assert!(result.first_sample().is_some());
        assert!(result.last_sample().is_some());

        // Test empty result
        let empty_result = MonitoringResult {
            samples: vec![],
            duration: Duration::from_secs(0),
            timed_out: false,
            interrupted: false,
        };

        assert!(!empty_result.has_samples());
        assert_eq!(empty_result.sample_count(), 0);
        assert!(empty_result.first_sample().is_none());
        assert!(empty_result.last_sample().is_none());
    }

    #[test]
    fn test_monitoring_config_defaults() {
        let config = MonitoringConfig::default();
        assert_eq!(config.sample_interval, sampling::STANDARD);
        assert_eq!(config.timeout, None);
        assert!(!config.monitor_after_exit);
        assert_eq!(config.final_sample_count, 0);
        assert_eq!(config.final_sample_delay, delays::STANDARD);
    }

    #[test]
    fn test_monitoring_config_new() {
        let config = MonitoringConfig::new();
        assert_eq!(config.sample_interval, sampling::STANDARD);
        assert_eq!(config.timeout, None);
        assert!(!config.monitor_after_exit);
        assert_eq!(config.final_sample_count, 0);
        assert_eq!(config.final_sample_delay, delays::STANDARD);
    }

    #[test]
    fn test_monitoring_config_chaining() {
        let config = MonitoringConfig::new()
            .with_sample_interval(sampling::SLOW)
            .with_timeout(timeouts::MEDIUM)
            .with_final_samples(10, delays::SHORT);

        assert_eq!(config.sample_interval, sampling::SLOW);
        assert_eq!(config.timeout, Some(timeouts::MEDIUM));
        assert!(config.monitor_after_exit);
        assert_eq!(config.final_sample_count, 10);
        assert_eq!(config.final_sample_delay, delays::SHORT);
    }

    #[test]
    fn test_monitoring_loop_creation() {
        let loop1 = MonitoringLoop::new();
        assert_eq!(loop1.config.sample_interval, sampling::STANDARD);
        assert!(loop1.interrupt_signal.is_none());

        let config = MonitoringConfig::fast_sampling();
        let loop2 = MonitoringLoop::with_config(config.clone());
        assert_eq!(loop2.config.sample_interval, config.sample_interval);

        let interrupt = Arc::new(AtomicBool::new(true));
        let loop3 = MonitoringLoop::new().with_interrupt_signal(interrupt.clone());
        assert!(loop3.interrupt_signal.is_some());
    }

    #[test]
    fn test_monitoring_loop_default() {
        let loop1 = MonitoringLoop::default();
        let loop2 = MonitoringLoop::new();

        assert_eq!(loop1.config.sample_interval, loop2.config.sample_interval);
        assert_eq!(loop1.config.timeout, loop2.config.timeout);
    }

    #[test]
    fn test_monitoring_result_flags() {
        let result = MonitoringResult {
            samples: vec![],
            duration: Duration::from_secs(5),
            timed_out: true,
            interrupted: false,
        };

        assert!(result.timed_out);
        assert!(!result.interrupted);

        let result = MonitoringResult {
            samples: vec![],
            duration: Duration::from_secs(3),
            timed_out: false,
            interrupted: true,
        };

        assert!(!result.timed_out);
        assert!(result.interrupted);
    }

    #[test]
    fn test_convenience_functions_exist() {
        // These functions should exist and compile, but we can't easily test them
        // without a real ProcessMonitor instance. We test their signatures here.
        use std::time::Duration;

        // Test that the functions can be called (they'll fail due to no process, but that's OK)
        let dummy_monitor = match ProcessMonitor::new(
            vec!["true".to_string()],
            Duration::from_millis(100),
            Duration::from_millis(1000),
        ) {
            Ok(m) => m,
            Err(_) => return, // Skip test if we can't create a monitor
        };

        let _result = monitor_until_completion(
            dummy_monitor,
            Duration::from_millis(10),
            Some(Duration::from_millis(100)),
        );
    }

    #[test]
    fn test_configuration_edge_cases() {
        // Test with zero final samples (should not enable monitor_after_exit)
        let config = MonitoringConfig::new().with_final_samples(0, delays::STANDARD);

        assert!(config.monitor_after_exit); // It's still set to true by the method
        assert_eq!(config.final_sample_count, 0);

        // Test with very small intervals
        let config = MonitoringConfig::new().with_sample_interval(Duration::from_millis(1));

        assert_eq!(config.sample_interval, Duration::from_millis(1));

        // Test with very large timeout
        let config = MonitoringConfig::new().with_timeout(Duration::from_secs(3600));

        assert_eq!(config.timeout, Some(Duration::from_secs(3600)));
    }

    #[test]
    fn test_monitoring_loop_with_processor() {
        use std::sync::atomic::AtomicUsize;
        use std::sync::Arc;

        // Use the current process for a more reliable test
        let monitor = match ProcessMonitor::from_pid_with_options(
            std::process::id() as usize,
            Duration::from_millis(10),
            Duration::from_millis(50),
            false,
        ) {
            Ok(m) => m,
            Err(_) => return, // Skip test if we can't create a monitor
        };

        let config = MonitoringConfig::new()
            .with_sample_interval(Duration::from_millis(10))
            .with_timeout(Duration::from_millis(100));

        let loop1 = MonitoringLoop::with_config(config);
        let counter = Arc::new(AtomicUsize::new(0));
        let counter_clone = counter.clone();

        let result = loop1.run_with_processor(monitor, |_metrics| {
            counter_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        });

        // Should timeout since we're monitoring the current process with a timeout
        assert!(result.timed_out || result.sample_count() > 0);
    }

    #[test]
    fn test_monitoring_loop_with_interrupt() {
        let monitor = match ProcessMonitor::from_pid_with_options(
            std::process::id() as usize,
            Duration::from_millis(10),
            Duration::from_millis(50),
            false,
        ) {
            Ok(m) => m,
            Err(_) => return, // Skip test if we can't create a monitor
        };

        let interrupt_signal = Arc::new(AtomicBool::new(true));
        let interrupt_clone = interrupt_signal.clone();

        let config = MonitoringConfig::new()
            .with_sample_interval(Duration::from_millis(10))
            .with_timeout(Duration::from_millis(1000));

        let monitoring_loop =
            MonitoringLoop::with_config(config).with_interrupt_signal(interrupt_signal);

        // Set interrupt signal to false to trigger interruption
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(50));
            interrupt_clone.store(false, std::sync::atomic::Ordering::SeqCst);
        });

        let result = monitoring_loop.run(monitor);

        // Should be interrupted or have some samples
        assert!(result.interrupted || result.sample_count() > 0);
    }

    #[test]
    fn test_monitoring_loop_with_final_samples() {
        let monitor = match ProcessMonitor::new(
            vec!["true".to_string()],
            Duration::from_millis(10),
            Duration::from_millis(50),
        ) {
            Ok(m) => m,
            Err(_) => return, // Skip test if we can't create a monitor
        };

        let config = MonitoringConfig::new()
            .with_sample_interval(Duration::from_millis(10))
            .with_timeout(Duration::from_millis(100))
            .with_final_samples(2, Duration::from_millis(10));

        let monitoring_loop = MonitoringLoop::with_config(config);
        let result = monitoring_loop.run(monitor);

        // Should have timed out or completed
        assert!(result.timed_out || result.duration > Duration::from_millis(0));
    }

    #[test]
    fn test_monitor_for_test_function() {
        let monitor = match ProcessMonitor::new(
            vec!["true".to_string()],
            Duration::from_millis(10),
            Duration::from_millis(50),
        ) {
            Ok(m) => m,
            Err(_) => return, // Skip test if we can't create a monitor
        };

        let result = monitor_for_test(monitor);

        // Should complete quickly due to test configuration
        assert!(result.timed_out || result.duration < Duration::from_secs(35));
    }

    #[test]
    fn test_monitor_with_progress_function() {
        use std::sync::atomic::AtomicUsize;

        let monitor = match ProcessMonitor::new(
            vec!["true".to_string()],
            Duration::from_millis(10),
            Duration::from_millis(50),
        ) {
            Ok(m) => m,
            Err(_) => return, // Skip test if we can't create a monitor
        };

        let progress_calls = Arc::new(AtomicUsize::new(0));
        let progress_clone = progress_calls.clone();

        let result =
            monitor_with_progress(monitor, Duration::from_millis(10), |_count, _metrics| {
                progress_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            });

        // Should have called progress callback if any samples were collected
        let progress_count = progress_calls.load(std::sync::atomic::Ordering::SeqCst);
        assert_eq!(progress_count, result.sample_count());
    }

    #[test]
    fn test_monitoring_loop_run_with_progress() {
        use std::sync::atomic::AtomicUsize;

        let monitor = match ProcessMonitor::new(
            vec!["true".to_string()],
            Duration::from_millis(10),
            Duration::from_millis(50),
        ) {
            Ok(m) => m,
            Err(_) => return, // Skip test if we can't create a monitor
        };

        let config = MonitoringConfig::new()
            .with_sample_interval(Duration::from_millis(10))
            .with_timeout(Duration::from_millis(100));

        let monitoring_loop = MonitoringLoop::with_config(config);
        let progress_calls = Arc::new(AtomicUsize::new(0));
        let progress_clone = progress_calls.clone();

        let result = monitoring_loop.run_with_progress(monitor, |count, _metrics| {
            progress_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            assert!(count > 0);
        });

        // Verify progress callback was called correctly
        let progress_count = progress_calls.load(std::sync::atomic::Ordering::SeqCst);
        assert_eq!(progress_count, result.sample_count());
    }

    #[test]
    fn test_monitoring_result_debug() {
        let result = MonitoringResult {
            samples: vec![Metrics::default()],
            duration: Duration::from_secs(1),
            timed_out: false,
            interrupted: false,
        };

        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("MonitoringResult"));
        assert!(debug_str.contains("samples"));
        assert!(debug_str.contains("duration"));
    }

    #[test]
    fn test_monitoring_config_debug() {
        let config = MonitoringConfig::new();
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("MonitoringConfig"));
        assert!(debug_str.contains("sample_interval"));
    }

    #[test]
    fn test_monitoring_config_clone() {
        let config1 = MonitoringConfig::new()
            .with_timeout(Duration::from_secs(10))
            .with_final_samples(5, delays::STANDARD);

        let config2 = config1.clone();

        assert_eq!(config1.sample_interval, config2.sample_interval);
        assert_eq!(config1.timeout, config2.timeout);
        assert_eq!(config1.monitor_after_exit, config2.monitor_after_exit);
        assert_eq!(config1.final_sample_count, config2.final_sample_count);
        assert_eq!(config1.final_sample_delay, config2.final_sample_delay);
    }
}