|
| 1 | +use std::collections::HashSet; |
| 2 | +use std::fmt; |
| 3 | +use std::io::{self, Write}; |
| 4 | +use std::path::{Path, PathBuf}; |
| 5 | +use std::sync::{Arc, RwLock}; |
| 6 | + |
| 7 | +use crate::directory::error::{DeleteError, OpenReadError, OpenWriteError}; |
| 8 | +use crate::directory::{Directory, DirectoryLock, FileHandle, FileSlice, Lock, TerminatingWrite, |
| 9 | + WatchCallback, WatchHandle, WritePtr}; |
| 10 | +use crate::directory::RamDirectory; |
| 11 | + |
| 12 | +/// A Directory that overlays a `RamDirectory` on top of a base `Directory`. |
| 13 | +/// |
| 14 | +/// - Writes (open_write and atomic_write) go to the in-memory overlay. |
| 15 | +/// - Reads first check the overlay, then fallback to the base directory. |
| 16 | +/// - sync_directory() persists overlay files that do not yet exist in the base directory. |
| 17 | +#[derive(Clone)] |
| 18 | +pub struct NrtDirectory { |
| 19 | + base: Box<dyn Directory>, |
| 20 | + overlay: RamDirectory, |
| 21 | + /// Tracks files written into the overlay to decide what to persist on sync. |
| 22 | + overlay_paths: Arc<RwLock<HashSet<PathBuf>>>, |
| 23 | +} |
| 24 | + |
| 25 | +impl NrtDirectory { |
| 26 | + /// Wraps a base directory with an NRT overlay. |
| 27 | + pub fn wrap(base: Box<dyn Directory>) -> NrtDirectory { |
| 28 | + NrtDirectory { |
| 29 | + base, |
| 30 | + overlay: RamDirectory::default(), |
| 31 | + overlay_paths: Arc::new(RwLock::new(HashSet::new())), |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + /// Persist overlay files into the base directory if missing there. |
| 36 | + fn persist_overlay_into_base(&self) -> crate::Result<()> { |
| 37 | + let snapshot_paths: Vec<PathBuf> = { |
| 38 | + let guard = self.overlay_paths.read().unwrap(); |
| 39 | + guard.iter().cloned().collect() |
| 40 | + }; |
| 41 | + for path in snapshot_paths { |
| 42 | + // Skip if base already has the file |
| 43 | + if self.base.exists(&path).unwrap_or(false) { |
| 44 | + continue; |
| 45 | + } |
| 46 | + // Read bytes from overlay |
| 47 | + let file_slice: FileSlice = match self.overlay.open_read(&path) { |
| 48 | + Ok(slice) => slice, |
| 49 | + Err(OpenReadError::FileDoesNotExist(_)) => continue, // was removed meanwhile |
| 50 | + Err(e) => return Err(e.into()), |
| 51 | + }; |
| 52 | + let bytes = file_slice |
| 53 | + .read_bytes() |
| 54 | + .map_err(|io_err| OpenReadError::IoError { |
| 55 | + io_error: Arc::new(io_err), |
| 56 | + filepath: path.clone(), |
| 57 | + })?; |
| 58 | + // Write to base |
| 59 | + let mut dest_wrt: WritePtr = self.base.open_write(&path)?; |
| 60 | + dest_wrt.write_all(bytes.as_slice())?; |
| 61 | + dest_wrt.terminate()?; |
| 62 | + } |
| 63 | + Ok(()) |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +impl fmt::Debug for NrtDirectory { |
| 68 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 69 | + write!(f, "NrtDirectory") |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +impl Directory for NrtDirectory { |
| 74 | + fn get_file_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>, OpenReadError> { |
| 75 | + if self.overlay.exists(path).unwrap_or(false) { |
| 76 | + return self.overlay.get_file_handle(path); |
| 77 | + } |
| 78 | + self.base.get_file_handle(path) |
| 79 | + } |
| 80 | + |
| 81 | + fn open_read(&self, path: &Path) -> Result<FileSlice, OpenReadError> { |
| 82 | + if self.overlay.exists(path).unwrap_or(false) { |
| 83 | + return self.overlay.open_read(path); |
| 84 | + } |
| 85 | + self.base.open_read(path) |
| 86 | + } |
| 87 | + |
| 88 | + fn delete(&self, path: &Path) -> Result<(), DeleteError> { |
| 89 | + let _ = self.overlay.delete(path); // best-effort |
| 90 | + self.base.delete(path) |
| 91 | + } |
| 92 | + |
| 93 | + fn exists(&self, path: &Path) -> Result<bool, OpenReadError> { |
| 94 | + if self.overlay.exists(path).unwrap_or(false) { |
| 95 | + return Ok(true); |
| 96 | + } |
| 97 | + self.base.exists(path) |
| 98 | + } |
| 99 | + |
| 100 | + fn open_write(&self, path: &Path) -> Result<WritePtr, OpenWriteError> { |
| 101 | + { |
| 102 | + let mut guard = self.overlay_paths.write().unwrap(); |
| 103 | + guard.insert(path.to_path_buf()); |
| 104 | + } |
| 105 | + self.overlay.open_write(path) |
| 106 | + } |
| 107 | + |
| 108 | + fn atomic_read(&self, path: &Path) -> Result<Vec<u8>, OpenReadError> { |
| 109 | + if self.overlay.exists(path).unwrap_or(false) { |
| 110 | + return self.overlay.atomic_read(path); |
| 111 | + } |
| 112 | + self.base.atomic_read(path) |
| 113 | + } |
| 114 | + |
| 115 | + fn atomic_write(&self, path: &Path, data: &[u8]) -> io::Result<()> { |
| 116 | + { |
| 117 | + let mut guard = self.overlay_paths.write().unwrap(); |
| 118 | + guard.insert(path.to_path_buf()); |
| 119 | + } |
| 120 | + self.overlay.atomic_write(path, data) |
| 121 | + } |
| 122 | + |
| 123 | + fn acquire_lock(&self, lock: &Lock) -> Result<DirectoryLock, crate::directory::error::LockError> { |
| 124 | + self.base.acquire_lock(lock) |
| 125 | + } |
| 126 | + |
| 127 | + fn watch(&self, watch_callback: WatchCallback) -> crate::Result<WatchHandle> { |
| 128 | + // Watch meta.json changes on the base directory |
| 129 | + self.base.watch(watch_callback) |
| 130 | + } |
| 131 | + |
| 132 | + fn sync_directory(&self) -> io::Result<()> { |
| 133 | + // Best effort: persist overlay, then sync base directory |
| 134 | + if let Err(err) = self.persist_overlay_into_base() { |
| 135 | + return Err(io::Error::new(io::ErrorKind::Other, format!("{err}"))); |
| 136 | + } |
| 137 | + self.base.sync_directory() |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | + |
0 commit comments