Skip to main content

coven_database/
raise_capture.rs

1//! The original queue prefix captured for an unpublished breaking raise.
2//!
3//! A capture fixes eligibility through its marker. Snapshot bytes are made from
4//! the counted base only after that prefix has acquired slots; later local
5//! originals remain outside it.
6use crate::sqlite::StoreSql;
7use crate::store_call::StoreCall;
8use crate::write_encoding::{audience, counter};
9use crate::{write_schema::WriteSchema, DbError};
10use coven_format::{admin::SnapshotId, snapshot::SnapshotHeader};
11use coven_foundation::id_source::DeviceId;
12use coven_merge::{Audience, WriteId};
13use sqlive::rusqlite::params;
14
15/// A breaking raise's fixed original prefix and current counted coverage.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct RaiseCapture {
18    /// Audience raised by this capture.
19    pub audience: Audience,
20    /// Schema version to announce.
21    pub version: u32,
22    /// Last captured original, including the migration marker.
23    pub through: WriteId,
24    /// Applied slot when this capture was prepared.
25    pub covers: u64,
26}
27
28pub(crate) fn capture(
29    db: &StoreSql,
30    _schema: &WriteSchema,
31    marker: WriteId,
32    version: u32,
33) -> Result<bool, DbError> {
34    let state = crate::store_state_tables::read(db)?;
35    db.execute("DELETE FROM _coven_raise_captures", [])?;
36    let Some(member) = state
37        .store
38        .as_ref()
39        .and_then(|_| state.devices.get(&marker.device))
40        .map(|device| device.member)
41    else {
42        return Ok(false);
43    };
44    // A circle awaiting its rebuild was never held at any version: its raise
45    // body is the rebuild's, captured when the rebuild installs.
46    let rebuilding = crate::reload_gate::rebuilding(db)?;
47    for selected in state.readable_audiences(&member) {
48        if rebuilding.contains_key(&selected) {
49            continue;
50        }
51        db.execute("INSERT INTO _coven_raise_captures(audience,version,through,covers) VALUES(?1,?2,?3,?4)",params![&selected,version,marker.number.to_be_bytes(),crate::sequence::applied(db)?.to_be_bytes()])?;
52    }
53    Ok(true)
54}
55
56/// The creator's raise, as the store it created comes into being. A breaking
57/// migration that ran before the store existed captured nothing, as there
58/// was no shared version to raise; the store's history records the version
59/// its creating app runs only once this device raises it, through the marker
60/// that migration queued (§18.3).
61pub(crate) fn capture_created(
62    db: &StoreSql,
63    call: &StoreCall<'_>,
64    schema: &WriteSchema,
65) -> Result<(), DbError> {
66    if breaking_version(db)? == 0 || !provisional(db)?.is_empty() {
67        return Ok(());
68    }
69    let device = call
70        .local_device()
71        .ok_or(DbError::Invariant { what: "a writer connection observes this device" })?;
72    let queued = db.query(
73        "SELECT number FROM _coven_uploads WHERE device=?1 ORDER BY number DESC",
74        [device],
75        |r| counter(r.get::<_, Vec<u8>>(0)?),
76    )?;
77    for number in queued {
78        let marker = WriteId { device, number };
79        let header = crate::upload::queued(db, marker)?
80            .ok_or(DbError::Invariant { what: "a queued write has its header" })?
81            .header;
82        if header.disposition == coven_format::write::WriteDisposition::Migration {
83            capture(db, schema, marker, crate::transaction_constants::schema_version(db, call)?)?;
84            return Ok(());
85        }
86    }
87    Ok(())
88}
89
90/// Raise a circle this device's member just made, when the base its creation
91/// recorded is below this installation's newest breaking migration: it was
92/// prepared before that migration and applied after it, so the migration's
93/// capture didn't include it. The circle has no rows yet, so this device holds
94/// its state at its own version, and its later writes wait for the raise as
95/// a migration's do. A device that starts reading a circle with history holds
96/// none of it at the circle's version, and waits for a device that held it
97/// (§15.5, §18.3).
98pub(crate) fn capture_made(
99    db: &StoreSql,
100    call: &StoreCall<'_>,
101    circle: coven_foundation::id_source::CircleId,
102    state: &crate::StoreState,
103    operation: Option<&crate::migration::MigrationOperation>,
104) -> Result<(), DbError> {
105    let audience = Audience::Circle(circle);
106    let device = call
107        .local_device()
108        .ok_or(DbError::Invariant { what: "a writer connection observes this device" })?;
109    let made = state
110        .devices
111        .get(&device)
112        .is_some_and(|local| local.active() && state.reads_circle(circle, &local.member));
113    if !made || state.reached(&audience) >= breaking_version(db)? {
114        return Ok(());
115    }
116    // Every capture holds the same prefix; with none, the prefix is every
117    // write this device has made so far.
118    let through = match captured_through(db)? {
119        Some(through) => through,
120        None => crate::write_metadata::newest_number(db, device)?.unwrap_or(0),
121    };
122    capture_circle(db, call, &audience, through, operation)
123}
124
125/// Capture `audience` through the device's write number `through` at the
126/// device's version, and open the journal through which passes publish the
127/// capture if the migration's has finished.
128fn capture_circle(
129    db: &StoreSql,
130    call: &StoreCall<'_>,
131    audience: &Audience,
132    through: u64,
133    operation: Option<&crate::migration::MigrationOperation>,
134) -> Result<(), DbError> {
135    db.execute(
136        "INSERT INTO _coven_raise_captures(audience,version,through,covers) VALUES(?1,?2,?3,?4)",
137        params![
138            audience,
139            crate::transaction_constants::schema_version(db, call)?,
140            through.to_be_bytes(),
141            crate::sequence::applied(db)?.to_be_bytes()
142        ],
143    )?;
144    // The migration's journal may have finished with its own raises; passes
145    // publish captures while one is open.
146    if let Some(operation) = operation {
147        if crate::operation::of_kind(db, crate::operation_kind::SCHEMA_RAISE)?.is_empty() {
148            journal(db, operation, crate::transaction_constants::schema_version(db, call)?)?;
149        }
150    }
151    Ok(())
152}
153
154/// The capture of a circle this device rebuilt, installed in the commit that
155/// loads it: the circle is held as any held audience is, so the device's
156/// writes after its migration marker `marker` wait for its raise (§18.3,
157/// §18.4).
158pub(crate) fn capture_rebuilt(
159    db: &StoreSql,
160    call: &StoreCall<'_>,
161    audience: &Audience,
162    marker: WriteId,
163    operation: Option<&crate::migration::MigrationOperation>,
164) -> Result<(), DbError> {
165    capture_circle(db, call, audience, marker.number, operation)
166}
167
168/// Journal the operation through which passes publish this installation's
169/// raise captures at `version`, at its first step.
170pub(crate) fn journal(
171    db: &StoreSql,
172    operation: &crate::migration::MigrationOperation,
173    version: u32,
174) -> Result<(), DbError> {
175    let new = operation(version)?;
176    let id = crate::operation::insert(db, &new)?;
177    crate::operation::advance(
178        db,
179        &crate::OperationUpdate { id, previous: 0, last_step: 1, data: new.data },
180    )
181}
182
183pub(crate) fn raise_to(
184    db: &StoreSql,
185    _tables: &[crate::SyncedTable],
186    device: DeviceId,
187    version: u32,
188) -> Result<bool, DbError> {
189    if captures(db, device)?.is_empty() {
190        return Ok(false);
191    }
192    // A capture is made through one of this device's writes, which stays.
193    let newest = crate::write_metadata::newest_number(db, device)?
194        .ok_or(DbError::Invariant { what: "a raise capture's device has a write" })?;
195    db.execute(
196        "UPDATE _coven_raise_captures SET version=?1,through=?2,covers=?3",
197        params![version, newest.to_be_bytes(), crate::sequence::applied(db)?.to_be_bytes()],
198    )?;
199    Ok(true)
200}
201
202/// A marker queued behind the writes a waiting raise captured: the raise's
203/// prefix now runs through it, so no raise goes out ahead of it (§18.4).
204pub(crate) fn follow(db: &StoreSql, marker: WriteId) -> Result<(), DbError> {
205    for capture in captures(db, marker.device)? {
206        db.execute(
207            "UPDATE _coven_raise_captures SET through=?1 WHERE audience=?2 AND version=?3",
208            params![marker.number.to_be_bytes(), capture.audience, capture.version],
209        )?;
210    }
211    Ok(())
212}
213
214pub(crate) fn prepare(
215    db: &StoreSql,
216    _schema: &WriteSchema,
217    device: DeviceId,
218    selected: &Audience,
219    version: u32,
220) -> Result<Option<RaiseCapture>, DbError> {
221    db.execute(
222        "UPDATE _coven_raise_captures SET covers=?1 WHERE audience=?2 AND version=?3",
223        params![crate::sequence::applied(db)?.to_be_bytes(), selected, version],
224    )?;
225    Ok(captures(db, device)?
226        .into_iter()
227        .find(|capture| capture.audience == *selected && capture.version == version))
228}
229
230pub(crate) fn captured_through(db: &StoreSql) -> Result<Option<u64>, DbError> {
231    Ok(db.query_row("SELECT max(through) FROM _coven_raise_captures", [], |r| {
232        r.get::<_, Option<Vec<u8>>>(0)?.map(counter).transpose()
233    })?)
234}
235
236pub(crate) fn provisional(db: &StoreSql) -> Result<Vec<(Audience, u32, u64)>, DbError> {
237    Ok(db.query(
238        "SELECT audience,version,covers FROM _coven_raise_captures ORDER BY audience",
239        [],
240        |r| Ok((audience(r, 0)?, r.get(1)?, counter(r.get(2)?)?)),
241    )?)
242}
243
244pub(crate) fn captures(db: &StoreSql, device: DeviceId) -> Result<Vec<RaiseCapture>, DbError> {
245    Ok(db.query(
246        "SELECT audience,version,through,covers FROM _coven_raise_captures ORDER BY audience",
247        [],
248        |r| {
249            Ok(RaiseCapture {
250                audience: audience(r, 0)?,
251                version: r.get(1)?,
252                through: WriteId { device, number: counter(r.get(2)?)? },
253                covers: counter(r.get(3)?)?,
254            })
255        },
256    )?)
257}
258
259pub(crate) fn write<E>(
260    db: &StoreSql,
261    call: &StoreCall<'_>,
262    schema: &WriteSchema,
263    id: SnapshotId,
264    version: u32,
265    begin: impl FnOnce(&SnapshotHeader) -> Result<(), E>,
266    emit: impl FnMut(Vec<u8>) -> Result<(), E>,
267) -> Result<u32, crate::SnapshotWriteError<E>> {
268    let capture = captures(db, id.device)?
269        .into_iter()
270        .find(|capture| capture.audience == id.audience && capture.version == version)
271        .ok_or(DbError::DamagedDatabase)?;
272    if crate::upload::unconfirmed(db, capture.through)?.is_some() {
273        return Err(DbError::ClaimUnsettled.into());
274    }
275    if capture.covers != crate::sequence::applied(db)? {
276        return Err(DbError::CaptureChanged.into());
277    }
278    crate::snapshot_write::write(db, call, schema, id, begin, emit)
279}
280
281/// The version of the newest breaking migration this installation ran, zero
282/// if none: received writes are read from it on (§18.5), and a snapshot this
283/// installation writes announces it as its breaking version (§16.3).
284pub(crate) fn breaking_version(db: &StoreSql) -> Result<u32, DbError> {
285    Ok(db.query_row("SELECT minimum FROM _coven_snapshot_schema WHERE singleton=1", [], |r| {
286        r.get(0)
287    })?)
288}
289
290/// Read received writes from schema version `minimum` on, the version a
291/// breaking migration requires (§18.5).
292pub(crate) fn require(db: &StoreSql, minimum: u32) -> Result<(), DbError> {
293    db.execute("UPDATE _coven_snapshot_schema SET minimum=?1 WHERE singleton=1", [minimum])?;
294    Ok(())
295}
296
297/// A snapshot of `audience` loaded at schema `version` covers every capture
298/// of it at that version or before.
299pub(crate) fn loaded(db: &StoreSql, audience: &Audience, version: u32) -> Result<(), DbError> {
300    db.execute(
301        "DELETE FROM _coven_raise_captures WHERE audience=?1 AND version<=?2",
302        params![audience, version],
303    )?;
304    Ok(())
305}
306
307/// Every capture of `audience`: a rebuild of it replaces them.
308pub(crate) fn supersede(db: &StoreSql, audience: &Audience) -> Result<(), DbError> {
309    db.execute("DELETE FROM _coven_raise_captures WHERE audience=?1", [audience])?;
310    Ok(())
311}
312
313pub(crate) fn discard(db: &StoreSql, audience: &Audience, version: u32) -> Result<(), DbError> {
314    db.execute(
315        "DELETE FROM _coven_raise_captures WHERE audience=?1 AND version=?2",
316        params![audience, version],
317    )?;
318    Ok(())
319}
320
321#[cfg(test)]
322#[path = "raise_capture_tests.rs"]
323pub(crate) mod tests;