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
//! Directory storage backend (using Files and Directories).

use std::{fs, io, path::{Path, PathBuf}};

use fs2::FileExt;
use uuid::Uuid;

use super::{Error, Result, Storage};

/// Storage backed by a folder.
///
/// ## Locking strategy
///
/// This storage locks entries while they are being read or writen to. Thus, readers and writers
/// should be dropped as soon as possible to prevent resource starvation. Note that multiple readers
/// are allowed at once on the same entry, like a `RwLock` does.
///
/// Nothing prevents other programs from tempering with the files while they are locked, as the
/// locks are only advisory locks. This storage will always check for locks before doing
/// anything though.
///
/// ## Errors
///
/// All files in the folder are considered part of this storage. Thus, any unexpected event
/// (denied permission, interrupted, ...) in the folder will result in an error.
///
/// It is expected that the folder remains valid as long a the storage exists. Tempering
/// with the folder in any way (deleting it, moving it, removing permissions, ...) will result in
/// an error.
///
/// ## Panics
///
/// A panic will occur if a file can't be locked or unlocked by this storage.
#[derive(Debug, Clone)]
pub struct Directory {
    path: PathBuf
}

impl Directory {
    /// Create a new directory storage, or open it if it already exist.
    /// Folders are created recursively if needed.
    ///
    /// # Examples
    ///
    /// ```
    /// use dodo::prelude::*;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #   let path  = tempfile::tempdir()?;
    ///     let directory = Directory::new(&path)?;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// This will return an error in the following situations :
    ///
    /// * Folders didn't exists, and storage wasn't able to create it.
    /// * Path points at a file, not a folder.
    /// * Other IO specific errors (permission denied, invalid path, ...).
    pub fn new<P>(path: P) -> Result<Self>
        where P: AsRef<Path> {
        let path: PathBuf = path.as_ref().into();

        if !path.exists() {
            fs::create_dir_all(&path)?;
        }

        if path.is_dir() {
            Ok(Self {
                path
            })
        } else {
            Err(Error::Io(io::Error::new(
                io::ErrorKind::Other,
                format!("not a directory: {}", path.display()),
            )))
        }
    }
}

impl Storage for Directory {
    type Read = File;
    type Write = File;
    type Iterator = Iter;

    fn new(&mut self) -> Result<(Uuid, Self::Write)> {
        //Loop until we find a unused id. Having a id collision is very unlikely, but we never know...
        loop {
            let entry = Uuid::new_v4();
            match File::new(&self.path, entry) {
                Ok(writer) => {
                    return Ok((entry, writer));
                }
                Err(Error::Io(e)) if e.kind() == io::ErrorKind::AlreadyExists => {
                    continue;
                }
                Err(e) => {
                    return Err(e);
                }
            }
        }
    }

    fn read(&self, entry: Uuid) -> Result<Self::Read> {
        File::read(&self.path, entry)
    }

    fn write(&mut self, entry: Uuid) -> Result<Self::Write> {
        File::write(&self.path, entry)
    }

    fn overwrite(&mut self, entry: Uuid) -> Result<Self::Write> {
        File::overwrite(&self.path, entry)
    }

    fn delete(&mut self, entry: Uuid) -> Result<()> {
        match fs::remove_file(&self.path.join(entry.to_string())) {
            Ok(_) => Ok(()),
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(Error::Io(e))
        }
    }

    fn clear(&mut self) -> Result<()> {
        for entry in self.iter()?.filter_map(Result::ok) {
            self.delete(entry)?
        }
        Ok(())
    }

    fn iter(&self) -> Result<Self::Iterator> {
        Iter::open(&self.path)
    }
}

/// Directory entry.
///
/// When reading, holds a shared lock on the file. When writing, holds a exclusive lock on the file.
/// There can be multiple readers, but only one writer.
#[derive(Debug)]
pub struct File {
    file: fs::File
}

impl File {
    fn new<P>(path: P, entry: Uuid) -> Result<Self>
        where P: AsRef<Path> {
        Self::open_exclusive(fs::OpenOptions::new().create(true).write(true), path, entry)
    }

    fn read<P>(path: P, entry: Uuid) -> Result<Self>
        where P: AsRef<Path> {
        Self::open_shared(fs::OpenOptions::new().read(true), path, entry)
    }

    fn write<P>(path: P, entry: Uuid) -> Result<Self>
        where P: AsRef<Path> {
        Self::open_exclusive(fs::OpenOptions::new().create(true).write(true).truncate(true), path, entry)
    }

    fn overwrite<P>(path: P, entry: Uuid) -> Result<Self>
        where P: AsRef<Path> {
        Self::open_exclusive(fs::OpenOptions::new().write(true).truncate(true), path, entry)
    }

    fn open_shared<P>(options: &fs::OpenOptions, path: P, entry: Uuid) -> Result<Self>
        where P: AsRef<Path> {
        let path = path.as_ref().join(entry.to_string());
        match options.open(&path) {
            Ok(file) => {
                //Expected not to fail. Panic if it does.
                file.lock_shared().expect(&format!("unable to lock file: {}", path.display()));
                Ok(Self { file })
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                Err(Error::NotFound(entry))
            }
            Err(e) => {
                Err(Error::Io(e))
            }
        }
    }

    fn open_exclusive<P>(options: &fs::OpenOptions, path: P, entry: Uuid) -> Result<Self>
        where P: AsRef<Path> {
        let path = path.as_ref().join(entry.to_string());
        match options.open(&path) {
            Ok(file) => {
                //Expected not to fail. Panic if it does.
                file.lock_exclusive().expect(&format!("unable to lock file: {}", path.display()));
                Ok(Self { file })
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                Err(Error::NotFound(entry))
            }
            Err(e) => {
                Err(Error::Io(e))
            }
        }
    }
}

impl Drop for File {
    fn drop(&mut self) {
        //Expected not to fail. Panic if it does.
        self.file.unlock().expect("unable to unlock file")
    }
}

impl io::Read for File {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.file.read(buf)
    }
}

impl io::Write for File {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.file.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.file.flush()
    }
}

/// Directory iterator.
///
/// This iterator is lazy and doesn't lock anything. Thus, returned items might not even exist.
#[derive(Debug)]
pub struct Iter {
    iterator: fs::ReadDir
}

impl Iter {
    fn open<P>(path: P) -> Result<Self>
        where P: AsRef<Path> {
        Ok(Self {
            iterator: path.as_ref().read_dir()?
        })
    }
}

impl Iterator for Iter {
    type Item = Result<Uuid>;

    fn next(&mut self) -> Option<Self::Item> {
        use std::ffi::OsString;

        let into_string = |result: io::Result<fs::DirEntry>| -> Result<OsString> {
            result.map(|entry| entry.file_name()).map_err(From::from)
        };

        let into_id = |result: Result<OsString>| -> Result<Uuid> {
            result.and_then(|name| {
                name.into_string().map_err(|e| Error::Io(io::Error::new(
                    io::ErrorKind::Other,
                    format!("file has invalid unicode data in his name: {:?}", e),
                )))
            }).and_then(|name| {
                Uuid::parse_str(&name).map_err(From::from)
            })
        };

        self.iterator
            .next()
            .map(into_string)
            .map(into_id)
    }
}