Skip to main content

tinystore/blobs/
list.rs

1//! A folder's files: a page of them, every page, what they count, and a clear
2//! of them all.
3
4use std::sync::{Arc, LazyLock};
5
6use rusqlite::params;
7
8use super::change::{Change, hidden};
9#[cfg(feature = "async")]
10use super::files::Done;
11use super::files::{Files, Writing};
12use super::info::{FileInfo, FileRow, Page, Usage, file_columns};
13use super::paths::MAX_PATH;
14use crate::sqlite::{Tx, sql_error};
15use crate::{Error, Result};
16
17/// Files a page holds at most, and when a list does not say.
18pub const PAGE_FILES: usize = 1000;
19
20/// Files a clear deletes in its own transaction; past them it marks the
21/// folder and maintenance deletes them.
22pub(crate) const CLEAR_AT_ONCE: usize = 10_000;
23
24const SELECT_PAGE: &str = concat!(
25    "select ",
26    file_columns!(),
27    " from _tinystore_blobs_files as f where f.set_id = ?1 and f.path >= ?2 and f.path < ?3
28        and (f.expires is null or f.expires > ?4) and not ",
29    hidden!(),
30    " order by f.path limit cast(?5 as integer)"
31);
32const SELECT_USAGE: &str = concat!(
33    "select count(*), coalesce(sum(f.size), 0) from _tinystore_blobs_files as f where f.set_id = ?1 and f.path >= ?2
34        and f.path < ?3 and (f.expires is null or f.expires > ?4) and not ",
35    hidden!()
36);
37const COUNT_UNDER: &str = "select count(*) from (
38    select 1 from _tinystore_blobs_files where set_id = ?1 and path >= ?2 and path < ?3 limit cast(?4 as integer))";
39const DELETE_UNDER: &str =
40    "delete from _tinystore_blobs_files where set_id = ?1 and path >= ?2 and path < ?3 returning content";
41const MARK_CLEARED: &str = "insert into _tinystore_blobs_cleared (set_id, prefix, revision) values (?1, ?2, ?3)
42    on conflict (set_id, prefix) do update set revision = excluded.revision";
43
44/// Past every path: longer than a path may be, of the last character.
45pub(crate) static PAST_EVERY: LazyLock<String> = LazyLock::new(|| "\u{10ffff}".repeat(MAX_PATH / 4 + 1));
46
47/// A page of a folder's files, its options before [`List::page`].
48#[derive(Debug)]
49#[must_use = "a list reads nothing until its page"]
50pub struct List<'f> {
51    files: &'f Files,
52    prefix: String,
53    after: Option<String>,
54    limit: usize,
55}
56
57impl Files {
58    /// A page of this folder's files and of the folders in it, in the byte
59    /// order of their paths: `10.jpg` before `9.jpg`.
60    pub fn list(&self) -> List<'_> {
61        List { files: self, prefix: String::new(), after: None, limit: PAGE_FILES }
62    }
63
64    /// Every file of this folder and of the folders in it, a page at a time,
65    /// holding nothing between pages.
66    pub fn all(&self) -> All {
67        All { files: self.clone(), after: None, page: Vec::new().into_iter(), done: false }
68    }
69
70    /// The files of this folder and of the folders in it, and their bytes, as
71    /// they are now: a count, not a bound.
72    pub fn usage(&self) -> Result<Usage> {
73        let folder = self.whole_folder()?;
74        let (from, to) = self.bounds("").map_err(|error| self.fail(&folder, error))?;
75        let now = self.blobs.now();
76        let (count, size): (i64, i64) = self
77            .blobs
78            .file
79            .read(|connection| {
80                connection
81                    .prepare_cached(SELECT_USAGE)
82                    .and_then(|mut statement| {
83                        statement.query_row(params![self.set, from, to, now], |row| Ok((row.get(0)?, row.get(1)?)))
84                    })
85                    .map_err(|error| sql_error("blobs: a folder's usage", error))
86            })
87            .map_err(|error| self.fail(&folder, error))?;
88        Ok(Usage { count: u64::try_from(count).unwrap_or(0), size: u64::try_from(size).unwrap_or(0) })
89    }
90
91    /// Removes this folder and every folder in it, at once for every reader,
92    /// however many files it holds. On the files themselves it empties them.
93    pub fn clear(&self) -> Result<()> {
94        #[cfg(feature = "replication")]
95        if self.is_copy() {
96            let folder = self.whole_folder()?;
97            let cleared = self.pass_on(&super::forward::Call::Clear { folder: &folder });
98            return cleared.map(drop).map_err(|error| self.fail(&folder, error));
99        }
100        let (folder, clearing) = self.clearing()?;
101        let ((), freed) = self.blobs.file.write(0, clearing).map_err(|error| self.fail(&folder, error))?;
102        self.blobs.remove_freed(&freed);
103        Ok(())
104    }
105
106    /// [`Files::clear`] for an awaited write, submitted: `done` is given its
107    /// answer once its commit ends, on the thread that answers the commit.
108    #[cfg(feature = "async")]
109    pub(crate) fn clear_then(&self, done: impl Done<()>) {
110        let (folder, clearing) = match self.clearing() {
111            Ok(clearing) => clearing,
112            Err(error) => return done(Err(error)),
113        };
114        let files = self.clone();
115        self.blobs.file.submit(0, clearing, move |cleared| done(cleared.map_err(|error| files.fail(&folder, error))));
116    }
117
118    /// The folder as an error names it, and what its clear writes in its
119    /// transaction: the files deleted, or past [`CLEAR_AT_ONCE`] a mark that
120    /// hides them until maintenance deletes them.
121    fn clearing(&self) -> Result<(String, Writing<()>)> {
122        let folder = self.whole_folder()?;
123        let blobs = Arc::clone(&self.blobs);
124        let (set, prefix) = (self.set, self.folder.prefix().to_owned());
125        let (from, to) = self.bounds("").map_err(|error| self.fail(&folder, error))?;
126        let bound = i64::try_from(CLEAR_AT_ONCE).unwrap_or(i64::MAX);
127        let clearing = move |tx: &Tx<'_>| {
128            let mut change = Change::new(tx, &blobs);
129            let count: i64 = tx
130                .prepare_cached(COUNT_UNDER)
131                .and_then(|mut statement| statement.query_row(params![set, from, to, bound + 1], |row| row.get(0)))
132                .map_err(|error| sql_error("blobs: count a folder", error))?;
133            if count <= bound {
134                let contents = change.deleted(DELETE_UNDER, params![set, from, to])?;
135                change.release_all(contents)?;
136            } else {
137                let revision = change.next_revision()?;
138                change.execute(MARK_CLEARED, params![set, prefix, revision])?;
139            }
140            Ok(((), change.freed))
141        };
142        Ok((folder, Box::new(clearing)))
143    }
144
145    /// The first path under this folder that starts with `prefix`, and the
146    /// first past every such path.
147    fn bounds(&self, prefix: &str) -> Result<(String, String)> {
148        let (from, to) = self.folder.range(prefix)?;
149        Ok((from, to.unwrap_or_else(|| PAST_EVERY.clone())))
150    }
151
152    /// The folder as an error names it, or why it is not one.
153    fn whole_folder(&self) -> Result<String> {
154        self.usable().map(|()| self.folder.prefix().to_owned())
155    }
156
157    fn page(&self, prefix: &str, after: Option<&str>, limit: usize) -> Result<Page> {
158        if limit == 0 || limit > PAGE_FILES {
159            return Err(Error::invalid(format!("a page of {limit} files; 1 to {PAGE_FILES}")));
160        }
161        let (mut from, to) = self.bounds(prefix)?;
162        if let Some(after) = after {
163            let (past_after, _) = self.folder.range(after)?;
164            from = from.max(format!("{past_after}\u{0}"));
165        }
166        let now = self.blobs.now();
167        let wanted = i64::try_from(limit + 1).unwrap_or(i64::MAX);
168        let rows = self.blobs.file.read(|connection| {
169            let mut statement =
170                connection.prepare_cached(SELECT_PAGE).map_err(|error| sql_error("blobs: a folder's page", error))?;
171            let rows = statement
172                .query_map(params![self.set, from, to, now, wanted], FileRow::read)
173                .map_err(|error| sql_error("blobs: a folder's page", error))?;
174            rows.collect::<rusqlite::Result<Vec<FileRow>>>().map_err(|error| sql_error("blobs: a folder's page", error))
175        })?;
176        let more = rows.len() > limit;
177        let files =
178            rows.into_iter().take(limit).map(|row| row.info(&self.folder)).collect::<Result<Vec<FileInfo>>>()?;
179        let next = if more { files.last().map(|file| file.path.clone()) } else { None };
180        Ok(Page { files, next })
181    }
182}
183
184impl List<'_> {
185    /// Only the files whose path within the folder starts with this text:
186    /// `"photos/1"` finds `photos/10.jpg` too.
187    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
188        self.prefix = prefix.into();
189        self
190    }
191
192    /// The page that starts past this path, as a page's `next` says it.
193    pub fn after(mut self, path: impl Into<String>) -> Self {
194        self.after = Some(path.into());
195        self
196    }
197
198    pub fn limit(mut self, files: usize) -> Self {
199        self.limit = files;
200        self
201    }
202
203    pub fn page(self) -> Result<Page> {
204        let folder = self.files.whole_folder()?;
205        self.files
206            .page(&self.prefix, self.after.as_deref(), self.limit)
207            .map_err(|error| self.files.fail(&folder, error))
208    }
209}
210
211/// Every file of a folder, a page at a time, as [`Files::all`] walks them.
212#[derive(Debug)]
213pub struct All {
214    files: Files,
215    after: Option<String>,
216    page: std::vec::IntoIter<FileInfo>,
217    done: bool,
218}
219
220impl Iterator for All {
221    type Item = Result<FileInfo>;
222
223    fn next(&mut self) -> Option<Result<FileInfo>> {
224        loop {
225            if let Some(file) = self.page.next() {
226                return Some(Ok(file));
227            }
228            if self.done {
229                return None;
230            }
231            let mut list = self.files.list();
232            if let Some(after) = self.after.take() {
233                list = list.after(after);
234            }
235            match list.page() {
236                Ok(page) => {
237                    self.done = page.next.is_none();
238                    self.after = page.next;
239                    self.page = page.files.into_iter();
240                }
241                Err(error) => {
242                    self.done = true;
243                    return Some(Err(error));
244                }
245            }
246        }
247    }
248}
249
250#[cfg(test)]
251#[path = "list_tests.rs"]
252mod tests;