pub struct Bucket {
pub name: String,
pub region: Region,
pub credentials: Arc<RwLock<Credentials>>,
pub extra_headers: HeaderMap,
pub extra_query: Query,
pub request_timeout: Option<Duration>,
/* private fields */
}Expand description
Instantiate an existing Bucket
Example
use s3::bucket::Bucket;
use s3::creds::Credentials;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse().unwrap();
let credentials = Credentials::default().unwrap();
let bucket = Bucket::new(bucket_name, region, credentials);Fields§
§name: String§region: Region§credentials: Arc<RwLock<Credentials>>§extra_headers: HeaderMap§extra_query: Query§request_timeout: Option<Duration>Implementations§
source§impl Bucket
impl Bucket
sourcepub fn credentials_refresh(&self) -> Result<(), S3Error>
pub fn credentials_refresh(&self) -> Result<(), S3Error>
Examples found in repository?
169 170 171 172 173 174 175 176 177 178 179 180 181 182
pub fn new<'b>(
bucket: &'b Bucket,
path: &'b str,
command: Command<'b>,
) -> Result<Reqwest<'b>, S3Error> {
bucket.credentials_refresh()?;
Ok(Reqwest {
bucket,
path,
command,
datetime: OffsetDateTime::now_utc(),
sync: false,
})
}source§impl Bucket
impl Bucket
sourcepub fn presign_get<S: AsRef<str>>(
&self,
path: S,
expiry_secs: u32,
custom_queries: Option<HashMap<String, String>>
) -> Result<String, S3Error>
pub fn presign_get<S: AsRef<str>>(
&self,
path: S,
expiry_secs: u32,
custom_queries: Option<HashMap<String, String>>
) -> Result<String, S3Error>
Get a presigned url for getting object on a given path
Example:
use std::collections::HashMap;
use s3::bucket::Bucket;
use s3::creds::Credentials;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse().unwrap();
let credentials = Credentials::default().unwrap();
let bucket = Bucket::new(bucket_name, region, credentials).unwrap();
// Add optional custom queries
let mut custom_queries = HashMap::new();
custom_queries.insert(
"response-content-disposition".into(),
"attachment; filename=\"test.png\"".into(),
);
let url = bucket.presign_get("/test.file", 86400, Some(custom_queries)).unwrap();
println!("Presigned url: {}", url);sourcepub fn presign_post<S: AsRef<str>>(
&self,
path: S,
expiry_secs: u32,
post_policy: String
) -> Result<String, S3Error>
pub fn presign_post<S: AsRef<str>>(
&self,
path: S,
expiry_secs: u32,
post_policy: String
) -> Result<String, S3Error>
Get a presigned url for posting an object to a given path
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use http::HeaderMap;
use http::header::HeaderName;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse().unwrap();
let credentials = Credentials::default().unwrap();
let bucket = Bucket::new(bucket_name, region, credentials).unwrap();
let post_policy = "eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJzaWd2NGV4YW1wbGVidWNrZXQifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwNCiAgICB7ImFjbCI6ICJwdWJsaWMtcmVhZCJ9LA0KICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL3NpZ3Y0ZXhhbXBsZWJ1Y2tldC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sDQogICAgeyJ4LWFtei1tZXRhLXV1aWQiOiAiMTQzNjUxMjM2NTEyNzQifSwNCiAgICB7IngtYW16LXNlcnZlci1zaWRlLWVuY3J5cHRpb24iOiAiQUVTMjU2In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sDQoNCiAgICB7IngtYW16LWNyZWRlbnRpYWwiOiAiQUtJQUlPU0ZPRE5ON0VYQU1QTEUvMjAxNTEyMjkvdXMtZWFzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LA0KICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwNCiAgICB7IngtYW16LWRhdGUiOiAiMjAxNTEyMjlUMDAwMDAwWiIgfQ0KICBdDQp9";
let url = bucket.presign_post("/test.file", 86400, post_policy.to_string()).unwrap();
println!("Presigned url: {}", url);sourcepub fn presign_put<S: AsRef<str>>(
&self,
path: S,
expiry_secs: u32,
custom_headers: Option<HeaderMap>
) -> Result<String, S3Error>
pub fn presign_put<S: AsRef<str>>(
&self,
path: S,
expiry_secs: u32,
custom_headers: Option<HeaderMap>
) -> Result<String, S3Error>
Get a presigned url for putting object to a given path
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use http::HeaderMap;
use http::header::HeaderName;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse().unwrap();
let credentials = Credentials::default().unwrap();
let bucket = Bucket::new(bucket_name, region, credentials).unwrap();
// Add optional custom headers
let mut custom_headers = HeaderMap::new();
custom_headers.insert(
HeaderName::from_static("custom_header"),
"custom_value".parse().unwrap(),
);
let url = bucket.presign_put("/test.file", 86400, Some(custom_headers)).unwrap();
println!("Presigned url: {}", url);sourcepub fn presign_delete<S: AsRef<str>>(
&self,
path: S,
expiry_secs: u32
) -> Result<String, S3Error>
pub fn presign_delete<S: AsRef<str>>(
&self,
path: S,
expiry_secs: u32
) -> Result<String, S3Error>
Get a presigned url for deleting object on a given path
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse().unwrap();
let credentials = Credentials::default().unwrap();
let bucket = Bucket::new(bucket_name, region, credentials).unwrap();
let url = bucket.presign_delete("/test.file", 86400).unwrap();
println!("Presigned url: {}", url);sourcepub async fn create(
name: &str,
region: Region,
credentials: Credentials,
config: BucketConfiguration
) -> Result<CreateBucketResponse, S3Error>
pub async fn create(
name: &str,
region: Region,
credentials: Credentials,
config: BucketConfiguration
) -> Result<CreateBucketResponse, S3Error>
Create a new Bucket and instantiate it
use s3::{Bucket, BucketConfiguration};
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let config = BucketConfiguration::default();
// Async variant with `tokio` or `async-std` features
let create_bucket_response = Bucket::create(bucket_name, region, credentials, config).await?;
// `sync` fature will produce an identical method
#[cfg(feature = "sync")]
let create_bucket_response = Bucket::create(bucket_name, region, credentials, config)?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let create_bucket_response = Bucket::create_blocking(bucket_name, region, credentials, config)?;sourcepub async fn create_with_path_style(
name: &str,
region: Region,
credentials: Credentials,
config: BucketConfiguration
) -> Result<CreateBucketResponse, S3Error>
pub async fn create_with_path_style(
name: &str,
region: Region,
credentials: Credentials,
config: BucketConfiguration
) -> Result<CreateBucketResponse, S3Error>
Create a new Bucket with path style and instantiate it
use s3::{Bucket, BucketConfiguration};
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let config = BucketConfiguration::default();
// Async variant with `tokio` or `async-std` features
let create_bucket_response = Bucket::create_with_path_style(bucket_name, region, credentials, config).await?;
// `sync` fature will produce an identical method
#[cfg(feature = "sync")]
let create_bucket_response = Bucket::create_with_path_style(bucket_name, region, credentials, config)?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let create_bucket_response = Bucket::create_with_path_style_blocking(bucket_name, region, credentials, config)?;sourcepub async fn delete(&self) -> Result<u16, S3Error>
pub async fn delete(&self) -> Result<u16, S3Error>
Delete existing Bucket
Example
use s3::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse().unwrap();
let credentials = Credentials::default().unwrap();
let bucket = Bucket::new(bucket_name, region, credentials).unwrap();
// Async variant with `tokio` or `async-std` features
bucket.delete().await.unwrap();
// `sync` fature will produce an identical method
#[cfg(feature = "sync")]
bucket.delete().unwrap();
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
bucket.delete_blocking().unwrap();
sourcepub fn new(
name: &str,
region: Region,
credentials: Credentials
) -> Result<Bucket, S3Error>
pub fn new(
name: &str,
region: Region,
credentials: Credentials
) -> Result<Bucket, S3Error>
Instantiate an existing Bucket.
Example
use s3::bucket::Bucket;
use s3::creds::Credentials;
// Fake credentials so we don't access user's real credentials in tests
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse().unwrap();
let credentials = Credentials::default().unwrap();
let bucket = Bucket::new(bucket_name, region, credentials).unwrap();Examples found in repository?
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
pub async fn create(
name: &str,
region: Region,
credentials: Credentials,
config: BucketConfiguration,
) -> Result<CreateBucketResponse, S3Error> {
let mut config = config;
config.set_region(region.clone());
let command = Command::CreateBucket { config };
let bucket = Bucket::new(name, region, credentials)?;
let request = RequestImpl::new(&bucket, "", command)?;
let response_data = request.response_data(false).await?;
let response_text = response_data.as_str()?;
Ok(CreateBucketResponse {
bucket,
response_text: response_text.to_string(),
response_code: response_data.status_code(),
})
}
/// Create a new `Bucket` with path style and instantiate it
///
/// ```no_run
/// use s3::{Bucket, BucketConfiguration};
/// use s3::creds::Credentials;
/// # use s3::region::Region;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let config = BucketConfiguration::default();
///
/// // Async variant with `tokio` or `async-std` features
/// let create_bucket_response = Bucket::create_with_path_style(bucket_name, region, credentials, config).await?;
///
/// // `sync` fature will produce an identical method
/// #[cfg(feature = "sync")]
/// let create_bucket_response = Bucket::create_with_path_style(bucket_name, region, credentials, config)?;
///
/// # let region: Region = "us-east-1".parse()?;
/// # let credentials = Credentials::default()?;
/// # let config = BucketConfiguration::default();
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let create_bucket_response = Bucket::create_with_path_style_blocking(bucket_name, region, credentials, config)?;
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn create_with_path_style(
name: &str,
region: Region,
credentials: Credentials,
config: BucketConfiguration,
) -> Result<CreateBucketResponse, S3Error> {
let mut config = config;
config.set_region(region.clone());
let command = Command::CreateBucket { config };
let bucket = Bucket::new(name, region, credentials)?.with_path_style();
let request = RequestImpl::new(&bucket, "", command)?;
let response_data = request.response_data(false).await?;
let response_text = response_data.to_string()?;
Ok(CreateBucketResponse {
bucket,
response_text,
response_code: response_data.status_code(),
})
}sourcepub fn new_public(name: &str, region: Region) -> Result<Bucket, S3Error>
pub fn new_public(name: &str, region: Region) -> Result<Bucket, S3Error>
Instantiate a public existing Bucket.
Example
use s3::bucket::Bucket;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse().unwrap();
let bucket = Bucket::new_public(bucket_name, region).unwrap();sourcepub fn with_path_style(&self) -> Bucket
pub fn with_path_style(&self) -> Bucket
Examples found in repository?
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
pub async fn create_with_path_style(
name: &str,
region: Region,
credentials: Credentials,
config: BucketConfiguration,
) -> Result<CreateBucketResponse, S3Error> {
let mut config = config;
config.set_region(region.clone());
let command = Command::CreateBucket { config };
let bucket = Bucket::new(name, region, credentials)?.with_path_style();
let request = RequestImpl::new(&bucket, "", command)?;
let response_data = request.response_data(false).await?;
let response_text = response_data.to_string()?;
Ok(CreateBucketResponse {
bucket,
response_text,
response_code: response_data.status_code(),
})
}pub fn with_extra_headers(&self, extra_headers: HeaderMap) -> Bucket
pub fn with_extra_query(&self, extra_query: HashMap<String, String>) -> Bucket
pub fn with_request_timeout(&self, request_timeout: Duration) -> Bucket
pub fn with_listobjects_v1(&self) -> Bucket
sourcepub async fn copy_object_internal<F: AsRef<str>, T: AsRef<str>>(
&self,
from: F,
to: T
) -> Result<u16, S3Error>
pub async fn copy_object_internal<F: AsRef<str>, T: AsRef<str>>(
&self,
from: F,
to: T
) -> Result<u16, S3Error>
Copy file from an S3 path, internally within the same bucket.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let code = bucket.copy_object_internal("/from.file", "/to.file").await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let code = bucket.copy_object_internal("/from.file", "/to.file")?;
sourcepub async fn get_object<S: AsRef<str>>(
&self,
path: S
) -> Result<ResponseData, S3Error>
pub async fn get_object<S: AsRef<str>>(
&self,
path: S
) -> Result<ResponseData, S3Error>
Gets file from an S3 path.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let response_data = bucket.get_object("/test.file").await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let response_data = bucket.get_object("/test.file")?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let response_data = bucket.get_object_blocking("/test.file")?;sourcepub async fn get_object_torrent<S: AsRef<str>>(
&self,
path: S
) -> Result<ResponseData, S3Error>
pub async fn get_object_torrent<S: AsRef<str>>(
&self,
path: S
) -> Result<ResponseData, S3Error>
Gets torrent from an S3 path.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let response_data = bucket.get_object_torrent("/test.file").await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let response_data = bucket.get_object_torrent("/test.file")?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let response_data = bucket.get_object_torrent_blocking("/test.file")?;sourcepub async fn get_object_range<S: AsRef<str>>(
&self,
path: S,
start: u64,
end: Option<u64>
) -> Result<ResponseData, S3Error>
pub async fn get_object_range<S: AsRef<str>>(
&self,
path: S,
start: u64,
end: Option<u64>
) -> Result<ResponseData, S3Error>
Gets specified inclusive byte range of file from an S3 path.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let response_data = bucket.get_object_range("/test.file", 0, Some(31)).await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let response_data = bucket.get_object_range("/test.file", 0, Some(31))?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let response_data = bucket.get_object_range_blocking("/test.file", 0, Some(31))?;sourcepub async fn get_object_range_to_writer<T: AsyncWrite + Send + Unpin, S: AsRef<str>>(
&self,
path: S,
start: u64,
end: Option<u64>,
writer: &mut T
) -> Result<u16, S3Error>
pub async fn get_object_range_to_writer<T: AsyncWrite + Send + Unpin, S: AsRef<str>>(
&self,
path: S,
start: u64,
end: Option<u64>,
writer: &mut T
) -> Result<u16, S3Error>
Stream range of bytes from S3 path to a local file, generic over T: Write.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
use std::fs::File;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
let mut output_file = File::create("output_file").expect("Unable to create file");
let mut async_output_file = tokio::fs::File::create("async_output_file").await.expect("Unable to create file");
#[cfg(feature = "with-async-std")]
let mut async_output_file = async_std::fs::File::create("async_output_file").await.expect("Unable to create file");
let start = 0;
let end = Some(1024);
// Async variant with `tokio` or `async-std` features
let status_code = bucket.get_object_range_to_writer("/test.file", start, end, &mut async_output_file).await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let status_code = bucket.get_object_range_to_writer("/test.file", start, end, &mut output_file)?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features. Based of the async branch
#[cfg(feature = "blocking")]
let status_code = bucket.get_object_range_to_writer_blocking("/test.file", start, end, &mut async_output_file)?;sourcepub async fn get_object_to_writer<T: AsyncWrite + Send + Unpin, S: AsRef<str>>(
&self,
path: S,
writer: &mut T
) -> Result<u16, S3Error>
pub async fn get_object_to_writer<T: AsyncWrite + Send + Unpin, S: AsRef<str>>(
&self,
path: S,
writer: &mut T
) -> Result<u16, S3Error>
Stream file from S3 path to a local file, generic over T: Write.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
use std::fs::File;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
let mut output_file = File::create("output_file").expect("Unable to create file");
let mut async_output_file = tokio::fs::File::create("async_output_file").await.expect("Unable to create file");
#[cfg(feature = "with-async-std")]
let mut async_output_file = async_std::fs::File::create("async_output_file").await.expect("Unable to create file");
// Async variant with `tokio` or `async-std` features
let status_code = bucket.get_object_to_writer("/test.file", &mut async_output_file).await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let status_code = bucket.get_object_to_writer("/test.file", &mut output_file)?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features. Based of the async branch
#[cfg(feature = "blocking")]
let status_code = bucket.get_object_to_writer_blocking("/test.file", &mut async_output_file)?;sourcepub async fn get_object_stream<S: AsRef<str>>(
&self,
path: S
) -> Result<ResponseDataStream, S3Error>
pub async fn get_object_stream<S: AsRef<str>>(
&self,
path: S
) -> Result<ResponseDataStream, S3Error>
Stream file from S3 path to a local file using an async stream.
Example
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
#[cfg(feature = "with-tokio")]
use tokio_stream::StreamExt;
#[cfg(feature = "with-tokio")]
use tokio::io::AsyncWriteExt;
#[cfg(feature = "with-async-std")]
use futures_util::StreamExt;
#[cfg(feature = "with-async-std")]
use futures_util::AsyncWriteExt;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
let path = "path";
let mut response_data_stream = bucket.get_object_stream(path).await?;
#[cfg(feature = "with-tokio")]
let mut async_output_file = tokio::fs::File::create("async_output_file").await.expect("Unable to create file");
#[cfg(feature = "with-async-std")]
let mut async_output_file = async_std::fs::File::create("async_output_file").await.expect("Unable to create file");
while let Some(chunk) = response_data_stream.bytes().next().await {
async_output_file.write_all(&chunk).await?;
}
sourcepub async fn put_object_stream<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: impl AsRef<str>
) -> Result<u16, S3Error>
pub async fn put_object_stream<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: impl AsRef<str>
) -> Result<u16, S3Error>
Stream file from local path to s3, generic over T: Write.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
use std::fs::File;
use std::io::Write;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
let path = "path";
let test: Vec<u8> = (0..1000).map(|_| 42).collect();
let mut file = File::create(path)?;
// tokio open file
let mut async_output_file = tokio::fs::File::create("async_output_file").await.expect("Unable to create file");
file.write_all(&test)?;
// Generic over std::io::Read
#[cfg(feature = "with-tokio")]
let status_code = bucket.put_object_stream(&mut async_output_file, "/path").await?;
#[cfg(feature = "with-async-std")]
let mut async_output_file = async_std::fs::File::create("async_output_file").await.expect("Unable to create file");
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
// Generic over std::io::Read
let status_code = bucket.put_object_stream(&mut path, "/path")?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let status_code = bucket.put_object_stream_blocking(&mut path, "/path")?;sourcepub async fn put_object_stream_with_content_type<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: impl AsRef<str>,
content_type: impl AsRef<str>
) -> Result<u16, S3Error>
pub async fn put_object_stream_with_content_type<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: impl AsRef<str>,
content_type: impl AsRef<str>
) -> Result<u16, S3Error>
Stream file from local path to s3, generic over T: Write with explicit content type.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
use std::fs::File;
use std::io::Write;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
let path = "path";
let test: Vec<u8> = (0..1000).map(|_| 42).collect();
let mut file = File::create(path)?;
file.write_all(&test)?;
#[cfg(feature = "with-tokio")]
let mut async_output_file = tokio::fs::File::create("async_output_file").await.expect("Unable to create file");
#[cfg(feature = "with-async-std")]
let mut async_output_file = async_std::fs::File::create("async_output_file").await.expect("Unable to create file");
// Async variant with `tokio` or `async-std` features
// Generic over std::io::Read
let status_code = bucket
.put_object_stream_with_content_type(&mut async_output_file, "/path", "application/octet-stream")
.await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
// Generic over std::io::Read
let status_code = bucket
.put_object_stream_with_content_type(&mut path, "/path", "application/octet-stream")?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let status_code = bucket
.put_object_stream_with_content_type_blocking(&mut path, "/path", "application/octet-stream")?;sourcepub async fn initiate_multipart_upload(
&self,
s3_path: &str,
content_type: &str
) -> Result<InitiateMultipartUploadResponse, S3Error>
pub async fn initiate_multipart_upload(
&self,
s3_path: &str,
content_type: &str
) -> Result<InitiateMultipartUploadResponse, S3Error>
Initiate multipart upload to s3.
Examples found in repository?
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
async fn _put_object_stream_with_content_type<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: &str,
content_type: &str,
) -> Result<u16, S3Error> {
// If the file is smaller CHUNK_SIZE, just do a regular upload.
// Otherwise perform a multi-part upload.
let first_chunk = crate::utils::read_chunk_async(reader).await?;
if first_chunk.len() < CHUNK_SIZE {
let response_data = self
.put_object_with_content_type(s3_path, first_chunk.as_slice(), content_type)
.await?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
return Ok(response_data.status_code());
}
let msg = self
.initiate_multipart_upload(s3_path, content_type)
.await?;
let path = msg.key;
let upload_id = &msg.upload_id;
let mut part_number: u32 = 0;
let mut etags = Vec::new();
// Collect request handles
let mut handles = vec![];
loop {
let chunk = if part_number == 0 {
first_chunk.clone()
} else {
crate::utils::read_chunk_async(reader).await?
};
let done = chunk.len() < CHUNK_SIZE;
// Start chunk upload
part_number += 1;
handles.push(self.make_multipart_request(
&path,
chunk,
part_number,
upload_id,
content_type,
));
if done {
break;
}
}
// Wait for all chunks to finish (or fail)
let responses = futures::future::join_all(handles).await;
for response in responses {
let response_data = response?;
if !(200..300).contains(&response_data.status_code()) {
// if chunk upload failed - abort the upload
match self.abort_upload(&path, upload_id).await {
Ok(_) => {
return Err(error_from_response_data(response_data)?);
}
Err(error) => {
return Err(error);
}
}
}
let etag = response_data.as_str()?;
etags.push(etag.to_string());
}
// Finish the upload
let inner_data = etags
.clone()
.into_iter()
.enumerate()
.map(|(i, x)| Part {
etag: x,
part_number: i as u32 + 1,
})
.collect::<Vec<Part>>();
let response_data = self
.complete_multipart_upload(&path, &msg.upload_id, inner_data)
.await?;
Ok(response_data.status_code())
}sourcepub async fn put_multipart_stream<R: Read + Unpin>(
&self,
reader: &mut R,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str
) -> Result<Part, S3Error>
pub async fn put_multipart_stream<R: Read + Unpin>(
&self,
reader: &mut R,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str
) -> Result<Part, S3Error>
Upload a streamed multipart chunk to s3 using a previously initiated multipart upload
sourcepub async fn put_multipart_chunk(
&self,
chunk: Vec<u8>,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str
) -> Result<Part, S3Error>
pub async fn put_multipart_chunk(
&self,
chunk: Vec<u8>,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str
) -> Result<Part, S3Error>
Upload a buffered multipart chunk to s3 using a previously initiated multipart upload
Examples found in repository?
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
pub async fn put_multipart_stream<R: Read + Unpin>(
&self,
reader: &mut R,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let chunk = crate::utils::read_chunk(reader)?;
self.put_multipart_chunk(chunk, path, part_number, upload_id, content_type)
.await
}sourcepub async fn complete_multipart_upload(
&self,
path: &str,
upload_id: &str,
parts: Vec<Part>
) -> Result<ResponseData, S3Error>
pub async fn complete_multipart_upload(
&self,
path: &str,
upload_id: &str,
parts: Vec<Part>
) -> Result<ResponseData, S3Error>
Completes a previously initiated multipart upload, with optional final data chunks
Examples found in repository?
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
async fn _put_object_stream_with_content_type<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: &str,
content_type: &str,
) -> Result<u16, S3Error> {
// If the file is smaller CHUNK_SIZE, just do a regular upload.
// Otherwise perform a multi-part upload.
let first_chunk = crate::utils::read_chunk_async(reader).await?;
if first_chunk.len() < CHUNK_SIZE {
let response_data = self
.put_object_with_content_type(s3_path, first_chunk.as_slice(), content_type)
.await?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
return Ok(response_data.status_code());
}
let msg = self
.initiate_multipart_upload(s3_path, content_type)
.await?;
let path = msg.key;
let upload_id = &msg.upload_id;
let mut part_number: u32 = 0;
let mut etags = Vec::new();
// Collect request handles
let mut handles = vec![];
loop {
let chunk = if part_number == 0 {
first_chunk.clone()
} else {
crate::utils::read_chunk_async(reader).await?
};
let done = chunk.len() < CHUNK_SIZE;
// Start chunk upload
part_number += 1;
handles.push(self.make_multipart_request(
&path,
chunk,
part_number,
upload_id,
content_type,
));
if done {
break;
}
}
// Wait for all chunks to finish (or fail)
let responses = futures::future::join_all(handles).await;
for response in responses {
let response_data = response?;
if !(200..300).contains(&response_data.status_code()) {
// if chunk upload failed - abort the upload
match self.abort_upload(&path, upload_id).await {
Ok(_) => {
return Err(error_from_response_data(response_data)?);
}
Err(error) => {
return Err(error);
}
}
}
let etag = response_data.as_str()?;
etags.push(etag.to_string());
}
// Finish the upload
let inner_data = etags
.clone()
.into_iter()
.enumerate()
.map(|(i, x)| Part {
etag: x,
part_number: i as u32 + 1,
})
.collect::<Vec<Part>>();
let response_data = self
.complete_multipart_upload(&path, &msg.upload_id, inner_data)
.await?;
Ok(response_data.status_code())
}sourcepub async fn location(&self) -> Result<(Region, u16), S3Error>
pub async fn location(&self) -> Result<(Region, u16), S3Error>
Get Bucket location.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let (region, status_code) = bucket.location().await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let (region, status_code) = bucket.location()?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let (region, status_code) = bucket.location_blocking()?;sourcepub async fn delete_object<S: AsRef<str>>(
&self,
path: S
) -> Result<ResponseData, S3Error>
pub async fn delete_object<S: AsRef<str>>(
&self,
path: S
) -> Result<ResponseData, S3Error>
Delete file from an S3 path.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let response_data = bucket.delete_object("/test.file").await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let response_data = bucket.delete_object("/test.file")?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let response_data = bucket.delete_object_blocking("/test.file")?;sourcepub async fn head_object<S: AsRef<str>>(
&self,
path: S
) -> Result<(HeadObjectResult, u16), S3Error>
pub async fn head_object<S: AsRef<str>>(
&self,
path: S
) -> Result<(HeadObjectResult, u16), S3Error>
Head object from S3.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let (head_object_result, code) = bucket.head_object("/test.png").await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let (head_object_result, code) = bucket.head_object("/test.png")?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let (head_object_result, code) = bucket.head_object_blocking("/test.png")?;sourcepub async fn put_object_with_content_type<S: AsRef<str>>(
&self,
path: S,
content: &[u8],
content_type: &str
) -> Result<ResponseData, S3Error>
pub async fn put_object_with_content_type<S: AsRef<str>>(
&self,
path: S,
content: &[u8],
content_type: &str
) -> Result<ResponseData, S3Error>
Put into an S3 bucket, with explicit content-type.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
let content = "I want to go to S3".as_bytes();
// Async variant with `tokio` or `async-std` features
let response_data = bucket.put_object_with_content_type("/test.file", content, "text/plain").await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let response_data = bucket.put_object_with_content_type("/test.file", content, "text/plain")?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let response_data = bucket.put_object_with_content_type_blocking("/test.file", content, "text/plain")?;Examples found in repository?
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
async fn _put_object_stream_with_content_type<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: &str,
content_type: &str,
) -> Result<u16, S3Error> {
// If the file is smaller CHUNK_SIZE, just do a regular upload.
// Otherwise perform a multi-part upload.
let first_chunk = crate::utils::read_chunk_async(reader).await?;
if first_chunk.len() < CHUNK_SIZE {
let response_data = self
.put_object_with_content_type(s3_path, first_chunk.as_slice(), content_type)
.await?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
return Ok(response_data.status_code());
}
let msg = self
.initiate_multipart_upload(s3_path, content_type)
.await?;
let path = msg.key;
let upload_id = &msg.upload_id;
let mut part_number: u32 = 0;
let mut etags = Vec::new();
// Collect request handles
let mut handles = vec![];
loop {
let chunk = if part_number == 0 {
first_chunk.clone()
} else {
crate::utils::read_chunk_async(reader).await?
};
let done = chunk.len() < CHUNK_SIZE;
// Start chunk upload
part_number += 1;
handles.push(self.make_multipart_request(
&path,
chunk,
part_number,
upload_id,
content_type,
));
if done {
break;
}
}
// Wait for all chunks to finish (or fail)
let responses = futures::future::join_all(handles).await;
for response in responses {
let response_data = response?;
if !(200..300).contains(&response_data.status_code()) {
// if chunk upload failed - abort the upload
match self.abort_upload(&path, upload_id).await {
Ok(_) => {
return Err(error_from_response_data(response_data)?);
}
Err(error) => {
return Err(error);
}
}
}
let etag = response_data.as_str()?;
etags.push(etag.to_string());
}
// Finish the upload
let inner_data = etags
.clone()
.into_iter()
.enumerate()
.map(|(i, x)| Part {
etag: x,
part_number: i as u32 + 1,
})
.collect::<Vec<Part>>();
let response_data = self
.complete_multipart_upload(&path, &msg.upload_id, inner_data)
.await?;
Ok(response_data.status_code())
}
#[maybe_async::sync_impl]
fn _put_object_stream_with_content_type<R: Read>(
&self,
reader: &mut R,
s3_path: &str,
content_type: &str,
) -> Result<u16, S3Error> {
let msg = self.initiate_multipart_upload(s3_path, content_type)?;
let path = msg.key;
let upload_id = &msg.upload_id;
let mut part_number: u32 = 0;
let mut etags = Vec::new();
loop {
let chunk = crate::utils::read_chunk(reader)?;
if chunk.len() < CHUNK_SIZE {
if part_number == 0 {
// Files is not big enough for multipart upload, going with regular put_object
self.abort_upload(&path, upload_id)?;
self.put_object(s3_path, chunk.as_slice())?;
} else {
part_number += 1;
let part = self.put_multipart_chunk(
chunk,
&path,
part_number,
upload_id,
content_type,
)?;
etags.push(part.etag);
let inner_data = etags
.into_iter()
.enumerate()
.map(|(i, x)| Part {
etag: x,
part_number: i as u32 + 1,
})
.collect::<Vec<Part>>();
return Ok(self
.complete_multipart_upload(&path, upload_id, inner_data)?
.status_code());
// let response = std::str::from_utf8(data.as_slice())?;
}
} else {
part_number += 1;
let part =
self.put_multipart_chunk(chunk, &path, part_number, upload_id, content_type)?;
etags.push(part.etag.to_string());
}
}
}
/// Initiate multipart upload to s3.
#[maybe_async::async_impl]
pub async fn initiate_multipart_upload(
&self,
s3_path: &str,
content_type: &str,
) -> Result<InitiateMultipartUploadResponse, S3Error> {
let command = Command::InitiateMultipartUpload { content_type };
let request = RequestImpl::new(self, s3_path, command)?;
let response_data = request.response_data(false).await?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
let msg: InitiateMultipartUploadResponse =
quick_xml::de::from_str(response_data.as_str()?)?;
Ok(msg)
}
#[maybe_async::sync_impl]
pub fn initiate_multipart_upload(
&self,
s3_path: &str,
content_type: &str,
) -> Result<InitiateMultipartUploadResponse, S3Error> {
let command = Command::InitiateMultipartUpload { content_type };
let request = RequestImpl::new(self, s3_path, command)?;
let response_data = request.response_data(false)?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
let msg: InitiateMultipartUploadResponse =
quick_xml::de::from_str(response_data.as_str()?)?;
Ok(msg)
}
/// Upload a streamed multipart chunk to s3 using a previously initiated multipart upload
#[maybe_async::async_impl]
pub async fn put_multipart_stream<R: Read + Unpin>(
&self,
reader: &mut R,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let chunk = crate::utils::read_chunk(reader)?;
self.put_multipart_chunk(chunk, path, part_number, upload_id, content_type)
.await
}
#[maybe_async::sync_impl]
pub async fn put_multipart_stream<R: Read + Unpin>(
&self,
reader: &mut R,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let chunk = crate::utils::read_chunk(reader)?;
self.put_multipart_chunk(chunk, path, part_number, upload_id, content_type)
}
/// Upload a buffered multipart chunk to s3 using a previously initiated multipart upload
#[maybe_async::async_impl]
pub async fn put_multipart_chunk(
&self,
chunk: Vec<u8>,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let command = Command::PutObject {
// part_number,
content: &chunk,
multipart: Some(Multipart::new(part_number, upload_id)), // upload_id: &msg.upload_id,
content_type,
};
let request = RequestImpl::new(self, path, command)?;
let response_data = request.response_data(true).await?;
if !(200..300).contains(&response_data.status_code()) {
// if chunk upload failed - abort the upload
match self.abort_upload(path, upload_id).await {
Ok(_) => {
return Err(error_from_response_data(response_data)?);
}
Err(error) => {
return Err(error);
}
}
}
let etag = response_data.as_str()?;
Ok(Part {
etag: etag.to_string(),
part_number,
})
}
#[maybe_async::sync_impl]
pub fn put_multipart_chunk(
&self,
chunk: Vec<u8>,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let command = Command::PutObject {
// part_number,
content: &chunk,
multipart: Some(Multipart::new(part_number, upload_id)), // upload_id: &msg.upload_id,
content_type,
};
let request = RequestImpl::new(self, path, command)?;
let response_data = request.response_data(true)?;
if !(200..300).contains(&response_data.status_code()) {
// if chunk upload failed - abort the upload
match self.abort_upload(path, upload_id) {
Ok(_) => {
return Err(error_from_response_data(response_data)?);
}
Err(error) => {
return Err(error);
}
}
}
let etag = response_data.as_str()?;
Ok(Part {
etag: etag.to_string(),
part_number,
})
}
/// Completes a previously initiated multipart upload, with optional final data chunks
#[maybe_async::async_impl]
pub async fn complete_multipart_upload(
&self,
path: &str,
upload_id: &str,
parts: Vec<Part>,
) -> Result<ResponseData, S3Error> {
let data = CompleteMultipartUploadData { parts };
let complete = Command::CompleteMultipartUpload { upload_id, data };
let complete_request = RequestImpl::new(self, path, complete)?;
complete_request.response_data(false).await
}
#[maybe_async::sync_impl]
pub fn complete_multipart_upload(
&self,
path: &str,
upload_id: &str,
parts: Vec<Part>,
) -> Result<ResponseData, S3Error> {
let data = CompleteMultipartUploadData { parts };
let complete = Command::CompleteMultipartUpload { upload_id, data };
let complete_request = RequestImpl::new(self, path, complete)?;
complete_request.response_data(false)
}
/// Get Bucket location.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let (region, status_code) = bucket.location().await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let (region, status_code) = bucket.location()?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let (region, status_code) = bucket.location_blocking()?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn location(&self) -> Result<(Region, u16), S3Error> {
let request = RequestImpl::new(self, "?location", Command::GetBucketLocation)?;
let response_data = request.response_data(false).await?;
let region_string = String::from_utf8_lossy(response_data.as_slice());
let region = match quick_xml::de::from_reader(region_string.as_bytes()) {
Ok(r) => {
let location_result: BucketLocationResult = r;
location_result.region.parse()?
}
Err(e) => {
if response_data.status_code() == 200 {
Region::Custom {
region: "Custom".to_string(),
endpoint: "".to_string(),
}
} else {
Region::Custom {
region: format!("Error encountered : {}", e),
endpoint: "".to_string(),
}
}
}
};
Ok((region, response_data.status_code()))
}
/// Delete file from an S3 path.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.delete_object("/test.file").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.delete_object("/test.file")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.delete_object_blocking("/test.file")?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn delete_object<S: AsRef<str>>(&self, path: S) -> Result<ResponseData, S3Error> {
let command = Command::DeleteObject;
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data(false).await
}
/// Head object from S3.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let (head_object_result, code) = bucket.head_object("/test.png").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let (head_object_result, code) = bucket.head_object("/test.png")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let (head_object_result, code) = bucket.head_object_blocking("/test.png")?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn head_object<S: AsRef<str>>(
&self,
path: S,
) -> Result<(HeadObjectResult, u16), S3Error> {
let command = Command::HeadObject;
let request = RequestImpl::new(self, path.as_ref(), command)?;
let (headers, status) = request.response_header().await?;
let header_object = HeadObjectResult::from(&headers);
Ok((header_object, status))
}
/// Put into an S3 bucket, with explicit content-type.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
/// let content = "I want to go to S3".as_bytes();
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.put_object_with_content_type("/test.file", content, "text/plain").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.put_object_with_content_type("/test.file", content, "text/plain")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.put_object_with_content_type_blocking("/test.file", content, "text/plain")?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn put_object_with_content_type<S: AsRef<str>>(
&self,
path: S,
content: &[u8],
content_type: &str,
) -> Result<ResponseData, S3Error> {
let command = Command::PutObject {
content,
content_type,
multipart: None,
};
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data(true).await
}
/// Put into an S3 bucket.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
/// let content = "I want to go to S3".as_bytes();
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.put_object("/test.file", content).await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.put_object("/test.file", content)?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.put_object_blocking("/test.file", content)?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn put_object<S: AsRef<str>>(
&self,
path: S,
content: &[u8],
) -> Result<ResponseData, S3Error> {
self.put_object_with_content_type(path, content, "application/octet-stream")
.await
}sourcepub async fn put_object<S: AsRef<str>>(
&self,
path: S,
content: &[u8]
) -> Result<ResponseData, S3Error>
pub async fn put_object<S: AsRef<str>>(
&self,
path: S,
content: &[u8]
) -> Result<ResponseData, S3Error>
Put into an S3 bucket.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
let content = "I want to go to S3".as_bytes();
// Async variant with `tokio` or `async-std` features
let response_data = bucket.put_object("/test.file", content).await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let response_data = bucket.put_object("/test.file", content)?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let response_data = bucket.put_object_blocking("/test.file", content)?;sourcepub async fn put_object_tagging<S: AsRef<str>>(
&self,
path: &str,
tags: &[(S, S)]
) -> Result<ResponseData, S3Error>
pub async fn put_object_tagging<S: AsRef<str>>(
&self,
path: &str,
tags: &[(S, S)]
) -> Result<ResponseData, S3Error>
Tag an S3 object.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let response_data = bucket.put_object_tagging("/test.file", &[("Tag1", "Value1"), ("Tag2", "Value2")]).await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let response_data = bucket.put_object_tagging("/test.file", &[("Tag1", "Value1"), ("Tag2", "Value2")])?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let response_data = bucket.put_object_tagging_blocking("/test.file", &[("Tag1", "Value1"), ("Tag2", "Value2")])?;sourcepub async fn delete_object_tagging<S: AsRef<str>>(
&self,
path: S
) -> Result<ResponseData, S3Error>
pub async fn delete_object_tagging<S: AsRef<str>>(
&self,
path: S
) -> Result<ResponseData, S3Error>
Delete tags from an S3 object.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let response_data = bucket.delete_object_tagging("/test.file").await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let response_data = bucket.delete_object_tagging("/test.file")?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let response_data = bucket.delete_object_tagging_blocking("/test.file")?;sourcepub async fn get_object_tagging<S: AsRef<str>>(
&self,
path: S
) -> Result<(Vec<Tag>, u16), S3Error>
pub async fn get_object_tagging<S: AsRef<str>>(
&self,
path: S
) -> Result<(Vec<Tag>, u16), S3Error>
Retrieve an S3 object list of tags.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let response_data = bucket.get_object_tagging("/test.file").await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let response_data = bucket.get_object_tagging("/test.file")?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let response_data = bucket.get_object_tagging_blocking("/test.file")?;sourcepub async fn list_page(
&self,
prefix: String,
delimiter: Option<String>,
continuation_token: Option<String>,
start_after: Option<String>,
max_keys: Option<usize>
) -> Result<(ListBucketResult, u16), S3Error>
pub async fn list_page(
&self,
prefix: String,
delimiter: Option<String>,
continuation_token: Option<String>,
start_after: Option<String>,
max_keys: Option<usize>
) -> Result<(ListBucketResult, u16), S3Error>
Examples found in repository?
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
pub async fn list(
&self,
prefix: String,
delimiter: Option<String>,
) -> Result<Vec<ListBucketResult>, S3Error> {
let the_bucket = self.to_owned();
let mut results = Vec::new();
let mut continuation_token = None;
loop {
let (list_bucket_result, _) = the_bucket
.list_page(
prefix.clone(),
delimiter.clone(),
continuation_token,
None,
None,
)
.await?;
continuation_token = list_bucket_result.next_continuation_token.clone();
results.push(list_bucket_result);
if continuation_token.is_none() {
break;
}
}
Ok(results)
}sourcepub async fn list(
&self,
prefix: String,
delimiter: Option<String>
) -> Result<Vec<ListBucketResult>, S3Error>
pub async fn list(
&self,
prefix: String,
delimiter: Option<String>
) -> Result<Vec<ListBucketResult>, S3Error>
List the contents of an S3 bucket.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let results = bucket.list("/".to_string(), Some("/".to_string())).await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let results = bucket.list("/".to_string(), Some("/".to_string()))?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let results = bucket.list_blocking("/".to_string(), Some("/".to_string()))?;sourcepub async fn list_multiparts_uploads_page(
&self,
prefix: Option<&str>,
delimiter: Option<&str>,
key_marker: Option<String>,
max_uploads: Option<usize>
) -> Result<(ListMultipartUploadsResult, u16), S3Error>
pub async fn list_multiparts_uploads_page(
&self,
prefix: Option<&str>,
delimiter: Option<&str>,
key_marker: Option<String>,
max_uploads: Option<usize>
) -> Result<(ListMultipartUploadsResult, u16), S3Error>
Examples found in repository?
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
pub async fn list_multiparts_uploads(
&self,
prefix: Option<&str>,
delimiter: Option<&str>,
) -> Result<Vec<ListMultipartUploadsResult>, S3Error> {
let the_bucket = self.to_owned();
let mut results = Vec::new();
let mut next_marker: Option<String> = None;
loop {
let (list_multiparts_uploads_result, _) = the_bucket
.list_multiparts_uploads_page(prefix, delimiter, next_marker, None)
.await?;
let is_truncated = list_multiparts_uploads_result.is_truncated;
next_marker = list_multiparts_uploads_result.next_marker.clone();
results.push(list_multiparts_uploads_result);
if !is_truncated {
break;
}
}
Ok(results)
}sourcepub async fn list_multiparts_uploads(
&self,
prefix: Option<&str>,
delimiter: Option<&str>
) -> Result<Vec<ListMultipartUploadsResult>, S3Error>
pub async fn list_multiparts_uploads(
&self,
prefix: Option<&str>,
delimiter: Option<&str>
) -> Result<Vec<ListMultipartUploadsResult>, S3Error>
List the ongoing multipart uploads of an S3 bucket. This may be useful to cleanup failed
uploads, together with crate::bucket::Bucket::abort_upload.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let results = bucket.list_multiparts_uploads(Some("/"), Some("/")).await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let results = bucket.list_multiparts_uploads(Some("/"), Some("/"))?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let results = bucket.list_multiparts_uploads_blocking(Some("/"), Some("/"))?;sourcepub async fn abort_upload(
&self,
key: &str,
upload_id: &str
) -> Result<(), S3Error>
pub async fn abort_upload(
&self,
key: &str,
upload_id: &str
) -> Result<(), S3Error>
Abort a running multipart upload.
Example:
use s3::bucket::Bucket;
use s3::creds::Credentials;
use anyhow::Result;
let bucket_name = "rust-s3-test";
let region = "us-east-1".parse()?;
let credentials = Credentials::default()?;
let bucket = Bucket::new(bucket_name, region, credentials)?;
// Async variant with `tokio` or `async-std` features
let results = bucket.abort_upload("/some/file.txt", "ZDFjM2I0YmEtMzU3ZC00OTQ1LTlkNGUtMTgxZThjYzIwNjA2").await?;
// `sync` feature will produce an identical method
#[cfg(feature = "sync")]
let results = bucket.abort_upload("/some/file.txt", "ZDFjM2I0YmEtMzU3ZC00OTQ1LTlkNGUtMTgxZThjYzIwNjA2")?;
// Blocking variant, generated with `blocking` feature in combination
// with `tokio` or `async-std` features.
#[cfg(feature = "blocking")]
let results = bucket.abort_upload_blocking("/some/file.txt", "ZDFjM2I0YmEtMzU3ZC00OTQ1LTlkNGUtMTgxZThjYzIwNjA2")?;Examples found in repository?
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
async fn _put_object_stream_with_content_type<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: &str,
content_type: &str,
) -> Result<u16, S3Error> {
// If the file is smaller CHUNK_SIZE, just do a regular upload.
// Otherwise perform a multi-part upload.
let first_chunk = crate::utils::read_chunk_async(reader).await?;
if first_chunk.len() < CHUNK_SIZE {
let response_data = self
.put_object_with_content_type(s3_path, first_chunk.as_slice(), content_type)
.await?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
return Ok(response_data.status_code());
}
let msg = self
.initiate_multipart_upload(s3_path, content_type)
.await?;
let path = msg.key;
let upload_id = &msg.upload_id;
let mut part_number: u32 = 0;
let mut etags = Vec::new();
// Collect request handles
let mut handles = vec![];
loop {
let chunk = if part_number == 0 {
first_chunk.clone()
} else {
crate::utils::read_chunk_async(reader).await?
};
let done = chunk.len() < CHUNK_SIZE;
// Start chunk upload
part_number += 1;
handles.push(self.make_multipart_request(
&path,
chunk,
part_number,
upload_id,
content_type,
));
if done {
break;
}
}
// Wait for all chunks to finish (or fail)
let responses = futures::future::join_all(handles).await;
for response in responses {
let response_data = response?;
if !(200..300).contains(&response_data.status_code()) {
// if chunk upload failed - abort the upload
match self.abort_upload(&path, upload_id).await {
Ok(_) => {
return Err(error_from_response_data(response_data)?);
}
Err(error) => {
return Err(error);
}
}
}
let etag = response_data.as_str()?;
etags.push(etag.to_string());
}
// Finish the upload
let inner_data = etags
.clone()
.into_iter()
.enumerate()
.map(|(i, x)| Part {
etag: x,
part_number: i as u32 + 1,
})
.collect::<Vec<Part>>();
let response_data = self
.complete_multipart_upload(&path, &msg.upload_id, inner_data)
.await?;
Ok(response_data.status_code())
}
#[maybe_async::sync_impl]
fn _put_object_stream_with_content_type<R: Read>(
&self,
reader: &mut R,
s3_path: &str,
content_type: &str,
) -> Result<u16, S3Error> {
let msg = self.initiate_multipart_upload(s3_path, content_type)?;
let path = msg.key;
let upload_id = &msg.upload_id;
let mut part_number: u32 = 0;
let mut etags = Vec::new();
loop {
let chunk = crate::utils::read_chunk(reader)?;
if chunk.len() < CHUNK_SIZE {
if part_number == 0 {
// Files is not big enough for multipart upload, going with regular put_object
self.abort_upload(&path, upload_id)?;
self.put_object(s3_path, chunk.as_slice())?;
} else {
part_number += 1;
let part = self.put_multipart_chunk(
chunk,
&path,
part_number,
upload_id,
content_type,
)?;
etags.push(part.etag);
let inner_data = etags
.into_iter()
.enumerate()
.map(|(i, x)| Part {
etag: x,
part_number: i as u32 + 1,
})
.collect::<Vec<Part>>();
return Ok(self
.complete_multipart_upload(&path, upload_id, inner_data)?
.status_code());
// let response = std::str::from_utf8(data.as_slice())?;
}
} else {
part_number += 1;
let part =
self.put_multipart_chunk(chunk, &path, part_number, upload_id, content_type)?;
etags.push(part.etag.to_string());
}
}
}
/// Initiate multipart upload to s3.
#[maybe_async::async_impl]
pub async fn initiate_multipart_upload(
&self,
s3_path: &str,
content_type: &str,
) -> Result<InitiateMultipartUploadResponse, S3Error> {
let command = Command::InitiateMultipartUpload { content_type };
let request = RequestImpl::new(self, s3_path, command)?;
let response_data = request.response_data(false).await?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
let msg: InitiateMultipartUploadResponse =
quick_xml::de::from_str(response_data.as_str()?)?;
Ok(msg)
}
#[maybe_async::sync_impl]
pub fn initiate_multipart_upload(
&self,
s3_path: &str,
content_type: &str,
) -> Result<InitiateMultipartUploadResponse, S3Error> {
let command = Command::InitiateMultipartUpload { content_type };
let request = RequestImpl::new(self, s3_path, command)?;
let response_data = request.response_data(false)?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
let msg: InitiateMultipartUploadResponse =
quick_xml::de::from_str(response_data.as_str()?)?;
Ok(msg)
}
/// Upload a streamed multipart chunk to s3 using a previously initiated multipart upload
#[maybe_async::async_impl]
pub async fn put_multipart_stream<R: Read + Unpin>(
&self,
reader: &mut R,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let chunk = crate::utils::read_chunk(reader)?;
self.put_multipart_chunk(chunk, path, part_number, upload_id, content_type)
.await
}
#[maybe_async::sync_impl]
pub async fn put_multipart_stream<R: Read + Unpin>(
&self,
reader: &mut R,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let chunk = crate::utils::read_chunk(reader)?;
self.put_multipart_chunk(chunk, path, part_number, upload_id, content_type)
}
/// Upload a buffered multipart chunk to s3 using a previously initiated multipart upload
#[maybe_async::async_impl]
pub async fn put_multipart_chunk(
&self,
chunk: Vec<u8>,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let command = Command::PutObject {
// part_number,
content: &chunk,
multipart: Some(Multipart::new(part_number, upload_id)), // upload_id: &msg.upload_id,
content_type,
};
let request = RequestImpl::new(self, path, command)?;
let response_data = request.response_data(true).await?;
if !(200..300).contains(&response_data.status_code()) {
// if chunk upload failed - abort the upload
match self.abort_upload(path, upload_id).await {
Ok(_) => {
return Err(error_from_response_data(response_data)?);
}
Err(error) => {
return Err(error);
}
}
}
let etag = response_data.as_str()?;
Ok(Part {
etag: etag.to_string(),
part_number,
})
}sourcepub fn is_path_style(&self) -> bool
pub fn is_path_style(&self) -> bool
Get path_style field of the Bucket struct
sourcepub fn is_subdomain_style(&self) -> bool
pub fn is_subdomain_style(&self) -> bool
Get negated path_style field of the Bucket struct
sourcepub fn set_path_style(&mut self)
pub fn set_path_style(&mut self)
Configure bucket to use path-style urls and headers
sourcepub fn set_subdomain_style(&mut self)
pub fn set_subdomain_style(&mut self)
Configure bucket to use subdomain style urls and headers [default]
sourcepub fn set_request_timeout(&mut self, timeout: Option<Duration>)
pub fn set_request_timeout(&mut self, timeout: Option<Duration>)
Configure bucket to apply this request timeout to all HTTP
requests, or no (infinity) timeout if None. Defaults to
30 seconds.
Only the attohttpc and the Reqwest backends obey this option; async code may instead await with a timeout.
sourcepub fn set_listobjects_v1(&mut self)
pub fn set_listobjects_v1(&mut self)
Configure bucket to use the older ListObjects API
If your provider doesn’t support the ListObjectsV2 interface, set this to use the v1 ListObjects interface instead. This is currently needed at least for Google Cloud Storage.
sourcepub fn set_listobjects_v2(&mut self)
pub fn set_listobjects_v2(&mut self)
Configure bucket to use the newer ListObjectsV2 API
sourcepub fn name(&self) -> String
pub fn name(&self) -> String
Get a reference to the name of the S3 bucket.
Examples found in repository?
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
pub async fn copy_object_internal<F: AsRef<str>, T: AsRef<str>>(
&self,
from: F,
to: T,
) -> Result<u16, S3Error> {
let fq_from = {
let from = from.as_ref();
let from = from.strip_prefix('/').unwrap_or(from);
format!("{bucket}/{path}", bucket = self.name(), path = from)
};
self.copy_object(fq_from, to).await
}
#[maybe_async::maybe_async]
async fn copy_object<F: AsRef<str>, T: AsRef<str>>(
&self,
from: F,
to: T,
) -> Result<u16, S3Error> {
let command = Command::CopyObject {
from: from.as_ref(),
};
let request = RequestImpl::new(self, to.as_ref(), command)?;
let response_data = request.response_data(false).await?;
Ok(response_data.status_code())
}
/// Gets file from an S3 path.
///
/// # Example:
///
/// ```rust,no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.get_object("/test.file").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.get_object("/test.file")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.get_object_blocking("/test.file")?;
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn get_object<S: AsRef<str>>(&self, path: S) -> Result<ResponseData, S3Error> {
let command = Command::GetObject;
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data(false).await
}
/// Gets torrent from an S3 path.
///
/// # Example:
///
/// ```rust,no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.get_object_torrent("/test.file").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.get_object_torrent("/test.file")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.get_object_torrent_blocking("/test.file")?;
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn get_object_torrent<S: AsRef<str>>(
&self,
path: S,
) -> Result<ResponseData, S3Error> {
let command = Command::GetObjectTorrent;
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data(false).await
}
/// Gets specified inclusive byte range of file from an S3 path.
///
/// # Example:
///
/// ```rust,no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.get_object_range("/test.file", 0, Some(31)).await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.get_object_range("/test.file", 0, Some(31))?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.get_object_range_blocking("/test.file", 0, Some(31))?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn get_object_range<S: AsRef<str>>(
&self,
path: S,
start: u64,
end: Option<u64>,
) -> Result<ResponseData, S3Error> {
if let Some(end) = end {
assert!(start < end);
}
let command = Command::GetObjectRange { start, end };
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data(false).await
}
/// Stream range of bytes from S3 path to a local file, generic over T: Write.
///
/// # Example:
///
/// ```rust,no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
/// use std::fs::File;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
/// let mut output_file = File::create("output_file").expect("Unable to create file");
/// let mut async_output_file = tokio::fs::File::create("async_output_file").await.expect("Unable to create file");
/// #[cfg(feature = "with-async-std")]
/// let mut async_output_file = async_std::fs::File::create("async_output_file").await.expect("Unable to create file");
///
/// let start = 0;
/// let end = Some(1024);
///
/// // Async variant with `tokio` or `async-std` features
/// let status_code = bucket.get_object_range_to_writer("/test.file", start, end, &mut async_output_file).await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let status_code = bucket.get_object_range_to_writer("/test.file", start, end, &mut output_file)?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features. Based of the async branch
/// #[cfg(feature = "blocking")]
/// let status_code = bucket.get_object_range_to_writer_blocking("/test.file", start, end, &mut async_output_file)?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::async_impl]
pub async fn get_object_range_to_writer<T: AsyncWrite + Send + Unpin, S: AsRef<str>>(
&self,
path: S,
start: u64,
end: Option<u64>,
writer: &mut T,
) -> Result<u16, S3Error> {
if let Some(end) = end {
assert!(start < end);
}
let command = Command::GetObjectRange { start, end };
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data_to_writer(writer).await
}
#[maybe_async::sync_impl]
pub async fn get_object_range_to_writer<T: std::io::Write + Send, S: AsRef<str>>(
&self,
path: S,
start: u64,
end: Option<u64>,
writer: &mut T,
) -> Result<u16, S3Error> {
if let Some(end) = end {
assert!(start < end);
}
let command = Command::GetObjectRange { start, end };
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data_to_writer(writer)
}
/// Stream file from S3 path to a local file, generic over T: Write.
///
/// # Example:
///
/// ```rust,no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
/// use std::fs::File;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
/// let mut output_file = File::create("output_file").expect("Unable to create file");
/// let mut async_output_file = tokio::fs::File::create("async_output_file").await.expect("Unable to create file");
/// #[cfg(feature = "with-async-std")]
/// let mut async_output_file = async_std::fs::File::create("async_output_file").await.expect("Unable to create file");
///
/// // Async variant with `tokio` or `async-std` features
/// let status_code = bucket.get_object_to_writer("/test.file", &mut async_output_file).await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let status_code = bucket.get_object_to_writer("/test.file", &mut output_file)?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features. Based of the async branch
/// #[cfg(feature = "blocking")]
/// let status_code = bucket.get_object_to_writer_blocking("/test.file", &mut async_output_file)?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::async_impl]
pub async fn get_object_to_writer<T: AsyncWrite + Send + Unpin, S: AsRef<str>>(
&self,
path: S,
writer: &mut T,
) -> Result<u16, S3Error> {
let command = Command::GetObject;
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data_to_writer(writer).await
}
#[maybe_async::sync_impl]
pub fn get_object_to_writer<T: std::io::Write + Send, S: AsRef<str>>(
&self,
path: S,
writer: &mut T,
) -> Result<u16, S3Error> {
let command = Command::GetObject;
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data_to_writer(writer)
}
/// Stream file from S3 path to a local file using an async stream.
///
/// # Example
///
/// ```rust,no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
/// #[cfg(feature = "with-tokio")]
/// use tokio_stream::StreamExt;
/// #[cfg(feature = "with-tokio")]
/// use tokio::io::AsyncWriteExt;
/// #[cfg(feature = "with-async-std")]
/// use futures_util::StreamExt;
/// #[cfg(feature = "with-async-std")]
/// use futures_util::AsyncWriteExt;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
/// let path = "path";
///
/// let mut response_data_stream = bucket.get_object_stream(path).await?;
///
/// #[cfg(feature = "with-tokio")]
/// let mut async_output_file = tokio::fs::File::create("async_output_file").await.expect("Unable to create file");
/// #[cfg(feature = "with-async-std")]
/// let mut async_output_file = async_std::fs::File::create("async_output_file").await.expect("Unable to create file");
///
/// while let Some(chunk) = response_data_stream.bytes().next().await {
/// async_output_file.write_all(&chunk).await?;
/// }
///
/// #
/// # Ok(())
/// # }
/// ```
#[cfg(any(feature = "with-tokio", feature = "with-async-std"))]
pub async fn get_object_stream<S: AsRef<str>>(
&self,
path: S,
) -> Result<ResponseDataStream, S3Error> {
let command = Command::GetObject;
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data_to_stream().await
}
/// Stream file from local path to s3, generic over T: Write.
///
/// # Example:
///
/// ```rust,no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
/// use std::fs::File;
/// use std::io::Write;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
/// let path = "path";
/// let test: Vec<u8> = (0..1000).map(|_| 42).collect();
/// let mut file = File::create(path)?;
/// // tokio open file
/// let mut async_output_file = tokio::fs::File::create("async_output_file").await.expect("Unable to create file");
/// file.write_all(&test)?;
///
/// // Generic over std::io::Read
/// #[cfg(feature = "with-tokio")]
/// let status_code = bucket.put_object_stream(&mut async_output_file, "/path").await?;
///
///
/// #[cfg(feature = "with-async-std")]
/// let mut async_output_file = async_std::fs::File::create("async_output_file").await.expect("Unable to create file");
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// // Generic over std::io::Read
/// let status_code = bucket.put_object_stream(&mut path, "/path")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let status_code = bucket.put_object_stream_blocking(&mut path, "/path")?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::async_impl]
pub async fn put_object_stream<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: impl AsRef<str>,
) -> Result<u16, S3Error> {
self._put_object_stream_with_content_type(
reader,
s3_path.as_ref(),
"application/octet-stream",
)
.await
}
#[maybe_async::sync_impl]
pub fn put_object_stream<R: Read>(
&self,
reader: &mut R,
s3_path: impl AsRef<str>,
) -> Result<u16, S3Error> {
self._put_object_stream_with_content_type(
reader,
s3_path.as_ref(),
"application/octet-stream",
)
}
/// Stream file from local path to s3, generic over T: Write with explicit content type.
///
/// # Example:
///
/// ```rust,no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
/// use std::fs::File;
/// use std::io::Write;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
/// let path = "path";
/// let test: Vec<u8> = (0..1000).map(|_| 42).collect();
/// let mut file = File::create(path)?;
/// file.write_all(&test)?;
///
/// #[cfg(feature = "with-tokio")]
/// let mut async_output_file = tokio::fs::File::create("async_output_file").await.expect("Unable to create file");
///
/// #[cfg(feature = "with-async-std")]
/// let mut async_output_file = async_std::fs::File::create("async_output_file").await.expect("Unable to create file");
///
/// // Async variant with `tokio` or `async-std` features
/// // Generic over std::io::Read
/// let status_code = bucket
/// .put_object_stream_with_content_type(&mut async_output_file, "/path", "application/octet-stream")
/// .await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// // Generic over std::io::Read
/// let status_code = bucket
/// .put_object_stream_with_content_type(&mut path, "/path", "application/octet-stream")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let status_code = bucket
/// .put_object_stream_with_content_type_blocking(&mut path, "/path", "application/octet-stream")?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::async_impl]
pub async fn put_object_stream_with_content_type<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: impl AsRef<str>,
content_type: impl AsRef<str>,
) -> Result<u16, S3Error> {
self._put_object_stream_with_content_type(reader, s3_path.as_ref(), content_type.as_ref())
.await
}
#[maybe_async::sync_impl]
pub fn put_object_stream_with_content_type<R: Read>(
&self,
reader: &mut R,
s3_path: impl AsRef<str>,
content_type: impl AsRef<str>,
) -> Result<u16, S3Error> {
self._put_object_stream_with_content_type(reader, s3_path.as_ref(), content_type.as_ref())
}
#[maybe_async::async_impl]
async fn make_multipart_request(
&self,
path: &str,
chunk: Vec<u8>,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<ResponseData, S3Error> {
let command = Command::PutObject {
content: &chunk,
multipart: Some(Multipart::new(part_number, upload_id)), // upload_id: &msg.upload_id,
content_type,
};
let request = RequestImpl::new(self, path, command)?;
request.response_data(true).await
}
#[maybe_async::async_impl]
async fn _put_object_stream_with_content_type<R: AsyncRead + Unpin>(
&self,
reader: &mut R,
s3_path: &str,
content_type: &str,
) -> Result<u16, S3Error> {
// If the file is smaller CHUNK_SIZE, just do a regular upload.
// Otherwise perform a multi-part upload.
let first_chunk = crate::utils::read_chunk_async(reader).await?;
if first_chunk.len() < CHUNK_SIZE {
let response_data = self
.put_object_with_content_type(s3_path, first_chunk.as_slice(), content_type)
.await?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
return Ok(response_data.status_code());
}
let msg = self
.initiate_multipart_upload(s3_path, content_type)
.await?;
let path = msg.key;
let upload_id = &msg.upload_id;
let mut part_number: u32 = 0;
let mut etags = Vec::new();
// Collect request handles
let mut handles = vec![];
loop {
let chunk = if part_number == 0 {
first_chunk.clone()
} else {
crate::utils::read_chunk_async(reader).await?
};
let done = chunk.len() < CHUNK_SIZE;
// Start chunk upload
part_number += 1;
handles.push(self.make_multipart_request(
&path,
chunk,
part_number,
upload_id,
content_type,
));
if done {
break;
}
}
// Wait for all chunks to finish (or fail)
let responses = futures::future::join_all(handles).await;
for response in responses {
let response_data = response?;
if !(200..300).contains(&response_data.status_code()) {
// if chunk upload failed - abort the upload
match self.abort_upload(&path, upload_id).await {
Ok(_) => {
return Err(error_from_response_data(response_data)?);
}
Err(error) => {
return Err(error);
}
}
}
let etag = response_data.as_str()?;
etags.push(etag.to_string());
}
// Finish the upload
let inner_data = etags
.clone()
.into_iter()
.enumerate()
.map(|(i, x)| Part {
etag: x,
part_number: i as u32 + 1,
})
.collect::<Vec<Part>>();
let response_data = self
.complete_multipart_upload(&path, &msg.upload_id, inner_data)
.await?;
Ok(response_data.status_code())
}
#[maybe_async::sync_impl]
fn _put_object_stream_with_content_type<R: Read>(
&self,
reader: &mut R,
s3_path: &str,
content_type: &str,
) -> Result<u16, S3Error> {
let msg = self.initiate_multipart_upload(s3_path, content_type)?;
let path = msg.key;
let upload_id = &msg.upload_id;
let mut part_number: u32 = 0;
let mut etags = Vec::new();
loop {
let chunk = crate::utils::read_chunk(reader)?;
if chunk.len() < CHUNK_SIZE {
if part_number == 0 {
// Files is not big enough for multipart upload, going with regular put_object
self.abort_upload(&path, upload_id)?;
self.put_object(s3_path, chunk.as_slice())?;
} else {
part_number += 1;
let part = self.put_multipart_chunk(
chunk,
&path,
part_number,
upload_id,
content_type,
)?;
etags.push(part.etag);
let inner_data = etags
.into_iter()
.enumerate()
.map(|(i, x)| Part {
etag: x,
part_number: i as u32 + 1,
})
.collect::<Vec<Part>>();
return Ok(self
.complete_multipart_upload(&path, upload_id, inner_data)?
.status_code());
// let response = std::str::from_utf8(data.as_slice())?;
}
} else {
part_number += 1;
let part =
self.put_multipart_chunk(chunk, &path, part_number, upload_id, content_type)?;
etags.push(part.etag.to_string());
}
}
}
/// Initiate multipart upload to s3.
#[maybe_async::async_impl]
pub async fn initiate_multipart_upload(
&self,
s3_path: &str,
content_type: &str,
) -> Result<InitiateMultipartUploadResponse, S3Error> {
let command = Command::InitiateMultipartUpload { content_type };
let request = RequestImpl::new(self, s3_path, command)?;
let response_data = request.response_data(false).await?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
let msg: InitiateMultipartUploadResponse =
quick_xml::de::from_str(response_data.as_str()?)?;
Ok(msg)
}
#[maybe_async::sync_impl]
pub fn initiate_multipart_upload(
&self,
s3_path: &str,
content_type: &str,
) -> Result<InitiateMultipartUploadResponse, S3Error> {
let command = Command::InitiateMultipartUpload { content_type };
let request = RequestImpl::new(self, s3_path, command)?;
let response_data = request.response_data(false)?;
if response_data.status_code() >= 300 {
return Err(error_from_response_data(response_data)?);
}
let msg: InitiateMultipartUploadResponse =
quick_xml::de::from_str(response_data.as_str()?)?;
Ok(msg)
}
/// Upload a streamed multipart chunk to s3 using a previously initiated multipart upload
#[maybe_async::async_impl]
pub async fn put_multipart_stream<R: Read + Unpin>(
&self,
reader: &mut R,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let chunk = crate::utils::read_chunk(reader)?;
self.put_multipart_chunk(chunk, path, part_number, upload_id, content_type)
.await
}
#[maybe_async::sync_impl]
pub async fn put_multipart_stream<R: Read + Unpin>(
&self,
reader: &mut R,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let chunk = crate::utils::read_chunk(reader)?;
self.put_multipart_chunk(chunk, path, part_number, upload_id, content_type)
}
/// Upload a buffered multipart chunk to s3 using a previously initiated multipart upload
#[maybe_async::async_impl]
pub async fn put_multipart_chunk(
&self,
chunk: Vec<u8>,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let command = Command::PutObject {
// part_number,
content: &chunk,
multipart: Some(Multipart::new(part_number, upload_id)), // upload_id: &msg.upload_id,
content_type,
};
let request = RequestImpl::new(self, path, command)?;
let response_data = request.response_data(true).await?;
if !(200..300).contains(&response_data.status_code()) {
// if chunk upload failed - abort the upload
match self.abort_upload(path, upload_id).await {
Ok(_) => {
return Err(error_from_response_data(response_data)?);
}
Err(error) => {
return Err(error);
}
}
}
let etag = response_data.as_str()?;
Ok(Part {
etag: etag.to_string(),
part_number,
})
}
#[maybe_async::sync_impl]
pub fn put_multipart_chunk(
&self,
chunk: Vec<u8>,
path: &str,
part_number: u32,
upload_id: &str,
content_type: &str,
) -> Result<Part, S3Error> {
let command = Command::PutObject {
// part_number,
content: &chunk,
multipart: Some(Multipart::new(part_number, upload_id)), // upload_id: &msg.upload_id,
content_type,
};
let request = RequestImpl::new(self, path, command)?;
let response_data = request.response_data(true)?;
if !(200..300).contains(&response_data.status_code()) {
// if chunk upload failed - abort the upload
match self.abort_upload(path, upload_id) {
Ok(_) => {
return Err(error_from_response_data(response_data)?);
}
Err(error) => {
return Err(error);
}
}
}
let etag = response_data.as_str()?;
Ok(Part {
etag: etag.to_string(),
part_number,
})
}
/// Completes a previously initiated multipart upload, with optional final data chunks
#[maybe_async::async_impl]
pub async fn complete_multipart_upload(
&self,
path: &str,
upload_id: &str,
parts: Vec<Part>,
) -> Result<ResponseData, S3Error> {
let data = CompleteMultipartUploadData { parts };
let complete = Command::CompleteMultipartUpload { upload_id, data };
let complete_request = RequestImpl::new(self, path, complete)?;
complete_request.response_data(false).await
}
#[maybe_async::sync_impl]
pub fn complete_multipart_upload(
&self,
path: &str,
upload_id: &str,
parts: Vec<Part>,
) -> Result<ResponseData, S3Error> {
let data = CompleteMultipartUploadData { parts };
let complete = Command::CompleteMultipartUpload { upload_id, data };
let complete_request = RequestImpl::new(self, path, complete)?;
complete_request.response_data(false)
}
/// Get Bucket location.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let (region, status_code) = bucket.location().await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let (region, status_code) = bucket.location()?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let (region, status_code) = bucket.location_blocking()?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn location(&self) -> Result<(Region, u16), S3Error> {
let request = RequestImpl::new(self, "?location", Command::GetBucketLocation)?;
let response_data = request.response_data(false).await?;
let region_string = String::from_utf8_lossy(response_data.as_slice());
let region = match quick_xml::de::from_reader(region_string.as_bytes()) {
Ok(r) => {
let location_result: BucketLocationResult = r;
location_result.region.parse()?
}
Err(e) => {
if response_data.status_code() == 200 {
Region::Custom {
region: "Custom".to_string(),
endpoint: "".to_string(),
}
} else {
Region::Custom {
region: format!("Error encountered : {}", e),
endpoint: "".to_string(),
}
}
}
};
Ok((region, response_data.status_code()))
}
/// Delete file from an S3 path.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.delete_object("/test.file").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.delete_object("/test.file")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.delete_object_blocking("/test.file")?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn delete_object<S: AsRef<str>>(&self, path: S) -> Result<ResponseData, S3Error> {
let command = Command::DeleteObject;
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data(false).await
}
/// Head object from S3.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let (head_object_result, code) = bucket.head_object("/test.png").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let (head_object_result, code) = bucket.head_object("/test.png")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let (head_object_result, code) = bucket.head_object_blocking("/test.png")?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn head_object<S: AsRef<str>>(
&self,
path: S,
) -> Result<(HeadObjectResult, u16), S3Error> {
let command = Command::HeadObject;
let request = RequestImpl::new(self, path.as_ref(), command)?;
let (headers, status) = request.response_header().await?;
let header_object = HeadObjectResult::from(&headers);
Ok((header_object, status))
}
/// Put into an S3 bucket, with explicit content-type.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
/// let content = "I want to go to S3".as_bytes();
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.put_object_with_content_type("/test.file", content, "text/plain").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.put_object_with_content_type("/test.file", content, "text/plain")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.put_object_with_content_type_blocking("/test.file", content, "text/plain")?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn put_object_with_content_type<S: AsRef<str>>(
&self,
path: S,
content: &[u8],
content_type: &str,
) -> Result<ResponseData, S3Error> {
let command = Command::PutObject {
content,
content_type,
multipart: None,
};
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data(true).await
}
/// Put into an S3 bucket.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
/// let content = "I want to go to S3".as_bytes();
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.put_object("/test.file", content).await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.put_object("/test.file", content)?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.put_object_blocking("/test.file", content)?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn put_object<S: AsRef<str>>(
&self,
path: S,
content: &[u8],
) -> Result<ResponseData, S3Error> {
self.put_object_with_content_type(path, content, "application/octet-stream")
.await
}
fn _tags_xml<S: AsRef<str>>(&self, tags: &[(S, S)]) -> String {
let mut s = String::new();
let content = tags
.iter()
.map(|&(ref name, ref value)| {
format!(
"<Tag><Key>{}</Key><Value>{}</Value></Tag>",
name.as_ref(),
value.as_ref()
)
})
.fold(String::new(), |mut a, b| {
a.push_str(b.as_str());
a
});
s.push_str("<Tagging><TagSet>");
s.push_str(&content);
s.push_str("</TagSet></Tagging>");
s
}
/// Tag an S3 object.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.put_object_tagging("/test.file", &[("Tag1", "Value1"), ("Tag2", "Value2")]).await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.put_object_tagging("/test.file", &[("Tag1", "Value1"), ("Tag2", "Value2")])?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.put_object_tagging_blocking("/test.file", &[("Tag1", "Value1"), ("Tag2", "Value2")])?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn put_object_tagging<S: AsRef<str>>(
&self,
path: &str,
tags: &[(S, S)],
) -> Result<ResponseData, S3Error> {
let content = self._tags_xml(tags);
let command = Command::PutObjectTagging { tags: &content };
let request = RequestImpl::new(self, path, command)?;
request.response_data(false).await
}
/// Delete tags from an S3 object.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.delete_object_tagging("/test.file").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.delete_object_tagging("/test.file")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.delete_object_tagging_blocking("/test.file")?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn delete_object_tagging<S: AsRef<str>>(
&self,
path: S,
) -> Result<ResponseData, S3Error> {
let command = Command::DeleteObjectTagging;
let request = RequestImpl::new(self, path.as_ref(), command)?;
request.response_data(false).await
}
/// Retrieve an S3 object list of tags.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let response_data = bucket.get_object_tagging("/test.file").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let response_data = bucket.get_object_tagging("/test.file")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let response_data = bucket.get_object_tagging_blocking("/test.file")?;
/// #
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "tags")]
#[maybe_async::maybe_async]
pub async fn get_object_tagging<S: AsRef<str>>(
&self,
path: S,
) -> Result<(Vec<Tag>, u16), S3Error> {
let command = Command::GetObjectTagging {};
let request = RequestImpl::new(self, path.as_ref(), command)?;
let result = request.response_data(false).await?;
let mut tags = Vec::new();
if result.status_code() == 200 {
let result_string = String::from_utf8_lossy(result.as_slice());
// Add namespace if it doesn't exist
let ns = "http://s3.amazonaws.com/doc/2006-03-01/";
let result_string =
if let Err(minidom::Error::MissingNamespace) = result_string.parse::<Element>() {
result_string
.replace("<Tagging>", &format!("<Tagging xmlns=\"{}\">", ns))
.into()
} else {
result_string
};
if let Ok(tagging) = result_string.parse::<Element>() {
for tag_set in tagging.children() {
if tag_set.is("TagSet", ns) {
for tag in tag_set.children() {
if tag.is("Tag", ns) {
let key = if let Some(element) = tag.get_child("Key", ns) {
element.text()
} else {
"Could not parse Key from Tag".to_string()
};
let value = if let Some(element) = tag.get_child("Value", ns) {
element.text()
} else {
"Could not parse Values from Tag".to_string()
};
tags.push(Tag { key, value });
}
}
}
}
}
}
Ok((tags, result.status_code()))
}
#[maybe_async::maybe_async]
pub async fn list_page(
&self,
prefix: String,
delimiter: Option<String>,
continuation_token: Option<String>,
start_after: Option<String>,
max_keys: Option<usize>,
) -> Result<(ListBucketResult, u16), S3Error> {
let command = if self.listobjects_v2 {
Command::ListObjectsV2 {
prefix,
delimiter,
continuation_token,
start_after,
max_keys,
}
} else {
// In the v1 ListObjects request, there is only one "marker"
// field that serves as both the initial starting position,
// and as the continuation token.
Command::ListObjects {
prefix,
delimiter,
marker: std::cmp::max(continuation_token, start_after),
max_keys,
}
};
let request = RequestImpl::new(self, "/", command)?;
let response_data = request.response_data(false).await?;
let list_bucket_result = quick_xml::de::from_reader(response_data.as_slice())?;
Ok((list_bucket_result, response_data.status_code()))
}
/// List the contents of an S3 bucket.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let results = bucket.list("/".to_string(), Some("/".to_string())).await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let results = bucket.list("/".to_string(), Some("/".to_string()))?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let results = bucket.list_blocking("/".to_string(), Some("/".to_string()))?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn list(
&self,
prefix: String,
delimiter: Option<String>,
) -> Result<Vec<ListBucketResult>, S3Error> {
let the_bucket = self.to_owned();
let mut results = Vec::new();
let mut continuation_token = None;
loop {
let (list_bucket_result, _) = the_bucket
.list_page(
prefix.clone(),
delimiter.clone(),
continuation_token,
None,
None,
)
.await?;
continuation_token = list_bucket_result.next_continuation_token.clone();
results.push(list_bucket_result);
if continuation_token.is_none() {
break;
}
}
Ok(results)
}
#[maybe_async::maybe_async]
pub async fn list_multiparts_uploads_page(
&self,
prefix: Option<&str>,
delimiter: Option<&str>,
key_marker: Option<String>,
max_uploads: Option<usize>,
) -> Result<(ListMultipartUploadsResult, u16), S3Error> {
let command = Command::ListMultipartUploads {
prefix,
delimiter,
key_marker,
max_uploads,
};
let request = RequestImpl::new(self, "/", command)?;
let response_data = request.response_data(false).await?;
let list_bucket_result = quick_xml::de::from_reader(response_data.as_slice())?;
Ok((list_bucket_result, response_data.status_code()))
}
/// List the ongoing multipart uploads of an S3 bucket. This may be useful to cleanup failed
/// uploads, together with [`crate::bucket::Bucket::abort_upload`].
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let results = bucket.list_multiparts_uploads(Some("/"), Some("/")).await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let results = bucket.list_multiparts_uploads(Some("/"), Some("/"))?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let results = bucket.list_multiparts_uploads_blocking(Some("/"), Some("/"))?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn list_multiparts_uploads(
&self,
prefix: Option<&str>,
delimiter: Option<&str>,
) -> Result<Vec<ListMultipartUploadsResult>, S3Error> {
let the_bucket = self.to_owned();
let mut results = Vec::new();
let mut next_marker: Option<String> = None;
loop {
let (list_multiparts_uploads_result, _) = the_bucket
.list_multiparts_uploads_page(prefix, delimiter, next_marker, None)
.await?;
let is_truncated = list_multiparts_uploads_result.is_truncated;
next_marker = list_multiparts_uploads_result.next_marker.clone();
results.push(list_multiparts_uploads_result);
if !is_truncated {
break;
}
}
Ok(results)
}
/// Abort a running multipart upload.
///
/// # Example:
///
/// ```no_run
/// use s3::bucket::Bucket;
/// use s3::creds::Credentials;
/// use anyhow::Result;
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
///
/// let bucket_name = "rust-s3-test";
/// let region = "us-east-1".parse()?;
/// let credentials = Credentials::default()?;
/// let bucket = Bucket::new(bucket_name, region, credentials)?;
///
/// // Async variant with `tokio` or `async-std` features
/// let results = bucket.abort_upload("/some/file.txt", "ZDFjM2I0YmEtMzU3ZC00OTQ1LTlkNGUtMTgxZThjYzIwNjA2").await?;
///
/// // `sync` feature will produce an identical method
/// #[cfg(feature = "sync")]
/// let results = bucket.abort_upload("/some/file.txt", "ZDFjM2I0YmEtMzU3ZC00OTQ1LTlkNGUtMTgxZThjYzIwNjA2")?;
///
/// // Blocking variant, generated with `blocking` feature in combination
/// // with `tokio` or `async-std` features.
/// #[cfg(feature = "blocking")]
/// let results = bucket.abort_upload_blocking("/some/file.txt", "ZDFjM2I0YmEtMzU3ZC00OTQ1LTlkNGUtMTgxZThjYzIwNjA2")?;
/// #
/// # Ok(())
/// # }
/// ```
#[maybe_async::maybe_async]
pub async fn abort_upload(&self, key: &str, upload_id: &str) -> Result<(), S3Error> {
let abort = Command::AbortMultipartUpload { upload_id };
let abort_request = RequestImpl::new(self, key, abort)?;
let response_data = abort_request.response_data(false).await?;
if (200..300).contains(&response_data.status_code()) {
Ok(())
} else {
let utf8_content = String::from_utf8(response_data.as_slice().to_vec())?;
Err(S3Error::Http(response_data.status_code(), utf8_content))
}
}
/// Get path_style field of the Bucket struct
pub fn is_path_style(&self) -> bool {
self.path_style
}
/// Get negated path_style field of the Bucket struct
pub fn is_subdomain_style(&self) -> bool {
!self.path_style
}
/// Configure bucket to use path-style urls and headers
pub fn set_path_style(&mut self) {
self.path_style = true;
}
/// Configure bucket to use subdomain style urls and headers \[default\]
pub fn set_subdomain_style(&mut self) {
self.path_style = false;
}
/// Configure bucket to apply this request timeout to all HTTP
/// requests, or no (infinity) timeout if `None`. Defaults to
/// 30 seconds.
///
/// Only the attohttpc and the Reqwest backends obey this option;
/// async code may instead await with a timeout.
pub fn set_request_timeout(&mut self, timeout: Option<Duration>) {
self.request_timeout = timeout;
}
/// Configure bucket to use the older ListObjects API
///
/// If your provider doesn't support the ListObjectsV2 interface, set this to
/// use the v1 ListObjects interface instead. This is currently needed at least
/// for Google Cloud Storage.
pub fn set_listobjects_v1(&mut self) {
self.listobjects_v2 = false;
}
/// Configure bucket to use the newer ListObjectsV2 API
pub fn set_listobjects_v2(&mut self) {
self.listobjects_v2 = true;
}
/// Get a reference to the name of the S3 bucket.
pub fn name(&self) -> String {
self.name.to_string()
}
// Get a reference to the hostname of the S3 API endpoint.
pub fn host(&self) -> String {
if self.path_style {
self.path_style_host()
} else {
self.subdomain_style_host()
}
}
pub fn url(&self) -> String {
if self.path_style {
format!(
"{}://{}/{}",
self.scheme(),
self.path_style_host(),
self.name()
)
} else {
format!("{}://{}", self.scheme(), self.subdomain_style_host())
}
}sourcepub fn url(&self) -> String
pub fn url(&self) -> String
Examples found in repository?
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
fn url(&self) -> Result<Url, S3Error> {
let mut url_str = self.bucket().url();
if let Command::CreateBucket { .. } = self.command() {
return Ok(Url::parse(&url_str)?);
}
let path = if self.path().starts_with('/') {
self.path()[1..].to_string()
} else {
self.path()[..].to_string()
};
url_str.push('/');
url_str.push_str(&signing::uri_encode(&path, false));
// Append to url_path
#[allow(clippy::collapsible_match)]
match self.command() {
Command::InitiateMultipartUpload { .. } | Command::ListMultipartUploads { .. } => {
url_str.push_str("?uploads")
}
Command::AbortMultipartUpload { upload_id } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::CompleteMultipartUpload { upload_id, .. } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::GetObjectTorrent => url_str.push_str("?torrent"),
Command::PutObject { multipart, .. } => {
if let Some(multipart) = multipart {
url_str.push_str(&multipart.query_string())
}
}
_ => {}
}
let mut url = Url::parse(&url_str)?;
for (key, value) in &self.bucket().extra_query {
url.query_pairs_mut().append_pair(key, value);
}
if let Command::ListObjectsV2 {
prefix,
delimiter,
continuation_token,
start_after,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
query_pairs.append_pair("list-type", "2");
if let Some(token) = continuation_token {
query_pairs.append_pair("continuation-token", &token);
}
if let Some(start_after) = start_after {
query_pairs.append_pair("start-after", &start_after);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
if let Command::ListObjects {
prefix,
delimiter,
marker,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
if let Some(marker) = marker {
query_pairs.append_pair("marker", &marker);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
match self.command() {
Command::ListMultipartUploads {
prefix,
delimiter,
key_marker,
max_uploads,
} => {
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", d));
if let Some(prefix) = prefix {
query_pairs.append_pair("prefix", prefix);
}
if let Some(key_marker) = key_marker {
query_pairs.append_pair("key-marker", &key_marker);
}
if let Some(max_uploads) = max_uploads {
query_pairs.append_pair("max-uploads", max_uploads.to_string().as_str());
}
}
Command::PutObjectTagging { .. }
| Command::GetObjectTagging
| Command::DeleteObjectTagging => {
url.query_pairs_mut().append_pair("tagging", "");
}
_ => {}
}
Ok(url)
}sourcepub fn path_style_host(&self) -> String
pub fn path_style_host(&self) -> String
Get a paths-style reference to the hostname of the S3 API endpoint.
Examples found in repository?
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
pub fn host(&self) -> String {
if self.path_style {
self.path_style_host()
} else {
self.subdomain_style_host()
}
}
pub fn url(&self) -> String {
if self.path_style {
format!(
"{}://{}/{}",
self.scheme(),
self.path_style_host(),
self.name()
)
} else {
format!("{}://{}", self.scheme(), self.subdomain_style_host())
}
}sourcepub fn subdomain_style_host(&self) -> String
pub fn subdomain_style_host(&self) -> String
Examples found in repository?
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
pub fn host(&self) -> String {
if self.path_style {
self.path_style_host()
} else {
self.subdomain_style_host()
}
}
pub fn url(&self) -> String {
if self.path_style {
format!(
"{}://{}/{}",
self.scheme(),
self.path_style_host(),
self.name()
)
} else {
format!("{}://{}", self.scheme(), self.subdomain_style_host())
}
}sourcepub fn scheme(&self) -> String
pub fn scheme(&self) -> String
Examples found in repository?
2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
pub fn url(&self) -> String {
if self.path_style {
format!(
"{}://{}/{}",
self.scheme(),
self.path_style_host(),
self.name()
)
} else {
format!("{}://{}", self.scheme(), self.subdomain_style_host())
}
}sourcepub fn region(&self) -> Region
pub fn region(&self) -> Region
Get the region this object will connect to.
Examples found in repository?
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
fn signing_key(&self) -> Result<Vec<u8>, S3Error> {
signing::signing_key(
&self.datetime(),
&self
.bucket()
.secret_key()?
.expect("Secret key must be provided to sign headers, found None"),
&self.bucket().region(),
"s3",
)
}
fn request_body(&self) -> Vec<u8> {
if let Command::PutObject { content, .. } = self.command() {
Vec::from(content)
} else if let Command::PutObjectTagging { tags } = self.command() {
Vec::from(tags)
} else if let Command::UploadPart { content, .. } = self.command() {
Vec::from(content)
} else if let Command::CompleteMultipartUpload { data, .. } = &self.command() {
let body = data.to_string();
println!("CompleteMultipartUpload: {}", body);
body.as_bytes().to_vec()
} else if let Command::CreateBucket { config } = &self.command() {
if let Some(payload) = config.location_constraint_payload() {
Vec::from(payload)
} else {
Vec::new()
}
} else {
Vec::new()
}
}
fn long_date(&self) -> Result<String, S3Error> {
Ok(self.datetime().format(LONG_DATETIME)?)
}
fn string_to_sign(&self, request: &str) -> Result<String, S3Error> {
match self.command() {
Command::PresignPost { post_policy, .. } => Ok(post_policy),
_ => Ok(signing::string_to_sign(
&self.datetime(),
&self.bucket().region(),
request,
)?),
}
}
fn host_header(&self) -> String {
self.bucket().host()
}
fn presigned(&self) -> Result<String, S3Error> {
let (expiry, custom_headers, custom_queries) = match self.command() {
Command::PresignGet {
expiry_secs,
custom_queries,
} => (expiry_secs, None, custom_queries),
Command::PresignPut {
expiry_secs,
custom_headers,
} => (expiry_secs, custom_headers, None),
Command::PresignDelete { expiry_secs } => (expiry_secs, None, None),
_ => unreachable!(),
};
Ok(format!(
"{}&X-Amz-Signature={}",
self.presigned_url_no_sig(expiry, custom_headers.as_ref(), custom_queries.as_ref())?,
self.presigned_authorization(custom_headers.as_ref())?
))
}
fn presigned_authorization(
&self,
custom_headers: Option<&HeaderMap>,
) -> Result<String, S3Error> {
let mut headers = HeaderMap::new();
let host_header = self.host_header();
headers.insert(HOST, host_header.parse()?);
if let Some(custom_headers) = custom_headers {
for (k, v) in custom_headers.iter() {
headers.insert(k.clone(), v.clone());
}
}
let canonical_request = self.presigned_canonical_request(&headers)?;
let string_to_sign = self.string_to_sign(&canonical_request)?;
let mut hmac = signing::HmacSha256::new_from_slice(&self.signing_key()?)?;
hmac.update(string_to_sign.as_bytes());
let signature = hex::encode(hmac.finalize().into_bytes());
// let signed_header = signing::signed_header_string(&headers);
Ok(signature)
}
fn presigned_canonical_request(&self, headers: &HeaderMap) -> Result<String, S3Error> {
let (expiry, custom_headers, custom_queries) = match self.command() {
Command::PresignGet {
expiry_secs,
custom_queries,
} => (expiry_secs, None, custom_queries),
Command::PresignPut {
expiry_secs,
custom_headers,
} => (expiry_secs, custom_headers, None),
Command::PresignDelete { expiry_secs } => (expiry_secs, None, None),
_ => unreachable!(),
};
signing::canonical_request(
&self.command().http_verb().to_string(),
&self.presigned_url_no_sig(expiry, custom_headers.as_ref(), custom_queries.as_ref())?,
headers,
"UNSIGNED-PAYLOAD",
)
}
fn presigned_url_no_sig(
&self,
expiry: u32,
custom_headers: Option<&HeaderMap>,
custom_queries: Option<&HashMap<String, String>>,
) -> Result<Url, S3Error> {
let bucket = self.bucket();
let token = if let Some(security_token) = bucket.security_token()? {
Some(security_token)
} else {
bucket.session_token()?
};
let url = Url::parse(&format!(
"{}{}{}",
self.url()?,
&signing::authorization_query_params_no_sig(
&self.bucket().access_key()?.unwrap_or_default(),
&self.datetime(),
&self.bucket().region(),
expiry,
custom_headers,
token.as_ref()
)?,
&signing::flatten_queries(custom_queries)?,
))?;
Ok(url)
}
fn url(&self) -> Result<Url, S3Error> {
let mut url_str = self.bucket().url();
if let Command::CreateBucket { .. } = self.command() {
return Ok(Url::parse(&url_str)?);
}
let path = if self.path().starts_with('/') {
self.path()[1..].to_string()
} else {
self.path()[..].to_string()
};
url_str.push('/');
url_str.push_str(&signing::uri_encode(&path, false));
// Append to url_path
#[allow(clippy::collapsible_match)]
match self.command() {
Command::InitiateMultipartUpload { .. } | Command::ListMultipartUploads { .. } => {
url_str.push_str("?uploads")
}
Command::AbortMultipartUpload { upload_id } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::CompleteMultipartUpload { upload_id, .. } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::GetObjectTorrent => url_str.push_str("?torrent"),
Command::PutObject { multipart, .. } => {
if let Some(multipart) = multipart {
url_str.push_str(&multipart.query_string())
}
}
_ => {}
}
let mut url = Url::parse(&url_str)?;
for (key, value) in &self.bucket().extra_query {
url.query_pairs_mut().append_pair(key, value);
}
if let Command::ListObjectsV2 {
prefix,
delimiter,
continuation_token,
start_after,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
query_pairs.append_pair("list-type", "2");
if let Some(token) = continuation_token {
query_pairs.append_pair("continuation-token", &token);
}
if let Some(start_after) = start_after {
query_pairs.append_pair("start-after", &start_after);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
if let Command::ListObjects {
prefix,
delimiter,
marker,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
if let Some(marker) = marker {
query_pairs.append_pair("marker", &marker);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
match self.command() {
Command::ListMultipartUploads {
prefix,
delimiter,
key_marker,
max_uploads,
} => {
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", d));
if let Some(prefix) = prefix {
query_pairs.append_pair("prefix", prefix);
}
if let Some(key_marker) = key_marker {
query_pairs.append_pair("key-marker", &key_marker);
}
if let Some(max_uploads) = max_uploads {
query_pairs.append_pair("max-uploads", max_uploads.to_string().as_str());
}
}
Command::PutObjectTagging { .. }
| Command::GetObjectTagging
| Command::DeleteObjectTagging => {
url.query_pairs_mut().append_pair("tagging", "");
}
_ => {}
}
Ok(url)
}
fn canonical_request(&self, headers: &HeaderMap) -> Result<String, S3Error> {
signing::canonical_request(
&self.command().http_verb().to_string(),
&self.url()?,
headers,
&self.command().sha256(),
)
}
fn authorization(&self, headers: &HeaderMap) -> Result<String, S3Error> {
let canonical_request = self.canonical_request(headers)?;
let string_to_sign = self.string_to_sign(&canonical_request)?;
let mut hmac = signing::HmacSha256::new_from_slice(&self.signing_key()?)?;
hmac.update(string_to_sign.as_bytes());
let signature = hex::encode(hmac.finalize().into_bytes());
let signed_header = signing::signed_header_string(headers);
signing::authorization_header(
&self.bucket().access_key()?.expect("No access_key provided"),
&self.datetime(),
&self.bucket().region(),
&signed_header,
&signature,
)
}sourcepub fn access_key(&self) -> Result<Option<String>, S3Error>
pub fn access_key(&self) -> Result<Option<String>, S3Error>
Get a reference to the AWS access key.
Examples found in repository?
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
fn presigned_url_no_sig(
&self,
expiry: u32,
custom_headers: Option<&HeaderMap>,
custom_queries: Option<&HashMap<String, String>>,
) -> Result<Url, S3Error> {
let bucket = self.bucket();
let token = if let Some(security_token) = bucket.security_token()? {
Some(security_token)
} else {
bucket.session_token()?
};
let url = Url::parse(&format!(
"{}{}{}",
self.url()?,
&signing::authorization_query_params_no_sig(
&self.bucket().access_key()?.unwrap_or_default(),
&self.datetime(),
&self.bucket().region(),
expiry,
custom_headers,
token.as_ref()
)?,
&signing::flatten_queries(custom_queries)?,
))?;
Ok(url)
}
fn url(&self) -> Result<Url, S3Error> {
let mut url_str = self.bucket().url();
if let Command::CreateBucket { .. } = self.command() {
return Ok(Url::parse(&url_str)?);
}
let path = if self.path().starts_with('/') {
self.path()[1..].to_string()
} else {
self.path()[..].to_string()
};
url_str.push('/');
url_str.push_str(&signing::uri_encode(&path, false));
// Append to url_path
#[allow(clippy::collapsible_match)]
match self.command() {
Command::InitiateMultipartUpload { .. } | Command::ListMultipartUploads { .. } => {
url_str.push_str("?uploads")
}
Command::AbortMultipartUpload { upload_id } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::CompleteMultipartUpload { upload_id, .. } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::GetObjectTorrent => url_str.push_str("?torrent"),
Command::PutObject { multipart, .. } => {
if let Some(multipart) = multipart {
url_str.push_str(&multipart.query_string())
}
}
_ => {}
}
let mut url = Url::parse(&url_str)?;
for (key, value) in &self.bucket().extra_query {
url.query_pairs_mut().append_pair(key, value);
}
if let Command::ListObjectsV2 {
prefix,
delimiter,
continuation_token,
start_after,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
query_pairs.append_pair("list-type", "2");
if let Some(token) = continuation_token {
query_pairs.append_pair("continuation-token", &token);
}
if let Some(start_after) = start_after {
query_pairs.append_pair("start-after", &start_after);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
if let Command::ListObjects {
prefix,
delimiter,
marker,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
if let Some(marker) = marker {
query_pairs.append_pair("marker", &marker);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
match self.command() {
Command::ListMultipartUploads {
prefix,
delimiter,
key_marker,
max_uploads,
} => {
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", d));
if let Some(prefix) = prefix {
query_pairs.append_pair("prefix", prefix);
}
if let Some(key_marker) = key_marker {
query_pairs.append_pair("key-marker", &key_marker);
}
if let Some(max_uploads) = max_uploads {
query_pairs.append_pair("max-uploads", max_uploads.to_string().as_str());
}
}
Command::PutObjectTagging { .. }
| Command::GetObjectTagging
| Command::DeleteObjectTagging => {
url.query_pairs_mut().append_pair("tagging", "");
}
_ => {}
}
Ok(url)
}
fn canonical_request(&self, headers: &HeaderMap) -> Result<String, S3Error> {
signing::canonical_request(
&self.command().http_verb().to_string(),
&self.url()?,
headers,
&self.command().sha256(),
)
}
fn authorization(&self, headers: &HeaderMap) -> Result<String, S3Error> {
let canonical_request = self.canonical_request(headers)?;
let string_to_sign = self.string_to_sign(&canonical_request)?;
let mut hmac = signing::HmacSha256::new_from_slice(&self.signing_key()?)?;
hmac.update(string_to_sign.as_bytes());
let signature = hex::encode(hmac.finalize().into_bytes());
let signed_header = signing::signed_header_string(headers);
signing::authorization_header(
&self.bucket().access_key()?.expect("No access_key provided"),
&self.datetime(),
&self.bucket().region(),
&signed_header,
&signature,
)
}sourcepub fn secret_key(&self) -> Result<Option<String>, S3Error>
pub fn secret_key(&self) -> Result<Option<String>, S3Error>
Get a reference to the AWS secret key.
Examples found in repository?
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
fn signing_key(&self) -> Result<Vec<u8>, S3Error> {
signing::signing_key(
&self.datetime(),
&self
.bucket()
.secret_key()?
.expect("Secret key must be provided to sign headers, found None"),
&self.bucket().region(),
"s3",
)
}
fn request_body(&self) -> Vec<u8> {
if let Command::PutObject { content, .. } = self.command() {
Vec::from(content)
} else if let Command::PutObjectTagging { tags } = self.command() {
Vec::from(tags)
} else if let Command::UploadPart { content, .. } = self.command() {
Vec::from(content)
} else if let Command::CompleteMultipartUpload { data, .. } = &self.command() {
let body = data.to_string();
println!("CompleteMultipartUpload: {}", body);
body.as_bytes().to_vec()
} else if let Command::CreateBucket { config } = &self.command() {
if let Some(payload) = config.location_constraint_payload() {
Vec::from(payload)
} else {
Vec::new()
}
} else {
Vec::new()
}
}
fn long_date(&self) -> Result<String, S3Error> {
Ok(self.datetime().format(LONG_DATETIME)?)
}
fn string_to_sign(&self, request: &str) -> Result<String, S3Error> {
match self.command() {
Command::PresignPost { post_policy, .. } => Ok(post_policy),
_ => Ok(signing::string_to_sign(
&self.datetime(),
&self.bucket().region(),
request,
)?),
}
}
fn host_header(&self) -> String {
self.bucket().host()
}
fn presigned(&self) -> Result<String, S3Error> {
let (expiry, custom_headers, custom_queries) = match self.command() {
Command::PresignGet {
expiry_secs,
custom_queries,
} => (expiry_secs, None, custom_queries),
Command::PresignPut {
expiry_secs,
custom_headers,
} => (expiry_secs, custom_headers, None),
Command::PresignDelete { expiry_secs } => (expiry_secs, None, None),
_ => unreachable!(),
};
Ok(format!(
"{}&X-Amz-Signature={}",
self.presigned_url_no_sig(expiry, custom_headers.as_ref(), custom_queries.as_ref())?,
self.presigned_authorization(custom_headers.as_ref())?
))
}
fn presigned_authorization(
&self,
custom_headers: Option<&HeaderMap>,
) -> Result<String, S3Error> {
let mut headers = HeaderMap::new();
let host_header = self.host_header();
headers.insert(HOST, host_header.parse()?);
if let Some(custom_headers) = custom_headers {
for (k, v) in custom_headers.iter() {
headers.insert(k.clone(), v.clone());
}
}
let canonical_request = self.presigned_canonical_request(&headers)?;
let string_to_sign = self.string_to_sign(&canonical_request)?;
let mut hmac = signing::HmacSha256::new_from_slice(&self.signing_key()?)?;
hmac.update(string_to_sign.as_bytes());
let signature = hex::encode(hmac.finalize().into_bytes());
// let signed_header = signing::signed_header_string(&headers);
Ok(signature)
}
fn presigned_canonical_request(&self, headers: &HeaderMap) -> Result<String, S3Error> {
let (expiry, custom_headers, custom_queries) = match self.command() {
Command::PresignGet {
expiry_secs,
custom_queries,
} => (expiry_secs, None, custom_queries),
Command::PresignPut {
expiry_secs,
custom_headers,
} => (expiry_secs, custom_headers, None),
Command::PresignDelete { expiry_secs } => (expiry_secs, None, None),
_ => unreachable!(),
};
signing::canonical_request(
&self.command().http_verb().to_string(),
&self.presigned_url_no_sig(expiry, custom_headers.as_ref(), custom_queries.as_ref())?,
headers,
"UNSIGNED-PAYLOAD",
)
}
fn presigned_url_no_sig(
&self,
expiry: u32,
custom_headers: Option<&HeaderMap>,
custom_queries: Option<&HashMap<String, String>>,
) -> Result<Url, S3Error> {
let bucket = self.bucket();
let token = if let Some(security_token) = bucket.security_token()? {
Some(security_token)
} else {
bucket.session_token()?
};
let url = Url::parse(&format!(
"{}{}{}",
self.url()?,
&signing::authorization_query_params_no_sig(
&self.bucket().access_key()?.unwrap_or_default(),
&self.datetime(),
&self.bucket().region(),
expiry,
custom_headers,
token.as_ref()
)?,
&signing::flatten_queries(custom_queries)?,
))?;
Ok(url)
}
fn url(&self) -> Result<Url, S3Error> {
let mut url_str = self.bucket().url();
if let Command::CreateBucket { .. } = self.command() {
return Ok(Url::parse(&url_str)?);
}
let path = if self.path().starts_with('/') {
self.path()[1..].to_string()
} else {
self.path()[..].to_string()
};
url_str.push('/');
url_str.push_str(&signing::uri_encode(&path, false));
// Append to url_path
#[allow(clippy::collapsible_match)]
match self.command() {
Command::InitiateMultipartUpload { .. } | Command::ListMultipartUploads { .. } => {
url_str.push_str("?uploads")
}
Command::AbortMultipartUpload { upload_id } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::CompleteMultipartUpload { upload_id, .. } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::GetObjectTorrent => url_str.push_str("?torrent"),
Command::PutObject { multipart, .. } => {
if let Some(multipart) = multipart {
url_str.push_str(&multipart.query_string())
}
}
_ => {}
}
let mut url = Url::parse(&url_str)?;
for (key, value) in &self.bucket().extra_query {
url.query_pairs_mut().append_pair(key, value);
}
if let Command::ListObjectsV2 {
prefix,
delimiter,
continuation_token,
start_after,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
query_pairs.append_pair("list-type", "2");
if let Some(token) = continuation_token {
query_pairs.append_pair("continuation-token", &token);
}
if let Some(start_after) = start_after {
query_pairs.append_pair("start-after", &start_after);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
if let Command::ListObjects {
prefix,
delimiter,
marker,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
if let Some(marker) = marker {
query_pairs.append_pair("marker", &marker);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
match self.command() {
Command::ListMultipartUploads {
prefix,
delimiter,
key_marker,
max_uploads,
} => {
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", d));
if let Some(prefix) = prefix {
query_pairs.append_pair("prefix", prefix);
}
if let Some(key_marker) = key_marker {
query_pairs.append_pair("key-marker", &key_marker);
}
if let Some(max_uploads) = max_uploads {
query_pairs.append_pair("max-uploads", max_uploads.to_string().as_str());
}
}
Command::PutObjectTagging { .. }
| Command::GetObjectTagging
| Command::DeleteObjectTagging => {
url.query_pairs_mut().append_pair("tagging", "");
}
_ => {}
}
Ok(url)
}
fn canonical_request(&self, headers: &HeaderMap) -> Result<String, S3Error> {
signing::canonical_request(
&self.command().http_verb().to_string(),
&self.url()?,
headers,
&self.command().sha256(),
)
}
fn authorization(&self, headers: &HeaderMap) -> Result<String, S3Error> {
let canonical_request = self.canonical_request(headers)?;
let string_to_sign = self.string_to_sign(&canonical_request)?;
let mut hmac = signing::HmacSha256::new_from_slice(&self.signing_key()?)?;
hmac.update(string_to_sign.as_bytes());
let signature = hex::encode(hmac.finalize().into_bytes());
let signed_header = signing::signed_header_string(headers);
signing::authorization_header(
&self.bucket().access_key()?.expect("No access_key provided"),
&self.datetime(),
&self.bucket().region(),
&signed_header,
&signature,
)
}
fn headers(&self) -> Result<HeaderMap, S3Error> {
// Generate this once, but it's used in more than one place.
let sha256 = self.command().sha256();
// Start with extra_headers, that way our headers replace anything with
// the same name.
let mut headers = HeaderMap::new();
for (k, v) in self.bucket().extra_headers.iter() {
headers.insert(k.clone(), v.clone());
}
let host_header = self.host_header();
headers.insert(HOST, host_header.parse()?);
match self.command() {
Command::CopyObject { from } => {
headers.insert(HeaderName::from_static("x-amz-copy-source"), from.parse()?);
}
Command::ListObjects { .. } => {}
Command::ListObjectsV2 { .. } => {}
Command::GetObject => {}
Command::GetObjectTagging => {}
Command::GetBucketLocation => {}
_ => {
headers.insert(
CONTENT_LENGTH,
self.command().content_length().to_string().parse()?,
);
headers.insert(CONTENT_TYPE, self.command().content_type().parse()?);
}
}
headers.insert(
HeaderName::from_static("x-amz-content-sha256"),
sha256.parse()?,
);
headers.insert(
HeaderName::from_static("x-amz-date"),
self.long_date()?.parse()?,
);
if let Some(session_token) = self.bucket().session_token()? {
headers.insert(
HeaderName::from_static("x-amz-security-token"),
session_token.parse()?,
);
} else if let Some(security_token) = self.bucket().security_token()? {
headers.insert(
HeaderName::from_static("x-amz-security-token"),
security_token.parse()?,
);
}
if let Command::PutObjectTagging { tags } = self.command() {
let digest = md5::compute(tags);
let hash = base64::encode(digest.as_ref());
headers.insert(HeaderName::from_static("content-md5"), hash.parse()?);
} else if let Command::PutObject { content, .. } = self.command() {
let digest = md5::compute(content);
let hash = base64::encode(digest.as_ref());
headers.insert(HeaderName::from_static("content-md5"), hash.parse()?);
} else if let Command::UploadPart { content, .. } = self.command() {
let digest = md5::compute(content);
let hash = base64::encode(digest.as_ref());
headers.insert(HeaderName::from_static("content-md5"), hash.parse()?);
} else if let Command::GetObject {} = self.command() {
headers.insert(ACCEPT, "application/octet-stream".to_string().parse()?);
// headers.insert(header::ACCEPT_CHARSET, HeaderValue::from_str("UTF-8")?);
} else if let Command::GetObjectRange { start, end } = self.command() {
headers.insert(ACCEPT, "application/octet-stream".to_string().parse()?);
let mut range = format!("bytes={}-", start);
if let Some(end) = end {
range.push_str(&end.to_string());
}
headers.insert(RANGE, range.parse()?);
} else if let Command::CreateBucket { ref config } = self.command() {
config.add_headers(&mut headers)?;
}
// This must be last, as it signs the other headers, omitted if no secret key is provided
if self.bucket().secret_key()?.is_some() {
let authorization = self.authorization(&headers)?;
headers.insert(AUTHORIZATION, authorization.parse()?);
}
// The format of RFC2822 is somewhat malleable, so including it in
// signed headers can cause signature mismatches. We do include the
// X-Amz-Date header, so requests are still properly limited to a date
// range and can't be used again e.g. reply attacks. Adding this header
// after the generation of the Authorization header leaves it out of
// the signed headers.
headers.insert(DATE, self.datetime().format(&Rfc2822)?.parse()?);
Ok(headers)
}sourcepub fn security_token(&self) -> Result<Option<String>, S3Error>
pub fn security_token(&self) -> Result<Option<String>, S3Error>
Get a reference to the AWS security token.
Examples found in repository?
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
fn presigned_url_no_sig(
&self,
expiry: u32,
custom_headers: Option<&HeaderMap>,
custom_queries: Option<&HashMap<String, String>>,
) -> Result<Url, S3Error> {
let bucket = self.bucket();
let token = if let Some(security_token) = bucket.security_token()? {
Some(security_token)
} else {
bucket.session_token()?
};
let url = Url::parse(&format!(
"{}{}{}",
self.url()?,
&signing::authorization_query_params_no_sig(
&self.bucket().access_key()?.unwrap_or_default(),
&self.datetime(),
&self.bucket().region(),
expiry,
custom_headers,
token.as_ref()
)?,
&signing::flatten_queries(custom_queries)?,
))?;
Ok(url)
}
fn url(&self) -> Result<Url, S3Error> {
let mut url_str = self.bucket().url();
if let Command::CreateBucket { .. } = self.command() {
return Ok(Url::parse(&url_str)?);
}
let path = if self.path().starts_with('/') {
self.path()[1..].to_string()
} else {
self.path()[..].to_string()
};
url_str.push('/');
url_str.push_str(&signing::uri_encode(&path, false));
// Append to url_path
#[allow(clippy::collapsible_match)]
match self.command() {
Command::InitiateMultipartUpload { .. } | Command::ListMultipartUploads { .. } => {
url_str.push_str("?uploads")
}
Command::AbortMultipartUpload { upload_id } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::CompleteMultipartUpload { upload_id, .. } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::GetObjectTorrent => url_str.push_str("?torrent"),
Command::PutObject { multipart, .. } => {
if let Some(multipart) = multipart {
url_str.push_str(&multipart.query_string())
}
}
_ => {}
}
let mut url = Url::parse(&url_str)?;
for (key, value) in &self.bucket().extra_query {
url.query_pairs_mut().append_pair(key, value);
}
if let Command::ListObjectsV2 {
prefix,
delimiter,
continuation_token,
start_after,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
query_pairs.append_pair("list-type", "2");
if let Some(token) = continuation_token {
query_pairs.append_pair("continuation-token", &token);
}
if let Some(start_after) = start_after {
query_pairs.append_pair("start-after", &start_after);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
if let Command::ListObjects {
prefix,
delimiter,
marker,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
if let Some(marker) = marker {
query_pairs.append_pair("marker", &marker);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
match self.command() {
Command::ListMultipartUploads {
prefix,
delimiter,
key_marker,
max_uploads,
} => {
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", d));
if let Some(prefix) = prefix {
query_pairs.append_pair("prefix", prefix);
}
if let Some(key_marker) = key_marker {
query_pairs.append_pair("key-marker", &key_marker);
}
if let Some(max_uploads) = max_uploads {
query_pairs.append_pair("max-uploads", max_uploads.to_string().as_str());
}
}
Command::PutObjectTagging { .. }
| Command::GetObjectTagging
| Command::DeleteObjectTagging => {
url.query_pairs_mut().append_pair("tagging", "");
}
_ => {}
}
Ok(url)
}
fn canonical_request(&self, headers: &HeaderMap) -> Result<String, S3Error> {
signing::canonical_request(
&self.command().http_verb().to_string(),
&self.url()?,
headers,
&self.command().sha256(),
)
}
fn authorization(&self, headers: &HeaderMap) -> Result<String, S3Error> {
let canonical_request = self.canonical_request(headers)?;
let string_to_sign = self.string_to_sign(&canonical_request)?;
let mut hmac = signing::HmacSha256::new_from_slice(&self.signing_key()?)?;
hmac.update(string_to_sign.as_bytes());
let signature = hex::encode(hmac.finalize().into_bytes());
let signed_header = signing::signed_header_string(headers);
signing::authorization_header(
&self.bucket().access_key()?.expect("No access_key provided"),
&self.datetime(),
&self.bucket().region(),
&signed_header,
&signature,
)
}
fn headers(&self) -> Result<HeaderMap, S3Error> {
// Generate this once, but it's used in more than one place.
let sha256 = self.command().sha256();
// Start with extra_headers, that way our headers replace anything with
// the same name.
let mut headers = HeaderMap::new();
for (k, v) in self.bucket().extra_headers.iter() {
headers.insert(k.clone(), v.clone());
}
let host_header = self.host_header();
headers.insert(HOST, host_header.parse()?);
match self.command() {
Command::CopyObject { from } => {
headers.insert(HeaderName::from_static("x-amz-copy-source"), from.parse()?);
}
Command::ListObjects { .. } => {}
Command::ListObjectsV2 { .. } => {}
Command::GetObject => {}
Command::GetObjectTagging => {}
Command::GetBucketLocation => {}
_ => {
headers.insert(
CONTENT_LENGTH,
self.command().content_length().to_string().parse()?,
);
headers.insert(CONTENT_TYPE, self.command().content_type().parse()?);
}
}
headers.insert(
HeaderName::from_static("x-amz-content-sha256"),
sha256.parse()?,
);
headers.insert(
HeaderName::from_static("x-amz-date"),
self.long_date()?.parse()?,
);
if let Some(session_token) = self.bucket().session_token()? {
headers.insert(
HeaderName::from_static("x-amz-security-token"),
session_token.parse()?,
);
} else if let Some(security_token) = self.bucket().security_token()? {
headers.insert(
HeaderName::from_static("x-amz-security-token"),
security_token.parse()?,
);
}
if let Command::PutObjectTagging { tags } = self.command() {
let digest = md5::compute(tags);
let hash = base64::encode(digest.as_ref());
headers.insert(HeaderName::from_static("content-md5"), hash.parse()?);
} else if let Command::PutObject { content, .. } = self.command() {
let digest = md5::compute(content);
let hash = base64::encode(digest.as_ref());
headers.insert(HeaderName::from_static("content-md5"), hash.parse()?);
} else if let Command::UploadPart { content, .. } = self.command() {
let digest = md5::compute(content);
let hash = base64::encode(digest.as_ref());
headers.insert(HeaderName::from_static("content-md5"), hash.parse()?);
} else if let Command::GetObject {} = self.command() {
headers.insert(ACCEPT, "application/octet-stream".to_string().parse()?);
// headers.insert(header::ACCEPT_CHARSET, HeaderValue::from_str("UTF-8")?);
} else if let Command::GetObjectRange { start, end } = self.command() {
headers.insert(ACCEPT, "application/octet-stream".to_string().parse()?);
let mut range = format!("bytes={}-", start);
if let Some(end) = end {
range.push_str(&end.to_string());
}
headers.insert(RANGE, range.parse()?);
} else if let Command::CreateBucket { ref config } = self.command() {
config.add_headers(&mut headers)?;
}
// This must be last, as it signs the other headers, omitted if no secret key is provided
if self.bucket().secret_key()?.is_some() {
let authorization = self.authorization(&headers)?;
headers.insert(AUTHORIZATION, authorization.parse()?);
}
// The format of RFC2822 is somewhat malleable, so including it in
// signed headers can cause signature mismatches. We do include the
// X-Amz-Date header, so requests are still properly limited to a date
// range and can't be used again e.g. reply attacks. Adding this header
// after the generation of the Authorization header leaves it out of
// the signed headers.
headers.insert(DATE, self.datetime().format(&Rfc2822)?.parse()?);
Ok(headers)
}sourcepub fn session_token(&self) -> Result<Option<String>, S3Error>
pub fn session_token(&self) -> Result<Option<String>, S3Error>
Get a reference to the AWS session token.
Examples found in repository?
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
fn presigned_url_no_sig(
&self,
expiry: u32,
custom_headers: Option<&HeaderMap>,
custom_queries: Option<&HashMap<String, String>>,
) -> Result<Url, S3Error> {
let bucket = self.bucket();
let token = if let Some(security_token) = bucket.security_token()? {
Some(security_token)
} else {
bucket.session_token()?
};
let url = Url::parse(&format!(
"{}{}{}",
self.url()?,
&signing::authorization_query_params_no_sig(
&self.bucket().access_key()?.unwrap_or_default(),
&self.datetime(),
&self.bucket().region(),
expiry,
custom_headers,
token.as_ref()
)?,
&signing::flatten_queries(custom_queries)?,
))?;
Ok(url)
}
fn url(&self) -> Result<Url, S3Error> {
let mut url_str = self.bucket().url();
if let Command::CreateBucket { .. } = self.command() {
return Ok(Url::parse(&url_str)?);
}
let path = if self.path().starts_with('/') {
self.path()[1..].to_string()
} else {
self.path()[..].to_string()
};
url_str.push('/');
url_str.push_str(&signing::uri_encode(&path, false));
// Append to url_path
#[allow(clippy::collapsible_match)]
match self.command() {
Command::InitiateMultipartUpload { .. } | Command::ListMultipartUploads { .. } => {
url_str.push_str("?uploads")
}
Command::AbortMultipartUpload { upload_id } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::CompleteMultipartUpload { upload_id, .. } => {
write!(url_str, "?uploadId={}", upload_id).expect("Could not write to url_str");
}
Command::GetObjectTorrent => url_str.push_str("?torrent"),
Command::PutObject { multipart, .. } => {
if let Some(multipart) = multipart {
url_str.push_str(&multipart.query_string())
}
}
_ => {}
}
let mut url = Url::parse(&url_str)?;
for (key, value) in &self.bucket().extra_query {
url.query_pairs_mut().append_pair(key, value);
}
if let Command::ListObjectsV2 {
prefix,
delimiter,
continuation_token,
start_after,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
query_pairs.append_pair("list-type", "2");
if let Some(token) = continuation_token {
query_pairs.append_pair("continuation-token", &token);
}
if let Some(start_after) = start_after {
query_pairs.append_pair("start-after", &start_after);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
if let Command::ListObjects {
prefix,
delimiter,
marker,
max_keys,
} = self.command().clone()
{
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", &d));
query_pairs.append_pair("prefix", &prefix);
if let Some(marker) = marker {
query_pairs.append_pair("marker", &marker);
}
if let Some(max_keys) = max_keys {
query_pairs.append_pair("max-keys", &max_keys.to_string());
}
}
match self.command() {
Command::ListMultipartUploads {
prefix,
delimiter,
key_marker,
max_uploads,
} => {
let mut query_pairs = url.query_pairs_mut();
delimiter.map(|d| query_pairs.append_pair("delimiter", d));
if let Some(prefix) = prefix {
query_pairs.append_pair("prefix", prefix);
}
if let Some(key_marker) = key_marker {
query_pairs.append_pair("key-marker", &key_marker);
}
if let Some(max_uploads) = max_uploads {
query_pairs.append_pair("max-uploads", max_uploads.to_string().as_str());
}
}
Command::PutObjectTagging { .. }
| Command::GetObjectTagging
| Command::DeleteObjectTagging => {
url.query_pairs_mut().append_pair("tagging", "");
}
_ => {}
}
Ok(url)
}
fn canonical_request(&self, headers: &HeaderMap) -> Result<String, S3Error> {
signing::canonical_request(
&self.command().http_verb().to_string(),
&self.url()?,
headers,
&self.command().sha256(),
)
}
fn authorization(&self, headers: &HeaderMap) -> Result<String, S3Error> {
let canonical_request = self.canonical_request(headers)?;
let string_to_sign = self.string_to_sign(&canonical_request)?;
let mut hmac = signing::HmacSha256::new_from_slice(&self.signing_key()?)?;
hmac.update(string_to_sign.as_bytes());
let signature = hex::encode(hmac.finalize().into_bytes());
let signed_header = signing::signed_header_string(headers);
signing::authorization_header(
&self.bucket().access_key()?.expect("No access_key provided"),
&self.datetime(),
&self.bucket().region(),
&signed_header,
&signature,
)
}
fn headers(&self) -> Result<HeaderMap, S3Error> {
// Generate this once, but it's used in more than one place.
let sha256 = self.command().sha256();
// Start with extra_headers, that way our headers replace anything with
// the same name.
let mut headers = HeaderMap::new();
for (k, v) in self.bucket().extra_headers.iter() {
headers.insert(k.clone(), v.clone());
}
let host_header = self.host_header();
headers.insert(HOST, host_header.parse()?);
match self.command() {
Command::CopyObject { from } => {
headers.insert(HeaderName::from_static("x-amz-copy-source"), from.parse()?);
}
Command::ListObjects { .. } => {}
Command::ListObjectsV2 { .. } => {}
Command::GetObject => {}
Command::GetObjectTagging => {}
Command::GetBucketLocation => {}
_ => {
headers.insert(
CONTENT_LENGTH,
self.command().content_length().to_string().parse()?,
);
headers.insert(CONTENT_TYPE, self.command().content_type().parse()?);
}
}
headers.insert(
HeaderName::from_static("x-amz-content-sha256"),
sha256.parse()?,
);
headers.insert(
HeaderName::from_static("x-amz-date"),
self.long_date()?.parse()?,
);
if let Some(session_token) = self.bucket().session_token()? {
headers.insert(
HeaderName::from_static("x-amz-security-token"),
session_token.parse()?,
);
} else if let Some(security_token) = self.bucket().security_token()? {
headers.insert(
HeaderName::from_static("x-amz-security-token"),
security_token.parse()?,
);
}
if let Command::PutObjectTagging { tags } = self.command() {
let digest = md5::compute(tags);
let hash = base64::encode(digest.as_ref());
headers.insert(HeaderName::from_static("content-md5"), hash.parse()?);
} else if let Command::PutObject { content, .. } = self.command() {
let digest = md5::compute(content);
let hash = base64::encode(digest.as_ref());
headers.insert(HeaderName::from_static("content-md5"), hash.parse()?);
} else if let Command::UploadPart { content, .. } = self.command() {
let digest = md5::compute(content);
let hash = base64::encode(digest.as_ref());
headers.insert(HeaderName::from_static("content-md5"), hash.parse()?);
} else if let Command::GetObject {} = self.command() {
headers.insert(ACCEPT, "application/octet-stream".to_string().parse()?);
// headers.insert(header::ACCEPT_CHARSET, HeaderValue::from_str("UTF-8")?);
} else if let Command::GetObjectRange { start, end } = self.command() {
headers.insert(ACCEPT, "application/octet-stream".to_string().parse()?);
let mut range = format!("bytes={}-", start);
if let Some(end) = end {
range.push_str(&end.to_string());
}
headers.insert(RANGE, range.parse()?);
} else if let Command::CreateBucket { ref config } = self.command() {
config.add_headers(&mut headers)?;
}
// This must be last, as it signs the other headers, omitted if no secret key is provided
if self.bucket().secret_key()?.is_some() {
let authorization = self.authorization(&headers)?;
headers.insert(AUTHORIZATION, authorization.parse()?);
}
// The format of RFC2822 is somewhat malleable, so including it in
// signed headers can cause signature mismatches. We do include the
// X-Amz-Date header, so requests are still properly limited to a date
// range and can't be used again e.g. reply attacks. Adding this header
// after the generation of the Authorization header leaves it out of
// the signed headers.
headers.insert(DATE, self.datetime().format(&Rfc2822)?.parse()?);
Ok(headers)
}sourcepub fn credentials(&self) -> Arc<RwLock<Credentials>>
pub fn credentials(&self) -> Arc<RwLock<Credentials>>
Get a reference to the full Credentials
object used by this Bucket.
Examples found in repository?
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
pub fn access_key(&self) -> Result<Option<String>, S3Error> {
Ok(self
.credentials()
.try_read()
.map_err(|_| S3Error::RLCredentials)?
.access_key
.clone()
.map(|key| key.replace('\n', "")))
}
/// Get a reference to the AWS secret key.
pub fn secret_key(&self) -> Result<Option<String>, S3Error> {
Ok(self
.credentials()
.try_read()
.map_err(|_| S3Error::RLCredentials)?
.secret_key
.clone()
.map(|key| key.replace('\n', "")))
}
/// Get a reference to the AWS security token.
pub fn security_token(&self) -> Result<Option<String>, S3Error> {
Ok(self
.credentials()
.try_read()
.map_err(|_| S3Error::RLCredentials)?
.security_token
.clone())
}
/// Get a reference to the AWS session token.
pub fn session_token(&self) -> Result<Option<String>, S3Error> {
Ok(self
.credentials()
.try_read()
.map_err(|_| S3Error::RLCredentials)?
.session_token
.clone())
}sourcepub fn set_credentials(&mut self, credentials: Credentials)
pub fn set_credentials(&mut self, credentials: Credentials)
Change the credentials used by the Bucket.
sourcepub fn add_header(&mut self, key: &str, value: &str)
pub fn add_header(&mut self, key: &str, value: &str)
Add an extra header to send with requests to S3.
Add an extra header to send with requests. Note that the library already sets a number of headers - headers set with this method will be overridden by the library headers:
- Host
- Content-Type
- Date
- Content-Length
- Authorization
- X-Amz-Content-Sha256
- X-Amz-Date
sourcepub fn extra_headers(&self) -> &HeaderMap
pub fn extra_headers(&self) -> &HeaderMap
Get a reference to the extra headers to be passed to the S3 API.
sourcepub fn extra_headers_mut(&mut self) -> &mut HeaderMap
pub fn extra_headers_mut(&mut self) -> &mut HeaderMap
Get a mutable reference to the extra headers to be passed to the S3 API.
sourcepub fn add_query(&mut self, key: &str, value: &str)
pub fn add_query(&mut self, key: &str, value: &str)
Add an extra query pair to the URL used for S3 API access.
sourcepub fn extra_query(&self) -> &Query
pub fn extra_query(&self) -> &Query
Get a reference to the extra query pairs to be passed to the S3 API.
sourcepub fn extra_query_mut(&mut self) -> &mut Query
pub fn extra_query_mut(&mut self) -> &mut Query
Get a mutable reference to the extra query pairs to be passed to the S3 API.