| 1 | //! db.rs — SQLite database lifecycle: WAL-mode setup, the long-running read-lock |
| 2 | //! checkpoint takeover, the WAL→LTX capture loop, and manual checkpointing. |
| 3 | //! Ported from [email protected] `db.go`. |
| 4 | //! |
| 5 | //! The highest-risk interaction is a long-running read transaction with a manual |
| 6 | //! `PRAGMA wal_checkpoint`, so the implementation uses independently tested steps. |
| 7 | //! |
| 8 | //! ## Async/blocking shape |
| 9 | //! `rusqlite::Connection` is `!Sync` and a `rusqlite::Transaction` borrows its |
| 10 | //! `Connection`. Rather than thread a borrow across `.await`, this module keeps |
| 11 | //! the capture API **synchronous** and owns the connection directly: the |
| 12 | //! long-running read transaction is held with raw `BEGIN`/`ROLLBACK` SQL plus a |
| 13 | //! `read_lock_held` flag — exactly as Go does (`acquireReadLock` runs `BEGIN` + |
| 14 | //! `SELECT COUNT(1)`, db.go:956-976; `releaseReadLock` rolls back, db.go:979-992). |
| 15 | //! `Replica` drives `sync()` and `checkpoint()` from a blocking context |
| 16 | //! (`spawn_blocking` or a dedicated DB thread). This sidesteps the !Sync/borrow |
| 17 | //! problem entirely and makes the idempotent-release behavior (issue #934) a |
| 18 | //! trivial flag check. |
| 19 | //! |
| 20 | //! ## What this implements (the functional capture path) |
| 21 | //! - `open`/`init`: WAL-mode DSN, `wal_autocheckpoint(0)`, control tables, read |
| 22 | //! page size, acquire the read lock, ensure the WAL has ≥1 frame. |
| 23 | //! - `acquire_read_lock`/`release_read_lock`: the checkpoint takeover; release is |
| 24 | //! idempotent (db.go:979-992 / issue #934). |
| 25 | //! - `sync` → `verify` → `sync_inner` → `write_ltx_from_wal`/`write_ltx_from_db`: |
| 26 | //! diff the real WAL against the last LTX position and write the next L0 LTX |
| 27 | //! file (`db.go:1517-1723`), with atomic tmp→rename and the pos cache. |
| 28 | //! - `verify`: the snapshot-on-continuity-break branch lattice |
| 29 | //! (`db.go:1296-1436`), including the issue #900 / #927 edge cases. |
| 30 | //! - `checkpoint`/`exec_checkpoint`: release→`PRAGMA wal_checkpoint(<mode>)`→ |
| 31 | //! re-acquire (`db.go:1875-1919`) and the two-phase WAL-restart handling |
| 32 | //! (`db.go:1808-1873`). |
| 33 | //! - `checkpoint_if_needed`: the 3-tier policy + the three anti-feedback flags |
| 34 | //! (`synced_since_checkpoint`/`synced_to_wal_end`/`last_synced_wal_offset`, |
| 35 | //! issues #896/#927/#997). |
| 36 | //! - Litestream #1292 / celld #150: seal passive checkpoints with a writer |
| 37 | //! barrier, retain database-growth pages, and snapshot truncate boundaries. |
| 38 | //! - `crc64`, `pos` (cached + `LTXError` mapping), `reset_local_state`, |
| 39 | //! `snapshot_to_writer`. |
| 40 | //! |
| 41 | //! ## Deferred work outside the functional path |
| 42 | //! - `setPersistWAL` (the `unsafe` `sqlite3_file_control(SQLITE_FCNTL_PERSIST_WAL)` |
| 43 | //! FFI): only matters when *all* connections close and SQLite |
| 44 | //! would delete the WAL; the capture path keeps its own connection open. |
| 45 | //! - The background monitor loop, `ensure_exists`, `sync_status`, `sync_and_wait`, |
| 46 | //! retention, and retry behavior are not implemented. |
| 47 | //! - A `loom` model of the lock protocol. |
| 48 | |
| 49 | use crate::error::{new_ltx_error, Error, Result}; |
| 50 | use crate::ltx::{self, lock_pgno, Crc64}; |
| 51 | use crate::wal::WalReader; |
| 52 | use crate::{ |
| 53 | ltx_file_path, ltx_level_dir, Pos, CHECKPOINT_MODE_PASSIVE, CHECKPOINT_MODE_RESTART, |
| 54 | CHECKPOINT_MODE_TRUNCATE, META_DIR_SUFFIX, TXID, WAL_FRAME_HEADER_SIZE, WAL_HEADER_SIZE, |
| 55 | }; |
| 56 | use rusqlite::{Connection, OpenFlags}; |
| 57 | use std::collections::HashMap; |
| 58 | use std::path::{Path, PathBuf}; |
| 59 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 60 | |
| 61 | /// Maps a `rusqlite::Error` into the crate error type. |
| 62 | fn sql_err(e: rusqlite::Error) -> Error { |
| 63 | Error::Other(Box::new(e)) |
| 64 | } |
| 65 | |
| 66 | /// SQLite checkpoint mode. Replaces Go's stringly-typed `mode` param; `Display` |
| 67 | /// interpolates straight into `PRAGMA wal_checkpoint(<mode>)` (db.go:1905), so it |
| 68 | /// must render exactly `PASSIVE`/`FULL`/`RESTART`/`TRUNCATE`. |
| 69 | /// |
| 70 | /// Ported from [email protected] litestream.go:22-28. RESTART was removed from |
| 71 | /// automatic use (issue #724) but is still callable (`crc64` forces it), so all |
| 72 | /// four variants are kept. |
| 73 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 74 | pub enum CheckpointMode { |
| 75 | /// Non-blocking checkpoint; skips if there are active transactions. |
| 76 | Passive, |
| 77 | /// Like RESTART but does not block new transactions before flushing. |
| 78 | Full, |
| 79 | /// Blocks new transactions, flushes, and restarts the WAL. |
| 80 | Restart, |
| 81 | /// Like RESTART plus truncates the WAL file to zero length. |
| 82 | Truncate, |
| 83 | } |
| 84 | |
| 85 | impl std::fmt::Display for CheckpointMode { |
| 86 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 87 | let s = match self { |
| 88 | CheckpointMode::Passive => CHECKPOINT_MODE_PASSIVE, |
| 89 | CheckpointMode::Full => crate::CHECKPOINT_MODE_FULL, |
| 90 | CheckpointMode::Restart => CHECKPOINT_MODE_RESTART, |
| 91 | CheckpointMode::Truncate => CHECKPOINT_MODE_TRUNCATE, |
| 92 | }; |
| 93 | f.write_str(s) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /// `verify()`'s decision result (db.go:1509-1515). |
| 98 | #[derive(Debug, Clone, Default)] |
| 99 | struct SyncInfo { |
| 100 | /// End of the previous LTX read (byte offset into the WAL). |
| 101 | offset: i64, |
| 102 | salt1: u32, |
| 103 | salt2: u32, |
| 104 | /// Database page count recorded by the previous LTX file. |
| 105 | prev_commit: u32, |
| 106 | /// If true, a full snapshot is required. |
| 107 | snapshotting: bool, |
| 108 | /// Reason for the snapshot, for logging and diagnostics. |
| 109 | reason: String, |
| 110 | } |
| 111 | |
| 112 | /// A SQLite database managed for replication. |
| 113 | /// |
| 114 | /// Owns the connection (WAL mode, auto-checkpoint disabled) so litestream — not |
| 115 | /// SQLite — decides when the WAL is checkpointed, and holds the long-running read |
| 116 | /// transaction that takes over checkpointing. |
| 117 | /// |
| 118 | /// Ported from `DB` (db.go:64-198). The synchronous `!Sync` connection stays on |
| 119 | /// the thread that drives it. |
| 120 | /// What `verify` reads back from the last L0 this instance wrote: the |
| 121 | /// header fields, plus the final consumed WAL frame's page. The ported |
| 122 | /// check decodes the whole L0 and searches its pages for that frame; the |
| 123 | /// L0's entry for the final frame's page IS that frame (page-map keeps |
| 124 | /// the last write per page, and nothing follows the final frame), so |
| 125 | /// comparing against the cached frame answers the same question — and a |
| 126 | /// spurious mismatch only forces a snapshot, the safe direction. |
| 127 | fn snapshot_reason_code(reason: &str) -> u8 { |
| 128 | match reason { |
| 129 | "" => 1, // first sync leaves the default reason empty |
| 130 | "wal truncated by another process" => 2, |
| 131 | "wal header salt reset, snapshotting" => 3, |
| 132 | "last page does not exist in last ltx file, wal overwritten by another process" => 4, |
| 133 | "full or restart checkpoint detected, snapshotting" => 5, |
| 134 | "checkpoint boundary snapshot" => 6, |
| 135 | _ => 7, |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | #[derive(Clone, Debug)] |
| 140 | struct LastL0Header { |
| 141 | wal_offset: i64, |
| 142 | wal_size: i64, |
| 143 | wal_salt1: u32, |
| 144 | wal_salt2: u32, |
| 145 | commit: u32, |
| 146 | final_pgno: u32, |
| 147 | final_page: Vec<u8>, |
| 148 | } |
| 149 | |
| 150 | /// Per-phase wall time of one `Db::sync` call, in microseconds. |
| 151 | #[derive(Clone, Copy, Debug, Default)] |
| 152 | pub struct SyncTiming { |
| 153 | /// Control-table self-heal and WAL existence checks. |
| 154 | pub prepare_us: u64, |
| 155 | /// The two halves of `prepare_us`: the schema-version pragma (plus |
| 156 | /// the DDL when it fires) and the WAL existence stat, so a field |
| 157 | /// inflation names its syscall. |
| 158 | pub schema_check_us: u64, |
| 159 | pub wal_exists_us: u64, |
| 160 | /// `verify`: the WAL scan and continuity validation. |
| 161 | pub verify_us: u64, |
| 162 | /// `sync_inner` minus the fsync: WAL page reads, LTX encode, the file |
| 163 | /// write and rename. |
| 164 | pub encode_write_us: u64, |
| 165 | /// The sub-phases of `encode_write_us`, so a field inflation names its |
| 166 | /// line instead of hiding in the aggregate: position resolution, the |
| 167 | /// WAL read (tail or full), page-map plus page collection, the LTX |
| 168 | /// encode, and the file write-and-rename. |
| 169 | pub pos_us: u64, |
| 170 | pub wal_read_us: u64, |
| 171 | pub map_collect_us: u64, |
| 172 | pub ltx_encode_us: u64, |
| 173 | pub file_write_us: u64, |
| 174 | /// The WAL length seen by this call, for scaling. |
| 175 | pub wal_len_bytes: u64, |
| 176 | /// True when this call snapshotted (the full-database path). |
| 177 | pub snapshot: bool, |
| 178 | /// Which WAL read ran: 0 tail, 1 full because snapshotting, 2 full |
| 179 | /// because the offset sat at the WAL start, 3 full because the tail |
| 180 | /// read fell back. `wal_read_bytes` is what that read actually |
| 181 | /// transferred (the tail length, or the whole file). |
| 182 | pub wal_read_kind: u8, |
| 183 | pub wal_read_bytes: u64, |
| 184 | /// The bytes the sync allocated to hold what it read: the tail plus the |
| 185 | /// header on the tail path, the file otherwise. |
| 186 | pub wal_image_bytes: u64, |
| 187 | /// Which verify branch forced the snapshot: 0 none, 1 first sync, |
| 188 | /// 2 wal truncated by another process, 3 salt reset, 4 last page |
| 189 | /// missing from the last L0, 5 full or restart checkpoint detected, |
| 190 | /// 6 checkpoint boundary, 7 other. |
| 191 | pub snapshot_reason: u8, |
| 192 | /// The cut file's fsync (zero under lazy capture). |
| 193 | pub fsync_us: u64, |
| 194 | /// `checkpoint_if_needed`: SQLite's checkpoint, including its own |
| 195 | /// writes and fsyncs through the SQLite VFS. |
| 196 | pub checkpoint_us: u64, |
| 197 | } |
| 198 | |
| 199 | pub struct Db { |
| 200 | host: crate::LtxHost, |
| 201 | path: PathBuf, |
| 202 | meta_path: PathBuf, |
| 203 | /// Main connection: writes, PRAGMAs, checkpoints, page-size reads. |
| 204 | conn: Connection, |
| 205 | /// Dedicated connection that holds the long-running read transaction. |
| 206 | /// |
| 207 | /// Go's `db.db` is a `*sql.DB` **connection pool**: the read lock (`db.rtx`) |
| 208 | /// lives on one pooled connection while every other `db.db.Exec` grabs a |
| 209 | /// *different* connection from the pool. A single `rusqlite::Connection` |
| 210 | /// cannot do that — an `INSERT` issued on the same connection that holds the |
| 211 | /// read transaction would be buffered in that transaction and not flushed to |
| 212 | /// the WAL (it would not write a fresh WAL page after a TRUNCATE checkpoint). |
| 213 | /// So the read lock gets its own connection, mirroring the pool's separation. |
| 214 | rtx_conn: Connection, |
| 215 | page_size: u32, |
| 216 | |
| 217 | /// `true` while the long-running read transaction is open (db.go:70 `rtx`). |
| 218 | /// We track a flag rather than holding a borrowing `rusqlite::Transaction`. |
| 219 | read_lock_held: bool, |
| 220 | |
| 221 | /// The last `sync` call's per-phase wall time. Telemetry only: the |
| 222 | /// closed-book capture ledger reads it; nothing branches on it. |
| 223 | last_sync_timing: SyncTiming, |
| 224 | |
| 225 | // ── Tunables (db.go:131-197) ──────────────────────────────────────────── |
| 226 | /// PASSIVE checkpoint threshold, in pages (db.go:34 default 1000). |
| 227 | pub min_checkpoint_page_n: u32, |
| 228 | /// TRUNCATE checkpoint threshold, in pages; 0 disables (db.go:35 default). |
| 229 | pub truncate_page_n: u32, |
| 230 | /// Time-based PASSIVE checkpoint interval; 0 disables (db.go:32 default 60s). |
| 231 | pub checkpoint_interval: Duration, |
| 232 | /// Busy timeout for SQLite locks (db.go:33 default 1s). |
| 233 | pub busy_timeout: Duration, |
| 234 | |
| 235 | // ── Anti-feedback-loop bookkeeping (issues #896/#927/#997) ────────────── |
| 236 | /// True once data has synced since the last checkpoint (#896, db.go:80). |
| 237 | synced_since_checkpoint: bool, |
| 238 | /// True if the last sync reached the exact WAL EOF (#927, db.go:88). |
| 239 | synced_to_wal_end: bool, |
| 240 | /// Logical end of WAL content after the last sync = `WALOffset + WALSize` |
| 241 | /// from the last LTX (#997, db.go:96). Used for checkpoint thresholds |
| 242 | /// instead of file size (stale post-checkpoint frames inflate file size). |
| 243 | last_synced_wal_offset: i64, |
| 244 | /// The schema version `ensure_control_tables` last verified. The |
| 245 | /// self-heal exists for a swept `sqlite_schema`, and any sweep bumps |
| 246 | /// SQLite's schema version, so an unchanged version proves the tables |
| 247 | /// still stand without re-running DDL through the parser every capture |
| 248 | /// (~0.8 ms per sync in the 2026-08-25 closed-book ledger). |
| 249 | verified_schema_version: Option<i64>, |
| 250 | /// The header fields of the last L0 this instance wrote, keyed by its |
| 251 | /// TXID. `verify` needs exactly these to place the next incremental |
| 252 | /// read; re-reading the whole L0 file to parse its header cost more |
| 253 | /// than the header is long. A miss (restore, compaction, reopen) |
| 254 | /// falls back to the file. |
| 255 | last_l0_header: Option<(TXID, LastL0Header)>, |
| 256 | |
| 257 | /// Cached L0 position; `None` = invalid (db.go:106-109). |
| 258 | pos_cache: Option<Pos>, |
| 259 | /// The L0 level directory exists: created on the first cut (or after a |
| 260 | /// `NotFound` on a later one), not probed with `mkdir` on every sync. |
| 261 | l0_dir_ready: bool, |
| 262 | /// The WAL, opened once. Every sync used to open it three times and stat |
| 263 | /// it five; each was a path walk on a directory the node fsyncs thousands |
| 264 | /// of times a second. See [`Db::with_wal_file`]. |
| 265 | wal_file: Option<crate::HostFile>, |
| 266 | /// Last L0 `FileInfo` (db.go:99-102; only L0 is tracked in the one-shot). |
| 267 | max_l0_file_info: Option<ltx::FileInfo>, |
| 268 | } |
| 269 | |
| 270 | /// DDL for the replication control tables managed inside each database: |
| 271 | /// `_litestream_seq` forces WAL writes when empty; `_litestream_lock` forces |
| 272 | /// a write lock during sync (db.go:857-864). The text is byte-visible: |
| 273 | /// `sqlite_schema` stores it verbatim in a replicated page, so it must stay |
| 274 | /// character-identical to litestream's, and one copy serves every creation |
| 275 | /// site. |
| 276 | const CONTROL_TABLES_DDL: &str = |
| 277 | "CREATE TABLE IF NOT EXISTS _litestream_seq (id INTEGER PRIMARY KEY, seq INTEGER);\ |
| 278 | CREATE TABLE IF NOT EXISTS _litestream_lock (id INTEGER);"; |
| 279 | |
| 280 | /// True for exactly the two control tables above, compared without case the |
| 281 | /// way SQLite compares identifiers. Application-facing paths (deleteAll |
| 282 | /// sweeps, the SQL authorizer) must exempt these names, so the predicate |
| 283 | /// lives here with the tables. Exact names, not a `_litestream_` prefix: |
| 284 | /// ltx is a port of a pinned litestream, and workerd reserves only `_cf_`, |
| 285 | /// so any other name stays reachable by application SQL. |
| 286 | pub fn is_control_table(name: &str) -> bool { |
| 287 | name.eq_ignore_ascii_case("_litestream_seq") || name.eq_ignore_ascii_case("_litestream_lock") |
| 288 | } |
| 289 | |
| 290 | impl Db { |
| 291 | /// Default minimum-checkpoint page count (`DefaultMinCheckpointPageN`, |
| 292 | /// db.go:34). |
| 293 | pub const DEFAULT_MIN_CHECKPOINT_PAGE_N: u32 = 1000; |
| 294 | /// Default truncate page count (`DefaultTruncatePageN`, db.go:35). |
| 295 | pub const DEFAULT_TRUNCATE_PAGE_N: u32 = 121_359; |
| 296 | /// Default checkpoint interval (`DefaultCheckpointInterval`, db.go:32). |
| 297 | pub const DEFAULT_CHECKPOINT_INTERVAL: Duration = Duration::from_secs(60); |
| 298 | /// Default busy timeout (`DefaultBusyTimeout`, db.go:33). |
| 299 | pub const DEFAULT_BUSY_TIMEOUT: Duration = Duration::from_secs(1); |
| 300 | |
| 301 | /// Opens and initializes the database with litestream's WAL-mode setup and |
| 302 | /// acquires the long-running read lock. |
| 303 | /// |
| 304 | /// Ported from `DB.init` (db.go:795-911) — the connection-setup half plus the |
| 305 | /// read-lock acquire and `ensureWALExists`. |
| 306 | pub fn open(path: impl AsRef<Path>) -> Result<Db> { |
| 307 | Self::open_with_host(path, crate::LtxHost::default()) |
| 308 | } |
| 309 | |
| 310 | /// Opens the database with an injected clock and executor host. |
| 311 | pub fn open_with_host(path: impl AsRef<Path>, host: crate::LtxHost) -> Result<Db> { |
| 312 | Self::open_with_host_and_optional_vfs(path, host, None) |
| 313 | } |
| 314 | |
| 315 | /// Opens both managed connections through a named SQLite VFS. |
| 316 | #[cfg(celld_internal_tests)] |
| 317 | pub fn open_with_host_and_vfs( |
| 318 | path: impl AsRef<Path>, |
| 319 | host: crate::LtxHost, |
| 320 | vfs: &str, |
| 321 | ) -> Result<Db> { |
| 322 | Self::open_with_host_and_optional_vfs(path, host, Some(vfs)) |
| 323 | } |
| 324 | |
| 325 | fn open_with_host_and_optional_vfs( |
| 326 | path: impl AsRef<Path>, |
| 327 | host: crate::LtxHost, |
| 328 | vfs: Option<&str>, |
| 329 | ) -> Result<Db> { |
| 330 | let path = path.as_ref().to_path_buf(); |
| 331 | let meta_path = Self::meta_path_for(&path); |
| 332 | |
| 333 | let open = |path: &Path| match vfs { |
| 334 | Some(vfs) => Connection::open_with_flags_and_vfs(path, OpenFlags::default(), vfs), |
| 335 | None => Connection::open(path), |
| 336 | }; |
| 337 | let conn = open(&path).map_err(sql_err)?; |
| 338 | |
| 339 | // DSN pragmas: busy_timeout + wal_autocheckpoint(0) (db.go:818). |
| 340 | // autocheckpoint MUST be 0 because litestream owns checkpointing. |
| 341 | // Per-connection, not per-file: the cell's own writer |
| 342 | // connection keeps SQLite's default 1000-page autocheckpoint, which |
| 343 | // is safe because this connection's long-running read transaction |
| 344 | // pins a WAL read mark, so a PASSIVE checkpoint elsewhere can |
| 345 | // backfill but never reset or truncate the WAL under the reader. |
| 346 | conn.busy_timeout(Self::DEFAULT_BUSY_TIMEOUT) |
| 347 | .map_err(sql_err)?; |
| 348 | conn.pragma_update(None, "wal_autocheckpoint", 0) |
| 349 | .map_err(sql_err)?; |
| 350 | |
| 351 | // Enable WAL; SQLite returns the new mode on success (db.go:849-853). |
| 352 | let mode: String = conn |
| 353 | .query_row("PRAGMA journal_mode=WAL", [], |r| r.get(0)) |
| 354 | .map_err(sql_err)?; |
| 355 | if mode != "wal" { |
| 356 | return Err(Error::Other( |
| 357 | format!("enable wal failed, mode={mode:?}").into(), |
| 358 | )); |
| 359 | } |
| 360 | |
| 361 | conn.execute_batch(CONTROL_TABLES_DDL).map_err(sql_err)?; |
| 362 | |
| 363 | // Dedicated read-lock connection (mirrors a second pooled connection). |
| 364 | let rtx_conn = open(&path).map_err(sql_err)?; |
| 365 | rtx_conn |
| 366 | .busy_timeout(Self::DEFAULT_BUSY_TIMEOUT) |
| 367 | .map_err(sql_err)?; |
| 368 | |
| 369 | let mut db = Db { |
| 370 | host, |
| 371 | path, |
| 372 | meta_path, |
| 373 | conn, |
| 374 | rtx_conn, |
| 375 | page_size: 0, |
| 376 | read_lock_held: false, |
| 377 | last_sync_timing: SyncTiming::default(), |
| 378 | min_checkpoint_page_n: Self::DEFAULT_MIN_CHECKPOINT_PAGE_N, |
| 379 | truncate_page_n: Self::DEFAULT_TRUNCATE_PAGE_N, |
| 380 | checkpoint_interval: Self::DEFAULT_CHECKPOINT_INTERVAL, |
| 381 | busy_timeout: Self::DEFAULT_BUSY_TIMEOUT, |
| 382 | synced_since_checkpoint: false, |
| 383 | synced_to_wal_end: false, |
| 384 | last_synced_wal_offset: 0, |
| 385 | verified_schema_version: None, |
| 386 | last_l0_header: None, |
| 387 | pos_cache: None, |
| 388 | l0_dir_ready: false, |
| 389 | wal_file: None, |
| 390 | max_l0_file_info: None, |
| 391 | }; |
| 392 | |
| 393 | // Start the long-running read transaction (db.go:867-871). |
| 394 | db.acquire_read_lock()?; |
| 395 | |
| 396 | // Read page size (db.go:874-878). |
| 397 | let page_size: i64 = db |
| 398 | .conn |
| 399 | .query_row("PRAGMA page_size", [], |r| r.get(0)) |
| 400 | .map_err(sql_err)?; |
| 401 | if page_size <= 0 { |
| 402 | return Err(Error::Other( |
| 403 | format!("invalid db page size: {page_size}").into(), |
| 404 | )); |
| 405 | } |
| 406 | // Validated > 0 above; SQLite page sizes are <= 65536. |
| 407 | db.page_size = page_size as u32; |
| 408 | |
| 409 | // Ensure the meta directory exists (db.go:880-883). |
| 410 | db.host.create_dir_all(&db.meta_path)?; |
| 411 | |
| 412 | // Clear crash-leftover temp files (db.go:576). |
| 413 | remove_tmp_files(&db.host, &db.meta_path)?; |
| 414 | |
| 415 | // Ensure the WAL has at least one frame (db.go:886-888). |
| 416 | db.ensure_wal_exists()?; |
| 417 | |
| 418 | Ok(db) |
| 419 | } |
| 420 | |
| 421 | // ── Paths ────────────────────────────────────────────────────────────── |
| 422 | |
| 423 | /// Computes the litestream meta-directory path (`.<file>-litestream`) for a |
| 424 | /// database file path, without opening it. Public so a host can locate (e.g. |
| 425 | /// to wipe, during a hard recovery) the meta dir of a database it no longer |
| 426 | /// has an open [`Db`] handle for. Mirrors `DB.MetaPath` (db.go:292) at the |
| 427 | /// path level. |
| 428 | pub fn meta_path_for_path(path: impl AsRef<Path>) -> PathBuf { |
| 429 | Self::meta_path_for(path.as_ref()) |
| 430 | } |
| 431 | |
| 432 | fn meta_path_for(path: &Path) -> PathBuf { |
| 433 | // Go: filepath.Join(dir, "."+file+MetaDirSuffix) (db.go:206). |
| 434 | let dir = path.parent(); |
| 435 | let file = path.file_name().map(|s| s.to_owned()).unwrap_or_default(); |
| 436 | let mut name = std::ffi::OsString::from("."); |
| 437 | name.push(&file); |
| 438 | name.push(META_DIR_SUFFIX); |
| 439 | match dir { |
| 440 | Some(d) if !d.as_os_str().is_empty() => d.join(name), |
| 441 | _ => PathBuf::from(name), |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | /// The database file path. Ported from `DB.Path` (db.go:275). |
| 446 | pub fn path(&self) -> &Path { |
| 447 | &self.path |
| 448 | } |
| 449 | |
| 450 | /// Path to the litestream meta directory (`.<file>-litestream`). |
| 451 | /// Ported from `DB.MetaPath` (db.go:292). |
| 452 | pub fn meta_path(&self) -> &Path { |
| 453 | &self.meta_path |
| 454 | } |
| 455 | |
| 456 | /// Path to SQLite's WAL sidecar file (`<db>-wal`). |
| 457 | /// Ported from `DB.WALPath` (db.go:287-289). |
| 458 | pub fn wal_path(&self) -> PathBuf { |
| 459 | let mut s = self.path.clone().into_os_string(); |
| 460 | s.push("-wal"); |
| 461 | PathBuf::from(s) |
| 462 | } |
| 463 | |
| 464 | /// Root LTX directory (`<meta>/ltx`). Ported from `DB.LTXDir` (db.go:302). |
| 465 | fn ltx_dir(&self) -> String { |
| 466 | crate::ltx_dir(&self.meta_path.to_string_lossy()) |
| 467 | } |
| 468 | |
| 469 | /// LTX level sub-directory. Ported from `DB.LTXLevelDir` (db.go:332). |
| 470 | fn ltx_level_dir(&self, level: u32) -> String { |
| 471 | ltx_level_dir(&self.meta_path.to_string_lossy(), level) |
| 472 | } |
| 473 | |
| 474 | /// Local path of a single LTX file. Ported from `DB.LTXPath` (db.go:338). |
| 475 | /// |
| 476 | /// `pub` so the [`crate::replica::Replica`] can read the local L0 LTX files |
| 477 | /// the capture loop wrote and upload them (the Go exported `DB.LTXPath`, |
| 478 | /// used by `Replica.uploadLTXFile`, replica.go:183). |
| 479 | pub fn ltx_path(&self, level: u32, min_txid: TXID, max_txid: TXID) -> String { |
| 480 | ltx_file_path(&self.meta_path.to_string_lossy(), level, min_txid, max_txid) |
| 481 | } |
| 482 | |
| 483 | /// Reads one local LTX file through the host filesystem. |
| 484 | pub fn read_ltx_file(&self, level: u32, min_txid: TXID, max_txid: TXID) -> Result<Vec<u8>> { |
| 485 | let path = self.ltx_path(level, min_txid, max_txid); |
| 486 | Ok(self.host.read(Path::new(&path))?) |
| 487 | } |
| 488 | |
| 489 | /// The SQLite page size, in bytes. Ported from `DB.PageSize` (db.go:445). |
| 490 | pub fn page_size(&self) -> u32 { |
| 491 | self.page_size |
| 492 | } |
| 493 | |
| 494 | // ── Read-lock takeover (checkpoint prevention) ───────────────────────── |
| 495 | |
| 496 | /// Begins a long-running read transaction to prevent external checkpoints. |
| 497 | /// |
| 498 | /// Ported from `acquireReadLock` (db.go:956-976): `BEGIN` then `SELECT |
| 499 | /// COUNT(1) FROM _litestream_seq` to obtain the SHARED read lock. Held with |
| 500 | /// raw SQL + a flag instead of a borrowing `rusqlite::Transaction` (see |
| 501 | /// module docs). Idempotent: a no-op if already held. |
| 502 | fn acquire_read_lock(&mut self) -> Result<()> { |
| 503 | if self.read_lock_held { |
| 504 | return Ok(()); |
| 505 | } |
| 506 | self.rtx_conn |
| 507 | .prepare_cached("BEGIN") |
| 508 | .and_then(|mut statement| statement.execute([])) |
| 509 | .map_err(sql_err)?; |
| 510 | // Execute a read query to obtain the read lock. On failure, roll back. |
| 511 | if let Err(e) = self |
| 512 | .rtx_conn |
| 513 | .query_row("SELECT COUNT(1) FROM _litestream_seq", [], |r| { |
| 514 | r.get::<_, i64>(0) |
| 515 | }) |
| 516 | { |
| 517 | let _ = self.rtx_conn.execute_batch("ROLLBACK"); |
| 518 | return Err(sql_err(e)); |
| 519 | } |
| 520 | self.read_lock_held = true; |
| 521 | Ok(()) |
| 522 | } |
| 523 | |
| 524 | /// Rolls back the long-running read transaction. |
| 525 | /// |
| 526 | /// Ported from `releaseReadLock` (db.go:979-992). Uses the `rollback` helper |
| 527 | /// semantics: a "no transaction is active" / "already rolled back" error is |
| 528 | /// swallowed (issue #934) — a double release must return |
| 529 | /// `Ok(())`. The `read_lock_held` flag is cleared regardless. |
| 530 | fn release_read_lock(&mut self) -> Result<()> { |
| 531 | if !self.read_lock_held { |
| 532 | return Ok(()); |
| 533 | } |
| 534 | self.read_lock_held = false; |
| 535 | rollback(&self.rtx_conn) |
| 536 | } |
| 537 | |
| 538 | // ── WAL bootstrap ────────────────────────────────────────────────────── |
| 539 | |
| 540 | /// Recreates the control tables if they are missing. They are created at |
| 541 | /// open, but an application-level sweep of `sqlite_schema` can drop them |
| 542 | /// (they do not carry the protected `_cf_` prefix); `CREATE TABLE IF NOT |
| 543 | /// EXISTS` on an existing table is a no-op, so this is safe to run on |
| 544 | /// every capture. |
| 545 | fn ensure_control_tables(&mut self) -> Result<()> { |
| 546 | // A swept control table is a schema change, and every schema change |
| 547 | // bumps SQLite's schema version — so an unchanged version proves |
| 548 | // the last verification still holds and the DDL (a full parse and |
| 549 | // execute per statement) can be skipped on the hot capture path. |
| 550 | // Through the statement cache: this guard runs on every sync, and a |
| 551 | // fresh `PRAGMA` per sync was one SQL compilation per capture on the |
| 552 | // fleet profile. |
| 553 | let version: i64 = self |
| 554 | .conn |
| 555 | .prepare_cached("PRAGMA schema_version") |
| 556 | .and_then(|mut statement| statement.query_row([], |row| row.get(0))) |
| 557 | .map_err(sql_err)?; |
| 558 | if self.verified_schema_version == Some(version) { |
| 559 | return Ok(()); |
| 560 | } |
| 561 | self.conn |
| 562 | .execute_batch(CONTROL_TABLES_DDL) |
| 563 | .map_err(sql_err)?; |
| 564 | let verified: i64 = self |
| 565 | .conn |
| 566 | .prepare_cached("PRAGMA schema_version") |
| 567 | .and_then(|mut statement| statement.query_row([], |row| row.get(0))) |
| 568 | .map_err(sql_err)?; |
| 569 | self.verified_schema_version = Some(verified); |
| 570 | Ok(()) |
| 571 | } |
| 572 | |
| 573 | /// Ensures the real WAL exists and has a header. |
| 574 | /// |
| 575 | /// Ported from `ensureWALExists` (db.go:1199-1209): exit early if the WAL |
| 576 | /// header is present; otherwise force a write to `_litestream_seq`. |
| 577 | /// Runs `op` on the held WAL handle, opening it on first use. A WAL that |
| 578 | /// SQLite recreated, or that a truncation shortened under a read, surfaces |
| 579 | /// as `NotFound` or `UnexpectedEof`; the handle is dropped and `op` runs |
| 580 | /// once more on a fresh open, so a stale handle costs one retry, never a |
| 581 | /// wrong answer. Any other error also drops the handle. |
| 582 | fn with_wal_file<T>( |
| 583 | &mut self, |
| 584 | op: impl Fn(&mut crate::HostFile) -> std::io::Result<T>, |
| 585 | ) -> std::io::Result<T> { |
| 586 | let mut attempt = 0; |
| 587 | loop { |
| 588 | if self.wal_file.is_none() { |
| 589 | self.wal_file = Some(self.host.open(&self.wal_path())?); |
| 590 | } |
| 591 | let file = self.wal_file.as_mut().expect("opened above"); |
| 592 | match op(file) { |
| 593 | Ok(value) => return Ok(value), |
| 594 | Err(error) => { |
| 595 | self.wal_file = None; |
| 596 | let retry = attempt == 0 |
| 597 | && matches!( |
| 598 | error.kind(), |
| 599 | std::io::ErrorKind::NotFound | std::io::ErrorKind::UnexpectedEof |
| 600 | ); |
| 601 | if !retry { |
| 602 | return Err(error); |
| 603 | } |
| 604 | attempt += 1; |
| 605 | } |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | /// The 32-byte WAL header through the held handle (`readWALHeader`, |
| 611 | /// litestream.go:138-148: an error if the file is missing or short). |
| 612 | fn wal_header_bytes(&mut self) -> Result<[u8; WAL_HEADER_SIZE]> { |
| 613 | let bytes = self.with_wal_file(|file| file.read_exact_at(0, WAL_HEADER_SIZE))?; |
| 614 | Ok(bytes |
| 615 | .try_into() |
| 616 | .expect("the exact read has the header size")) |
| 617 | } |
| 618 | |
| 619 | /// `n` bytes at `offset` of the WAL through the held handle |
| 620 | /// (`readWALFileAt`, litestream.go:152-166: a short read is an error). |
| 621 | fn wal_bytes_at(&mut self, offset: i64, n: i64) -> Result<Vec<u8>> { |
| 622 | Ok(self.with_wal_file(|file| file.read_exact_at(offset as u64, n as usize))?) |
| 623 | } |
| 624 | |
| 625 | fn ensure_wal_exists(&mut self) -> Result<()> { |
| 626 | if self.wal_file_size()? >= WAL_HEADER_SIZE as i64 { |
| 627 | return Ok(()); |
| 628 | } |
| 629 | self.conn |
| 630 | .execute_batch( |
| 631 | "INSERT INTO _litestream_seq (id, seq) VALUES (1, 1) \ |
| 632 | ON CONFLICT (id) DO UPDATE SET seq = seq + 1", |
| 633 | ) |
| 634 | .map_err(sql_err)?; |
| 635 | Ok(()) |
| 636 | } |
| 637 | |
| 638 | /// Size of the WAL file in bytes, 0 if absent. Ported from `walFileSize` |
| 639 | /// (db.go:1183-1191). |
| 640 | fn wal_file_size(&mut self) -> Result<i64> { |
| 641 | match self.with_wal_file(|file| file.file_len()) { |
| 642 | Ok(len) => Ok(len as i64), |
| 643 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0), |
| 644 | Err(e) => Err(e.into()), |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | /// The size of the main database file in bytes, 0 if absent. |
| 649 | fn db_file_size(&self) -> Result<i64> { |
| 650 | match self.host.metadata(&self.path) { |
| 651 | Ok(md) => Ok(md.len as i64), |
| 652 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0), |
| 653 | Err(e) => Err(e.into()), |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | // ── Position ─────────────────────────────────────────────────────────── |
| 658 | |
| 659 | /// The highest `(min,max)` TXID pair in the L0 directory, `(0,0)` if none. |
| 660 | /// Ported from `DB.MaxLTX` (db.go:363-380). |
| 661 | fn max_ltx(&self) -> Result<(TXID, TXID)> { |
| 662 | let dir = self.ltx_level_dir(0); |
| 663 | let entries = match self.host.read_dir(Path::new(&dir)) { |
| 664 | Ok(e) => e, |
| 665 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((TXID(0), TXID(0))), |
| 666 | Err(e) => return Err(e.into()), |
| 667 | }; |
| 668 | let mut min_txid = TXID(0); |
| 669 | let mut max_txid = TXID(0); |
| 670 | for ent in entries { |
| 671 | let name = ent.file_name; |
| 672 | let name = name.to_string_lossy(); |
| 673 | if let Ok((mn, mx)) = ltx::parse_filename(&name) { |
| 674 | if mx > max_txid { |
| 675 | min_txid = mn; |
| 676 | max_txid = mx; |
| 677 | } |
| 678 | } |
| 679 | } |
| 680 | Ok((min_txid, max_txid)) |
| 681 | } |
| 682 | |
| 683 | /// The current replication position (cached; recomputed from the max L0 file). |
| 684 | /// |
| 685 | /// Ported from `DB.Pos` (db.go:392-425). Wraps fs/decode failures in |
| 686 | /// `LTXError` (db.go:412,418). |
| 687 | pub fn pos(&mut self) -> Result<Pos> { |
| 688 | if let Some(p) = self.pos_cache { |
| 689 | return Ok(p); |
| 690 | } |
| 691 | |
| 692 | let (min_txid, max_txid) = self.max_ltx()?; |
| 693 | if min_txid == TXID(0) { |
| 694 | return Ok(Pos::ZERO); // no replication yet |
| 695 | } |
| 696 | |
| 697 | let ltx_path = self.ltx_path(0, min_txid, max_txid); |
| 698 | let bytes = match self.host.read(Path::new(<x_path)) { |
| 699 | Ok(b) => b, |
| 700 | Err(e) => { |
| 701 | return Err(Error::Ltx(Box::new(new_ltx_error( |
| 702 | "open", |
| 703 | <x_path, |
| 704 | 0, |
| 705 | min_txid.0, |
| 706 | max_txid.0, |
| 707 | e.into(), |
| 708 | )))); |
| 709 | } |
| 710 | }; |
| 711 | |
| 712 | let decoded = match ltx::decode_file(&bytes) { |
| 713 | Ok(d) => d, |
| 714 | Err(_e) => { |
| 715 | // Decode/verify failure indicates corruption (db.go:417-419). |
| 716 | return Err(Error::Ltx(Box::new(new_ltx_error( |
| 717 | "verify", |
| 718 | <x_path, |
| 719 | 0, |
| 720 | min_txid.0, |
| 721 | max_txid.0, |
| 722 | Error::LTXCorrupted, |
| 723 | )))); |
| 724 | } |
| 725 | }; |
| 726 | |
| 727 | let pos = Pos::new(decoded.header.max_txid, decoded.trailer.post_apply_checksum); |
| 728 | self.pos_cache = Some(pos); |
| 729 | Ok(pos) |
| 730 | } |
| 731 | |
| 732 | /// Clears the cached position so the next `pos()` recomputes from disk. |
| 733 | /// Ported from `invalidatePosCache` (db.go:430-434). |
| 734 | fn invalidate_pos_cache(&mut self) { |
| 735 | self.pos_cache = None; |
| 736 | } |
| 737 | |
| 738 | /// Removes local LTX files, forcing a fresh snapshot on the next sync. |
| 739 | /// Ported from `DB.ResetLocalState` (db.go:309-328). |
| 740 | pub fn reset_local_state(&mut self) -> Result<()> { |
| 741 | match self.host.remove_dir_all(Path::new(&self.ltx_dir())) { |
| 742 | Ok(()) => {} |
| 743 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 744 | Err(e) => return Err(e.into()), |
| 745 | } |
| 746 | self.max_l0_file_info = None; |
| 747 | self.invalidate_pos_cache(); |
| 748 | Ok(()) |
| 749 | } |
| 750 | |
| 751 | /// Clears the local L0 directory and seeds it with a single baseline L0 LTX |
| 752 | /// file (`data` for the `min_txid`..`max_txid` range), atomically. The next |
| 753 | /// [`Db::sync`] then sees the baseline does not match the real WAL and writes |
| 754 | /// a fresh snapshot at the current database state. |
| 755 | /// |
| 756 | /// This is the file-writing tail of `checkDatabaseBehindReplica` |
| 757 | /// (db.go:1241-1293): clear L0, invalidate the pos cache, write the fetched |
| 758 | /// remote L0 file to its local path via a temp-file + fsync + rename, then |
| 759 | /// invalidate the cache again. The *detection* half (compare DB pos vs replica |
| 760 | /// pos and fetch the bytes) lives on [`crate::replica::Replica`] because the |
| 761 | /// synchronous `Db` has no `ReplicaClient` handle of its own. Used by |
| 762 | /// [`crate::replica::Replica::check_database_behind_replica`] (issue #781). |
| 763 | pub fn seed_l0_baseline(&mut self, min_txid: TXID, max_txid: TXID, data: &[u8]) -> Result<()> { |
| 764 | // Clear local L0 files (db.go:1241-1249). |
| 765 | let l0_dir = self.ltx_level_dir(0); |
| 766 | match self.host.remove_dir_all(Path::new(&l0_dir)) { |
| 767 | Ok(()) => {} |
| 768 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 769 | Err(e) => return Err(e.into()), |
| 770 | } |
| 771 | self.max_l0_file_info = None; |
| 772 | self.invalidate_pos_cache(); |
| 773 | self.host.create_dir_all(Path::new(&l0_dir))?; |
| 774 | |
| 775 | // Write the baseline file atomically (db.go:1260-1286). |
| 776 | let local_path = self.ltx_path(0, min_txid, max_txid); |
| 777 | let tmp_path = format!("{local_path}.tmp"); |
| 778 | let _ = write_file_atomic(&self.host, &tmp_path, &local_path, data)?; |
| 779 | self.last_l0_header = None; |
| 780 | self.invalidate_pos_cache(); |
| 781 | Ok(()) |
| 782 | } |
| 783 | |
| 784 | // ── Capture loop ─────────────────────────────────────────────────────── |
| 785 | |
| 786 | /// Where one `sync` call's wall time went, phase by phase. The phases |
| 787 | /// sum to the call's wall time minus only dispatch overhead, so a |
| 788 | /// capture ledger built on this closes its books. `checkpoint_us` is |
| 789 | /// SQLite's own checkpoint (its writes and fsyncs run through the |
| 790 | /// SQLite VFS, invisible to the LTX host filesystem), measured here |
| 791 | /// because no other layer can see it. |
| 792 | pub fn last_sync_timing(&self) -> SyncTiming { |
| 793 | self.last_sync_timing |
| 794 | } |
| 795 | |
| 796 | /// Copies pending data from the WAL into the next L0 LTX file and applies |
| 797 | /// the checkpoint policy. |
| 798 | /// |
| 799 | /// Ported from `DB.Sync` (db.go:994-1056). The public entry point of the |
| 800 | /// capture loop. This function is synchronous as described in the module docs. |
| 801 | pub fn sync(&mut self) -> Result<()> { |
| 802 | self.sync_with_verify_hook(None) |
| 803 | } |
| 804 | |
| 805 | /// `sync` with an optional hook that runs between `verify` and the |
| 806 | /// capture read — the window a concurrent WAL change would land in. |
| 807 | /// Test-only through `internal::sync_with_verify_hook`; production |
| 808 | /// passes `None`. |
| 809 | fn sync_with_verify_hook(&mut self, hook: Option<Box<dyn FnOnce()>>) -> Result<()> { |
| 810 | self.last_sync_timing = SyncTiming::default(); |
| 811 | let phase = crate::host::telemetry_us(); |
| 812 | // Self-heal: recreate the control tables if something swept them out |
| 813 | // of `sqlite_schema` from under the replicator — without them every |
| 814 | // capture fails until the database is reopened. A no-op when the |
| 815 | // tables exist (no schema change, no WAL write). |
| 816 | self.ensure_control_tables()?; |
| 817 | let schema_done = crate::host::telemetry_us(); |
| 818 | self.last_sync_timing.schema_check_us = schema_done.saturating_sub(phase); |
| 819 | |
| 820 | // Ensure the WAL has at least one frame (db.go:1017-1020). |
| 821 | self.ensure_wal_exists()?; |
| 822 | self.last_sync_timing.wal_exists_us = |
| 823 | crate::host::telemetry_us().saturating_sub(schema_done); |
| 824 | self.last_sync_timing.prepare_us = crate::host::telemetry_us().saturating_sub(phase); |
| 825 | |
| 826 | let (orig_wal_size, new_wal_size, synced) = self.verify_and_sync(hook)?; |
| 827 | |
| 828 | // Track that data was synced for time-based checkpoint decisions. |
| 829 | if synced { |
| 830 | self.synced_since_checkpoint = true; |
| 831 | } |
| 832 | |
| 833 | let phase = crate::host::telemetry_us(); |
| 834 | self.checkpoint_if_needed(orig_wal_size, new_wal_size)?; |
| 835 | self.last_sync_timing.checkpoint_us = crate::host::telemetry_us().saturating_sub(phase); |
| 836 | |
| 837 | // Recompute the cached position (kept for parity with db.go:1037-1041). |
| 838 | let _ = self.pos()?; |
| 839 | |
| 840 | Ok(()) |
| 841 | } |
| 842 | |
| 843 | /// Verifies the last sync against the current WAL, then syncs. |
| 844 | /// |
| 845 | /// Ported from `DB.verifyAndSync` (db.go:1058-1090). Returns |
| 846 | /// `(orig_wal_size, new_wal_size, synced)` where the sizes are the **logical** |
| 847 | /// WAL offset (`WALOffset+WALSize` of the last LTX), not file size (#997). |
| 848 | fn verify_and_sync(&mut self, between: Option<Box<dyn FnOnce()>>) -> Result<(i64, i64, bool)> { |
| 849 | // Use the last synced WAL offset as the logical size for checkpoint |
| 850 | // decisions; on the first sync fall back to file size (db.go:1062-1069). |
| 851 | let mut orig_wal_size = self.last_synced_wal_offset; |
| 852 | if orig_wal_size == 0 { |
| 853 | orig_wal_size = self.wal_file_size()?; |
| 854 | } |
| 855 | |
| 856 | let phase = crate::host::telemetry_us(); |
| 857 | let info = self.verify()?; |
| 858 | self.last_sync_timing.verify_us = crate::host::telemetry_us().saturating_sub(phase); |
| 859 | if let Some(between) = between { |
| 860 | between(); |
| 861 | } |
| 862 | let phase = crate::host::telemetry_us(); |
| 863 | let synced = self.sync_inner(info)?; |
| 864 | self.last_sync_timing.encode_write_us = crate::host::telemetry_us() |
| 865 | .saturating_sub(phase) |
| 866 | .saturating_sub(self.last_sync_timing.fsync_us); |
| 867 | |
| 868 | let new_wal_size = self.last_synced_wal_offset; |
| 869 | Ok((orig_wal_size, new_wal_size, synced)) |
| 870 | } |
| 871 | |
| 872 | /// Ensures the LTX state matches where it left off from the real WAL. |
| 873 | /// |
| 874 | /// Ported branch-for-branch from `DB.verify` (db.go:1296-1436). |
| 875 | /// This is the snapshot-on-continuity-break brain — do not refactor for |
| 876 | /// elegance on pass one. |
| 877 | fn verify(&mut self) -> Result<SyncInfo> { |
| 878 | let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64; |
| 879 | let mut info = SyncInfo { |
| 880 | snapshotting: true, |
| 881 | ..Default::default() |
| 882 | }; |
| 883 | |
| 884 | let pos = self.pos()?; |
| 885 | if pos.txid == TXID(0) { |
| 886 | info.offset = WAL_HEADER_SIZE as i64; |
| 887 | return Ok(info); // first sync |
| 888 | } |
| 889 | |
| 890 | // Determine the last WAL offset we saved from: the header of the |
| 891 | // last L0 (db.go:1311-1326). This instance wrote that header one |
| 892 | // sync ago, so the cache answers without re-reading the file; a |
| 893 | // key miss (restore, compaction, reopen) reads and parses as the |
| 894 | // port always did. |
| 895 | let cache_hit = matches!(&self.last_l0_header, Some((txid, _)) if *txid == pos.txid); |
| 896 | let (hdr, ltx_bytes) = if cache_hit { |
| 897 | let (_, cached) = self.last_l0_header.as_ref().expect("matched above"); |
| 898 | (cached.clone(), None) |
| 899 | } else { |
| 900 | let ltx_path = self.ltx_path(0, pos.txid, pos.txid); |
| 901 | let ltx_bytes = match self.host.read(Path::new(<x_path)) { |
| 902 | Ok(b) => b, |
| 903 | Err(e) => { |
| 904 | return Err(Error::Ltx(Box::new(new_ltx_error( |
| 905 | "open", |
| 906 | <x_path, |
| 907 | 0, |
| 908 | pos.txid.0, |
| 909 | pos.txid.0, |
| 910 | e.into(), |
| 911 | )))); |
| 912 | } |
| 913 | }; |
| 914 | let parsed = match ltx::Header::parse(<x_bytes) { |
| 915 | Ok(h) => h, |
| 916 | Err(_) => { |
| 917 | return Err(Error::Ltx(Box::new(new_ltx_error( |
| 918 | "decode", |
| 919 | <x_path, |
| 920 | 0, |
| 921 | pos.txid.0, |
| 922 | pos.txid.0, |
| 923 | Error::LTXCorrupted, |
| 924 | )))); |
| 925 | } |
| 926 | }; |
| 927 | ( |
| 928 | LastL0Header { |
| 929 | wal_offset: parsed.wal_offset, |
| 930 | wal_size: parsed.wal_size, |
| 931 | wal_salt1: parsed.wal_salt1, |
| 932 | wal_salt2: parsed.wal_salt2, |
| 933 | commit: parsed.commit, |
| 934 | final_pgno: 0, |
| 935 | final_page: Vec::new(), |
| 936 | }, |
| 937 | Some(ltx_bytes), |
| 938 | ) |
| 939 | }; |
| 940 | info.offset = hdr.wal_offset + hdr.wal_size; |
| 941 | info.salt1 = hdr.wal_salt1; |
| 942 | info.salt2 = hdr.wal_salt2; |
| 943 | info.prev_commit = hdr.commit; |
| 944 | |
| 945 | // If the LTX WAL offset exceeds the real WAL size, the WAL was truncated. |
| 946 | let wal_size = self.wal_file_size()?; |
| 947 | if info.offset > wal_size { |
| 948 | // If we previously synced to the exact WAL end, this truncation is an |
| 949 | // expected checkpoint: reset to the header and continue incrementally |
| 950 | // rather than snapshotting (issue #927, db.go:1335-1355). |
| 951 | if self.synced_to_wal_end { |
| 952 | self.synced_to_wal_end = false; |
| 953 | |
| 954 | let wal_hdr = self.wal_header_bytes()?; |
| 955 | info.offset = WAL_HEADER_SIZE as i64; |
| 956 | info.salt1 = be_u32(&wal_hdr[16..]); |
| 957 | info.salt2 = be_u32(&wal_hdr[20..]); |
| 958 | info.snapshotting = false; |
| 959 | info.reason = String::new(); |
| 960 | return Ok(info); |
| 961 | } |
| 962 | |
| 963 | info.reason = "wal truncated by another process".to_string(); |
| 964 | return Ok(info); |
| 965 | } |
| 966 | |
| 967 | // Compare WAL headers; restart from the beginning of the WAL if different. |
| 968 | let wal_hdr = self.wal_header_bytes()?; |
| 969 | let salt1 = be_u32(&wal_hdr[16..]); |
| 970 | let salt2 = be_u32(&wal_hdr[20..]); |
| 971 | let salt_match = salt1 == hdr.wal_salt1 && salt2 == hdr.wal_salt2; |
| 972 | |
| 973 | // Edge case: LTX represents the start of the WAL (WALOffset=32, WALSize=0). |
| 974 | // Handle this before computing prev_wal_offset to avoid underflow |
| 975 | // (32 - 4120 = -4088). See issue #900 (db.go:1375-1383). |
| 976 | if info.offset == WAL_HEADER_SIZE as i64 { |
| 977 | if salt_match { |
| 978 | info.snapshotting = false; |
| 979 | return Ok(info); |
| 980 | } |
| 981 | info.reason = "wal header salt reset, snapshotting".to_string(); |
| 982 | return Ok(info); |
| 983 | } |
| 984 | |
| 985 | // If the offset is at the start of the first page, we can't check the |
| 986 | // previous page (db.go:1386-1399). |
| 987 | let prev_wal_offset = info.offset - frame_size; |
| 988 | if prev_wal_offset == WAL_HEADER_SIZE as i64 { |
| 989 | if salt_match { |
| 990 | info.snapshotting = false; |
| 991 | return Ok(info); |
| 992 | } |
| 993 | info.reason = "wal header salt reset, snapshotting".to_string(); |
| 994 | return Ok(info); |
| 995 | } else if prev_wal_offset < WAL_HEADER_SIZE as i64 { |
| 996 | return Err(Error::Other( |
| 997 | format!("prev WAL offset is less than the header size: {prev_wal_offset}").into(), |
| 998 | )); |
| 999 | } |
| 1000 | |
| 1001 | // If we can't verify the last page is in the last LTX file, snapshot. |
| 1002 | let last_page_match = match <x_bytes { |
| 1003 | Some(bytes) => self.last_page_match(bytes, &hdr, prev_wal_offset, frame_size)?, |
| 1004 | None => self.last_page_match_cached(&hdr, prev_wal_offset, frame_size)?, |
| 1005 | }; |
| 1006 | if !last_page_match { |
| 1007 | info.reason = |
| 1008 | "last page does not exist in last ltx file, wal overwritten by another process" |
| 1009 | .to_string(); |
| 1010 | return Ok(info); |
| 1011 | } |
| 1012 | |
| 1013 | // Salt changed (possible FULL/RESTART checkpoint). With a last-page match |
| 1014 | // we assume the WAL was not overwritten (db.go:1412-1431). |
| 1015 | if !salt_match { |
| 1016 | info.offset = WAL_HEADER_SIZE as i64; |
| 1017 | info.salt1 = salt1; |
| 1018 | info.salt2 = salt2; |
| 1019 | |
| 1020 | let detected = |
| 1021 | self.detect_full_checkpoint(&[(salt1, salt2), (hdr.wal_salt1, hdr.wal_salt2)])?; |
| 1022 | if detected { |
| 1023 | info.reason = "full or restart checkpoint detected, snapshotting".to_string(); |
| 1024 | } else { |
| 1025 | info.snapshotting = false; |
| 1026 | } |
| 1027 | return Ok(info); |
| 1028 | } |
| 1029 | |
| 1030 | info.snapshotting = false; |
| 1031 | Ok(info) |
| 1032 | } |
| 1033 | |
| 1034 | /// Checks whether the last page read in the WAL exists in the last LTX file. |
| 1035 | /// |
| 1036 | /// Ported from `DB.lastPageMatch` (db.go:1438-1475). Re-reads the last synced |
| 1037 | /// WAL frame and searches the last LTX file's pages for a matching |
| 1038 | /// `(pgno, data)` pair. |
| 1039 | fn last_page_match( |
| 1040 | &mut self, |
| 1041 | ltx_bytes: &[u8], |
| 1042 | hdr: &LastL0Header, |
| 1043 | prev_wal_offset: i64, |
| 1044 | frame_size: i64, |
| 1045 | ) -> Result<bool> { |
| 1046 | if prev_wal_offset <= WAL_HEADER_SIZE as i64 { |
| 1047 | return Ok(false); |
| 1048 | } |
| 1049 | |
| 1050 | let frame = self.wal_bytes_at(prev_wal_offset, frame_size)?; |
| 1051 | let pgno = be_u32(&frame[0..]); |
| 1052 | let fsalt1 = be_u32(&frame[8..]); |
| 1053 | let fsalt2 = be_u32(&frame[12..]); |
| 1054 | let data = &frame[WAL_FRAME_HEADER_SIZE..]; |
| 1055 | |
| 1056 | if fsalt1 != hdr.wal_salt1 || fsalt2 != hdr.wal_salt2 { |
| 1057 | return Ok(false); |
| 1058 | } |
| 1059 | |
| 1060 | // Verify the last WAL page exists, byte-for-byte, in the last LTX file. |
| 1061 | // Decode the full file and compare the decompressed page bytes. |
| 1062 | let pages = ltx::decode_file_pages(ltx_bytes).map_err(|_| Error::LTXCorrupted)?; |
| 1063 | for (p, page_data) in &pages { |
| 1064 | if *p == pgno && page_data.as_slice() == data { |
| 1065 | return Ok(true); |
| 1066 | } |
| 1067 | } |
| 1068 | Ok(false) |
| 1069 | } |
| 1070 | |
| 1071 | /// The cache-backed page check: compares the WAL frame at |
| 1072 | /// `prev_wal_offset` against the final frame the previous sync |
| 1073 | /// consumed. Equivalent to the ported search when the WAL is |
| 1074 | /// unchanged (the L0's entry for that page IS that frame), and |
| 1075 | /// strictly more conservative when it is not — a mismatch forces a |
| 1076 | /// snapshot, never an incremental read over rewritten history. |
| 1077 | fn last_page_match_cached( |
| 1078 | &mut self, |
| 1079 | hdr: &LastL0Header, |
| 1080 | prev_wal_offset: i64, |
| 1081 | frame_size: i64, |
| 1082 | ) -> Result<bool> { |
| 1083 | if prev_wal_offset <= WAL_HEADER_SIZE as i64 || hdr.final_page.is_empty() { |
| 1084 | return Ok(false); |
| 1085 | } |
| 1086 | let frame = self.wal_bytes_at(prev_wal_offset, frame_size)?; |
| 1087 | let pgno = be_u32(&frame[0..]); |
| 1088 | let fsalt1 = be_u32(&frame[8..]); |
| 1089 | let fsalt2 = be_u32(&frame[12..]); |
| 1090 | let data = &frame[WAL_FRAME_HEADER_SIZE..]; |
| 1091 | Ok(fsalt1 == hdr.wal_salt1 |
| 1092 | && fsalt2 == hdr.wal_salt2 |
| 1093 | && pgno == hdr.final_pgno |
| 1094 | && data == hdr.final_page.as_slice()) |
| 1095 | } |
| 1096 | |
| 1097 | /// Detects whether a FULL or RESTART checkpoint occurred (we may have missed |
| 1098 | /// frames). Ported from `DB.detectFullCheckpoint` (db.go:1477-1507). |
| 1099 | fn detect_full_checkpoint(&self, known_salts: &[(u32, u32)]) -> Result<bool> { |
| 1100 | let wal_bytes = self.host.read(&self.wal_path())?; |
| 1101 | let rd = WalReader::new(&wal_bytes).map_err(Error::from)?; |
| 1102 | let last_known = known_salts.last().copied().unwrap_or((0, 0)); |
| 1103 | let mut m = rd.frame_salts_until(last_known); |
| 1104 | for s in known_salts { |
| 1105 | m.remove(s); |
| 1106 | } |
| 1107 | Ok(!m.is_empty()) |
| 1108 | } |
| 1109 | |
| 1110 | /// Copies pending bytes from the real WAL into a new L0 LTX file. |
| 1111 | /// |
| 1112 | /// Ported from `DB.sync` (db.go:1517-1723). Returns `true` if an LTX file was |
| 1113 | /// written (there were new pages or we were snapshotting). Atomic |
| 1114 | /// tmp→fsync→rename with the pos cache + anti-feedback flags updated after. |
| 1115 | fn sync_inner(&mut self, mut info: SyncInfo) -> Result<bool> { |
| 1116 | let phase = crate::host::telemetry_us(); |
| 1117 | let pos = self.pos()?; |
| 1118 | let tx_id = TXID(pos.txid.0 + 1); |
| 1119 | let filename = self.ltx_path(0, tx_id, tx_id); |
| 1120 | |
| 1121 | let db_size = self.db_file_size()?; |
| 1122 | let mut commit = (db_size / self.page_size as i64) as u32; |
| 1123 | self.last_sync_timing.pos_us = crate::host::telemetry_us().saturating_sub(phase); |
| 1124 | let phase = crate::host::telemetry_us(); |
| 1125 | |
| 1126 | // The incremental path reads only what the reader touches: the |
| 1127 | // 32-byte WAL header, the previous frame, and the frames from |
| 1128 | // `info.offset` on. The whole-file read it replaces cost ~1.5 us |
| 1129 | // per WAL page PER SYNC at constant delta (sync_cost.rs), which |
| 1130 | // was 69% of the fleet's capture time at saturation. The sparse |
| 1131 | // image keeps every offset absolute, so the reader and the page |
| 1132 | // collectors are byte-for-byte unchanged; a short tail read (a |
| 1133 | // rare truncation race) falls back to the full read the port |
| 1134 | // always did. |
| 1135 | let frame_size_bytes = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64; |
| 1136 | let mut wal = if info.snapshotting |
| 1137 | || info.offset <= WAL_HEADER_SIZE as i64 + frame_size_bytes |
| 1138 | { |
| 1139 | self.last_sync_timing.wal_read_kind = if info.snapshotting { 1 } else { 2 }; |
| 1140 | let bytes = self.host.read(&self.wal_path())?; |
| 1141 | self.last_sync_timing.wal_read_bytes = bytes.len() as u64; |
| 1142 | self.last_sync_timing.wal_len_bytes = bytes.len() as u64; |
| 1143 | WalImage::whole(bytes) |
| 1144 | } else { |
| 1145 | // The tail starts one frame early: the offset reader re-reads the |
| 1146 | // previous frame to seed its checksum. The image is the header |
| 1147 | // followed by that tail, and nothing in between — the reader maps |
| 1148 | // offsets through `tail_base` — so a sync allocates what it reads, |
| 1149 | // not the length of a file whose middle it never touches. |
| 1150 | let start = info.offset - frame_size_bytes; |
| 1151 | let tail_image = self.with_wal_file(|file| { |
| 1152 | let len = file.file_len()? as usize; |
| 1153 | if start as usize >= len { |
| 1154 | return Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof)); |
| 1155 | } |
| 1156 | let mut bytes = Vec::with_capacity(WAL_HEADER_SIZE + (len - start as usize)); |
| 1157 | bytes.extend_from_slice(&file.read_exact_at(0, WAL_HEADER_SIZE)?); |
| 1158 | bytes.extend_from_slice(&file.read_exact_at(start as u64, len - start as usize)?); |
| 1159 | Ok(WalImage { |
| 1160 | bytes, |
| 1161 | tail_base: start as usize, |
| 1162 | file_len: len, |
| 1163 | }) |
| 1164 | }); |
| 1165 | match tail_image { |
| 1166 | Ok(image) => { |
| 1167 | self.last_sync_timing.wal_read_kind = 0; |
| 1168 | self.last_sync_timing.wal_read_bytes = image.bytes.len() as u64; |
| 1169 | self.last_sync_timing.wal_len_bytes = image.file_len as u64; |
| 1170 | image |
| 1171 | } |
| 1172 | Err(_) => { |
| 1173 | self.last_sync_timing.wal_read_kind = 3; |
| 1174 | let bytes = self.host.read(&self.wal_path())?; |
| 1175 | self.last_sync_timing.wal_read_bytes = bytes.len() as u64; |
| 1176 | self.last_sync_timing.wal_len_bytes = bytes.len() as u64; |
| 1177 | WalImage::whole(bytes) |
| 1178 | } |
| 1179 | } |
| 1180 | }; |
| 1181 | |
| 1182 | self.last_sync_timing.wal_read_us = crate::host::telemetry_us().saturating_sub(phase); |
| 1183 | self.last_sync_timing.wal_image_bytes = wal.bytes.len() as u64; |
| 1184 | self.last_sync_timing.snapshot = info.snapshotting; |
| 1185 | self.last_sync_timing.snapshot_reason = if info.snapshotting { |
| 1186 | snapshot_reason_code(&info.reason) |
| 1187 | } else { |
| 1188 | 0 |
| 1189 | }; |
| 1190 | let phase = crate::host::telemetry_us(); |
| 1191 | |
| 1192 | // Choose the WAL reader start: from the header, or seek to info.offset. |
| 1193 | // A previous-frame mismatch falls back to a full read (snapshot), |
| 1194 | // mirroring NewWALReaderWithOffset's PrevFrameMismatchError handling |
| 1195 | // (db.go:1565-1581). |
| 1196 | // A previous-frame mismatch restarts the read from the header. The |
| 1197 | // sparse tail image is zero-filled below `start`, so a from-header |
| 1198 | // reader over it would see no valid frame and report "nothing to |
| 1199 | // capture" — a silent miss the ship loop would then credit. The |
| 1200 | // mismatch path therefore re-reads the complete WAL first, which is |
| 1201 | // exactly the port's former full-read behavior on this branch. |
| 1202 | let mismatch = !(info.offset == WAL_HEADER_SIZE as i64) |
| 1203 | && matches!( |
| 1204 | wal.reader_at(info.offset, info.salt1, info.salt2), |
| 1205 | Err(crate::wal::WalError::PrevFrameMismatch) |
| 1206 | ); |
| 1207 | if mismatch { |
| 1208 | info.offset = WAL_HEADER_SIZE as i64; |
| 1209 | if self.last_sync_timing.wal_read_kind == 0 { |
| 1210 | let bytes = self.host.read(&self.wal_path())?; |
| 1211 | self.last_sync_timing.wal_read_kind = 3; |
| 1212 | self.last_sync_timing.wal_read_bytes = bytes.len() as u64; |
| 1213 | self.last_sync_timing.wal_len_bytes = bytes.len() as u64; |
| 1214 | self.last_sync_timing.wal_image_bytes = bytes.len() as u64; |
| 1215 | wal = WalImage::whole(bytes); |
| 1216 | } |
| 1217 | } |
| 1218 | let mut rd = if info.offset == WAL_HEADER_SIZE as i64 { |
| 1219 | WalReader::new(&wal.bytes).map_err(Error::from)? |
| 1220 | } else { |
| 1221 | wal.reader_at(info.offset, info.salt1, info.salt2) |
| 1222 | .map_err(Error::from)? |
| 1223 | }; |
| 1224 | |
| 1225 | let (page_map, max_offset, wal_commit) = rd.page_map().map_err(Error::from)?; |
| 1226 | if wal_commit > 0 { |
| 1227 | commit = wal_commit; |
| 1228 | } |
| 1229 | |
| 1230 | let sz = if max_offset > 0 { |
| 1231 | max_offset - info.offset |
| 1232 | } else { |
| 1233 | 0 |
| 1234 | }; |
| 1235 | if sz < 0 { |
| 1236 | return Err(Error::Other( |
| 1237 | format!( |
| 1238 | "wal size must be positive: sz={sz}, maxOffset={max_offset}, info.offset={}", |
| 1239 | info.offset |
| 1240 | ) |
| 1241 | .into(), |
| 1242 | )); |
| 1243 | } |
| 1244 | |
| 1245 | // Exit if there are no new WAL pages and we are not snapshotting |
| 1246 | // (db.go:1603-1607). |
| 1247 | if !info.snapshotting && sz == 0 { |
| 1248 | return Ok(false); |
| 1249 | } |
| 1250 | |
| 1251 | let (rd_salt1, rd_salt2) = rd.salt(); |
| 1252 | |
| 1253 | // Build the page set for the encoder. |
| 1254 | let pages: Vec<(u32, Vec<u8>)> = if info.snapshotting { |
| 1255 | self.collect_snapshot_pages(&wal, &page_map, commit)? |
| 1256 | } else { |
| 1257 | self.collect_wal_pages(&wal, &page_map, info.prev_commit, commit)? |
| 1258 | }; |
| 1259 | self.last_sync_timing.map_collect_us = crate::host::telemetry_us().saturating_sub(phase); |
| 1260 | let phase = crate::host::telemetry_us(); |
| 1261 | |
| 1262 | let header = ltx::Header { |
| 1263 | version: ltx::VERSION, |
| 1264 | flags: ltx::HEADER_FLAG_NO_CHECKSUM, |
| 1265 | page_size: self.page_size, |
| 1266 | commit, |
| 1267 | min_txid: tx_id, |
| 1268 | max_txid: tx_id, |
| 1269 | timestamp: self.host.now_unix_millis(), |
| 1270 | pre_apply_checksum: 0, |
| 1271 | wal_offset: info.offset, |
| 1272 | wal_size: sz, |
| 1273 | wal_salt1: rd_salt1, |
| 1274 | wal_salt2: rd_salt2, |
| 1275 | node_id: 0, |
| 1276 | }; |
| 1277 | |
| 1278 | // Encode the LTX file (with HeaderFlagNoChecksum, so post-apply is 0). |
| 1279 | let encoded = ltx::encode_file(&header, &pages, 0)?; |
| 1280 | self.last_sync_timing.ltx_encode_us = crate::host::telemetry_us().saturating_sub(phase); |
| 1281 | let phase = crate::host::telemetry_us(); |
| 1282 | |
| 1283 | // Atomic tmp → fsync → rename (db.go:1609-1685). |
| 1284 | let tmp_filename = format!("{filename}.tmp"); |
| 1285 | let parent = Path::new(&tmp_filename).parent().map(Path::to_path_buf); |
| 1286 | if !self.l0_dir_ready { |
| 1287 | if let Some(parent) = &parent { |
| 1288 | self.host.create_dir_all(parent)?; |
| 1289 | } |
| 1290 | self.l0_dir_ready = true; |
| 1291 | } |
| 1292 | // On rename failure, clear the L0 cache + invalidate pos |
| 1293 | // (db.go:1680-1684); the error path below does that. A directory |
| 1294 | // that vanished under a ready flag is recreated once and the cut |
| 1295 | // retried, so the flag saves a `mkdir` per sync without trusting it. |
| 1296 | self.last_sync_timing.fsync_us = |
| 1297 | match write_file_atomic(&self.host, &tmp_filename, &filename, &encoded) { |
| 1298 | Err(Error::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => { |
| 1299 | if let Some(parent) = &parent { |
| 1300 | self.host.create_dir_all(parent)?; |
| 1301 | } |
| 1302 | write_file_atomic(&self.host, &tmp_filename, &filename, &encoded)? |
| 1303 | } |
| 1304 | other => other?, |
| 1305 | }; |
| 1306 | self.last_sync_timing.file_write_us = crate::host::telemetry_us() |
| 1307 | .saturating_sub(phase) |
| 1308 | .saturating_sub(self.last_sync_timing.fsync_us); |
| 1309 | // The next verify reads exactly these fields back; caching them — |
| 1310 | // plus the final consumed WAL frame for the page check — is what |
| 1311 | // spares it re-reading the file it just watched being written. |
| 1312 | let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64; |
| 1313 | let final_frame_offset = max_offset - frame_size; |
| 1314 | let (final_pgno, final_page) = match (final_frame_offset >= WAL_HEADER_SIZE as i64) |
| 1315 | .then(|| wal.slice(final_frame_offset, frame_size as usize)) |
| 1316 | .flatten() |
| 1317 | { |
| 1318 | Some(frame) => (be_u32(&frame[0..]), frame[WAL_FRAME_HEADER_SIZE..].to_vec()), |
| 1319 | None => (0, Vec::new()), |
| 1320 | }; |
| 1321 | self.last_l0_header = Some(( |
| 1322 | tx_id, |
| 1323 | LastL0Header { |
| 1324 | wal_offset: info.offset, |
| 1325 | wal_size: sz, |
| 1326 | wal_salt1: rd_salt1, |
| 1327 | wal_salt2: rd_salt2, |
| 1328 | commit, |
| 1329 | final_pgno, |
| 1330 | final_page, |
| 1331 | }, |
| 1332 | )); |
| 1333 | |
| 1334 | // Update the L0 file-info cache and the cached position (db.go:1687-1702). |
| 1335 | self.max_l0_file_info = Some(ltx::FileInfo { |
| 1336 | level: 0, |
| 1337 | min_txid: tx_id, |
| 1338 | max_txid: tx_id, |
| 1339 | pre_apply_checksum: 0, |
| 1340 | post_apply_checksum: 0, |
| 1341 | size: encoded.len() as i64, |
| 1342 | created_at: Some(system_time_from_unix_millis(self.host.now_unix_millis())), |
| 1343 | }); |
| 1344 | // The encoder's post-apply pos: for a NoChecksum file the post-apply |
| 1345 | // checksum is 0; the position is (tx_id, 0). |
| 1346 | self.pos_cache = Some(Pos::new(tx_id, 0)); |
| 1347 | |
| 1348 | // Track the logical end of WAL content for checkpoint decisions |
| 1349 | // (db.go:1704-1718, issues #997/#927). |
| 1350 | let final_offset = info.offset + sz; |
| 1351 | self.last_synced_wal_offset = final_offset; |
| 1352 | self.synced_to_wal_end = match self.wal_file_size() { |
| 1353 | Ok(wal_size) => final_offset == wal_size, |
| 1354 | Err(_) => false, |
| 1355 | }; |
| 1356 | |
| 1357 | Ok(true) |
| 1358 | } |
| 1359 | |
| 1360 | /// Collects the page set for an incremental sync, in ascending page-number |
| 1361 | /// order. Pages absent from the WAL growth range come from the database file |
| 1362 | /// (Litestream #1292 / celld #150). |
| 1363 | fn collect_wal_pages( |
| 1364 | &self, |
| 1365 | wal: &WalImage, |
| 1366 | page_map: &HashMap<u32, i64>, |
| 1367 | prev_commit: u32, |
| 1368 | commit: u32, |
| 1369 | ) -> Result<Vec<(u32, Vec<u8>)>> { |
| 1370 | let mut pgnos: Vec<u32> = page_map.keys().copied().collect(); |
| 1371 | let lock = lock_pgno(self.page_size); |
| 1372 | if commit > prev_commit { |
| 1373 | for pgno in (prev_commit + 1)..=commit { |
| 1374 | if pgno != lock && !page_map.contains_key(&pgno) { |
| 1375 | pgnos.push(pgno); |
| 1376 | } |
| 1377 | } |
| 1378 | } |
| 1379 | pgnos.sort_unstable(); |
| 1380 | |
| 1381 | let mut out = Vec::with_capacity(pgnos.len()); |
| 1382 | let mut db_file: Option<crate::HostFile> = None; |
| 1383 | for pgno in pgnos { |
| 1384 | let data = if let Some(&offset) = page_map.get(&pgno) { |
| 1385 | wal.page(offset, self.page_size)? |
| 1386 | } else { |
| 1387 | let f = match &mut db_file { |
| 1388 | Some(f) => f, |
| 1389 | None => { |
| 1390 | db_file = Some(self.host.open(&self.path)?); |
| 1391 | db_file.as_mut().unwrap() |
| 1392 | } |
| 1393 | }; |
| 1394 | let offset = (pgno as i64 - 1) * self.page_size as i64; |
| 1395 | f.read_exact_at(offset as u64, self.page_size as usize)? |
| 1396 | }; |
| 1397 | out.push((pgno, data)); |
| 1398 | } |
| 1399 | Ok(out) |
| 1400 | } |
| 1401 | |
| 1402 | /// Collects the full page set for a snapshot: every page `1..=commit` |
| 1403 | /// (skipping the lock page), reading from the WAL where present, else the DB |
| 1404 | /// file. Ported from `DB.writeLTXFromDB` (db.go:1725-1770). |
| 1405 | fn collect_snapshot_pages( |
| 1406 | &self, |
| 1407 | wal: &WalImage, |
| 1408 | page_map: &HashMap<u32, i64>, |
| 1409 | commit: u32, |
| 1410 | ) -> Result<Vec<(u32, Vec<u8>)>> { |
| 1411 | let lock = lock_pgno(self.page_size); |
| 1412 | let mut db_file: Option<crate::HostFile> = None; |
| 1413 | let mut out = Vec::with_capacity(commit as usize); |
| 1414 | |
| 1415 | for pgno in 1..=commit { |
| 1416 | if pgno == lock { |
| 1417 | continue; |
| 1418 | } |
| 1419 | if let Some(&offset) = page_map.get(&pgno) { |
| 1420 | let data = wal.page(offset, self.page_size)?; |
| 1421 | out.push((pgno, data)); |
| 1422 | continue; |
| 1423 | } |
| 1424 | // Read directly from the database file. |
| 1425 | let f = match &mut db_file { |
| 1426 | Some(f) => f, |
| 1427 | None => { |
| 1428 | db_file = Some(self.host.open(&self.path)?); |
| 1429 | db_file.as_mut().unwrap() |
| 1430 | } |
| 1431 | }; |
| 1432 | let offset = (pgno as i64 - 1) * self.page_size as i64; |
| 1433 | let data = f.read_exact_at(offset as u64, self.page_size as usize)?; |
| 1434 | out.push((pgno, data)); |
| 1435 | } |
| 1436 | Ok(out) |
| 1437 | } |
| 1438 | |
| 1439 | // ── Checkpointing ────────────────────────────────────────────────────── |
| 1440 | |
| 1441 | /// Performs a checkpoint based on the configured thresholds (3-tier policy). |
| 1442 | /// |
| 1443 | /// Ported from `DB.checkpointIfNeeded` (db.go:1092-1156). Checks |
| 1444 | /// in priority order: TruncatePageN (TRUNCATE, blocking) → MinCheckpointPageN |
| 1445 | /// (PASSIVE) → CheckpointInterval (PASSIVE, gated on `synced_since_checkpoint`). |
| 1446 | fn checkpoint_if_needed(&mut self, orig_wal_size: i64, new_wal_size: i64) -> Result<()> { |
| 1447 | if self.page_size == 0 { |
| 1448 | return Ok(()); |
| 1449 | } |
| 1450 | |
| 1451 | // Priority 1: emergency TRUNCATE (blocking) on the *original* logical size. |
| 1452 | if self.truncate_page_n > 0 |
| 1453 | && orig_wal_size >= calc_wal_size(self.page_size, self.truncate_page_n) |
| 1454 | { |
| 1455 | return self.checkpoint(CheckpointMode::Truncate); |
| 1456 | } |
| 1457 | |
| 1458 | // Priority 2: PASSIVE at the min threshold on the *new* logical size. |
| 1459 | if new_wal_size >= calc_wal_size(self.page_size, self.min_checkpoint_page_n) { |
| 1460 | return self.checkpoint_passive_swallowing_busy(); |
| 1461 | } |
| 1462 | |
| 1463 | // Priority 3: time-based PASSIVE, gated on data synced since last |
| 1464 | // checkpoint (#896). Uses the DB-file mtime and a logical-size guard so an |
| 1465 | // idle DB does not spin LTX files (db.go:1133-1153). |
| 1466 | if self.checkpoint_interval > Duration::ZERO && self.synced_since_checkpoint { |
| 1467 | let elapsed = self.host.file_age(&self.path)?; |
| 1468 | if elapsed > self.checkpoint_interval && new_wal_size > calc_wal_size(self.page_size, 1) |
| 1469 | { |
| 1470 | return self.checkpoint_passive_swallowing_busy(); |
| 1471 | } |
| 1472 | } |
| 1473 | |
| 1474 | Ok(()) |
| 1475 | } |
| 1476 | |
| 1477 | /// PASSIVE checkpoint that swallows SQLITE_BUSY (log-and-continue, the one |
| 1478 | /// sanctioned best-effort case, db.go:1118-1124). |
| 1479 | fn checkpoint_passive_swallowing_busy(&mut self) -> Result<()> { |
| 1480 | match self.checkpoint(CheckpointMode::Passive) { |
| 1481 | Ok(()) => Ok(()), |
| 1482 | Err(e) if is_sqlite_busy_error(&e) => Ok(()), |
| 1483 | Err(e) => Err(e), |
| 1484 | } |
| 1485 | } |
| 1486 | |
| 1487 | /// Performs a checkpoint on the WAL. |
| 1488 | /// |
| 1489 | /// Ported from `DB.Checkpoint`/`DB.checkpoint` (db.go:1801-1873). |
| 1490 | /// A passive checkpoint seals the WAL under a short writer barrier before |
| 1491 | /// it runs. If any checkpoint restarts the WAL, a post-checkpoint write lock |
| 1492 | /// protects either an incremental sync or a full boundary snapshot. |
| 1493 | /// |
| 1494 | /// The upstream `chkMu.TryLock` snapshot-vs-checkpoint gate is unnecessary in |
| 1495 | /// the synchronous `Db`. `&mut self` serializes `sync`, `checkpoint`, and |
| 1496 | /// `snapshot`, and one blocking thread owns the `Db`. |
| 1497 | pub fn checkpoint(&mut self, mode: CheckpointMode) -> Result<()> { |
| 1498 | self.checkpoint_with_passive_hooks(mode, None, None) |
| 1499 | } |
| 1500 | |
| 1501 | fn checkpoint_with_passive_hooks( |
| 1502 | &mut self, |
| 1503 | mode: CheckpointMode, |
| 1504 | passive_hook: Option<Box<dyn FnOnce() + Send>>, |
| 1505 | passive_unlocked_hook: Option<Box<dyn FnOnce() + Send>>, |
| 1506 | ) -> Result<()> { |
| 1507 | // Self-heal, as in `sync`: `checkpoint` writes to both control tables |
| 1508 | // and re-acquires the read lock through `_litestream_seq`, and the |
| 1509 | // invariant is that the tables exist before any control-table |
| 1510 | // statement — not only before a capture. |
| 1511 | self.ensure_control_tables()?; |
| 1512 | |
| 1513 | // Read the WAL header before the checkpoint to detect a restart. |
| 1514 | let hdr = self.wal_header_bytes()?; |
| 1515 | |
| 1516 | // Copy the end of the WAL before the checkpoint to capture as much as |
| 1517 | // possible (db.go:1823-1826). |
| 1518 | self.verify_and_sync(None)?; |
| 1519 | |
| 1520 | let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64; |
| 1521 | let pre_checkpoint_frame_n = if self.last_synced_wal_offset > WAL_HEADER_SIZE as i64 { |
| 1522 | (self.last_synced_wal_offset - WAL_HEADER_SIZE as i64) / frame_size |
| 1523 | } else { |
| 1524 | 0 |
| 1525 | }; |
| 1526 | |
| 1527 | // A passive checkpoint does not acquire SQLite's writer lock. Hold a |
| 1528 | // short write transaction on the dedicated read-lock connection, then |
| 1529 | // sync again to seal every commit before running the checkpoint on the |
| 1530 | // main connection. Keep the barrier until the checkpoint completes. |
| 1531 | let wal_frame_n = if mode == CheckpointMode::Passive { |
| 1532 | self.exec_passive_checkpoint_with_barrier(hdr, passive_hook, passive_unlocked_hook)? |
| 1533 | } else { |
| 1534 | self.exec_checkpoint(mode)? |
| 1535 | }; |
| 1536 | |
| 1537 | // Force a write so a restarted WAL has a new header and at least one |
| 1538 | // frame that verify can read. |
| 1539 | self.conn |
| 1540 | .execute_batch( |
| 1541 | "INSERT INTO _litestream_seq (id, seq) VALUES (1, 1) \ |
| 1542 | ON CONFLICT (id) DO UPDATE SET seq = seq + 1", |
| 1543 | ) |
| 1544 | .map_err(sql_err)?; |
| 1545 | |
| 1546 | // If the WAL header is unchanged, the WAL did not restart — done. |
| 1547 | let other = self.wal_header_bytes()?; |
| 1548 | if hdr == other { |
| 1549 | self.synced_since_checkpoint = false; |
| 1550 | return Ok(()); |
| 1551 | } |
| 1552 | |
| 1553 | // The WAL restarted. Grab the write lock, then either copy the new WAL |
| 1554 | // tail or take a complete boundary image. TRUNCATE always needs the |
| 1555 | // boundary image because SQLite reports zero frames after resetting the |
| 1556 | // WAL. A forced checkpoint also needs one if it covered more frames than |
| 1557 | // the sealed pre-checkpoint sync observed. |
| 1558 | self.conn |
| 1559 | .prepare_cached("BEGIN") |
| 1560 | .and_then(|mut statement| statement.execute([])) |
| 1561 | .map_err(sql_err)?; |
| 1562 | let post = (|| -> Result<()> { |
| 1563 | self.conn |
| 1564 | .prepare_cached("INSERT INTO _litestream_lock (id) VALUES (1)") |
| 1565 | .and_then(|mut statement| statement.execute([])) |
| 1566 | .map_err(sql_err)?; |
| 1567 | if mode == CheckpointMode::Truncate |
| 1568 | || (mode != CheckpointMode::Passive && wal_frame_n > pre_checkpoint_frame_n) |
| 1569 | { |
| 1570 | let info = SyncInfo { |
| 1571 | offset: WAL_HEADER_SIZE as i64, |
| 1572 | salt1: be_u32(&other[16..]), |
| 1573 | salt2: be_u32(&other[20..]), |
| 1574 | snapshotting: true, |
| 1575 | reason: "checkpoint boundary snapshot".to_string(), |
| 1576 | ..Default::default() |
| 1577 | }; |
| 1578 | self.sync_inner(info)?; |
| 1579 | } else { |
| 1580 | self.verify_and_sync(None)?; |
| 1581 | } |
| 1582 | Ok(()) |
| 1583 | })(); |
| 1584 | // Always roll back the write transaction (db.go:1849,1867). |
| 1585 | let rb = rollback(&self.conn); |
| 1586 | post?; |
| 1587 | rb?; |
| 1588 | |
| 1589 | self.synced_since_checkpoint = false; |
| 1590 | Ok(()) |
| 1591 | } |
| 1592 | |
| 1593 | /// Seals and runs a passive checkpoint while holding SQLite's writer lock. |
| 1594 | /// |
| 1595 | /// The long-lived read transaction uses `rtx_conn`, so this method releases |
| 1596 | /// that read lock and temporarily reuses the same connection for the writer |
| 1597 | /// barrier. The checkpoint itself runs through `conn`, as SQLite does not |
| 1598 | /// permit a checkpoint on the connection that owns the write transaction. |
| 1599 | fn exec_passive_checkpoint_with_barrier( |
| 1600 | &mut self, |
| 1601 | pre_checkpoint_header: [u8; WAL_HEADER_SIZE], |
| 1602 | hook: Option<Box<dyn FnOnce() + Send>>, |
| 1603 | unlocked_hook: Option<Box<dyn FnOnce() + Send>>, |
| 1604 | ) -> Result<i64> { |
| 1605 | self.release_read_lock()?; |
| 1606 | if let Some(hook) = unlocked_hook { |
| 1607 | hook(); |
| 1608 | } |
| 1609 | |
| 1610 | let result = (|| -> Result<i64> { |
| 1611 | self.rtx_conn |
| 1612 | .prepare_cached("BEGIN") |
| 1613 | .and_then(|mut statement| statement.execute([])) |
| 1614 | .map_err(sql_err)?; |
| 1615 | self.rtx_conn |
| 1616 | .prepare_cached("INSERT INTO _litestream_lock (id) VALUES (1)") |
| 1617 | .and_then(|mut statement| statement.execute([])) |
| 1618 | .map_err(sql_err)?; |
| 1619 | |
| 1620 | // Writers can cross their own autocheckpoint threshold after the |
| 1621 | // read lock is released but before this barrier wins SQLite's |
| 1622 | // writer lock. A changed WAL header means some of those commits |
| 1623 | // can already live only in the database file. The normal |
| 1624 | // synced-to-end shortcut cannot distinguish that race from our own |
| 1625 | // completed checkpoint, so an incremental LTX can omit the |
| 1626 | // checkpointed pages and produce a malformed restore. Seal the |
| 1627 | // complete boundary while the writer lock makes the database file |
| 1628 | // and the new WAL tail a stable pair. The cost is one database-size |
| 1629 | // LTX file only when another checkpoint wins this narrow gap. |
| 1630 | let barrier_header = self.wal_header_bytes()?; |
| 1631 | if barrier_header != pre_checkpoint_header { |
| 1632 | let info = SyncInfo { |
| 1633 | offset: WAL_HEADER_SIZE as i64, |
| 1634 | salt1: be_u32(&barrier_header[16..]), |
| 1635 | salt2: be_u32(&barrier_header[20..]), |
| 1636 | snapshotting: true, |
| 1637 | reason: "WAL restarted before passive checkpoint barrier".to_string(), |
| 1638 | ..Default::default() |
| 1639 | }; |
| 1640 | self.sync_inner(info)?; |
| 1641 | } else { |
| 1642 | // Commits can land between the earlier sync and acquisition of |
| 1643 | // the barrier. This second sync seals them before the |
| 1644 | // checkpoint. |
| 1645 | self.verify_and_sync(None)?; |
| 1646 | } |
| 1647 | if let Some(hook) = hook { |
| 1648 | hook(); |
| 1649 | } |
| 1650 | self.run_checkpoint_pragma(CheckpointMode::Passive) |
| 1651 | })(); |
| 1652 | |
| 1653 | // Release the writer barrier before restoring the long-lived read lock. |
| 1654 | // Preserve the operation error if both the operation and cleanup fail. |
| 1655 | let rollback_result = rollback(&self.rtx_conn); |
| 1656 | let reacquire_result = self.acquire_read_lock(); |
| 1657 | match result { |
| 1658 | Err(error) => Err(error), |
| 1659 | Ok(wal_frame_n) => { |
| 1660 | rollback_result?; |
| 1661 | reacquire_result?; |
| 1662 | Ok(wal_frame_n) |
| 1663 | } |
| 1664 | } |
| 1665 | } |
| 1666 | |
| 1667 | /// Releases the read lock, runs `PRAGMA wal_checkpoint(<mode>)`, and |
| 1668 | /// re-acquires the read lock — re-acquiring even on error. |
| 1669 | /// |
| 1670 | /// Ported from `DB.execCheckpoint` (db.go:1875-1919). The exact |
| 1671 | /// release→checkpoint→re-acquire sequence is load-bearing. |
| 1672 | fn exec_checkpoint(&mut self, mode: CheckpointMode) -> Result<i64> { |
| 1673 | // Ensure the read lock is removed before the checkpoint; defer the |
| 1674 | // re-acquire so it runs even on early return. |
| 1675 | self.release_read_lock()?; |
| 1676 | |
| 1677 | let result = self.run_checkpoint_pragma(mode); |
| 1678 | |
| 1679 | // Re-acquire the read lock immediately after the checkpoint (the deferred |
| 1680 | // re-acquire in Go). If the pragma succeeded, propagate any re-acquire |
| 1681 | // error; otherwise surface the original pragma error. |
| 1682 | let reacquire = self.acquire_read_lock(); |
| 1683 | match (result, reacquire) { |
| 1684 | (Ok(wal_frame_n), Ok(())) => Ok(wal_frame_n), |
| 1685 | (Ok(_), Err(e)) => Err(e), |
| 1686 | (Err(e), _) => Err(e), |
| 1687 | } |
| 1688 | } |
| 1689 | |
| 1690 | /// Runs the raw `PRAGMA wal_checkpoint(<mode>)` and reads its 3-int result. |
| 1691 | fn run_checkpoint_pragma(&self, mode: CheckpointMode) -> Result<i64> { |
| 1692 | let sql = format!("PRAGMA wal_checkpoint({mode})"); |
| 1693 | let (_, wal_frame_n, _): (i64, i64, i64) = self |
| 1694 | .conn |
| 1695 | .prepare_cached(&sql) |
| 1696 | .map_err(sql_err)? |
| 1697 | .query_row([], |row| { |
| 1698 | Ok(( |
| 1699 | row.get::<_, i64>(0)?, |
| 1700 | row.get::<_, i64>(1)?, |
| 1701 | row.get::<_, i64>(2)?, |
| 1702 | )) |
| 1703 | }) |
| 1704 | .map_err(sql_err)?; |
| 1705 | Ok(wal_frame_n) |
| 1706 | } |
| 1707 | |
| 1708 | // ── CRC64 ────────────────────────────────────────────────────────────── |
| 1709 | |
| 1710 | /// Returns a CRC-64/ISO checksum of the database file and its current |
| 1711 | /// position, after forcing a RESTART checkpoint so the DB sits at the WAL |
| 1712 | /// start. Ported from `DB.CRC64` (db.go:2329-2359). |
| 1713 | pub fn crc64(&mut self) -> Result<(u64, Pos)> { |
| 1714 | // Force a RESTART checkpoint to ensure the DB is at the start of the WAL. |
| 1715 | self.checkpoint(CheckpointMode::Restart)?; |
| 1716 | |
| 1717 | let pos = self.pos()?; |
| 1718 | |
| 1719 | // Checksum the whole database file (CRC64-ISO). |
| 1720 | let bytes = self.host.read(&self.path)?; |
| 1721 | let mut h = Crc64::new(); |
| 1722 | h.update(&bytes); |
| 1723 | Ok((h.sum64(), pos)) |
| 1724 | } |
| 1725 | |
| 1726 | // ── Snapshot ─────────────────────────────────────────────────────────── |
| 1727 | |
| 1728 | /// Writes a full database snapshot as an LTX file to `w` and returns the |
| 1729 | /// snapshot position. Ported from `DB.SnapshotReader` (db.go:1922-2021), |
| 1730 | /// buffered rather than streamed, as described in `client/mod.rs`. |
| 1731 | /// |
| 1732 | /// The snapshot spans `MinTXID=1 .. MaxTXID=pos.TXID` (db.go:1996-1997). Its |
| 1733 | /// page set is the full DB (lock page skipped), and — being a snapshot — the |
| 1734 | /// rolling post-apply checksum **is** tracked. |
| 1735 | pub fn snapshot_to_writer<W: std::io::Write>(&mut self, w: &mut W) -> Result<Pos> { |
| 1736 | if self.page_size == 0 { |
| 1737 | return Err(Error::Other( |
| 1738 | "db not ready: page size not initialized".into(), |
| 1739 | )); |
| 1740 | } |
| 1741 | |
| 1742 | let pos = self.pos()?; |
| 1743 | |
| 1744 | let db_size = self.db_file_size()?; |
| 1745 | let mut commit = (db_size / self.page_size as i64) as u32; |
| 1746 | |
| 1747 | let wal = WalImage::whole(self.host.read(&self.wal_path())?); |
| 1748 | let mut rd = WalReader::new(&wal.bytes).map_err(Error::from)?; |
| 1749 | let (page_map, max_offset, wal_commit) = rd.page_map().map_err(Error::from)?; |
| 1750 | if wal_commit > 0 { |
| 1751 | commit = wal_commit; |
| 1752 | } |
| 1753 | let wal_offset = rd.offset(); |
| 1754 | let sz = if max_offset > 0 { |
| 1755 | max_offset - wal_offset |
| 1756 | } else { |
| 1757 | 0 |
| 1758 | }; |
| 1759 | let (salt1, salt2) = rd.salt(); |
| 1760 | |
| 1761 | let pages = self.collect_snapshot_pages(&wal, &page_map, commit)?; |
| 1762 | |
| 1763 | // A snapshot tracks the rolling post-apply checksum (MinTXID==1, no |
| 1764 | // NoChecksum flag) — compute it the way decode_file verifies it. |
| 1765 | let lock = lock_pgno(self.page_size); |
| 1766 | let mut rolling: crate::Checksum = crate::CHECKSUM_FLAG; |
| 1767 | for (p, d) in &pages { |
| 1768 | if *p != lock { |
| 1769 | rolling = crate::CHECKSUM_FLAG | (rolling ^ ltx::checksum_page(*p, d)); |
| 1770 | } |
| 1771 | } |
| 1772 | |
| 1773 | let header = ltx::Header { |
| 1774 | version: ltx::VERSION, |
| 1775 | flags: 0, |
| 1776 | page_size: self.page_size, |
| 1777 | commit, |
| 1778 | min_txid: TXID(1), |
| 1779 | max_txid: pos.txid, |
| 1780 | timestamp: self.host.now_unix_millis(), |
| 1781 | pre_apply_checksum: 0, |
| 1782 | wal_offset, |
| 1783 | wal_size: sz, |
| 1784 | wal_salt1: salt1, |
| 1785 | wal_salt2: salt2, |
| 1786 | node_id: 0, |
| 1787 | }; |
| 1788 | |
| 1789 | let encoded = ltx::encode_file(&header, &pages, rolling)?; |
| 1790 | w.write_all(&encoded)?; |
| 1791 | |
| 1792 | Ok(Pos::new(pos.txid, rolling)) |
| 1793 | } |
| 1794 | |
| 1795 | /// Closes the database, releasing the read lock first so other processes can |
| 1796 | /// checkpoint. Ported from the read-lock-release + connection-close portion of |
| 1797 | /// `DB.Close` (db.go:623-647). |
| 1798 | pub fn close(mut self) -> Result<()> { |
| 1799 | self.release_read_lock()?; |
| 1800 | // The connection is dropped here, closing it. |
| 1801 | Ok(()) |
| 1802 | } |
| 1803 | } |
| 1804 | |
| 1805 | // ── free functions ───────────────────────────────────────────────────────── |
| 1806 | |
| 1807 | /// Returns the size of the WAL for a given page size & count, in i64 math to |
| 1808 | /// avoid u32 overflow with large page sizes. Ported from `calcWALSize` |
| 1809 | /// (db.go:1193-1197). |
| 1810 | fn calc_wal_size(page_size: u32, page_n: u32) -> i64 { |
| 1811 | WAL_HEADER_SIZE as i64 + (WAL_FRAME_HEADER_SIZE as i64 + page_size as i64) * page_n as i64 |
| 1812 | } |
| 1813 | |
| 1814 | /// `true` if the error indicates an SQLITE_BUSY condition. Ported from |
| 1815 | /// `isSQLiteBusyError` (db.go:1158-1167). Matches both the rusqlite busy code and |
| 1816 | /// the Go substrings. |
| 1817 | fn is_sqlite_busy_error(err: &Error) -> bool { |
| 1818 | // Prefer matching the rusqlite error code when present. |
| 1819 | if let Error::Other(b) = err { |
| 1820 | if let Some(re) = b.downcast_ref::<rusqlite::Error>() { |
| 1821 | if let Some(code) = re.sqlite_error_code() { |
| 1822 | if code == rusqlite::ErrorCode::DatabaseBusy |
| 1823 | || code == rusqlite::ErrorCode::DatabaseLocked |
| 1824 | { |
| 1825 | return true; |
| 1826 | } |
| 1827 | } |
| 1828 | } |
| 1829 | } |
| 1830 | let s = err.to_string(); |
| 1831 | s.contains("database is locked") || s.contains("SQLITE_BUSY") |
| 1832 | } |
| 1833 | |
| 1834 | /// `true` if the error indicates disk space issues (ENOSPC/EDQUOT). Ported from |
| 1835 | /// `isDiskFullError` (db.go:1169-1180) — case-insensitive substring |
| 1836 | /// match for parity with the Go table. This classifier matches the background |
| 1837 | /// monitor's disk-full temporary-file cleanup behavior (db.go:2304-2309). |
| 1838 | #[cfg_attr(not(test), allow(dead_code))] |
| 1839 | fn is_disk_full_error(err_msg: &str) -> bool { |
| 1840 | let s = err_msg.to_lowercase(); |
| 1841 | s.contains("no space left on device") |
| 1842 | || s.contains("disk quota exceeded") |
| 1843 | || s.contains("enospc") |
| 1844 | || s.contains("edquot") |
| 1845 | } |
| 1846 | |
| 1847 | /// Rolls back the connection's current transaction, swallowing the |
| 1848 | /// "already rolled back" / "no transaction is active" errors (issue #934). |
| 1849 | /// Ported from `rollback` (litestream.go:130-135), adapted to rusqlite's message. |
| 1850 | fn rollback(conn: &Connection) -> Result<()> { |
| 1851 | match conn |
| 1852 | .prepare_cached("ROLLBACK") |
| 1853 | .and_then(|mut statement| statement.execute([]).map(|_| ())) |
| 1854 | { |
| 1855 | Ok(()) => Ok(()), |
| 1856 | Err(e) => { |
| 1857 | let msg = e.to_string(); |
| 1858 | // Go swallows "transaction has already been committed or rolled back". |
| 1859 | // rusqlite/SQLite reports "cannot rollback - no transaction is active". |
| 1860 | if msg.contains("transaction has already been committed or rolled back") |
| 1861 | || msg.contains("no transaction is active") |
| 1862 | || msg.contains("cannot rollback") |
| 1863 | { |
| 1864 | Ok(()) |
| 1865 | } else { |
| 1866 | Err(sql_err(e)) |
| 1867 | } |
| 1868 | } |
| 1869 | } |
| 1870 | } |
| 1871 | |
| 1872 | /// Reads the 32-byte WAL header. Ported from `readWALHeader` |
| 1873 | /// (litestream.go:138-148): returns the header bytes; errors if the file is |
| 1874 | /// missing or shorter than 32 bytes. |
| 1875 | fn read_wal_header(host: &crate::LtxHost, path: &Path) -> Result<[u8; WAL_HEADER_SIZE]> { |
| 1876 | let mut file = host.open(path)?; |
| 1877 | let bytes = file.read_exact_at(0, WAL_HEADER_SIZE)?; |
| 1878 | Ok(bytes |
| 1879 | .try_into() |
| 1880 | .expect("the exact read has the header size")) |
| 1881 | } |
| 1882 | |
| 1883 | /// Reads one page's worth of bytes from an in-memory WAL buffer at the frame |
| 1884 | /// `offset` (the offset is the start of the *frame header*; the page data follows |
| 1885 | /// the 24-byte frame header). Mirrors `walFile.ReadAt(data, offset+WALFrameHeaderSize)` |
| 1886 | /// (db.go:1745,1787). |
| 1887 | /// What one sync read of the WAL: the whole file (`tail_base` 0), or the |
| 1888 | /// 32-byte header followed by the file's bytes from `tail_base` onward. |
| 1889 | /// Offsets stay absolute at every consumer; the image maps them. |
| 1890 | struct WalImage { |
| 1891 | bytes: Vec<u8>, |
| 1892 | tail_base: usize, |
| 1893 | file_len: usize, |
| 1894 | } |
| 1895 | |
| 1896 | impl WalImage { |
| 1897 | fn whole(bytes: Vec<u8>) -> Self { |
| 1898 | let file_len = bytes.len(); |
| 1899 | Self { |
| 1900 | bytes, |
| 1901 | tail_base: 0, |
| 1902 | file_len, |
| 1903 | } |
| 1904 | } |
| 1905 | |
| 1906 | /// A reader positioned at `offset`, over whichever shape this image has. |
| 1907 | fn reader_at( |
| 1908 | &self, |
| 1909 | offset: i64, |
| 1910 | salt1: u32, |
| 1911 | salt2: u32, |
| 1912 | ) -> std::result::Result<WalReader<'_>, crate::wal::WalError> { |
| 1913 | if self.tail_base == 0 { |
| 1914 | WalReader::new_with_offset(&self.bytes, offset, salt1, salt2) |
| 1915 | } else { |
| 1916 | WalReader::new_with_offset_over_tail( |
| 1917 | &self.bytes, |
| 1918 | self.tail_base as i64, |
| 1919 | offset, |
| 1920 | salt1, |
| 1921 | salt2, |
| 1922 | ) |
| 1923 | } |
| 1924 | } |
| 1925 | |
| 1926 | /// `n` bytes at absolute file `offset`, or `None` when the image does not |
| 1927 | /// hold them (a short read, or the gap between the header and the tail). |
| 1928 | fn slice(&self, offset: i64, n: usize) -> Option<&[u8]> { |
| 1929 | if offset < 0 { |
| 1930 | return None; |
| 1931 | } |
| 1932 | let offset = offset as usize; |
| 1933 | let start = if self.tail_base == 0 || offset < WAL_HEADER_SIZE { |
| 1934 | offset |
| 1935 | } else { |
| 1936 | WAL_HEADER_SIZE + offset.checked_sub(self.tail_base)? |
| 1937 | }; |
| 1938 | let end = start.checked_add(n)?; |
| 1939 | (end <= self.bytes.len()).then(|| &self.bytes[start..end]) |
| 1940 | } |
| 1941 | |
| 1942 | /// One page's worth of bytes at frame `offset` (the offset is the start of |
| 1943 | /// the *frame header*; the page data follows it). |
| 1944 | fn page(&self, offset: i64, page_size: u32) -> Result<Vec<u8>> { |
| 1945 | self.slice(offset + WAL_FRAME_HEADER_SIZE as i64, page_size as usize) |
| 1946 | .map(<[u8]>::to_vec) |
| 1947 | .ok_or_else(|| { |
| 1948 | Error::Io(std::io::Error::new( |
| 1949 | std::io::ErrorKind::UnexpectedEof, |
| 1950 | format!("short read wal page @ {offset}"), |
| 1951 | )) |
| 1952 | }) |
| 1953 | } |
| 1954 | } |
| 1955 | |
| 1956 | /// Writes `data` to `tmp_path`, fsyncs, then renames to `final_path` — the |
| 1957 | /// crash-consistent atomic-write idiom. On any failure the temp |
| 1958 | /// file is removed. |
| 1959 | fn write_file_atomic( |
| 1960 | host: &crate::LtxHost, |
| 1961 | tmp_path: &str, |
| 1962 | final_path: &str, |
| 1963 | data: &[u8], |
| 1964 | ) -> Result<u64> { |
| 1965 | let result = (|| -> Result<u64> { |
| 1966 | let mut file = host.create(Path::new(tmp_path))?; |
| 1967 | file.write_all(data)?; |
| 1968 | let fsync = crate::host::telemetry_us(); |
| 1969 | file.sync_all()?; |
| 1970 | let fsync_us = crate::host::telemetry_us().saturating_sub(fsync); |
| 1971 | drop(file); |
| 1972 | host.rename(Path::new(tmp_path), Path::new(final_path))?; |
| 1973 | Ok(fsync_us) |
| 1974 | })(); |
| 1975 | if result.is_err() { |
| 1976 | let _ = host.remove_file(Path::new(tmp_path)); |
| 1977 | } |
| 1978 | result |
| 1979 | } |
| 1980 | |
| 1981 | /// Recursively removes `.tmp` files under `root`. Ported from `removeTmpFiles` |
| 1982 | /// (litestream.go:169-182): missing root / errored entries are skipped. |
| 1983 | fn remove_tmp_files(host: &crate::LtxHost, root: &Path) -> Result<()> { |
| 1984 | fn walk(host: &crate::LtxHost, dir: &Path) { |
| 1985 | let entries = match host.read_dir(dir) { |
| 1986 | Ok(e) => e, |
| 1987 | Err(_) => return, |
| 1988 | }; |
| 1989 | for ent in entries { |
| 1990 | let path = ent.path; |
| 1991 | if ent.is_dir { |
| 1992 | walk(host, &path); |
| 1993 | } else if path.extension().and_then(|e| e.to_str()) == Some("tmp") { |
| 1994 | let _ = host.remove_file(&path); |
| 1995 | } |
| 1996 | } |
| 1997 | } |
| 1998 | walk(host, root); |
| 1999 | Ok(()) |
| 2000 | } |
| 2001 | |
| 2002 | fn system_time_from_unix_millis(milliseconds: i64) -> SystemTime { |
| 2003 | if milliseconds >= 0 { |
| 2004 | UNIX_EPOCH + Duration::from_millis(milliseconds as u64) |
| 2005 | } else { |
| 2006 | UNIX_EPOCH - Duration::from_millis(milliseconds.unsigned_abs()) |
| 2007 | } |
| 2008 | } |
| 2009 | |
| 2010 | /// Big-endian `u32` from the first four bytes of `b`. |
| 2011 | #[inline] |
| 2012 | fn be_u32(b: &[u8]) -> u32 { |
| 2013 | u32::from_be_bytes([b[0], b[1], b[2], b[3]]) |
| 2014 | } |
| 2015 | |
| 2016 | #[doc(hidden)] |
| 2017 | pub mod internal { |
| 2018 | /// Counts SQL compilations on the capture's connections: SQLite runs the |
| 2019 | /// authorizer once per compilation, so the counter moves for a fresh |
| 2020 | /// `prepare` and for a re-prepare, and stays still for a cached statement. |
| 2021 | /// (Installing the authorizer expires the statements compiled so far, so |
| 2022 | /// the first sync after this call compiles once more.) |
| 2023 | pub fn count_sql_compilations(db: &super::Db) -> std::sync::Arc<std::sync::atomic::AtomicU64> { |
| 2024 | use rusqlite::hooks::{AuthContext, Authorization}; |
| 2025 | let counter = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); |
| 2026 | for conn in [&db.conn, &db.rtx_conn] { |
| 2027 | let counter = counter.clone(); |
| 2028 | conn.authorizer(Some(move |_: AuthContext<'_>| { |
| 2029 | counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2030 | Authorization::Allow |
| 2031 | })); |
| 2032 | } |
| 2033 | counter |
| 2034 | } |
| 2035 | |
| 2036 | use super::*; |
| 2037 | |
| 2038 | pub struct VerifyInfo { |
| 2039 | inner: SyncInfo, |
| 2040 | pub offset: i64, |
| 2041 | pub prev_commit: u32, |
| 2042 | pub snapshotting: bool, |
| 2043 | pub reason: String, |
| 2044 | } |
| 2045 | |
| 2046 | pub fn calc_wal_size(page_size: u32, page_n: u32) -> i64 { |
| 2047 | super::calc_wal_size(page_size, page_n) |
| 2048 | } |
| 2049 | |
| 2050 | pub fn is_sqlite_busy_error(error: &Error) -> bool { |
| 2051 | super::is_sqlite_busy_error(error) |
| 2052 | } |
| 2053 | |
| 2054 | pub fn is_disk_full_error(message: &str) -> bool { |
| 2055 | super::is_disk_full_error(message) |
| 2056 | } |
| 2057 | |
| 2058 | pub fn read_lock_held(db: &Db) -> bool { |
| 2059 | db.read_lock_held |
| 2060 | } |
| 2061 | |
| 2062 | /// Run one `sync` with `hook` invoked between `verify` and the capture |
| 2063 | /// read — the only window in which a WAL change can reach the |
| 2064 | /// previous-frame check without `verify` seeing it first. |
| 2065 | pub fn sync_with_verify_hook(db: &mut Db, hook: impl FnOnce() + 'static) -> Result<()> { |
| 2066 | db.sync_with_verify_hook(Some(Box::new(hook))) |
| 2067 | } |
| 2068 | |
| 2069 | pub fn wal_journal_mode(db: &Db) -> Result<String> { |
| 2070 | db.conn |
| 2071 | .query_row("PRAGMA journal_mode", [], |row| row.get(0)) |
| 2072 | .map_err(sql_err) |
| 2073 | } |
| 2074 | |
| 2075 | pub fn wal_autocheckpoint(db: &Db) -> Result<i64> { |
| 2076 | db.conn |
| 2077 | .query_row("PRAGMA wal_autocheckpoint", [], |row| row.get(0)) |
| 2078 | .map_err(sql_err) |
| 2079 | } |
| 2080 | |
| 2081 | pub fn rollback_read_lock_connection(db: &Db) -> Result<()> { |
| 2082 | db.rtx_conn.execute_batch("ROLLBACK").map_err(sql_err) |
| 2083 | } |
| 2084 | |
| 2085 | pub fn release_read_lock(db: &mut Db) -> Result<()> { |
| 2086 | db.release_read_lock() |
| 2087 | } |
| 2088 | |
| 2089 | pub fn acquire_read_lock(db: &mut Db) -> Result<()> { |
| 2090 | db.acquire_read_lock() |
| 2091 | } |
| 2092 | |
| 2093 | pub fn verify(db: &mut Db) -> Result<VerifyInfo> { |
| 2094 | let inner = db.verify()?; |
| 2095 | Ok(VerifyInfo { |
| 2096 | offset: inner.offset, |
| 2097 | prev_commit: inner.prev_commit, |
| 2098 | snapshotting: inner.snapshotting, |
| 2099 | reason: inner.reason.clone(), |
| 2100 | inner, |
| 2101 | }) |
| 2102 | } |
| 2103 | |
| 2104 | pub fn sync_inner(db: &mut Db, info: VerifyInfo) -> Result<bool> { |
| 2105 | db.sync_inner(info.inner) |
| 2106 | } |
| 2107 | |
| 2108 | pub fn read_wal_header(db: &Db) -> Result<[u8; WAL_HEADER_SIZE]> { |
| 2109 | super::read_wal_header(&db.host, &db.wal_path()) |
| 2110 | } |
| 2111 | |
| 2112 | pub fn invalidate_pos_cache(db: &mut Db) { |
| 2113 | db.invalidate_pos_cache(); |
| 2114 | } |
| 2115 | |
| 2116 | pub fn ltx_level_dir(db: &Db, level: u32) -> String { |
| 2117 | db.ltx_level_dir(level) |
| 2118 | } |
| 2119 | |
| 2120 | pub fn checkpoint_passive_with_barrier_hook( |
| 2121 | db: &mut Db, |
| 2122 | hook: Box<dyn FnOnce() + Send>, |
| 2123 | ) -> Result<()> { |
| 2124 | db.checkpoint_with_passive_hooks(CheckpointMode::Passive, Some(hook), None) |
| 2125 | } |
| 2126 | |
| 2127 | pub fn checkpoint_passive_with_unlocked_hook( |
| 2128 | db: &mut Db, |
| 2129 | hook: Box<dyn FnOnce() + Send>, |
| 2130 | ) -> Result<()> { |
| 2131 | db.checkpoint_with_passive_hooks(CheckpointMode::Passive, None, Some(hook)) |
| 2132 | } |
| 2133 | |
| 2134 | pub fn be_u32(bytes: &[u8]) -> u32 { |
| 2135 | super::be_u32(bytes) |
| 2136 | } |
| 2137 | } |