s3_simple/
types.rs

1use serde::Deserialize;
2use std::str::FromStr;
3
4#[derive(Clone, Debug)]
5pub(crate) struct Multipart<'a> {
6    part_number: u32,
7    upload_id: &'a str,
8}
9
10impl<'a> Multipart<'a> {
11    pub fn query_string(&self) -> String {
12        format!(
13            "?partNumber={}&uploadId={}",
14            self.part_number, self.upload_id
15        )
16    }
17
18    pub fn new(part_number: u32, upload_id: &'a str) -> Self {
19        Multipart {
20            part_number,
21            upload_id,
22        }
23    }
24}
25
26#[derive(Deserialize, Debug, Clone)]
27pub struct Owner {
28    #[serde(rename = "DisplayName")]
29    /// Object owner's name.
30    pub display_name: Option<String>,
31    #[serde(rename = "ID")]
32    /// Object owner's ID.
33    pub id: String,
34}
35
36#[derive(Deserialize, Debug, Clone)]
37pub struct Object {
38    #[serde(rename = "LastModified")]
39    /// Date and time the object was last modified.
40    pub last_modified: String,
41    #[serde(rename = "ETag")]
42    /// The entity tag is an MD5 hash of the object. The ETag only reflects changes to the
43    /// contents of an object, not its metadata.
44    pub e_tag: Option<String>,
45    #[serde(rename = "StorageClass")]
46    /// STANDARD | STANDARD_IA | REDUCED_REDUNDANCY | GLACIER
47    pub storage_class: Option<String>,
48    #[serde(rename = "Key")]
49    /// The object's key
50    pub key: String,
51    #[serde(rename = "Owner")]
52    /// Bucket owner
53    pub owner: Option<Owner>,
54    #[serde(rename = "Size")]
55    /// Size in bytes of the object.
56    pub size: u64,
57}
58
59#[derive(Deserialize, Debug, Clone)]
60pub struct CommonPrefix {
61    #[serde(rename = "Prefix")]
62    /// Keys that begin with the indicated prefix.
63    pub prefix: String,
64}
65
66// Taken from https://github.com/rusoto/rusoto
67#[derive(Deserialize, Debug, Default, Clone)]
68pub struct HeadObjectResult {
69    #[serde(rename = "AcceptRanges")]
70    /// Indicates that a range of bytes was specified.
71    pub accept_ranges: Option<String>,
72    #[serde(rename = "CacheControl")]
73    /// Specifies caching behavior along the request/reply chain.
74    pub cache_control: Option<String>,
75    #[serde(rename = "ContentDisposition")]
76    /// Specifies presentational information for the object.
77    pub content_disposition: Option<String>,
78    #[serde(rename = "ContentEncoding")]
79    /// 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.
80    pub content_encoding: Option<String>,
81    #[serde(rename = "ContentLanguage")]
82    /// The language the content is in.
83    pub content_language: Option<String>,
84    #[serde(rename = "ContentLength")]
85    /// Size of the body in bytes.
86    pub content_length: Option<u64>,
87    #[serde(rename = "ContentType")]
88    /// A standard MIME type describing the format of the object data.
89    pub content_type: Option<String>,
90    #[serde(rename = "DeleteMarker")]
91    /// Specifies whether the object retrieved was (true) or was not (false) a Delete Marker.
92    pub delete_marker: Option<bool>,
93    #[serde(rename = "ETag")]
94    /// An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL.
95    pub e_tag: Option<String>,
96    #[serde(rename = "Expiration")]
97    /// 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.
98    /// The value of the rule-id is URL encoded.
99    pub expiration: Option<String>,
100    #[serde(rename = "Expires")]
101    /// The date and time at which the object is no longer cacheable.
102    pub expires: Option<String>,
103    #[serde(rename = "LastModified")]
104    /// Last modified date of the object
105    pub last_modified: Option<String>,
106    #[serde(rename = "Metadata", default)]
107    /// A map of metadata to store with the object in S3.
108    pub metadata: Option<::std::collections::HashMap<String, String>>,
109    #[serde(rename = "MissingMeta")]
110    /// 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
111    /// the REST API. For example, using SOAP, you can create metadata whose values are not legal HTTP headers.
112    pub missing_meta: Option<i64>,
113    #[serde(rename = "ObjectLockLegalHoldStatus")]
114    /// Specifies whether a legal hold is in effect for this object. This header is only returned if the requester has the s3:GetObjectLegalHold permission.
115    /// This header is not returned if the specified version of this object has never had a legal hold applied.
116    pub object_lock_legal_hold_status: Option<String>,
117    #[serde(rename = "ObjectLockMode")]
118    /// The Object Lock mode, if any, that's in effect for this object.
119    pub object_lock_mode: Option<String>,
120    #[serde(rename = "ObjectLockRetainUntilDate")]
121    /// The date and time when the Object Lock retention period expires.
122    /// This header is only returned if the requester has the s3:GetObjectRetention permission.
123    pub object_lock_retain_until_date: Option<String>,
124    #[serde(rename = "PartsCount")]
125    /// The count of parts this object has.
126    pub parts_count: Option<i64>,
127    #[serde(rename = "ReplicationStatus")]
128    /// If your request involves a bucket that is either a source or destination in a replication rule.
129    pub replication_status: Option<String>,
130    #[serde(rename = "RequestCharged")]
131    pub request_charged: Option<String>,
132    #[serde(rename = "Restore")]
133    /// 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.
134    /// If an archive copy is already restored, the header value indicates when Amazon S3 is scheduled to delete the object copy.
135    pub restore: Option<String>,
136    #[serde(rename = "SseCustomerAlgorithm")]
137    /// If server-side encryption with a customer-provided encryption key was requested, the response will include this header confirming the encryption algorithm used.
138    pub sse_customer_algorithm: Option<String>,
139    #[serde(rename = "SseCustomerKeyMd5")]
140    /// 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.
141    pub sse_customer_key_md5: Option<String>,
142    #[serde(rename = "SsekmsKeyId")]
143    /// 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.
144    pub ssekms_key_id: Option<String>,
145    #[serde(rename = "ServerSideEncryption")]
146    /// 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,
147    /// 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).
148    pub server_side_encryption: Option<String>,
149    #[serde(rename = "StorageClass")]
150    /// Provides storage class information of the object. Amazon S3 returns this header for all objects except for S3 Standard storage class objects.
151    pub storage_class: Option<String>,
152    #[serde(rename = "VersionId")]
153    /// Version of the object.
154    pub version_id: Option<String>,
155    #[serde(rename = "WebsiteRedirectLocation")]
156    /// 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.
157    pub website_redirect_location: Option<String>,
158}
159
160trait GetAndConvertHeaders {
161    fn get_and_convert<T: FromStr>(&self, header: &str) -> Option<T>;
162    fn get_string(&self, header: &str) -> Option<String>;
163}
164
165impl GetAndConvertHeaders for http::header::HeaderMap {
166    fn get_and_convert<T: FromStr>(&self, header: &str) -> Option<T> {
167        self.get(header)?.to_str().ok()?.parse::<T>().ok()
168    }
169    fn get_string(&self, header: &str) -> Option<String> {
170        Some(self.get(header)?.to_str().ok()?.to_owned())
171    }
172}
173
174impl From<&http::HeaderMap> for HeadObjectResult {
175    fn from(headers: &http::HeaderMap) -> Self {
176        let mut result = HeadObjectResult {
177            accept_ranges: headers.get_string("accept-ranges"),
178            cache_control: headers.get_string("Cache-Control"),
179            content_disposition: headers.get_string("Content-Disposition"),
180            content_encoding: headers.get_string("Content-Encoding"),
181            content_language: headers.get_string("Content-Language"),
182            content_length: headers.get_and_convert("Content-Length"),
183            content_type: headers.get_string("Content-Type"),
184            delete_marker: headers.get_and_convert("x-amz-delete-marker"),
185            e_tag: headers.get_string("ETag"),
186            expiration: headers.get_string("x-amz-expiration"),
187            expires: headers.get_string("Expires"),
188            last_modified: headers.get_string("Last-Modified"),
189            ..Default::default()
190        };
191        let mut values = ::std::collections::HashMap::new();
192        for (key, value) in headers.iter() {
193            if key.as_str().starts_with("x-amz-meta-") {
194                if let Ok(value) = value.to_str() {
195                    values.insert(
196                        key.as_str()["x-amz-meta-".len()..].to_owned(),
197                        value.to_owned(),
198                    );
199                }
200            }
201        }
202        result.metadata = Some(values);
203        result.missing_meta = headers.get_and_convert("x-amz-missing-meta");
204        result.object_lock_legal_hold_status = headers.get_string("x-amz-object-lock-legal-hold");
205        result.object_lock_mode = headers.get_string("x-amz-object-lock-mode");
206        result.object_lock_retain_until_date =
207            headers.get_string("x-amz-object-lock-retain-until-date");
208        result.parts_count = headers.get_and_convert("x-amz-mp-parts-count");
209        result.replication_status = headers.get_string("x-amz-replication-status");
210        result.request_charged = headers.get_string("x-amz-request-charged");
211        result.restore = headers.get_string("x-amz-restore");
212        result.sse_customer_algorithm =
213            headers.get_string("x-amz-server-side-encryption-customer-algorithm");
214        result.sse_customer_key_md5 =
215            headers.get_string("x-amz-server-side-encryption-customer-key-MD5");
216        result.ssekms_key_id = headers.get_string("x-amz-server-side-encryption-aws-kms-key-id");
217        result.server_side_encryption = headers.get_string("x-amz-server-side-encryption");
218        result.storage_class = headers.get_string("x-amz-storage-class");
219        result.version_id = headers.get_string("x-amz-version-id");
220        result.website_redirect_location = headers.get_string("x-amz-website-redirect-location");
221        result
222    }
223}
224
225#[derive(Deserialize, Debug, Clone)]
226pub struct ListBucketResult {
227    #[serde(rename = "Name")]
228    /// Name of the bucket.
229    pub name: String,
230    #[serde(rename = "Delimiter")]
231    /// A delimiter is a character you use to group keys.
232    pub delimiter: Option<String>,
233    #[serde(rename = "MaxKeys")]
234    /// Sets the maximum number of keys returned in the response body.
235    pub max_keys: Option<i32>,
236    #[serde(rename = "Prefix")]
237    /// Limits the response to keys that begin with the specified prefix.
238    pub prefix: Option<String>,
239    #[serde(rename = "ContinuationToken")] // for ListObjectsV2 request
240    #[serde(alias = "Marker")] // for ListObjects request
241    /// Indicates where in the bucket listing begins. It is included in the response if
242    /// it was sent with the request.
243    pub continuation_token: Option<String>,
244    #[serde(rename = "EncodingType")]
245    /// Specifies the encoding method to used
246    pub encoding_type: Option<String>,
247    #[serde(default, rename = "IsTruncated")]
248    ///  Specifies whether (true) or not (false) all of the results were returned.
249    ///  If the number of results exceeds that specified by MaxKeys, all of the results
250    ///  might not be returned.
251
252    /// When the response is truncated (that is, the IsTruncated element value in the response
253    /// is true), you can use the key name in in 'next_continuation_token' as a marker in the
254    /// subsequent request to get next set of objects. Amazon S3 lists objects in UTF-8 character
255    /// encoding in lexicographical order.
256    pub is_truncated: bool,
257    #[serde(rename = "NextContinuationToken", default)] // for ListObjectsV2 request
258    #[serde(alias = "NextMarker")] // for ListObjects request
259    pub next_continuation_token: Option<String>,
260    #[serde(rename = "Contents", default)]
261    /// Metadata about each object returned.
262    pub contents: Vec<Object>,
263    #[serde(rename = "CommonPrefixes", default)]
264    /// All of the keys rolled up into a common prefix count as a single return when
265    /// calculating the number of returns.
266    pub common_prefixes: Option<Vec<CommonPrefix>>,
267}
268
269#[derive(Deserialize, Debug)]
270pub(crate) struct InitiateMultipartUploadResponse {
271    #[serde(rename = "Bucket")]
272    _bucket: String,
273    #[serde(rename = "Key")]
274    pub key: String,
275    #[serde(rename = "UploadId")]
276    pub upload_id: String,
277}
278
279#[derive(Debug)]
280pub struct PutStreamResponse {
281    pub status_code: u16,
282    pub uploaded_bytes: usize,
283}