1use crate::{Migration, RowIdentity, SyncedTable};
4
5#[path = "readable_objects.rs"]
6mod readable_objects;
7pub use crate::internal_schema::sync_status::{
8 save_last_pass_outside_store, save_location_outside_store,
9};
10pub use crate::operation::{finish_outside_store, journal_outside_store, OutcomeListing};
11pub use crate::pending::save_outside_store;
12pub use readable_objects::{make_readable_objects, record_user_file};
13pub use sqlive::rusqlite::Connection;
16
17#[path = "work_counts.rs"]
18mod work_counts;
19pub(crate) use work_counts::StoreWork;
20pub use work_counts::{WorkCounter, WorkCounts};
21
22pub use sqlive::{report_cost, report_time, StatementLog};
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum WriteCheckpoint {
27 Judged,
29 Committed,
31 Observed,
33 StagingReleased,
35 FileRemoved,
38 FileRemovalRecorded,
40 Finished,
42}
43
44impl From<sqlive::CommitPoint> for WriteCheckpoint {
45 fn from(point: sqlive::CommitPoint) -> Self {
46 match point {
47 sqlive::CommitPoint::Judged => Self::Judged,
48 sqlive::CommitPoint::Committed => Self::Committed,
49 sqlive::CommitPoint::Observed => Self::Observed,
50 }
51 }
52}
53
54pub struct Followed<T, E> {
57 query: Option<crate::LiveQuery<T, E>>,
61 latest: Option<T>,
62}
63
64impl<T, E> Followed<T, E>
65where
66 T: Clone + PartialEq + std::fmt::Debug + Send + 'static,
67 E: From<crate::DbError> + coven_foundation::task::CarriesBug + std::fmt::Debug + Send + 'static,
68{
69 pub fn new(query: crate::LiveQuery<T, E>) -> Self {
71 Self { query: Some(query), latest: None }
72 }
73
74 pub async fn next(&mut self) -> T {
77 let query = self
78 .query
79 .take()
80 .expect("a test stopped waiting for this live query's result, so the query is gone");
81 let (query, next) = coven_foundation::clock::within(crate::next_result(query))
82 .await
83 .unwrap_or_else(|| panic!("no result after {:?}", self.latest));
84 self.query = Some(query);
85 let next = next.expect("the live query ended").expect("the live query failed");
86 self.latest = Some(next.clone());
87 next
88 }
89
90 pub async fn latest(&mut self) -> T {
92 match self.latest.clone() {
93 Some(latest) => latest,
94 None => self.next().await,
95 }
96 }
97
98 pub async fn wait_for(&mut self, mut matches: impl FnMut(&T) -> bool) -> T {
100 let mut result = self.latest().await;
101 while !matches(&result) {
102 result = self.next().await;
103 }
104 result
105 }
106}
107
108pub fn idle_writers() -> crate::Writers {
112 crate::Writers::new(std::collections::BTreeMap::from([(
113 coven_foundation::id_source::DeviceId(u64::MAX),
114 None,
115 )]))
116}
117
118pub fn signer() -> coven_crypto::SigningKey {
120 coven_format::test_utils::keys_from_seed(0xA5).public_keys().signing
121}
122
123pub async fn stage_plaintext(
126 database: &crate::StoreDatabase,
127 id: coven_format::admin::SnapshotId,
128 prefix: coven_format::sealed_snapshot::SnapshotObjectPrefix,
129 mut input: impl std::io::Read,
130) -> Result<crate::SnapshotStaging, crate::DbError> {
131 let mut staging = database.stage_snapshot(id, prefix).await?;
132 loop {
133 let mut chunk = vec![0; coven_format::chunks::CHUNK_SIZE];
134 let length = match input.read(&mut chunk) {
135 Ok(0) => break,
136 Ok(length) => length,
137 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
138 Err(error) => return Err(crate::SnapshotError::Read(error).into()),
139 };
140 chunk.truncate(length);
141 staging.stage(chunk).await?;
142 }
143 staging.finish().await?;
144 Ok(staging)
145}
146
147pub fn notes_tables() -> Vec<SyncedTable> {
149 vec![SyncedTable::new("notes", RowIdentity::IndependentUuid)]
150}
151
152pub fn notes_migrations() -> Vec<Migration> {
154 vec![Migration::addition(1, "notes", "CREATE TABLE notes (id TEXT NOT NULL PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL DEFAULT '')")]
155}
156
157#[derive(Clone, Copy, Debug, Default)]
161pub struct TestAuthorship;
162
163impl TestAuthorship {
164 const STORE: coven_foundation::id_source::StoreId =
165 coven_foundation::id_source::StoreId(uuid::Uuid::from_bytes([0x10; 16]));
166
167 pub fn key() -> coven_crypto::StoreKey {
169 coven_crypto::StoreKey::from_bytes(
170 coven_foundation::id_source::KeyId(uuid::Uuid::from_bytes([1; 16])),
171 [17; 32],
172 )
173 }
174
175 fn path(write: coven_merge::WriteId) -> String {
176 coven_format::path::ObjectPath::slot(
177 Self::STORE,
178 std::num::NonZeroU64::new(write.number).expect("a positive write number"),
179 )
180 .into()
181 }
182
183 pub fn write(record: &coven_format::write::WriteRecord) -> crate::WriteAuthorship {
185 let encoder = coven_format::write_stream::WriteEncoder::new(record).unwrap();
186 Self::for_header(
187 encoder.header(),
188 record.parts.iter().map(coven_format::authorship::part_leaves).collect(),
189 )
190 }
191
192 pub(crate) fn for_header(
194 frame: &coven_format::write_stream::WriteHeaderFrame,
195 leaves: Vec<Vec<coven_format::authorship::Leaf>>,
196 ) -> crate::WriteAuthorship {
197 let key = Self::key();
198 let object = coven_format::sealed_write::WriteObjectPrefix {
199 format: coven_format::FormatVersion::CURRENT,
200 store_key: key.id(),
201 part_keys: vec![key.id(); frame.parts.len()],
202 };
203 let prefix = object.encode().unwrap();
204 let plain = frame.encode().unwrap();
205 let sealed = key
206 .derive()
207 .seal_object_chunk(&Self::path(frame.header.position), &prefix, 0, 0, &plain)
208 .unwrap();
209 let header = coven_format::sealed_write::WriteObjectLayout::new(
210 object,
211 &plain,
212 frame.parts.iter().map(|part| part.plaintext_length).collect(),
213 )
214 .unwrap()
215 .encode_chunk(&sealed)
216 .unwrap();
217 let hasher = key.derive().authorship_hasher();
218 crate::WriteAuthorship {
219 evidence: crate::HeaderEvidence {
220 prefix,
221 header,
222 roots: leaves
223 .iter()
224 .map(|leaves| coven_format::authorship::root(&hasher, leaves).unwrap())
225 .collect(),
226 signature: [0; 64],
227 },
228 hashers: frame.parts.iter().map(|_| Some(hasher.clone())).collect(),
229 }
230 }
231}
232
233impl crate::Authorship for TestAuthorship {
234 #[expect(
235 clippy::map_err_ignore,
236 reason = "a test fixture whose header does not open is the fixture refusal this names"
237 )]
238 fn header(
239 &self,
240 evidence: &coven_format::authorship::WriteEvidence,
241 ) -> Result<coven_format::write_stream::WriteHeaderFrame, crate::DbError> {
242 let sealed = coven_format::sealed_write::WriteObjectPrefix::header_chunk(&evidence.header)?;
243 let plain = Self::key()
244 .derive()
245 .open_object_chunk(&Self::path(evidence.write), &evidence.prefix, 0, 0, sealed)
246 .map_err(|_| crate::snapshot_error::invalid("test evidence header does not open"))?;
247 Ok(coven_format::write_stream::WriteHeaderFrame::decode(&plain)?)
248 }
249
250 fn hasher(
251 &self,
252 _audience: &coven_merge::Audience,
253 _key: coven_foundation::id_source::KeyId,
254 ) -> Result<coven_crypto::AuthorshipHasher, crate::DbError> {
255 Ok(Self::key().derive().authorship_hasher())
256 }
257}
258
259#[cfg(test)]
260#[path = "test_utils_tests.rs"]
261pub(crate) mod tests;