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