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
//! Virtual file system interface for database storage.

use std::{fmt::Debug, io::Write, path::PathBuf};

#[cfg(feature = "fslock")]
use std::collections::HashMap;

use relative_path::{RelativePath, RelativePathBuf};
use vfs::{MemoryFS, VfsFileType, VfsPath};

use crate::error::Error;

/// Represents a virtual file system.
///
/// File paths are characters within pattern `[a-z0-9._]` in Unix style
/// where directory separators as slashes (`/`). Paths are specified in
/// relative notation such as `example/my_file.ext`.
///
/// Implementations are not expected to support directory traversal notations
/// or handling redundant slashes. Implementations can return an error in
/// those cases.
pub trait Vfs {
    /// Lock the file preventing other processes from accessing it.
    ///
    /// If the file is already locked, an error is returned.
    fn lock(&mut self, path: &str) -> Result<(), Error>;

    /// Unlock the file.
    ///
    /// If the file is not locked, an error is returned.
    fn unlock(&mut self, path: &str) -> Result<(), Error>;

    /// Read the contents of a file to a vector.
    fn read(&self, path: &str) -> Result<Vec<u8>, Error>;

    /// Write the contents to a file.
    ///
    /// The file will be created if it does not exist and existing data is
    /// overwritten.
    ///
    /// If `sync_option` is a flushing operation, it will flush data from
    /// buffers to persistent storage before returning.
    fn write(&mut self, path: &str, data: &[u8], sync_option: VfsSyncOption) -> Result<(), Error>;

    /// Flush buffered data of a file to persistent storage.
    ///
    /// If supported by the file system, the method calls the appropriate
    /// sync operation on an existing, writable file without modifying the file
    /// contents. Flush operations complete before returning.
    fn sync_file(&mut self, path: &str, sync_option: VfsSyncOption) -> Result<(), Error>;

    /// Delete a file.
    ///
    /// If the file does not exist, an error is returned.
    fn remove_file(&mut self, path: &str) -> Result<(), Error>;

    /// Return a vector of filenames in a directory.
    fn read_dir(&self, path: &str) -> Result<Vec<String>, Error>;

    /// Create a directory at the given path.
    ///
    /// The parent directory must exist.
    fn create_dir(&mut self, path: &str) -> Result<(), Error>;

    /// Create directories for all components of the path if they do not exist.
    fn create_dir_all(&mut self, path: &str) -> Result<(), Error> {
        let mut current_path = RelativePathBuf::default();
        for part in RelativePath::new(path).components() {
            current_path.push(part.as_str());

            if !self.exists(current_path.as_str())? {
                self.create_dir(current_path.as_str())?;
            }
        }

        Ok(())
    }

    /// Remove an empty directory.
    ///
    /// If the path is not an empty directory, an error is returned.
    fn remove_dir(&mut self, path: &str) -> Result<(), Error>;

    /// Remove empty directories in the path if they exist.
    fn remove_empty_dir_all(&mut self, path: &str) -> Result<(), Error> {
        let mut current_path = RelativePathBuf::from(path);

        loop {
            if current_path.as_str() != "" && self.read_dir(current_path.as_str())?.is_empty() {
                self.remove_dir(current_path.as_str())?;
            } else {
                break;
            }

            if let Some(parent) = current_path.parent() {
                current_path = parent.to_owned();
            } else {
                break;
            }
        }

        Ok(())
    }

    /// Rename a file.
    ///
    /// If the destination file path already exists, the file is overwritten.
    fn rename_file(&mut self, old_path: &str, new_path: &str) -> Result<(), Error>;

    /// Return whether the path is a directory.
    ///
    /// Returns an error if the path does not exist.
    fn is_dir(&self, path: &str) -> Result<bool, Error>;

    /// Return whether the path exists.
    fn exists(&self, path: &str) -> Result<bool, Error>;
}

/// File system synchronization options for synchronizing data to disk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VfsSyncOption {
    /// Don't require any flushing.
    None,

    /// Flush file content only. Equivalent to `File::sync_data()` or Unix `fdatasync()`.
    Data,

    /// Flush file content and metadata. Equivalent to `File::sync_all()` or Unix `fsync()`.
    All,
}

impl Default for VfsSyncOption {
    fn default() -> Self {
        Self::None
    }
}

/// A file system that is stored temporarily to memory.
#[derive(Clone)]
pub struct MemoryVfs {
    vfs: VfsPath,
}

impl MemoryVfs {
    /// Create a in-memory file system.
    pub fn new() -> Self {
        Self {
            vfs: VfsPath::new(MemoryFS::default()),
        }
    }
}

impl Default for MemoryVfs {
    fn default() -> Self {
        Self::new()
    }
}

impl Debug for MemoryVfs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "MemoryVfs")
    }
}

impl Vfs for MemoryVfs {
    fn lock(&mut self, _path: &str) -> Result<(), Error> {
        Ok(())
    }

    fn unlock(&mut self, _path: &str) -> Result<(), Error> {
        Ok(())
    }

    fn read(&self, path: &str) -> Result<Vec<u8>, Error> {
        let mut file = self.vfs.join(path)?.open_file()?;
        let mut buffer = Vec::new();
        file.read_to_end(&mut buffer)?;
        Ok(buffer)
    }

    fn write(&mut self, path: &str, data: &[u8], _sync_option: VfsSyncOption) -> Result<(), Error> {
        let mut file = self.vfs.join(path)?.create_file()?;
        file.write_all(data)?;
        Ok(())
    }

    fn sync_file(&mut self, _path: &str, _sync_option: VfsSyncOption) -> Result<(), Error> {
        Ok(())
    }

    fn remove_file(&mut self, path: &str) -> Result<(), Error> {
        self.vfs.join(path)?.remove_file()?;
        Ok(())
    }

    fn read_dir(&self, path: &str) -> Result<Vec<String>, Error> {
        let mut filenames = Vec::new();

        for sub_path in self.vfs.join(path)?.read_dir()? {
            filenames.push(sub_path.filename());
        }

        Ok(filenames)
    }

    fn create_dir(&mut self, path: &str) -> Result<(), Error> {
        self.vfs.join(path)?.create_dir()?;
        Ok(())
    }

    fn remove_dir(&mut self, path: &str) -> Result<(), Error> {
        self.vfs.join(path)?.remove_dir()?;
        Ok(())
    }

    fn rename_file(&mut self, old_path: &str, new_path: &str) -> Result<(), Error> {
        if self.exists(new_path)? {
            self.remove_file(new_path)?;
        }

        self.vfs
            .join(old_path)?
            .move_file(&self.vfs.join(new_path)?)?;

        Ok(())
    }

    fn is_dir(&self, path: &str) -> Result<bool, Error> {
        let metadata = self.vfs.join(path)?.metadata()?;
        Ok(matches!(metadata.file_type, VfsFileType::Directory))
    }

    fn exists(&self, path: &str) -> Result<bool, Error> {
        Ok(self.vfs.join(path)?.exists()?)
    }
}

#[cfg(feature = "fslock")]
type LockFileType = fslock::LockFile;

/// Interface to a real file system on disk.
pub struct OsVfs {
    root: PathBuf,

    #[cfg(feature = "fslock")]
    locks: HashMap<PathBuf, LockFileType>,
}

impl OsVfs {
    /// Create a file system interface to the given path.
    ///
    /// The given path is treated as the root for subsequent relative path
    /// operations.
    pub fn new<P>(root: P) -> Self
    where
        P: Into<PathBuf>,
    {
        Self {
            root: root.into(),
            #[cfg(feature = "fslock")]
            locks: HashMap::new(),
        }
    }
}

impl Debug for OsVfs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "OsVfs {{ path: {:?} }}", &self.root)
    }
}

impl Vfs for OsVfs {
    #[cfg(feature = "fslock")]
    fn lock(&mut self, path: &str) -> Result<(), Error> {
        let mut lock = fslock::LockFile::open(self.root.join(path).as_path())?;
        if !lock.try_lock()? {
            return Err(Error::Locked);
        }
        self.locks.insert(self.root.join(path), lock);

        Ok(())
    }
    #[cfg(not(feature = "fslock"))]
    fn lock(&mut self, _path: &str) -> Result<(), Error> {
        Err(Error::FileLockingUnavailable)
    }

    #[cfg(feature = "fslock")]
    fn unlock(&mut self, path: &str) -> Result<(), Error> {
        if let Some(mut lock) = self.locks.remove(&self.root.join(path)) {
            lock.unlock()?;
        } else {
            return Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "file not locked",
            )));
        }

        Ok(())
    }

    #[cfg(not(feature = "fslock"))]
    fn unlock(&mut self, _path: &str) -> Result<(), Error> {
        Err(Error::FileLockingUnavailable)
    }

    fn read(&self, path: &str) -> Result<Vec<u8>, Error> {
        Ok(std::fs::read(self.root.join(path))?)
    }

    fn write(&mut self, path: &str, data: &[u8], sync_option: VfsSyncOption) -> Result<(), Error> {
        match sync_option {
            VfsSyncOption::None => Ok(std::fs::write(self.root.join(path), data)?),
            VfsSyncOption::Data => {
                let mut file = std::fs::File::create(self.root.join(path))?;
                file.write_all(&data)?;
                file.sync_data()?;

                Ok(())
            }
            VfsSyncOption::All => {
                let mut file = std::fs::File::create(self.root.join(path))?;
                file.write_all(&data)?;
                file.sync_all()?;

                Ok(())
            }
        }
    }

    fn sync_file(&mut self, path: &str, sync_option: VfsSyncOption) -> Result<(), Error> {
        let file = std::fs::OpenOptions::new()
            .append(true)
            .open(self.root.join(path))?;

        match sync_option {
            VfsSyncOption::None => {}
            VfsSyncOption::Data => {
                file.sync_data()?;
            }
            VfsSyncOption::All => {
                file.sync_all()?;
            }
        }

        Ok(())
    }

    fn remove_file(&mut self, path: &str) -> Result<(), Error> {
        Ok(std::fs::remove_file(self.root.join(path))?)
    }

    fn read_dir(&self, path: &str) -> Result<Vec<String>, Error> {
        let dir = std::fs::read_dir(self.root.join(path))?;
        let mut filenames = Vec::new();

        for entry in dir {
            let entry = entry?;

            if let Ok(filename) = entry.file_name().into_string() {
                filenames.push(filename);
            }
        }

        Ok(filenames)
    }

    fn create_dir(&mut self, path: &str) -> Result<(), Error> {
        std::fs::create_dir(self.root.join(path))?;
        Ok(())
    }

    fn remove_dir(&mut self, path: &str) -> Result<(), Error> {
        std::fs::remove_dir(self.root.join(path))?;
        Ok(())
    }

    fn rename_file(&mut self, old_path: &str, new_path: &str) -> Result<(), Error> {
        std::fs::rename(self.root.join(old_path), self.root.join(new_path))?;
        Ok(())
    }

    fn is_dir(&self, path: &str) -> Result<bool, Error> {
        let metadata = std::fs::metadata(self.root.join(path))?;

        Ok(metadata.is_dir())
    }

    fn exists(&self, path: &str) -> Result<bool, Error> {
        Ok(self.root.join(path).exists())
    }
}

/// Wrapper that allows only read operations.
pub struct ReadOnlyVfs {
    inner: Box<dyn Vfs + Sync + Send>,
}

impl ReadOnlyVfs {
    /// Wrap a VFS.
    pub fn new(inner: Box<dyn Vfs + Sync + Send>) -> Self {
        Self { inner }
    }

    /// Return the wrapped VFS.
    pub fn into_inner(self) -> Box<dyn Vfs + Sync + Send> {
        self.inner
    }
}

impl Vfs for ReadOnlyVfs {
    fn lock(&mut self, path: &str) -> Result<(), Error> {
        self.inner.lock(path)
    }

    fn unlock(&mut self, path: &str) -> Result<(), Error> {
        self.inner.unlock(path)
    }

    fn read(&self, path: &str) -> Result<Vec<u8>, Error> {
        self.inner.read(path)
    }

    fn write(
        &mut self,
        _path: &str,
        _data: &[u8],
        _sync_option: VfsSyncOption,
    ) -> Result<(), Error> {
        Err(Error::ReadOnly)
    }

    fn sync_file(&mut self, _path: &str, _sync_option: VfsSyncOption) -> Result<(), Error> {
        Err(Error::ReadOnly)
    }

    fn remove_file(&mut self, _path: &str) -> Result<(), Error> {
        Err(Error::ReadOnly)
    }

    fn read_dir(&self, path: &str) -> Result<Vec<String>, Error> {
        self.inner.read_dir(path)
    }

    fn create_dir(&mut self, _path: &str) -> Result<(), Error> {
        Err(Error::ReadOnly)
    }

    fn remove_dir(&mut self, _path: &str) -> Result<(), Error> {
        Err(Error::ReadOnly)
    }

    fn rename_file(&mut self, _old_path: &str, _new_path: &str) -> Result<(), Error> {
        Err(Error::ReadOnly)
    }

    fn is_dir(&self, path: &str) -> Result<bool, Error> {
        self.inner.is_dir(path)
    }

    fn exists(&self, path: &str) -> Result<bool, Error> {
        self.inner.exists(path)
    }
}

impl Debug for ReadOnlyVfs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ReadOnlyVfs")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_recursive_helpers() {
        let mut vfs = MemoryVfs::new();

        vfs.create_dir_all("a/b/c").unwrap();
        vfs.write(
            "a/b/c/my_file",
            "hello world!".as_bytes(),
            VfsSyncOption::None,
        )
        .unwrap();
        vfs.remove_empty_dir_all("a/b/c").unwrap();
        assert!(vfs.exists("a/b/c").unwrap());
        vfs.remove_file("a/b/c/my_file").unwrap();
        vfs.remove_empty_dir_all("a/b/c").unwrap();
        assert!(!vfs.exists("a/b/c").unwrap());
    }
}