rusty_s3/actions/multipart_upload/
upload.rs

1use std::time::Duration;
2
3use jiff::Timestamp;
4use url::Url;
5
6use crate::actions::Method;
7use crate::actions::S3Action;
8use crate::signing::sign;
9use crate::sorting_iter::SortingIterator;
10use crate::{Bucket, Credentials, Map};
11
12/// Upload a part to a previously created multipart upload.
13///
14/// Every part must be between 5 MB and 5 GB in size, except for the last part.
15///
16/// The part must be uploaded via a PUT request, on success the server will
17/// return an `ETag` header which must be given to
18/// [`CompleteMultipartUpload`][crate::actions::CompleteMultipartUpload] in order to
19/// complete the upload.
20///
21/// A maximum of 10,000 parts can be uploaded to a single multipart upload.
22///
23/// The uploaded part will consume storage on S3 until the multipart upload
24/// is completed or aborted.
25///
26/// Find out more about `UploadPart` from the [AWS API Reference][api]
27///
28/// [api]: https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html
29#[allow(clippy::module_name_repetitions)]
30#[derive(Debug, Clone)]
31pub struct UploadPart<'a> {
32    bucket: &'a Bucket,
33    credentials: Option<&'a Credentials>,
34    object: &'a str,
35
36    part_number: u16,
37    upload_id: &'a str,
38
39    query: Map<'a>,
40    headers: Map<'a>,
41}
42
43impl<'a> UploadPart<'a> {
44    #[inline]
45    #[must_use]
46    pub const fn new(
47        bucket: &'a Bucket,
48        credentials: Option<&'a Credentials>,
49        object: &'a str,
50        part_number: u16,
51        upload_id: &'a str,
52    ) -> Self {
53        Self {
54            bucket,
55            credentials,
56            object,
57
58            part_number,
59            upload_id,
60
61            query: Map::new(),
62            headers: Map::new(),
63        }
64    }
65}
66
67impl<'a> S3Action<'a> for UploadPart<'a> {
68    const METHOD: Method = Method::Put;
69
70    fn query_mut(&mut self) -> &mut Map<'a> {
71        &mut self.query
72    }
73
74    fn headers_mut(&mut self) -> &mut Map<'a> {
75        &mut self.headers
76    }
77
78    fn sign_with_time(&self, expires_in: Duration, time: &Timestamp) -> Url {
79        let url = self.bucket.object_url(self.object).unwrap();
80
81        let part_number = self.part_number.to_string();
82        let query = [
83            ("partNumber", part_number.as_str()),
84            ("uploadId", self.upload_id),
85        ];
86
87        match self.credentials {
88            Some(credentials) => sign(
89                time,
90                Self::METHOD,
91                url,
92                credentials.key(),
93                credentials.secret(),
94                credentials.token(),
95                self.bucket.region(),
96                expires_in.as_secs(),
97                SortingIterator::new(query.iter().copied(), self.query.iter()),
98                self.headers.iter(),
99            ),
100            None => crate::signing::util::add_query_params(url, query.iter().copied()),
101        }
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use pretty_assertions::assert_eq;
108
109    use super::*;
110    use crate::{Bucket, Credentials, UrlStyle};
111
112    #[test]
113    fn aws_example() {
114        // Fri, 24 May 2013 00:00:00 GMT
115        let date = Timestamp::from_second(1369353600).unwrap();
116
117        let expires_in = Duration::from_secs(86400);
118
119        let endpoint = "https://s3.amazonaws.com".parse().unwrap();
120        let bucket = Bucket::new(
121            endpoint,
122            UrlStyle::VirtualHost,
123            "examplebucket",
124            "us-east-1",
125        )
126        .unwrap();
127        let credentials = Credentials::new(
128            "AKIAIOSFODNN7EXAMPLE",
129            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
130        );
131
132        let action = UploadPart::new(&bucket, Some(&credentials), "test.txt", 1, "abcd");
133
134        let url = action.sign_with_time(expires_in, &date);
135        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&partNumber=1&uploadId=abcd&X-Amz-Signature=d2ed12e1e116c88a79cd6d1726f5fe75c99db8a0292ba000f97ecc309a9303f8";
136
137        assert_eq!(expected, url.as_str());
138    }
139
140    #[test]
141    fn anonymous_custom_query() {
142        let expires_in = Duration::from_secs(86400);
143
144        let endpoint = "https://s3.amazonaws.com".parse().unwrap();
145        let bucket = Bucket::new(
146            endpoint,
147            UrlStyle::VirtualHost,
148            "examplebucket",
149            "us-east-1",
150        )
151        .unwrap();
152
153        let action = UploadPart::new(&bucket, None, "test.txt", 1, "abcd");
154        let url = action.sign(expires_in);
155        let expected = "https://examplebucket.s3.amazonaws.com/test.txt?partNumber=1&uploadId=abcd";
156
157        assert_eq!(expected, url.as_str());
158    }
159}