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
#![deny(rust_2018_idioms, unused, unused_import_braces, unused_qualifications, warnings)]

use {
    std::{
        fmt,
        fs::File as SyncFile,
        io::{
            self,
            Read as _,
            Write as _
        },
        mem::forget,
        num::ParseIntError,
        path::{
            Path,
            PathBuf
        },
        thread,
        time::Duration
    },
    async_std::{
        fs::{
            self,
            File
        },
        io::prelude::*,
        task::{
            block_on,
            sleep
        }
    },
    derive_more::From,
    heim::process::pid_exists
};

#[must_use = "must call the drop_async method to unlock"]
pub struct DirLock<'a>(&'a Path);

#[derive(Debug, From)]
pub enum Error {
    #[from(ignore)]
    Cloned(String, String),
    HeimProcess(heim::process::ProcessError),
    #[from(ignore)]
    Io(io::Error, Option<PathBuf>),
    ParseInt(ParseIntError)
}

impl Clone for Error {
    fn clone(&self) -> Error {
        match *self {
            Error::Cloned(ref display, ref debug) => Error::Cloned(display.clone(), debug.clone()),
            Error::HeimProcess(ref e) => Error::Cloned(format!("heim process error: {}", e), format!("{:?}", e)),
            Error::Io(ref e, Some(ref path)) => Error::Cloned(format!("I/O error at {}: {}", path.display(), e), format!("{:?}", e)),
            Error::Io(ref e, None) => Error::Cloned(format!("I/O error: {}", e), format!("{:?}", e)),
            Error::ParseInt(ref e) => Error::ParseInt(e.clone())
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Cloned(display, _) => display.fmt(f),
            Error::HeimProcess(e) => write!(f, "heim process error: {}", e),
            Error::Io(e, Some(path)) => write!(f, "I/O error at {}: {}", path.display(), e),
            Error::Io(e, None) => write!(f, "I/O error: {}", e),
            Error::ParseInt(e) => e.fmt(f)
        }
    }
}

trait IoResultExt {
    type T;

    fn at(self, path: impl AsRef<Path>) -> Self::T;
}

impl IoResultExt for io::Error {
    type T = Error;

    fn at(self, path: impl AsRef<Path>) -> Error {
        Error::Io(self, Some(path.as_ref().to_owned()))
    }
}

impl<T, E: IoResultExt> IoResultExt for Result<T, E> {
    type T = Result<T, E::T>;

    fn at(self, path: impl AsRef<Path>) -> Result<T, E::T> {
        self.map_err(|e| e.at(path))
    }
}

impl DirLock<'_> {
    pub async fn new(path: &impl AsRef<Path>) -> Result<DirLock<'_>, Error> {
        let path = path.as_ref();
        loop {
            match fs::create_dir(path).await { // see https://github.com/rust-lang/rustup.rs/issues/988
                Ok(()) => {
                    let pidfile = path.join("pid");
                    writeln!(SyncFile::create(&pidfile).at(&pidfile)?, "{}", std::process::id()).at(pidfile)?; //TODO replace SyncFile with File once format_args! is Sync
                    return Ok(DirLock(path));
                }
                Err(e) => match e.kind() {
                    io::ErrorKind::AlreadyExists => {
                        if match File::open(path.join("pid")).await {
                            Ok(mut f) => {
                                let mut buf = String::default();
                                f.read_to_string(&mut buf).await.at(path.join("pid"))?;
                                !buf.is_empty() // assume pidfile is still being written if empty //TODO check timestamp
                                && !pid_exists(buf.trim().parse()?).await?
                            }
                            Err(e) => if e.kind() == io::ErrorKind::NotFound {
                                false
                            } else {
                                return Err(e.at(path.join("pid")));
                            }
                        } {
                            DirLock(path).clean_up().await?;
                        }
                        sleep(Duration::from_secs(1)).await;
                        continue;
                    }
                    _ => { return Err(e.at(path)); }
                }
            }
        }
    }

    /// Blocks the current thread until the lock can be established.
    pub fn new_sync(path: &impl AsRef<Path>) -> Result<DirLock<'_>, Error> {
        let path = path.as_ref();
        loop {
            match std::fs::create_dir(path) { // see https://github.com/rust-lang/rustup.rs/issues/988
                Ok(()) => {
                    let pidfile = path.join("pid");
                    writeln!(SyncFile::create(&pidfile).at(&pidfile)?, "{}", std::process::id()).at(pidfile)?;
                    return Ok(DirLock(path));
                }
                Err(e) => match e.kind() {
                    io::ErrorKind::AlreadyExists => {
                        if match SyncFile::open(path.join("pid")) {
                            Ok(mut f) => {
                                let mut buf = String::default();
                                f.read_to_string(&mut buf).at(path.join("pid"))?;
                                !buf.is_empty() // assume pidfile is still being written if empty //TODO check timestamp
                                && !block_on(pid_exists(buf.trim().parse()?))?
                            }
                            Err(e) => if e.kind() == io::ErrorKind::NotFound {
                                false
                            } else {
                                return Err(e.at(path.join("pid")));
                            }
                        } {
                            DirLock(path).clean_up_sync()?;
                        }
                        thread::sleep(Duration::from_secs(1));
                        continue;
                    }
                    _ => { return Err(e.at(path)); }
                }
            }
        }
    }

    pub async fn drop_async(self) -> Result<(), Error> {
        self.clean_up().await?;
        forget(self);
        Ok(())
    }

    async fn clean_up(&self) -> Result<(), Error> {
        if let Err(e) = fs::remove_file(self.0.join("pid")).await {
            if e.kind() != io::ErrorKind::NotFound {
                return Err(e.at(self.0.join("pid")));
            }
        }
        if let Err(e) = fs::remove_dir(self.0).await {
            if e.kind() != io::ErrorKind::NotFound {
                return Err(e.at(self.0));
            }
        }
        Ok(())
    }

    fn clean_up_sync(&self) -> Result<(), Error> {
        if let Err(e) = std::fs::remove_file(self.0.join("pid")) {
            if e.kind() != io::ErrorKind::NotFound {
                return Err(e.at(self.0.join("pid")));
            }
        }
        if let Err(e) = std::fs::remove_dir(self.0) {
            if e.kind() != io::ErrorKind::NotFound {
                return Err(e.at(self.0));
            }
        }
        Ok(())
    }
}

impl Drop for DirLock<'_> {
    fn drop(&mut self) {
        self.clean_up_sync().expect("failed to clean up dir lock");
    }
}