use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use rusqlite::{OptionalExtension, params};
use super::change::{Change, Condition, Content, Place, Version, WhenThere, hidden};
use super::engine::Blobs;
use super::info::{FileInfo, FileRow, OCTETS, file_columns, meta_text};
use super::paths::Folder;
use super::read::StoredFile;
use super::upload::Upload;
#[cfg(feature = "async")]
use crate::memory::Waiting;
use crate::sqlite::{Tx, sql_error};
use crate::{Error, Key, Result, Store};
const SET_EXPIRES: &str = "update files set expires = ?3 where set_id = ?1 and path = ?2";
const MAX_TYPE: usize = 256;
const MAX_META: usize = 2 << 10;
#[derive(Debug)]
pub struct FilesBuilder<'s> {
store: &'s Store,
name: String,
ttl: Option<Duration>,
max_file_size: Option<u64>,
}
impl<'s> FilesBuilder<'s> {
pub(crate) fn new(store: &'s Store, name: &str) -> Self {
FilesBuilder { store, name: name.to_owned(), ttl: None, max_file_size: None }
}
pub fn ttl(mut self, ttl: Duration) -> Self {
self.ttl = Some(ttl);
self
}
pub fn max_file_size(mut self, bytes: u64) -> Self {
self.max_file_size = Some(bytes);
self
}
pub fn open(self) -> Result<Files> {
check_name(&self.name)?;
let blobs = Blobs::of(self.store)?;
let set = blobs.set_id(&self.name)?;
Ok(Files {
blobs,
name: Arc::from(self.name),
set,
folder: Folder::default(),
refused: None,
ttl: self.ttl,
max_file_size: self.max_file_size,
})
}
}
#[derive(Clone)]
pub struct Files {
pub(crate) blobs: Arc<Blobs>,
name: Arc<str>,
pub(crate) set: i64,
pub(crate) folder: Folder,
refused: Option<Arc<Error>>,
ttl: Option<Duration>,
pub(crate) max_file_size: Option<u64>,
}
impl fmt::Debug for Files {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Files({}, {:?})", self.name, self.folder.prefix())
}
}
impl Files {
pub fn folder(&self, segment: impl Key) -> Files {
let mut folder = self.clone();
if folder.refused.is_none() {
match self.folder.folder(&segment.text()) {
Ok(inner) => folder.folder = inner,
Err(error) => folder.refused = Some(Arc::new(self.fail(self.folder.prefix(), error))),
}
}
folder
}
pub fn key(&self, path: &str) -> FileCall<'_> {
FileCall { files: self, path: path.to_owned(), options: Options::default() }
}
pub fn put(&self, path: &str, bytes: impl AsRef<[u8]>) -> Result<FileInfo> {
self.key(path).put(bytes)
}
pub fn create(&self, path: &str, bytes: impl AsRef<[u8]>) -> Result<bool> {
self.key(path).create(bytes)
}
pub fn upload(&self, path: &str) -> Result<Upload> {
self.key(path).upload()
}
pub fn get(&self, path: &str) -> Result<Option<StoredFile>> {
let whole = self.whole(path)?;
StoredFile::open(self, &whole).map_err(|error| self.fail(&whole, error))
}
pub fn head(&self, path: &str) -> Result<Option<FileInfo>> {
let whole = self.whole(path)?;
self.head_of(&whole).map_err(|error| self.fail(&whole, error))
}
pub fn delete(&self, path: &str) -> Result<()> {
self.key(path).delete()
}
pub fn copy(&self, from: &str, to: &str) -> Result<FileInfo> {
self.key(to).copy_from(from)
}
pub fn rename(&self, from: &str, to: &str) -> Result<FileInfo> {
self.key(to).rename_from(from)
}
pub fn expire(&self, path: &str, after: Duration) -> Result<bool> {
let whole = self.whole(path)?;
self.expire_after(&whole, after).map_err(|error| self.fail(&whole, error))
}
#[cfg(any(feature = "replication", feature = "async"))]
pub(crate) fn call(&self, path: &str, options: Options) -> FileCall<'_> {
FileCall { files: self, path: path.to_owned(), options }
}
#[cfg(feature = "replication")]
pub(crate) fn is_copy(&self) -> bool {
self.blobs.file.is_copy()
}
#[cfg(feature = "replication")]
pub(crate) fn pass_on(&self, call: &super::forward::Call<'_>) -> Result<bool> {
let set = super::forward::Set { name: &self.name, ttl: self.ttl, max_file_size: self.max_file_size };
super::forward::pass_on(&self.blobs.store()?, &set, call)
}
#[cfg(feature = "replication")]
pub(crate) fn head_here(&self, whole: &str) -> Result<Option<FileInfo>> {
self.head_of(whole)
}
pub(crate) fn whole(&self, path: &str) -> Result<String> {
self.usable()?;
self.folder.path(path).map_err(|error| self.fail(&format!("{}{path}", self.folder.prefix()), error))
}
pub(crate) fn usable(&self) -> Result<()> {
self.refused.as_ref().map_or(Ok(()), |refused| Err(refused.duplicate()))
}
pub(crate) fn fail(&self, path: &str, error: Error) -> Error {
error.within(format!("{path:?}")).within(format!("files {}", self.name))
}
pub(crate) fn describe(&self) -> String {
format!("files {}", self.name)
}
pub(crate) fn expiry(&self, ttl: Option<Duration>, now: i64) -> Option<i64> {
ttl.or(self.ttl).map(|ttl| now.saturating_add(crate::clock::millis(ttl)))
}
fn head_of(&self, whole: &str) -> Result<Option<FileInfo>> {
const SELECT_HEAD: &str = concat!(
"select ",
file_columns!(),
" from files as f where f.set_id = ?1 and f.path = ?2 and (f.expires is null or f.expires > ?3) and not ",
hidden!()
);
let now = self.blobs.now();
let row = self.blobs.file.read(|connection| {
connection
.prepare_cached(SELECT_HEAD)
.and_then(|mut statement| statement.query_row(params![self.set, whole, now], FileRow::read).optional())
.map_err(|error| sql_error("blobs: a file's head", error))
})?;
row.map(|row| row.info(&self.folder)).transpose()
}
pub(crate) fn publish(
&self,
whole: &str,
options: &Options,
content: Content,
condition: Condition,
) -> Result<Option<FileInfo>> {
let (bytes, publication) = self.publication(whole, options, content, condition);
let (info, freed) = self.blobs.file.write(bytes, publication)?;
self.blobs.remove_freed(&freed);
self.count_written(info.as_ref());
Ok(info)
}
pub(super) fn publication(
&self,
whole: &str,
options: &Options,
content: Content,
condition: Condition,
) -> (usize, Writing<Option<FileInfo>>) {
let blobs = Arc::clone(&self.blobs);
let files = self.clone();
let (path, content_type, meta, ttl) =
(whole.to_owned(), options.content_type(), meta_text(&options.meta), options.ttl);
let bytes = match &content.place {
Place::Inline(body) => body.len(),
Place::File | Place::Shared => 0,
};
let publication = move |tx: &Tx<'_>| {
let mut change = Change::new(tx, &blobs);
let version =
Version { content, content_type, meta, modified: change.now, expires: files.expiry(ttl, change.now) };
if !change.write(files.set, &path, &version, &condition)? {
return Ok((None, Vec::new()));
}
Ok((Some(version.info(&files.folder, &path)?), change.freed))
};
(bytes, Box::new(publication))
}
pub(super) fn count_written(&self, info: Option<&FileInfo>) {
if let Some(info) = info {
self.blobs.probe.count("tinystore_blobs_written_total", &[], 1.0);
self.blobs.probe.count("tinystore_blobs_written_bytes_total", &[], info.size as f64);
}
}
#[cfg(feature = "async")]
pub(crate) fn remove_freed(&self, freed: &[i64]) {
self.blobs.remove_freed(freed);
}
fn copy_to(&self, from: &str, to: &str, options: &Options, rename: bool) -> Result<FileInfo> {
refuse_onto_itself(from, to)?;
#[cfg(feature = "replication")]
if self.is_copy() {
self.pass_on(&super::forward::Call::Copy { from, to, options, rename })?;
return self.head_of(to)?.ok_or_else(|| Error::internal("a copy its home wrote that this copy lacks"));
}
let (info, freed) = self.blobs.file.write(0, self.copying(from, to, options, rename))?;
self.blobs.remove_freed(&freed);
Ok(info)
}
fn copying(&self, from: &str, to: &str, options: &Options, rename: bool) -> Writing<FileInfo> {
let blobs = Arc::clone(&self.blobs);
let files = self.clone();
let (from, to, options) = (from.to_owned(), to.to_owned(), options.clone());
let condition = Condition { if_match: options.if_match.clone(), when_there: WhenThere::Conflict };
Box::new(move |tx| {
let mut change = Change::new(tx, &blobs);
let source =
change.current(files.set, &from)?.filter(|current| current.live(change.now)).ok_or_else(|| {
Error::not_found(format!("no file at {from:?} to {}", if rename { "rename" } else { "copy" }))
})?;
let version = Version {
content: Content { id: source.content, size: source.size, sha256: source.sha256, place: Place::Shared },
content_type: options.content_type.clone().unwrap_or(source.content_type),
meta: if options.meta_given { meta_text(&options.meta) } else { source.meta },
modified: change.now,
expires: files.expiry(options.ttl, change.now),
};
change.write(files.set, &to, &version, &condition)?;
if rename {
change.remove(files.set, &from)?;
}
Ok((version.info(&files.folder, &to)?, change.freed))
})
}
fn delete_at(&self, whole: &str, if_match: Option<String>) -> Result<()> {
#[cfg(feature = "replication")]
if self.is_copy() {
return self
.pass_on(&super::forward::Call::Delete { path: whole, if_match: if_match.as_deref() })
.map(drop);
}
let ((), freed) = self.blobs.file.write(0, self.deleting(whole, if_match))?;
self.blobs.remove_freed(&freed);
Ok(())
}
fn deleting(&self, whole: &str, if_match: Option<String>) -> Writing<()> {
let blobs = Arc::clone(&self.blobs);
let (set, path) = (self.set, whole.to_owned());
Box::new(move |tx| {
let mut change = Change::new(tx, &blobs);
if let Some(etag) = &if_match {
super::change::holds_etag(etag, change.current(set, &path)?.as_ref(), change.now)?;
}
change.remove(set, &path)?;
Ok(((), change.freed))
})
}
fn expire_after(&self, whole: &str, after: Duration) -> Result<bool> {
#[cfg(feature = "replication")]
if self.is_copy() {
return self.pass_on(&super::forward::Call::Expire { path: whole, after });
}
self.blobs.file.write(0, self.expiring(whole, after)).map(|(expired, _)| expired)
}
fn expiring(&self, whole: &str, after: Duration) -> Writing<bool> {
let blobs = Arc::clone(&self.blobs);
let (set, path) = (self.set, whole.to_owned());
let after = crate::clock::millis(after);
Box::new(move |tx| {
let change = Change::new(tx, &blobs);
if !change.current(set, &path)?.is_some_and(|current| current.live(change.now)) {
return Ok((false, Vec::new()));
}
let expires = change.now.saturating_add(after);
change.execute(SET_EXPIRES, params![set, path, expires])?;
Ok((true, Vec::new()))
})
}
#[cfg(feature = "async")]
pub(crate) fn expire_then(&self, path: &str, after: Duration, done: impl Done<bool>) {
let whole = match self.whole(path) {
Ok(whole) => whole,
Err(error) => return done(Err(error)),
};
let expiring = self.expiring(&whole, after);
let files = self.clone();
self.blobs.file.submit(0, expiring, move |expired| done(expired.map_err(|error| files.fail(&whole, error))));
}
}
#[cfg(feature = "async")]
pub(crate) trait Done<T>: FnOnce(Result<(T, Freed)>) + Send + 'static {}
#[cfg(feature = "async")]
impl<T, F: FnOnce(Result<(T, Freed)>) + Send + 'static> Done<T> for F {}
pub(crate) type Freed = Vec<i64>;
pub(super) type Writing<T> = Box<dyn FnOnce(&Tx<'_>) -> Result<(T, Freed)> + Send>;
fn refuse_onto_itself(from: &str, to: &str) -> Result<()> {
if from == to {
return Err(Error::invalid("a copy or a rename onto its own path"));
}
Ok(())
}
#[derive(Clone, Debug, Default)]
pub(crate) struct Options {
pub(crate) content_type: Option<String>,
pub(crate) meta: BTreeMap<String, String>,
pub(crate) meta_given: bool,
pub(crate) ttl: Option<Duration>,
pub(crate) if_match: Option<String>,
pub(crate) size: Option<u64>,
}
impl Options {
fn content_type(&self) -> String {
self.content_type.clone().unwrap_or_else(|| OCTETS.to_owned())
}
fn check(&self) -> Result<()> {
if self.content_type.as_ref().is_some_and(|content_type| content_type.len() > MAX_TYPE) {
return Err(Error::invalid(format!("a content type over {MAX_TYPE} bytes")));
}
let meta: usize = self.meta.iter().map(|(name, value)| name.len() + value.len()).sum();
if meta > MAX_META {
return Err(Error::invalid(format!("meta of {meta} bytes, over 2 KiB")));
}
Ok(())
}
}
#[derive(Debug)]
#[must_use = "a call does nothing until its verb"]
pub struct FileCall<'f> {
files: &'f Files,
path: String,
options: Options,
}
impl<'f> FileCall<'f> {
pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
self.options.content_type = Some(content_type.into());
self
}
pub fn meta(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.options.meta.insert(name.into(), value.into());
self.options.meta_given = true;
self
}
pub fn ttl(mut self, ttl: Duration) -> Self {
self.options.ttl = Some(ttl);
self
}
pub fn if_match(mut self, etag: impl Into<String>) -> Self {
self.options.if_match = Some(etag.into());
self
}
pub fn size(mut self, bytes: u64) -> Self {
self.options.size = Some(bytes);
self
}
pub fn put(self, bytes: impl AsRef<[u8]>) -> Result<FileInfo> {
let condition = Condition { if_match: self.options.if_match.clone(), when_there: WhenThere::Replace };
self.write_all(bytes.as_ref(), condition)?.ok_or_else(|| Error::internal("a put that wrote nothing"))
}
pub fn create(self, bytes: impl AsRef<[u8]>) -> Result<bool> {
let condition = Condition { if_match: self.options.if_match.clone(), when_there: WhenThere::Skip };
self.write_all(bytes.as_ref(), condition).map(|info| info.is_some())
}
pub fn upload(self) -> Result<Upload> {
let whole = self.checked()?;
Upload::start(self.files.clone(), whole, self.options)
}
pub fn delete(self) -> Result<()> {
let whole = self.files.whole(&self.path)?;
self.files.delete_at(&whole, self.options.if_match).map_err(|error| self.files.fail(&whole, error))
}
pub fn copy_from(self, from: &str) -> Result<FileInfo> {
self.copied(from, false)
}
pub fn rename_from(self, from: &str) -> Result<FileInfo> {
self.copied(from, true)
}
fn copied(self, from: &str, rename: bool) -> Result<FileInfo> {
let (source, target) = (self.files.whole(from)?, self.checked()?);
self.files.copy_to(&source, &target, &self.options, rename).map_err(|error| self.files.fail(&target, error))
}
fn checked(&self) -> Result<String> {
let whole = self.files.whole(&self.path)?;
self.options.check().map_err(|error| self.files.fail(&whole, error))?;
Ok(whole)
}
#[cfg(feature = "async")]
pub(crate) fn into_parts(self) -> (&'f Files, String, Options) {
(self.files, self.path, self.options)
}
#[cfg(feature = "async")]
pub(crate) fn upload_then(self, done: impl FnOnce(Result<Upload>) + Send + 'static) -> Option<Waiting> {
let whole = match self.checked() {
Ok(whole) => whole,
Err(error) => {
done(Err(error));
return None;
}
};
let (files, options) = (self.files.clone(), self.options);
Some(Upload::reserve_then(self.files, move |reserved| {
let reserved = reserved.map_err(|error| files.fail(&whole, error));
done(reserved.and_then(|reserved| Upload::reserved(files, whole, options, reserved)));
}))
}
#[cfg(feature = "async")]
pub(crate) fn delete_then(self, done: impl Done<()>) {
let whole = match self.files.whole(&self.path) {
Ok(whole) => whole,
Err(error) => return done(Err(error)),
};
let deleting = self.files.deleting(&whole, self.options.if_match);
let files = self.files.clone();
self.files
.blobs
.file
.submit(0, deleting, move |deleted| done(deleted.map_err(|error| files.fail(&whole, error))));
}
#[cfg(feature = "async")]
pub(crate) fn copied_then(self, from: &str, rename: bool, done: impl Done<FileInfo>) {
let wholes = self.files.whole(from).and_then(|source| Ok((source, self.checked()?)));
let (source, target) = match wholes {
Ok(wholes) => wholes,
Err(error) => return done(Err(error)),
};
if let Err(error) = refuse_onto_itself(&source, &target) {
return done(Err(self.files.fail(&target, error)));
}
let copying = self.files.copying(&source, &target, &self.options, rename);
let files = self.files.clone();
self.files
.blobs
.file
.submit(0, copying, move |copied| done(copied.map_err(|error| files.fail(&target, error))));
}
#[cfg(any(feature = "wire", feature = "replication", feature = "async"))]
pub(crate) fn written(self, bytes: &[u8], create: bool) -> Result<Option<FileInfo>> {
let when_there = if create { WhenThere::Skip } else { WhenThere::Replace };
let condition = Condition { if_match: self.options.if_match.clone(), when_there };
self.write_all(bytes, condition)
}
fn write_all(self, bytes: &[u8], condition: Condition) -> Result<Option<FileInfo>> {
let whole = self.checked()?;
let mut upload = Upload::start(self.files.clone(), whole, self.options)?;
upload.take(bytes)?;
upload.finish(condition)
}
}
fn check_name(name: &str) -> Result<()> {
crate::text::check_name("a set's", name)
}
#[cfg(test)]
#[path = "files_tests.rs"]
mod tests;