use std::fmt;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use super::Store;
use super::oneshot::{Answer, pending};
use super::run;
use crate::blobs::{CallOptions, FileInfo, Freed};
use crate::polled::{self, Lead};
use crate::pool::Pool;
use crate::sync::lock;
use crate::{Error, Key, Result};
mod cache;
mod filling;
mod list;
mod read;
mod upload;
pub use cache::SetMaxSize;
pub use list::{All, List};
pub use read::StoredFile;
pub use upload::Upload;
impl Store {
pub fn files(&self, name: &str) -> FilesBuilder<'_> {
FilesBuilder { builder: self.blocking().files(name), pool: self.pool() }
}
}
#[derive(Debug)]
pub struct FilesBuilder<'s> {
builder: crate::blobs::FilesBuilder<'s>,
pool: &'s Arc<Pool>,
}
impl<'s> FilesBuilder<'s> {
#[cfg(feature = "sql")]
pub(crate) fn new(builder: crate::blobs::FilesBuilder<'s>, pool: &'s Arc<Pool>) -> Self {
FilesBuilder { builder, pool }
}
pub fn ttl(mut self, ttl: Duration) -> Self {
self.builder = self.builder.ttl(ttl);
self
}
pub fn idle(mut self, idle: Duration) -> Self {
self.builder = self.builder.idle(idle);
self
}
pub fn max_file_size(mut self, bytes: u64) -> Self {
self.builder = self.builder.max_file_size(bytes);
self
}
pub fn max_size(mut self, bytes: u64) -> Self {
self.builder = self.builder.max_size(bytes);
self
}
pub fn when_full(mut self, when_full: crate::blobs::WhenFull) -> Self {
self.builder = self.builder.when_full(when_full);
self
}
pub fn open(self) -> Result<Files> {
Ok(Files { blocking: self.builder.open()?, pool: Arc::clone(self.pool) })
}
}
#[derive(Clone)]
pub struct Files {
blocking: crate::blobs::Files,
pool: Arc<Pool>,
}
impl fmt::Debug for Files {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.blocking, f)
}
}
impl From<crate::blobs::Files> for Files {
fn from(blocking: crate::blobs::Files) -> Files {
let pool = Arc::clone(&blocking.blobs.pool);
Files { blocking, pool }
}
}
impl Files {
pub fn blocking(&self) -> &crate::blobs::Files {
&self.blocking
}
pub fn folder(&self, segment: impl Key) -> Files {
Files { blocking: self.blocking.folder(segment), pool: Arc::clone(&self.pool) }
}
pub fn key(&self, path: &str) -> FileCall<'_> {
FileCall { call: self.blocking.key(path), pool: &self.pool }
}
pub fn put(
&self,
path: &str,
bytes: impl AsRef<[u8]> + Send + 'static,
) -> impl Future<Output = Result<FileInfo>> + Send + 'static {
self.key(path).put(bytes)
}
pub fn create(
&self,
path: &str,
bytes: impl AsRef<[u8]> + Send + 'static,
) -> impl Future<Output = Result<bool>> + Send + 'static {
self.key(path).create(bytes)
}
pub fn upload(&self, path: &str) -> impl Future<Output = Result<Upload>> + Send + 'static {
self.key(path).upload()
}
pub fn get(&self, path: &str) -> impl Future<Output = Result<Option<StoredFile>>> + Send + 'static {
let (files, path, pool) = (self.blocking.clone(), path.to_owned(), Arc::clone(&self.pool));
let opened = run::point(&self.pool, describe(&files, &path, "a get"), move || files.get(&path));
async move { Ok(opened.await?.map(|file| StoredFile::new(file, pool))) }
}
pub fn head(&self, path: &str) -> impl Future<Output = Result<Option<FileInfo>>> + Send + 'static {
let (files, path) = (self.blocking.clone(), path.to_owned());
run::point(&self.pool, describe(&files, &path, "a head"), move || files.head(&path))
}
pub fn delete(&self, path: &str) -> impl Future<Output = Result<()>> + Send + 'static {
self.key(path).delete()
}
pub fn copy(&self, from: &str, to: &str) -> impl Future<Output = Result<FileInfo>> + Send + 'static {
self.key(to).copy_from(from)
}
pub fn rename(&self, from: &str, to: &str) -> impl Future<Output = Result<FileInfo>> + Send + 'static {
self.key(to).rename_from(from)
}
pub fn expire(&self, path: &str, after: Duration) -> impl Future<Output = Result<bool>> + Send + 'static {
let owned = Owned { path: path.to_owned(), ..self.owned() };
write(
owned,
"an expiry",
move |owned, done| owned.files.expire_then(&owned.path, after, done),
move |owned| owned.files.expire(&owned.path, after),
)
}
fn owned(&self) -> Owned {
Owned {
files: self.blocking.clone(),
path: String::new(),
options: CallOptions::default(),
pool: Arc::clone(&self.pool),
}
}
}
#[derive(Debug)]
#[must_use = "a call does nothing until its verb, and its verb nothing until it is awaited"]
pub struct FileCall<'f> {
call: crate::blobs::FileCall<'f>,
pool: &'f Arc<Pool>,
}
impl FileCall<'_> {
pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
self.call = self.call.content_type(content_type);
self
}
pub fn meta(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.call = self.call.meta(name, value);
self
}
pub fn ttl(mut self, ttl: Duration) -> Self {
self.call = self.call.ttl(ttl);
self
}
pub fn if_match(mut self, etag: impl Into<String>) -> Self {
self.call = self.call.if_match(etag);
self
}
pub fn size(mut self, bytes: u64) -> Self {
self.call = self.call.size(bytes);
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.call = self.call.timeout(timeout);
self
}
pub fn get_or_create<T, E, W, F>(
self,
work: W,
) -> impl Future<Output = std::result::Result<StoredFile, E>> + Send + use<T, E, W, F>
where
T: Into<crate::blobs::Fill> + Send,
E: From<Error> + fmt::Display + Send + 'static,
W: FnMut() -> F + Send,
F: Future<Output = std::result::Result<T, E>> + Send,
{
let whole = self.call.to_get_or_create();
let owned = self.owned();
async move { filling::get_or_create(owned, whole?, work).await }
}
pub fn put(
self,
bytes: impl AsRef<[u8]> + Send + 'static,
) -> impl Future<Output = Result<FileInfo>> + Send + 'static {
let written = self.written(bytes, false);
async move { written.await?.ok_or_else(|| Error::internal("a put that wrote nothing")) }
}
pub fn create(
self,
bytes: impl AsRef<[u8]> + Send + 'static,
) -> impl Future<Output = Result<bool>> + Send + 'static {
let written = self.written(bytes, true);
async move { written.await.map(|info| info.is_some()) }
}
pub fn upload(self) -> impl Future<Output = Result<Upload>> + Send + 'static {
let owned = self.owned();
async move {
let Owned { files, path, options, pool } = owned;
let (answer, started) = pending(describe(&files, &path, "an upload"));
let _waiting = files.call(&path, options).upload_then(move |upload| answer.send(upload));
let upload = started.await?;
Ok(Upload::new(upload, files, path, pool))
}
}
pub fn delete(self) -> impl Future<Output = Result<()>> + Send + 'static {
write(self.owned(), "a delete", |owned, done| owned.call().delete_then(done), |owned| owned.call().delete())
}
pub fn copy_from(self, from: &str) -> impl Future<Output = Result<FileInfo>> + Send + 'static {
self.copied(from, false)
}
pub fn rename_from(self, from: &str) -> impl Future<Output = Result<FileInfo>> + Send + 'static {
self.copied(from, true)
}
fn copied(self, from: &str, rename: bool) -> impl Future<Output = Result<FileInfo>> + Send + 'static {
let (source, again) = (from.to_owned(), from.to_owned());
write(
self.owned(),
if rename { "a rename" } else { "a copy" },
move |owned, done| owned.call().copied_then(&source, rename, done),
move |owned| if rename { owned.call().rename_from(&again) } else { owned.call().copy_from(&again) },
)
}
fn written(
self,
bytes: impl AsRef<[u8]> + Send + 'static,
create: bool,
) -> impl Future<Output = Result<Option<FileInfo>>> + Send + 'static {
let owned = self.owned();
let lead = run::lead_on(&owned.pool);
async move {
let what = owned.what(if create { "a create" } else { "a put" });
if passed_home(&owned.files) {
return run::passed_on(what, move || owned.call().written(bytes.as_ref(), create)).await;
}
let (answer, answered) = pending(what);
polled::leading_on(&lead.clone(), || Putting { owned, lead, create, answer }.start(bytes));
answered.await
}
}
fn owned(self) -> Owned {
let (files, path, options) = self.call.into_parts();
Owned { files: files.clone(), path, options, pool: Arc::clone(self.pool) }
}
}
struct Owned {
files: crate::blobs::Files,
path: String,
options: CallOptions,
pool: Arc<Pool>,
}
impl Owned {
fn call(&self) -> crate::blobs::FileCall<'_> {
self.files.call(&self.path, self.options.clone())
}
fn what(&self, verb: &str) -> String {
describe(&self.files, &self.path, verb)
}
}
fn describe(files: &crate::blobs::Files, path: &str, verb: &str) -> String {
format!("{}: {verb}", label(files, path))
}
fn label(files: &crate::blobs::Files, path: &str) -> String {
match format!("{}{path}", files.folder.prefix()) {
whole if whole.is_empty() => files.describe(),
whole => format!("{}: {whole:?}", files.describe()),
}
}
struct Putting {
owned: Owned,
lead: Lead,
create: bool,
answer: Answer<Option<FileInfo>>,
}
impl Putting {
fn start(self, bytes: impl AsRef<[u8]> + Send + 'static) {
let (files, path, options) = (self.owned.files.clone(), self.owned.path.clone(), self.owned.options.clone());
let kept = Arc::new(Mutex::new(None));
let waiter = Arc::clone(&kept);
let waiting = files.call(&path, options).upload_then(move |upload| {
let _answered = waiter;
self.publish(upload, bytes);
});
*lock(&kept) = waiting;
}
fn publish(self, upload: Result<crate::blobs::Upload>, bytes: impl AsRef<[u8]> + Send + 'static) {
let Putting { owned, lead, create, answer } = self;
let mut upload = match upload {
Ok(upload) => upload,
Err(error) => return answer.send(Err(error)),
};
if !upload.stays_in_memory(bytes.as_ref().len()) {
return on_the_pool(&owned.pool, answer, move || {
upload.take(bytes.as_ref())?;
upload.publish(create)
});
}
if let Err(error) = upload.take(bytes.as_ref()) {
return answer.send(Err(error));
}
if upload.inline_id().is_none() {
return on_the_pool(&owned.pool, answer, move || upload.publish(create));
}
let done = answering(&owned.files, &owned.pool, answer);
polled::leading_on(&lead, || upload.publish_inline_then(create, done));
}
}
type Answering<T> = Box<dyn FnOnce(Result<(T, Freed)>) + Send>;
fn answering<T: Send + 'static>(files: &crate::blobs::Files, pool: &Arc<Pool>, answer: Answer<T>) -> Answering<T> {
let (files, pool) = (files.clone(), Arc::clone(pool));
Box::new(move |written| match written {
Ok((value, freed)) if !freed.is_empty() => pool.run_always(Box::new(move || {
files.remove_freed(&freed);
answer.send(Ok(value));
})),
written => answer.send(written.map(|(value, _)| value)),
})
}
fn write<T: Send + 'static>(
owned: Owned,
verb: &str,
submit: impl FnOnce(&Owned, Answering<T>) + Send + 'static,
on_a_copy: impl FnOnce(&Owned) -> Result<T> + Send + 'static,
) -> impl Future<Output = Result<T>> + Send + 'static {
let what = owned.what(verb);
async move {
if passed_home(&owned.files) {
return run::passed_on(what, move || on_a_copy(&owned)).await;
}
let pool = Arc::clone(&owned.pool);
run::write(&pool, what, move |answer| {
let done = answering(&owned.files, &owned.pool, answer);
submit(&owned, done);
})
.await
}
}
fn passed_home(files: &crate::blobs::Files) -> bool {
#[cfg(feature = "replication")]
return files.is_copy();
#[cfg(not(feature = "replication"))]
{
let _ = files;
false
}
}
fn on_the_pool<T: Send + 'static>(
pool: &Arc<Pool>,
answer: Answer<T>,
work: impl FnOnce() -> Result<T> + Send + 'static,
) {
pool.run(Box::new(move || match catch_unwind(AssertUnwindSafe(work)) {
Ok(outcome) => answer.send(outcome),
Err(payload) => answer.panicked(payload),
}));
}
#[cfg(feature = "sql")]
impl crate::transaction::sealed::Sealed for Files {}
#[cfg(feature = "sql")]
impl crate::TxHandle for Files {
type InTx<'h> = crate::blobs::TxFiles<'h>;
fn in_tx<'h>(&'h self, tx: &'h crate::Transaction<'h>) -> crate::blobs::TxFiles<'h> {
crate::TxHandle::in_tx(&self.blocking, tx)
}
}
#[cfg(test)]
#[path = "blobs_tests.rs"]
mod tests;