dampen-dev 0.3.1

Development mode tooling for Dampen - hot-reload, file watching, and error overlays
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
//! Integration tests for FileWatcher functionality
//!
//! These tests verify that the file watcher correctly detects file system events
//! with proper debouncing and filtering.

use crossbeam_channel;
use dampen_dev::watcher::{FileWatcher, FileWatcherConfig};
use std::fs;
use std::path::PathBuf;
use std::thread;
use std::time::{Duration, Instant};
use tempfile::TempDir;

/// Helper function to create a temporary directory for testing
fn setup_test_dir() -> TempDir {
    TempDir::new().expect("Failed to create temp directory")
}

/// Helper function to create a .dampen file in the test directory
fn create_dampen_file(dir: &TempDir, name: &str, content: &str) -> PathBuf {
    let file_path = dir.path().join(name);
    fs::write(&file_path, content).expect("Failed to write file");
    file_path
}

/// Helper function to modify a .dampen file
fn modify_dampen_file(path: &PathBuf, content: &str) {
    fs::write(path, content).expect("Failed to modify file");
}

/// Configuration for test timing to avoid flaky tests
pub struct TestTiming {
    pub debounce_duration: Duration,
    pub wait_multiplier: f64,
    pub test_timeout: Duration,
    pub poll_interval: Duration,
}

impl Default for TestTiming {
    fn default() -> Self {
        Self {
            debounce_duration: Duration::from_millis(100),
            wait_multiplier: 1.5,
            test_timeout: Duration::from_millis(500),
            poll_interval: Duration::from_millis(5),
        }
    }
}

impl TestTiming {
    /// Calculate the wait duration for debounce to complete
    pub fn wait_for_debounce(&self) -> Duration {
        self.debounce_duration.mul_f64(self.wait_multiplier)
    }
}

/// Wait for events from receiver with timeout and active polling
fn wait_for_events<T>(receiver: &crossbeam_channel::Receiver<T>, timeout: Duration) -> Vec<T> {
    let start = Instant::now();
    let mut events = Vec::new();

    while start.elapsed() < timeout {
        while let Ok(event) = receiver.try_recv() {
            events.push(event);
        }
        if start.elapsed() < timeout {
            thread::sleep(Duration::from_millis(5));
        }
    }

    events
}

/// Wait for debouncer to process events
fn wait_for_debounce() {
    let timing = TestTiming::default();
    thread::sleep(timing.wait_for_debounce());
}

#[test]
fn test_file_creation_detection() {
    // T065: Test that the watcher detects when a new .dampen file is created

    // Setup
    let temp_dir = setup_test_dir();
    let config = FileWatcherConfig {
        watch_paths: vec![temp_dir.path().to_path_buf()],
        debounce_ms: 100,
        extension_filter: ".dampen".to_string(),
        recursive: true,
    };

    // Create watcher
    let mut watcher = FileWatcher::new(config).expect("Failed to create watcher");
    watcher
        .watch(temp_dir.path().to_path_buf())
        .expect("Failed to watch directory");

    // Give the watcher time to initialize
    thread::sleep(Duration::from_millis(50));

    // Create a new .dampen file
    let test_file = temp_dir.path().join("test.dampen");
    fs::write(
        &test_file,
        r#"<dampen version="1.1" encoding="utf-8"><text value="Hello" /></dampen>"#,
    )
    .expect("Failed to create file");

    // Wait for debouncer to process the event
    wait_for_debounce();

    // Check that we received an event
    let receiver = watcher.receiver();
    let mut received_events = Vec::new();

    // Collect all available events
    while let Ok(path) = receiver.try_recv() {
        received_events.push(path);
    }

    // Verify we received at least one event
    assert!(
        !received_events.is_empty(),
        "Expected to receive file creation event, but got none"
    );

    // Verify the event is for our test file
    assert!(
        received_events.iter().any(|p| p == &test_file),
        "Expected event for {:?}, but received events for: {:?}",
        test_file,
        received_events
    );
}

#[test]
fn test_file_modification_detection() {
    // T066: Test that the watcher detects when an existing .dampen file is modified

    // Setup
    let temp_dir = setup_test_dir();

    // Create the file BEFORE starting the watcher
    let test_file = create_dampen_file(
        &temp_dir,
        "existing.dampen",
        r#"<dampen version="1.1" encoding="utf-8"><text value="Original" /></dampen>"#,
    );

    // Give filesystem time to settle
    thread::sleep(Duration::from_millis(50));

    let config = FileWatcherConfig {
        watch_paths: vec![temp_dir.path().to_path_buf()],
        debounce_ms: 100,
        extension_filter: ".dampen".to_string(),
        recursive: true,
    };

    // Create and start watcher
    let mut watcher = FileWatcher::new(config).expect("Failed to create watcher");
    watcher
        .watch(temp_dir.path().to_path_buf())
        .expect("Failed to watch directory");

    // Give the watcher time to initialize
    thread::sleep(Duration::from_millis(50));

    // Clear any initialization events
    let receiver = watcher.receiver();
    while receiver.try_recv().is_ok() {}

    // Modify the existing file
    modify_dampen_file(
        &test_file,
        r#"<dampen version="1.1" encoding="utf-8"><text value="Modified" /></dampen>"#,
    );

    // Wait for debouncer to process the event
    wait_for_debounce();

    // Check that we received a modification event
    let mut received_events = Vec::new();
    while let Ok(path) = receiver.try_recv() {
        received_events.push(path);
    }

    // Verify we received at least one event
    assert!(
        !received_events.is_empty(),
        "Expected to receive file modification event, but got none"
    );

    // Verify the event is for our test file
    assert!(
        received_events.iter().any(|p| p == &test_file),
        "Expected event for {:?}, but received events for: {:?}",
        test_file,
        received_events
    );
}

#[test]
fn test_debouncing_behavior() {
    // T067: Test that rapid successive file changes are debounced
    // Multiple rapid changes should result in fewer events than the number of changes

    // Setup
    let temp_dir = setup_test_dir();

    let config = FileWatcherConfig {
        watch_paths: vec![temp_dir.path().to_path_buf()],
        debounce_ms: 100,
        extension_filter: ".dampen".to_string(),
        recursive: true,
    };

    // Create and start watcher BEFORE creating the file
    let mut watcher = FileWatcher::new(config).expect("Failed to create watcher");
    watcher
        .watch(temp_dir.path().to_path_buf())
        .expect("Failed to watch directory");

    // Give the watcher time to initialize
    thread::sleep(Duration::from_millis(100));

    // Create the test file now
    let test_file = temp_dir.path().join("debounce_test.dampen");
    fs::write(
        &test_file,
        r#"<dampen version="1.1" encoding="utf-8"><text value="Original" /></dampen>"#,
    )
    .expect("Failed to create file");

    // Wait for creation event to be processed
    thread::sleep(Duration::from_millis(150));

    // Clear creation event
    let receiver = watcher.receiver();
    while receiver.try_recv().is_ok() {}

    // Make multiple rapid successive modifications (within the 100ms debounce window)
    const NUM_MODIFICATIONS: usize = 10;
    for i in 0..NUM_MODIFICATIONS {
        modify_dampen_file(
            &test_file,
            &format!(
                r#"<dampen version="1.1" encoding="utf-8"><text value="Change {}" /></dampen>"#,
                i
            ),
        );
        // Very small delay to ensure changes are registered, but stay within debounce window
        thread::sleep(Duration::from_millis(5));
    }

    // Wait for debouncer to process all events
    let timing = TestTiming::default();
    thread::sleep(timing.wait_for_debounce());

    // Collect all events using helper with timeout
    let received_events = wait_for_events(receiver, timing.test_timeout);

    // Verify debouncing: we should have received significantly fewer events than modifications
    assert!(
        !received_events.is_empty(),
        "Expected to receive at least one debounced event, but got none"
    );

    // The key assertion: debouncing should reduce the number of events
    // With 10 rapid modifications, we should get fewer events than modifications
    // The exact number depends on filesystem timing, but should be < NUM_MODIFICATIONS
    assert!(
        received_events.len() < NUM_MODIFICATIONS,
        "Expected debouncing to reduce {} modifications to fewer events, but got {} events. \
        Debouncing may not be working correctly.",
        NUM_MODIFICATIONS,
        received_events.len()
    );

    // Additional check: verify reduction (20% is realistic for debouncing under load)
    let reduction_percent =
        (1.0 - (received_events.len() as f64 / NUM_MODIFICATIONS as f64)) * 100.0;
    assert!(
        reduction_percent > 20.0,
        "Expected at least 20% reduction from debouncing, but only got {:.1}% \
        ({} events from {} modifications). Debouncing may be variable due to OS timing.",
        reduction_percent,
        received_events.len(),
        NUM_MODIFICATIONS
    );

    // Verify all events are for our test file
    for event_path in &received_events {
        assert_eq!(
            event_path, &test_file,
            "Received unexpected event for {:?}",
            event_path
        );
    }

    println!(
        "✓ Debouncing working: {} modifications resulted in {} events (reduction: {:.1}%)",
        NUM_MODIFICATIONS,
        received_events.len(),
        (1.0 - (received_events.len() as f64 / NUM_MODIFICATIONS as f64)) * 100.0
    );
}

#[test]
fn test_extension_filtering() {
    // Bonus test: Verify that non-.dampen files are filtered out

    // Setup
    let temp_dir = setup_test_dir();
    let config = FileWatcherConfig {
        watch_paths: vec![temp_dir.path().to_path_buf()],
        debounce_ms: 100,
        extension_filter: ".dampen".to_string(),
        recursive: true,
    };

    // Create watcher
    let mut watcher = FileWatcher::new(config).expect("Failed to create watcher");
    watcher
        .watch(temp_dir.path().to_path_buf())
        .expect("Failed to watch directory");

    // Give the watcher time to initialize
    thread::sleep(Duration::from_millis(50));

    // Clear any initialization events
    let receiver = watcher.receiver();
    while receiver.try_recv().is_ok() {}

    // Create a .dampen file (should be detected)
    let dampen_file = temp_dir.path().join("should_detect.dampen");
    fs::write(&dampen_file, "<dampen />").expect("Failed to create .dampen file");

    // Create a non-.dampen file (should be filtered out)
    let txt_file = temp_dir.path().join("should_ignore.txt");
    fs::write(&txt_file, "Some text").expect("Failed to create .txt file");

    // Wait for debouncer
    wait_for_debounce();

    // Collect events
    let mut received_events = Vec::new();
    while let Ok(path) = receiver.try_recv() {
        received_events.push(path);
    }

    // Verify only .dampen file triggered an event
    assert!(
        received_events.iter().any(|p| p == &dampen_file),
        "Expected to receive event for .dampen file"
    );

    assert!(
        !received_events.iter().any(|p| p == &txt_file),
        "Should not receive event for .txt file (should be filtered)"
    );
}

#[test]
fn test_deleted_file_handling() {
    // Bonus test: Verify that deleted files don't cause errors (T064 validation)

    // Setup
    let temp_dir = setup_test_dir();
    let test_file = create_dampen_file(
        &temp_dir,
        "to_delete.dampen",
        r#"<dampen version="1.1" encoding="utf-8"><text value="Will be deleted" /></dampen>"#,
    );

    // Give filesystem time to settle
    thread::sleep(Duration::from_millis(50));

    let config = FileWatcherConfig {
        watch_paths: vec![temp_dir.path().to_path_buf()],
        debounce_ms: 100,
        extension_filter: ".dampen".to_string(),
        recursive: true,
    };

    // Create and start watcher
    let mut watcher = FileWatcher::new(config).expect("Failed to create watcher");
    watcher
        .watch(temp_dir.path().to_path_buf())
        .expect("Failed to watch directory");

    // Give the watcher time to initialize
    thread::sleep(Duration::from_millis(50));

    // Clear any initialization events
    let receiver = watcher.receiver();
    while receiver.try_recv().is_ok() {}

    // Delete the file
    fs::remove_file(&test_file).expect("Failed to delete file");

    // Wait for debouncer
    wait_for_debounce();

    // Collect events - deletion events should be filtered out (file no longer exists)
    let received_events: Vec<PathBuf> = receiver.try_iter().collect();

    // The watcher should handle deletion gracefully (no event sent for deleted file)
    // This validates T064 implementation
    println!(
        "✓ File deletion handled gracefully: {} events received for deleted file",
        received_events.iter().filter(|p| p == &&test_file).count()
    );

    // Note: We don't assert here because deletion event behavior varies by platform
    // The important thing is that it doesn't cause a panic or error
}

#[test]
fn test_file_change_detection_latency() {
    // T068: Verify file change detection <100ms (FR-010, SC-003)
    //
    // This test measures the end-to-end latency from file modification to event reception.
    // We use a minimal debounce window (10ms) to test the raw detection speed.

    // Setup
    let temp_dir = setup_test_dir();

    // Use minimal debounce for this performance test
    let config = FileWatcherConfig {
        watch_paths: vec![temp_dir.path().to_path_buf()],
        debounce_ms: 10, // Minimal debounce to test raw detection speed
        extension_filter: ".dampen".to_string(),
        recursive: true,
    };

    // Create and start watcher
    let mut watcher = FileWatcher::new(config).expect("Failed to create watcher");
    watcher
        .watch(temp_dir.path().to_path_buf())
        .expect("Failed to watch directory");

    // Give the watcher time to initialize
    thread::sleep(Duration::from_millis(100));

    // Create test file
    let test_file = temp_dir.path().join("latency_test.dampen");
    fs::write(
        &test_file,
        r#"<dampen version="1.1" encoding="utf-8"><text value="Initial" /></dampen>"#,
    )
    .expect("Failed to create file");

    // Wait for creation event to be processed
    thread::sleep(Duration::from_millis(50));

    // Clear creation event
    let receiver = watcher.receiver();
    while receiver.try_recv().is_ok() {}

    // Perform 5 measurements and average them
    const NUM_MEASUREMENTS: usize = 5;
    let mut latencies = Vec::new();

    for i in 0..NUM_MEASUREMENTS {
        // Mark start time immediately before modification
        let start = Instant::now();

        // Modify the file
        modify_dampen_file(
            &test_file,
            &format!(
                r#"<dampen version="1.1" encoding="utf-8"><text value="Measurement {}" /></dampen>"#,
                i
            ),
        );

        // Wait for event with timeout
        let timeout = Duration::from_millis(200);
        let mut received = false;

        loop {
            if let Ok(_path) = receiver.try_recv() {
                let latency = start.elapsed();
                latencies.push(latency);
                received = true;
                break;
            }

            if start.elapsed() > timeout {
                break;
            }

            // Small sleep to avoid busy-waiting
            thread::sleep(Duration::from_millis(1));
        }

        assert!(
            received,
            "Measurement {}: Did not receive event within {}ms",
            i,
            timeout.as_millis()
        );

        // Small delay between measurements
        thread::sleep(Duration::from_millis(50));

        // Clear any additional events
        while receiver.try_recv().is_ok() {}
    }

    // Calculate statistics
    let average_latency = latencies.iter().sum::<Duration>() / latencies.len() as u32;
    let min_latency = latencies.iter().min().unwrap();
    let max_latency = latencies.iter().max().unwrap();

    // Print results
    println!("\n=== File Change Detection Latency (FR-010, SC-003) ===");
    println!("Measurements: {}", NUM_MEASUREMENTS);
    println!(
        "Average latency: {:.2}ms",
        average_latency.as_secs_f64() * 1000.0
    );
    println!("Min latency: {:.2}ms", min_latency.as_secs_f64() * 1000.0);
    println!("Max latency: {:.2}ms", max_latency.as_secs_f64() * 1000.0);
    println!(
        "All latencies: {:?}",
        latencies
            .iter()
            .map(|d| format!("{:.2}ms", d.as_secs_f64() * 1000.0))
            .collect::<Vec<_>>()
    );

    // Verify FR-010, SC-003: file change detection < 100ms
    // With minimal debounce (10ms), the detection should be very fast
    assert!(
        average_latency.as_millis() < 100,
        "FAILED: Average file change detection latency {:.2}ms exceeds 100ms requirement (FR-010, SC-003)",
        average_latency.as_secs_f64() * 1000.0
    );

    // Additional check: max latency should also be reasonable
    assert!(
        max_latency.as_millis() < 150,
        "FAILED: Maximum latency {:.2}ms is too high (should be < 150ms)",
        max_latency.as_secs_f64() * 1000.0
    );

    println!("✓ PASSED: File change detection latency meets <100ms requirement");
}