Skip to main content

coven_database/
archive_bytes.rs

1//! The archives that resets kept in the store's directory, with their
2//! sizes, in `coven_archive_bytes` (§17.8, §19.3): coven writes each
3//! archive's row as the store opens after the swap that kept it, and
4//! deletes the row in the step that moves the archive out of the store's
5//! directory to delete it.
6
7use crate::database::{process, StoreDatabase};
8use crate::sqlite::StoreSql;
9use crate::DbError;
10use coven_foundation::files::{StoreDir, StoreDirAccess};
11
12/// Record each archive in `directory` that has no row yet, with its size,
13/// as the store opens, failing the handle if the write fails. A reset's
14/// swap moves the old installation into its archive while no database is
15/// open and the store refuses opens. The opening of the swapped store comes
16/// next and records the archive. When the process stops between the two,
17/// the next reset's opening of the swapped store records it, so no reader
18/// sees an archive without its row. Nothing writes into an archive once a
19/// reset keeps it, so its size stays right.
20pub(crate) fn record_opened(writer: &mut StoreSql, directory: &StoreDir) -> Result<(), DbError> {
21    let recorded =
22        writer.query("SELECT archive FROM coven_archive_bytes", [], |r| r.get::<_, String>(0))?;
23    let mut kept = Vec::new();
24    for name in directory.discarded_devices()? {
25        if !recorded.contains(&name) {
26            let bytes = directory.discarded_device_size(&name)?;
27            kept.push((name, crate::sqlite::integer("archive size", bytes)?));
28        }
29    }
30    if kept.is_empty() {
31        return Ok(());
32    }
33    crate::pending::state_transaction(writer, |db| {
34        for (name, bytes) in &kept {
35            db.execute(
36                "INSERT INTO coven_archive_bytes(archive,bytes) VALUES(?1,?2)",
37                (name, bytes),
38            )?;
39        }
40        Ok(())
41    })
42}
43
44/// Return the total size of the archives that resets kept, or `None` when
45/// there are none.
46pub(crate) fn kept(db: &StoreSql) -> Result<Option<u64>, DbError> {
47    let (archives, bytes) =
48        db.query_row("SELECT count(*),coalesce(sum(bytes),0) FROM coven_archive_bytes", [], |r| {
49            Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?))
50        })?;
51    if archives == 0 {
52        return Ok(None);
53    }
54    Ok(Some(crate::sqlite::unsigned(bytes)?))
55}
56
57/// Delete the archive `name`'s row, in the transaction under way.
58fn forget_archive(db: &StoreSql, name: &str) -> Result<(), DbError> {
59    db.execute("DELETE FROM coven_archive_bytes WHERE archive=?1", [name])?;
60    Ok(())
61}
62
63/// Move the archive `name` out of `directory` and delete its row, in one
64/// step, on `writer`, the store's writer, which the caller holds.
65fn retire_archive(writer: &mut StoreSql, directory: &StoreDir, name: &str) -> Result<(), DbError> {
66    crate::database::library_bytes::uncount(
67        writer,
68        || directory.retire_discarded_device(name),
69        || directory.return_discarded_device(name),
70        |db| forget_archive(db, name),
71    )
72}
73
74impl StoreDatabase {
75    /// Delete every archive that resets kept in the store's directory
76    /// (§19.3). For each archive, one step moves it into the removal folder
77    /// and deletes its row; then the method deletes the removal folder on
78    /// the blocking pool. On a failure the method returns the error. Each
79    /// archive is then either still in the store's directory with its row,
80    /// or in the removal folder, which the next call deletes.
81    pub async fn delete_discarded_devices(&self) -> Result<(), DbError> {
82        let directory = self
83            .call(|inner| {
84                let directory = &inner.access.directory;
85                inner.access.with_writer(|writer, _| {
86                    let names = writer.query(
87                        "SELECT archive FROM coven_archive_bytes ORDER BY archive",
88                        [],
89                        |r| r.get::<_, String>(0),
90                    )?;
91                    for name in names {
92                        retire_archive(writer, directory, &name)?;
93                    }
94                    Ok::<_, DbError>(())
95                })?;
96                Ok::<_, DbError>(directory.clone())
97            })
98            .await?;
99        process(&self.bugs, move || Ok(directory.remove_retired_devices()?)).await
100    }
101
102    /// Delete the archive `name` the way `delete_discarded_devices` deletes
103    /// each archive. A restore calls it to delete the archive of the
104    /// installation it replaced (§13.1).
105    pub async fn remove_discarded_device(&self, name: String) -> Result<(), DbError> {
106        let directory = self
107            .call(move |inner| {
108                let directory = &inner.access.directory;
109                inner.access.with_writer(|writer, _| retire_archive(writer, directory, &name))?;
110                Ok::<_, DbError>(directory.clone())
111            })
112            .await?;
113        process(&self.bugs, move || Ok(directory.remove_retired_devices()?)).await
114    }
115}