Skip to main content

link_cli/engine/
sqlite.rs

1//! Optional SQLite page-WAL component at the ordered revision-log boundary.
2//! A dedicated connection belongs to this log. Drop rolls pending records back.
3//! SQLite writer locking does not coordinate independent cached engine states;
4//! stale-tail/component errors fence this owner until it is dropped and reopened.
5use crate::{LinkError, TransitionLogStore};
6use rusqlite::{params, Connection};
7use std::path::Path;
8use std::time::Duration;
9
10#[cfg(test)]
11#[path = "sqlite_tests.rs"]
12mod tests;
13
14const APPLICATION_ID: i64 = 0x4c4e4b4a;
15const SCHEMA: &str = "CREATE TABLE link_cli_log (sequence INTEGER PRIMARY KEY CHECK(sequence>0), record BLOB NOT NULL CHECK(typeof(record)='blob'))";
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct SqliteOptions {
19    /// Finite SQLite busy retry interval; zero fails immediately.
20    pub busy_timeout_ms: u32,
21    /// WAL pages before SQLite attempts an automatic checkpoint; zero is manual.
22    pub auto_checkpoint_pages: u32,
23}
24impl Default for SqliteOptions {
25    fn default() -> Self {
26        Self {
27            busy_timeout_ms: 0,
28            auto_checkpoint_pages: 1000,
29        }
30    }
31}
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum CheckpointMode {
34    Passive,
35    Full,
36    Restart,
37    Truncate,
38}
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct CheckpointResult {
41    pub busy: i64,
42    pub log_frames: i64,
43    pub checkpointed_frames: i64,
44}
45
46#[derive(Debug)]
47pub struct SqliteLog {
48    connection: Connection,
49    tail: i64,
50    pending: bool,
51    poisoned: bool,
52}
53fn error(message: impl std::fmt::Display) -> LinkError {
54    LinkError::StorageError(message.to_string())
55}
56
57impl SqliteLog {
58    /// Opens a dedicated database. Default builds have no SQLite dependency.
59    /// Requires a same-host filesystem/VFS implementing SQLite WAL locking and
60    /// truthful synchronization; all sidecars belong to the database.
61    pub fn open(path: impl AsRef<Path>, options: SqliteOptions) -> Result<Self, LinkError> {
62        if options.busy_timeout_ms > i32::MAX as u32
63            || options.auto_checkpoint_pages > i32::MAX as u32
64        {
65            return Err(error(
66                "SQLite options must fit nonnegative signed 32-bit integers",
67            ));
68        }
69        let mut log = Self {
70            connection: Connection::open(path).map_err(error)?,
71            tail: 0,
72            pending: false,
73            poisoned: false,
74        };
75        log.initialize(options)?;
76        Ok(log)
77    }
78    fn initialize(&mut self, options: SqliteOptions) -> Result<(), LinkError> {
79        if rusqlite::version_number() < 3_051_003 {
80            return Err(error("SQLite >= 3.51.3 is required"));
81        }
82        self.identity()?; // Do not change a foreign database's journal mode.
83        self.connection
84            .busy_timeout(Duration::from_millis(options.busy_timeout_ms.into()))
85            .map_err(error)?;
86        let mode: String = self
87            .connection
88            .query_row("PRAGMA journal_mode=WAL", [], |row| row.get(0))
89            .map_err(error)?;
90        if mode != "wal" {
91            return Err(error("SQLite journal requires file-backed WAL"));
92        }
93        self.connection
94            .execute_batch(&format!(
95                "PRAGMA synchronous=FULL; PRAGMA wal_autocheckpoint={}",
96                options.auto_checkpoint_pages
97            ))
98            .map_err(error)?;
99        self.settings()?;
100        if self.scalar("PRAGMA busy_timeout")? != i64::from(options.busy_timeout_ms)
101            || self.scalar("PRAGMA wal_autocheckpoint")? != i64::from(options.auto_checkpoint_pages)
102        {
103            return Err(error("SQLite options were not applied"));
104        }
105        self.connection
106            .execute_batch("BEGIN IMMEDIATE")
107            .map_err(error)?;
108        self.pending = true;
109        if self.identity()? {
110            self.connection
111                .execute_batch(&format!(
112                    "{SCHEMA}; PRAGMA application_id={APPLICATION_ID}; PRAGMA user_version=1"
113                ))
114                .map_err(error)?;
115        }
116        let (count, first, last): (i64, i64, i64) = self.connection.query_row(
117            "SELECT COUNT(*), COALESCE(MIN(sequence),0), COALESCE(MAX(sequence),0) FROM link_cli_log", [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
118        ).map_err(error)?;
119        if count < 0 || count != last || first != if count == 0 { 0 } else { 1 } {
120            return Err(error("journal sequences must be contiguous from one"));
121        }
122        self.tail = last;
123        self.connection.execute_batch("COMMIT").map_err(error)?;
124        self.pending = false;
125        Ok(())
126    }
127    fn scalar(&self, query: &str) -> Result<i64, LinkError> {
128        self.connection
129            .query_row(query, [], |row| row.get(0))
130            .map_err(error)
131    }
132    fn identity(&self) -> Result<bool, LinkError> {
133        let id = self.scalar("PRAGMA application_id")?;
134        let version = self.scalar("PRAGMA user_version")?;
135        let mut statement = self
136            .connection
137            .prepare("SELECT type, name, tbl_name, sql FROM sqlite_schema ORDER BY name")
138            .map_err(error)?;
139        let objects: Vec<(String, String, String, Option<String>)> = statement
140            .query_map([], |row| {
141                Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
142            })
143            .map_err(error)?
144            .collect::<Result<_, _>>()
145            .map_err(error)?;
146        if id == 0 && version == 0 && objects.is_empty() {
147            return Ok(true);
148        }
149        if id != APPLICATION_ID
150            || version != 1
151            || objects.len() != 1
152            || objects[0]
153                != (
154                    "table".into(),
155                    "link_cli_log".into(),
156                    "link_cli_log".into(),
157                    Some(SCHEMA.into()),
158                )
159        {
160            return Err(error("foreign or unsupported journal schema"));
161        }
162        Ok(false)
163    }
164    fn settings(&self) -> Result<(), LinkError> {
165        let mode: String = self
166            .connection
167            .query_row("PRAGMA journal_mode", [], |row| row.get(0))
168            .map_err(error)?;
169        if mode != "wal" || self.scalar("PRAGMA synchronous")? != 2 {
170            return Err(error("SQLite WAL/FULL settings changed"));
171        }
172        Ok(())
173    }
174    fn check(&self) -> Result<(), LinkError> {
175        if self.poisoned {
176            return Err(error("indeterminate journal outcome; drop and reopen"));
177        }
178        Ok(())
179    }
180    fn rollback(&mut self) {
181        if self.pending {
182            // A failed COMMIT can already have committed. Preserve the original
183            // error and release a still-active transaction without deleting rows.
184            let _ = self.connection.execute_batch("ROLLBACK");
185            self.pending = false;
186        }
187    }
188    fn io<T>(
189        &mut self,
190        operation: impl FnOnce(&mut Self) -> Result<T, LinkError>,
191    ) -> Result<T, LinkError> {
192        match operation(self) {
193            Ok(value) => Ok(value),
194            Err(failure) => {
195                self.poisoned = true;
196                self.rollback();
197                Err(failure)
198            }
199        }
200    }
201    fn flush_with(
202        &mut self,
203        commit: impl FnOnce(&Connection) -> Result<(), LinkError>,
204    ) -> Result<(), LinkError> {
205        self.check()?;
206        if !self.pending {
207            return Ok(());
208        }
209        self.io(|log| {
210            log.settings()?;
211            commit(&log.connection)?;
212            log.pending = false;
213            Ok(())
214        })
215    }
216    /// Explicit physical page maintenance. Logical journal records are retained.
217    /// Pending appends reject without poisoning. Reader contention is returned
218    /// in the counters, bounded by the configured SQLite busy interval.
219    pub fn checkpoint(&mut self, mode: CheckpointMode) -> Result<CheckpointResult, LinkError> {
220        self.check()?;
221        if self.pending {
222            return Err(error("cannot checkpoint pending appends"));
223        }
224        self.io(|log| {
225            log.settings()?;
226            let mode = match mode {
227                CheckpointMode::Passive => "PASSIVE",
228                CheckpointMode::Full => "FULL",
229                CheckpointMode::Restart => "RESTART",
230                CheckpointMode::Truncate => "TRUNCATE",
231            };
232            log.connection
233                .query_row(&format!("PRAGMA wal_checkpoint({mode})"), [], |row| {
234                    Ok(CheckpointResult {
235                        busy: row.get(0)?,
236                        log_frames: row.get(1)?,
237                        checkpointed_frames: row.get(2)?,
238                    })
239                })
240                .map_err(error)
241        })
242    }
243}
244impl TransitionLogStore for SqliteLog {
245    fn supports_durable_flush(&self) -> bool {
246        true
247    }
248    fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
249        self.check()?;
250        self.io(|log| {
251            let mut statement = log
252                .connection
253                .prepare("SELECT sequence, record FROM link_cli_log ORDER BY sequence")
254                .map_err(error)?;
255            let mut rows = statement.query([]).map_err(error)?;
256            let mut records = Vec::new();
257            let mut previous = 0i64;
258            while let Some(row) = rows.next().map_err(error)? {
259                let current: i64 = row.get(0).map_err(error)?;
260                if previous.checked_add(1) != Some(current) {
261                    return Err(error("journal sequences must be contiguous from one"));
262                }
263                let bytes: Vec<u8> = row.get(1).map_err(error)?;
264                let record = String::from_utf8(bytes).map_err(error)?;
265                if record.contains(['\r', '\n']) {
266                    return Err(error("journal record contains a physical line break"));
267                }
268                records.push(record);
269                previous = current;
270            }
271            if previous != log.tail {
272                return Err(error("stale journal owner: sequence tail changed"));
273            }
274            Ok(records)
275        })
276    }
277    fn append_log_entry(&mut self, record: &str) -> Result<(), LinkError> {
278        self.check()?;
279        if record.contains(['\r', '\n']) {
280            return Err(error("journal records must not contain line breaks"));
281        }
282        let next = self
283            .tail
284            .checked_add(1)
285            .ok_or_else(|| error("journal sequence exhausted"))?;
286        self.io(|log| {
287            if !log.pending {
288                log.connection
289                    .execute_batch("BEGIN IMMEDIATE")
290                    .map_err(error)?;
291                log.pending = true;
292                log.settings()?;
293                if log.scalar("SELECT COALESCE(MAX(sequence),0) FROM link_cli_log")? != log.tail {
294                    return Err(error("stale journal owner: sequence tail changed"));
295                }
296            }
297            log.connection
298                .execute(
299                    "INSERT INTO link_cli_log (sequence, record) VALUES (?1, ?2)",
300                    params![next, record.as_bytes()],
301                )
302                .map_err(error)?;
303            log.tail = next;
304            Ok(())
305        })
306    }
307    fn flush_log(&mut self) -> Result<(), LinkError> {
308        self.flush_with(|connection| connection.execute_batch("COMMIT").map_err(error))
309    }
310}
311impl Drop for SqliteLog {
312    fn drop(&mut self) {
313        self.rollback();
314    }
315}