Diffinery

homeflare/celldpublic

celld/crates/ltx/src/paged_vfs.rs
681 lines · 27.0 KBRaw History
1//! paged_vfs.rs — a SQLite VFS that faults main-db pages in from the bucket.
2//!
3//! The fault-in model of paged restore. The main db is a real local file
4//! that starts sparse, sized to the pinned cut. On a read of a page the
5//! local file does not hold yet, the VFS fetches that page's run from the
6//! bucket ([`PageSource`]), writes it into the local file, then lets SQLite
7//! read it normally. SQLite otherwise runs as usual over the local file —
8//! WAL, page-1 writes, checkpoint — and faulting is hydration.
9//!
10//! It is a thin wrapper over a base VFS (the host's named VFS, or SQLite's
11//! default): every method forwards, except the main db's `xRead`, which
12//! faults first, `xWrite` and `xTruncate`, which keep the hydration set
13//! honest, and `xOpen`, which sizes the sparse file. The invariants:
14//!
15//! - One registration serves one database. The hydration set is per
16//! registration, shared by every connection to that file, so a checkpoint
17//! or an earlier fault by one connection is never overwritten by another
18//! connection re-faulting the older cut page.
19//! - A page is faulted at most once, and only when the local file does not
20//! hold newer bytes: a page a connection wrote (a checkpoint) is marked
21//! hydrated, and a run that arrives with a fault only fills pages not yet
22//! hydrated.
23//! - A page absent from the cut past the commit reads as
24//! the sparse file's zeros, and is marked resolved so it never faults again.
25//! - Pages truncated away are forgotten, so a later regrowth faults or
26//! writes them afresh rather than trusting stale marks.
27//! - A registration serves one file, the cell's database; any other main
28//! database opened by its name is a plain file, so no second sparse view
29//! can mark the cell's hydration set for bytes the cell never received.
30//! - The fault runs on the calling thread and touches no runtime; a failure
31//! surfaces to SQLite as `SQLITE_IOERR_READ` on that read.
32//! - Unregistering frees the registration; open files keep their own
33//! references to the reader and the hydration set, and SQLite opens
34//! nothing new through an unregistered VFS.
35
36use crate::ltx::lock_pgno;
37use crate::paged::PageSource;
38use rusqlite::ffi;
39use std::collections::HashSet;
40use std::ffi::{c_void, CStr, CString};
41use std::os::raw::{c_char, c_int};
42use std::path::Path;
43use std::sync::atomic::Ordering;
44use std::sync::{Arc, Mutex};
45
46/// Type-erased page reader so one VFS registration can serve any client type.
47pub trait PageReader: Send + Sync {
48 fn page_size(&self) -> u32;
49 fn commit(&self) -> u32;
50 /// The cut's bytes for `pgno` and the pages stored right after it that
51 /// came along in the same read (first entry is `pgno`); empty if the cut
52 /// has no such page.
53 fn read_run(&self, pgno: u32) -> crate::error::Result<Vec<(u32, Vec<u8>)>>;
54 /// Faults served so far, for the hydration count.
55 fn faults(&self) -> u64 {
56 0
57 }
58}
59
60impl PageReader for PageSource {
61 fn page_size(&self) -> u32 {
62 PageSource::page_size(self)
63 }
64 fn commit(&self) -> u32 {
65 PageSource::commit(self)
66 }
67 fn read_run(&self, pgno: u32) -> crate::error::Result<Vec<(u32, Vec<u8>)>> {
68 self.read_run_blocking(pgno)
69 }
70 fn faults(&self) -> u64 {
71 PageSource::faults(self)
72 }
73}
74
75/// Per-registration state, hung off the VFS `pAppData`.
76struct VfsAppData {
77 base: *mut ffi::sqlite3_vfs,
78 /// The cell's database, as the base VFS spells it: the one file the
79 /// registration serves.
80 path: CString,
81 reader: Arc<dyn PageReader>,
82 /// Files open through this registration. Unregistering with files still
83 /// open used to free the VFS under them: the pager's close deletes the
84 /// WAL through `xDelete`, which reads `pAppData` of the freed struct.
85 /// The registration is freed by whichever comes last, the unregister or
86 /// the final close.
87 open_files: std::sync::atomic::AtomicUsize,
88 retired: std::sync::atomic::AtomicBool,
89 /// Pages whose newest bytes the local main-db file already holds, shared
90 /// by every connection opened through this registration. Per-connection
91 /// sets would let a later connection re-fault the older cut page over a
92 /// page another connection already checkpointed — silent data rollback.
93 /// One registration serves one database, so registration scope is
94 /// database scope.
95 hydrated: Arc<Mutex<HashSet<u32>>>,
96}
97
98/// Our `sqlite3_file` subclass: SQLite reads `methods` (first field); the rest is
99/// ours. `base` is the underlying VFS's file; `state` its fault-in bookkeeping.
100#[repr(C)]
101struct PagedFile {
102 methods: *const ffi::sqlite3_io_methods,
103 base: *mut ffi::sqlite3_file,
104 state: *mut FileState,
105}
106
107struct FileState {
108 /// The registration, for the open-file count (see [`VfsAppData::open_files`]).
109 vfs: *mut ffi::sqlite3_vfs,
110 /// `Some` only for the main db; other files (WAL, journal) forward untouched.
111 reader: Option<Arc<dyn PageReader>>,
112 /// The registration's shared hydration set (see [`VfsAppData::hydrated`]).
113 hydrated: Arc<Mutex<HashSet<u32>>>,
114 page_size: u32,
115}
116
117unsafe fn base_vfs(vfs: *mut ffi::sqlite3_vfs) -> *mut ffi::sqlite3_vfs {
118 (*((*vfs).pAppData as *mut VfsAppData)).base
119}
120
121unsafe fn base_methods(file: *mut ffi::sqlite3_file) -> *const ffi::sqlite3_io_methods {
122 let paged = file as *mut PagedFile;
123 (*(*paged).base).pMethods
124}
125
126// ── file methods ────────────────────────────────────────────────────────────
127
128/// A panic here would unwind across `extern "C"` and abort the process; the
129/// fault path spawns threads and locks a mutex, both of which can panic.
130/// It is an I/O error to the query instead.
131unsafe extern "C" fn x_read(
132 file: *mut ffi::sqlite3_file,
133 buf: *mut c_void,
134 amt: c_int,
135 ofst: ffi::sqlite3_int64,
136) -> c_int {
137 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
138 x_read_inner(file, buf, amt, ofst)
139 }))
140 .unwrap_or(ffi::SQLITE_IOERR_READ)
141}
142
143unsafe fn x_read_inner(
144 file: *mut ffi::sqlite3_file,
145 buf: *mut c_void,
146 amt: c_int,
147 ofst: ffi::sqlite3_int64,
148) -> c_int {
149 let paged = file as *mut PagedFile;
150 let state = &*(*paged).state;
151 if let Some(reader) = &state.reader {
152 let ps = state.page_size.max(1) as i64;
153 let first = (ofst / ps) as u32 + 1;
154 let last = ((ofst + amt as i64 - 1) / ps) as u32 + 1;
155 for pgno in first..=last {
156 if state.hydrated.lock().unwrap().contains(&pgno) {
157 continue;
158 }
159 // The fetch runs without the lock, so a fault by one connection
160 // never stalls another's read of a hydrated page, and a
161 // background hydration step never stalls a foreground fault.
162 // Two faults of one run both fetch; the loser writes nothing.
163 let run = match reader.read_run(pgno) {
164 Ok(run) => run,
165 Err(_) => return ffi::SQLITE_IOERR_READ,
166 };
167 let mut hydrated = state.hydrated.lock().unwrap();
168 if hydrated.contains(&pgno) {
169 continue;
170 }
171 // Absent in the cut. Past the commit (or the lock page) the
172 // sparse file's zeros stand; mark resolved so we do not re-fault.
173 // Inside it the map is broken — a plan starts with a snapshot,
174 // and a snapshot carries every page — and zeros would go out as
175 // data (a 2 GB opener two thirds holes, fleet 2026-09-02): fail
176 // the read instead.
177 if run.is_empty() {
178 if pgno <= reader.commit() && pgno != lock_pgno(ps as u32) {
179 return ffi::SQLITE_IOERR_READ;
180 }
181 hydrated.insert(pgno);
182 continue;
183 }
184 // Hydrate the whole run, except a page that already holds newer
185 // bytes (a checkpoint, or an earlier run) — the cut is older.
186 for (pgno_, page) in run {
187 if pgno_ != pgno && hydrated.contains(&pgno_) {
188 continue;
189 }
190 let base = (*paged).base;
191 let write = (*base_methods(file)).xWrite.unwrap();
192 let rc = write(
193 base,
194 page.as_ptr() as *const c_void,
195 page.len() as c_int,
196 (pgno_ as i64 - 1) * ps,
197 );
198 if rc != ffi::SQLITE_OK {
199 return rc;
200 }
201 hydrated.insert(pgno_);
202 }
203 }
204 }
205 let read = (*base_methods(file)).xRead.unwrap();
206 read((*paged).base, buf, amt, ofst)
207}
208
209unsafe extern "C" fn x_write(
210 file: *mut ffi::sqlite3_file,
211 buf: *const c_void,
212 amt: c_int,
213 ofst: ffi::sqlite3_int64,
214) -> c_int {
215 // A write (e.g. a checkpoint) establishes the newest bytes for its pages, so
216 // mark them hydrated to keep a later read from faulting an older cut page
217 // over them.
218 let paged = file as *mut PagedFile;
219 let state = &*(*paged).state;
220 if state.reader.is_some() {
221 let ps = state.page_size.max(1) as i64;
222 let first = (ofst / ps) as u32 + 1;
223 let last = ((ofst + amt as i64 - 1) / ps) as u32 + 1;
224 let mut hydrated = state.hydrated.lock().unwrap();
225 let write = (*base_methods(file)).xWrite.unwrap();
226 let rc = write((*paged).base, buf, amt, ofst);
227 // Only bytes that landed count: a mark on a failed write would turn
228 // the page into a hole the fault path never fills.
229 if rc == ffi::SQLITE_OK {
230 hydrated.extend(first..=last);
231 }
232 return rc;
233 }
234 let write = (*base_methods(file)).xWrite.unwrap();
235 write((*paged).base, buf, amt, ofst)
236}
237
238unsafe extern "C" fn x_close(file: *mut ffi::sqlite3_file) -> c_int {
239 let paged = file as *mut PagedFile;
240 let rc = match (*base_methods(file)).xClose {
241 Some(close) => close((*paged).base),
242 None => ffi::SQLITE_OK,
243 };
244 ffi::sqlite3_free((*paged).base as *mut c_void);
245 let state = Box::from_raw((*paged).state);
246 let vfs = state.vfs;
247 drop(state);
248 let app = &*((*vfs).pAppData as *mut VfsAppData);
249 let last = app.open_files.fetch_sub(1, Ordering::AcqRel) == 1;
250 if last && app.retired.load(Ordering::Acquire) {
251 free_vfs(vfs);
252 }
253 rc
254}
255
256/// Frees a registration's allocations: after its unregister, once no file
257/// is open through it.
258unsafe fn free_vfs(vfs: *mut ffi::sqlite3_vfs) {
259 drop(Box::from_raw((*vfs).pAppData as *mut VfsAppData));
260 drop(CString::from_raw((*vfs).zName as *mut c_char));
261 drop(Box::from_raw(vfs));
262}
263
264/// Forward an io-method to the base file verbatim.
265macro_rules! forward_io {
266 ($name:ident ( $($arg:ident : $ty:ty),* ) $(-> $ret:ty)? => $field:ident) => {
267 unsafe extern "C" fn $name(file: *mut ffi::sqlite3_file $(, $arg: $ty)*) $(-> $ret)? {
268 let paged = file as *mut PagedFile;
269 let m = (*base_methods(file)).$field.unwrap();
270 m((*paged).base $(, $arg)*)
271 }
272 };
273}
274
275unsafe extern "C" fn x_truncate(file: *mut ffi::sqlite3_file, size: ffi::sqlite3_int64) -> c_int {
276 // Pages past the new size are gone from the local file; drop their marks
277 // so a later regrowth faults or writes them afresh instead of reading
278 // the base file's zeros as hydrated data.
279 let paged = file as *mut PagedFile;
280 let state = &*(*paged).state;
281 if state.reader.is_some() {
282 let ps = state.page_size.max(1) as i64;
283 let keep = ((size + ps - 1) / ps).max(0) as u32;
284 state.hydrated.lock().unwrap().retain(|pgno| *pgno <= keep);
285 }
286 let truncate = (*base_methods(file)).xTruncate.unwrap();
287 truncate((*paged).base, size)
288}
289forward_io!(x_sync(flags: c_int) -> c_int => xSync);
290forward_io!(x_file_size(size: *mut ffi::sqlite3_int64) -> c_int => xFileSize);
291forward_io!(x_lock(lock: c_int) -> c_int => xLock);
292forward_io!(x_unlock(lock: c_int) -> c_int => xUnlock);
293forward_io!(x_check_reserved_lock(out: *mut c_int) -> c_int => xCheckReservedLock);
294forward_io!(x_file_control(op: c_int, arg: *mut c_void) -> c_int => xFileControl);
295forward_io!(x_sector_size() -> c_int => xSectorSize);
296forward_io!(x_device_characteristics() -> c_int => xDeviceCharacteristics);
297forward_io!(x_shm_map(pg: c_int, sz: c_int, ext: c_int, out: *mut *mut c_void) -> c_int => xShmMap);
298forward_io!(x_shm_lock(ofst: c_int, n: c_int, flags: c_int) -> c_int => xShmLock);
299forward_io!(x_shm_unmap(delete: c_int) -> c_int => xShmUnmap);
300
301unsafe extern "C" fn x_shm_barrier(file: *mut ffi::sqlite3_file) {
302 if let Some(barrier) = (*base_methods(file)).xShmBarrier {
303 let paged = file as *mut PagedFile;
304 barrier((*paged).base);
305 }
306}
307
308static PAGED_IO_METHODS: ffi::sqlite3_io_methods = ffi::sqlite3_io_methods {
309 iVersion: 2,
310 xClose: Some(x_close),
311 xRead: Some(x_read),
312 xWrite: Some(x_write),
313 xTruncate: Some(x_truncate),
314 xSync: Some(x_sync),
315 xFileSize: Some(x_file_size),
316 xLock: Some(x_lock),
317 xUnlock: Some(x_unlock),
318 xCheckReservedLock: Some(x_check_reserved_lock),
319 xFileControl: Some(x_file_control),
320 xSectorSize: Some(x_sector_size),
321 xDeviceCharacteristics: Some(x_device_characteristics),
322 xShmMap: Some(x_shm_map),
323 xShmLock: Some(x_shm_lock),
324 xShmBarrier: Some(x_shm_barrier),
325 xShmUnmap: Some(x_shm_unmap),
326 xFetch: None,
327 xUnfetch: None,
328};
329
330// ── vfs methods ───────────────────────────────────────────────────────────────
331
332/// The path SQLite hands `xOpen` is the base VFS's full pathname (absolute,
333/// symlinks resolved on unix), so the registered path is spelled the same
334/// way, by the same VFS, before the comparison.
335unsafe fn full_pathname(base: *mut ffi::sqlite3_vfs, path: &Path) -> Option<CString> {
336 let raw = CString::new(path.as_os_str().as_encoded_bytes()).ok()?;
337 let mut out = vec![0u8; (*base).mxPathname as usize + 1];
338 let full = (*base).xFullPathname?;
339 let rc = full(
340 base,
341 raw.as_ptr(),
342 out.len() as c_int,
343 out.as_mut_ptr().cast(),
344 );
345 // SQLITE_OK_SYMLINK (OK in the low byte) reports a resolved symlink.
346 if rc & 0xff != ffi::SQLITE_OK {
347 return None;
348 }
349 CStr::from_bytes_until_nul(&out).ok().map(CStr::to_owned)
350}
351
352unsafe extern "C" fn x_open(
353 vfs: *mut ffi::sqlite3_vfs,
354 name: *const c_char,
355 file: *mut ffi::sqlite3_file,
356 flags: c_int,
357 out_flags: *mut c_int,
358) -> c_int {
359 let app = &*((*vfs).pAppData as *mut VfsAppData);
360 let base = app.base;
361 // A separate base file, sized as the base VFS expects.
362 let base_file = ffi::sqlite3_malloc((*base).szOsFile) as *mut ffi::sqlite3_file;
363 if base_file.is_null() {
364 return ffi::SQLITE_NOMEM;
365 }
366 std::ptr::write_bytes(base_file as *mut u8, 0, (*base).szOsFile as usize);
367
368 let open = (*base).xOpen.unwrap();
369 let rc = open(base, name, base_file, flags, out_flags);
370 if rc != ffi::SQLITE_OK {
371 ffi::sqlite3_free(base_file as *mut c_void);
372 return rc;
373 }
374
375 // The registration serves one file: the cell's database. Any other
376 // main database opened by this VFS name (a backup destination, an
377 // inspection copy, a neighbour's file) is a plain file, because a second
378 // sparse view of the cut would share the hydration set and mark pages
379 // the cell's file never received, so the cell reads holes
380 // (CelldPagedVfs.tla, `BreakSecondFileShares`).
381 let is_cell = flags & ffi::SQLITE_OPEN_MAIN_DB != 0
382 && !name.is_null()
383 && CStr::from_ptr(name) == app.path.as_c_str();
384 let (reader, page_size) = if is_cell {
385 (Some(app.reader.clone()), app.reader.page_size())
386 } else {
387 (None, 0)
388 };
389 let state = Box::into_raw(Box::new(FileState {
390 vfs,
391 reader,
392 hydrated: app.hydrated.clone(),
393 page_size,
394 }));
395 app.open_files.fetch_add(1, Ordering::AcqRel);
396
397 let paged = file as *mut PagedFile;
398 (*paged).methods = &PAGED_IO_METHODS;
399 (*paged).base = base_file;
400 (*paged).state = state;
401
402 // Size an EMPTY local main-db file to the cut so its logical size is
403 // right and un-faulted pages read as holes we intercept. A later open
404 // (the actor's connection, an alarm read) finds a file a checkpoint may
405 // have grown past the cut; sizing it again would cut those pages off
406 // while their hydration marks survive (CelldPagedVfs.tla,
407 // `BreakOpenTruncates`).
408 if is_cell {
409 let methods = &*base_methods(file);
410 let mut size: ffi::sqlite3_int64 = 0;
411 let rc = (methods.xFileSize.unwrap())(base_file, &mut size);
412 if rc != ffi::SQLITE_OK {
413 return rc;
414 }
415 if size == 0 {
416 let bytes = i64::from(app.reader.page_size()) * i64::from(app.reader.commit());
417 let rc = (methods.xTruncate.unwrap())(base_file, bytes);
418 if rc != ffi::SQLITE_OK {
419 return rc;
420 }
421 }
422 }
423 ffi::SQLITE_OK
424}
425
426macro_rules! forward_vfs {
427 ($name:ident ( $($arg:ident : $ty:ty),* ) $(-> $ret:ty)? => $field:ident) => {
428 unsafe extern "C" fn $name(vfs: *mut ffi::sqlite3_vfs $(, $arg: $ty)*) $(-> $ret)? {
429 let base = base_vfs(vfs);
430 let m = (*base).$field.unwrap();
431 m(base $(, $arg)*)
432 }
433 };
434}
435
436forward_vfs!(x_delete(name: *const c_char, sync: c_int) -> c_int => xDelete);
437forward_vfs!(x_access(name: *const c_char, flags: c_int, out: *mut c_int) -> c_int => xAccess);
438forward_vfs!(x_full_pathname(name: *const c_char, n: c_int, out: *mut c_char) -> c_int => xFullPathname);
439forward_vfs!(x_randomness(n: c_int, out: *mut c_char) -> c_int => xRandomness);
440forward_vfs!(x_sleep(micros: c_int) -> c_int => xSleep);
441forward_vfs!(x_current_time(out: *mut f64) -> c_int => xCurrentTime);
442forward_vfs!(x_get_last_error(n: c_int, out: *mut c_char) -> c_int => xGetLastError);
443
444/// A process-unique suffix for each registration, so re-activations never
445/// collide on a name: SQLite finds a VFS by name, process-wide, and an
446/// unregistered name may still have files open through it.
447static REGISTRATION_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
448
449/// The next registration's name, unique in this process.
450pub fn next_registration_name() -> String {
451 format!(
452 "celld-paged-{}",
453 REGISTRATION_SEQ.fetch_add(1, Ordering::SeqCst)
454 )
455}
456
457/// Registers a paged VFS named `name` that faults the main db's pages in from
458/// `reader`. celld opens the cell's database through this VFS name. Call
459/// [`unregister_paged_vfs`] when the cell closes.
460///
461/// `base` names the VFS the paged one wraps; `None` is SQLite's default.
462/// celld passes its own named VFS when it runs one, so the local file's I/O
463/// stays under that host's control — the deterministic simulation in
464/// particular, which cannot judge a crash image written past it.
465pub fn register_paged_vfs(
466 name: &str,
467 base: Option<&str>,
468 path: &Path,
469 reader: Arc<dyn PageReader>,
470) -> crate::error::Result<()> {
471 let cname = CString::new(name).map_err(|_| crate::error::Error::LTXCorrupted)?;
472 let base_name = base
473 .map(CString::new)
474 .transpose()
475 .map_err(|_| crate::error::Error::LTXCorrupted)?;
476 unsafe {
477 let base =
478 ffi::sqlite3_vfs_find(base_name.as_ref().map_or(std::ptr::null(), |n| n.as_ptr()));
479 if base.is_null() {
480 return Err(crate::error::Error::Other("no base sqlite VFS".into()));
481 }
482 let Some(path) = full_pathname(base, path) else {
483 return Err(crate::error::Error::Other("paged vfs path".into()));
484 };
485 let app = Box::into_raw(Box::new(VfsAppData {
486 base,
487 path,
488 reader,
489 hydrated: Arc::new(Mutex::new(HashSet::new())),
490 open_files: std::sync::atomic::AtomicUsize::new(0),
491 retired: std::sync::atomic::AtomicBool::new(false),
492 }));
493 let vfs = Box::into_raw(Box::new(ffi::sqlite3_vfs {
494 iVersion: 2,
495 szOsFile: std::mem::size_of::<PagedFile>() as c_int,
496 mxPathname: (*base).mxPathname,
497 pNext: std::ptr::null_mut(),
498 zName: cname.into_raw(),
499 pAppData: app as *mut c_void,
500 xOpen: Some(x_open),
501 xDelete: Some(x_delete),
502 xAccess: Some(x_access),
503 xFullPathname: Some(x_full_pathname),
504 xDlOpen: (*base).xDlOpen,
505 xDlError: (*base).xDlError,
506 xDlSym: (*base).xDlSym,
507 xDlClose: (*base).xDlClose,
508 xRandomness: Some(x_randomness),
509 xSleep: Some(x_sleep),
510 xCurrentTime: Some(x_current_time),
511 xGetLastError: Some(x_get_last_error),
512 xCurrentTimeInt64: None,
513 xSetSystemCall: None,
514 xGetSystemCall: None,
515 xNextSystemCall: None,
516 }));
517 let rc = ffi::sqlite3_vfs_register(vfs, 0);
518 if rc != ffi::SQLITE_OK {
519 return Err(crate::error::Error::Other(
520 format!("register vfs {name}: {rc}").into(),
521 ));
522 }
523 }
524 Ok(())
525}
526
527/// How much of the cut the cell's file holds.
528#[derive(Clone, Copy, Debug, PartialEq, Eq)]
529pub struct Hydration {
530 /// Pages of the cut the file holds (the lock page never counts).
531 pub hydrated: u32,
532 /// Pages the cut has, less the lock page.
533 pub total: u32,
534 /// Faults the registration served so far, foreground and background.
535 pub faults: u64,
536}
537
538impl Hydration {
539 pub fn complete(&self) -> bool {
540 self.hydrated >= self.total
541 }
542}
543
544/// The registration's hydration count, or `None` for an unknown name.
545pub fn hydration(name: &str) -> Option<Hydration> {
546 let cname = CString::new(name).ok()?;
547 unsafe {
548 let vfs = ffi::sqlite3_vfs_find(cname.as_ptr());
549 if vfs.is_null() {
550 return None;
551 }
552 let app = &*((*vfs).pAppData as *mut VfsAppData);
553 let commit = app.reader.commit();
554 let lock = lock_pgno(app.reader.page_size());
555 let hydrated = app.hydrated.lock().unwrap();
556 Some(Hydration {
557 hydrated: (1..=commit)
558 .filter(|p| *p != lock && hydrated.contains(p))
559 .count() as u32,
560 total: commit - u32::from(lock <= commit),
561 faults: app.reader.faults(),
562 })
563 }
564}
565
566/// Faults the rest of the cut in, a run at a time, through the VFS's own
567/// read path: a connection on the cell's file whose reads are issued below
568/// the pager, so every page arrives the way a foreground fault brings it and
569/// nothing else changes. The caller paces the steps and stops them; a
570/// hydrated cell reads only its local file, and its faults are inert.
571pub struct Hydrator {
572 conn: rusqlite::Connection,
573 name: String,
574 cursor: u32,
575}
576
577impl Hydrator {
578 pub fn open(name: &str, path: &Path) -> crate::error::Result<Self> {
579 let conn = rusqlite::Connection::open_with_flags_and_vfs(
580 path,
581 rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
582 name,
583 )
584 .map_err(|error| crate::error::Error::Other(format!("hydrator open: {error}").into()))?;
585 Ok(Self {
586 conn,
587 name: name.to_string(),
588 cursor: 1,
589 })
590 }
591
592 /// Faults in the next hole and the holes after it until at least `pages`
593 /// pages arrived (a fault brings a run, so one read can bring many) or
594 /// the cut is complete; returns the count afterwards.
595 pub fn step(&mut self, pages: u32) -> crate::error::Result<Hydration> {
596 let cname =
597 CString::new(self.name.as_str()).map_err(|_| crate::error::Error::LTXCorrupted)?;
598 let (page_size, commit, lock) = unsafe {
599 let vfs = ffi::sqlite3_vfs_find(cname.as_ptr());
600 if vfs.is_null() {
601 return Err(crate::error::Error::Other("hydrator: vfs is gone".into()));
602 }
603 let app = &*((*vfs).pAppData as *mut VfsAppData);
604 let page_size = app.reader.page_size();
605 let commit = app.reader.commit();
606 (page_size, commit, lock_pgno(page_size))
607 };
608 let mut file: *mut ffi::sqlite3_file = std::ptr::null_mut();
609 // SAFETY: `conn` is open, and FILE_POINTER hands out its main file.
610 let rc = unsafe {
611 ffi::sqlite3_file_control(
612 self.conn.handle(),
613 c"main".as_ptr(),
614 ffi::SQLITE_FCNTL_FILE_POINTER,
615 (&mut file as *mut *mut ffi::sqlite3_file).cast(),
616 )
617 };
618 if rc != ffi::SQLITE_OK || file.is_null() {
619 return Err(crate::error::Error::Other("hydrator: no main file".into()));
620 }
621 let mut page = vec![0u8; page_size as usize];
622 let gone = || crate::error::Error::Other("hydrator: vfs is gone".into());
623 let start = hydration(&self.name).ok_or_else(gone)?.hydrated;
624 // The count is recomputed only after a read that faulted: a page the
625 // file already holds costs one set lookup, never a walk of the cut,
626 // or a whale's step would be quadratic in its pages (the fleet's fill
627 // made no progress in ten minutes).
628 while self.cursor <= commit {
629 let pgno = self.cursor;
630 self.cursor += 1;
631 if pgno == lock {
632 continue;
633 }
634 let held = unsafe {
635 let app = &*((*ffi::sqlite3_vfs_find(cname.as_ptr())).pAppData as *mut VfsAppData);
636 let hydrated = app.hydrated.lock().unwrap();
637 hydrated.contains(&pgno)
638 };
639 if held {
640 continue;
641 }
642 // SAFETY: `file` is the live main file and `page` holds a page.
643 let rc = unsafe {
644 let read = (*(*file).pMethods).xRead.expect("xRead");
645 read(
646 file,
647 page.as_mut_ptr().cast(),
648 page_size as c_int,
649 (i64::from(pgno) - 1) * i64::from(page_size),
650 )
651 };
652 if rc != ffi::SQLITE_OK {
653 return Err(crate::error::Error::Other(
654 format!("hydrate page {pgno}: sqlite rc {rc}").into(),
655 ));
656 }
657 if hydration(&self.name).ok_or_else(gone)?.hydrated - start >= pages {
658 break;
659 }
660 }
661 hydration(&self.name).ok_or_else(gone)
662 }
663}
664
665/// Unregisters and frees a paged VFS registered by [`register_paged_vfs`].
666pub fn unregister_paged_vfs(name: &str) -> crate::error::Result<()> {
667 let cname = CString::new(name).map_err(|_| crate::error::Error::LTXCorrupted)?;
668 unsafe {
669 let vfs = ffi::sqlite3_vfs_find(cname.as_ptr());
670 if vfs.is_null() {
671 return Ok(());
672 }
673 ffi::sqlite3_vfs_unregister(vfs);
674 let app = &*((*vfs).pAppData as *mut VfsAppData);
675 app.retired.store(true, Ordering::Release);
676 if app.open_files.load(Ordering::Acquire) == 0 {
677 free_vfs(vfs);
678 }
679 }
680 Ok(())
681}