Diffinery

homeflare/celldpublic

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