| 1 | //! Host facilities that can affect LTX scheduling or timestamps. |
| 2 | |
| 3 | use std::ffi::OsString; |
| 4 | use std::future::Future; |
| 5 | use std::io; |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | use std::pin::Pin; |
| 8 | use std::sync::Arc; |
| 9 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 10 | |
| 11 | type HostFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>; |
| 12 | type BlockingJob = Box<dyn FnOnce() + Send>; |
| 13 | type NowUnixMillis = dyn Fn() -> i64 + Send + Sync; |
| 14 | type FileAge = dyn Fn(&Path) -> io::Result<Duration> + Send + Sync; |
| 15 | type ReadFile = dyn Fn(PathBuf) -> HostFuture<io::Result<Vec<u8>>> + Send + Sync; |
| 16 | type RunBlocking = dyn Fn(BlockingJob) -> HostFuture<Result<(), HostTaskError>> + Send + Sync; |
| 17 | |
| 18 | /// The filesystem metadata that the LTX engine uses. |
| 19 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 20 | pub struct HostMetadata { |
| 21 | pub len: u64, |
| 22 | pub is_dir: bool, |
| 23 | pub is_file: bool, |
| 24 | /// The modification time as Unix milliseconds, or zero when it is not |
| 25 | /// available from the host filesystem. |
| 26 | pub modified_unix_millis: i64, |
| 27 | } |
| 28 | |
| 29 | /// One directory entry returned by the injected filesystem. |
| 30 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 31 | pub struct HostDirEntry { |
| 32 | pub path: PathBuf, |
| 33 | pub file_name: OsString, |
| 34 | pub is_dir: bool, |
| 35 | } |
| 36 | |
| 37 | /// The operations on one open injected file. |
| 38 | pub trait HostFileIo: Send { |
| 39 | fn write_all(&mut self, bytes: &[u8]) -> io::Result<()>; |
| 40 | fn read_exact_at(&mut self, offset: u64, len: usize) -> io::Result<Vec<u8>>; |
| 41 | fn sync_all(&mut self) -> io::Result<()>; |
| 42 | } |
| 43 | |
| 44 | /// One open file owned by an injected filesystem. |
| 45 | pub struct HostFile { |
| 46 | inner: Box<dyn HostFileIo>, |
| 47 | } |
| 48 | |
| 49 | impl HostFile { |
| 50 | pub fn write_all(&mut self, bytes: &[u8]) -> io::Result<()> { |
| 51 | self.inner.write_all(bytes) |
| 52 | } |
| 53 | |
| 54 | pub fn read_exact_at(&mut self, offset: u64, len: usize) -> io::Result<Vec<u8>> { |
| 55 | self.inner.read_exact_at(offset, len) |
| 56 | } |
| 57 | |
| 58 | pub fn sync_all(&mut self) -> io::Result<()> { |
| 59 | self.inner.sync_all() |
| 60 | } |
| 61 | |
| 62 | pub fn from_io(inner: impl HostFileIo + 'static) -> Self { |
| 63 | Self { |
| 64 | inner: Box::new(inner), |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// The complete local-file surface used by celld and the LTX engine. |
| 70 | pub trait FileSystem: Send + Sync { |
| 71 | fn read(&self, path: &Path) -> io::Result<Vec<u8>>; |
| 72 | fn read_dir(&self, path: &Path) -> io::Result<Vec<HostDirEntry>>; |
| 73 | fn metadata(&self, path: &Path) -> io::Result<HostMetadata>; |
| 74 | fn create(&self, path: &Path) -> io::Result<HostFile>; |
| 75 | fn open(&self, path: &Path) -> io::Result<HostFile>; |
| 76 | fn write(&self, path: &Path, bytes: &[u8]) -> io::Result<()>; |
| 77 | fn sync_all(&self, path: &Path) -> io::Result<()>; |
| 78 | fn rename(&self, from: &Path, to: &Path) -> io::Result<()>; |
| 79 | fn remove_file(&self, path: &Path) -> io::Result<()>; |
| 80 | fn remove_dir_all(&self, path: &Path) -> io::Result<()>; |
| 81 | fn create_dir_all(&self, path: &Path) -> io::Result<()>; |
| 82 | } |
| 83 | |
| 84 | /// The ordinary direct-filesystem backend. |
| 85 | #[derive(Default)] |
| 86 | pub struct DirectFileSystem; |
| 87 | |
| 88 | struct DirectFile { |
| 89 | file: std::fs::File, |
| 90 | } |
| 91 | |
| 92 | #[allow(clippy::disallowed_methods)] |
| 93 | impl HostFileIo for DirectFile { |
| 94 | fn write_all(&mut self, bytes: &[u8]) -> io::Result<()> { |
| 95 | std::io::Write::write_all(&mut self.file, bytes) |
| 96 | } |
| 97 | |
| 98 | fn read_exact_at(&mut self, offset: u64, len: usize) -> io::Result<Vec<u8>> { |
| 99 | use std::io::{Read as _, Seek as _, SeekFrom}; |
| 100 | self.file.seek(SeekFrom::Start(offset))?; |
| 101 | let mut bytes = vec![0; len]; |
| 102 | self.file.read_exact(&mut bytes)?; |
| 103 | Ok(bytes) |
| 104 | } |
| 105 | |
| 106 | fn sync_all(&mut self) -> io::Result<()> { |
| 107 | self.file.sync_all() |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | #[allow(clippy::disallowed_methods)] |
| 112 | impl FileSystem for DirectFileSystem { |
| 113 | fn read(&self, path: &Path) -> io::Result<Vec<u8>> { |
| 114 | std::fs::read(path) |
| 115 | } |
| 116 | |
| 117 | fn read_dir(&self, path: &Path) -> io::Result<Vec<HostDirEntry>> { |
| 118 | std::fs::read_dir(path)? |
| 119 | .map(|entry| { |
| 120 | let entry = entry?; |
| 121 | let file_type = entry.file_type()?; |
| 122 | Ok(HostDirEntry { |
| 123 | path: entry.path(), |
| 124 | file_name: entry.file_name(), |
| 125 | is_dir: file_type.is_dir(), |
| 126 | }) |
| 127 | }) |
| 128 | .collect() |
| 129 | } |
| 130 | |
| 131 | fn metadata(&self, path: &Path) -> io::Result<HostMetadata> { |
| 132 | let metadata = std::fs::metadata(path)?; |
| 133 | let modified_unix_millis = metadata |
| 134 | .modified() |
| 135 | .ok() |
| 136 | .and_then(|time| time.duration_since(UNIX_EPOCH).ok()) |
| 137 | .map(|duration| duration.as_millis() as i64) |
| 138 | .unwrap_or(0); |
| 139 | Ok(HostMetadata { |
| 140 | len: metadata.len(), |
| 141 | is_dir: metadata.is_dir(), |
| 142 | is_file: metadata.is_file(), |
| 143 | modified_unix_millis, |
| 144 | }) |
| 145 | } |
| 146 | |
| 147 | fn create(&self, path: &Path) -> io::Result<HostFile> { |
| 148 | Ok(HostFile::from_io(DirectFile { |
| 149 | file: std::fs::File::create(path)?, |
| 150 | })) |
| 151 | } |
| 152 | |
| 153 | fn open(&self, path: &Path) -> io::Result<HostFile> { |
| 154 | Ok(HostFile::from_io(DirectFile { |
| 155 | file: std::fs::File::open(path)?, |
| 156 | })) |
| 157 | } |
| 158 | |
| 159 | fn write(&self, path: &Path, bytes: &[u8]) -> io::Result<()> { |
| 160 | std::fs::write(path, bytes) |
| 161 | } |
| 162 | |
| 163 | fn sync_all(&self, path: &Path) -> io::Result<()> { |
| 164 | std::fs::File::open(path)?.sync_all() |
| 165 | } |
| 166 | |
| 167 | fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { |
| 168 | std::fs::rename(from, to) |
| 169 | } |
| 170 | |
| 171 | fn remove_file(&self, path: &Path) -> io::Result<()> { |
| 172 | std::fs::remove_file(path) |
| 173 | } |
| 174 | |
| 175 | fn remove_dir_all(&self, path: &Path) -> io::Result<()> { |
| 176 | std::fs::remove_dir_all(path) |
| 177 | } |
| 178 | |
| 179 | fn create_dir_all(&self, path: &Path) -> io::Result<()> { |
| 180 | std::fs::create_dir_all(path) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /// A failure to dispatch or join one host blocking job. |
| 185 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 186 | pub struct HostTaskError { |
| 187 | message: String, |
| 188 | } |
| 189 | |
| 190 | impl HostTaskError { |
| 191 | pub fn new(message: impl Into<String>) -> Self { |
| 192 | Self { |
| 193 | message: message.into(), |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | impl std::fmt::Display for HostTaskError { |
| 199 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 200 | formatter.write_str(&self.message) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | impl std::error::Error for HostTaskError {} |
| 205 | |
| 206 | struct Inner { |
| 207 | now_unix_millis: Arc<NowUnixMillis>, |
| 208 | file_age: Arc<FileAge>, |
| 209 | read_file: Arc<ReadFile>, |
| 210 | run_blocking: Arc<RunBlocking>, |
| 211 | filesystem: Arc<dyn FileSystem>, |
| 212 | #[cfg(celld_internal_tests)] |
| 213 | drop_compaction_input: Arc<dyn Fn() -> bool + Send + Sync>, |
| 214 | } |
| 215 | |
| 216 | /// The clock and executor facilities used by the LTX engine. |
| 217 | /// |
| 218 | /// The default uses the host clock, filesystem, and Tokio executor. A caller |
| 219 | /// can inject one object when it needs to own these observations and jobs. |
| 220 | #[derive(Clone)] |
| 221 | pub struct LtxHost { |
| 222 | inner: Arc<Inner>, |
| 223 | } |
| 224 | |
| 225 | impl LtxHost { |
| 226 | /// Creates an injected host from four cohesive facilities. |
| 227 | pub fn new<N, A, R, RF, B, BF>(now: N, age: A, read: R, blocking: B) -> Self |
| 228 | where |
| 229 | N: Fn() -> i64 + Send + Sync + 'static, |
| 230 | A: Fn(&Path) -> io::Result<Duration> + Send + Sync + 'static, |
| 231 | R: Fn(PathBuf) -> RF + Send + Sync + 'static, |
| 232 | RF: Future<Output = io::Result<Vec<u8>>> + Send + 'static, |
| 233 | B: Fn(BlockingJob) -> BF + Send + Sync + 'static, |
| 234 | BF: Future<Output = Result<(), HostTaskError>> + Send + 'static, |
| 235 | { |
| 236 | Self { |
| 237 | inner: Arc::new(Inner { |
| 238 | now_unix_millis: Arc::new(now), |
| 239 | file_age: Arc::new(age), |
| 240 | read_file: Arc::new(move |path| Box::pin(read(path))), |
| 241 | run_blocking: Arc::new(move |job| Box::pin(blocking(job))), |
| 242 | filesystem: Arc::new(DirectFileSystem), |
| 243 | #[cfg(celld_internal_tests)] |
| 244 | drop_compaction_input: Arc::new(|| false), |
| 245 | }), |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | /// Selects the filesystem used by synchronous local LTX operations. |
| 250 | pub fn with_filesystem(mut self, filesystem: Arc<dyn FileSystem>) -> Self { |
| 251 | Arc::get_mut(&mut self.inner) |
| 252 | .expect("a fresh LtxHost has one owner") |
| 253 | .filesystem = filesystem; |
| 254 | self |
| 255 | } |
| 256 | |
| 257 | pub fn filesystem(&self) -> Arc<dyn FileSystem> { |
| 258 | self.inner.filesystem.clone() |
| 259 | } |
| 260 | |
| 261 | pub fn read(&self, path: &Path) -> io::Result<Vec<u8>> { |
| 262 | self.inner.filesystem.read(path) |
| 263 | } |
| 264 | |
| 265 | pub fn read_dir(&self, path: &Path) -> io::Result<Vec<HostDirEntry>> { |
| 266 | self.inner.filesystem.read_dir(path) |
| 267 | } |
| 268 | |
| 269 | pub fn metadata(&self, path: &Path) -> io::Result<HostMetadata> { |
| 270 | self.inner.filesystem.metadata(path) |
| 271 | } |
| 272 | |
| 273 | pub fn create(&self, path: &Path) -> io::Result<HostFile> { |
| 274 | self.inner.filesystem.create(path) |
| 275 | } |
| 276 | |
| 277 | pub fn open(&self, path: &Path) -> io::Result<HostFile> { |
| 278 | self.inner.filesystem.open(path) |
| 279 | } |
| 280 | |
| 281 | pub fn write(&self, path: &Path, bytes: &[u8]) -> io::Result<()> { |
| 282 | self.inner.filesystem.write(path, bytes) |
| 283 | } |
| 284 | |
| 285 | pub fn sync_all(&self, path: &Path) -> io::Result<()> { |
| 286 | self.inner.filesystem.sync_all(path) |
| 287 | } |
| 288 | |
| 289 | pub fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { |
| 290 | self.inner.filesystem.rename(from, to) |
| 291 | } |
| 292 | |
| 293 | pub fn remove_file(&self, path: &Path) -> io::Result<()> { |
| 294 | self.inner.filesystem.remove_file(path) |
| 295 | } |
| 296 | |
| 297 | pub fn remove_dir_all(&self, path: &Path) -> io::Result<()> { |
| 298 | self.inner.filesystem.remove_dir_all(path) |
| 299 | } |
| 300 | |
| 301 | pub fn create_dir_all(&self, path: &Path) -> io::Result<()> { |
| 302 | self.inner.filesystem.create_dir_all(path) |
| 303 | } |
| 304 | |
| 305 | /// Install the S1 compaction tooth. The callback is absent from ordinary |
| 306 | /// builds and is queried only while a test compaction selects its inputs. |
| 307 | #[cfg(celld_internal_tests)] |
| 308 | pub fn with_compaction_input_drop( |
| 309 | mut self, |
| 310 | armed: impl Fn() -> bool + Send + Sync + 'static, |
| 311 | ) -> Self { |
| 312 | Arc::get_mut(&mut self.inner) |
| 313 | .expect("a fresh LtxHost has one owner") |
| 314 | .drop_compaction_input = Arc::new(armed); |
| 315 | self |
| 316 | } |
| 317 | |
| 318 | #[cfg(celld_internal_tests)] |
| 319 | pub(crate) fn drop_compaction_input(&self) -> bool { |
| 320 | (self.inner.drop_compaction_input)() |
| 321 | } |
| 322 | |
| 323 | /// Returns the current wall time as Unix milliseconds. |
| 324 | pub fn now_unix_millis(&self) -> i64 { |
| 325 | (self.inner.now_unix_millis)() |
| 326 | } |
| 327 | |
| 328 | /// Returns the age of one file according to the host wall-clock view. |
| 329 | pub fn file_age(&self, path: &Path) -> io::Result<Duration> { |
| 330 | (self.inner.file_age)(path) |
| 331 | } |
| 332 | |
| 333 | /// Reads one compactor input through the host executor. |
| 334 | pub async fn read_file(&self, path: impl Into<PathBuf>) -> io::Result<Vec<u8>> { |
| 335 | (self.inner.read_file)(path.into()).await |
| 336 | } |
| 337 | |
| 338 | /// Runs one CPU or filesystem job through the host blocking executor. |
| 339 | pub async fn run_blocking<T, F>(&self, operation: F) -> Result<T, HostTaskError> |
| 340 | where |
| 341 | T: Send + 'static, |
| 342 | F: FnOnce() -> T + Send + 'static, |
| 343 | { |
| 344 | let (send, receive) = tokio::sync::oneshot::channel(); |
| 345 | let job = Box::new(move || { |
| 346 | let output = std::panic::catch_unwind(std::panic::AssertUnwindSafe(operation)) |
| 347 | .map_err(|_| HostTaskError::new("the host blocking job panicked")); |
| 348 | let _ = send.send(output); |
| 349 | }); |
| 350 | (self.inner.run_blocking)(job).await?; |
| 351 | receive |
| 352 | .await |
| 353 | .map_err(|_| HostTaskError::new("the host blocking job stopped without a result"))? |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | // This is the lower crate's production and stand-alone-test backend. celld |
| 358 | // injects an execution-domain-backed host on every engine path. |
| 359 | #[allow(clippy::disallowed_methods)] |
| 360 | impl Default for LtxHost { |
| 361 | fn default() -> Self { |
| 362 | Self::new( |
| 363 | || { |
| 364 | SystemTime::now() |
| 365 | .duration_since(UNIX_EPOCH) |
| 366 | .map(|duration| duration.as_millis() as i64) |
| 367 | .unwrap_or(0) |
| 368 | }, |
| 369 | |path| { |
| 370 | let modified = std::fs::metadata(path)?.modified()?; |
| 371 | Ok(SystemTime::now() |
| 372 | .duration_since(modified) |
| 373 | .unwrap_or(Duration::ZERO)) |
| 374 | }, |
| 375 | |path| async move { tokio::fs::read(path).await }, |
| 376 | |job| async move { |
| 377 | tokio::task::spawn_blocking(job) |
| 378 | .await |
| 379 | .map_err(|error| HostTaskError::new(error.to_string())) |
| 380 | }, |
| 381 | ) |
| 382 | } |
| 383 | } |