Skip to main content

khive_db/
progress_conn.rs

1//! A SQLite connection whose progress handler is installed once, when it is built.
2//!
3//! rusqlite 0.41 takes `&mut Connection` to install any hook, while read scopes run on shared
4//! borrows handed out by the pool. So the handler is installed here, with the owned connection,
5//! and never per read: it asks the per-thread read registration whether a statement on THIS
6//! connection should stop (`read_cancellation::progress_stop`). A read scope accepts only a
7//! `ProgressConn`, so a connection without the handler cannot reach one.
8
9use std::ops::Deref;
10use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
11
12use rusqlite::Connection;
13
14/// SQLite VM steps between progress callbacks.
15const PROGRESS_STEPS: std::os::raw::c_int = 1_000;
16
17static NEXT_ID: AtomicU64 = AtomicU64::new(1);
18
19/// A connection carrying the read-cancellation progress handler and a process-unique identity.
20///
21/// It dereferences to [`Connection`] for statements but gives no `&mut Connection` outside
22/// [`ProgressConn::with_mut`], which re-installs the handler afterwards, so nothing can replace
23/// or remove it:
24/// ```compile_fail
25/// use khive_db::ProgressConn;
26/// let mut conn = ProgressConn::new(rusqlite::Connection::open_in_memory().unwrap()).unwrap();
27/// conn.progress_handler(0, None::<fn() -> bool>).unwrap();
28/// ```
29#[derive(Debug)]
30pub struct ProgressConn {
31    conn: Connection,
32    id: u64,
33    unarmed: AtomicBool,
34}
35
36impl ProgressConn {
37    /// Takes the connection and installs the handler.
38    pub fn new(mut conn: Connection) -> rusqlite::Result<Self> {
39        let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
40        #[cfg(any(test, feature = "test-support"))]
41        crate::test_hooks::adopt(&mut conn)?;
42        arm(&mut conn, id)?;
43        Ok(ProgressConn {
44            conn,
45            id,
46            unarmed: AtomicBool::new(false),
47        })
48    }
49
50    /// The identity a read registration names.
51    pub(crate) fn id(&self) -> u64 {
52        self.id
53    }
54
55    /// Whether the handler is known to be installed. A failed re-install leaves the connection
56    /// unarmed, and a read scope then refuses it.
57    pub(crate) fn armed(&self) -> bool {
58        !self.unarmed.load(Ordering::Acquire)
59    }
60
61    /// Runs `f` with the owned connection, then installs the handler again whatever `f` did. If
62    /// that install fails the connection stays usable for writes but no read scope accepts it.
63    pub fn with_mut<R>(&mut self, f: impl FnOnce(&mut Connection) -> R) -> R {
64        let result = f(&mut self.conn);
65        if let Err(error) = arm(&mut self.conn, self.id) {
66            self.unarmed.store(true, Ordering::Release);
67            tracing::error!(target: "khive_db::pool", %error, "failed to re-install the read progress handler");
68        }
69        result
70    }
71
72    /// Counts progress at `period` VM steps through `hook` until [`Self::test_progress_reset`];
73    /// the read-cancellation verdict still applies.
74    #[cfg(test)]
75    pub(crate) fn test_progress_every(
76        &mut self,
77        period: std::os::raw::c_int,
78        mut hook: impl FnMut() -> bool + Send + 'static,
79    ) {
80        let id = self.id;
81        self.conn
82            .progress_handler(
83                period,
84                Some(move || hook() || crate::read_cancellation::progress_stop(id)),
85            )
86            .expect("install the test progress handler");
87    }
88
89    #[cfg(test)]
90    pub(crate) fn test_progress_reset(&mut self) {
91        arm(&mut self.conn, self.id).expect("re-install the progress handler");
92    }
93
94    /// The connection, for closing it. The handler stays installed and its identity is never
95    /// registered again, so it never stops a statement.
96    pub(crate) fn into_inner(self) -> Connection {
97        #[cfg(any(test, feature = "test-support"))]
98        crate::test_hooks::unregister(&self.conn);
99        self.conn
100    }
101}
102
103impl Deref for ProgressConn {
104    type Target = Connection;
105
106    fn deref(&self) -> &Connection {
107        &self.conn
108    }
109}
110
111fn arm(conn: &mut Connection, id: u64) -> rusqlite::Result<()> {
112    #[cfg(any(test, feature = "test-support"))]
113    let test_slots = crate::test_hooks::slots_of(conn);
114    conn.progress_handler(
115        PROGRESS_STEPS,
116        Some(move || {
117            #[cfg(any(test, feature = "test-support"))]
118            if test_slots
119                .as_deref()
120                .is_some_and(crate::test_hooks::progress)
121            {
122                return true;
123            }
124            crate::read_cancellation::progress_stop(id)
125        }),
126    )
127}