Skip to main content

coven_database/
file_pins.rs

1//! The files a switch to the cloud asked this device to keep whole (§17.8):
2//! a durable request, recorded in the switching write, that coven fulfils
3//! itself, resuming after a restart. An app file's request keeps coven's copy
4//! until the cache copy is made from it; a user's original is never read for
5//! the cache, so its request downloads from storage.
6
7use crate::sqlite::StoreSql;
8use crate::DbError;
9use coven_foundation::{files::StagedName, id_source::FileId};
10use sqlive::rusqlite::params;
11
12/// One file this device keeps whole as a switch asked.
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct PinRequest {
15    /// The request's own id, never reused: its wait, and what coven keeps
16    /// of it in memory, are never a later request's for the same file.
17    pub id: i64,
18    /// The file.
19    pub file: FileId,
20    /// Coven's copy of an app file's bytes, while the cache copy is still to
21    /// be made from it; `None` for a file the pin downloads from storage.
22    pub copy: Option<StagedName>,
23    /// The persisted wait after a failed attempt, if one is armed (§6.7).
24    pub retry: Option<crate::RetryWait>,
25}
26
27/// Ask this device to keep `file` whole, from coven's copy when it has one.
28pub(crate) fn request(db: &StoreSql, file: FileId) -> Result<(), DbError> {
29    db.execute(
30        "INSERT INTO _coven_pin_requests(file,copy)
31         SELECT ?1,(SELECT path FROM _coven_device_files WHERE file=?1)
32         ON CONFLICT DO NOTHING",
33        params![file],
34    )?;
35    Ok(())
36}
37
38/// End `file`'s request, if one waits: the app unpinned the file, or it is
39/// gone from this device or left its stored bytes. Returns whether a request
40/// waited.
41pub(crate) fn end(db: &StoreSql, file: FileId) -> Result<bool, DbError> {
42    let ended =
43        db.query("DELETE FROM _coven_pin_requests WHERE file=?1 RETURNING copy", [file], |r| {
44            r.get::<_, Option<String>>(0)
45        })?;
46    release(db, ended)
47}
48
49/// End the request `id`, if it still waits: its pin is made, or its file
50/// left the stored bytes. Returns whether it waited.
51pub(crate) fn end_request(db: &StoreSql, id: i64) -> Result<bool, DbError> {
52    let ended =
53        db.query("DELETE FROM _coven_pin_requests WHERE id=?1 RETURNING copy", [id], |r| {
54            r.get::<_, Option<String>>(0)
55        })?;
56    release(db, ended)
57}
58
59/// An ended request's record and wait went with its row; the copy it kept
60/// goes once nothing else names it. Returns whether a request ended.
61fn release(db: &StoreSql, mut ended: Vec<Option<String>>) -> Result<bool, DbError> {
62    let Some(copy) = ended.pop() else {
63        return Ok(false);
64    };
65    if let Some(copy) = copy {
66        crate::file_queue::release_copy(db, &copy)?;
67    }
68    Ok(true)
69}
70
71/// The cache copy couldn't be made from coven's copy for request `id`: the
72/// pin downloads from storage instead, and the copy goes once nothing else
73/// names it.
74pub(crate) fn drop_copy(db: &StoreSql, id: i64) -> Result<(), DbError> {
75    let copy = db
76        .query("SELECT copy FROM _coven_pin_requests WHERE id=?1", [id], |r| {
77            r.get::<_, Option<String>>(0)
78        })?
79        .pop()
80        .flatten();
81    let Some(copy) = copy else {
82        return Ok(());
83    };
84    db.execute("UPDATE _coven_pin_requests SET copy=NULL WHERE id=?1", [id])?;
85    crate::file_queue::release_copy(db, &copy)
86}
87
88/// Every request, with its persisted wait.
89pub(crate) fn read(db: &StoreSql) -> Result<Vec<PinRequest>, DbError> {
90    db.query("SELECT id,file,copy FROM _coven_pin_requests ORDER BY file", [], |r| {
91        Ok((r.get::<_, i64>(0)?, r.get::<_, FileId>(1)?, r.get::<_, Option<String>>(2)?))
92    })?
93    .into_iter()
94    .map(|(id, file, copy)| {
95        Ok(PinRequest {
96            id,
97            file,
98            copy: copy
99                .map(|copy| StagedName::parse(&copy).ok_or(DbError::DamagedDatabase))
100                .transpose()?,
101            retry: crate::retry::find(db, crate::RetrySubject::Pin(id))?,
102        })
103    })
104    .collect()
105}
106
107#[cfg(test)]
108#[path = "file_pins_tests.rs"]
109pub(crate) mod tests;