Skip to main content

coven_database/
joining_write.rs

1//! The app's write for a member's device as its registration applies (§13.2):
2//! the person's profile, written in the transaction that first applies the
3//! device's registration, from the facts of its member's latest admission, or
4//! of slot 1 for the store's creator (§10.3).
5
6use crate::sqlite::StoreSql;
7use crate::store_call::StoreCall;
8use crate::{
9    file_write::{FileWrite, WriteFiles},
10    write_schema::WriteSchema,
11    DbError, StoreState,
12};
13use coven_foundation::id_source::{CircleId, DeviceId, MemberId};
14use sqlive::rusqlite::{Params, Row};
15
16/// The facts of a member's latest admission, or of slot 1 for the store's
17/// creator, which the joining write reads (§10.3, §13.2).
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct Joining {
20    /// The member whose device registers.
21    pub member: MemberId,
22    /// The name the member's join request carried, or the creator's
23    /// `create_store` was given; none after a recovery.
24    pub person: Option<String>,
25    /// The circle their latest admission made, or the creator's private
26    /// circle slot 1 made.
27    pub circle: CircleId,
28}
29
30/// App SQL inside a joining write: the statements of a local write and
31/// nothing of coven's steps, so no operation, file or journal can be reached
32/// from it. Returning an error rolls back the write and the registration it
33/// runs with.
34pub struct JoiningWrite<'write> {
35    files: &'write FileWrite<'write>,
36}
37
38impl<'write> JoiningWrite<'write> {
39    pub(crate) fn new(files: &'write FileWrite<'write>) -> Self {
40        Self { files }
41    }
42
43    /// Execute one app statement with parameters.
44    pub fn execute<P: Params>(&self, sql: &str, params: P) -> sqlive::rusqlite::Result<usize> {
45        self.files.execute(sql, params)
46    }
47
48    /// Execute app statements within this write's transaction.
49    pub fn execute_batch(&self, sql: &str) -> sqlive::rusqlite::Result<()> {
50        self.files.execute_batch(sql)
51    }
52
53    /// Map one app row, including changes already made by this write.
54    pub fn query_row<T, P, F>(&self, sql: &str, params: P, map: F) -> sqlive::rusqlite::Result<T>
55    where
56        P: Params,
57        F: FnOnce(&Row<'_>) -> sqlive::rusqlite::Result<T>,
58    {
59        self.files.query_row(sql, params, map)
60    }
61
62    /// Map all app rows produced by a query within this write.
63    pub fn query<T, P, F>(&self, sql: &str, params: P, map: F) -> sqlive::rusqlite::Result<Vec<T>>
64    where
65        P: Params,
66        F: FnMut(&Row<'_>) -> sqlive::rusqlite::Result<T>,
67    {
68        self.files.query(sql, params, map)
69    }
70}
71
72/// The app's joining write, as the database keeps it.
73pub(crate) type JoiningHook =
74    dyn Fn(&JoiningWrite<'_>, &Joining) -> Result<(), DbError> + Send + Sync;
75
76/// A joining write owed to a transaction that registers this device: the
77/// app's write and the facts it takes, with what a local write needs.
78pub(crate) struct Registering<'a> {
79    hook: &'a JoiningHook,
80    joining: Joining,
81    schema: &'a WriteSchema,
82    device: DeviceId,
83    now: std::time::SystemTime,
84    files: &'a WriteFiles<'a>,
85}
86
87impl Registering<'_> {
88    /// Make the owed write through `write`, which runs a local write's phases
89    /// on its transaction with what that write needs and the app's SQL.
90    pub(crate) fn make<R>(
91        &self,
92        write: impl FnOnce(
93            &WriteSchema,
94            DeviceId,
95            std::time::SystemTime,
96            &WriteFiles<'_>,
97            &dyn Fn(&FileWrite<'_>) -> Result<(), DbError>,
98        ) -> R,
99    ) -> R {
100        write(self.schema, self.device, self.now, self.files, &|files| {
101            (self.hook)(&JoiningWrite::new(files), &self.joining)
102        })
103    }
104}
105
106/// The joining write the transaction that commits `state` owes, if any: the
107/// app registered one, this device is a device of an active member, and the
108/// state the database holds doesn't register it yet. Read before the transaction begins, so the write runs in
109/// the one transaction that first applies the registration, and in none after
110/// it (§13.2).
111pub(crate) fn owed<'a>(
112    db: &StoreSql,
113    call: &StoreCall<'_>,
114    hook: Option<&'a JoiningHook>,
115    state: &StoreState,
116    schema: &'a WriteSchema,
117    now: std::time::SystemTime,
118    files: &'a WriteFiles<'a>,
119) -> Result<Option<Registering<'a>>, DbError> {
120    let (Some(hook), Some(device)) = (hook, call.local_device()) else {
121        return Ok(None);
122    };
123    if crate::store_state_tables::device_member(db, device)?.is_some() {
124        return Ok(None);
125    }
126    let Some(registered) = state.devices.get(&device) else {
127        return Ok(None);
128    };
129    let Some(member) = state.active_member(&registered.member).filter(|_| registered.active())
130    else {
131        return Ok(None);
132    };
133    let joined = &member.joined;
134    Ok(Some(Registering {
135        hook,
136        joining: Joining {
137            member: registered.member,
138            person: joined.person.clone(),
139            circle: joined.circle,
140        },
141        schema,
142        device,
143        now,
144        files,
145    }))
146}
147
148#[cfg(test)]
149#[path = "joining_write_tests.rs"]
150pub(crate) mod tests;