Skip to main content

coven_database/
database_operations_tests.rs

1//! Test transport support using the actual local-write queue.
2
3use super::StoreDatabase;
4use crate::{test_utils::StatementLog, DbError};
5
6impl StoreDatabase {
7    /// Record the statements every read context of this database runs into
8    /// `log` (`query` and `query_row`, in reads and live queries' runs), as
9    /// SQLite reads them with their bound values written in. Writes and
10    /// migrations are not recorded. Install while the database is quiescent.
11    pub async fn record_statements(&self, log: StatementLog) -> Result<(), DbError> {
12        self.call(move |inner| {
13            inner.access.with_writer(|writer, _| {
14                writer.test_record_statements(log.clone());
15                Ok::<_, DbError>(())
16            })?;
17            inner.access.database.each_reader(|reader| reader.test_record_statements(log.clone()));
18            Ok::<_, DbError>(())
19        })
20        .await
21    }
22
23    /// Count executed work on every connection without including counter reads.
24    /// Install while the database is quiescent, before starting the measured pass.
25    pub async fn test_track_work(
26        &self,
27        counter: crate::test_utils::WorkCounter,
28    ) -> Result<(), DbError> {
29        self.call(move |inner| {
30            inner.access.with_writer(|writer, _| {
31                counter.track(writer);
32                Ok::<_, DbError>(())
33            })?;
34            inner.access.database.each_reader(|reader| counter.track(reader));
35            inner.access.tests.track_work(counter.clone());
36            inner.inputs.test_track_work(&counter);
37            Ok(())
38        })
39        .await
40    }
41
42    /// The plaintext bytes each section of a snapshot `id` would hold now:
43    /// what the sealed object's size can't tell apart.
44    pub async fn test_snapshot_section_bytes(
45        &self,
46        id: coven_format::admin::SnapshotId,
47    ) -> Result<
48        [u64; coven_format::snapshot::SECTIONS],
49        crate::SnapshotWriteError<std::convert::Infallible>,
50    > {
51        let sections =
52            std::sync::Arc::new(std::sync::Mutex::new([0; coven_format::snapshot::SECTIONS]));
53        let counted = sections.clone();
54        self.write_snapshot(
55            id,
56            |_| Ok(()),
57            move |frame| {
58                if let Some(section) = coven_format::snapshot::frame_section(&frame) {
59                    counted.lock().expect("no test panics counting")[section] += frame.len() as u64;
60                }
61                Ok(())
62            },
63        )
64        .await?;
65        let bytes = *sections.lock().expect("no test panics counting");
66        Ok(bytes)
67    }
68
69    /// Observe transaction completion and file cleanup on the writer thread.
70    /// Install after setup; the callback may terminate a subprocess to simulate
71    /// a crash without Rust destructors or SQLite connection shutdown.
72    pub async fn test_on_write_checkpoint(
73        &self,
74        callback: impl Fn(crate::test_utils::WriteCheckpoint) + Send + 'static,
75    ) -> Result<(), DbError> {
76        self.call(move |inner| {
77            inner.access.with_writer(|writer, call| {
78                call.on_write_checkpoint(writer, callback);
79                Ok(())
80            })
81        })
82        .await
83    }
84
85    /// Panic in the next write the writer judges, before it commits, as a
86    /// bug in it would: the write rolls back, and its call fails with
87    /// `DbError::Bug` carrying `message` (E15).
88    pub async fn test_panic_in_next_write(&self, message: &'static str) -> Result<(), DbError> {
89        let armed = std::sync::atomic::AtomicBool::new(true);
90        self.test_on_write_checkpoint(move |point| {
91            if point == crate::test_utils::WriteCheckpoint::Judged
92                && armed.swap(false, std::sync::atomic::Ordering::SeqCst)
93            {
94                panic!("{message}");
95            }
96        })
97        .await
98    }
99
100    /// Make every later write of how the passes go fail, as a full disk
101    /// would: their move, their end and the last synced time. Counting a
102    /// start still writes, so the loop starts and its first pass fails.
103    pub async fn test_fail_sync_status(&self) -> Result<(), DbError> {
104        self.call(move |inner| {
105            inner.access.with_writer(|writer, _| {
106                Ok(writer.batch(
107                    "CREATE TEMP TRIGGER fail_sync_status
108                     BEFORE UPDATE OF last_pass,moved,last_synced ON coven_sync_status
109                     BEGIN SELECT RAISE(ABORT,'injected sync status failure'); END;",
110                )?)
111            })
112        })
113        .await
114    }
115
116    /// Make every later write of the reset notice fail, as a full disk would.
117    pub async fn test_fail_device_reset(&self) -> Result<(), DbError> {
118        self.call(move |inner| {
119            inner.access.with_writer(|writer, _| {
120                Ok(writer.batch(
121                    "CREATE TEMP TRIGGER fail_device_reset BEFORE INSERT ON _coven_device_reset
122                     BEGIN SELECT RAISE(ABORT,'injected reset notice failure'); END;",
123                )?)
124            })
125        })
126        .await
127    }
128
129    /// Make every write of the device-id-in-use record fail, as a full disk
130    /// would, or let them succeed again.
131    pub async fn test_fail_device_id_in_use(&self, fail: bool) -> Result<(), DbError> {
132        self.call(move |inner| {
133            inner.access.with_writer(|writer, _| {
134                Ok(writer.batch(if fail {
135                    "CREATE TEMP TRIGGER fail_device_id_in_use BEFORE INSERT ON _coven_device_id_in_use
136                     BEGIN SELECT RAISE(ABORT,'injected device id record failure'); END;"
137                } else {
138                    "DROP TRIGGER IF EXISTS fail_device_id_in_use;"
139                })?)
140            })
141        })
142        .await
143    }
144
145    /// Make every later write of the retry effect fail, as a full disk would.
146    pub async fn test_fail_retry_effect(&self) -> Result<(), DbError> {
147        self.call(move |inner| {
148            inner.access.with_writer(|writer, _| {
149                Ok(writer.batch(
150                    "CREATE TEMP TRIGGER fail_retry_effect BEFORE UPDATE ON coven_retry_effect
151                     BEGIN SELECT RAISE(ABORT,'injected retry effect failure'); END;",
152                )?)
153            })
154        })
155        .await
156    }
157
158    /// Test transport: read actual queued records without reauthoring their writes.
159    pub async fn test_queued_writes(
160        &self,
161    ) -> Result<Vec<coven_format::write::WriteRecord>, DbError> {
162        self.call(move |inner| {
163            inner.access.with_writer(|writer, _| {
164                writer
165                    .query("SELECT record FROM _coven_uploads ORDER BY device,number", [], |r| {
166                        r.get::<_, Vec<u8>>(0)
167                    })?
168                    .iter()
169                    .map(|bytes| {
170                        coven_format::write_stream::decode_plaintext(bytes).map_err(Into::into)
171                    })
172                    .collect()
173            })
174        })
175        .await
176    }
177}
178
179/// Fill this domain's tables from the rows of the plan audit's `fixture`
180/// table, inside its transaction (`internal_schema_scan_reasons_tests.rs`).
181#[cfg(test)]
182pub(crate) fn fill_for_plans(db: &sqlive::rusqlite::Connection) {
183    db.execute_batch(
184        "INSERT INTO _coven_gone_storage_cleared SELECT n FROM fixture;
185         INSERT INTO _coven_requests_ended SELECT n FROM fixture;",
186    )
187    .unwrap();
188}