1use 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
22pub struct InviteExpiry {
27 stop: watch::Sender<bool>,
28 task: tokio::sync::Mutex<Option<coven_foundation::task::OwnedTask>>,
29 #[cfg(any(test, feature = "test-utils"))]
31 parks: crate::Parks,
32}
33
34impl InviteExpiry {
35 pub async fn opened(database: &StoreDatabase, now: SystemTime) -> Result<(), DbError> {
39 write(database, now).await.map(drop)
40 }
41
42 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 #[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 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 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 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 _ = stopping.changed() => return,
119 changed = journal.next() => if changed.is_err() { return },
121 woke = wake => if let Err(error) = woke {
122 database.fail_expiry_wait(error);
125 return;
126 },
127 never = parks.parked() => match never {},
128 }
129 }
130}
131
132pub(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
151struct Ended {
153 invites: Vec<OperationId>,
155 pairings: bool,
157}
158
159impl Ended {
160 fn any(&self) -> bool {
161 !self.invites.is_empty() || self.pairings
162 }
163}
164
165async 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
195async 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;