rusty_s3/actions/multipart_upload/
create.rs

1use std::io::{BufReader, Read};
2use std::iter;
3use std::time::Duration;
4
5use jiff::Timestamp;
6use serde::Deserialize;
7use url::Url;
8
9use crate::actions::Method;
10use crate::actions::S3Action;
11use crate::signing::sign;
12use crate::sorting_iter::SortingIterator;
13use crate::{Bucket, Credentials, Map};
14
15/// Create a multipart upload.
16///
17/// A few advantages of multipart uploads are:
18///
19/// * being able to be resume without having to start back from the beginning
20/// * parallelize the uploads across multiple threads
21///
22/// Find out more about `CreateMultipartUpload` from the [AWS API Reference][api]
23///
24/// [api]: https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html
25#[allow(clippy::module_name_repetitions)]
26#[derive(Debug, Clone)]
27pub struct CreateMultipartUpload<'a> {
28    bucket: &'a Bucket,
29    credentials: Option<&'a Credentials>,
30    object: &'a str,
31
32    query: Map<'a>,
33    headers: Map<'a>,
34}
35
36#[allow(clippy::module_name_repetitions)]
37#[derive(Debug, Clone)]
38pub struct CreateMultipartUploadResponse(InnerCreateMultipartUploadResponse);
39
40#[allow(clippy::module_name_repetitions)]
41#[derive(Debug, Clone, Deserialize)]
42struct InnerCreateMultipartUploadResponse {
43    #[serde(rename = "UploadId")]
44    upload_id: String,
45}
46
47impl<'a> CreateMultipartUpload<'a> {
48    #[inline]
49    #[must_use]
50    pub const fn new(
51        bucket: &'a Bucket,
52        credentials: Option<&'a Credentials>,
53        object: &'a str,
54    ) -> Self {
55        Self {
56            bucket,
57            credentials,
58            object,
59
60            query: Map::new(),
61            headers: Map::new(),
62        }
63    }
64
65    /// Parse the XML response from S3
66    ///
67    /// # Errors
68    ///
69    /// Will return an error if the body is not valid XML
70    pub fn parse_response(
71        s: impl AsRef<[u8]>,
72    ) -> Result<CreateMultipartUploadResponse, quick_xml::DeError> {
73        Self::parse_response_from_reader(&mut s.as_ref())
74    }
75
76    /// Parse the XML response from S3
77    ///
78    /// # Errors
79    ///
80    /// Will return an error if the body is not valid XML
81    pub fn parse_response_from_reader(
82        s: impl Read,
83    ) -> Result<CreateMultipartUploadResponse, quick_xml::DeError> {
84        let parsed = quick_xml::de::from_reader(BufReader::new(s))?;
85        Ok(CreateMultipartUploadResponse(parsed))
86    }
87}
88
89impl CreateMultipartUploadResponse {
90    #[must_use]
91    pub fn upload_id(&self) -> &str {
92        &self.0.upload_id
93    }
94}
95
96impl<'a> S3Action<'a> for CreateMultipartUpload<'a> {
97    const METHOD: Method = Method::Post;
98
99    fn query_mut(&mut self) -> &mut Map<'a> {
100        &mut self.query
101    }
102
103    fn headers_mut(&mut self) -> &mut Map<'a> {
104        &mut self.headers
105    }
106
107    fn sign_with_time(&self, expires_in: Duration, time: &Timestamp) -> Url {
108        let url = self.bucket.object_url(self.object).unwrap();
109        let query = iter::once(("uploads", "1"));
110
111        match self.credentials {
112            Some(credentials) => sign(
113                time,
114                Self::METHOD,
115                url,
116                credentials.key(),
117                credentials.secret(),
118                credentials.token(),
119                self.bucket.region(),
120                expires_in.as_secs(),
121                SortingIterator::new(query, self.query.iter()),
122                self.headers.iter(),
123            ),
124            None => crate::signing::util::add_query_params(url, query),
125        }
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use pretty_assertions::assert_eq;
132
133    use super::*;
134    use crate::{Bucket, Credentials, UrlStyle};
135
136    #[test]
137    fn aws_example() {
138        // Fri, 24 May 2013 00:00:00 GMT
139        let date = Timestamp::from_second(1369353600).unwrap();
140        let expires_in = Duration::from_secs(86400);
141
142        let endpoint = "https://s3.amazonaws.com".parse().unwrap();
143        let bucket = Bucket::new(
144            endpoint,
145            UrlStyle::VirtualHost,
146            "examplebucket",
147            "us-east-1",
148        )
149        .unwrap();
150        let credentials = Credentials::new(
151            "AKIAIOSFODNN7EXAMPLE",
152            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
153        );
154
155        let action = CreateMultipartUpload::new(&bucket, Some(&credentials), "test.txt");
156
157        let url = action.sign_with_time(expires_in, &date);
158        let expected = "https://examplebucket.s3.amazonaws.com/test.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20130524T000000Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&uploads=1&X-Amz-Signature=a6289f9e5ff2a914c6e324403bcd00b1d258c568487faa50d317ef0910c25c0a";
159
160        assert_eq!(expected, url.as_str());
161    }
162
163    #[test]
164    fn anonymous_custom_query() {
165        let expires_in = Duration::from_secs(86400);
166
167        let endpoint = "https://s3.amazonaws.com".parse().unwrap();
168        let bucket = Bucket::new(
169            endpoint,
170            UrlStyle::VirtualHost,
171            "examplebucket",
172            "us-east-1",
173        )
174        .unwrap();
175
176        let action = CreateMultipartUpload::new(&bucket, None, "test.txt");
177        let url = action.sign(expires_in);
178        let expected = "https://examplebucket.s3.amazonaws.com/test.txt?uploads=1";
179
180        assert_eq!(expected, url.as_str());
181    }
182}