use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use rusqlite::{OptionalExtension, params};
use super::cache::{Asked, Counted, WhenFull};
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;
use super::uses::{Seen, ceiled};
#[cfg(feature = "async")]
use crate::memory::Waiting;
use crate::sqlite::{Tx, sql_error};
use crate::{Error, Key, Result, Store};
const SET_EXPIRES: &str = "update _tinystore_blobs_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> {
home: Home<'s>,
name: String,
ttl: Option<Duration>,
idle: Option<Duration>,
max_file_size: Option<u64>,
ceiling: Asked,
observing: bool,
}
#[derive(Debug)]
enum Home<'s> {
Store(&'s Store),
#[cfg(feature = "sql")]
Database(Arc<crate::engine::SharedFile>),
}
impl<'s> FilesBuilder<'s> {
pub(crate) fn new(store: &'s Store, name: &str) -> Self {
FilesBuilder::at(Home::Store(store), name)
}
#[cfg(feature = "sql")]
pub(crate) fn in_file(shared: Arc<crate::engine::SharedFile>, name: &str) -> FilesBuilder<'static> {
FilesBuilder::at(Home::Database(shared), name)
}
fn at(home: Home<'s>, name: &str) -> Self {
let name = name.to_owned();
FilesBuilder {
home,
name,
ttl: None,
idle: None,
max_file_size: None,
ceiling: Asked::default(),
observing: false,
}
}
pub fn ttl(mut self, ttl: Duration) -> Self {
self.ttl = Some(ttl);
self
}
pub fn idle(mut self, idle: Duration) -> Self {
self.idle = Some(idle);
self
}
pub fn max_file_size(mut self, bytes: u64) -> Self {
self.max_file_size = Some(bytes);
self
}
pub fn max_size(mut self, bytes: u64) -> Self {
self.ceiling.max_size = Some(bytes);
self
}
pub fn when_full(mut self, when_full: WhenFull) -> Self {
self.ceiling.when_full = Some(when_full);
self
}
#[cfg(any(feature = "wire", feature = "client"))]
pub(crate) fn observing(mut self) -> Self {
self.observing = true;
self
}
pub fn open(self) -> Result<Files> {
check_name(&self.name)?;
if self.ttl.is_some() && self.idle.is_some() {
return Err(Error::invalid("ttl and idle exclude each other: a term from the write, or from the last use")
.within(format!("files {}", self.name)));
}
let (blobs, beside) = match &self.home {
Home::Store(store) => (Blobs::of(store)?, store.is_beside()),
#[cfg(feature = "sql")]
Home::Database(shared) => (Blobs::in_file(shared)?, false),
};
let set = blobs.set_id(&self.name)?;
let observing = self.observing || beside;
let files = Files {
blobs,
name: Arc::from(self.name),
set,
folder: Folder::default(),
refused: None,
ttl: self.ttl,
max_file_size: self.max_file_size,
policy: Arc::new(Policy { idle: self.idle, observing }),
};
self.ceiling.settle(&files, !observing).map_err(|error| error.within(files.describe()))?;
Ok(files)
}
}
#[derive(Clone)]
pub struct Files {
pub(crate) blobs: Arc<Blobs>,
pub(super) 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>,
policy: Arc<Policy>,
}
#[derive(Debug)]
struct Policy {
idle: Option<Duration>,
observing: bool,
}
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::new(self, path, 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)?;
self.get_whole(&whole)
}
pub(crate) fn get_whole(&self, whole: &str) -> Result<Option<StoredFile>> {
let opened = (|| {
let Some((mut file, seen)) = StoredFile::open(self, whole)? else { return Ok(None) };
if let Some(until) = self.used(whole, &seen)? {
file.renewed(Blobs::time(until));
}
Ok(Some(file))
})();
opened.map_err(|error| self.fail(whole, error))
}
pub fn head(&self, path: &str) -> Result<Option<FileInfo>> {
let whole = self.whole(path)?;
let found = (|| {
let Some((mut info, seen)) = self.head_seen(&whole)? else { return Ok(None) };
if let Some(until) = self.used(&whole, &seen)? {
info.expires = Some(Blobs::time(until));
}
Ok(Some(info))
})();
found.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::new(self, path, 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 ttl = self.ttl.or(self.policy.idle);
let set = super::forward::Set { name: &self.name, 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 name(&self) -> &str {
&self.name
}
pub(crate) fn expiry(&self, ttl: Option<Duration>, now: i64) -> Option<i64> {
ttl.or(self.ttl).or(self.policy.idle).map(|ttl| now.saturating_add(crate::clock::millis(ttl)))
}
pub(super) fn records_uses(&self, seen: &Seen) -> bool {
!self.policy.observing && (self.policy.idle.is_some() || seen.ceiled)
}
pub(super) fn idle(&self) -> Option<Duration> {
self.policy.idle
}
pub(super) fn counted(&self) -> Counted {
Counted { set: self.set, name: Arc::clone(&self.name) }
}
#[cfg(feature = "replication")]
fn head_of(&self, whole: &str) -> Result<Option<FileInfo>> {
self.blobs.file.read(|connection| self.head_on(connection, whole))
}
fn head_seen(&self, whole: &str) -> Result<Option<(FileInfo, Seen)>> {
const SELECT_SEEN: &str = concat!(
"select ",
file_columns!(),
", f.revision, f.used, ",
ceiled!(),
" from _tinystore_blobs_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_SEEN)
.and_then(|mut statement| {
let seen =
|row: &rusqlite::Row<'_>| Ok((FileRow::read(row)?, (row.get(7)?, row.get(8)?, row.get(9)?)));
statement.query_row(params![self.set, whole, now], seen).optional()
})
.map_err(|error| sql_error("blobs: a file's head", error))
})?;
row.map(|(row, (revision, used, ceiled)): (FileRow, (i64, Option<i64>, bool))| {
let seen = Seen { revision, modified: row.modified, used, expires: row.expires, ceiled };
Ok((row.info(&self.folder)?, seen))
})
.transpose()
}
#[cfg(any(feature = "replication", feature = "sql"))]
pub(super) fn head_on(&self, connection: &rusqlite::Connection, whole: &str) -> Result<Option<FileInfo>> {
const SELECT_HEAD: &str = concat!(
"select ",
file_columns!(),
" from _tinystore_blobs_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 = 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 before = change.total(files.set)?.size;
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()));
}
change.fit(&files.counted(), (&path, version.content.size), before)?;
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, fill: None };
Box::new(move |tx| {
let mut change = Change::new(tx, &blobs);
let before = change.total(files.set)?.size;
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)?;
}
change.fit(&files.counted(), (&to, version.content.size), before)?;
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>,
pub(crate) timeout: Option<Duration>,
pub(crate) fill: Option<i64>,
}
impl Options {
pub(super) fn condition(&self, when_there: WhenThere) -> Condition {
let when_there = if self.fill.is_some() { WhenThere::Skip } else { when_there };
Condition { if_match: self.if_match.clone(), when_there, fill: self.fill }
}
fn content_type(&self) -> String {
self.content_type.clone().unwrap_or_else(|| OCTETS.to_owned())
}
pub(super) 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,
#[cfg(feature = "sql")]
tx: Option<&'f crate::Transaction<'f>>,
}
impl<'f> FileCall<'f> {
fn new(files: &'f Files, path: &str, options: Options) -> Self {
#[cfg(feature = "sql")]
return FileCall { files, path: path.to_owned(), options, tx: None };
#[cfg(not(feature = "sql"))]
FileCall { files, path: path.to_owned(), options }
}
#[cfg(feature = "sql")]
pub(super) fn inside(files: &'f Files, tx: &'f crate::Transaction<'f>, path: &str) -> Self {
FileCall { tx: Some(tx), ..FileCall::new(files, path, Options::default()) }
}
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 timeout(mut self, timeout: Duration) -> Self {
self.options.timeout = Some(timeout);
self
}
pub fn get_or_create<T, E>(
self,
work: impl FnMut() -> std::result::Result<T, E>,
) -> std::result::Result<StoredFile, E>
where
T: Into<super::Fill>,
E: From<Error> + fmt::Display + 'static,
{
let whole = self.to_get_or_create()?;
super::filling::get_or_create(self.files, &whole, &self.options, work)
}
pub(crate) fn to_get_or_create(&self) -> Result<String> {
let whole = self.checked()?;
#[cfg(feature = "sql")]
if self.tx.is_some() {
let refused = Error::invalid("a getOrCreate inside a transaction, whose function would hold its writer");
return Err(self.files.fail(&whole, refused));
}
#[cfg(feature = "replication")]
if self.files.is_copy() {
let refused = Error::invalid("a getOrCreate on a node's copy of blobs.db: call it at the file's home");
return Err(self.files.fail(&whole, refused));
}
Ok(whole)
}
#[cfg(feature = "wire")]
pub(crate) fn filling(mut self, owner: i64) -> Self {
self.options.fill = Some(owner);
self
}
pub fn put(self, bytes: impl AsRef<[u8]>) -> Result<FileInfo> {
let condition = self.options.condition(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 = self.options.condition(WhenThere::Skip);
self.write_all(bytes.as_ref(), condition).map(|info| info.is_some())
}
pub fn upload(self) -> Result<Upload> {
let whole = self.checked()?;
#[cfg(feature = "sql")]
if self.tx.is_some() {
let refused = Error::invalid("an upload inside a transaction: put its bytes, which commit with it");
return Err(self.files.fail(&whole, refused));
}
Upload::start(self.files.clone(), whole, self.options)
}
pub fn delete(self) -> Result<()> {
let whole = self.files.whole(&self.path)?;
#[cfg(feature = "sql")]
if let Some(tx) = self.tx {
let deleting = self.files.deleting(&whole, self.options.if_match);
let deleted = super::tx::on_file(tx, self.files, |sql| deleting(sql).map(drop));
return deleted.map_err(|error| self.files.fail(&whole, error));
}
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()?);
#[cfg(feature = "sql")]
if let Some(tx) = self.tx {
let copied = refuse_onto_itself(&source, &target).and_then(|()| {
let copying = self.files.copying(&source, &target, &self.options, rename);
super::tx::on_file(tx, self.files, |sql| copying(sql).map(|(info, _)| info))
});
return copied.map_err(|error| self.files.fail(&target, error));
}
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 = self.options.condition(when_there);
self.write_all(bytes, condition)
}
fn write_all(self, bytes: &[u8], condition: Condition) -> Result<Option<FileInfo>> {
let whole = self.checked()?;
#[cfg(feature = "sql")]
if let Some(tx) = self.tx {
let written = super::tx::write_in(tx, self.files, (&whole, &self.options), bytes, condition);
return written.map_err(|error| self.files.fail(&whole, error));
}
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;