1use crate::sqlite::StoreSql;
3use crate::write_encoding::{audience, counter, damaged};
4use crate::{DbError, StoreState, StoreVersion};
5use coven_format::{
6 admin::SnapshotId, snapshot_rows::ChangeVerdict, value::Slot, write::WriteHeader,
7};
8use coven_foundation::id_source::DeviceId;
9use coven_merge::Audience;
10use sqlive::rusqlite::params;
11use std::collections::BTreeSet;
12
13#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum Boundary {
17 SchemaChange(StoreVersion),
19 Reset {
21 entry: Slot,
23 snapshot: SnapshotId,
25 },
26}
27
28impl Boundary {
29 pub fn entry(&self) -> Slot {
31 match self {
32 Self::SchemaChange(version) => version.entry,
33 Self::Reset { entry, .. } => *entry,
34 }
35 }
36
37 pub fn snapshot(&self) -> &SnapshotId {
39 match self {
40 Self::SchemaChange(version) => &version.snapshot,
41 Self::Reset { snapshot, .. } => snapshot,
42 }
43 }
44
45 pub fn schema_in_place(state: &StoreState, version: u32, snapshot: &SnapshotId) -> bool {
48 version <= state.reached(&snapshot.audience)
49 }
50
51 pub fn reset_in_place(state: &StoreState, snapshot: &SnapshotId) -> bool {
53 state.resets.get(&snapshot.audience) == Some(snapshot)
54 }
55
56 pub fn already_in_place(&self, state: &StoreState) -> bool {
58 match self {
59 Self::SchemaChange(version) => {
60 Self::schema_in_place(state, version.number, &version.snapshot)
61 }
62 Self::Reset { snapshot, .. } => Self::reset_in_place(state, snapshot),
63 }
64 }
65
66 pub fn apply(&self, state: &mut StoreState) {
68 match self {
69 Self::SchemaChange(version) => {
70 state.schema.insert(version.snapshot.audience.clone(), version.clone());
71 }
72 Self::Reset { snapshot, .. } => {
73 state.resets.insert(snapshot.audience.clone(), snapshot.clone());
74 }
75 }
76 }
77
78 pub(crate) fn load_selected(database: &StoreSql) -> Result<Vec<Self>, DbError> {
79 Ok(retained(database)?.into_iter().map(|row| row.boundary).collect())
80 }
81}
82
83#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct BoundaryCoverage {
86 pub boundary: Boundary,
88 pub included: u64,
90}
91
92pub(crate) fn record(database: &StoreSql, boundary: &Boundary) -> Result<(), DbError> {
95 let (kind, version) = match boundary {
96 Boundary::SchemaChange(version) => ("schema", Some(version.number)),
97 Boundary::Reset { .. } => ("reset", None),
98 };
99 let entry = boundary.entry();
100 let snapshot = boundary.snapshot();
101 crate::reset_bytes::bound(database, &snapshot.audience, entry.get())?;
102 database.execute(
103 "INSERT INTO _coven_boundaries(slot,kind,version,audience,snapshot_device,snapshot_number)
104 VALUES(?1,?2,?3,?4,?5,?6) ON CONFLICT(slot) DO NOTHING",
105 params![
106 entry.get().to_be_bytes().as_slice(),
107 kind,
108 version,
109 &snapshot.audience,
110 snapshot.device,
111 snapshot.number.to_be_bytes().as_slice()
112 ],
113 )?;
114 Ok(())
115}
116
117pub(crate) fn record_coverage(
121 database: &StoreSql,
122 coverage: &BoundaryCoverage,
123) -> Result<bool, DbError> {
124 record(database, &coverage.boundary)?;
125 let previous: (Option<Vec<u8>>, bool) = database.query_row(
126 "SELECT included,applied FROM _coven_boundaries WHERE slot=?1",
127 [coverage.boundary.entry().get().to_be_bytes().as_slice()],
128 |row| Ok((row.get(0)?, row.get(1)?)),
129 )?;
130 let included = coverage.included.to_be_bytes().to_vec();
131 if let Some(checked) = previous.0 {
132 if checked != included {
133 return Err(crate::snapshot_error::invalid("checked boundary coverage changed"));
134 }
135 }
136 if previous.1 {
137 return Ok(false);
138 }
139 database.execute(
140 "UPDATE _coven_boundaries SET included=?2,applied=1 WHERE slot=?1",
141 params![coverage.boundary.entry().get().to_be_bytes().as_slice(), included],
142 )?;
143 Ok(true)
144}
145
146pub(crate) fn replace(
150 database: &StoreSql,
151 boundaries: Vec<BoundaryCoverage>,
152) -> Result<Vec<Slot>, DbError> {
153 let mut ids = BTreeSet::new();
154 for boundary in &boundaries {
155 if !ids.insert(boundary.boundary.entry()) {
156 return Err(crate::snapshot_error::invalid("reload repeats a boundary slot"));
157 }
158 }
159 let previous: BTreeSet<_> = database
160 .query("SELECT slot FROM _coven_boundaries WHERE applied=1 AND kind='reset'", [], |row| {
161 crate::store_state_tables::slot(row, 0)
162 })?
163 .into_iter()
164 .collect();
165 let changed_resets = boundaries
166 .iter()
167 .filter_map(|coverage| match &coverage.boundary {
168 Boundary::Reset { entry, .. } if ids.contains(entry) && !previous.contains(entry) => {
169 Some(*entry)
170 }
171 _ => None,
172 })
173 .collect();
174 database.execute("DELETE FROM _coven_boundaries", [])?;
175 for boundary in &boundaries {
176 record_coverage(database, boundary)?;
177 }
178 Ok(changed_resets)
179}
180
181struct RetainedBoundary {
182 boundary: Boundary,
183 included: Option<u64>,
184 applied: bool,
185}
186
187fn retained(database: &StoreSql) -> Result<Vec<RetainedBoundary>, DbError> {
188 Ok(database.query(
189 "SELECT b.kind,b.version,b.audience,b.snapshot_device,b.snapshot_number,b.slot,b.included,b.applied
190 FROM _coven_boundaries b ORDER BY b.slot",
191 [],
192 |row| {
193 let snapshot = SnapshotId {
194 audience: audience(row, 2)?,
195 device: row.get::<_, DeviceId>(3)?,
196 number: counter(row.get(4)?)?,
197 };
198 let entry = crate::store_state_tables::slot(row, 5)?;
199 let boundary = match (row.get::<_, String>(0)?.as_str(), row.get::<_, Option<u32>>(1)?) {
200 ("schema", Some(number)) => Boundary::SchemaChange(StoreVersion { number, snapshot, entry }),
201 ("reset", None) => Boundary::Reset { entry, snapshot },
202 _ => return Err(damaged(0, sqlive::rusqlite::types::Type::Text)),
203 };
204 let included = row.get::<_, Option<Vec<u8>>>(6)?.map(counter).transpose()?;
205 Ok(RetainedBoundary { boundary, included, applied: row.get(7)? })
206 },
207 )?)
208}
209
210#[derive(Clone, Debug, PartialEq, Eq)]
212pub(crate) enum BoundaryRule {
213 Raise(u32),
216 Reset(Slot),
218}
219
220pub(crate) struct WriteBoundary {
222 pub(crate) audience: Audience,
223 pub(crate) rule: BoundaryRule,
224 pub(crate) included: u64,
225}
226
227impl WriteBoundary {
228 pub(crate) fn load(database: &StoreSql) -> Result<Vec<Self>, DbError> {
229 let mut state = StoreState::default();
230 let mut result = Vec::new();
231 for row in retained(database)? {
232 if row.boundary.already_in_place(&state) {
233 continue;
234 }
235 row.boundary.apply(&mut state);
236 if row.applied {
237 result.push(Self {
238 audience: row.boundary.snapshot().audience.clone(),
239 rule: match &row.boundary {
240 Boundary::SchemaChange(version) => BoundaryRule::Raise(version.number),
241 Boundary::Reset { entry, .. } => BoundaryRule::Reset(*entry),
242 },
243 included: row.included.ok_or(DbError::DamagedDatabase)?,
244 });
245 }
246 }
247 Ok(result)
248 }
249
250 pub(crate) fn judging(database: &StoreSql) -> Result<Vec<Self>, DbError> {
256 let mut boundaries = Self::load(database)?;
257 for (audience, version, included) in crate::raise_capture::provisional(database)? {
258 let realized = boundaries.iter().any(|b| {
259 b.audience == audience
260 && matches!(b.rule, BoundaryRule::Raise(number) if number >= version)
261 });
262 if !realized {
263 boundaries.push(Self { audience, rule: BoundaryRule::Raise(version), included });
264 }
265 }
266 Ok(boundaries)
267 }
268
269 pub(crate) fn excludes(
274 &self,
275 header: &WriteHeader,
276 audience: &Audience,
277 slot: Option<Slot>,
278 ) -> Option<ChangeVerdict> {
279 if *audience != self.audience || slot.is_some_and(|slot| slot.get() <= self.included) {
280 return None;
281 }
282 match &self.rule {
283 BoundaryRule::Raise(version) => {
284 (header.schema_version < *version).then_some(ChangeVerdict::Excluded(*version))
285 }
286 BoundaryRule::Reset(entry) => {
287 (header.read_through < entry.get()).then_some(ChangeVerdict::Ignored(*entry))
288 }
289 }
290 }
291
292 pub(crate) fn ignore(
295 boundaries: &[Self],
296 header: &WriteHeader,
297 audience: &Audience,
298 slot: Option<Slot>,
299 ) -> bool {
300 matches!(
301 Self::part_verdict(boundaries, header, audience, slot),
302 Some(ChangeVerdict::Ignored(_))
303 )
304 }
305
306 pub(crate) fn part_verdict(
310 boundaries: &[Self],
311 header: &WriteHeader,
312 audience: &Audience,
313 slot: Option<Slot>,
314 ) -> Option<ChangeVerdict> {
315 let verdicts: Vec<_> = boundaries
316 .iter()
317 .filter_map(|boundary| boundary.excludes(header, audience, slot))
318 .collect();
319 verdicts
320 .iter()
321 .find(|verdict| matches!(verdict, ChangeVerdict::Ignored(_)))
322 .cloned()
323 .or_else(|| {
324 verdicts
325 .iter()
326 .filter_map(|verdict| match verdict {
327 ChangeVerdict::Excluded(version) => Some(*version),
328 _ => None,
329 })
330 .max()
331 .map(ChangeVerdict::Excluded)
332 })
333 }
334}
335#[cfg(test)]
336#[path = "write_boundary_tests.rs"]
337pub(crate) mod tests;