Skip to main content

coven_sync/
invite_expiry.rs

1//! An invite's or a pairing's expiry, a write like approving, declining or
2//! cancelling it (ยง13.2). The handle that holds the store's writer writes it, with or
3//! without a storage connection: opening writes each expiry already past,
4//! and the handle then wakes when this device's wall clock reaches the
5//! earliest open invite's or pairing's expiry, by running or by being set past
6//! it, and writes it. A clock that can't wait for it fails the handle. The write
7//! ends the invite in the journal, which takes it out of `coven_invites`.
8//! Deleting its request and taking back its access is the ended invite's
9//! own work, which a pass does once storage is connected, as for an invite
10//! ended any other way. A pairing's expiry ends it the same way, and the
11//! pass puts its marker in the place of its request or handover.
12
13use super::InviteWork;
14use crate::sequence_sync::sequence_pairings::PairingWork;
15use crate::{RetryWaits, SequenceState};
16use coven_database::operation_kind;
17use coven_database::{DbError, OperationId, StoreDatabase};
18use coven_foundation::clock::ClockRef;
19use std::{sync::Arc, time::SystemTime};
20use tokio::sync::watch;
21
22/// Ends this device's invites as their lifetimes end, from the store's
23/// opening until its handle closes. Dropping it stops the wakes too. A
24/// panic in it goes to the store's bug sink and ends the wakes, as does a
25/// bug a write returns; the next open writes the expiries that passed.
26pub struct InviteExpiry {
27    stop: watch::Sender<bool>,
28    task: tokio::sync::Mutex<Option<coven_foundation::task::OwnedTask>>,
29    /// Each time the wakes have written every expiry due and wait.
30    #[cfg(any(test, feature = "test-utils"))]
31    parks: crate::Parks,
32}
33
34impl InviteExpiry {
35    /// End each invite whose lifetime ended while the store was closed, as
36    /// it opens, before any app reads its invites. A failed write fails the
37    /// handle with its cause.
38    pub async fn opened(database: &StoreDatabase, now: SystemTime) -> Result<(), DbError> {
39        write(database, now).await.map(drop)
40    }
41
42    /// Wake at each invite's expiry and write it, until closed. A new
43    /// invite brings its expiry into the wakes as it is made.
44    pub fn start(
45        database: StoreDatabase,
46        clock: ClockRef,
47        waits: Arc<RetryWaits>,
48        state: Arc<SequenceState>,
49    ) -> Self {
50        let (stop, stopping) = watch::channel(false);
51        let bugs = database.bugs().clone();
52        let parks = crate::Parks::new();
53        #[cfg(any(test, feature = "test-utils"))]
54        let expiry_parks = parks.clone();
55        let task = coven_foundation::task::spawn_owned(
56            "invite expiry",
57            bugs,
58            run(database, clock, waits, state, stopping, parks),
59            |_| async {},
60        );
61        Self {
62            stop,
63            task: tokio::sync::Mutex::new(Some(task)),
64            #[cfg(any(test, feature = "test-utils"))]
65            parks: expiry_parks,
66        }
67    }
68
69    /// Each time the wakes have written every expiry the clock has reached,
70    /// and wait for the next.
71    #[cfg(any(test, feature = "test-utils"))]
72    pub fn parked_from_now(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
73        self.parks.parked_from_now()
74    }
75
76    /// Stop waking, once a write under way has finished.
77    pub async fn close(&self) {
78        self.stop.send_replace(true);
79        if let Some(task) = self.task.lock().await.take() {
80            task.ended().await;
81        }
82    }
83}
84
85async fn run(
86    database: StoreDatabase,
87    clock: ClockRef,
88    waits: Arc<RetryWaits>,
89    state: Arc<SequenceState>,
90    mut stopping: watch::Receiver<bool>,
91    parks: crate::Parks,
92) {
93    let _running = parks.running();
94    let mut journal = database.started_operations();
95    loop {
96        let next = match expire(&database, clock.now(), &waits, &state).await {
97            Ok(next) => next,
98            // The failed write has failed the handle, which every call and
99            // live query reports, `coven_invites`' included; a bug in it
100            // reaches nobody else.
101            Err(error) => {
102                if !coven_foundation::task::report_carried(database.bugs().as_ref(), &error) {
103                    tracing::debug!("invite expiry stopped on a failed handle: {error}");
104                }
105                return;
106            }
107        };
108        // The clock says when it reaches the expiry, by running or by being
109        // set past it; a clock set back moves the wake later.
110        let wake = match next {
111            Some(at) => clock.sleep_until(at),
112            None => Box::pin(std::future::pending()),
113        };
114        tokio::select! {
115            biased;
116            never = parks.polling() => match never {},
117            // Closed, or dropped with its handle.
118            _ = stopping.changed() => return,
119            // A closed or failed handle leaves nothing to write.
120            changed = journal.next() => if changed.is_err() { return },
121            woke = wake => if let Err(error) = woke {
122                // An invite this handle can't end in time fails the handle,
123                // which every call and live query then reports.
124                database.fail_expiry_wait(error);
125                return;
126            },
127            never = parks.parked() => match never {},
128        }
129    }
130}
131
132/// Write the expiry of each invite whose lifetime ended by `now`, and
133/// return when the next one's does. Each ended invite's work is due at
134/// once, and a pass is asked for to do it.
135pub(crate) async fn expire(
136    database: &StoreDatabase,
137    now: SystemTime,
138    waits: &RetryWaits,
139    state: &SequenceState,
140) -> Result<Option<SystemTime>, DbError> {
141    let (ended, next) = write(database, now).await?;
142    for id in &ended.invites {
143        waits.operation_advanced(*id);
144    }
145    if ended.any() {
146        state.request_pass();
147    }
148    Ok(next)
149}
150
151/// The invites and pairings an expiry write ended.
152struct Ended {
153    /// The ended invites' operations, whose waits end.
154    invites: Vec<OperationId>,
155    /// Whether any pairing ended.
156    pairings: bool,
157}
158
159impl Ended {
160    fn any(&self) -> bool {
161        !self.invites.is_empty() || self.pairings
162    }
163}
164
165/// End each invite and pairing whose lifetime ended by `now`, each kind in
166/// one step on the writer with reading them: no other write comes between.
167/// Returns what ended and the earliest expiry still to come.
168async fn write(
169    database: &StoreDatabase,
170    now: SystemTime,
171) -> Result<(Ended, Option<SystemTime>), DbError> {
172    let (invites, invite_next) = write_kind(
173        database,
174        operation_kind::INVITE,
175        move |work: &InviteWork| work.expired(now),
176        InviteWork::end,
177        |work: &InviteWork| work.expires().then_some(work.expires_at),
178    )
179    .await?;
180    let (pairings, pairing_next) = write_kind(
181        database,
182        operation_kind::PAIRING,
183        move |work: &PairingWork| work.expired(now),
184        PairingWork::expire,
185        PairingWork::expiry,
186    )
187    .await?;
188    let next = match (invite_next, pairing_next) {
189        (Some(invite), Some(pairing)) => Some(invite.min(pairing)),
190        (invite, pairing) => invite.or(pairing),
191    };
192    Ok((Ended { invites, pairings: !pairings.is_empty() }, next))
193}
194
195/// End each journaled work of `kind` that `expired`, with `end`, and return
196/// the ended operations and the earliest `expiry` of the rest.
197async fn write_kind<W>(
198    database: &StoreDatabase,
199    kind: &str,
200    expired: impl Fn(&W) -> bool + Send + 'static,
201    end: impl Fn(&mut W) + Send + 'static,
202    expiry: impl Fn(&W) -> Option<SystemTime> + Send + 'static,
203) -> Result<(Vec<OperationId>, Option<SystemTime>), DbError>
204where
205    W: serde::Serialize + serde::de::DeserializeOwned,
206{
207    database
208        .advance_operations(kind, move |records| {
209            let mut updates = Vec::new();
210            let mut ended = Vec::new();
211            let mut next: Option<SystemTime> = None;
212            for record in records {
213                let mut work: W =
214                    serde_json::from_slice(&record.data).map_err(DbError::StateEncoding)?;
215                if expired(&work) {
216                    end(&mut work);
217                    updates.push(
218                        record.next_step(
219                            serde_json::to_vec(&work).map_err(DbError::StateEncoding)?,
220                        )?,
221                    );
222                    ended.push(record.id);
223                } else if let Some(at) = expiry(&work) {
224                    next = Some(next.map_or(at, |earlier: SystemTime| earlier.min(at)));
225                }
226            }
227            Ok((updates, (ended, next)))
228        })
229        .await
230}
231
232#[cfg(test)]
233#[path = "invite_expiry_tests.rs"]
234mod tests;