1use crate::operation_kind::{INVITE, PAIRING};
4use crate::sqlite::StoreSql;
5use crate::DbError;
6
7#[derive(
9 Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
10)]
11pub struct OperationId(pub i64);
12
13#[derive(Clone, PartialEq)]
15pub struct OperationRecord {
16 pub id: OperationId,
18 pub kind: String,
20 pub last_step: u32,
22 pub data: Vec<u8>,
24 pub started_by: String,
26}
27
28impl OperationRecord {
29 pub fn next_step(&self, data: Vec<u8>) -> Result<OperationUpdate, crate::DbError> {
33 Ok(OperationUpdate {
34 id: self.id,
35 previous: self.last_step,
36 last_step: self
37 .last_step
38 .checked_add(1)
39 .ok_or(crate::DbError::Invariant { what: "an operation's steps fit u32" })?,
40 data,
41 })
42 }
43}
44
45impl std::fmt::Debug for OperationRecord {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 f.debug_struct("OperationRecord")
48 .field("id", &self.id)
49 .field("kind", &self.kind)
50 .field("last_step", &self.last_step)
51 .field("data", &"[REDACTED]")
52 .field("started_by", &self.started_by)
53 .finish()
54 }
55}
56
57pub struct NewOperation {
59 pub kind: String,
61 pub data: Vec<u8>,
63 pub started_by: String,
65 pub pauses_writes: bool,
69}
70
71pub struct OperationUpdate {
73 pub id: OperationId,
75 pub previous: u32,
77 pub last_step: u32,
79 pub data: Vec<u8>,
81}
82
83macro_rules! journal {
87 ($db:expr, $new:expr) => {{
88 let (db, new): (_, &NewOperation) = ($db, $new);
89 let id = db.query_row(
90 "INSERT INTO _coven_operations(kind,last_step,data,started_by) VALUES(?1,0,?2,?3) RETURNING id",
91 (&new.kind, &new.data, &new.started_by),
92 |r| Ok(OperationId(r.get(0)?)),
93 )?;
94 if new.pauses_writes {
95 db.execute("INSERT INTO _coven_write_pause(paused,operation) VALUES(1,?1)", [id.0])?;
98 }
99 Ok::<_, DbError>(id)
100 }};
101}
102
103const LIST: &str = "INSERT INTO _coven_app_operations(operation,kind) VALUES(?1,?2)";
106
107const LIST_OUTCOME: &str =
110 "INSERT INTO _coven_app_operations(operation,kind,outcome) VALUES(?1,?2,?3)";
111
112const SET_OUTCOME: &str = "UPDATE _coven_app_operations SET outcome=?2 WHERE operation=?1";
114
115const DELETE: &str = "DELETE FROM _coven_operations WHERE id=?1";
117
118macro_rules! finish {
125 ($db:expr, $id:expr, $claimed:expr, $clear_pending:expr) => {{
126 let (db, id): (_, OperationId) = ($db, $id);
127 if $claimed {
128 return Err(DbError::Invariant { what: "an operation ends after its claim" });
129 }
130 $clear_pending?;
131 db.execute(DELETE, [id.0])?
132 }};
133}
134
135macro_rules! finish_with_outcome {
141 ($db:expr, $id:expr, $outcome:expr, $finish:expr) => {{
142 let (db, id, outcome): (_, OperationId, Vec<u8>) = ($db, $id, $outcome);
143 db.execute(SET_OUTCOME, (id.0, outcome))?;
144 if $finish != 1 {
145 return Err(DbError::OperationChanged(id));
146 }
147 Ok(())
148 }};
149}
150
151pub(crate) fn insert(db: &StoreSql, new: &NewOperation) -> Result<OperationId, DbError> {
152 journal!(db, new)
153}
154
155pub(crate) fn insert_for_app(
159 db: &StoreSql,
160 new: &NewOperation,
161 kind: &str,
162) -> Result<OperationId, DbError> {
163 let id = insert(db, new)?;
164 db.execute(LIST, (id.0, kind))?;
165 Ok(id)
166}
167
168pub(crate) fn list_outcome(
172 db: &StoreSql,
173 id: OperationId,
174 kind: &str,
175 outcome: &crate::InviteOutcome,
176) -> Result<(), DbError> {
177 db.execute(LIST_OUTCOME, (id.0, kind, crate::operation_outcome::encode(outcome)))?;
178 Ok(())
179}
180
181#[cfg(any(test, feature = "test-utils"))]
185pub fn journal_outside_store(
186 connection: &sqlive::rusqlite::Connection,
187 new: &NewOperation,
188 listed_as: Option<&str>,
189) -> Result<OperationId, DbError> {
190 let id = journal!(connection, new)?;
191 if let Some(kind) = listed_as {
192 connection.execute(LIST, (id.0, kind))?;
193 }
194 Ok(id)
195}
196
197#[cfg(any(test, feature = "test-utils"))]
206pub fn finish_outside_store(
207 connection: &sqlive::rusqlite::Connection,
208 id: OperationId,
209 listing: OutcomeListing<'_>,
210) -> Result<(), DbError> {
211 let finished = || -> Result<usize, DbError> {
212 Ok(finish!(
213 connection,
214 id,
215 false,
216 crate::pending::clear_operation_outside_store(connection, id)
217 ))
218 };
219 match listing {
220 OutcomeListing::Listed(outcome) => {
221 finish_with_outcome!(connection, id, outcome.encode(), finished()?)
222 }
223 OutcomeListing::Unlisted { kind, outcome } => {
224 connection.execute(LIST_OUTCOME, (id.0, kind, outcome.encode()))?;
225 if finished()? != 1 {
226 return Err(DbError::OperationChanged(id));
227 }
228 Ok(())
229 }
230 }
231}
232
233#[cfg(any(test, feature = "test-utils"))]
237pub enum OutcomeListing<'a> {
238 Listed(&'a crate::ListedOutcome),
240 Unlisted {
242 kind: &'a str,
244 outcome: &'a crate::ListedOutcome,
246 },
247}
248
249pub(crate) fn acknowledge(db: &StoreSql, id: OperationId) -> Result<(), DbError> {
254 let finished: Option<bool> = db
255 .query(
256 "SELECT outcome IS NOT NULL FROM _coven_app_operations WHERE operation=?1",
257 [id.0],
258 |row| row.get(0),
259 )?
260 .pop();
261 match finished {
262 None => Err(DbError::OperationUnknown(id)),
263 Some(false) => Err(DbError::OperationRunning(id)),
264 Some(true) => {
265 db.execute("DELETE FROM _coven_app_operations WHERE operation=?1", [id.0])?;
266 Ok(())
267 }
268 }
269}
270
271pub(crate) fn writes_paused(db: &StoreSql) -> Result<bool, DbError> {
273 Ok(db.query_row("SELECT EXISTS(SELECT 1 FROM _coven_write_pause WHERE paused=1)", [], |r| {
274 r.get(0)
275 })?)
276}
277
278pub(crate) fn check_write_pause(db: &StoreSql) -> Result<(), DbError> {
280 if writes_paused(db)? {
281 return Err(DbError::MemberKeysChanging);
282 }
283 Ok(())
284}
285
286pub(crate) fn reserve_snapshot(db: &StoreSql) -> Result<std::num::NonZeroU64, DbError> {
291 let number = db.query_row(
292 "UPDATE _coven_snapshot_reservation SET number=number+1 WHERE singleton=1 RETURNING number",
293 [],
294 |r| r.get::<_, i64>(0),
295 )?;
296 u64::try_from(number).ok().and_then(std::num::NonZeroU64::new).ok_or(DbError::DamagedDatabase)
297}
298
299pub(crate) fn read(db: &StoreSql) -> Result<Vec<OperationRecord>, DbError> {
300 Ok(db.query(
301 "SELECT id,kind,last_step,data,started_by FROM _coven_operations ORDER BY id",
302 [],
303 record,
304 )?)
305}
306
307pub(crate) fn of_kind(db: &StoreSql, kind: &str) -> Result<Vec<OperationRecord>, DbError> {
308 Ok(db.query(
309 "SELECT id,kind,last_step,data,started_by FROM _coven_operations WHERE kind=?1 ORDER BY id",
310 [kind],
311 record,
312 )?)
313}
314
315pub(crate) fn find(db: &StoreSql, id: OperationId) -> Result<Option<OperationRecord>, DbError> {
316 Ok(db
317 .query(
318 "SELECT id,kind,last_step,data,started_by FROM _coven_operations WHERE id=?1",
319 [id.0],
320 record,
321 )?
322 .pop())
323}
324
325pub(crate) fn first(db: &StoreSql, kind: &str) -> Result<Option<OperationRecord>, DbError> {
326 Ok(db.query(
327 "SELECT id,kind,last_step,data,started_by FROM _coven_operations WHERE kind=?1 ORDER BY id LIMIT 1",
328 [kind],
329 record,
330 )?.pop())
331}
332
333fn record(row: &sqlive::rusqlite::Row<'_>) -> sqlive::rusqlite::Result<OperationRecord> {
334 Ok(OperationRecord {
335 id: OperationId(row.get(0)?),
336 kind: row.get(1)?,
337 last_step: row.get(2)?,
338 data: row.get(3)?,
339 started_by: row.get(4)?,
340 })
341}
342
343pub(crate) fn advance(db: &StoreSql, update: &OperationUpdate) -> Result<(), DbError> {
344 let changed = db.execute(
345 "UPDATE _coven_operations SET last_step=?1,data=?2 WHERE id=?3 AND last_step=?4",
346 (&update.last_step, &update.data, update.id.0, update.previous),
347 )?;
348 if changed != 1 {
349 return Err(DbError::OperationChanged(update.id));
350 }
351 crate::pending::clear_operation(db, update.id)
352}
353
354pub(crate) fn set_step(db: &StoreSql, id: OperationId, step: u32) -> Result<(), DbError> {
358 db.execute(
359 "UPDATE _coven_operations SET last_step=?2 WHERE id=?1 AND last_step!=?2",
360 (id.0, step),
361 )?;
362 Ok(())
363}
364
365pub(crate) fn finish_with_outcome(
373 db: &StoreSql,
374 id: OperationId,
375 outcome: Option<&crate::ListedOutcome>,
376) -> Result<(), DbError> {
377 match outcome {
378 Some(outcome) => finish_with_encoded(db, id, outcome.encode()),
379 None if finish(db, id)? == 1 => Ok(()),
380 None => Err(DbError::OperationChanged(id)),
381 }
382}
383
384fn finish_with_encoded(db: &StoreSql, id: OperationId, outcome: Vec<u8>) -> Result<(), DbError> {
387 finish_with_outcome!(db, id, outcome, finish(db, id)?)
388}
389
390pub(crate) fn finish(db: &StoreSql, id: OperationId) -> Result<usize, DbError> {
395 Ok(finish!(db, id, crate::claim::held_by(db, id)?, crate::pending::clear_operation(db, id)))
396}
397
398pub(crate) fn end_on_stop(db: &StoreSql) -> Result<(), DbError> {
404 let (running, invites) = journaled_for_good(db)?;
405 if running.is_empty() && invites.is_empty() {
406 return Ok(());
407 }
408 match stopped(db)? {
409 Some(stop) => end(db, stop, running, invites),
410 None => Ok(()),
411 }
412}
413
414pub(crate) fn end_for_good(db: &StoreSql, stop: crate::DeviceStop) -> Result<(), DbError> {
424 if stop == crate::DeviceStop::Copied {
425 return Err(DbError::Invariant { what: "a copy's stop records its slot (end_for_copy)" });
426 }
427 let (running, invites) = journaled_for_good(db)?;
428 end(db, stop, running, invites)
429}
430
431pub(crate) fn end_for_copy(db: &StoreSql, slot: coven_merge::Slot) -> Result<(), DbError> {
435 let (running, invites) = journaled_for_good(db)?;
436 end(db, crate::DeviceStop::Copied, running, invites)?;
437 crate::device_reset::record_in_use(db, slot)
438}
439
440fn journaled_for_good(db: &StoreSql) -> Result<(Vec<OperationId>, Vec<OperationId>), DbError> {
443 let running = db.query(
444 "SELECT operation FROM _coven_app_operations WHERE outcome IS NULL ORDER BY operation",
445 [],
446 |r| Ok(OperationId(r.get(0)?)),
447 )?;
448 let invites = db.query(
449 "SELECT id FROM _coven_operations WHERE kind=?1 OR started_by=?1 OR kind=?2 ORDER BY id",
450 [INVITE, PAIRING],
451 |r| Ok(OperationId(r.get(0)?)),
452 )?;
453 Ok((running, invites))
454}
455
456fn end(
457 db: &StoreSql,
458 stop: crate::DeviceStop,
459 running: Vec<OperationId>,
460 invites: Vec<OperationId>,
461) -> Result<(), DbError> {
462 let landed = crate::claim::landed_operation(db)?;
463 for id in running {
464 let outcome = match landed {
465 Some((entry, slot)) if entry == id => crate::StopOutcome::Landed(slot),
466 _ => crate::StopOutcome::Stopped(stop),
467 };
468 crate::claim::drop_operation(db, id)?;
469 finish_with_encoded(db, id, outcome.encode())?;
470 }
471 for id in invites {
472 crate::claim::drop_operation(db, id)?;
473 finish(db, id)?;
474 }
475 Ok(())
476}
477
478pub(crate) fn stopped(db: &StoreSql) -> Result<Option<crate::DeviceStop>, DbError> {
481 use crate::DeviceState::{Active, Replaced};
482 let held: bool =
483 db.query_row("SELECT EXISTS(SELECT 1 FROM _coven_held_keys)", [], |r| r.get(0))?;
484 if !held {
485 return Err(DbError::Invariant {
486 what: "an installation whose writes journal operations records the pairs it holds",
487 });
488 }
489 let found: Option<(crate::DeviceState, bool, bool)> = db
490 .query(
491 "SELECT d.state,m.removed,h.signing IS NOT NULL FROM _coven_devices AS d
492 JOIN _coven_members AS m ON m.member=d.member
493 LEFT JOIN _coven_held_keys AS h ON h.signing=m.signing AND h.sealing=m.sealing
494 WHERE d.device=_coven_device()",
495 [],
496 |r| {
497 Ok((
498 crate::write_encoding::stored(r, 0, sqlive::rusqlite::types::Type::Text)?,
499 r.get(1)?,
500 r.get(2)?,
501 ))
502 },
503 )?
504 .pop();
505 Ok(found.and_then(|(state, removed, held)| match (state, removed, held) {
506 (Replaced, ..) => Some(crate::DeviceStop::Replaced),
507 (Active, false, true) => None,
508 (Active, false, false) => Some(crate::DeviceStop::MemberKeysReplaced),
509 (_, true, _) => Some(crate::DeviceStop::Removed(crate::Removal::Member)),
514 _ => Some(crate::DeviceStop::Removed(crate::Removal::Device)),
515 }))
516}
517
518pub(crate) fn hold_keys(
520 db: &StoreSql,
521 keys: &[coven_crypto::MemberPublicKeys],
522) -> Result<(), DbError> {
523 for pair in keys {
524 db.execute(
525 "INSERT INTO _coven_held_keys(signing,sealing) VALUES(?1,?2) ON CONFLICT DO NOTHING",
526 (pair.signing.as_bytes().as_slice(), pair.sealing.as_bytes().as_slice()),
527 )?;
528 }
529 Ok(())
530}
531
532#[cfg(test)]
533#[path = "operation_tests.rs"]
534pub(crate) mod tests;