xref: /wasmtime-44.0.1/crates/cache/src/worker.rs (revision 3ecb338e)
1 //! Background worker that watches over the cache.
2 //!
3 //! It cleans up old cache, updates statistics and optimizes the cache.
4 //! We allow losing some messages (it doesn't hurt) and some races,
5 //! but we guarantee eventual consistency and fault tolerancy.
6 //! Background tasks can be CPU intensive, but the worker thread has low priority.
7 
8 #![cfg_attr(
9     not(test),
10     expect(
11         clippy::useless_conversion,
12         reason = "cfg(test) and cfg(not(test)) have a different definition \
13                   of `SystemTime`, so conversions below are needed in \
14                   one mode but not the other, just ignore the lint in this \
15                   module in not(test) mode where the conversion isn't required",
16     )
17 )]
18 
19 use super::{CacheConfig, fs_write_atomic};
20 use log::{debug, info, trace, warn};
21 use serde_derive::{Deserialize, Serialize};
22 use std::cmp;
23 use std::collections::HashMap;
24 use std::ffi::OsStr;
25 use std::fmt;
26 use std::fs;
27 use std::path::{Path, PathBuf};
28 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
29 #[cfg(test)]
30 use std::sync::{Arc, Condvar, Mutex};
31 use std::thread;
32 use std::time::Duration;
33 #[cfg(not(test))]
34 use std::time::SystemTime;
35 #[cfg(test)]
36 use tests::system_time_stub::SystemTimeStub as SystemTime;
37 
38 #[derive(Clone)]
39 pub(super) struct Worker {
40     sender: SyncSender<CacheEvent>,
41     #[cfg(test)]
42     stats: Arc<(Mutex<WorkerStats>, Condvar)>,
43 }
44 
45 struct WorkerThread {
46     receiver: Receiver<CacheEvent>,
47     cache_config: CacheConfig,
48     #[cfg(test)]
49     stats: Arc<(Mutex<WorkerStats>, Condvar)>,
50 }
51 
52 #[cfg(test)]
53 #[derive(Default)]
54 struct WorkerStats {
55     dropped: u32,
56     sent: u32,
57     handled: u32,
58 }
59 
60 #[derive(Debug, Clone)]
61 enum CacheEvent {
62     OnCacheGet(PathBuf),
63     OnCacheUpdate(PathBuf),
64 }
65 
66 impl Worker {
67     pub(super) fn start_new(cache_config: &CacheConfig) -> Self {
68         let queue_size = match cache_config.worker_event_queue_size() {
69             num if num <= usize::max_value() as u64 => num as usize,
70             _ => usize::max_value(),
71         };
72         let (tx, rx) = sync_channel(queue_size);
73 
74         #[cfg(test)]
75         let stats = Arc::new((Mutex::new(WorkerStats::default()), Condvar::new()));
76 
77         let worker_thread = WorkerThread {
78             receiver: rx,
79             cache_config: cache_config.clone(),
80             #[cfg(test)]
81             stats: stats.clone(),
82         };
83 
84         // when self is dropped, sender will be dropped, what will cause the channel
85         // to hang, and the worker thread to exit -- it happens in the tests
86         // non-tests binary has only a static worker, so Rust doesn't drop it
87         thread::spawn(move || worker_thread.run());
88 
89         Self {
90             sender: tx,
91             #[cfg(test)]
92             stats,
93         }
94     }
95 
96     pub(super) fn on_cache_get_async(&self, path: impl AsRef<Path>) {
97         let event = CacheEvent::OnCacheGet(path.as_ref().to_path_buf());
98         self.send_cache_event(event);
99     }
100 
101     pub(super) fn on_cache_update_async(&self, path: impl AsRef<Path>) {
102         let event = CacheEvent::OnCacheUpdate(path.as_ref().to_path_buf());
103         self.send_cache_event(event);
104     }
105 
106     #[inline]
107     fn send_cache_event(&self, event: CacheEvent) {
108         let sent_event = self.sender.try_send(event.clone());
109 
110         if let Err(ref err) = sent_event {
111             info!(
112                 "Failed to send asynchronously message to worker thread, \
113                  event: {event:?}, error: {err}"
114             );
115         }
116 
117         #[cfg(test)]
118         {
119             let mut stats = self
120                 .stats
121                 .0
122                 .lock()
123                 .expect("Failed to acquire worker stats lock");
124 
125             if sent_event.is_ok() {
126                 stats.sent += 1;
127             } else {
128                 stats.dropped += 1;
129             }
130         }
131     }
132 
133     #[cfg(test)]
134     pub(super) fn events_dropped(&self) -> u32 {
135         let stats = self
136             .stats
137             .0
138             .lock()
139             .expect("Failed to acquire worker stats lock");
140         stats.dropped
141     }
142 
143     #[cfg(test)]
144     pub(super) fn wait_for_all_events_handled(&self) {
145         let (stats, condvar) = &*self.stats;
146         let mut stats = stats.lock().expect("Failed to acquire worker stats lock");
147         while stats.handled != stats.sent {
148             stats = condvar
149                 .wait(stats)
150                 .expect("Failed to reacquire worker stats lock");
151         }
152     }
153 }
154 
155 impl fmt::Debug for Worker {
156     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157         f.debug_struct("Worker").finish()
158     }
159 }
160 
161 #[derive(Serialize, Deserialize)]
162 struct ModuleCacheStatistics {
163     pub usages: u64,
164     #[serde(rename = "optimized-compression")]
165     pub compression_level: i32,
166 }
167 
168 impl ModuleCacheStatistics {
169     fn default(cache_config: &CacheConfig) -> Self {
170         Self {
171             usages: 0,
172             compression_level: cache_config.baseline_compression_level(),
173         }
174     }
175 }
176 
177 enum CacheEntry {
178     Recognized {
179         path: PathBuf,
180         mtime: SystemTime,
181         size: u64,
182     },
183     Unrecognized {
184         path: PathBuf,
185         is_dir: bool,
186     },
187 }
188 
189 macro_rules! unwrap_or_warn {
190     ($result:expr, $cont:stmt, $err_msg:expr, $path:expr) => {
191         match $result {
192             Ok(val) => val,
193             Err(err) => {
194                 warn!("{}, path: {}, msg: {}", $err_msg, $path.display(), err);
195                 $cont
196             }
197         }
198     };
199 }
200 
201 impl WorkerThread {
202     fn run(self) {
203         debug!("Cache worker thread started.");
204 
205         Self::lower_thread_priority();
206 
207         #[cfg(test)]
208         let (stats, condvar) = &*self.stats;
209 
210         for event in self.receiver.iter() {
211             match event {
212                 CacheEvent::OnCacheGet(path) => self.handle_on_cache_get(path),
213                 CacheEvent::OnCacheUpdate(path) => self.handle_on_cache_update(path),
214             }
215 
216             #[cfg(test)]
217             {
218                 let mut stats = stats.lock().expect("Failed to acquire worker stats lock");
219                 stats.handled += 1;
220                 condvar.notify_all();
221             }
222         }
223     }
224 
225     #[cfg(target_os = "fuchsia")]
226     fn lower_thread_priority() {
227         // TODO This needs to use Fuchsia thread profiles
228         // https://fuchsia.dev/fuchsia-src/reference/kernel_objects/profile
229         warn!(
230             "Lowering thread priority on Fuchsia is currently a noop. It might affect application performance."
231         );
232     }
233 
234     #[cfg(target_os = "windows")]
235     fn lower_thread_priority() {
236         use windows_sys::Win32::System::Threading::*;
237 
238         // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadpriority
239         // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
240 
241         if unsafe { SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN) } == 0 {
242             warn!(
243                 "Failed to lower worker thread priority. It might affect application performance."
244             );
245         }
246     }
247 
248     #[cfg(not(any(target_os = "windows", target_os = "fuchsia")))]
249     fn lower_thread_priority() {
250         // http://man7.org/linux/man-pages/man7/sched.7.html
251 
252         const NICE_DELTA_FOR_BACKGROUND_TASKS: i32 = 3;
253 
254         match rustix::process::nice(NICE_DELTA_FOR_BACKGROUND_TASKS) {
255             Ok(current_nice) => {
256                 debug!("New nice value of worker thread: {current_nice}");
257             }
258             Err(err) => {
259                 warn!(
260                     "Failed to lower worker thread priority ({err:?}). It might affect application performance."
261                 );
262             }
263         };
264     }
265 
266     /// Increases the usage counter and recompresses the file
267     /// if the usage counter reached configurable threshold.
268     fn handle_on_cache_get(&self, path: PathBuf) {
269         trace!("handle_on_cache_get() for path: {}", path.display());
270 
271         // construct .stats file path
272         let filename = path.file_name().unwrap().to_str().unwrap();
273         let stats_path = path.with_file_name(format!("{filename}.stats"));
274 
275         // load .stats file (default if none or error)
276         let mut stats = read_stats_file(stats_path.as_ref())
277             .unwrap_or_else(|| ModuleCacheStatistics::default(&self.cache_config));
278 
279         // step 1: update the usage counter & write to the disk
280         //         it's racy, but it's fine (the counter will be just smaller,
281         //         sometimes will retrigger recompression)
282         stats.usages += 1;
283         if !write_stats_file(stats_path.as_ref(), &stats) {
284             return;
285         }
286 
287         // step 2: recompress if there's a need
288         let opt_compr_lvl = self.cache_config.optimized_compression_level();
289         if stats.compression_level >= opt_compr_lvl
290             || stats.usages
291                 < self
292                     .cache_config
293                     .optimized_compression_usage_counter_threshold()
294         {
295             return;
296         }
297 
298         let lock_path = if let Some(p) = acquire_task_fs_lock(
299             path.as_ref(),
300             self.cache_config.optimizing_compression_task_timeout(),
301             self.cache_config
302                 .allowed_clock_drift_for_files_from_future(),
303         ) {
304             p
305         } else {
306             return;
307         };
308 
309         trace!("Trying to recompress file: {}", path.display());
310 
311         // recompress, write to other file, rename (it's atomic file content exchange)
312         // and update the stats file
313         let compressed_cache_bytes = unwrap_or_warn!(
314             fs::read(&path),
315             return,
316             "Failed to read old cache file",
317             path
318         );
319 
320         let cache_bytes = unwrap_or_warn!(
321             zstd::decode_all(&compressed_cache_bytes[..]),
322             return,
323             "Failed to decompress cached code",
324             path
325         );
326 
327         let recompressed_cache_bytes = unwrap_or_warn!(
328             zstd::encode_all(&cache_bytes[..], opt_compr_lvl),
329             return,
330             "Failed to compress cached code",
331             path
332         );
333 
334         unwrap_or_warn!(
335             fs::write(&lock_path, &recompressed_cache_bytes),
336             return,
337             "Failed to write recompressed cache",
338             lock_path
339         );
340 
341         unwrap_or_warn!(
342             fs::rename(&lock_path, &path),
343             {
344                 if let Err(error) = fs::remove_file(&lock_path) {
345                     warn!(
346                         "Failed to clean up (remove) recompressed cache, path {}, err: {}",
347                         lock_path.display(),
348                         error
349                     );
350                 }
351 
352                 return;
353             },
354             "Failed to rename recompressed cache",
355             lock_path
356         );
357 
358         // update stats file (reload it! recompression can take some time)
359         if let Some(mut new_stats) = read_stats_file(stats_path.as_ref()) {
360             if new_stats.compression_level >= opt_compr_lvl {
361                 // Rare race:
362                 //    two instances with different opt_compr_lvl: we don't know in which order they updated
363                 //    the cache file and the stats file (they are not updated together atomically)
364                 // Possible solution is to use directories per cache entry, but it complicates the system
365                 // and is not worth it.
366                 debug!(
367                     "DETECTED task did more than once (or race with new file): \
368                      recompression of {}. Note: if optimized compression level setting \
369                      has changed in the meantine, the stats file might contain \
370                      inconsistent compression level due to race.",
371                     path.display()
372                 );
373             } else {
374                 new_stats.compression_level = opt_compr_lvl;
375                 let _ = write_stats_file(stats_path.as_ref(), &new_stats);
376             }
377 
378             if new_stats.usages < stats.usages {
379                 debug!(
380                     "DETECTED lower usage count (new file or race with counter \
381                      increasing): file {}",
382                     path.display()
383                 );
384             }
385         } else {
386             debug!(
387                 "Can't read stats file again to update compression level (it might got \
388                  cleaned up): file {}",
389                 stats_path.display()
390             );
391         }
392 
393         trace!("Task finished: recompress file: {}", path.display());
394     }
395 
396     fn handle_on_cache_update(&self, path: PathBuf) {
397         trace!("handle_on_cache_update() for path: {}", path.display());
398 
399         // ---------------------- step 1: create .stats file
400 
401         // construct .stats file path
402         let filename = path
403             .file_name()
404             .expect("Expected valid cache file name")
405             .to_str()
406             .expect("Expected valid cache file name");
407         let stats_path = path.with_file_name(format!("{filename}.stats"));
408 
409         // create and write stats file
410         let mut stats = ModuleCacheStatistics::default(&self.cache_config);
411         stats.usages += 1;
412         write_stats_file(&stats_path, &stats);
413 
414         // ---------------------- step 2: perform cleanup task if needed
415 
416         // acquire lock for cleanup task
417         // Lock is a proof of recent cleanup task, so we don't want to delete them.
418         // Expired locks will be deleted by the cleanup task.
419         let cleanup_file = self.cache_config.directory().join(".cleanup"); // some non existing marker file
420         if acquire_task_fs_lock(
421             &cleanup_file,
422             self.cache_config.cleanup_interval(),
423             self.cache_config
424                 .allowed_clock_drift_for_files_from_future(),
425         )
426         .is_none()
427         {
428             return;
429         }
430 
431         trace!("Trying to clean up cache");
432 
433         let mut cache_index = self.list_cache_contents();
434         let future_tolerance = SystemTime::now()
435             .checked_add(
436                 self.cache_config
437                     .allowed_clock_drift_for_files_from_future(),
438             )
439             .expect("Brace your cache, the next Big Bang is coming (time overflow)");
440         cache_index.sort_unstable_by(|lhs, rhs| {
441             // sort by age
442             use CacheEntry::*;
443             match (lhs, rhs) {
444                 (Recognized { mtime: lhs_mt, .. }, Recognized { mtime: rhs_mt, .. }) => {
445                     match (*lhs_mt > future_tolerance, *rhs_mt > future_tolerance) {
446                         // later == younger
447                         (false, false) => rhs_mt.cmp(lhs_mt),
448                         // files from far future are treated as oldest recognized files
449                         // we want to delete them, so the cache keeps track of recent files
450                         // however, we don't delete them uncodintionally,
451                         // because .stats file can be overwritten with a meaningful mtime
452                         (true, false) => cmp::Ordering::Greater,
453                         (false, true) => cmp::Ordering::Less,
454                         (true, true) => cmp::Ordering::Equal,
455                     }
456                 }
457                 // unrecognized is kind of infinity
458                 (Recognized { .. }, Unrecognized { .. }) => cmp::Ordering::Less,
459                 (Unrecognized { .. }, Recognized { .. }) => cmp::Ordering::Greater,
460                 (Unrecognized { .. }, Unrecognized { .. }) => cmp::Ordering::Equal,
461             }
462         });
463 
464         // find "cut" boundary:
465         // - remove unrecognized files anyway,
466         // - remove some cache files if some quota has been exceeded
467         let mut total_size = 0u64;
468         let mut start_delete_idx = None;
469         let mut start_delete_idx_if_deleting_recognized_items: Option<usize> = None;
470 
471         let total_size_limit = self.cache_config.files_total_size_soft_limit();
472         let file_count_limit = self.cache_config.file_count_soft_limit();
473         let tsl_if_deleting = total_size_limit
474             .checked_mul(
475                 self.cache_config
476                     .files_total_size_limit_percent_if_deleting() as u64,
477             )
478             .unwrap()
479             / 100;
480         let fcl_if_deleting = file_count_limit
481             .checked_mul(self.cache_config.file_count_limit_percent_if_deleting() as u64)
482             .unwrap()
483             / 100;
484 
485         for (idx, item) in cache_index.iter().enumerate() {
486             let size = if let CacheEntry::Recognized { size, .. } = item {
487                 size
488             } else {
489                 start_delete_idx = Some(idx);
490                 break;
491             };
492 
493             total_size += size;
494             if start_delete_idx_if_deleting_recognized_items.is_none()
495                 && (total_size > tsl_if_deleting || (idx + 1) as u64 > fcl_if_deleting)
496             {
497                 start_delete_idx_if_deleting_recognized_items = Some(idx);
498             }
499 
500             if total_size > total_size_limit || (idx + 1) as u64 > file_count_limit {
501                 start_delete_idx = start_delete_idx_if_deleting_recognized_items;
502                 break;
503             }
504         }
505 
506         if let Some(idx) = start_delete_idx {
507             for item in &cache_index[idx..] {
508                 let (result, path, entity) = match item {
509                     CacheEntry::Recognized { path, .. }
510                     | CacheEntry::Unrecognized {
511                         path,
512                         is_dir: false,
513                     } => (fs::remove_file(path), path, "file"),
514                     CacheEntry::Unrecognized { path, is_dir: true } => {
515                         (fs::remove_dir_all(path), path, "directory")
516                     }
517                 };
518                 if let Err(err) = result {
519                     warn!(
520                         "Failed to remove {} during cleanup, path: {}, err: {}",
521                         entity,
522                         path.display(),
523                         err
524                     );
525                 }
526             }
527         }
528 
529         trace!("Task finished: clean up cache");
530     }
531 
532     // Be fault tolerant: list as much as you can, and ignore the rest
533     fn list_cache_contents(&self) -> Vec<CacheEntry> {
534         fn enter_dir(
535             vec: &mut Vec<CacheEntry>,
536             dir_path: &Path,
537             level: u8,
538             cache_config: &CacheConfig,
539         ) {
540             macro_rules! add_unrecognized {
541                 (file: $path:expr) => {
542                     add_unrecognized!(false, $path)
543                 };
544                 (dir: $path:expr) => {
545                     add_unrecognized!(true, $path)
546                 };
547                 ($is_dir:expr, $path:expr) => {
548                     vec.push(CacheEntry::Unrecognized {
549                         path: $path.to_path_buf(),
550                         is_dir: $is_dir,
551                     })
552                 };
553             }
554             macro_rules! add_unrecognized_and {
555                 ([ $( $ty:ident: $path:expr ),* ], $cont:stmt) => {{
556                     $( add_unrecognized!($ty: $path); )*
557                         $cont
558                 }};
559             }
560 
561             macro_rules! unwrap_or {
562                 ($result:expr, $cont:stmt, $err_msg:expr) => {
563                     unwrap_or!($result, $cont, $err_msg, dir_path)
564                 };
565                 ($result:expr, $cont:stmt, $err_msg:expr, $path:expr) => {
566                     unwrap_or_warn!(
567                         $result,
568                         $cont,
569                         format!("{}, level: {}", $err_msg, level),
570                         $path
571                     )
572                 };
573             }
574 
575             // If we fail to list a directory, something bad is happening anyway
576             // (something touches our cache or we have disk failure)
577             // Try to delete it, so we can stay within soft limits of the cache size.
578             // This comment applies later in this function, too.
579             let it = unwrap_or!(
580                 fs::read_dir(dir_path),
581                 add_unrecognized_and!([dir: dir_path], return),
582                 "Failed to list cache directory, deleting it"
583             );
584 
585             let mut cache_files = HashMap::new();
586             for entry in it {
587                 // read_dir() returns an iterator over results - in case some of them are errors
588                 // we don't know their names, so we can't delete them. We don't want to delete
589                 // the whole directory with good entries too, so we just ignore the erroneous entries.
590                 let entry = unwrap_or!(
591                     entry,
592                     continue,
593                     "Failed to read a cache dir entry (NOT deleting it, it still occupies space)"
594                 );
595                 let path = entry.path();
596                 match (level, path.is_dir()) {
597                     (0..=1, true) => enter_dir(vec, &path, level + 1, cache_config),
598                     (0..=1, false) => {
599                         if level == 0
600                             && path.file_stem() == Some(OsStr::new(".cleanup"))
601                                 && path.extension().is_some()
602                                 // assume it's cleanup lock
603                                 && !is_fs_lock_expired(
604                                     Some(&entry),
605                                     &path,
606                                     cache_config.cleanup_interval(),
607                                     cache_config.allowed_clock_drift_for_files_from_future(),
608                                 )
609                         {
610                             continue; // skip active lock
611                         }
612                         add_unrecognized!(file: path);
613                     }
614                     (2, false) => {
615                         match path.extension().and_then(OsStr::to_str) {
616                             // mod or stats file
617                             None | Some("stats") => {
618                                 cache_files.insert(path, entry);
619                             }
620 
621                             Some(ext) => {
622                                 // check if valid lock
623                                 let recognized = ext.starts_with("wip-")
624                                     && !is_fs_lock_expired(
625                                         Some(&entry),
626                                         &path,
627                                         cache_config.optimizing_compression_task_timeout(),
628                                         cache_config.allowed_clock_drift_for_files_from_future(),
629                                     );
630 
631                                 if !recognized {
632                                     add_unrecognized!(file: path);
633                                 }
634                             }
635                         }
636                     }
637                     (_, is_dir) => add_unrecognized!(is_dir, path),
638                 }
639             }
640 
641             // associate module with its stats & handle them
642             // assumption: just mods and stats
643             for (path, entry) in cache_files.iter() {
644                 let path_buf: PathBuf;
645                 let (mod_, stats_, is_mod) = match path.extension() {
646                     Some(_) => {
647                         path_buf = path.with_extension("");
648                         (
649                             cache_files.get(&path_buf).map(|v| (&path_buf, v)),
650                             Some((path, entry)),
651                             false,
652                         )
653                     }
654                     None => {
655                         path_buf = path.with_extension("stats");
656                         (
657                             Some((path, entry)),
658                             cache_files.get(&path_buf).map(|v| (&path_buf, v)),
659                             true,
660                         )
661                     }
662                 };
663 
664                 // construct a cache entry
665                 match (mod_, stats_, is_mod) {
666                     (Some((mod_path, mod_entry)), Some((stats_path, stats_entry)), true) => {
667                         let mod_metadata = unwrap_or!(
668                             mod_entry.metadata(),
669                             add_unrecognized_and!([file: stats_path, file: mod_path], continue),
670                             "Failed to get metadata, deleting BOTH module cache and stats files",
671                             mod_path
672                         );
673                         let stats_mtime = unwrap_or!(
674                             stats_entry.metadata().and_then(|m| m.modified()),
675                             add_unrecognized_and!(
676                                 [file: stats_path],
677                                 unwrap_or!(
678                                     mod_metadata.modified(),
679                                     add_unrecognized_and!(
680                                         [file: stats_path, file: mod_path],
681                                         continue
682                                     ),
683                                     "Failed to get mtime, deleting BOTH module cache and stats \
684                                      files",
685                                     mod_path
686                                 )
687                             ),
688                             "Failed to get metadata/mtime, deleting the file",
689                             stats_path
690                         );
691                         // .into() called for the SystemTimeStub if cfg(test)
692                         vec.push(CacheEntry::Recognized {
693                             path: mod_path.to_path_buf(),
694                             mtime: stats_mtime.into(),
695                             size: mod_metadata.len(),
696                         })
697                     }
698                     (Some(_), Some(_), false) => (), // was or will be handled by previous branch
699                     (Some((mod_path, mod_entry)), None, _) => {
700                         let (mod_metadata, mod_mtime) = unwrap_or!(
701                             mod_entry
702                                 .metadata()
703                                 .and_then(|md| md.modified().map(|mt| (md, mt))),
704                             add_unrecognized_and!([file: mod_path], continue),
705                             "Failed to get metadata/mtime, deleting the file",
706                             mod_path
707                         );
708                         // .into() called for the SystemTimeStub if cfg(test)
709                         vec.push(CacheEntry::Recognized {
710                             path: mod_path.to_path_buf(),
711                             mtime: mod_mtime.into(),
712                             size: mod_metadata.len(),
713                         })
714                     }
715                     (None, Some((stats_path, _stats_entry)), _) => {
716                         debug!("Found orphaned stats file: {}", stats_path.display());
717                         add_unrecognized!(file: stats_path);
718                     }
719                     _ => unreachable!(),
720                 }
721             }
722         }
723 
724         let mut vec = Vec::new();
725         enter_dir(
726             &mut vec,
727             self.cache_config.directory(),
728             0,
729             &self.cache_config,
730         );
731         vec
732     }
733 }
734 
735 fn read_stats_file(path: &Path) -> Option<ModuleCacheStatistics> {
736     fs::read_to_string(path)
737         .map_err(|err| {
738             trace!(
739                 "Failed to read stats file, path: {}, err: {}",
740                 path.display(),
741                 err
742             )
743         })
744         .and_then(|contents| {
745             toml::from_str::<ModuleCacheStatistics>(&contents).map_err(|err| {
746                 trace!(
747                     "Failed to parse stats file, path: {}, err: {}",
748                     path.display(),
749                     err,
750                 )
751             })
752         })
753         .ok()
754 }
755 
756 fn write_stats_file(path: &Path, stats: &ModuleCacheStatistics) -> bool {
757     toml::to_string_pretty(&stats)
758         .map_err(|err| {
759             warn!(
760                 "Failed to serialize stats file, path: {}, err: {}",
761                 path.display(),
762                 err
763             )
764         })
765         .and_then(|serialized| {
766             fs_write_atomic(path, "stats", serialized.as_bytes()).map_err(|_| ())
767         })
768         .is_ok()
769 }
770 
771 /// Tries to acquire a lock for specific task.
772 ///
773 /// Returns Some(path) to the lock if succeeds. The task path must not
774 /// contain any extension and have file stem.
775 ///
776 /// To release a lock you need either manually rename or remove it,
777 /// or wait until it expires and cleanup task removes it.
778 ///
779 /// Note: this function is racy. Main idea is: be fault tolerant and
780 ///       never block some task. The price is that we rarely do some task
781 ///       more than once.
782 fn acquire_task_fs_lock(
783     task_path: &Path,
784     timeout: Duration,
785     allowed_future_drift: Duration,
786 ) -> Option<PathBuf> {
787     assert!(task_path.extension().is_none());
788     assert!(task_path.file_stem().is_some());
789 
790     // list directory
791     let dir_path = task_path.parent()?;
792     let it = fs::read_dir(dir_path)
793         .map_err(|err| {
794             warn!(
795                 "Failed to list cache directory, path: {}, err: {}",
796                 dir_path.display(),
797                 err
798             )
799         })
800         .ok()?;
801 
802     // look for existing locks
803     for entry in it {
804         let entry = entry
805             .map_err(|err| {
806                 warn!(
807                     "Failed to list cache directory, path: {}, err: {}",
808                     dir_path.display(),
809                     err
810                 )
811             })
812             .ok()?;
813 
814         let path = entry.path();
815         if path.is_dir() || path.file_stem() != task_path.file_stem() {
816             continue;
817         }
818 
819         // check extension and mtime
820         match path.extension() {
821             None => continue,
822             Some(ext) => {
823                 if let Some(ext_str) = ext.to_str() {
824                     // if it's None, i.e. not valid UTF-8 string, then that's not our lock for sure
825                     if ext_str.starts_with("wip-")
826                         && !is_fs_lock_expired(Some(&entry), &path, timeout, allowed_future_drift)
827                     {
828                         return None;
829                     }
830                 }
831             }
832         }
833     }
834 
835     // create the lock
836     let lock_path = task_path.with_extension(format!("wip-{}", std::process::id()));
837     let _file = fs::OpenOptions::new()
838         .create_new(true)
839         .write(true)
840         .open(&lock_path)
841         .map_err(|err| {
842             warn!(
843                 "Failed to create lock file (note: it shouldn't exists): path: {}, err: {}",
844                 lock_path.display(),
845                 err
846             )
847         })
848         .ok()?;
849 
850     Some(lock_path)
851 }
852 
853 // we have either both, or just path; dir entry is desirable since on some platforms we can get
854 // metadata without extra syscalls
855 // furthermore: it's better to get a path if we have it instead of allocating a new one from the dir entry
856 fn is_fs_lock_expired(
857     entry: Option<&fs::DirEntry>,
858     path: &PathBuf,
859     threshold: Duration,
860     allowed_future_drift: Duration,
861 ) -> bool {
862     let mtime = match entry
863         .map_or_else(|| path.metadata(), |e| e.metadata())
864         .and_then(|metadata| metadata.modified())
865     {
866         Ok(mt) => mt,
867         Err(err) => {
868             warn!(
869                 "Failed to get metadata/mtime, treating as an expired lock, path: {}, err: {}",
870                 path.display(),
871                 err
872             );
873             return true; // can't read mtime, treat as expired, so this task will not be starved
874         }
875     };
876 
877     // DON'T use: mtime.elapsed() -- we must call SystemTime directly for the tests to be deterministic
878     match SystemTime::now().duration_since(mtime) {
879         Ok(elapsed) => elapsed >= threshold,
880         Err(err) => {
881             trace!(
882                 "Found mtime in the future, treating as a not expired lock, path: {}, err: {}",
883                 path.display(),
884                 err
885             );
886             // the lock is expired if the time is too far in the future
887             // it is fine to have network share and not synchronized clocks,
888             // but it's not good when user changes time in their system clock
889             err.duration() > allowed_future_drift
890         }
891     }
892 }
893 
894 #[cfg(test)]
895 mod tests;
896