wasmtime-internal-cache 42.0.2

INTERNAL: Support for automatic module caching with Wasmtime
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
use super::*;
use crate::config::tests::test_prolog;
use std::iter::repeat;
use std::process;
// load_config! comes from crate::cache(::config::tests);

// when doing anything with the tests, make sure they are DETERMINISTIC
// -- the result shouldn't rely on system time!
pub mod system_time_stub;

#[test]
fn test_on_get_create_stats_file() {
    let (_tempdir, cache_dir, config_path) = test_prolog();
    let cache_config = load_config!(
        config_path,
        "[cache]\n\
         directory = '{cache_dir}'",
        cache_dir
    );
    let worker = Worker::start_new(&cache_config);

    let mod_file = cache_dir.join("some-mod");
    worker.on_cache_get_async(mod_file);
    worker.wait_for_all_events_handled();
    assert_eq!(worker.events_dropped(), 0);

    let stats_file = cache_dir.join("some-mod.stats");
    let stats = read_stats_file(&stats_file).expect("Failed to read stats file");
    assert_eq!(stats.usages, 1);
    assert_eq!(
        stats.compression_level,
        cache_config.baseline_compression_level()
    );
}

#[test]
fn test_on_get_update_usage_counter() {
    let (_tempdir, cache_dir, config_path) = test_prolog();
    let cache_config = load_config!(
        config_path,
        "[cache]\n\
         directory = '{cache_dir}'\n\
         worker-event-queue-size = '16'",
        cache_dir
    );
    let worker = Worker::start_new(&cache_config);

    let mod_file = cache_dir.join("some-mod");
    let stats_file = cache_dir.join("some-mod.stats");
    let default_stats = ModuleCacheStatistics::default(&cache_config);
    assert!(write_stats_file(&stats_file, &default_stats));

    let mut usages = 0;
    for times_used in &[4, 7, 2] {
        for _ in 0..*times_used {
            worker.on_cache_get_async(mod_file.clone());
            usages += 1;
        }

        worker.wait_for_all_events_handled();
        assert_eq!(worker.events_dropped(), 0);

        let stats = read_stats_file(&stats_file).expect("Failed to read stats file");
        assert_eq!(stats.usages, usages);
    }
}

#[test]
fn test_on_get_recompress_no_mod_file() {
    let (_tempdir, cache_dir, config_path) = test_prolog();
    let cache_config = load_config!(
        config_path,
        "[cache]\n\
         directory = '{cache_dir}'\n\
         worker-event-queue-size = '16'\n\
         baseline-compression-level = 3\n\
         optimized-compression-level = 7\n\
         optimized-compression-usage-counter-threshold = '256'",
        cache_dir
    );
    let worker = Worker::start_new(&cache_config);

    let mod_file = cache_dir.join("some-mod");
    let stats_file = cache_dir.join("some-mod.stats");
    let mut start_stats = ModuleCacheStatistics::default(&cache_config);
    start_stats.usages = 250;
    assert!(write_stats_file(&stats_file, &start_stats));

    let mut usages = start_stats.usages;
    for times_used in &[4, 7, 2] {
        for _ in 0..*times_used {
            worker.on_cache_get_async(mod_file.clone());
            usages += 1;
        }

        worker.wait_for_all_events_handled();
        assert_eq!(worker.events_dropped(), 0);

        let stats = read_stats_file(&stats_file).expect("Failed to read stats file");
        assert_eq!(stats.usages, usages);
        assert_eq!(
            stats.compression_level,
            cache_config.baseline_compression_level()
        );
    }
}

#[test]
fn test_on_get_recompress_with_mod_file() {
    let (_tempdir, cache_dir, config_path) = test_prolog();
    let cache_config = load_config!(
        config_path,
        "[cache]\n\
         directory = '{cache_dir}'\n\
         worker-event-queue-size = '16'\n\
         baseline-compression-level = 3\n\
         optimized-compression-level = 7\n\
         optimized-compression-usage-counter-threshold = '256'",
        cache_dir
    );
    let worker = Worker::start_new(&cache_config);

    let mod_file = cache_dir.join("some-mod");
    let mod_data = "some test data to be compressed";
    let data = zstd::encode_all(
        mod_data.as_bytes(),
        cache_config.baseline_compression_level(),
    )
    .expect("Failed to compress sample mod file");
    fs::write(&mod_file, &data).expect("Failed to write sample mod file");

    let stats_file = cache_dir.join("some-mod.stats");
    let mut start_stats = ModuleCacheStatistics::default(&cache_config);
    start_stats.usages = 250;
    assert!(write_stats_file(&stats_file, &start_stats));

    // scenarios:
    // 1. Shouldn't be recompressed
    // 2. Should be recompressed
    // 3. After lowering compression level, should be recompressed
    let scenarios = [(4, false), (7, true), (2, false)];

    let mut usages = start_stats.usages;
    assert!(usages < cache_config.optimized_compression_usage_counter_threshold());
    let mut tested_higher_opt_compr_lvl = false;
    for (times_used, lower_compr_lvl) in &scenarios {
        for _ in 0..*times_used {
            worker.on_cache_get_async(mod_file.clone());
            usages += 1;
        }

        worker.wait_for_all_events_handled();
        assert_eq!(worker.events_dropped(), 0);

        let mut stats = read_stats_file(&stats_file).expect("Failed to read stats file");
        assert_eq!(stats.usages, usages);
        assert_eq!(
            stats.compression_level,
            if usages < cache_config.optimized_compression_usage_counter_threshold() {
                cache_config.baseline_compression_level()
            } else {
                cache_config.optimized_compression_level()
            }
        );
        let compressed_data = fs::read(&mod_file).expect("Failed to read mod file");
        let decoded_data =
            zstd::decode_all(&compressed_data[..]).expect("Failed to decompress mod file");
        assert_eq!(decoded_data, mod_data.as_bytes());

        if *lower_compr_lvl {
            assert!(usages >= cache_config.optimized_compression_usage_counter_threshold());
            tested_higher_opt_compr_lvl = true;
            stats.compression_level -= 1;
            assert!(write_stats_file(&stats_file, &stats));
        }
    }
    assert!(usages >= cache_config.optimized_compression_usage_counter_threshold());
    assert!(tested_higher_opt_compr_lvl);
}

#[test]
fn test_on_get_recompress_lock() {
    let (_tempdir, cache_dir, config_path) = test_prolog();
    let cache_config = load_config!(
        config_path,
        "[cache]\n\
         directory = '{cache_dir}'\n\
         worker-event-queue-size = '16'\n\
         baseline-compression-level = 3\n\
         optimized-compression-level = 7\n\
         optimized-compression-usage-counter-threshold = '256'\n\
         optimizing-compression-task-timeout = '30m'\n\
         allowed-clock-drift-for-files-from-future = '1d'",
        cache_dir
    );
    let worker = Worker::start_new(&cache_config);

    let mod_file = cache_dir.join("some-mod");
    let mod_data = "some test data to be compressed";
    let data = zstd::encode_all(
        mod_data.as_bytes(),
        cache_config.baseline_compression_level(),
    )
    .expect("Failed to compress sample mod file");
    fs::write(&mod_file, &data).expect("Failed to write sample mod file");

    let stats_file = cache_dir.join("some-mod.stats");
    let mut start_stats = ModuleCacheStatistics::default(&cache_config);
    start_stats.usages = 255;

    let lock_file = cache_dir.join("some-mod.wip-lock");

    let scenarios = [
        // valid lock
        (true, "past", Duration::from_secs(30 * 60 - 1)),
        // valid future lock
        (true, "future", Duration::from_secs(24 * 60 * 60)),
        // expired lock
        (false, "past", Duration::from_secs(30 * 60)),
        // expired future lock
        (false, "future", Duration::from_secs(24 * 60 * 60 + 1)),
    ];

    for (lock_valid, duration_sign, duration) in &scenarios {
        assert!(write_stats_file(&stats_file, &start_stats)); // restore usage & compression level
        create_file_with_mtime(&lock_file, "", duration_sign, &duration);

        worker.on_cache_get_async(mod_file.clone());
        worker.wait_for_all_events_handled();
        assert_eq!(worker.events_dropped(), 0);

        let stats = read_stats_file(&stats_file).expect("Failed to read stats file");
        assert_eq!(stats.usages, start_stats.usages + 1);
        assert_eq!(
            stats.compression_level,
            if *lock_valid {
                cache_config.baseline_compression_level()
            } else {
                cache_config.optimized_compression_level()
            }
        );
        let compressed_data = fs::read(&mod_file).expect("Failed to read mod file");
        let decoded_data =
            zstd::decode_all(&compressed_data[..]).expect("Failed to decompress mod file");
        assert_eq!(decoded_data, mod_data.as_bytes());
    }
}

#[test]
fn test_on_update_fresh_stats_file() {
    let (_tempdir, cache_dir, config_path) = test_prolog();
    let cache_config = load_config!(
        config_path,
        "[cache]\n\
         directory = '{cache_dir}'\n\
         worker-event-queue-size = '16'\n\
         baseline-compression-level = 3\n\
         optimized-compression-level = 7\n\
         cleanup-interval = '1h'",
        cache_dir
    );
    let worker = Worker::start_new(&cache_config);

    let mod_file = cache_dir.join("some-mod");
    let stats_file = cache_dir.join("some-mod.stats");
    let cleanup_certificate = cache_dir.join(".cleanup.wip-done");
    create_file_with_mtime(&cleanup_certificate, "", "future", &Duration::from_secs(0));
    // the below created by the worker if it cleans up
    let worker_lock_file = cache_dir.join(format!(".cleanup.wip-{}", process::id()));

    // scenarios:
    // 1. Create new stats file
    // 2. Overwrite existing file
    for update_file in &[true, false] {
        worker.on_cache_update_async(mod_file.clone());
        worker.wait_for_all_events_handled();
        assert_eq!(worker.events_dropped(), 0);

        let mut stats = read_stats_file(&stats_file).expect("Failed to read stats file");
        assert_eq!(stats.usages, 1);
        assert_eq!(
            stats.compression_level,
            cache_config.baseline_compression_level()
        );

        if *update_file {
            stats.usages += 42;
            stats.compression_level += 1;
            assert!(write_stats_file(&stats_file, &stats));
        }

        assert!(!worker_lock_file.exists());
    }
}

#[test]
fn test_on_update_cleanup_limits_trash_locks() {
    let (_tempdir, cache_dir, config_path) = test_prolog();
    let cache_config = load_config!(
        config_path,
        "[cache]\n\
         directory = '{cache_dir}'\n\
         worker-event-queue-size = '16'\n\
         cleanup-interval = '30m'\n\
         optimizing-compression-task-timeout = '30m'\n\
         allowed-clock-drift-for-files-from-future = '1d'\n\
         file-count-soft-limit = '5'\n\
         files-total-size-soft-limit = '30K'\n\
         file-count-limit-percent-if-deleting = '70%'\n\
         files-total-size-limit-percent-if-deleting = '70%'
         ",
        cache_dir
    );
    let worker = Worker::start_new(&cache_config);
    let content_1k = "a".repeat(1_000);
    let content_10k = "a".repeat(10_000);

    let mods_files_dir = cache_dir.join("target-triple").join("compiler-version");
    let mod_with_stats = mods_files_dir.join("mod-with-stats");
    let trash_dirs = [
        mods_files_dir.join("trash"),
        mods_files_dir.join("trash").join("trash"),
    ];
    let trash_files = [
        cache_dir.join("trash-file"),
        cache_dir.join("trash-file.wip-lock"),
        cache_dir.join("target-triple").join("trash.txt"),
        cache_dir.join("target-triple").join("trash.txt.wip-lock"),
        mods_files_dir.join("trash.ogg"),
        mods_files_dir.join("trash").join("trash.doc"),
        mods_files_dir.join("trash").join("trash.doc.wip-lock"),
        mods_files_dir.join("trash").join("trash").join("trash.xls"),
        mods_files_dir
            .join("trash")
            .join("trash")
            .join("trash.xls.wip-lock"),
    ];
    let mod_locks = [
        // valid lock
        (
            mods_files_dir.join("mod0.wip-lock"),
            true,
            "past",
            Duration::from_secs(30 * 60 - 1),
        ),
        // valid future lock
        (
            mods_files_dir.join("mod1.wip-lock"),
            true,
            "future",
            Duration::from_secs(24 * 60 * 60),
        ),
        // expired lock
        (
            mods_files_dir.join("mod2.wip-lock"),
            false,
            "past",
            Duration::from_secs(30 * 60),
        ),
        // expired future lock
        (
            mods_files_dir.join("mod3.wip-lock"),
            false,
            "future",
            Duration::from_secs(24 * 60 * 60 + 1),
        ),
    ];
    // the below created by the worker if it cleans up
    let worker_lock_file = cache_dir.join(format!(".cleanup.wip-{}", process::id()));

    let scenarios = [
        // Close to limits, but not reached, only trash deleted
        (2, 2, 4),
        // File count limit exceeded
        (1, 10, 3),
        // Total size limit exceeded
        (4, 0, 2),
        // Both limits exceeded
        (3, 5, 3),
    ];

    for (files_10k, files_1k, remaining_files) in &scenarios {
        let mut secs_ago = 100;

        for d in &trash_dirs {
            fs::create_dir_all(d).expect("Failed to create directories");
        }
        for f in &trash_files {
            create_file_with_mtime(f, "", "past", &Duration::from_secs(0));
        }
        for (f, _, sign, duration) in &mod_locks {
            create_file_with_mtime(f, "", sign, &duration);
        }

        let mut mods_paths = vec![];
        for content in repeat(&content_10k)
            .take(*files_10k)
            .chain(repeat(&content_1k).take(*files_1k))
        {
            mods_paths.push(mods_files_dir.join(format!("test-mod-{}", mods_paths.len())));
            create_file_with_mtime(
                mods_paths.last().unwrap(),
                content,
                "past",
                &Duration::from_secs(secs_ago),
            );
            assert!(secs_ago > 0);
            secs_ago -= 1;
        }

        // creating .stats file updates mtime what affects test results
        // so we use a separate nonexistent module here (orphaned .stats will be removed anyway)
        worker.on_cache_update_async(mod_with_stats.clone());
        worker.wait_for_all_events_handled();
        assert_eq!(worker.events_dropped(), 0);

        for ent in trash_dirs.iter().chain(trash_files.iter()) {
            assert!(!ent.exists());
        }
        for (f, valid, ..) in &mod_locks {
            assert_eq!(f.exists(), *valid);
        }
        for (idx, path) in mods_paths.iter().enumerate() {
            let should_exist = idx >= mods_paths.len() - *remaining_files;
            assert_eq!(path.exists(), should_exist);
            if should_exist {
                // cleanup before next iteration
                fs::remove_file(path).expect("Failed to remove a file");
            }
        }
        fs::remove_file(&worker_lock_file).expect("Failed to remove lock file");
    }
}

#[test]
fn test_on_update_cleanup_lru_policy() {
    let (_tempdir, cache_dir, config_path) = test_prolog();
    let cache_config = load_config!(
        config_path,
        "[cache]\n\
         directory = '{cache_dir}'\n\
         worker-event-queue-size = '16'\n\
         file-count-soft-limit = '5'\n\
         files-total-size-soft-limit = '30K'\n\
         file-count-limit-percent-if-deleting = '80%'\n\
         files-total-size-limit-percent-if-deleting = '70%'",
        cache_dir
    );
    let worker = Worker::start_new(&cache_config);
    let content_1k = "a".repeat(1_000);
    let content_5k = "a".repeat(5_000);
    let content_10k = "a".repeat(10_000);

    let mods_files_dir = cache_dir.join("target-triple").join("compiler-version");
    fs::create_dir_all(&mods_files_dir).expect("Failed to create directories");
    let nonexistent_mod_file = cache_dir.join("nonexistent-mod");
    let orphaned_stats_file = cache_dir.join("orphaned-mod.stats");
    let worker_lock_file = cache_dir.join(format!(".cleanup.wip-{}", process::id()));

    // content, how long ago created, how long ago stats created (if created), should be alive
    let scenarios = [
        &[
            (&content_10k, 29, None, false),
            (&content_10k, 28, None, false),
            (&content_10k, 27, None, false),
            (&content_1k, 26, None, true),
            (&content_10k, 25, None, true),
            (&content_1k, 24, None, true),
        ],
        &[
            (&content_10k, 29, None, false),
            (&content_10k, 28, None, false),
            (&content_10k, 27, None, true),
            (&content_1k, 26, None, true),
            (&content_5k, 25, None, true),
            (&content_1k, 24, None, true),
        ],
        &[
            (&content_10k, 29, Some(19), true),
            (&content_10k, 28, None, false),
            (&content_10k, 27, None, false),
            (&content_1k, 26, Some(18), true),
            (&content_5k, 25, None, true),
            (&content_1k, 24, None, true),
        ],
        &[
            (&content_10k, 29, Some(19), true),
            (&content_10k, 28, Some(18), true),
            (&content_10k, 27, None, false),
            (&content_1k, 26, Some(17), true),
            (&content_5k, 25, None, false),
            (&content_1k, 24, None, false),
        ],
        &[
            (&content_10k, 29, Some(19), true),
            (&content_10k, 28, None, false),
            (&content_1k, 27, None, false),
            (&content_5k, 26, Some(18), true),
            (&content_1k, 25, None, false),
            (&content_10k, 24, None, false),
        ],
    ];

    for mods in &scenarios {
        let filenames = (0..mods.len())
            .map(|i| {
                (
                    mods_files_dir.join(format!("mod-{i}")),
                    mods_files_dir.join(format!("mod-{i}.stats")),
                )
            })
            .collect::<Vec<_>>();

        for ((content, mod_secs_ago, create_stats, _), (mod_filename, stats_filename)) in
            mods.iter().zip(filenames.iter())
        {
            create_file_with_mtime(
                mod_filename,
                content,
                "past",
                &Duration::from_secs(*mod_secs_ago),
            );
            if let Some(stats_secs_ago) = create_stats {
                create_file_with_mtime(
                    stats_filename,
                    "cleanup doesn't care",
                    "past",
                    &Duration::from_secs(*stats_secs_ago),
                );
            }
        }
        create_file_with_mtime(
            &orphaned_stats_file,
            "cleanup doesn't care",
            "past",
            &Duration::from_secs(0),
        );

        worker.on_cache_update_async(nonexistent_mod_file.clone());
        worker.wait_for_all_events_handled();
        assert_eq!(worker.events_dropped(), 0);

        assert!(!orphaned_stats_file.exists());
        for ((_, _, create_stats, alive), (mod_filename, stats_filename)) in
            mods.iter().zip(filenames.iter())
        {
            assert_eq!(mod_filename.exists(), *alive);
            assert_eq!(stats_filename.exists(), *alive && create_stats.is_some());

            // cleanup for next iteration
            if *alive {
                fs::remove_file(&mod_filename).expect("Failed to remove a file");
                if create_stats.is_some() {
                    fs::remove_file(&stats_filename).expect("Failed to remove a file");
                }
            }
        }

        fs::remove_file(&worker_lock_file).expect("Failed to remove lock file");
    }
}

// clock drift should be applied to mod cache & stats, too
// however, postpone deleting files to as late as possible
#[test]
fn test_on_update_cleanup_future_files() {
    let (_tempdir, cache_dir, config_path) = test_prolog();
    let cache_config = load_config!(
        config_path,
        "[cache]\n\
         directory = '{cache_dir}'\n\
         worker-event-queue-size = '16'\n\
         allowed-clock-drift-for-files-from-future = '1d'\n\
         file-count-soft-limit = '3'\n\
         files-total-size-soft-limit = '1M'\n\
         file-count-limit-percent-if-deleting = '70%'\n\
         files-total-size-limit-percent-if-deleting = '70%'",
        cache_dir
    );
    let worker = Worker::start_new(&cache_config);
    let content_1k = "a".repeat(1_000);

    let mods_files_dir = cache_dir.join("target-triple").join("compiler-version");
    fs::create_dir_all(&mods_files_dir).expect("Failed to create directories");
    let nonexistent_mod_file = cache_dir.join("nonexistent-mod");
    // the below created by the worker if it cleans up
    let worker_lock_file = cache_dir.join(format!(".cleanup.wip-{}", process::id()));

    let scenarios: [&[_]; 5] = [
        // NOT cleaning up, everything is ok
        &[
            (Duration::from_secs(0), None, true),
            (Duration::from_secs(24 * 60 * 60), None, true),
        ],
        // NOT cleaning up, everything is ok
        &[
            (Duration::from_secs(0), None, true),
            (Duration::from_secs(24 * 60 * 60 + 1), None, true),
        ],
        // cleaning up, removing files from oldest
        &[
            (Duration::from_secs(0), None, false),
            (Duration::from_secs(24 * 60 * 60), None, true),
            (Duration::from_secs(1), None, false),
            (Duration::from_secs(2), None, true),
        ],
        // cleaning up, removing files from oldest; deleting file from far future
        &[
            (Duration::from_secs(0), None, false),
            (Duration::from_secs(1), None, true),
            (Duration::from_secs(24 * 60 * 60 + 1), None, false),
            (Duration::from_secs(2), None, true),
        ],
        // cleaning up, removing files from oldest; file from far future should have .stats from +-now => it's a legitimate file
        &[
            (Duration::from_secs(0), None, false),
            (Duration::from_secs(1), None, false),
            (
                Duration::from_secs(24 * 60 * 60 + 1),
                Some(Duration::from_secs(3)),
                true,
            ),
            (Duration::from_secs(2), None, true),
        ],
    ];

    for mods in &scenarios {
        let filenames = (0..mods.len())
            .map(|i| {
                (
                    mods_files_dir.join(format!("mod-{i}")),
                    mods_files_dir.join(format!("mod-{i}.stats")),
                )
            })
            .collect::<Vec<_>>();

        for ((duration, opt_stats_duration, _), (mod_filename, stats_filename)) in
            mods.iter().zip(filenames.iter())
        {
            create_file_with_mtime(mod_filename, &content_1k, "future", duration);
            if let Some(stats_duration) = opt_stats_duration {
                create_file_with_mtime(stats_filename, "", "future", stats_duration);
            }
        }

        worker.on_cache_update_async(nonexistent_mod_file.clone());
        worker.wait_for_all_events_handled();
        assert_eq!(worker.events_dropped(), 0);

        for ((_, opt_stats_duration, alive), (mod_filename, stats_filename)) in
            mods.iter().zip(filenames.iter())
        {
            assert_eq!(mod_filename.exists(), *alive);
            assert_eq!(
                stats_filename.exists(),
                *alive && opt_stats_duration.is_some()
            );
            if *alive {
                fs::remove_file(mod_filename).expect("Failed to remove a file");
                if opt_stats_duration.is_some() {
                    fs::remove_file(stats_filename).expect("Failed to remove a file");
                }
            }
        }

        fs::remove_file(&worker_lock_file).expect("Failed to remove lock file");
    }
}

// this tests if worker triggered cleanup or not when some cleanup lock/certificate was out there
#[test]
fn test_on_update_cleanup_self_lock() {
    let (_tempdir, cache_dir, config_path) = test_prolog();
    let cache_config = load_config!(
        config_path,
        "[cache]\n\
         directory = '{cache_dir}'\n\
         worker-event-queue-size = '16'\n\
         cleanup-interval = '30m'\n\
         allowed-clock-drift-for-files-from-future = '1d'",
        cache_dir
    );
    let worker = Worker::start_new(&cache_config);

    let mod_file = cache_dir.join("some-mod");
    let trash_file = cache_dir.join("trash-file.txt");

    let lock_file = cache_dir.join(".cleanup.wip-lock");
    // the below created by the worker if it cleans up
    let worker_lock_file = cache_dir.join(format!(".cleanup.wip-{}", process::id()));

    let scenarios = [
        // valid lock
        (true, "past", Duration::from_secs(30 * 60 - 1)),
        // valid future lock
        (true, "future", Duration::from_secs(24 * 60 * 60)),
        // expired lock
        (false, "past", Duration::from_secs(30 * 60)),
        // expired future lock
        (false, "future", Duration::from_secs(24 * 60 * 60 + 1)),
    ];

    for (lock_valid, duration_sign, duration) in &scenarios {
        create_file_with_mtime(
            &trash_file,
            "with trash content",
            "future",
            &Duration::from_secs(0),
        );
        create_file_with_mtime(&lock_file, "", duration_sign, &duration);

        worker.on_cache_update_async(mod_file.clone());
        worker.wait_for_all_events_handled();
        assert_eq!(worker.events_dropped(), 0);

        assert_eq!(trash_file.exists(), *lock_valid);
        assert_eq!(lock_file.exists(), *lock_valid);
        if *lock_valid {
            assert!(!worker_lock_file.exists());
        } else {
            fs::remove_file(&worker_lock_file).expect("Failed to remove lock file");
        }
    }
}

fn create_file_with_mtime(filename: &Path, contents: &str, offset_sign: &str, offset: &Duration) {
    fs::write(filename, contents).expect("Failed to create a file");
    let mtime = match offset_sign {
        "past" => system_time_stub::NOW
            .checked_sub(*offset)
            .expect("Failed to calculate new mtime"),
        "future" => system_time_stub::NOW
            .checked_add(*offset)
            .expect("Failed to calculate new mtime"),
        _ => unreachable!(),
    };
    filetime::set_file_mtime(filename, mtime.into()).expect("Failed to set mtime");
}