Skip to main content

opendal_core/raw/http_util/
multipart.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::mem;
19use std::str::FromStr;
20
21use bytes::Bytes;
22use bytes::BytesMut;
23use http::HeaderMap;
24use http::HeaderName;
25use http::HeaderValue;
26use http::Method;
27use http::Request;
28use http::Response;
29use http::StatusCode;
30use http::Uri;
31use http::Version;
32use http::header::CONTENT_DISPOSITION;
33use http::header::CONTENT_LENGTH;
34use http::header::CONTENT_TYPE;
35use http::uri::PathAndQuery;
36
37use super::new_request_build_error;
38use crate::*;
39
40/// Multipart is a builder for multipart/form-data.
41#[derive(Debug)]
42pub struct Multipart<T: Part> {
43    boundary: String,
44    parts: Vec<T>,
45}
46
47impl<T: Part> Default for Multipart<T> {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53impl<T: Part> Multipart<T> {
54    /// Create a new multipart with random boundary.
55    pub fn new() -> Self {
56        Multipart {
57            boundary: format!("opendal-{}", uuid::Uuid::new_v4()),
58            parts: Vec::default(),
59        }
60    }
61
62    /// Set the boundary with given string.
63    pub fn with_boundary(mut self, boundary: &str) -> Self {
64        self.boundary = boundary.to_string();
65        self
66    }
67
68    /// Insert a part into multipart.
69    pub fn part(mut self, part: T) -> Self {
70        self.parts.push(part);
71        self
72    }
73
74    /// Into parts.
75    pub fn into_parts(self) -> Vec<T> {
76        self.parts
77    }
78
79    /// Parse a response with multipart body into Multipart.
80    pub fn parse(mut self, bs: Bytes) -> Result<Self> {
81        let s = String::from_utf8(bs.to_vec()).map_err(|err| {
82            Error::new(
83                ErrorKind::Unexpected,
84                "multipart response contains invalid utf-8 chars",
85            )
86            .set_source(err)
87        })?;
88
89        let parts = s
90            .split(format!("--{}", self.boundary).as_str())
91            .collect::<Vec<&str>>();
92
93        for part in parts {
94            if part.is_empty() || part.starts_with("--") {
95                continue;
96            }
97
98            self.parts.push(T::parse(part)?);
99        }
100
101        Ok(self)
102    }
103
104    pub(crate) fn build(self) -> Buffer {
105        let mut bufs = Vec::with_capacity(self.parts.len() + 2);
106
107        // Build pre part.
108        let mut bs = BytesMut::new();
109        bs.extend_from_slice(b"--");
110        bs.extend_from_slice(self.boundary.as_bytes());
111        bs.extend_from_slice(b"\r\n");
112        let pre_part = Buffer::from(bs.freeze());
113
114        // Write all parts.
115        for part in self.parts {
116            bufs.push(pre_part.clone());
117            bufs.push(part.format());
118        }
119
120        // Write the last boundary
121        let mut bs = BytesMut::new();
122        bs.extend_from_slice(b"--");
123        bs.extend_from_slice(self.boundary.as_bytes());
124        bs.extend_from_slice(b"--");
125        bs.extend_from_slice(b"\r\n");
126
127        // Build final part.
128        bufs.push(Buffer::from(bs.freeze()));
129
130        bufs.into_iter().flatten().collect()
131    }
132
133    /// Consume the input and generate a request with multipart body.
134    ///
135    /// This function will make sure content_type and content_length set correctly.
136    pub fn apply(self, mut builder: http::request::Builder) -> Result<Request<Buffer>> {
137        let boundary = self.boundary.clone();
138        let buf = self.build();
139        let content_length = buf.len();
140
141        // Insert content type with correct boundary.
142        builder = builder.header(
143            CONTENT_TYPE,
144            format!("multipart/{}; boundary={}", T::TYPE, boundary).as_str(),
145        );
146        // Insert content length with calculated size.
147        builder = builder.header(CONTENT_LENGTH, content_length);
148
149        builder.body(buf).map_err(new_request_build_error)
150    }
151}
152
153/// Part is a trait for multipart part.
154pub trait Part: Sized + 'static {
155    /// TYPE is the type of multipart.
156    ///
157    /// Current available types are: `form-data` and `mixed`
158    const TYPE: &'static str;
159
160    /// format will generates the bytes.
161    fn format(self) -> Buffer;
162
163    /// parse will parse the bytes into a part.
164    fn parse(s: &str) -> Result<Self>;
165}
166
167/// FormDataPart is a builder for multipart/form-data part.
168pub struct FormDataPart {
169    headers: HeaderMap,
170
171    content: Buffer,
172}
173
174impl FormDataPart {
175    /// Create a new part builder
176    ///
177    /// # Panics
178    ///
179    /// Input name must be percent encoded.
180    pub fn new(name: &str) -> Self {
181        // Insert content disposition header for part.
182        let mut headers = HeaderMap::new();
183        headers.insert(
184            CONTENT_DISPOSITION,
185            format!("form-data; name=\"{name}\"").parse().unwrap(),
186        );
187
188        Self {
189            headers,
190            content: Buffer::new(),
191        }
192    }
193
194    /// Insert a header into part.
195    pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self {
196        self.headers.insert(key, value);
197        self
198    }
199
200    /// Set the content for this part.
201    pub fn content(mut self, content: impl Into<Buffer>) -> Self {
202        self.content = content.into();
203        self
204    }
205}
206
207impl Part for FormDataPart {
208    const TYPE: &'static str = "form-data";
209
210    fn format(self) -> Buffer {
211        let mut bufs = Vec::with_capacity(3);
212
213        // Building pre-content.
214        let mut bs = BytesMut::new();
215        for (k, v) in self.headers.iter() {
216            // Trick!
217            //
218            // Seafile could not recognize header names like `content-disposition`
219            // and requires to use `Content-Disposition`. So we hardcode the part
220            // headers name here.
221            match k.as_str() {
222                "content-disposition" => {
223                    bs.extend_from_slice("Content-Disposition".as_bytes());
224                }
225                _ => {
226                    bs.extend_from_slice(k.as_str().as_bytes());
227                }
228            }
229            bs.extend_from_slice(b": ");
230            bs.extend_from_slice(v.as_bytes());
231            bs.extend_from_slice(b"\r\n");
232        }
233        bs.extend_from_slice(b"\r\n");
234        bufs.push(Buffer::from(bs.freeze()));
235
236        // Building content.
237        bufs.push(self.content);
238
239        // Building post-content.
240        bufs.push(Buffer::from("\r\n"));
241
242        bufs.into_iter().flatten().collect()
243    }
244
245    fn parse(_: &str) -> Result<Self> {
246        Err(Error::new(
247            ErrorKind::Unsupported,
248            "parse of form-data is not supported",
249        ))
250    }
251}
252
253/// MixedPart is a builder for multipart/mixed part.
254pub struct MixedPart {
255    part_headers: HeaderMap,
256
257    /// Common
258    version: Version,
259    headers: HeaderMap,
260    content: Buffer,
261
262    /// Request only
263    method: Option<Method>,
264    uri: Option<Uri>,
265
266    /// Response only
267    status_code: Option<StatusCode>,
268}
269
270impl MixedPart {
271    /// Create a new mixed part with given uri.
272    pub fn new(uri: &str) -> Self {
273        let mut part_headers = HeaderMap::new();
274        part_headers.insert(CONTENT_TYPE, "application/http".parse().unwrap());
275        part_headers.insert("content-transfer-encoding", "binary".parse().unwrap());
276
277        let uri = Uri::from_str(uri).expect("the uri used to build a mixed part must be valid");
278
279        Self {
280            part_headers,
281
282            version: Version::HTTP_11,
283            headers: HeaderMap::new(),
284            content: Buffer::new(),
285
286            uri: Some(uri),
287            method: None,
288
289            status_code: None,
290        }
291    }
292
293    /// Build a mixed part from a request.
294    pub fn from_request(req: Request<Buffer>) -> Self {
295        let mut part_headers = HeaderMap::new();
296        part_headers.insert(CONTENT_TYPE, "application/http".parse().unwrap());
297        part_headers.insert("content-transfer-encoding", "binary".parse().unwrap());
298
299        let (parts, content) = req.into_parts();
300
301        Self {
302            part_headers,
303            uri: Some(
304                Uri::from_str(
305                    parts
306                        .uri
307                        .path_and_query()
308                        .unwrap_or(&PathAndQuery::from_static("/"))
309                        .as_str(),
310                )
311                .expect("the uri used to build a mixed part must be valid"),
312            ),
313            version: parts.version,
314            headers: parts.headers,
315            content,
316
317            method: Some(parts.method),
318            status_code: None,
319        }
320    }
321
322    /// Consume a mixed part to build a response.
323    pub fn into_response(mut self) -> Response<Buffer> {
324        let mut builder = Response::builder();
325
326        builder = builder.status(self.status_code.unwrap_or(StatusCode::OK));
327        builder = builder.version(self.version);
328        // Swap headers directly instead of copy the entire map.
329        mem::swap(builder.headers_mut().unwrap(), &mut self.headers);
330
331        builder
332            .body(self.content)
333            .expect("mixed part must be valid response")
334    }
335
336    /// Insert a part header into part.
337    pub fn part_header(mut self, key: HeaderName, value: HeaderValue) -> Self {
338        self.part_headers.insert(key, value);
339        self
340    }
341
342    /// Set the method for request in this part.
343    pub fn method(mut self, method: Method) -> Self {
344        self.method = Some(method);
345        self
346    }
347
348    /// Set the version for request in this part.
349    pub fn version(mut self, version: Version) -> Self {
350        self.version = version;
351        self
352    }
353
354    /// Insert a header into part.
355    pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self {
356        self.headers.insert(key, value);
357        self
358    }
359
360    /// Set the content for this part.
361    pub fn content(mut self, content: impl Into<Buffer>) -> Self {
362        self.content = content.into();
363        self
364    }
365}
366
367impl Part for MixedPart {
368    const TYPE: &'static str = "mixed";
369
370    fn format(self) -> Buffer {
371        let mut bufs = Vec::with_capacity(3);
372
373        // Write parts headers.
374        let mut bs = BytesMut::new();
375        for (k, v) in self.part_headers.iter() {
376            // Trick!
377            //
378            // Azblob could not recognize header names like `content-type`
379            // and requires to use `Content-Type`. So we hardcode the part
380            // headers name here.
381            match k.as_str() {
382                "content-type" => {
383                    bs.extend_from_slice("Content-Type".as_bytes());
384                }
385                "content-id" => {
386                    bs.extend_from_slice("Content-ID".as_bytes());
387                }
388                "content-transfer-encoding" => {
389                    bs.extend_from_slice("Content-Transfer-Encoding".as_bytes());
390                }
391                _ => {
392                    bs.extend_from_slice(k.as_str().as_bytes());
393                }
394            }
395            bs.extend_from_slice(b": ");
396            bs.extend_from_slice(v.as_bytes());
397            bs.extend_from_slice(b"\r\n");
398        }
399
400        // Write request line: `DELETE /container0/blob0 HTTP/1.1`
401        bs.extend_from_slice(b"\r\n");
402        bs.extend_from_slice(
403            self.method
404                .as_ref()
405                .expect("mixed part must be a valid request that contains method")
406                .as_str()
407                .as_bytes(),
408        );
409        bs.extend_from_slice(b" ");
410        let uri = self
411            .uri
412            .as_ref()
413            .expect("mixed part must be a valid request that contains uri");
414        bs.extend_from_slice(
415            uri.path_and_query()
416                .map_or_else(|| uri.path(), PathAndQuery::as_str)
417                .as_bytes(),
418        );
419        bs.extend_from_slice(b" ");
420        bs.extend_from_slice(format!("{:?}", self.version).as_bytes());
421        bs.extend_from_slice(b"\r\n");
422
423        // Write request headers.
424        for (k, v) in self.headers.iter() {
425            bs.extend_from_slice(k.as_str().as_bytes());
426            bs.extend_from_slice(b": ");
427            bs.extend_from_slice(v.as_bytes());
428            bs.extend_from_slice(b"\r\n");
429        }
430        bs.extend_from_slice(b"\r\n");
431        bufs.push(Buffer::from(bs.freeze()));
432
433        if !self.content.is_empty() {
434            bufs.push(self.content);
435            bufs.push(Buffer::from("\r\n"))
436        }
437
438        bufs.into_iter().flatten().collect()
439    }
440
441    /// TODO
442    ///
443    /// This is a simple implementation and have a lot of space to improve.
444    fn parse(s: &str) -> Result<Self> {
445        let parts = s.splitn(2, "\r\n\r\n").collect::<Vec<&str>>();
446        let part_headers_content = parts[0];
447        let http_response = parts.get(1).unwrap_or(&"");
448
449        let mut part_headers = HeaderMap::new();
450        for line in part_headers_content.lines() {
451            let parts = line.splitn(2, ": ").collect::<Vec<&str>>();
452            if parts.len() == 2 {
453                let header_name = HeaderName::from_str(parts[0]).map_err(|err| {
454                    Error::new(
455                        ErrorKind::Unexpected,
456                        "multipart response contains invalid part header name",
457                    )
458                    .set_source(err)
459                })?;
460                let header_value = parts[1].parse().map_err(|err| {
461                    Error::new(
462                        ErrorKind::Unexpected,
463                        "multipart response contains invalid part header value",
464                    )
465                    .set_source(err)
466                })?;
467
468                part_headers.insert(header_name, header_value);
469            }
470        }
471
472        let parts = http_response.split("\r\n\r\n").collect::<Vec<&str>>();
473        let headers_content = parts[0];
474        let body_content = parts.get(1).unwrap_or(&"");
475        let body_bytes = Buffer::from(body_content.as_bytes().to_vec());
476
477        let status_line = headers_content.lines().next().unwrap_or("");
478        let status_code = status_line
479            .split_whitespace()
480            .nth(1)
481            .unwrap_or("")
482            .parse::<u16>()
483            .unwrap_or(200);
484
485        let mut headers = HeaderMap::new();
486        for line in headers_content.lines().skip(1) {
487            let parts = line.splitn(2, ": ").collect::<Vec<&str>>();
488            if parts.len() == 2 {
489                let header_name = HeaderName::from_str(parts[0]).map_err(|err| {
490                    Error::new(
491                        ErrorKind::Unexpected,
492                        "multipart response contains invalid part header name",
493                    )
494                    .set_source(err)
495                })?;
496                let header_value = parts[1].parse().map_err(|err| {
497                    Error::new(
498                        ErrorKind::Unexpected,
499                        "multipart response contains invalid part header value",
500                    )
501                    .set_source(err)
502                })?;
503
504                headers.insert(header_name, header_value);
505            }
506        }
507
508        Ok(Self {
509            part_headers,
510            version: Version::HTTP_11,
511            headers,
512            content: body_bytes,
513
514            method: None,
515            uri: None,
516
517            status_code: Some(StatusCode::from_u16(status_code).map_err(|err| {
518                Error::new(
519                    ErrorKind::Unexpected,
520                    "multipart response contains invalid status code",
521                )
522                .set_source(err)
523            })?),
524        })
525    }
526}
527
528/// RelatedPart is a builder for multipart/related part.
529pub struct RelatedPart {
530    /// Common
531    headers: HeaderMap,
532    content: Buffer,
533}
534
535impl Default for RelatedPart {
536    fn default() -> Self {
537        Self::new()
538    }
539}
540
541impl RelatedPart {
542    /// Create a new related
543    pub fn new() -> Self {
544        Self {
545            headers: HeaderMap::new(),
546            content: Buffer::new(),
547        }
548    }
549
550    /// Build a mixed part from a request.
551    pub fn from_request(req: Request<Buffer>) -> Self {
552        let (parts, content) = req.into_parts();
553
554        Self {
555            headers: parts.headers,
556            content,
557        }
558    }
559
560    /// Consume a mixed part to build a response.
561    pub fn into_response(mut self) -> Response<Buffer> {
562        let mut builder = Response::builder();
563
564        // Swap headers directly instead of copy the entire map.
565        mem::swap(builder.headers_mut().unwrap(), &mut self.headers);
566
567        builder
568            .body(self.content)
569            .expect("a related part must be valid response")
570    }
571
572    /// Insert a header into part.
573    pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self {
574        self.headers.insert(key, value);
575        self
576    }
577
578    /// Set the content for this part.
579    pub fn content(mut self, content: impl Into<Buffer>) -> Self {
580        self.content = content.into();
581        self
582    }
583}
584
585impl Part for RelatedPart {
586    const TYPE: &'static str = "related";
587
588    fn format(self) -> Buffer {
589        // This is what multipart/related body might look for an insert in GCS
590        // https://cloud.google.com/storage/docs/uploading-objects
591        /*
592        --separator_string
593        Content-Type: application/json; charset=UTF-8
594
595        {"name":"my-document.txt"}
596
597        --separator_string
598        Content-Type: text/plain
599
600        This is a text file.
601        --separator_string--
602        */
603
604        let mut bufs = Vec::with_capacity(3);
605        let mut bs = BytesMut::new();
606
607        // Write request headers.
608        for (k, v) in self.headers.iter() {
609            bs.extend_from_slice(k.as_str().as_bytes());
610            bs.extend_from_slice(b": ");
611            bs.extend_from_slice(v.as_bytes());
612            bs.extend_from_slice(b"\r\n");
613        }
614        bs.extend_from_slice(b"\r\n");
615        bufs.push(Buffer::from(bs.freeze()));
616
617        if !self.content.is_empty() {
618            bufs.push(self.content);
619            bufs.push(Buffer::from("\r\n"))
620        }
621
622        bufs.into_iter().flatten().collect()
623    }
624
625    fn parse(_s: &str) -> Result<Self> {
626        Err(Error::new(
627            ErrorKind::Unsupported,
628            "parsing multipart/related is not supported",
629        ))
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use http::header::CONTENT_TYPE;
636    use pretty_assertions::assert_eq;
637
638    use super::*;
639
640    #[test]
641    fn test_multipart_formdata_basic() -> Result<()> {
642        let multipart = Multipart::new()
643            .with_boundary("lalala")
644            .part(FormDataPart::new("foo").content(Bytes::from("bar")))
645            .part(FormDataPart::new("hello").content(Bytes::from("world")));
646
647        let bs = multipart.build();
648
649        let expected = "--lalala\r\n\
650             Content-Disposition: form-data; name=\"foo\"\r\n\
651             \r\n\
652             bar\r\n\
653             --lalala\r\n\
654             Content-Disposition: form-data; name=\"hello\"\r\n\
655             \r\n\
656             world\r\n\
657             --lalala--\r\n";
658
659        assert_eq!(Bytes::from(expected), bs.to_bytes());
660        Ok(())
661    }
662
663    /// This test is inspired by <https://docs.aws.amazon.com/AmazonS3/latest/userguide/HTTPPOSTExamples.html>
664    #[test]
665    fn test_multipart_formdata_s3_form_upload() -> Result<()> {
666        let multipart = Multipart::new()
667            .with_boundary("9431149156168")
668            .part(FormDataPart::new("key").content("user/eric/MyPicture.jpg"))
669            .part(FormDataPart::new("acl").content("public-read"))
670            .part(FormDataPart::new("success_action_redirect").content(
671                "https://awsexamplebucket1.s3.us-west-1.amazonaws.com/successful_upload.html",
672            ))
673            .part(FormDataPart::new("content-type").content("image/jpeg"))
674            .part(FormDataPart::new("x-amz-meta-uuid").content("14365123651274"))
675            .part(FormDataPart::new("x-amz-meta-tag").content("Some,Tag,For,Picture"))
676            .part(FormDataPart::new("AWSAccessKeyId").content("AKIAIOSFODNN7EXAMPLE"))
677            .part(FormDataPart::new("Policy").content("eyAiZXhwaXJhdGlvbiI6ICIyMDA3LTEyLTAxVDEyOjAwOjAwLjAwMFoiLAogICJjb25kaXRpb25zIjogWwogICAgeyJidWNrZXQiOiAiam9obnNtaXRoIn0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci9lcmljLyJdLAogICAgeyJhY2wiOiAicHVibGljLXJlYWQifSwKICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL2pvaG5zbWl0aC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwKICAgIFsic3RhcnRzLXdpdGgiLCAiJENvbnRlbnQtVHlwZSIsICJpbWFnZS8iXSwKICAgIHsieC1hbXotbWV0YS11dWlkIjogIjE0MzY1MTIzNjUxMjc0In0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiR4LWFtei1tZXRhLXRhZyIsICIiXQogIF0KfQo="))
678            .part(FormDataPart::new("Signature").content("0RavWzkygo6QX9caELEqKi9kDbU="))
679            .part(FormDataPart::new("file").header(CONTENT_TYPE, "image/jpeg".parse().unwrap()).content("...file content...")).part(FormDataPart::new("submit").content("Upload to Amazon S3"));
680
681        let bs = multipart.build();
682
683        let expected = r#"--9431149156168
684Content-Disposition: form-data; name="key"
685
686user/eric/MyPicture.jpg
687--9431149156168
688Content-Disposition: form-data; name="acl"
689
690public-read
691--9431149156168
692Content-Disposition: form-data; name="success_action_redirect"
693
694https://awsexamplebucket1.s3.us-west-1.amazonaws.com/successful_upload.html
695--9431149156168
696Content-Disposition: form-data; name="content-type"
697
698image/jpeg
699--9431149156168
700Content-Disposition: form-data; name="x-amz-meta-uuid"
701
70214365123651274
703--9431149156168
704Content-Disposition: form-data; name="x-amz-meta-tag"
705
706Some,Tag,For,Picture
707--9431149156168
708Content-Disposition: form-data; name="AWSAccessKeyId"
709
710AKIAIOSFODNN7EXAMPLE
711--9431149156168
712Content-Disposition: form-data; name="Policy"
713
714eyAiZXhwaXJhdGlvbiI6ICIyMDA3LTEyLTAxVDEyOjAwOjAwLjAwMFoiLAogICJjb25kaXRpb25zIjogWwogICAgeyJidWNrZXQiOiAiam9obnNtaXRoIn0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci9lcmljLyJdLAogICAgeyJhY2wiOiAicHVibGljLXJlYWQifSwKICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL2pvaG5zbWl0aC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwKICAgIFsic3RhcnRzLXdpdGgiLCAiJENvbnRlbnQtVHlwZSIsICJpbWFnZS8iXSwKICAgIHsieC1hbXotbWV0YS11dWlkIjogIjE0MzY1MTIzNjUxMjc0In0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiR4LWFtei1tZXRhLXRhZyIsICIiXQogIF0KfQo=
715--9431149156168
716Content-Disposition: form-data; name="Signature"
717
7180RavWzkygo6QX9caELEqKi9kDbU=
719--9431149156168
720Content-Disposition: form-data; name="file"
721content-type: image/jpeg
722
723...file content...
724--9431149156168
725Content-Disposition: form-data; name="submit"
726
727Upload to Amazon S3
728--9431149156168--
729"#;
730
731        assert_eq!(
732            expected,
733            // Rust can't represent `\r` in a string literal, so we
734            // replace `\r\n` with `\n` for comparison
735            String::from_utf8(bs.to_bytes().to_vec())
736                .unwrap()
737                .replace("\r\n", "\n")
738        );
739
740        Ok(())
741    }
742
743    /// This test is inspired by <https://cloud.google.com/storage/docs/batch>
744    #[test]
745    fn test_multipart_mixed_gcs_batch_metadata() -> Result<()> {
746        let multipart = Multipart::new()
747            .with_boundary("===============7330845974216740156==")
748            .part(
749                MixedPart::new("/storage/v1/b/example-bucket/o/obj1")
750                    .method(Method::PATCH)
751                    .part_header(
752                        "content-id".parse().unwrap(),
753                        "<b29c5de2-0db4-490b-b421-6a51b598bd22+1>".parse().unwrap(),
754                    )
755                    .header(
756                        "content-type".parse().unwrap(),
757                        "application/json".parse().unwrap(),
758                    )
759                    .header(
760                        "accept".parse().unwrap(),
761                        "application/json".parse().unwrap(),
762                    )
763                    .header("content-length".parse().unwrap(), "31".parse().unwrap())
764                    .content(r#"{"metadata": {"type": "tabby"}}"#),
765            )
766            .part(
767                MixedPart::new("/storage/v1/b/example-bucket/o/obj2")
768                    .method(Method::PATCH)
769                    .part_header(
770                        "content-id".parse().unwrap(),
771                        "<b29c5de2-0db4-490b-b421-6a51b598bd22+2>".parse().unwrap(),
772                    )
773                    .header(
774                        "content-type".parse().unwrap(),
775                        "application/json".parse().unwrap(),
776                    )
777                    .header(
778                        "accept".parse().unwrap(),
779                        "application/json".parse().unwrap(),
780                    )
781                    .header("content-length".parse().unwrap(), "32".parse().unwrap())
782                    .content(r#"{"metadata": {"type": "tuxedo"}}"#),
783            )
784            .part(
785                MixedPart::new("/storage/v1/b/example-bucket/o/obj3")
786                    .method(Method::PATCH)
787                    .part_header(
788                        "content-id".parse().unwrap(),
789                        "<b29c5de2-0db4-490b-b421-6a51b598bd22+3>".parse().unwrap(),
790                    )
791                    .header(
792                        "content-type".parse().unwrap(),
793                        "application/json".parse().unwrap(),
794                    )
795                    .header(
796                        "accept".parse().unwrap(),
797                        "application/json".parse().unwrap(),
798                    )
799                    .header("content-length".parse().unwrap(), "32".parse().unwrap())
800                    .content(r#"{"metadata": {"type": "calico"}}"#),
801            );
802
803        let bs = multipart.build();
804
805        let expected = r#"--===============7330845974216740156==
806Content-Type: application/http
807Content-Transfer-Encoding: binary
808Content-ID: <b29c5de2-0db4-490b-b421-6a51b598bd22+1>
809
810PATCH /storage/v1/b/example-bucket/o/obj1 HTTP/1.1
811content-type: application/json
812accept: application/json
813content-length: 31
814
815{"metadata": {"type": "tabby"}}
816--===============7330845974216740156==
817Content-Type: application/http
818Content-Transfer-Encoding: binary
819Content-ID: <b29c5de2-0db4-490b-b421-6a51b598bd22+2>
820
821PATCH /storage/v1/b/example-bucket/o/obj2 HTTP/1.1
822content-type: application/json
823accept: application/json
824content-length: 32
825
826{"metadata": {"type": "tuxedo"}}
827--===============7330845974216740156==
828Content-Type: application/http
829Content-Transfer-Encoding: binary
830Content-ID: <b29c5de2-0db4-490b-b421-6a51b598bd22+3>
831
832PATCH /storage/v1/b/example-bucket/o/obj3 HTTP/1.1
833content-type: application/json
834accept: application/json
835content-length: 32
836
837{"metadata": {"type": "calico"}}
838--===============7330845974216740156==--
839"#;
840
841        assert_eq!(
842            expected,
843            // Rust can't represent `\r` in a string literal, so we
844            // replace `\r\n` with `\n` for comparison
845            String::from_utf8(bs.to_bytes().to_vec())
846                .unwrap()
847                .replace("\r\n", "\n")
848        );
849
850        Ok(())
851    }
852
853    #[test]
854    fn test_multipart_mixed_request_line_keeps_query() {
855        let req = Request::delete(
856            "https://storage.googleapis.com/storage/v1/b/example-bucket/o/obj1?generation=123",
857        )
858        .body(Buffer::new())
859        .unwrap();
860        let multipart = Multipart::new()
861            .with_boundary("batch")
862            .part(MixedPart::from_request(req));
863
864        let bs = String::from_utf8(multipart.build().to_bytes().to_vec()).unwrap();
865
866        assert!(bs.contains(
867            "\r\nDELETE /storage/v1/b/example-bucket/o/obj1?generation=123 HTTP/1.1\r\n"
868        ));
869    }
870
871    /// This test is inspired by <https://learn.microsoft.com/en-us/rest/api/storageservices/blob-batch?tabs=azure-ad>
872    #[test]
873    fn test_multipart_mixed_azblob_batch_delete() -> Result<()> {
874        let multipart = Multipart::new()
875            .with_boundary("batch_357de4f7-6d0b-4e02-8cd2-6361411a9525")
876            .part(
877                MixedPart::new("/container0/blob0")
878                    .method(Method::DELETE)
879                    .part_header("content-id".parse().unwrap(), "0".parse().unwrap())
880                    .header(
881                        "x-ms-date".parse().unwrap(),
882                        "Thu, 14 Jun 2018 16:46:54 GMT".parse().unwrap(),
883                    )
884                    .header(
885                        "authorization".parse().unwrap(),
886                        "SharedKey account:G4jjBXA7LI/RnWKIOQ8i9xH4p76pAQ+4Fs4R1VxasaE="
887                            .parse()
888                            .unwrap(),
889                    )
890                    .header("content-length".parse().unwrap(), "0".parse().unwrap()),
891            )
892            .part(
893                MixedPart::new("/container1/blob1")
894                    .method(Method::DELETE)
895                    .part_header("content-id".parse().unwrap(), "1".parse().unwrap())
896                    .header(
897                        "x-ms-date".parse().unwrap(),
898                        "Thu, 14 Jun 2018 16:46:54 GMT".parse().unwrap(),
899                    )
900                    .header(
901                        "authorization".parse().unwrap(),
902                        "SharedKey account:IvCoYDQ+0VcaA/hKFjUmQmIxXv2RT3XwwTsOTHL39HI="
903                            .parse()
904                            .unwrap(),
905                    )
906                    .header("content-length".parse().unwrap(), "0".parse().unwrap()),
907            )
908            .part(
909                MixedPart::new("/container2/blob2")
910                    .method(Method::DELETE)
911                    .part_header("content-id".parse().unwrap(), "2".parse().unwrap())
912                    .header(
913                        "x-ms-date".parse().unwrap(),
914                        "Thu, 14 Jun 2018 16:46:54 GMT".parse().unwrap(),
915                    )
916                    .header(
917                        "authorization".parse().unwrap(),
918                        "SharedKey account:S37N2JTjcmOQVLHLbDmp2johz+KpTJvKhbVc4M7+UqI="
919                            .parse()
920                            .unwrap(),
921                    )
922                    .header("content-length".parse().unwrap(), "0".parse().unwrap()),
923            );
924
925        let bs = multipart.build();
926
927        let expected = r#"--batch_357de4f7-6d0b-4e02-8cd2-6361411a9525
928Content-Type: application/http
929Content-Transfer-Encoding: binary
930Content-ID: 0
931
932DELETE /container0/blob0 HTTP/1.1
933x-ms-date: Thu, 14 Jun 2018 16:46:54 GMT
934authorization: SharedKey account:G4jjBXA7LI/RnWKIOQ8i9xH4p76pAQ+4Fs4R1VxasaE=
935content-length: 0
936
937--batch_357de4f7-6d0b-4e02-8cd2-6361411a9525
938Content-Type: application/http
939Content-Transfer-Encoding: binary
940Content-ID: 1
941
942DELETE /container1/blob1 HTTP/1.1
943x-ms-date: Thu, 14 Jun 2018 16:46:54 GMT
944authorization: SharedKey account:IvCoYDQ+0VcaA/hKFjUmQmIxXv2RT3XwwTsOTHL39HI=
945content-length: 0
946
947--batch_357de4f7-6d0b-4e02-8cd2-6361411a9525
948Content-Type: application/http
949Content-Transfer-Encoding: binary
950Content-ID: 2
951
952DELETE /container2/blob2 HTTP/1.1
953x-ms-date: Thu, 14 Jun 2018 16:46:54 GMT
954authorization: SharedKey account:S37N2JTjcmOQVLHLbDmp2johz+KpTJvKhbVc4M7+UqI=
955content-length: 0
956
957--batch_357de4f7-6d0b-4e02-8cd2-6361411a9525--
958"#;
959
960        assert_eq!(
961            expected,
962            // Rust can't represent `\r` in a string literal, so we
963            // replace `\r\n` with `\n` for comparison
964            String::from_utf8(bs.to_bytes().to_vec())
965                .unwrap()
966                .replace("\r\n", "\n")
967        );
968
969        Ok(())
970    }
971
972    /// This test is inspired by <https://cloud.google.com/storage/docs/batch>
973    #[test]
974    fn test_multipart_mixed_gcs_batch_metadata_response() {
975        let response = r#"--batch_pK7JBAk73-E=_AA5eFwv4m2Q=
976Content-Type: application/http
977Content-ID: <response-b29c5de2-0db4-490b-b421-6a51b598bd22+1>
978
979HTTP/1.1 200 OK
980ETag: "lGaP-E0memYDumK16YuUDM_6Gf0/V43j6azD55CPRGb9b6uytDYl61Y"
981Content-Type: application/json; charset=UTF-8
982Date: Mon, 22 Jan 2018 18:56:00 GMT
983Expires: Mon, 22 Jan 2018 18:56:00 GMT
984Cache-Control: private, max-age=0
985Content-Length: 846
986
987{"kind": "storage#object","id": "example-bucket/obj1/1495822576643790","metadata": {"type": "tabby"}}
988
989--batch_pK7JBAk73-E=_AA5eFwv4m2Q=
990Content-Type: application/http
991Content-ID: <response-b29c5de2-0db4-490b-b421-6a51b598bd22+2>
992
993HTTP/1.1 200 OK
994ETag: "lGaP-E0memYDumK16YuUDM_6Gf0/91POdd-sxSAkJnS8Dm7wMxBSDKk"
995Content-Type: application/json; charset=UTF-8
996Date: Mon, 22 Jan 2018 18:56:00 GMT
997Expires: Mon, 22 Jan 2018 18:56:00 GMT
998Cache-Control: private, max-age=0
999Content-Length: 846
1000
1001{"kind": "storage#object","id": "example-bucket/obj2/1495822576643790","metadata": {"type": "tuxedo"}}
1002
1003--batch_pK7JBAk73-E=_AA5eFwv4m2Q=
1004Content-Type: application/http
1005Content-ID: <response-b29c5de2-0db4-490b-b421-6a51b598bd22+3>
1006
1007HTTP/1.1 200 OK
1008ETag: "lGaP-E0memYDumK16YuUDM_6Gf0/d2Z1F1_ZVbB1dC0YKM9rX5VAgIQ"
1009Content-Type: application/json; charset=UTF-8
1010Date: Mon, 22 Jan 2018 18:56:00 GMT
1011Expires: Mon, 22 Jan 2018 18:56:00 GMT
1012Cache-Control: private, max-age=0
1013Content-Length: 846
1014
1015{"kind": "storage#object","id": "example-bucket/obj3/1495822576643790","metadata": {"type": "calico"}}
1016
1017--batch_pK7JBAk73-E=_AA5eFwv4m2Q=--"#.replace('\n', "\r\n");
1018
1019        let multipart: Multipart<MixedPart> = Multipart::new()
1020            .with_boundary("batch_pK7JBAk73-E=_AA5eFwv4m2Q=")
1021            .parse(Bytes::from(response))
1022            .unwrap();
1023
1024        let part0_bs = Bytes::from_static(
1025            r#"{"kind": "storage#object","id": "example-bucket/obj1/1495822576643790","metadata": {"type": "tabby"}}"#.as_bytes());
1026        let part1_bs = Bytes::from_static(
1027            r#"{"kind": "storage#object","id": "example-bucket/obj2/1495822576643790","metadata": {"type": "tuxedo"}}"#
1028                .as_bytes()
1029        );
1030        let part2_bs = Bytes::from_static(
1031            r#"{"kind": "storage#object","id": "example-bucket/obj3/1495822576643790","metadata": {"type": "calico"}}"#
1032                .as_bytes()
1033        );
1034
1035        assert_eq!(multipart.parts.len(), 3);
1036
1037        assert_eq!(multipart.parts[0].part_headers, {
1038            let mut h = HeaderMap::new();
1039            h.insert("Content-Type", "application/http".parse().unwrap());
1040            h.insert(
1041                "Content-ID",
1042                "<response-b29c5de2-0db4-490b-b421-6a51b598bd22+1>"
1043                    .parse()
1044                    .unwrap(),
1045            );
1046
1047            h
1048        });
1049        assert_eq!(multipart.parts[0].version, Version::HTTP_11);
1050        assert_eq!(multipart.parts[0].headers, {
1051            let mut h = HeaderMap::new();
1052            h.insert(
1053                "ETag",
1054                "\"lGaP-E0memYDumK16YuUDM_6Gf0/V43j6azD55CPRGb9b6uytDYl61Y\""
1055                    .parse()
1056                    .unwrap(),
1057            );
1058            h.insert(
1059                "Content-Type",
1060                "application/json; charset=UTF-8".parse().unwrap(),
1061            );
1062            h.insert("Date", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1063            h.insert("Expires", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1064            h.insert("Cache-Control", "private, max-age=0".parse().unwrap());
1065            h.insert("Content-Length", "846".parse().unwrap());
1066
1067            h
1068        });
1069        assert_eq!(multipart.parts[0].content.len(), part0_bs.len());
1070        assert_eq!(multipart.parts[0].uri, None);
1071        assert_eq!(multipart.parts[0].method, None);
1072        assert_eq!(
1073            multipart.parts[0].status_code,
1074            Some(StatusCode::from_u16(200).unwrap())
1075        );
1076
1077        assert_eq!(multipart.parts[1].part_headers, {
1078            let mut h = HeaderMap::new();
1079            h.insert("Content-Type", "application/http".parse().unwrap());
1080            h.insert(
1081                "Content-ID",
1082                "<response-b29c5de2-0db4-490b-b421-6a51b598bd22+2>"
1083                    .parse()
1084                    .unwrap(),
1085            );
1086
1087            h
1088        });
1089        assert_eq!(multipart.parts[1].version, Version::HTTP_11);
1090        assert_eq!(multipart.parts[1].headers, {
1091            let mut h = HeaderMap::new();
1092            h.insert(
1093                "ETag",
1094                "\"lGaP-E0memYDumK16YuUDM_6Gf0/91POdd-sxSAkJnS8Dm7wMxBSDKk\""
1095                    .parse()
1096                    .unwrap(),
1097            );
1098            h.insert(
1099                "Content-Type",
1100                "application/json; charset=UTF-8".parse().unwrap(),
1101            );
1102            h.insert("Date", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1103            h.insert("Expires", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1104            h.insert("Cache-Control", "private, max-age=0".parse().unwrap());
1105            h.insert("Content-Length", "846".parse().unwrap());
1106
1107            h
1108        });
1109        assert_eq!(multipart.parts[1].content.len(), part1_bs.len());
1110        assert_eq!(multipart.parts[1].uri, None);
1111        assert_eq!(multipart.parts[1].method, None);
1112        assert_eq!(
1113            multipart.parts[1].status_code,
1114            Some(StatusCode::from_u16(200).unwrap())
1115        );
1116
1117        assert_eq!(multipart.parts[2].part_headers, {
1118            let mut h = HeaderMap::new();
1119            h.insert("Content-Type", "application/http".parse().unwrap());
1120            h.insert(
1121                "Content-ID",
1122                "<response-b29c5de2-0db4-490b-b421-6a51b598bd22+3>"
1123                    .parse()
1124                    .unwrap(),
1125            );
1126
1127            h
1128        });
1129        assert_eq!(multipart.parts[2].version, Version::HTTP_11);
1130        assert_eq!(multipart.parts[2].headers, {
1131            let mut h = HeaderMap::new();
1132            h.insert(
1133                "ETag",
1134                "\"lGaP-E0memYDumK16YuUDM_6Gf0/d2Z1F1_ZVbB1dC0YKM9rX5VAgIQ\""
1135                    .parse()
1136                    .unwrap(),
1137            );
1138            h.insert(
1139                "Content-Type",
1140                "application/json; charset=UTF-8".parse().unwrap(),
1141            );
1142            h.insert("Date", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1143            h.insert("Expires", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1144            h.insert("Cache-Control", "private, max-age=0".parse().unwrap());
1145            h.insert("Content-Length", "846".parse().unwrap());
1146
1147            h
1148        });
1149        assert_eq!(multipart.parts[2].content.len(), part2_bs.len());
1150        assert_eq!(multipart.parts[2].uri, None);
1151        assert_eq!(multipart.parts[2].method, None);
1152        assert_eq!(
1153            multipart.parts[2].status_code,
1154            Some(StatusCode::from_u16(200).unwrap())
1155        );
1156    }
1157
1158    #[test]
1159    fn test_multipart_related_gcs_simple() {
1160        // This is what multipart/related body might look for an insert in GCS
1161        // https://cloud.google.com/storage/docs/uploading-objects
1162        let expected = r#"--separator_string
1163content-type: application/json; charset=UTF-8
1164
1165{"name":"my-document.txt"}
1166--separator_string
1167content-type: text/plain
1168
1169This is a text file.
1170--separator_string--
1171"#;
1172
1173        let multipart = Multipart::new()
1174            .with_boundary("separator_string")
1175            .part(
1176                RelatedPart::new()
1177                    .header(
1178                        "Content-Type".parse().unwrap(),
1179                        "application/json; charset=UTF-8".parse().unwrap(),
1180                    )
1181                    .content(r#"{"name":"my-document.txt"}"#),
1182            )
1183            .part(
1184                RelatedPart::new()
1185                    .header(
1186                        "Content-Type".parse().unwrap(),
1187                        "text/plain".parse().unwrap(),
1188                    )
1189                    .content("This is a text file."),
1190            );
1191
1192        let bs = multipart.build();
1193
1194        let output = String::from_utf8(bs.to_bytes().to_vec())
1195            .unwrap()
1196            .replace("\r\n", "\n");
1197
1198        assert_eq!(output, expected);
1199    }
1200}