zng_ext_fs_watcher/
lock.rs

1use std::time::Duration;
2
3#[cfg(not(target_arch = "wasm32"))]
4pub use fs4::fs_std::FileExt;
5
6#[cfg(target_arch = "wasm32")]
7pub trait FileExt {
8    fn try_lock_shared(&self) -> std::io::Result<()> {
9        not_supported()
10    }
11    fn try_lock_exclusive(&self) -> std::io::Result<()> {
12        not_supported()
13    }
14    fn unlock(&self) -> std::io::Result<()> {
15        not_supported()
16    }
17}
18#[cfg(target_arch = "wasm32")]
19impl FileExt for std::fs::File {}
20#[cfg(target_arch = "wasm32")]
21fn not_supported() -> std::io::Result<()> {
22    Err(std::io::Error::new(
23        std::io::ErrorKind::Other,
24        "operation not supported on wasm yet",
25    ))
26}
27
28/// Calls `fs4::FileExt::lock_exclusive` with a timeout.
29pub fn lock_exclusive(file: &impl FileExt, timeout: Duration) -> std::io::Result<()> {
30    lock_timeout(file, |f| f.try_lock_exclusive(), timeout)
31}
32
33/// Calls `fs4::FileExt::lock_shared` with a timeout.
34pub fn lock_shared(file: &impl FileExt, timeout: Duration) -> std::io::Result<()> {
35    lock_timeout(file, |f| f.try_lock_shared(), timeout)
36}
37
38#[cfg(target_arch = "wasm32")]
39
40pub fn lock_timeout<F: FileExt>(_: &F, _: impl Fn(&F) -> std::io::Result<()>, _: Duration) -> std::io::Result<()> {
41    not_supported()
42}
43#[cfg(not(target_arch = "wasm32"))]
44pub fn lock_timeout<F: FileExt>(file: &F, try_lock: impl Fn(&F) -> std::io::Result<()>, mut timeout: Duration) -> std::io::Result<()> {
45    let mut locked_error = None;
46    loop {
47        match try_lock(file) {
48            Ok(()) => return Ok(()),
49            Err(e) => {
50                if e.kind() != std::io::ErrorKind::WouldBlock
51                    && e.raw_os_error() != locked_error.get_or_insert_with(fs4::lock_contended_error).raw_os_error()
52                {
53                    return Err(e);
54                }
55
56                const INTERVAL: Duration = Duration::from_millis(10);
57                timeout = timeout.saturating_sub(INTERVAL);
58                if timeout.is_zero() {
59                    return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, e));
60                } else {
61                    std::thread::sleep(INTERVAL.min(timeout));
62                }
63            }
64        }
65    }
66}
67
68pub fn unlock_ok(file: &impl FileExt) -> std::io::Result<()> {
69    if let Err(e) = file.unlock() {
70        if let Some(_code) = e.raw_os_error() {
71            #[cfg(windows)]
72            if _code == 158 {
73                // ERROR_NOT_LOCKED
74                return Ok(());
75            }
76
77            #[cfg(unix)]
78            if _code == 22 {
79                // EINVAL
80                return Ok(());
81            }
82        }
83
84        Err(e)
85    } else {
86        Ok(())
87    }
88}