Skip to main content

coven_database/
database_local_bytes.rs

1//! What the store keeps on this device, read from coven's tables (§17.8,
2//! §19.3, Appendix C.3): the counters the cache keeps with its entries, the
3//! partial downloads pins left, the sizes of the store's own files and of
4//! the archives that resets kept.
5
6use super::{Mode, StoreDatabase};
7use crate::sqlite::{unsigned, StoreSql};
8use crate::{DbError, LiveQuery};
9use coven_foundation::locks::read_unpoisoned;
10use coven_foundation::task::CarriesBug;
11
12/// One namespace's cache, in bytes on disk.
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct NamespaceBytes {
15    /// The namespace's name as declared.
16    pub namespace: String,
17    /// Its budget, declared or since set.
18    pub budget: u64,
19    /// Chunks and headers: what counts toward the budget.
20    pub cached: u64,
21    /// Pinned whole copies.
22    pub pinned: u64,
23}
24
25/// The cache's bytes: every declared namespace's, and the partial downloads
26/// pins left, which the cache neither counts nor evicts.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct CacheBytes {
29    /// Each declared namespace's cache, in declaration order.
30    pub namespaces: Vec<NamespaceBytes>,
31    /// Partial downloads pins left.
32    pub pinning: u64,
33}
34
35/// What a store keeps on this device, in bytes on disk (§17.8, §19.3).
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct LocalBytes {
38    /// Each declared namespace's cache, in declaration order.
39    pub namespaces: Vec<NamespaceBytes>,
40    /// Partial downloads pins left, kept apart from the cache.
41    pub pinning: u64,
42    /// The store's own files: its database files as their last checkpoints
43    /// left them, coven's copies of app files, the snapshot and floor bodies
44    /// this device captured to upload, and a rebuild's database files while
45    /// one runs.
46    pub library: u64,
47    /// The total size of the archives that resets kept, while there is one.
48    pub before_reset: Option<u64>,
49}
50
51/// Every namespace's budget and counters, by name.
52pub(crate) fn budgets(db: &StoreSql) -> Result<Vec<NamespaceBytes>, DbError> {
53    db.query(
54        "SELECT namespace,budget,cached,pinned FROM _coven_cache_budgets ORDER BY namespace",
55        [],
56        |r| {
57            Ok((
58                r.get::<_, String>(0)?,
59                r.get::<_, i64>(1)?,
60                r.get::<_, i64>(2)?,
61                r.get::<_, i64>(3)?,
62            ))
63        },
64    )?
65    .into_iter()
66    .map(|(namespace, budget, cached, pinned)| {
67        Ok(NamespaceBytes {
68            namespace,
69            budget: unsigned(budget)?,
70            cached: unsigned(cached)?,
71            pinned: unsigned(pinned)?,
72        })
73    })
74    .collect()
75}
76
77/// The sum of the partial downloads' sizes.
78pub(crate) fn partials(db: &StoreSql) -> Result<u64, DbError> {
79    unsigned(db.query_row("SELECT coalesce(sum(size),0) FROM _coven_cache_partials", [], |r| {
80        r.get::<_, i64>(0)
81    })?)
82}
83
84/// What the store keeps on this device, from the transaction under way:
85/// the namespaces named in `declared`, in that order, the partial
86/// downloads, the store's own files and the archives that resets kept.
87pub(crate) fn read(db: &StoreSql, declared: &[String]) -> Result<LocalBytes, DbError> {
88    let mut kept = budgets(db)?;
89    let namespaces = declared
90        .iter()
91        .filter_map(|name| {
92            kept.iter().position(|bytes| &bytes.namespace == name).map(|at| kept.swap_remove(at))
93        })
94        .collect();
95    Ok(LocalBytes {
96        namespaces,
97        pinning: partials(db)?,
98        library: crate::database::library_bytes::library(db)?,
99        before_reset: crate::database::archive_bytes::kept(db)?,
100    })
101}
102
103impl<M: Mode> StoreDatabase<M> {
104    /// The names of the namespaces declared at open, in declaration order;
105    /// none once the store has closed.
106    fn declared_namespaces(&self) -> Vec<String> {
107        read_unpoisoned(&self.inner).as_ref().map_or_else(Vec::new, |open| {
108            M::access(open).write_schema.namespaces.iter().map(|n| n.name.clone()).collect()
109        })
110    }
111
112    /// The cache's counters and the partial downloads' sizes, from one
113    /// snapshot, for the namespaces declared at open, in declaration order.
114    pub async fn cache_bytes(&self) -> Result<CacheBytes, DbError> {
115        let declared = self.declared_namespaces();
116        let bytes = self.read_committed(move |db| read(db, &declared)).await?;
117        Ok(CacheBytes { namespaces: bytes.namespaces, pinning: bytes.pinning })
118    }
119}
120
121impl StoreDatabase {
122    /// What the store keeps on this device, from one snapshot of its tables
123    /// (§17.8, §19.3): each declared namespace's cache, the partial
124    /// downloads pins left, the store's own files and the archives resets
125    /// kept.
126    pub async fn local_bytes(&self) -> Result<LocalBytes, DbError> {
127        let declared = self.declared_namespaces();
128        self.read_committed(move |db| read(db, &declared)).await
129    }
130
131    /// `local_bytes` now and after each write that changes what it reads: a
132    /// namespace's counters or budget, a partial download, a database
133    /// file's size after a checkpoint, a copy kept or released, a captured
134    /// body, a rebuild's folder or an archive. A cached read's recency
135    /// changes none of them.
136    pub fn subscribe_local_bytes<E>(&self) -> LiveQuery<LocalBytes, E>
137    where
138        E: From<DbError> + CarriesBug + Send + 'static,
139    {
140        let declared = self.declared_namespaces();
141        self.follow(move |db| read(db, &declared).map_err(E::from))
142    }
143}
144
145#[cfg(test)]
146#[path = "database_local_bytes_tests.rs"]
147mod tests;