s3/
serde_types.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Deserialize, Debug)]
4pub struct InitiateMultipartUploadResponse {
5    #[serde(rename = "Bucket")]
6    _bucket: String,
7    #[serde(rename = "Key")]
8    pub key: String,
9    #[serde(rename = "UploadId")]
10    pub upload_id: String,
11}
12
13/// Owner information for the object
14#[derive(Deserialize, Debug, Clone)]
15pub struct Owner {
16    #[serde(rename = "DisplayName")]
17    /// Object owner's name.
18    pub display_name: Option<String>,
19    #[serde(rename = "ID")]
20    /// Object owner's ID.
21    pub id: String,
22}
23
24pub type DateTime = chrono::DateTime<chrono::Utc>;
25
26/// An individual object in a `ListBucketResult`
27#[derive(Deserialize, Debug, Clone)]
28pub struct Object {
29    #[serde(rename = "LastModified")]
30    /// Date and time the object was last modified.
31    pub last_modified: DateTime,
32    #[serde(rename = "ETag")]
33    /// The entity tag is an MD5 hash of the object. The ETag only reflects changes to the
34    /// contents of an object, not its metadata.
35    pub e_tag: Option<String>,
36    #[serde(rename = "StorageClass")]
37    /// STANDARD | STANDARD_IA | REDUCED_REDUNDANCY | GLACIER
38    pub storage_class: Option<String>,
39    #[serde(rename = "Key")]
40    /// The object's key
41    pub key: String,
42    #[serde(rename = "Owner")]
43    /// Bucket owner
44    pub owner: Option<Owner>,
45    #[serde(rename = "Size")]
46    /// Size in bytes of the object.
47    pub size: u64,
48}
49
50/// An individual upload in a `ListMultipartUploadsResult`
51#[derive(Deserialize, Debug, Clone)]
52pub struct MultipartUpload {
53    #[serde(rename = "Initiated")]
54    /// Date and time the multipart upload was initiated
55    pub initiated: DateTime,
56    #[serde(rename = "StorageClass")]
57    /// STANDARD | STANDARD_IA | REDUCED_REDUNDANCY | GLACIER
58    pub storage_class: String,
59    #[serde(rename = "Key")]
60    /// The object's key
61    pub key: String,
62    #[serde(rename = "Owner")]
63    /// Bucket owner
64    pub owner: Option<Owner>,
65    #[serde(rename = "UploadId")]
66    /// The identifier of the upload
67    pub id: String,
68}
69
70use std::fmt;
71
72impl fmt::Display for CompleteMultipartUploadData {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        let mut parts = String::new();
75        for part in self.parts.clone() {
76            parts.push_str(&part.to_string())
77        }
78        write!(
79            f,
80            "<CompleteMultipartUpload>{}</CompleteMultipartUpload>",
81            parts
82        )
83    }
84}
85
86impl CompleteMultipartUploadData {
87    pub fn len(&self) -> usize {
88        self.to_string().as_bytes().len()
89    }
90
91    pub fn is_empty(&self) -> bool {
92        self.to_string().as_bytes().len() == 0
93    }
94}
95
96#[derive(Debug, Clone)]
97pub struct CompleteMultipartUploadData {
98    pub parts: Vec<Part>,
99}
100
101#[derive(Debug, Clone, Serialize)]
102pub struct Part {
103    #[serde(rename = "PartNumber")]
104    pub part_number: u32,
105    #[serde(rename = "ETag")]
106    pub etag: String,
107}
108
109impl fmt::Display for Part {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        write!(f, "<Part>").expect("Can't fail");
112        write!(f, "<PartNumber>{}</PartNumber>", self.part_number).expect("Can't fail");
113        write!(f, "<ETag>{}</ETag>", self.etag).expect("Can't fail");
114        write!(f, "</Part>")
115    }
116}
117
118#[derive(Deserialize, Debug, Clone)]
119pub struct BucketLocationResult {
120    #[serde(rename = "$value")]
121    pub region: String,
122}
123
124/// The parsed result of a s3 bucket listing
125///
126/// This accepts the ListBucketResult format returned for both ListObjects and ListObjectsV2
127#[derive(Deserialize, Debug, Clone)]
128pub struct ListBucketResult {
129    #[serde(rename = "Name")]
130    /// Name of the bucket.
131    pub name: String,
132    #[serde(rename = "Delimiter")]
133    /// A delimiter is a character you use to group keys.
134    pub delimiter: Option<String>,
135    #[serde(rename = "MaxKeys")]
136    /// Sets the maximum number of keys returned in the response body.
137    pub max_keys: Option<i32>,
138    #[serde(rename = "Prefix")]
139    /// Limits the response to keys that begin with the specified prefix.
140    pub prefix: Option<String>,
141    #[serde(rename = "ContinuationToken")] // for ListObjectsV2 request
142    #[serde(alias = "Marker")] // for ListObjects request
143    /// Indicates where in the bucket listing begins. It is included in the response if
144    /// it was sent with the request.
145    pub continuation_token: Option<String>,
146    #[serde(rename = "EncodingType")]
147    /// Specifies the encoding method to used
148    pub encoding_type: Option<String>,
149    #[serde(
150        default,
151        rename = "IsTruncated",
152        deserialize_with = "super::deserializer::bool_deserializer"
153    )]
154    ///  Specifies whether (true) or not (false) all of the results were returned.
155    ///  If the number of results exceeds that specified by MaxKeys, all of the results
156    ///  might not be returned.
157
158    /// When the response is truncated (that is, the IsTruncated element value in the response
159    /// is true), you can use the key name in in 'next_continuation_token' as a marker in the
160    /// subsequent request to get next set of objects. Amazon S3 lists objects in UTF-8 character
161    /// encoding in lexicographical order.
162    pub is_truncated: bool,
163    #[serde(rename = "NextContinuationToken", default)] // for ListObjectsV2 request
164    #[serde(alias = "NextMarker")] // for ListObjects request
165    pub next_continuation_token: Option<String>,
166    #[serde(rename = "Contents", default)]
167    /// Metadata about each object returned.
168    pub contents: Vec<Object>,
169    #[serde(rename = "CommonPrefixes", default)]
170    /// All of the keys rolled up into a common prefix count as a single return when
171    /// calculating the number of returns.
172    pub common_prefixes: Option<Vec<CommonPrefix>>,
173}
174
175/// The parsed result of a s3 bucket listing of uploads
176#[derive(Deserialize, Debug, Clone)]
177pub struct ListMultipartUploadsResult {
178    #[serde(rename = "Bucket")]
179    /// Name of the bucket.
180    pub name: String,
181    #[serde(rename = "NextKeyMarker")]
182    /// When the response is truncated (that is, the IsTruncated element value in the response
183    /// is true), you can use the key name in this field as a marker in the subsequent request
184    /// to get next set of objects. Amazon S3 lists objects in UTF-8 character encoding in
185    /// lexicographical order.
186    pub next_marker: Option<String>,
187    #[serde(rename = "Prefix")]
188    /// The prefix, present if the request contained a prefix too, shows the search root for the
189    /// uploads listed in this structure.
190    pub prefix: Option<String>,
191    #[serde(rename = "KeyMarker")]
192    /// Indicates where in the bucket listing begins.
193    pub marker: Option<String>,
194    #[serde(rename = "EncodingType")]
195    /// Specifies the encoding method to used
196    pub encoding_type: Option<String>,
197    #[serde(
198        rename = "IsTruncated",
199        deserialize_with = "super::deserializer::bool_deserializer"
200    )]
201    ///  Specifies whether (true) or not (false) all of the results were returned.
202    ///  If the number of results exceeds that specified by MaxKeys, all of the results
203    ///  might not be returned.
204    pub is_truncated: bool,
205    #[serde(rename = "Upload", default)]
206    /// Metadata about each upload returned.
207    pub uploads: Vec<MultipartUpload>,
208    #[serde(rename = "CommonPrefixes", default)]
209    /// All of the keys rolled up into a common prefix count as a single return when
210    /// calculating the number of returns.
211    pub common_prefixes: Option<Vec<CommonPrefix>>,
212}
213
214/// `CommonPrefix` is used to group keys
215#[derive(Deserialize, Debug, Clone)]
216pub struct CommonPrefix {
217    #[serde(rename = "Prefix")]
218    /// Keys that begin with the indicated prefix.
219    pub prefix: String,
220}
221
222// Taken from https://github.com/rusoto/rusoto
223#[derive(Deserialize, Debug, Default, Clone)]
224pub struct HeadObjectResult {
225    #[serde(rename = "AcceptRanges")]
226    /// Indicates that a range of bytes was specified.
227    pub accept_ranges: Option<String>,
228    #[serde(rename = "CacheControl")]
229    /// Specifies caching behavior along the request/reply chain.
230    pub cache_control: Option<String>,
231    #[serde(rename = "ContentDisposition")]
232    /// Specifies presentational information for the object.
233    pub content_disposition: Option<String>,
234    #[serde(rename = "ContentEncoding")]
235    /// Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field.
236    pub content_encoding: Option<String>,
237    #[serde(rename = "ContentLanguage")]
238    /// The language the content is in.
239    pub content_language: Option<String>,
240    #[serde(rename = "ContentLength")]
241    /// Size of the body in bytes.
242    pub content_length: Option<i64>,
243    #[serde(rename = "ContentType")]
244    /// A standard MIME type describing the format of the object data.
245    pub content_type: Option<String>,
246    #[serde(rename = "DeleteMarker")]
247    /// Specifies whether the object retrieved was (true) or was not (false) a Delete Marker.
248    pub delete_marker: Option<bool>,
249    #[serde(rename = "ETag")]
250    /// An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL.
251    pub e_tag: Option<String>,
252    #[serde(rename = "Expiration")]
253    /// If the object expiration is configured, the response includes this header. It includes the expiry-date and rule-id key-value pairs providing object expiration information.
254    /// The value of the rule-id is URL encoded.
255    pub expiration: Option<String>,
256    #[serde(rename = "Expires")]
257    /// The date and time at which the object is no longer cacheable.
258    pub expires: Option<DateTime>,
259    #[serde(rename = "LastModified")]
260    /// Last modified date of the object
261    pub last_modified: Option<DateTime>,
262    #[serde(rename = "Metadata", default)]
263    /// A map of metadata to store with the object in S3.
264    pub metadata: Option<::std::collections::HashMap<String, String>>,
265    #[serde(rename = "MissingMeta")]
266    /// This is set to the number of metadata entries not returned in x-amz-meta headers. This can happen if you create metadata using an API like SOAP that supports more flexible metadata than
267    /// the REST API. For example, using SOAP, you can create metadata whose values are not legal HTTP headers.
268    pub missing_meta: Option<i64>,
269    #[serde(rename = "ObjectLockLegalHoldStatus")]
270    /// Specifies whether a legal hold is in effect for this object. This header is only returned if the requester has the s3:GetObjectLegalHold permission.
271    /// This header is not returned if the specified version of this object has never had a legal hold applied.
272    pub object_lock_legal_hold_status: Option<String>,
273    #[serde(rename = "ObjectLockMode")]
274    /// The Object Lock mode, if any, that's in effect for this object.
275    pub object_lock_mode: Option<String>,
276    #[serde(rename = "ObjectLockRetainUntilDate")]
277    /// The date and time when the Object Lock retention period expires.
278    /// This header is only returned if the requester has the s3:GetObjectRetention permission.
279    pub object_lock_retain_until_date: Option<String>,
280    #[serde(rename = "PartsCount")]
281    /// The count of parts this object has.
282    pub parts_count: Option<i64>,
283    #[serde(rename = "ReplicationStatus")]
284    /// If your request involves a bucket that is either a source or destination in a replication rule.
285    pub replication_status: Option<String>,
286    #[serde(rename = "RequestCharged")]
287    pub request_charged: Option<String>,
288    #[serde(rename = "Restore")]
289    /// If the object is an archived object (an object whose storage class is GLACIER), the response includes this header if either the archive restoration is in progress or an archive copy is already restored.
290    /// If an archive copy is already restored, the header value indicates when Amazon S3 is scheduled to delete the object copy.
291    pub restore: Option<String>,
292    #[serde(rename = "SseCustomerAlgorithm")]
293    /// If server-side encryption with a customer-provided encryption key was requested, the response will include this header confirming the encryption algorithm used.
294    pub sse_customer_algorithm: Option<String>,
295    #[serde(rename = "SseCustomerKeyMd5")]
296    /// If server-side encryption with a customer-provided encryption key was requested, the response will include this header to provide round-trip message integrity verification of the customer-provided encryption key.
297    pub sse_customer_key_md5: Option<String>,
298    #[serde(rename = "SsekmsKeyId")]
299    /// If present, specifies the ID of the AWS Key Management Service (AWS KMS) symmetric customer managed customer master key (CMK) that was used for the object.
300    pub ssekms_key_id: Option<String>,
301    #[serde(rename = "ServerSideEncryption")]
302    /// If the object is stored using server-side encryption either with an AWS KMS customer master key (CMK) or an Amazon S3-managed encryption key,
303    /// The response includes this header with the value of the server-side encryption algorithm used when storing this object in Amazon S3 (for example, AES256, aws:kms).
304    pub server_side_encryption: Option<String>,
305    #[serde(rename = "StorageClass")]
306    /// Provides storage class information of the object. Amazon S3 returns this header for all objects except for S3 Standard storage class objects.
307    pub storage_class: Option<String>,
308    #[serde(rename = "VersionId")]
309    /// Version of the object.
310    pub version_id: Option<String>,
311    #[serde(rename = "WebsiteRedirectLocation")]
312    /// If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. Amazon S3 stores the value of this header in the object metadata.
313    pub website_redirect_location: Option<String>,
314}
315
316#[derive(Deserialize, Debug)]
317pub struct AwsError {
318    #[serde(rename = "Code")]
319    pub code: String,
320    #[serde(rename = "Message")]
321    pub message: String,
322    #[serde(rename = "RequestId")]
323    pub request_id: String,
324}
325
326#[derive(Clone, Debug, Serialize, Deserialize)]
327#[serde(rename = "CORSConfiguration")]
328pub struct CorsConfiguration {
329    #[serde(rename = "CORSRule")]
330    rules: Vec<CorsRule>,
331}
332
333impl CorsConfiguration {
334    pub fn new(rules: Vec<CorsRule>) -> Self {
335        CorsConfiguration { rules }
336    }
337}
338
339#[derive(Clone, Debug, Serialize, Deserialize)]
340pub struct CorsRule {
341    #[serde(rename = "AllowedHeader")]
342    #[serde(skip_serializing_if = "Option::is_none")]
343    allowed_headers: Option<Vec<String>>,
344    #[serde(rename = "AllowedMethod")]
345    allowed_methods: Vec<String>,
346    #[serde(rename = "AllowedOrigin")]
347    allowed_origins: Vec<String>,
348    #[serde(rename = "ExposeHeader")]
349    #[serde(skip_serializing_if = "Option::is_none")]
350    expose_headers: Option<Vec<String>>,
351    #[serde(rename = "ID")]
352    id: Option<String>,
353    #[serde(rename = "MaxAgeSeconds")]
354    #[serde(skip_serializing_if = "Option::is_none")]
355    max_age_seconds: Option<u32>,
356}
357
358impl CorsRule {
359    pub fn new(
360        allowed_headers: Option<Vec<String>>,
361        allowed_methods: Vec<String>,
362        allowed_origins: Vec<String>,
363        expose_headers: Option<Vec<String>>,
364        id: Option<String>,
365        max_age_seconds: Option<u32>,
366    ) -> Self {
367        Self {
368            allowed_headers,
369            allowed_methods,
370            allowed_origins,
371            expose_headers,
372            id,
373            max_age_seconds,
374        }
375    }
376}
377
378#[cfg(test)]
379mod test {
380    use super::{CorsConfiguration, CorsRule};
381
382    #[test]
383    fn cors_config_serde() {
384        let rule = CorsRule {
385            allowed_headers: Some(vec!["Authorization".to_string(), "Header2".to_string()]),
386            allowed_methods: vec!["GET".to_string(), "DELETE".to_string()],
387            allowed_origins: vec!["*".to_string()],
388            expose_headers: None,
389            id: Some("lala".to_string()),
390            max_age_seconds: None,
391        };
392
393        let config = CorsConfiguration {
394            rules: vec![rule.clone(), rule],
395        };
396
397        let se = quick_xml::se::to_string(&config).unwrap();
398        assert_eq!(
399            se,
400            r#"<CORSConfiguration><CORSRule><AllowedHeader>Authorization</AllowedHeader><AllowedHeader>Header2</AllowedHeader><AllowedMethod>GET</AllowedMethod><AllowedMethod>DELETE</AllowedMethod><AllowedOrigin>*</AllowedOrigin><ID>lala</ID></CORSRule><CORSRule><AllowedHeader>Authorization</AllowedHeader><AllowedHeader>Header2</AllowedHeader><AllowedMethod>GET</AllowedMethod><AllowedMethod>DELETE</AllowedMethod><AllowedOrigin>*</AllowedOrigin><ID>lala</ID></CORSRule></CORSConfiguration>"#
401        )
402    }
403}