Skip to main content

coven_database/
file_database_pins.rs

1//! The pins coven keeps for files kept here (§17.8), as the file owner
2//! reads and settles them.
3
4use super::{file_ref, FileDatabase};
5use crate::{DbError, FileRef};
6use coven_foundation::files::StagedName;
7
8impl FileDatabase {
9    /// The files a switch to the cloud asked this device to keep whole, each
10    /// with the copy its cache copy is made from and its wait (§17.8).
11    pub async fn pin_requests(&self) -> Result<Vec<crate::PinRequest>, DbError> {
12        self.read(|db, _| crate::file_pins::read(db)).await
13    }
14    /// The file of request `id` left the stored bytes the request asked to
15    /// keep: the request, its record and wait end, and the copy it kept goes
16    /// once nothing else names it.
17    pub async fn end_pin_request(&self, id: i64) -> Result<(), DbError> {
18        self.database
19            .call(move |inner| {
20                // The released copy goes once the writer is free (§21.2).
21                inner.with_files("end a pin request", |writer, _, _| {
22                    crate::pending::state_transaction(writer, |db| {
23                        crate::file_pins::end_request(db, id).map(drop)
24                    })
25                })
26            })
27            .await
28    }
29    /// Make the pin request `id` asked for from `prepared`, ending the
30    /// request in the same write, and return true (§17.8). A request that
31    /// ended since it was read, by the app's unpin or the file leaving,
32    /// makes nothing: false.
33    pub async fn keep(&self, prepared: crate::PreparedPin, id: i64) -> Result<bool, DbError> {
34        self.database
35            .write(move |sql| {
36                if !sql.end_pin_request(id)? {
37                    return Ok(false);
38                }
39                sql.pin(prepared)?;
40                Ok(true)
41            })
42            .await
43    }
44    /// The cache copy couldn't be made from coven's copy for request `id`:
45    /// the pin downloads from storage instead.
46    pub async fn drop_pin_copy(&self, id: i64) -> Result<(), DbError> {
47        self.database
48            .call(move |inner| {
49                inner.with_files("drop a pin's copy", |writer, _, _| {
50                    writer.transaction(|db| crate::file_pins::drop_copy(db, id))
51                })
52            })
53            .await
54    }
55    /// Record a failed attempt at the pin `request` asked for as its record,
56    /// with its next wait or none, in one transaction. A request already
57    /// ended records nothing.
58    pub async fn fail_pin<P: crate::PendingValue>(
59        &self,
60        request: &crate::PinRequest,
61        record: P,
62        retry: Option<crate::RetryWait>,
63    ) -> Result<(), DbError> {
64        let (id, file) = (request.id, request.file);
65        self.run(move |db, _, _, _, _| {
66            crate::pending::state_transaction(db, |db| {
67                if record.pin_of() != Some(file) {
68                    return Err(DbError::Invariant {
69                        what: "a kept pin's failure is its own record",
70                    });
71                }
72                if !db.query_row(
73                    "SELECT EXISTS(SELECT 1 FROM _coven_pin_requests WHERE id=?1)",
74                    [id],
75                    |r| r.get::<_, bool>(0),
76                )? {
77                    return Ok(());
78                }
79                crate::retry::save_failure(
80                    db,
81                    &record,
82                    crate::RetrySubject::Pin(id),
83                    retry.as_ref(),
84                )
85            })
86        })
87        .await
88    }
89    /// The first-read plaintext hash of one chunk of coven's copy, which the
90    /// cache copy made from it checks.
91    #[expect(
92        clippy::map_err_ignore,
93        reason = "a stored value that won't convert is damage, a computed one a broken invariant"
94    )]
95    pub async fn copy_chunk_hash(
96        &self,
97        copy: &StagedName,
98        index: u64,
99    ) -> Result<coven_crypto::ContentHash, DbError> {
100        let copy = copy.as_str().to_owned();
101        self.read(move |db, _| {
102            let index = i64::try_from(index)
103                .map_err(|_| DbError::Invariant { what: "a chunk index fits SQLite" })?;
104            let hash = db
105                .query(
106                    "SELECT hash FROM _coven_copy_chunks WHERE path=?1 AND chunk=?2",
107                    sqlive::rusqlite::params![copy, index],
108                    |r| r.get::<_, Vec<u8>>(0),
109                )?
110                .pop()
111                .ok_or(DbError::DamagedDatabase)?;
112            crate::file_hashes::stored_hash(hash)
113        })
114        .await
115    }
116    /// Open coven's copy a pin request keeps, which must still have the
117    /// file's size; it touches only the disk.
118    pub async fn open_pin_copy(
119        &self,
120        file: &FileRef,
121        copy: &StagedName,
122    ) -> Result<crate::LocalFileStream, crate::LocalFileError> {
123        let (id, size, copy) = (file.id().to_string(), file.size(), copy.clone());
124        self.database
125            .call(move |inner| file_ref::open_copy(&inner.access.directory, &id, size, &copy))
126            .await
127    }
128}