khive_db/
progress_conn.rs1use std::ops::Deref;
10use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
11
12use rusqlite::Connection;
13
14const PROGRESS_STEPS: std::os::raw::c_int = 1_000;
16
17static NEXT_ID: AtomicU64 = AtomicU64::new(1);
18
19#[derive(Debug)]
30pub struct ProgressConn {
31 conn: Connection,
32 id: u64,
33 unarmed: AtomicBool,
34}
35
36impl ProgressConn {
37 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 pub(crate) fn id(&self) -> u64 {
52 self.id
53 }
54
55 pub(crate) fn armed(&self) -> bool {
58 !self.unarmed.load(Ordering::Acquire)
59 }
60
61 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 #[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 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}