Skip to main content

coven_sync/
sequence_raises.rs

1//! A breaking migration's raises: each audience it captured is raised to
2//! its version through the operation path (§18.3, §18.5).
3use crate::{
4    sequence_sync::sequence_operations::{Request, SequenceOperation},
5    sequence_sync::snapshot_capture::SnapshotRequest,
6    sequence_sync::{SequenceSync, Session},
7    SyncError,
8};
9use coven_crypto::{MemberIdentity, StoreKeyring};
10use coven_database::operation_kind;
11use coven_format::sequence::Purpose;
12use std::collections::BTreeSet;
13
14impl SequenceSync {
15    /// Supply to `DatabaseBuilder::migration_operation` at the composition
16    /// root: the breaking migration's version commits with its schema, and
17    /// passes raise each audience it captured to that version (§18.3).
18    pub fn migration_operation(
19        version: u32,
20    ) -> Result<coven_database::NewOperation, coven_database::DbError> {
21        Ok(coven_database::NewOperation {
22            kind: operation_kind::SCHEMA_RAISE.into(),
23            data: serde_json::to_vec(&version).map_err(coven_database::DbError::StateEncoding)?,
24            started_by: operation_kind::COVEN.into(),
25            pauses_writes: false,
26        })
27    }
28
29    /// Raise every captured audience to its migration's version through the
30    /// operation path, then finish the migration's journal. An audience
31    /// another device already raised to that version, or a circle deleted
32    /// since the capture, keeps no capture (§15.9, §18.5).
33    pub(crate) async fn publish_raises(
34        &self,
35        session: &mut Session,
36        ring: &mut StoreKeyring,
37        member: &MemberIdentity,
38    ) -> Result<(), SyncError> {
39        let records: Vec<_> = self
40            .database
41            .operations()
42            .await?
43            .into_iter()
44            .filter(|record| record.kind == operation_kind::SCHEMA_RAISE)
45            .collect();
46        if records.is_empty() || !self.registered(session) {
47            return Ok(());
48        }
49        let pending: BTreeSet<_> = self
50            .database
51            .operations()
52            .await?
53            .into_iter()
54            .filter(|record| record.kind == operation_kind::SEQUENCE)
55            .map(|record| serde_json::from_slice::<SequenceOperation>(&record.data))
56            .collect::<Result<Vec<_>, _>>()?
57            .into_iter()
58            .filter_map(|work| match work.request {
59                Request::Snapshot(request) if matches!(request.purpose, Purpose::Raise(_)) => {
60                    Some(request.audience)
61                }
62                _ => None,
63            })
64            .collect();
65        for capture in self.database.raise_captures().await? {
66            if !session.history.state.awaits_raise(&capture.audience, capture.version) {
67                self.database.discard_raise_capture(capture.audience, capture.version).await?;
68                continue;
69            }
70            if pending.contains(&capture.audience) {
71                continue;
72            }
73            // The raise's snapshot covers the captured writes and the
74            // marker, so it starts once they have landed. A write a bound
75            // upload holds keeps it waiting until the file is stored, and
76            // the upload's own record says why (§17.4, §18.5).
77            if self.database.unconfirmed_own_prefix(capture.through).await?.is_some() {
78                continue;
79            }
80            let result = self
81                .start_request(
82                    session,
83                    ring,
84                    member,
85                    Request::Snapshot(SnapshotRequest {
86                        audience: capture.audience.clone(),
87                        purpose: Purpose::Raise(capture.version),
88                    }),
89                    operation_kind::COVEN,
90                )
91                .await
92                .and_then(crate::operation_outcome::EntryOutcome::into_slot)
93                .map(drop);
94            self.own_work(result, |request| {
95                matches!(request, Request::Snapshot(raise) if raise.audience == capture.audience)
96            })
97            .await?;
98        }
99        if self.database.raise_captures().await?.is_empty() {
100            for record in records {
101                self.database.finish_operation(record.id).await?;
102            }
103        }
104        Ok(())
105    }
106}
107
108#[cfg(test)]
109#[path = "sequence_raises_tests.rs"]
110pub(crate) mod tests;