Skip to main content

coven/
builder_creation.rs

1//! Create identity custody while the store remains unpublished.
2
3use super::*;
4use coven_foundation::files::{BootstrapDirectoryError, BootstrapStore};
5use coven_foundation::task::caught_sync;
6
7impl CovenBuilder {
8    /// Create and open a store, initializing its member, first store key and
9    /// slot 1 before publication; `device_name` names this installation.
10    /// Slot 1 records the creator's join facts as an admission records a
11    /// joiner's: `person`, her name, and her private circle, named by
12    /// `circle_name` from the member id coven makes for her, with her as its
13    /// only member. Applying slot 1 runs the app's joining write for this
14    /// device (§13.2). Slot 1 also makes a circle for each of `circles`,
15    /// named in order, with the creator as its first member and its key in
16    /// custody. Then `creating`, the app's first write, runs on a
17    /// [`MemberWrite`] with those circles' ids in that order, after slot 1
18    /// has registered the creator and this device and made the circles, so
19    /// its rows can name and go into them (§10.3). The store is published
20    /// only once that write has committed: a failed one leaves no store and
21    /// nothing in custody. Cancellation does not interrupt creation or
22    /// rollback. Errors carry no handle; a published store is closed before
23    /// returning.
24    pub async fn create_store<C, F>(
25        self,
26        name: &str,
27        device_name: &str,
28        person: &str,
29        circle_name: C,
30        circles: &[&str],
31        creating: F,
32    ) -> Result<CovenHandle, StoreCreationError>
33    where
34        C: FnOnce(MemberId) -> String + Send + 'static,
35        F: FnOnce(&MemberWrite<'_>, &[CircleId]) -> CovenResult<()> + Send + 'static,
36    {
37        let asked = Asked {
38            name: name.to_owned(),
39            device_name: device_name.to_owned(),
40            person: person.to_owned(),
41            circle: circle_name,
42            circles: circles.iter().map(|circle| (*circle).to_owned()).collect(),
43        };
44        let bugs = self.directories.bugs().clone();
45        let publish = coven_foundation::files::BootstrapStore::publish;
46        let creating = create(self, asked, creating, publish);
47        crate::task::spawn_completing("create the store", bugs, creating).await?
48    }
49}
50
51/// What the app asks slot 1 to record (§10.3): the store's name, this
52/// device's, the creator's join facts and the circles her first write asks
53/// for.
54pub(super) struct Asked<C> {
55    pub(super) name: String,
56    pub(super) device_name: String,
57    /// The creator's name, which her devices' joining write reads (§13.2).
58    pub(super) person: String,
59    /// The creator's private circle: the app's function that names it from
60    /// her member id, then the name it gave.
61    pub(super) circle: C,
62    pub(super) circles: Vec<String>,
63}
64
65impl<C: FnOnce(MemberId) -> String> Asked<C> {
66    /// The request with the creator's private circle named from `member`.
67    fn named(self, member: MemberId) -> Asked<String> {
68        let Self { name, device_name, person, circle, circles } = self;
69        Asked { name, device_name, person, circle: circle(member), circles }
70    }
71}
72
73/// The app's request with its private circle named, and the creator's
74/// member id it was named from.
75struct Founding {
76    asked: Asked<String>,
77    member: MemberId,
78}
79
80/// The app's first write, which runs once slot 1 is applied and before the
81/// store is published (§10.3).
82pub(super) trait Creating:
83    FnOnce(&MemberWrite<'_>, &[CircleId]) -> CovenResult<()> + Send + 'static
84{
85}
86impl<F> Creating for F where
87    F: FnOnce(&MemberWrite<'_>, &[CircleId]) -> CovenResult<()> + Send + 'static
88{
89}
90
91pub(super) async fn create(
92    builder: CovenBuilder,
93    asked: Asked<impl FnOnce(MemberId) -> String + Send + 'static>,
94    creating: impl Creating,
95    publish: impl FnOnce(&BootstrapStore) -> Result<(), BootstrapDirectoryError> + Send + 'static,
96) -> Result<CovenHandle, StoreCreationError> {
97    let id = StoreId(builder.ids.new_id());
98    let member = MemberId(builder.ids.new_id());
99    let asked = asked.named(member);
100    // A name the format refuses is refused before anything is made.
101    for name in [&asked.person, &asked.circle].into_iter().chain(&asked.circles) {
102        coven_format::value::name(name).map_err(SyncError::from)?;
103    }
104    let founding = Founding { asked, member };
105    let pending = Arc::new(builder.directories.begin_bootstrap(id, builder.ids.as_ref()).await?);
106    let bugs = builder.directories.bugs().clone();
107    match prepare(builder, pending.clone(), founding, creating, publish).await {
108        Ok(handle) => Ok(handle),
109        Err(error @ StoreCreationError::PublishedButNotSynced { .. }) => Err(error),
110        Err(error) => {
111            Err(
112                match crate::task::blocking_completing(
113                    "remove the unpublished store",
114                    bugs,
115                    move || pending.cancel(),
116                )
117                .await
118                {
119                    Ok(Ok(())) => error,
120                    Ok(Err(cleanup)) => error.with_cleanup(cleanup.into()),
121                    // The removal panicked or never ran, so the unpublished
122                    // store may stay on disk.
123                    Err(failed) => error.with_cleanup(failed.into()),
124                },
125            )
126        }
127    }
128}
129
130async fn prepare(
131    builder: CovenBuilder,
132    pending: Arc<BootstrapStore>,
133    founding: Founding,
134    creating: impl Creating,
135    publish: impl FnOnce(&BootstrapStore) -> Result<(), BootstrapDirectoryError> + Send + 'static,
136) -> Result<CovenHandle, StoreCreationError> {
137    let Founding { asked: Asked { name, device_name, person, circle, circles }, member } = founding;
138    let directory = pending.directory();
139    let database = builder.database(directory.clone())?.open().await?;
140    let waits = match coven_sync::RetryWaits::open(database.clone(), builder.clock.clone()).await {
141        Ok(waits) => Arc::new(waits),
142        Err(error) => return Err(close_failed(&database, CovenError::from(error).into()).await),
143    };
144    let bugs = builder.directories.bugs().clone();
145    let custody = crate::task::blocking_completing("create the store's custody", bugs.clone(), {
146        let directory = directory.clone();
147        move || {
148            let keychain = Arc::new(StoreKeychain::new(
149                builder.keychain().map_err(CovenError::from)?,
150                directory.id(),
151            ));
152            let owners = builder.owners(directory, keychain, crate::builder::Continuing::Fresh)?;
153            // Each step catches its panic, so a panic undoes custody as any
154            // failure before publication does (E15). Making the identity
155            // writes nothing, and refuses one custody already holds, so a
156            // failure there has nothing to undo; the undo takes back only
157            // what this creation wrote.
158            let identity =
159                caught_sync("make the member identity", || owners.custody.new_identity(member))
160                    .unwrap_or_else(|bug| Err(IdentityError::Bug(bug)))?;
161            match keep_custody(&owners, &identity, circle, circles) {
162                Ok((ring, circle, circles)) => Ok((owners, identity, ring, circle, circles)),
163                Err(error) => Err(undo_custody(&owners, error)),
164            }
165        }
166    })
167    .await
168    .unwrap_or_else(|shutdown| Err(shutdown.into()));
169    let (owners, identity, ring, circle, circles) = match custody {
170        Ok(kept) => kept,
171        Err(error) => return Err(close_failed(&database, error).await),
172    };
173    // Slot 1 is decided and applied before the store is visible: the creator
174    // is the store's first admin and this device its first device from the
175    // moment it exists, and the joining write has run for it (§10.3).
176    let creation = coven_sync::Creation {
177        store: directory.id(),
178        name,
179        device: owners.device,
180        device_name,
181        member: &identity,
182        person,
183        circle,
184        circles: circles.clone(),
185        ring: &ring,
186    };
187    if let Err(error) = coven_sync::decide_creation(&database, creation).await {
188        let undone = undo_blocking(owners, bugs, StoreCreationError::from(error)).await;
189        return Err(close_failed(&database, undone).await);
190    }
191    // The app's first write sees the creator, this device and the circles,
192    // and commits before the store is visible: a failure leaves no store and
193    // nothing in custody (§10.3).
194    let made: Vec<CircleId> = circles.iter().map(|circle| circle.circle).collect();
195    let written = database.write_as(move |sql| creating(&MemberWrite::new(sql), &made)).await;
196    if let Err(error) = written {
197        let undone = undo_blocking(owners, bugs, StoreCreationError::from(error)).await;
198        return Err(close_failed(&database, undone).await);
199    }
200    let published = crate::task::blocking_completing("publish the store", bugs, move || {
201        match published(&pending, publish) {
202            Publication::Done => Ok((owners, None)),
203            Publication::Failed(error) => Ok((owners, Some(error))),
204            Publication::Unknown(error) => Err(error),
205            Publication::Refused(error) => Err(undo_custody(&owners, error)),
206        }
207    })
208    .await
209    .unwrap_or_else(|shutdown| Err(shutdown.into()));
210    let (owners, publication) = match published {
211        Ok(owners) => owners,
212        Err(error) => return Err(close_failed(&database, error).await),
213    };
214    if let Err(error) = crate::storage::record_opened(
215        &database,
216        &owners.clock,
217        coven_database::RecordedLocation::None,
218        None,
219    )
220    .await
221    {
222        return Err(close_failed(&database, error.into()).await);
223    }
224    let handle = owners.into_handle(database, waits, false, false);
225    match publication {
226        None => Ok(handle),
227        Some(source) => {
228            let store = handle.store_id();
229            let source = match handle.close().await {
230                Ok(()) => source,
231                Err(cleanup) => source.with_cleanup(cleanup.into()),
232            };
233            Err(StoreCreationError::PublishedButNotSynced { store, source: Box::new(source) })
234        }
235    }
236}
237
238/// Save the new member's identity, this installation's device id, the first
239/// store key and the first key of the creator's private circle, named
240/// `circle`, and of each circle named in `circles` in custody, which the
241/// store's slot 1 introduces (§12.4).
242fn keep_custody(
243    owners: &crate::builder::OpeningOwners,
244    identity: &MemberIdentity,
245    circle: String,
246    circles: Vec<String>,
247) -> Result<(StoreKeyring, coven_sync::NewCircle, Vec<coven_sync::NewCircle>), StoreCreationError> {
248    caught_sync("save the member identity", || owners.identity.persist(identity))
249        .unwrap_or_else(|bug| Err(KeyError::Bug(bug)))
250        .map_err(|error| StoreCreationError::from(IdentityError::from(error)))?;
251    caught_sync("record the device id", || owners.keychain.set_device_id(owners.device))
252        .unwrap_or_else(|bug| Err(KeyError::Bug(bug)))
253        .map_err(CovenError::from)?;
254    let kept = caught_sync("keep the first keys", || {
255        let key =
256            coven_crypto::StoreKey::generate(KeyId(owners.ids.new_id())).map_err(KeyError::from)?;
257        let mut ring = StoreKeyring::new(key);
258        let mut make = |name: String| {
259            let (circle, key) = (CircleId(owners.ids.new_id()), KeyId(owners.ids.new_id()));
260            ring.insert_circle_key(
261                coven_crypto::CircleKey::generate(circle, key).map_err(KeyError::from)?,
262            )
263            .map_err(KeyError::from)?;
264            Ok::<_, KeyError>(coven_sync::NewCircle { circle, name, key })
265        };
266        let circle = make(circle)?;
267        let circles = circles.into_iter().map(&mut make).collect::<Result<Vec<_>, _>>()?;
268        owners.keys.persist(&ring)?;
269        Ok::<_, KeyError>((ring, circle, circles))
270    })
271    .unwrap_or_else(|bug| Err(KeyError::Bug(bug)))
272    .map_err(CovenError::from)?;
273    Ok(kept)
274}
275
276/// Take back what creation wrote to custody, trying every step and
277/// retaining every failure. The marker stays hidden.
278fn undo_custody(
279    owners: &crate::builder::OpeningOwners,
280    mut error: StoreCreationError,
281) -> StoreCreationError {
282    for cleanup in
283        [owners.identity.forget(), owners.keychain.delete_device_id(), owners.keys.forget()]
284    {
285        if let Err(cleanup) = cleanup {
286            error = error.with_cleanup(CovenError::from(cleanup).into());
287        }
288    }
289    error
290}
291
292/// [`undo_custody`] on the blocking pool.
293async fn undo_blocking(
294    owners: crate::builder::OpeningOwners,
295    bugs: coven_foundation::task::BugSinkRef,
296    error: StoreCreationError,
297) -> StoreCreationError {
298    match crate::task::blocking_completing("undo the store's custody", bugs, move || {
299        Err::<(), _>(undo_custody(&owners, error))
300    })
301    .await
302    {
303        Ok(Err(error)) => error,
304        Ok(Ok(())) => unreachable!("the undo answers the error it undid"),
305        Err(failed) => StoreCreationError::from(failed),
306    }
307}
308
309/// How far publishing the new store got.
310enum Publication {
311    /// The store is published.
312    Done,
313    /// The store is published, but the step failed after its marker went,
314    /// as syncing the directory does: its custody stays.
315    Failed(StoreCreationError),
316    /// The store isn't published: its custody is undone.
317    Refused(StoreCreationError),
318    /// Publishing panicked, and the marker that says how far it got couldn't
319    /// be read: custody stays, and listing the stores shows which (E15).
320    Unknown(StoreCreationError),
321}
322
323/// Publish the store with `publish`. Its panic leaves it unknown whether
324/// the marker went, so the marker says: creation keeps custody for a
325/// published store and undoes it for one that isn't (E15).
326fn published(
327    pending: &BootstrapStore,
328    publish: impl FnOnce(&BootstrapStore) -> Result<(), BootstrapDirectoryError>,
329) -> Publication {
330    let bug = match caught_sync("publish the store", || publish(pending)) {
331        Ok(Ok(())) => return Publication::Done,
332        Ok(Err(error)) if error.published_unsynced() => {
333            return Publication::Failed(StoreCreationError::Directory(error))
334        }
335        Ok(Err(error)) => return Publication::Refused(error.into()),
336        Err(bug) => StoreCreationError::Bug(bug),
337    };
338    match pending.is_published() {
339        Ok(true) => Publication::Failed(bug),
340        Ok(false) => Publication::Refused(bug),
341        Err(read) => {
342            Publication::Unknown(bug.with_cleanup(BootstrapDirectoryError::from(read).into()))
343        }
344    }
345}
346
347async fn close_failed(
348    database: &coven_database::StoreDatabase,
349    error: StoreCreationError,
350) -> StoreCreationError {
351    match database.close().await {
352        Ok(()) => error,
353        Err(cleanup) => error.with_cleanup(SyncError::from(cleanup).into()),
354    }
355}
356
357#[cfg(test)]
358#[path = "builder_creation_tests.rs"]
359mod tests;