Skip to main content

coven_database/
file_database_partial_pins.rs

1//! A pin's download that stopped (§17.8): the first bytes of a file's whole
2//! encrypted copy, synced and kept apart from the cache, so the next prepare
3//! of the file continues from them. The cache neither counts nor evicts them.
4//! They go when the app unpins the file, when the pin they became publishes,
5//! or when the stored bytes they are of leave this device.
6
7use super::{cache, BytesWriting, CacheReservation, FileDatabase};
8use crate::sqlite::StoreSql;
9use crate::{DbError, FileRef};
10use coven_foundation::files::FileName;
11
12impl FileDatabase {
13    /// The cache file a prepare of `file` writes its whole copy to, and how
14    /// many of its bytes are already kept: the partial copy an earlier
15    /// prepare left, reserved again, or else `fresh`, reserved as a new
16    /// file, with none. The bytes kept are whole chunks after the header,
17    /// synced.
18    #[expect(clippy::map_err_ignore, reason = "a stored name that won't decode is DamagedDatabase")]
19    pub async fn reserve_pin_download(
20        &self,
21        file: &FileRef,
22        fresh: FileName,
23    ) -> Result<(CacheReservation, u64), DbError> {
24        let database = &self.database;
25        let writing = BytesWriting::of(database).await;
26        let held = {
27            let file = file.clone();
28            database
29                .call(move |inner| {
30                    let found = inner.access.with_writer(|writer, call| {
31                        crate::transaction_constants::read_with_constants(writer, call, || {
32                            partial(writer, &file)
33                        })
34                    })?;
35                    let Some((path, size)) = found else {
36                        return Ok(None);
37                    };
38                    let name = FileName::new(&path).map_err(|_| DbError::DamagedDatabase)?;
39                    inner.staging.reserve([crate::file_removals::OwnedFile::Cached(name.clone())]);
40                    Ok::<_, DbError>(Some((
41                        CacheReservation {
42                            reserved: inner.staging.clone(),
43                            file,
44                            name,
45                            writing: Some(writing),
46                            partial: true,
47                        },
48                        size,
49                    )))
50                })
51                .await?
52        };
53        match held {
54            Some(held) => Ok(held),
55            None => Ok((self.reserve_cache_file(file, fresh).await?, 0)),
56        }
57    }
58
59    /// Keep the first `size` bytes of the reservation's cache file, which
60    /// are synced, as the partial copy the next prepare continues from.
61    /// `NoLongerStored` when no record here names the file's stored bytes
62    /// any more, and `PinChanged` when the app unpinned the file since the
63    /// copy was reserved, which ended the partial (§17.8).
64    #[expect(
65        clippy::map_err_ignore,
66        reason = "a size past SQLite's integer is TooLarge, which names the field and size"
67    )]
68    pub async fn keep_pin_download(
69        &self,
70        reservation: &mut CacheReservation,
71        size: u64,
72    ) -> Result<(), DbError> {
73        let (file, name, kept) =
74            (reservation.file.clone(), reservation.name.clone(), reservation.partial);
75        let size = i64::try_from(size).map_err(|_| DbError::TooLarge {
76            field: "partial pin download",
77            actual: size,
78            maximum: i64::MAX as u64,
79        })?;
80        self.run(move |db, _, _, _, _| db.transaction(|db| record(db, &file, &name, size, kept)))
81            .await?;
82        reservation.partial = true;
83        Ok(())
84    }
85
86    /// The cache file of the partial download kept for `file`, and how many
87    /// of its bytes are kept, for a test to look at.
88    #[cfg(any(test, feature = "test-utils"))]
89    #[expect(clippy::map_err_ignore, reason = "a stored name that won't decode is DamagedDatabase")]
90    pub async fn pin_download_kept(
91        &self,
92        file: &FileRef,
93    ) -> Result<Option<(FileName, u64)>, DbError> {
94        let file = file.clone();
95        let found = self.read(move |db, _| partial(db, &file)).await?;
96        found
97            .map(|(path, size)| {
98                Ok((FileName::new(&path).map_err(|_| DbError::DamagedDatabase)?, size))
99            })
100            .transpose()
101    }
102
103    /// End the partial copy of `file`, whose bytes are not the file's:
104    /// they go once the writer is free.
105    pub async fn discard_pin_download(&self, file: &FileRef) -> Result<(), DbError> {
106        let file = file.clone();
107        let chosen = self
108            .run(move |db, _, _, _, _| {
109                let object = cache::object_path_of(&file)?;
110                let paths = remove(db, file.namespace(), &object)?;
111                Ok::<_, DbError>(crate::file_removals::choose_cache(&paths))
112            })
113            .await?;
114        self.removed(chosen).await
115    }
116}
117
118/// The partial copy kept of `file`: its cache file and how many bytes of
119/// it are kept.
120#[expect(clippy::map_err_ignore, reason = "a stored size that won't convert is DamagedDatabase")]
121fn partial(db: &StoreSql, file: &FileRef) -> Result<Option<(String, u64)>, DbError> {
122    let found = db
123        .query(
124            "SELECT path,size FROM _coven_cache_partials WHERE namespace=?1 AND object_path=?2",
125            (file.namespace(), cache::object_path_of(file)?),
126            |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)),
127        )?
128        .pop();
129    found
130        .map(|(path, size)| Ok((path, u64::try_from(size).map_err(|_| DbError::DamagedDatabase)?)))
131        .transpose()
132}
133
134/// Record that `name` holds `size` synced bytes of `file`'s copy: its row
135/// updated when `kept`, which an unpin may have taken, and else made, naming
136/// the file's copy as a partial for the first time.
137fn record(
138    db: &StoreSql,
139    file: &FileRef,
140    name: &FileName,
141    size: i64,
142    kept: bool,
143) -> Result<(), DbError> {
144    if !cache::named(db, file)? {
145        return Err(DbError::NoLongerStored { file: file.id() });
146    }
147    let object = cache::object_path_of(file)?;
148    if kept {
149        let updated = db.execute(
150            "UPDATE _coven_cache_partials SET size=?4
151             WHERE namespace=?1 AND object_path=?2 AND path=?3",
152            sqlive::rusqlite::params![file.namespace(), object, name.as_str(), size],
153        )?;
154        return if updated == 1 { Ok(()) } else { Err(DbError::PinChanged { file: file.id() }) };
155    }
156    // The reservation's cleanup record goes before the row names its bytes.
157    crate::file_removals::keep(db, "cache", name.as_str())?;
158    db.execute(
159        "INSERT INTO _coven_cache_partials(namespace,object_path,path,size) VALUES(?1,?2,?3,?4)",
160        sqlive::rusqlite::params![file.namespace(), object, name.as_str(), size],
161    )?;
162    Ok(())
163}
164
165/// Delete the partial copy of the stored bytes at `object` and record its
166/// cache file for removal; returns the name.
167pub(crate) fn remove(db: &StoreSql, namespace: &str, object: &str) -> Result<Vec<String>, DbError> {
168    let paths = db.query(
169        "DELETE FROM _coven_cache_partials WHERE namespace=?1 AND object_path=?2 RETURNING path",
170        (namespace, object),
171        |r| r.get::<_, String>(0),
172    )?;
173    for path in &paths {
174        crate::file_removals::record_cached(db, path)?;
175    }
176    Ok(paths)
177}