use std::collections::BTreeMap;
use std::future::{poll_fn, Future, IntoFuture};
use std::marker::PhantomData;
use std::ops::{Bound, RangeBounds};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, SystemTime};
use bytes::Bytes;
use encore_sdk_core::objects;
use futures_core::future::BoxFuture;
use futures_core::Stream;
use tokio::io::AsyncRead;
use tokio_util::io::StreamReader;
use crate::perm::{Flag, Granted, No};
use crate::runtime::core;
pub use encore_sdk_core::objects::{
ByteRange, ListEntry, ObjectAttrs, ObjectVersion, Revision, StorageClass,
};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("object not found")]
NotFound,
#[error("precondition failed")]
PreconditionFailed,
#[error("object is retained")]
Retained,
#[error("invalid argument: {0}")]
InvalidArgument(String),
#[error(transparent)]
Other(Box<dyn std::error::Error + Send + Sync>),
}
impl Error {
fn other(message: impl Into<String>) -> Self {
Error::Other(message.into().into())
}
}
fn obj_err(err: objects::Error) -> Error {
match err {
objects::Error::NotFound => Error::NotFound,
objects::Error::PreconditionFailed => Error::PreconditionFailed,
objects::Error::Retained => Error::Retained,
objects::Error::InvalidArgument(message) => Error::InvalidArgument(message.into_owned()),
err @ (objects::Error::Internal(_) | objects::Error::Other(_)) => {
Error::Other(Box::new(err))
}
}
}
fn test_err(err: crate::Error) -> Error {
Error::Other(Box::new(err))
}
pub struct Download {
inner: objects::DownloadStream,
}
impl Download {
pub async fn next(&mut self) -> Option<Result<Bytes, Error>> {
poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
}
pub async fn bytes(mut self) -> Result<Vec<u8>, Error> {
let mut bytes = Vec::new();
while let Some(chunk) = self.next().await {
bytes.extend_from_slice(&chunk?);
}
Ok(bytes)
}
pub fn into_async_read(self) -> impl AsyncRead + Unpin + Send + 'static {
StreamReader::new(ChunkErrors(self))
}
}
impl Stream for Download {
type Item = Result<Bytes, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut()
.inner
.as_mut()
.poll_next(cx)
.map(|chunk| chunk.map(|chunk| chunk.map_err(obj_err)))
}
}
struct ChunkErrors(Download);
impl Stream for ChunkErrors {
type Item = std::io::Result<Bytes>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.get_mut().0)
.poll_next(cx)
.map(|chunk| chunk.map(|chunk| chunk.map_err(std::io::Error::other)))
}
}
pub struct ListIterator {
inner: objects::ListIterator,
}
impl ListIterator {
pub async fn next(&mut self) -> Option<Result<ListEntry, Error>> {
poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
}
}
impl Stream for ListIterator {
type Item = Result<ListEntry, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.get_mut().inner)
.poll_next(cx)
.map(|entry| entry.map(|entry| entry.map_err(obj_err)))
}
}
pub struct VersionIterator {
inner: objects::VersionIterator,
}
impl VersionIterator {
pub async fn next(&mut self) -> Option<Result<ObjectVersion, Error>> {
poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
}
}
impl Stream for VersionIterator {
type Item = Result<ObjectVersion, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.get_mut().inner)
.poll_next(cx)
.map(|version| version.map(|version| version.map_err(obj_err)))
}
}
struct ChunkReader<S>(std::sync::Mutex<Pin<Box<S>>>);
impl<S, B, E> Stream for ChunkReader<S>
where
S: Stream<Item = Result<B, E>>,
B: Into<Bytes>,
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
type Item = std::io::Result<Bytes>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let stream = self
.get_mut()
.0
.get_mut()
.unwrap_or_else(|e| e.into_inner());
stream
.as_mut()
.poll_next(cx)
.map(|chunk| chunk.map(|chunk| chunk.map(Into::into).map_err(std::io::Error::other)))
}
}
pub struct UploadBody(Body);
enum Body {
Bytes(Bytes),
Reader(Box<dyn AsyncRead + Unpin + Send + Sync + 'static>),
}
impl UploadBody {
pub fn reader(reader: impl AsyncRead + Unpin + Send + Sync + 'static) -> Self {
UploadBody(Body::Reader(Box::new(reader)))
}
pub fn chunks<S, B, E>(chunks: S) -> Self
where
S: Stream<Item = Result<B, E>> + Send + 'static,
B: Into<Bytes> + 'static,
E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
{
Self::reader(StreamReader::new(ChunkReader(std::sync::Mutex::new(
Box::pin(chunks),
))))
}
pub fn into_async_read(self) -> impl AsyncRead + Unpin + Send + Sync + 'static {
self.into_reader()
}
fn into_reader(self) -> Box<dyn AsyncRead + Unpin + Send + Sync + 'static> {
match self.0 {
Body::Bytes(bytes) => Box::new(std::io::Cursor::new(bytes)),
Body::Reader(reader) => reader,
}
}
}
impl From<Bytes> for UploadBody {
fn from(bytes: Bytes) -> Self {
UploadBody(Body::Bytes(bytes))
}
}
impl From<Vec<u8>> for UploadBody {
fn from(bytes: Vec<u8>) -> Self {
Bytes::from(bytes).into()
}
}
impl From<&'static [u8]> for UploadBody {
fn from(bytes: &'static [u8]) -> Self {
Bytes::from_static(bytes).into()
}
}
impl From<String> for UploadBody {
fn from(text: String) -> Self {
Bytes::from(text).into()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedUploadUrl {
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedDownloadUrl {
pub url: String,
}
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
pub struct LifecycleRule {
prefix: Option<&'static str>,
move_to_infrequent_after_days: Option<u32>,
move_to_cold_after_days: Option<u32>,
delete_after_days: Option<u32>,
delete_noncurrent_after_days: Option<u32>,
keep_noncurrent_versions: Option<u32>,
}
impl LifecycleRule {
pub const fn new() -> Self {
Self {
prefix: None,
move_to_infrequent_after_days: None,
move_to_cold_after_days: None,
delete_after_days: None,
delete_noncurrent_after_days: None,
keep_noncurrent_versions: None,
}
}
pub const fn prefix(mut self, prefix: &'static str) -> Self {
self.prefix = Some(prefix);
self
}
pub const fn move_to_infrequent_after_days(mut self, days: u32) -> Self {
self.move_to_infrequent_after_days = Some(days);
self
}
pub const fn move_to_cold_after_days(mut self, days: u32) -> Self {
self.move_to_cold_after_days = Some(days);
self
}
pub const fn delete_after_days(mut self, days: u32) -> Self {
self.delete_after_days = Some(days);
self
}
pub const fn delete_noncurrent_after_days(mut self, days: u32) -> Self {
self.delete_noncurrent_after_days = Some(days);
self
}
pub const fn keep_noncurrent_versions(mut self, count: u32) -> Self {
self.keep_noncurrent_versions = Some(count);
self
}
}
impl Default for LifecycleRule {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Retention {
#[allow(dead_code)]
days: u32,
}
impl Retention {
pub const fn days(days: u32) -> Self {
Self { days }
}
}
pub struct Bucket {
name: &'static str,
#[allow(dead_code)]
versioned: bool,
#[allow(dead_code)]
public: bool,
#[allow(dead_code)]
storage_class: Option<StorageClass>,
#[allow(dead_code)]
lifecycle: &'static [LifecycleRule],
#[allow(dead_code)]
retention: Option<Retention>,
#[allow(dead_code)]
object_retention: bool,
}
impl Bucket {
pub const fn new(name: &'static str) -> Self {
Self {
name,
versioned: false,
public: false,
storage_class: None,
lifecycle: &[],
retention: None,
object_retention: false,
}
}
pub const fn public(mut self) -> Self {
self.public = true;
self
}
pub const fn versioned(mut self) -> Self {
self.versioned = true;
self
}
pub const fn storage_class(mut self, class: StorageClass) -> Self {
self.storage_class = Some(class);
self
}
pub const fn lifecycle(mut self, rules: &'static [LifecycleRule]) -> Self {
self.lifecycle = rules;
self
}
pub const fn retention(mut self, retention: Retention) -> Self {
self.retention = Some(retention);
self
}
pub const fn object_retention(mut self) -> Self {
self.object_retention = true;
self
}
pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
self
}
pub const fn named(name: &'static str) -> Self {
Self::new(name)
}
pub const fn reference<P: BucketPerms>(&'static self) -> BucketRef<P::Id> {
BucketRef {
bucket: self,
perms: PhantomData,
}
}
fn resolve(&self) -> Result<objects::Bucket, Error> {
if let Some(test) = crate::testing::active().map_err(test_err)? {
return test.bucket(self.name).map_err(test_err);
}
core()
.objects()
.bucket(self.name.into())
.ok_or_else(|| Error::other(format!("bucket {:?} is not configured", self.name)))
}
fn object(&self, key: &str) -> Result<objects::Object, Error> {
Ok(self.resolve()?.object(key.to_string()))
}
pub fn list(&self) -> ListRequest<'_> {
ListRequest::new(self)
}
pub fn list_versions(&self) -> ListVersionsRequest<'_> {
ListVersionsRequest::new(self)
}
pub fn exists(&self, key: &str) -> ExistsRequest<'_> {
ExistsRequest::new(self, key)
}
pub fn attrs(&self, key: &str) -> AttrsRequest<'_> {
AttrsRequest::new(self, key)
}
pub fn upload(&self, key: &str, data: impl Into<UploadBody>) -> UploadRequest<'_> {
UploadRequest::new(self, key, data.into())
}
pub fn upload_if_match(
&self,
key: &str,
data: impl Into<UploadBody>,
revision: Revision,
) -> UploadIfMatchRequest<'_> {
UploadIfMatchRequest::new(self, key, data.into(), revision)
}
pub fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'_> {
UpdateAttrsRequest::new(self, key)
}
pub fn extend_retention(&self, key: &str, until: SystemTime) -> ExtendRetentionRequest<'_> {
ExtendRetentionRequest::new(self, key, until)
}
pub fn download(&self, key: &str) -> DownloadRequest<'_> {
DownloadRequest::new(self, key)
}
pub fn download_stream(&self, key: &str) -> DownloadStreamRequest<'_> {
DownloadStreamRequest::new(self, key)
}
pub fn remove(&self, key: &str) -> RemoveRequest<'_> {
RemoveRequest::new(self, key)
}
pub async fn remove_if_match(&self, key: &str, revision: Revision) -> Result<(), Error> {
let options = objects::DeleteOptions {
version: None,
if_match: Some(revision),
};
self.object(key)?.delete(options).await.map_err(obj_err)
}
pub fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'_> {
SignedUploadUrlRequest::new(self, key)
}
pub fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'_> {
SignedDownloadUrlRequest::new(self, key)
}
pub fn public_url(&self, key: &str) -> Result<String, Error> {
self.object(key)?.public_url().map_err(public_url_err)
}
}
fn public_url_err(err: objects::PublicUrlError) -> Error {
match err {
objects::PublicUrlError::PrivateBucket | objects::PublicUrlError::InvalidObjectName => {
Error::InvalidArgument(err.to_string())
}
objects::PublicUrlError::NoopBucket => Error::Other(Box::new(err)),
}
}
macro_rules! into_future {
($request:ident => $output:ty, $trait:ident::$run:ident) => {
impl<'a> IntoFuture for $request<'a, Bucket> {
type Output = Result<$output, Error>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
let bucket = self.on;
self.send(bucket)
}
}
impl<'a, T: $trait + ?Sized> IntoFuture for $request<'a, T> {
type Output = Result<$output, Error>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
let on = self.on;
Box::pin(on.$run(self))
}
}
};
}
macro_rules! version_setter {
() => {
pub fn version(mut self, version: impl Into<String>) -> Self {
self.version = Some(version.into());
self
}
};
}
macro_rules! upload_setters {
() => {
pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
self.content_type = Some(content_type.into());
self
}
pub fn cache_control(mut self, cache_control: impl Into<String>) -> Self {
self.cache_control = Some(cache_control.into());
self
}
pub fn content_disposition(mut self, content_disposition: impl Into<String>) -> Self {
self.content_disposition = Some(content_disposition.into());
self
}
pub fn metadata<K, V>(mut self, metadata: impl IntoIterator<Item = (K, V)>) -> Self
where
K: Into<String>,
V: Into<String>,
{
extend(&mut self.metadata, metadata);
self
}
pub fn storage_class(mut self, class: StorageClass) -> Self {
self.storage_class = Some(class);
self
}
pub fn retain_until(mut self, until: SystemTime) -> Self {
self.retain_until = Some(until);
self
}
};
}
fn extend<K: Into<String>, V: Into<String>>(
into: &mut BTreeMap<String, String>,
pairs: impl IntoIterator<Item = (K, V)>,
) {
into.extend(pairs.into_iter().map(|(k, v)| (k.into(), v.into())));
}
fn byte_range(range: impl RangeBounds<u64>) -> ByteRange {
let offset = match range.start_bound() {
Bound::Included(&start) => start,
Bound::Excluded(&start) => start.saturating_add(1),
Bound::Unbounded => 0,
};
let length = match range.end_bound() {
Bound::Included(&end) => Some(end.saturating_sub(offset).saturating_add(1)),
Bound::Excluded(&end) => Some(end.saturating_sub(offset)),
Bound::Unbounded => None,
};
let length = match range.end_bound() {
Bound::Included(&end) if end < offset => Some(0),
_ => length,
};
ByteRange { offset, length }
}
const SIGNED_URL_TTL: Duration = Duration::from_secs(60 * 60);
pub struct UploadRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub data: UploadBody,
pub content_type: Option<String>,
pub cache_control: Option<String>,
pub content_disposition: Option<String>,
pub metadata: BTreeMap<String, String>,
pub storage_class: Option<StorageClass>,
pub retain_until: Option<SystemTime>,
pub not_exists: bool,
}
impl<'a, T: ?Sized> UploadRequest<'a, T> {
fn new(on: &'a T, key: &str, data: UploadBody) -> Self {
Self {
on,
key: key.to_string(),
data,
content_type: None,
cache_control: None,
content_disposition: None,
metadata: BTreeMap::new(),
storage_class: None,
retain_until: None,
not_exists: false,
}
}
upload_setters!();
pub fn not_exists(mut self) -> Self {
self.not_exists = true;
self
}
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
let preconditions = self.not_exists.then_some(objects::UploadPreconditions {
not_exists: Some(true),
if_match: None,
});
let options = objects::UploadOptions {
content_type: self.content_type,
cache_control: self.cache_control,
content_disposition: self.content_disposition,
metadata: self.metadata,
storage_class: self.storage_class,
retain_until: self.retain_until,
preconditions,
};
upload(bucket, self.key, self.data, options)
}
}
into_future!(UploadRequest => ObjectAttrs, Uploader::run_upload);
pub struct UploadIfMatchRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub data: UploadBody,
pub revision: Revision,
pub content_type: Option<String>,
pub cache_control: Option<String>,
pub content_disposition: Option<String>,
pub metadata: BTreeMap<String, String>,
pub storage_class: Option<StorageClass>,
pub retain_until: Option<SystemTime>,
}
impl<'a, T: ?Sized> UploadIfMatchRequest<'a, T> {
fn new(on: &'a T, key: &str, data: UploadBody, revision: Revision) -> Self {
Self {
on,
key: key.to_string(),
data,
revision,
content_type: None,
cache_control: None,
content_disposition: None,
metadata: BTreeMap::new(),
storage_class: None,
retain_until: None,
}
}
upload_setters!();
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
let options = objects::UploadOptions {
content_type: self.content_type,
cache_control: self.cache_control,
content_disposition: self.content_disposition,
metadata: self.metadata,
storage_class: self.storage_class,
retain_until: self.retain_until,
preconditions: Some(objects::UploadPreconditions {
not_exists: None,
if_match: Some(self.revision),
}),
};
upload(bucket, self.key, self.data, options)
}
}
into_future!(UploadIfMatchRequest => ObjectAttrs, IfMatchUploader::run_upload_if_match);
fn upload(
bucket: &Bucket,
key: String,
data: UploadBody,
options: objects::UploadOptions,
) -> BoxFuture<'_, Result<ObjectAttrs, Error>> {
Box::pin(async move {
bucket
.object(&key)?
.upload(data.into_reader(), options)
.await
.map_err(obj_err)
})
}
pub struct UpdateAttrsRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub content_type: Option<String>,
pub cache_control: Option<String>,
pub content_disposition: Option<String>,
pub metadata: Option<BTreeMap<String, String>>,
pub version: Option<String>,
pub if_match: Option<Revision>,
}
impl<'a, T: ?Sized> UpdateAttrsRequest<'a, T> {
fn new(on: &'a T, key: &str) -> Self {
Self {
on,
key: key.to_string(),
content_type: None,
cache_control: None,
content_disposition: None,
metadata: None,
version: None,
if_match: None,
}
}
pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
self.content_type = Some(content_type.into());
self
}
pub fn cache_control(mut self, cache_control: impl Into<String>) -> Self {
self.cache_control = Some(cache_control.into());
self
}
pub fn content_disposition(mut self, content_disposition: impl Into<String>) -> Self {
self.content_disposition = Some(content_disposition.into());
self
}
pub fn metadata<K, V>(mut self, metadata: impl IntoIterator<Item = (K, V)>) -> Self
where
K: Into<String>,
V: Into<String>,
{
extend(self.metadata.get_or_insert_default(), metadata);
self
}
version_setter!();
pub fn if_match(mut self, revision: Revision) -> Self {
self.if_match = Some(revision);
self
}
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
let attrs = objects::UpdateAttrs {
content_type: self.content_type,
cache_control: self.cache_control,
content_disposition: self.content_disposition,
metadata: self.metadata,
};
let options = objects::UpdateAttrsOptions {
version: self.version,
if_match: self.if_match,
};
let key = self.key;
Box::pin(async move {
bucket
.object(&key)?
.update_attrs(attrs, options)
.await
.map_err(obj_err)
})
}
}
into_future!(UpdateAttrsRequest => ObjectAttrs, AttrsUpdater::run_update_attrs);
pub struct ExtendRetentionRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub until: SystemTime,
pub version: Option<String>,
}
impl<'a, T: ?Sized> ExtendRetentionRequest<'a, T> {
fn new(on: &'a T, key: &str, until: SystemTime) -> Self {
Self {
on,
key: key.to_string(),
until,
version: None,
}
}
version_setter!();
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
let (key, until) = (self.key, self.until);
let options = objects::ExtendRetentionOptions {
version: self.version,
};
Box::pin(async move {
bucket
.object(&key)?
.extend_retention(until, options)
.await
.map_err(obj_err)
})
}
}
into_future!(ExtendRetentionRequest => ObjectAttrs, AttrsUpdater::run_extend_retention);
pub struct DownloadRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub version: Option<String>,
pub range: Option<ByteRange>,
}
pub struct DownloadStreamRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub version: Option<String>,
pub range: Option<ByteRange>,
}
macro_rules! download_setters {
() => {
version_setter!();
pub fn range(mut self, range: impl RangeBounds<u64>) -> Self {
self.range = Some(byte_range(range));
self
}
fn options(&self) -> objects::DownloadOptions {
objects::DownloadOptions {
version: self.version.clone(),
range: self.range,
}
}
};
}
impl<'a, T: ?Sized> DownloadRequest<'a, T> {
fn new(on: &'a T, key: &str) -> Self {
Self {
on,
key: key.to_string(),
version: None,
range: None,
}
}
download_setters!();
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<Vec<u8>, Error>> {
let options = self.options();
let key = self.key;
Box::pin(async move {
bucket
.object(&key)?
.download_all(options)
.await
.map_err(obj_err)
})
}
}
into_future!(DownloadRequest => Vec<u8>, Downloader::run_download);
impl<'a, T: ?Sized> DownloadStreamRequest<'a, T> {
fn new(on: &'a T, key: &str) -> Self {
Self {
on,
key: key.to_string(),
version: None,
range: None,
}
}
download_setters!();
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<Download, Error>> {
let options = self.options();
let key = self.key;
Box::pin(async move {
bucket
.object(&key)?
.download_stream(options)
.await
.map(|inner| Download { inner })
.map_err(obj_err)
})
}
}
into_future!(DownloadStreamRequest => Download, Downloader::run_download_stream);
pub struct AttrsRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub version: Option<String>,
}
impl<'a, T: ?Sized> AttrsRequest<'a, T> {
fn new(on: &'a T, key: &str) -> Self {
Self {
on,
key: key.to_string(),
version: None,
}
}
version_setter!();
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
let key = self.key;
let options = objects::AttrsOptions {
version: self.version,
};
Box::pin(async move { bucket.object(&key)?.attrs(options).await.map_err(obj_err) })
}
}
into_future!(AttrsRequest => ObjectAttrs, Attrser::run_attrs);
pub struct ExistsRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub version: Option<String>,
}
impl<'a, T: ?Sized> ExistsRequest<'a, T> {
fn new(on: &'a T, key: &str) -> Self {
Self {
on,
key: key.to_string(),
version: None,
}
}
version_setter!();
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<bool, Error>> {
let key = self.key;
let options = objects::ExistsOptions {
version: self.version,
};
Box::pin(async move { bucket.object(&key)?.exists(options).await.map_err(obj_err) })
}
}
into_future!(ExistsRequest => bool, Attrser::run_exists);
pub struct RemoveRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub version: Option<String>,
}
impl<'a, T: ?Sized> RemoveRequest<'a, T> {
fn new(on: &'a T, key: &str) -> Self {
Self {
on,
key: key.to_string(),
version: None,
}
}
version_setter!();
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<(), Error>> {
let key = self.key;
let options = objects::DeleteOptions {
version: self.version,
if_match: None,
};
Box::pin(async move { bucket.object(&key)?.delete(options).await.map_err(obj_err) })
}
}
into_future!(RemoveRequest => (), Remover::run_remove);
pub struct ListRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub prefix: Option<String>,
pub limit: Option<u64>,
pub delimiter: Option<String>,
}
impl<'a, T: ?Sized> ListRequest<'a, T> {
fn new(on: &'a T) -> Self {
Self {
on,
prefix: None,
limit: None,
delimiter: None,
}
}
pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = Some(prefix.into());
self
}
pub fn limit(mut self, limit: u64) -> Self {
self.limit = Some(limit);
self
}
pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
self.delimiter = Some(delimiter.into());
self
}
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ListIterator, Error>> {
let options = objects::ListOptions {
prefix: self.prefix,
limit: self.limit,
delimiter: self.delimiter,
};
Box::pin(async move {
bucket
.resolve()?
.list(options)
.await
.map(|inner| ListIterator { inner })
.map_err(obj_err)
})
}
}
into_future!(ListRequest => ListIterator, Lister::run_list);
pub struct ListVersionsRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub prefix: Option<String>,
pub limit: Option<u64>,
}
impl<'a, T: ?Sized> ListVersionsRequest<'a, T> {
fn new(on: &'a T) -> Self {
Self {
on,
prefix: None,
limit: None,
}
}
pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = Some(prefix.into());
self
}
pub fn limit(mut self, limit: u64) -> Self {
self.limit = Some(limit);
self
}
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<VersionIterator, Error>> {
let options = objects::ListOptions {
prefix: self.prefix,
limit: self.limit,
delimiter: None,
};
Box::pin(async move {
bucket
.resolve()?
.list_versions(options)
.await
.map(|inner| VersionIterator { inner })
.map_err(obj_err)
})
}
}
into_future!(ListVersionsRequest => VersionIterator, Lister::run_list_versions);
pub struct SignedUploadUrlRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub ttl: Option<Duration>,
}
impl<'a, T: ?Sized> SignedUploadUrlRequest<'a, T> {
fn new(on: &'a T, key: &str) -> Self {
Self {
on,
key: key.to_string(),
ttl: None,
}
}
pub fn ttl(mut self, ttl: Duration) -> Self {
self.ttl = Some(ttl);
self
}
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<SignedUploadUrl, Error>> {
let key = self.key;
let options = objects::UploadUrlOptions {
ttl: self.ttl.unwrap_or(SIGNED_URL_TTL),
};
Box::pin(async move {
bucket
.object(&key)?
.signed_upload_url(options)
.await
.map(|url| SignedUploadUrl { url })
.map_err(obj_err)
})
}
}
into_future!(SignedUploadUrlRequest => SignedUploadUrl, SignedUploader::run_signed_upload_url);
pub struct SignedDownloadUrlRequest<'a, T: ?Sized = Bucket> {
on: &'a T,
pub key: String,
pub ttl: Option<Duration>,
}
impl<'a, T: ?Sized> SignedDownloadUrlRequest<'a, T> {
fn new(on: &'a T, key: &str) -> Self {
Self {
on,
key: key.to_string(),
ttl: None,
}
}
pub fn ttl(mut self, ttl: Duration) -> Self {
self.ttl = Some(ttl);
self
}
fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<SignedDownloadUrl, Error>> {
let key = self.key;
let options = objects::DownloadUrlOptions {
ttl: self.ttl.unwrap_or(SIGNED_URL_TTL),
};
Box::pin(async move {
bucket
.object(&key)?
.signed_download_url(options)
.await
.map(|url| SignedDownloadUrl { url })
.map_err(obj_err)
})
}
}
into_future!(
SignedDownloadUrlRequest => SignedDownloadUrl,
SignedDownloader::run_signed_download_url
);
pub mod perms {
use super::{sealed::Sealed, BucketPerms};
use crate::perm::{No, Yes};
macro_rules! perm {
($(#[$doc:meta])* $name:ident: $upload:ident, $signed_upload:ident, $download:ident,
$signed_download:ident, $attrs:ident, $list:ident, $remove:ident, $public_url:ident,
$update_attrs:ident, $if_match_upload:ident, $if_match_remove:ident) => {
$(#[$doc])*
pub enum $name {}
impl Sealed for $name {}
impl BucketPerms for $name {
type Id = Self;
type Upload = $upload;
type SignedUpload = $signed_upload;
type Download = $download;
type SignedDownload = $signed_download;
type Attrs = $attrs;
type List = $list;
type Remove = $remove;
type PublicUrl = $public_url;
type UpdateAttrs = $update_attrs;
type IfMatchUpload = $if_match_upload;
type IfMatchRemove = $if_match_remove;
}
};
}
perm!(
Uploader: Yes, No, No, No, No, No, No, No, No, No, No
);
perm!(
SignedUploader: No, Yes, No, No, No, No, No, No, No, No, No
);
perm!(
Downloader: No, No, Yes, No, No, No, No, No, No, No, No
);
perm!(
SignedDownloader: No, No, No, Yes, No, No, No, No, No, No, No
);
perm!(
Attrser: No, No, No, No, Yes, No, No, No, No, No, No
);
perm!(
Lister: No, No, No, No, No, Yes, No, No, No, No, No
);
perm!(
Remover: No, No, No, No, No, No, Yes, No, No, No, No
);
perm!(
PublicUrler: No, No, No, No, No, No, No, Yes, No, No, No
);
perm!(
AttrsUpdater: No, No, No, No, No, No, No, No, Yes, No, No
);
perm!(
IfMatchUploader: No, No, No, No, No, No, No, No, No, Yes, No
);
perm!(
IfMatchRemover: No, No, No, No, No, No, No, No, No, No, Yes
);
perm!(
ReadWriter: Yes, Yes, Yes, Yes, Yes, Yes, Yes, No, Yes, Yes, Yes
);
}
mod sealed {
pub trait Sealed {}
}
pub trait BucketPerms: sealed::Sealed {
#[doc(hidden)]
type Id: BucketPerms;
#[doc(hidden)]
type Upload: Flag;
#[doc(hidden)]
type SignedUpload: Flag;
#[doc(hidden)]
type Download: Flag;
#[doc(hidden)]
type SignedDownload: Flag;
#[doc(hidden)]
type Attrs: Flag;
#[doc(hidden)]
type List: Flag;
#[doc(hidden)]
type Remove: Flag;
#[doc(hidden)]
type PublicUrl: Flag;
#[doc(hidden)]
type UpdateAttrs: Flag;
#[doc(hidden)]
type IfMatchUpload: Flag;
#[doc(hidden)]
type IfMatchRemove: Flag;
}
impl sealed::Sealed for () {}
impl BucketPerms for () {
type Id = Self;
type Upload = No;
type SignedUpload = No;
type Download = No;
type SignedDownload = No;
type Attrs = No;
type List = No;
type Remove = No;
type PublicUrl = No;
type UpdateAttrs = No;
type IfMatchUpload = No;
type IfMatchRemove = No;
}
macro_rules! tuple_perms {
() => {};
($first:ident $(, $rest:ident)*) => {
impl<$first: BucketPerms, $($rest: BucketPerms),*> sealed::Sealed for ($first, $($rest,)*) {}
impl<$first: BucketPerms, $($rest: BucketPerms),*> BucketPerms for ($first, $($rest,)*) {
type Id = Self;
type Upload = <$first::Upload as Flag>::Or<<($($rest,)*) as BucketPerms>::Upload>;
type SignedUpload =
<$first::SignedUpload as Flag>::Or<<($($rest,)*) as BucketPerms>::SignedUpload>;
type Download = <$first::Download as Flag>::Or<<($($rest,)*) as BucketPerms>::Download>;
type SignedDownload =
<$first::SignedDownload as Flag>::Or<<($($rest,)*) as BucketPerms>::SignedDownload>;
type Attrs = <$first::Attrs as Flag>::Or<<($($rest,)*) as BucketPerms>::Attrs>;
type List = <$first::List as Flag>::Or<<($($rest,)*) as BucketPerms>::List>;
type Remove = <$first::Remove as Flag>::Or<<($($rest,)*) as BucketPerms>::Remove>;
type PublicUrl =
<$first::PublicUrl as Flag>::Or<<($($rest,)*) as BucketPerms>::PublicUrl>;
type UpdateAttrs =
<$first::UpdateAttrs as Flag>::Or<<($($rest,)*) as BucketPerms>::UpdateAttrs>;
type IfMatchUpload =
<$first::IfMatchUpload as Flag>::Or<<($($rest,)*) as BucketPerms>::IfMatchUpload>;
type IfMatchRemove =
<$first::IfMatchRemove as Flag>::Or<<($($rest,)*) as BucketPerms>::IfMatchRemove>;
}
tuple_perms!($($rest),*);
};
}
tuple_perms!(A, B, C, D, E, F, G, H, I, J, K, L);
pub struct BucketRef<P> {
bucket: &'static Bucket,
perms: PhantomData<fn() -> P>,
}
impl<P> Clone for BucketRef<P> {
fn clone(&self) -> Self {
*self
}
}
impl<P> Copy for BucketRef<P> {}
impl<P: BucketPerms> BucketRef<P> {
pub fn list(&self) -> ListRequest<'static>
where
P::List: Granted<perms::Lister>,
{
self.bucket.list()
}
pub fn list_versions(&self) -> ListVersionsRequest<'static>
where
P::List: Granted<perms::Lister>,
{
self.bucket.list_versions()
}
pub fn exists(&self, key: &str) -> ExistsRequest<'static>
where
P::Attrs: Granted<perms::Attrser>,
{
self.bucket.exists(key)
}
pub fn attrs(&self, key: &str) -> AttrsRequest<'static>
where
P::Attrs: Granted<perms::Attrser>,
{
self.bucket.attrs(key)
}
pub fn upload(&self, key: &str, data: impl Into<UploadBody>) -> UploadRequest<'static>
where
P::Upload: Granted<perms::Uploader>,
{
self.bucket.upload(key, data)
}
pub fn upload_if_match(
&self,
key: &str,
data: impl Into<UploadBody>,
revision: Revision,
) -> UploadIfMatchRequest<'static>
where
P::IfMatchUpload: Granted<perms::IfMatchUploader>,
{
self.bucket.upload_if_match(key, data, revision)
}
pub fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'static>
where
P::UpdateAttrs: Granted<perms::AttrsUpdater>,
{
self.bucket.update_attrs(key)
}
pub fn extend_retention(&self, key: &str, until: SystemTime) -> ExtendRetentionRequest<'static>
where
P::UpdateAttrs: Granted<perms::AttrsUpdater>,
{
self.bucket.extend_retention(key, until)
}
pub fn download(&self, key: &str) -> DownloadRequest<'static>
where
P::Download: Granted<perms::Downloader>,
{
self.bucket.download(key)
}
pub fn download_stream(&self, key: &str) -> DownloadStreamRequest<'static>
where
P::Download: Granted<perms::Downloader>,
{
self.bucket.download_stream(key)
}
pub fn remove(&self, key: &str) -> RemoveRequest<'static>
where
P::Remove: Granted<perms::Remover>,
{
self.bucket.remove(key)
}
pub async fn remove_if_match(&self, key: &str, revision: Revision) -> Result<(), Error>
where
P::IfMatchRemove: Granted<perms::IfMatchRemover>,
{
self.bucket.remove_if_match(key, revision).await
}
pub fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'static>
where
P::SignedUpload: Granted<perms::SignedUploader>,
{
self.bucket.signed_upload_url(key)
}
pub fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'static>
where
P::SignedDownload: Granted<perms::SignedDownloader>,
{
self.bucket.signed_download_url(key)
}
pub fn public_url(&self, key: &str) -> Result<String, Error>
where
P::PublicUrl: Granted<perms::PublicUrler>,
{
self.bucket.public_url(key)
}
}
pub trait Uploader: Send + Sync {
fn upload(&self, key: &str, data: impl Into<UploadBody>) -> UploadRequest<'_, Self> {
UploadRequest::new(self, key, data.into())
}
fn run_upload(
&self,
request: UploadRequest<'_, Self>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
}
pub trait IfMatchUploader: Send + Sync {
fn upload_if_match(
&self,
key: &str,
data: impl Into<UploadBody>,
revision: Revision,
) -> UploadIfMatchRequest<'_, Self> {
UploadIfMatchRequest::new(self, key, data.into(), revision)
}
fn run_upload_if_match(
&self,
request: UploadIfMatchRequest<'_, Self>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
}
pub trait SignedUploader: Send + Sync {
fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'_, Self> {
SignedUploadUrlRequest::new(self, key)
}
fn run_signed_upload_url(
&self,
request: SignedUploadUrlRequest<'_, Self>,
) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send;
}
pub trait Downloader: Send + Sync {
fn download(&self, key: &str) -> DownloadRequest<'_, Self> {
DownloadRequest::new(self, key)
}
fn download_stream(&self, key: &str) -> DownloadStreamRequest<'_, Self> {
DownloadStreamRequest::new(self, key)
}
fn run_download(
&self,
request: DownloadRequest<'_, Self>,
) -> impl Future<Output = Result<Vec<u8>, Error>> + Send;
fn run_download_stream(
&self,
request: DownloadStreamRequest<'_, Self>,
) -> impl Future<Output = Result<Download, Error>> + Send;
}
pub trait SignedDownloader: Send + Sync {
fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'_, Self> {
SignedDownloadUrlRequest::new(self, key)
}
fn run_signed_download_url(
&self,
request: SignedDownloadUrlRequest<'_, Self>,
) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send;
}
pub trait Attrser: Send + Sync {
fn exists(&self, key: &str) -> ExistsRequest<'_, Self> {
ExistsRequest::new(self, key)
}
fn attrs(&self, key: &str) -> AttrsRequest<'_, Self> {
AttrsRequest::new(self, key)
}
fn run_exists(
&self,
request: ExistsRequest<'_, Self>,
) -> impl Future<Output = Result<bool, Error>> + Send;
fn run_attrs(
&self,
request: AttrsRequest<'_, Self>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
}
pub trait Lister: Send + Sync {
fn list(&self) -> ListRequest<'_, Self> {
ListRequest::new(self)
}
fn list_versions(&self) -> ListVersionsRequest<'_, Self> {
ListVersionsRequest::new(self)
}
fn run_list(
&self,
request: ListRequest<'_, Self>,
) -> impl Future<Output = Result<ListIterator, Error>> + Send;
fn run_list_versions(
&self,
request: ListVersionsRequest<'_, Self>,
) -> impl Future<Output = Result<VersionIterator, Error>> + Send;
}
pub trait Remover: Send + Sync {
fn remove(&self, key: &str) -> RemoveRequest<'_, Self> {
RemoveRequest::new(self, key)
}
fn run_remove(
&self,
request: RemoveRequest<'_, Self>,
) -> impl Future<Output = Result<(), Error>> + Send;
}
pub trait IfMatchRemover: Send + Sync {
fn remove_if_match(
&self,
key: &str,
revision: Revision,
) -> impl Future<Output = Result<(), Error>> + Send;
}
pub trait PublicUrler: Send + Sync {
fn public_url(&self, key: &str) -> Result<String, Error>;
}
pub trait AttrsUpdater: Send + Sync {
fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'_, Self> {
UpdateAttrsRequest::new(self, key)
}
fn extend_retention(&self, key: &str, until: SystemTime) -> ExtendRetentionRequest<'_, Self> {
ExtendRetentionRequest::new(self, key, until)
}
fn run_update_attrs(
&self,
request: UpdateAttrsRequest<'_, Self>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
fn run_extend_retention(
&self,
request: ExtendRetentionRequest<'_, Self>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
}
pub trait ReadWriter:
Uploader
+ IfMatchUploader
+ SignedUploader
+ Downloader
+ SignedDownloader
+ Attrser
+ Lister
+ Remover
+ IfMatchRemover
+ AttrsUpdater
{
}
impl<T> ReadWriter for T where
T: Uploader
+ IfMatchUploader
+ SignedUploader
+ Downloader
+ SignedDownloader
+ Attrser
+ Lister
+ Remover
+ IfMatchRemover
+ AttrsUpdater
{
}
impl<P: BucketPerms> Uploader for BucketRef<P>
where
P::Upload: Granted<perms::Uploader>,
{
fn run_upload(
&self,
request: UploadRequest<'_, Self>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
request.send(self.bucket)
}
}
impl<P: BucketPerms> IfMatchUploader for BucketRef<P>
where
P::IfMatchUpload: Granted<perms::IfMatchUploader>,
{
fn run_upload_if_match(
&self,
request: UploadIfMatchRequest<'_, Self>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
request.send(self.bucket)
}
}
impl<P: BucketPerms> SignedUploader for BucketRef<P>
where
P::SignedUpload: Granted<perms::SignedUploader>,
{
fn run_signed_upload_url(
&self,
request: SignedUploadUrlRequest<'_, Self>,
) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send {
request.send(self.bucket)
}
}
impl<P: BucketPerms> Downloader for BucketRef<P>
where
P::Download: Granted<perms::Downloader>,
{
fn run_download(
&self,
request: DownloadRequest<'_, Self>,
) -> impl Future<Output = Result<Vec<u8>, Error>> + Send {
request.send(self.bucket)
}
fn run_download_stream(
&self,
request: DownloadStreamRequest<'_, Self>,
) -> impl Future<Output = Result<Download, Error>> + Send {
request.send(self.bucket)
}
}
impl<P: BucketPerms> SignedDownloader for BucketRef<P>
where
P::SignedDownload: Granted<perms::SignedDownloader>,
{
fn run_signed_download_url(
&self,
request: SignedDownloadUrlRequest<'_, Self>,
) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send {
request.send(self.bucket)
}
}
impl<P: BucketPerms> Attrser for BucketRef<P>
where
P::Attrs: Granted<perms::Attrser>,
{
fn run_exists(
&self,
request: ExistsRequest<'_, Self>,
) -> impl Future<Output = Result<bool, Error>> + Send {
request.send(self.bucket)
}
fn run_attrs(
&self,
request: AttrsRequest<'_, Self>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
request.send(self.bucket)
}
}
impl<P: BucketPerms> Lister for BucketRef<P>
where
P::List: Granted<perms::Lister>,
{
fn run_list(
&self,
request: ListRequest<'_, Self>,
) -> impl Future<Output = Result<ListIterator, Error>> + Send {
request.send(self.bucket)
}
fn run_list_versions(
&self,
request: ListVersionsRequest<'_, Self>,
) -> impl Future<Output = Result<VersionIterator, Error>> + Send {
request.send(self.bucket)
}
}
impl<P: BucketPerms> Remover for BucketRef<P>
where
P::Remove: Granted<perms::Remover>,
{
fn run_remove(
&self,
request: RemoveRequest<'_, Self>,
) -> impl Future<Output = Result<(), Error>> + Send {
request.send(self.bucket)
}
}
impl<P: BucketPerms> IfMatchRemover for BucketRef<P>
where
P::IfMatchRemove: Granted<perms::IfMatchRemover>,
{
fn remove_if_match(
&self,
key: &str,
revision: Revision,
) -> impl Future<Output = Result<(), Error>> + Send {
BucketRef::remove_if_match(self, key, revision)
}
}
impl<P: BucketPerms> PublicUrler for BucketRef<P>
where
P::PublicUrl: Granted<perms::PublicUrler>,
{
fn public_url(&self, key: &str) -> Result<String, Error> {
BucketRef::public_url(self, key)
}
}
impl<P: BucketPerms> AttrsUpdater for BucketRef<P>
where
P::UpdateAttrs: Granted<perms::AttrsUpdater>,
{
fn run_update_attrs(
&self,
request: UpdateAttrsRequest<'_, Self>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
request.send(self.bucket)
}
fn run_extend_retention(
&self,
request: ExtendRetentionRequest<'_, Self>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
request.send(self.bucket)
}
}
#[cfg(test)]
mod tests;