Diffinery

homeflare/celldpublic

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