aioduct 0.2.5

Async-native HTTP client built directly on hyper 1.x — no hyper-util, no legacy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
use bytes::{BufMut, Bytes, BytesMut};

/// Builder for multipart request bodies (default subtype `form-data`).
pub struct Multipart {
    boundary: String,
    subtype: String,
    parts: Vec<Part>,
}

/// A single part in a multipart body.
pub struct Part {
    name: String,
    filename: Option<String>,
    content_type: Option<String>,
    headers: Vec<(String, String)>,
    body: PartBody,
}

enum PartBody {
    Buffered(Bytes),
    Streaming(crate::body::RequestBodySend),
}

impl std::fmt::Debug for Multipart {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Multipart").finish()
    }
}

impl std::fmt::Debug for Part {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Part").field("name", &self.name).finish()
    }
}

impl Part {
    /// Create a new part with the given field name and text body.
    pub fn text(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            filename: None,
            content_type: None,
            headers: Vec::new(),
            body: PartBody::Buffered(Bytes::from(value.into())),
        }
    }

    /// Create a new part with the given field name and bytes body.
    pub fn bytes(name: impl Into<String>, data: impl Into<Bytes>) -> Self {
        Self {
            name: name.into(),
            filename: None,
            content_type: None,
            headers: Vec::new(),
            body: PartBody::Buffered(data.into()),
        }
    }

    /// Create a new part with a streaming body.
    pub fn stream(name: impl Into<String>, body: crate::body::RequestBodySend) -> Self {
        Self {
            name: name.into(),
            filename: None,
            content_type: None,
            headers: Vec::new(),
            body: PartBody::Streaming(body),
        }
    }

    /// Set the filename for this part.
    pub fn file_name(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }

    /// Set the MIME type for this part.
    pub fn mime_str(mut self, mime: impl Into<String>) -> Self {
        self.content_type = Some(mime.into());
        self
    }

    /// Add a custom header to this part.
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    fn is_streaming(&self) -> bool {
        matches!(self.body, PartBody::Streaming(_))
    }
}

impl Default for Multipart {
    fn default() -> Self {
        Self::new()
    }
}

impl Multipart {
    /// Create an empty multipart body.
    pub fn new() -> Self {
        Self {
            boundary: generate_boundary(),
            subtype: "form-data".to_owned(),
            parts: Vec::new(),
        }
    }

    /// Use a caller-supplied boundary instead of the generated one.
    ///
    /// The boundary must be 1–70 characters from the RFC 2046 `bcharsnospace`
    /// set (alphanumerics and ``'()+_,-./:=?``). Returns an error otherwise.
    /// Useful for reproducing WebKit-style boundaries or deterministic tests.
    ///
    /// # Caller responsibility
    ///
    /// Per RFC 2046, the boundary must not appear inside any part body. The
    /// default generated boundary is random, so collisions are effectively
    /// impossible; a caller-supplied boundary removes that guarantee. Choose a
    /// boundary that cannot occur in your part data, or framing will be
    /// corrupted. This is not validated here (streaming bodies cannot be
    /// scanned without buffering).
    pub fn with_boundary(
        mut self,
        boundary: impl Into<String>,
    ) -> Result<Self, crate::error::Error> {
        let boundary = boundary.into();
        validate_boundary(&boundary)?;
        self.boundary = boundary;
        Ok(self)
    }

    /// Set the multipart subtype (the part after `multipart/`).
    ///
    /// Defaults to `form-data`. Use e.g. `mixed` or `related` for other
    /// multipart kinds. The subtype must be a non-empty RFC 7230 token.
    pub fn subtype(mut self, subtype: impl Into<String>) -> Result<Self, crate::error::Error> {
        let subtype = subtype.into();
        validate_token(&subtype)?;
        self.subtype = subtype;
        Ok(self)
    }

    /// Add a text field.
    pub fn text(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.parts.push(Part::text(name, value));
        self
    }

    /// Add a file part with name, filename, content type, and data.
    pub fn file(
        mut self,
        name: impl Into<String>,
        filename: impl Into<String>,
        content_type: impl Into<String>,
        data: impl Into<Bytes>,
    ) -> Self {
        self.parts.push(
            Part::bytes(name, data)
                .file_name(filename)
                .mime_str(content_type),
        );
        self
    }

    /// Add a pre-built [`Part`].
    pub fn part(mut self, part: Part) -> Self {
        self.parts.push(part);
        self
    }

    /// Whether any part has a streaming body.
    pub fn has_streaming_parts(&self) -> bool {
        self.parts.iter().any(|p| p.is_streaming())
    }

    /// Return the MIME boundary string.
    pub fn boundary(&self) -> &str {
        &self.boundary
    }

    /// Return the full `Content-Type` header value including boundary.
    pub fn content_type(&self) -> String {
        format!("multipart/{}; boundary=\"{}\"", self.subtype, self.boundary)
    }

    pub(crate) fn into_bytes(self) -> Bytes {
        let mut buf = BytesMut::new();

        for part in &self.parts {
            buf.put_slice(format!("--{}\r\n", self.boundary).as_bytes());

            let escaped_name = escape_quote(&part.name);
            match (&part.filename, &part.content_type) {
                (Some(filename), Some(ct)) => {
                    let escaped_filename = escape_quote(filename);
                    buf.put_slice(
                        format!(
                            "Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
                            escaped_name, escaped_filename
                        )
                        .as_bytes(),
                    );
                    buf.put_slice(format!("Content-Type: {ct}\r\n").as_bytes());
                }
                (Some(filename), None) => {
                    let escaped_filename = escape_quote(filename);
                    buf.put_slice(
                        format!(
                            "Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
                            escaped_name, escaped_filename
                        )
                        .as_bytes(),
                    );
                }
                (None, Some(ct)) => {
                    buf.put_slice(
                        format!(
                            "Content-Disposition: form-data; name=\"{}\"\r\n",
                            escaped_name
                        )
                        .as_bytes(),
                    );
                    buf.put_slice(format!("Content-Type: {ct}\r\n").as_bytes());
                }
                (None, None) => {
                    buf.put_slice(
                        format!(
                            "Content-Disposition: form-data; name=\"{}\"\r\n",
                            escaped_name
                        )
                        .as_bytes(),
                    );
                }
            }

            for (name, value) in &part.headers {
                buf.put_slice(format!("{name}: {value}\r\n").as_bytes());
            }

            buf.put_slice(b"\r\n");
            if let PartBody::Buffered(data) = &part.body {
                buf.put_slice(data);
            }
            buf.put_slice(b"\r\n");
        }

        buf.put_slice(format!("--{}--\r\n", self.boundary).as_bytes());
        buf.freeze()
    }

    pub(crate) fn into_streaming_body(self) -> crate::body::RequestBodySend {
        use http_body_util::BodyExt;
        use http_body_util::StreamBody;

        let stream = AsyncStream {
            boundary: self.boundary,
            parts: self.parts.into_iter(),
            state: StreamState::NextPart,
            current_body: None,
        };
        let body = StreamBody::new(stream);
        body.map_err(|e| crate::error::Error::Other(Box::new(e)))
            .boxed_unsync()
    }
}

use std::pin::Pin;
use std::task::{Context, Poll};

enum StreamState {
    NextPart,
    Body,
    Done,
}

struct AsyncStream {
    boundary: String,
    parts: std::vec::IntoIter<Part>,
    state: StreamState,
    current_body: Option<crate::body::RequestBodySend>,
}

impl Unpin for AsyncStream {}

impl futures_core::Stream for AsyncStream {
    type Item = Result<hyper::body::Frame<Bytes>, std::io::Error>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = &mut *self;
        loop {
            match this.state {
                StreamState::NextPart => {
                    if let Some(part) = this.parts.next() {
                        let mut header_buf = BytesMut::new();
                        header_buf.put_slice(format!("--{}\r\n", this.boundary).as_bytes());

                        let escaped_name = escape_quote(&part.name);
                        match (&part.filename, &part.content_type) {
                            (Some(filename), Some(ct)) => {
                                let escaped_filename = escape_quote(filename);
                                header_buf.put_slice(
                                    format!(
                                        "Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
                                        escaped_name, escaped_filename
                                    )
                                    .as_bytes(),
                                );
                                header_buf.put_slice(format!("Content-Type: {ct}\r\n").as_bytes());
                            }
                            (Some(filename), None) => {
                                let escaped_filename = escape_quote(filename);
                                header_buf.put_slice(
                                    format!(
                                        "Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
                                        escaped_name, escaped_filename
                                    )
                                    .as_bytes(),
                                );
                            }
                            (None, Some(ct)) => {
                                header_buf.put_slice(
                                    format!(
                                        "Content-Disposition: form-data; name=\"{}\"\r\n",
                                        escaped_name
                                    )
                                    .as_bytes(),
                                );
                                header_buf.put_slice(format!("Content-Type: {ct}\r\n").as_bytes());
                            }
                            (None, None) => {
                                header_buf.put_slice(
                                    format!(
                                        "Content-Disposition: form-data; name=\"{}\"\r\n",
                                        escaped_name
                                    )
                                    .as_bytes(),
                                );
                            }
                        }

                        for (name, value) in &part.headers {
                            header_buf.put_slice(format!("{name}: {value}\r\n").as_bytes());
                        }
                        header_buf.put_slice(b"\r\n");

                        match part.body {
                            PartBody::Buffered(data) => {
                                header_buf.put_slice(&data);
                                header_buf.put_slice(b"\r\n");
                                return Poll::Ready(Some(Ok(hyper::body::Frame::data(
                                    header_buf.freeze(),
                                ))));
                            }
                            PartBody::Streaming(body) => {
                                this.current_body = Some(body);
                                this.state = StreamState::Body;
                                return Poll::Ready(Some(Ok(hyper::body::Frame::data(
                                    header_buf.freeze(),
                                ))));
                            }
                        }
                    } else {
                        this.state = StreamState::Done;
                        let trailer = Bytes::from(format!("--{}--\r\n", this.boundary));
                        return Poll::Ready(Some(Ok(hyper::body::Frame::data(trailer))));
                    }
                }
                StreamState::Body => {
                    if let Some(ref mut body) = this.current_body {
                        use http_body::Body;
                        match Pin::new(body).poll_frame(cx) {
                            Poll::Ready(Some(Ok(frame))) => {
                                if let Ok(data) = frame.into_data() {
                                    return Poll::Ready(Some(Ok(hyper::body::Frame::data(data))));
                                }
                                continue;
                            }
                            Poll::Ready(Some(Err(e))) => {
                                this.state = StreamState::Done;
                                return Poll::Ready(Some(Err(std::io::Error::other(
                                    e.to_string(),
                                ))));
                            }
                            Poll::Ready(None) => {
                                this.current_body = None;
                                this.state = StreamState::NextPart;
                                return Poll::Ready(Some(Ok(hyper::body::Frame::data(
                                    Bytes::from_static(b"\r\n"),
                                ))));
                            }
                            Poll::Pending => return Poll::Pending,
                        }
                    } else {
                        this.state = StreamState::NextPart;
                    }
                }
                StreamState::Done => return Poll::Ready(None),
            }
        }
    }
}

fn escape_quote(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

fn generate_boundary() -> String {
    use std::collections::hash_map::RandomState;
    use std::hash::{BuildHasher, Hasher};
    let r1 = RandomState::new().build_hasher().finish();
    let r2 = RandomState::new().build_hasher().finish();
    format!("----aioduct{r1:016x}{r2:016x}")
}

/// Validate a caller-supplied boundary against RFC 2046 `bcharsnospace`.
///
/// `bcharsnospace = DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," /
/// "-" / "." / "/" / ":" / "=" / "?"`. A boundary is 1–70 of these
/// characters (we reject the trailing-space form, which is not useful here).
fn validate_boundary(boundary: &str) -> Result<(), crate::error::Error> {
    if boundary.is_empty() || boundary.len() > 70 {
        return Err(crate::error::Error::InvalidHeader(format!(
            "multipart boundary must be 1-70 characters, got {}",
            boundary.len()
        )));
    }
    for c in boundary.chars() {
        let ok = c.is_ascii_alphanumeric()
            || matches!(
                c,
                '\'' | '(' | ')' | '+' | '_' | ',' | '-' | '.' | '/' | ':' | '=' | '?'
            );
        if !ok {
            return Err(crate::error::Error::InvalidHeader(format!(
                "invalid character {c:?} in multipart boundary"
            )));
        }
    }
    Ok(())
}

/// Validate an RFC 7230 token (used for the multipart subtype).
fn validate_token(token: &str) -> Result<(), crate::error::Error> {
    if token.is_empty() {
        return Err(crate::error::Error::InvalidHeader(
            "multipart subtype must not be empty".into(),
        ));
    }
    for c in token.chars() {
        let ok = c.is_ascii_alphanumeric()
            || matches!(
                c,
                '!' | '#'
                    | '$'
                    | '%'
                    | '&'
                    | '\''
                    | '*'
                    | '+'
                    | '-'
                    | '.'
                    | '^'
                    | '_'
                    | '`'
                    | '|'
                    | '~'
            );
        if !ok {
            return Err(crate::error::Error::InvalidHeader(format!(
                "invalid character {c:?} in multipart subtype"
            )));
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn extract_boundary(ct: &str) -> &str {
        let raw = ct.split("boundary=").nth(1).unwrap();
        raw.trim_matches('"')
    }

    #[test]
    fn content_type_format() {
        let mp = Multipart::new();
        let ct = mp.content_type();
        assert!(ct.starts_with("multipart/form-data; boundary="));
    }

    #[test]
    fn generated_boundary_is_rfc_2046_safe() {
        fn is_boundary_char(byte: u8) -> bool {
            byte.is_ascii_alphanumeric()
                || matches!(
                    byte,
                    b'\''
                        | b'('
                        | b')'
                        | b'+'
                        | b'_'
                        | b','
                        | b'-'
                        | b'.'
                        | b'/'
                        | b':'
                        | b'='
                        | b'?'
                )
        }

        for _ in 0..128 {
            let mp = Multipart::new();
            let boundary = mp.boundary();

            assert!(!boundary.is_empty(), "multipart boundary must not be empty");
            assert!(
                boundary.len() <= 70,
                "multipart boundary must be at most 70 bytes, got {} for {boundary:?}",
                boundary.len()
            );
            assert!(
                boundary.bytes().all(is_boundary_char),
                "multipart boundary contains an unsafe RFC 2046 character: {boundary:?}"
            );
        }
    }

    #[test]
    fn content_type_boundary_matches_body_delimiter() {
        let mp = Multipart::new().text("name", "value");
        let boundary = extract_boundary(&mp.content_type()).to_owned();
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        assert!(body.starts_with(&format!("--{boundary}\r\n")));
        assert!(body.ends_with(&format!("--{boundary}--\r\n")));
        assert!(!body.contains("----aioduct<boundary>"));
    }

    #[test]
    fn with_boundary_sets_custom_boundary() {
        let mp = Multipart::new()
            .with_boundary("WebKitFormBoundary7MA4YWxkTrZu0gW")
            .unwrap()
            .text("name", "value");
        assert_eq!(mp.boundary(), "WebKitFormBoundary7MA4YWxkTrZu0gW");
        let ct = mp.content_type();
        assert_eq!(
            ct,
            "multipart/form-data; boundary=\"WebKitFormBoundary7MA4YWxkTrZu0gW\""
        );
        let body = String::from_utf8(mp.into_bytes().to_vec()).unwrap();
        assert!(body.starts_with("--WebKitFormBoundary7MA4YWxkTrZu0gW\r\n"));
        assert!(body.ends_with("--WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n"));
    }

    #[test]
    fn with_boundary_rejects_invalid() {
        // space is not in bcharsnospace
        assert!(Multipart::new().with_boundary("has space").is_err());
        // empty
        assert!(Multipart::new().with_boundary("").is_err());
        // too long (> 70)
        assert!(Multipart::new().with_boundary("a".repeat(71)).is_err());
        // disallowed char
        assert!(Multipart::new().with_boundary("bad@boundary").is_err());
    }

    #[test]
    fn subtype_changes_content_type() {
        let mp = Multipart::new().subtype("mixed").unwrap();
        assert!(mp.content_type().starts_with("multipart/mixed; boundary="));

        let mp = Multipart::new().subtype("related").unwrap();
        assert!(
            mp.content_type()
                .starts_with("multipart/related; boundary=")
        );
    }

    #[test]
    fn subtype_rejects_invalid() {
        assert!(Multipart::new().subtype("").is_err());
        assert!(Multipart::new().subtype("has space").is_err());
        assert!(Multipart::new().subtype("bad/slash").is_err());
        // Header-injection-relevant chars must be rejected: `=` and `;` would
        // let a subtype smuggle extra Content-Type parameters.
        assert!(
            Multipart::new()
                .subtype("form-data; boundary=evil")
                .is_err()
        );
        assert!(Multipart::new().subtype("a=b").is_err());
    }

    #[test]
    fn with_boundary_accepts_allowed_specials_and_max_length() {
        // An allowed bcharsnospace special set, plus an exactly-70-char boundary.
        assert!(Multipart::new().with_boundary("a'()+_,-./:=?b").is_ok());
        assert!(Multipart::new().with_boundary("a".repeat(70)).is_ok());
    }

    #[test]
    fn custom_boundary_used_by_streaming_path() {
        // The streaming path reuses `self.boundary`; a dedicated wire assertion
        // through `into_streaming_body` lives in the `streaming_tests` module
        // (gated on the tokio feature). This test pins the buffered framing.
        let mp = Multipart::new()
            .with_boundary("CustomStreamBoundary123")
            .unwrap()
            .text("field", "v");
        let body = String::from_utf8(mp.into_bytes().to_vec()).unwrap();
        assert!(body.starts_with("--CustomStreamBoundary123\r\n"));
        assert!(body.ends_with("--CustomStreamBoundary123--\r\n"));
    }

    #[test]
    fn subtype_does_not_leak_into_body() {
        let mp = Multipart::new().subtype("mixed").unwrap().text("k", "v");
        let body = String::from_utf8(mp.into_bytes().to_vec()).unwrap();
        // The subtype belongs only in the Content-Type header, never the body.
        assert!(!body.contains("mixed"));
    }

    #[test]
    fn default_subtype_is_form_data() {
        assert!(
            Multipart::new()
                .content_type()
                .starts_with("multipart/form-data; ")
        );
    }

    #[test]
    fn has_streaming_parts_false_for_buffered() {
        let mp = Multipart::new().text("field", "value");
        assert!(!mp.has_streaming_parts());
    }

    #[test]
    fn has_streaming_parts_true_for_stream() {
        let body: crate::body::RequestBodySend = http_body_util::Empty::new()
            .map_err(|never| match never {})
            .boxed_unsync();
        let mp = Multipart::new().part(Part::stream("f", body));
        assert!(mp.has_streaming_parts());
    }

    #[test]
    fn into_bytes_text_field() {
        let mp = Multipart::new().text("name", "value");
        let boundary = extract_boundary(&mp.content_type()).to_owned();
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        assert!(body.contains(&format!("--{boundary}\r\n")));
        assert!(body.contains("Content-Disposition: form-data; name=\"name\"\r\n"));
        assert!(body.contains("\r\nvalue\r\n"));
        assert!(body.ends_with(&format!("--{boundary}--\r\n")));
    }

    #[test]
    fn into_bytes_file_part() {
        let mp = Multipart::new().file("upload", "test.txt", "text/plain", b"contents".to_vec());
        let boundary = extract_boundary(&mp.content_type()).to_owned();
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        assert!(body.contains("filename=\"test.txt\""));
        assert!(body.contains("Content-Type: text/plain\r\n"));
        assert!(body.contains("contents"));
        assert!(body.ends_with(&format!("--{boundary}--\r\n")));
    }

    #[test]
    fn into_bytes_no_filename_with_content_type() {
        let part = Part::text("f", "v").mime_str("application/json");
        let mp = Multipart::new().part(part);
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        assert!(body.contains("name=\"f\""));
        assert!(!body.contains("filename="));
        assert!(body.contains("Content-Type: application/json\r\n"));
    }

    #[test]
    fn into_bytes_filename_without_content_type() {
        let part = Part::text("f", "v").file_name("data.bin");
        let mp = Multipart::new().part(part);
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        assert!(body.contains("filename=\"data.bin\""));
        assert!(!body.contains("Content-Type:"));
    }

    #[test]
    fn into_bytes_no_filename_no_content_type() {
        let mp = Multipart::new().text("plain", "hi");
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        assert!(body.contains("name=\"plain\""));
        assert!(!body.contains("filename="));
        assert!(!body.contains("Content-Type:"));
    }

    #[test]
    fn into_bytes_custom_headers() {
        let part = Part::text("f", "v").header("X-Custom", "test-value");
        let mp = Multipart::new().part(part);
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        assert!(body.contains("X-Custom: test-value\r\n"));
    }

    #[test]
    fn into_bytes_multiple_parts() {
        let mp = Multipart::new().text("a", "1").text("b", "2").file(
            "c",
            "c.txt",
            "text/plain",
            b"3".to_vec(),
        );
        let boundary = extract_boundary(&mp.content_type()).to_owned();
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        let boundary_count = body.matches(&format!("--{boundary}\r\n")).count();
        assert_eq!(boundary_count, 3);
        assert!(body.contains(&format!("--{boundary}--\r\n")));
    }

    #[test]
    fn default_creates_empty() {
        let mp = Multipart::default();
        assert!(!mp.has_streaming_parts());
        let bytes = mp.into_bytes();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn multipart_debug_impl() {
        let mp = Multipart::new();
        let debug = format!("{:?}", mp);
        assert!(
            debug.contains("Multipart"),
            "Debug should contain struct name"
        );
    }

    #[test]
    fn part_debug_impl() {
        let part = Part::text("my_field", "some value");
        let debug = format!("{:?}", part);
        assert!(debug.contains("Part"), "Debug should contain struct name");
        assert!(
            debug.contains("my_field"),
            "Debug should contain the field name"
        );
    }

    use http_body_util::BodyExt;

    #[test]
    fn part_bytes_creates_buffered() {
        let part = Part::bytes("data", b"hello".to_vec());
        assert!(!part.is_streaming());
        assert_eq!(part.name, "data");
    }

    #[test]
    fn part_stream_creates_streaming() {
        let body: crate::body::RequestBodySend = http_body_util::Empty::new()
            .map_err(|never| match never {})
            .boxed_unsync();
        let part = Part::stream("s", body);
        assert!(part.is_streaming());
        assert_eq!(part.name, "s");
    }

    #[test]
    fn part_builder_methods() {
        let part = Part::text("f", "v")
            .file_name("name.txt")
            .mime_str("text/plain")
            .header("X-A", "1");
        assert_eq!(part.filename.as_deref(), Some("name.txt"));
        assert_eq!(part.content_type.as_deref(), Some("text/plain"));
        assert_eq!(part.headers.len(), 1);
    }

    #[test]
    fn into_bytes_skips_streaming_parts() {
        let data = bytes::Bytes::from("streamed data that should be absent");
        let stream_body: crate::body::RequestBodySend = http_body_util::Full::new(data)
            .map_err(|never| match never {})
            .boxed_unsync();
        let part = Part::stream("field", stream_body);
        let mp = Multipart::new().part(part);
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        assert!(
            !body.contains("streamed data that should be absent"),
            "streaming part body data must not appear in into_bytes() output, found:\n{body}"
        );
        // Headers for the streaming part should still appear.
        assert!(
            body.contains("name=\"field\""),
            "streaming part headers should appear"
        );
    }

    #[test]
    fn field_name_with_special_chars() {
        let mp = Multipart::new().text("na me", "value");
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        // The space in the field name should appear literally, not percent-encoded.
        assert!(
            body.contains("name=\"na me\""),
            "field name with space should appear with space intact in Content-Disposition, found:\n{body}"
        );
        assert!(
            !body.contains("na%20me"),
            "field name should not be percent-encoded"
        );
    }

    #[test]
    fn file_name_escape_quote() {
        // Input: file\"name.txt (contains a backslash and a literal quote character)
        let input = "file\\\"name.txt";
        let escaped = escape_quote(input);
        // After escape_quote: backslash -> \\, quote -> \"
        assert_eq!(escaped, "file\\\\\\\"name.txt");

        let part = Part::text("f", "v").file_name(input);
        let mp = Multipart::new().part(part);
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        // The escaped filename should appear in the serialized output.
        assert!(
            body.contains(&format!("filename=\"{}\"", escaped)),
            "escaped filename should appear in serialized output, found:\n{body}"
        );
    }

    #[test]
    fn duplicate_field_names_both_appear() {
        let mp = Multipart::new().text("dup", "val1").text("dup", "val2");
        let bytes = mp.into_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        assert!(
            body.contains("val1"),
            "first duplicate field value should appear, found:\n{body}"
        );
        assert!(
            body.contains("val2"),
            "second duplicate field value should appear, found:\n{body}"
        );
        // Both parts should have the same field name.
        let name_occurrences = body.matches("name=\"dup\"").count();
        assert_eq!(
            name_occurrences, 2,
            "field name 'dup' should appear exactly twice, found {name_occurrences} in:\n{body}"
        );
    }

    #[test]
    fn content_type_always_form_data() {
        let mp = Multipart::new().text("k", "v");
        let ct = mp.content_type();
        assert!(
            ct.starts_with("multipart/form-data"),
            "content_type() must start with multipart/form-data, got: {ct}"
        );
    }
}

#[cfg(all(test, feature = "tokio"))]
mod streaming_tests {
    use super::*;
    use http_body_util::BodyExt;

    async fn collect_streaming(mp: Multipart) -> String {
        let body = mp.into_streaming_body();
        let collected = body.collect().await.unwrap().to_bytes();
        String::from_utf8(collected.to_vec()).unwrap()
    }

    #[tokio::test]
    async fn streaming_buffered_text_field() {
        let mp = Multipart::new().text("name", "value");
        let boundary = mp
            .content_type()
            .split("boundary=")
            .nth(1)
            .unwrap()
            .trim_matches('"')
            .to_owned();
        let body = collect_streaming(mp).await;

        assert!(body.contains(&format!("--{boundary}\r\n")));
        assert!(body.contains("Content-Disposition: form-data; name=\"name\"\r\n"));
        assert!(body.contains("value\r\n"));
        assert!(body.ends_with(&format!("--{boundary}--\r\n")));
    }

    #[tokio::test]
    async fn streaming_honors_custom_boundary() {
        let stream_body: crate::body::RequestBodySend =
            http_body_util::Full::new(Bytes::from("streamed-value"))
                .map_err(|never| match never {})
                .boxed_unsync();
        let mp = Multipart::new()
            .with_boundary("CustomStreamBoundary123")
            .unwrap()
            .part(Part::stream("field", stream_body));
        assert!(mp.has_streaming_parts());

        let body = collect_streaming(mp).await;
        assert!(body.starts_with("--CustomStreamBoundary123\r\n"));
        assert!(body.ends_with("--CustomStreamBoundary123--\r\n"));
        assert!(body.contains("streamed-value"));
    }

    #[tokio::test]
    async fn streaming_file_part_with_filename_and_content_type() {
        let mp = Multipart::new().file("upload", "test.txt", "text/plain", b"contents".to_vec());
        let body = collect_streaming(mp).await;

        assert!(body.contains("filename=\"test.txt\""));
        assert!(body.contains("Content-Type: text/plain\r\n"));
        assert!(body.contains("contents"));
    }

    #[tokio::test]
    async fn streaming_filename_without_content_type() {
        let part = Part::text("f", "v").file_name("data.bin");
        let mp = Multipart::new().part(part);
        let body = collect_streaming(mp).await;

        assert!(body.contains("filename=\"data.bin\""));
        assert!(!body.contains("Content-Type:"));
    }

    #[tokio::test]
    async fn streaming_content_type_without_filename() {
        let part = Part::text("f", "v").mime_str("application/json");
        let mp = Multipart::new().part(part);
        let body = collect_streaming(mp).await;

        assert!(body.contains("name=\"f\""));
        assert!(!body.contains("filename="));
        assert!(body.contains("Content-Type: application/json\r\n"));
    }

    #[tokio::test]
    async fn streaming_no_filename_no_content_type() {
        let mp = Multipart::new().text("plain", "hi");
        let body = collect_streaming(mp).await;

        assert!(body.contains("name=\"plain\""));
        assert!(!body.contains("filename="));
        assert!(!body.contains("Content-Type:"));
    }

    #[tokio::test]
    async fn streaming_custom_headers() {
        let part = Part::text("f", "v").header("X-Custom", "test-value");
        let mp = Multipart::new().part(part);
        let body = collect_streaming(mp).await;

        assert!(body.contains("X-Custom: test-value\r\n"));
    }

    #[tokio::test]
    async fn streaming_multiple_buffered_parts() {
        let mp = Multipart::new().text("a", "1").text("b", "2").file(
            "c",
            "c.txt",
            "text/plain",
            b"3".to_vec(),
        );
        let boundary = mp
            .content_type()
            .split("boundary=")
            .nth(1)
            .unwrap()
            .trim_matches('"')
            .to_owned();
        let body = collect_streaming(mp).await;

        let boundary_count = body.matches(&format!("--{boundary}\r\n")).count();
        assert_eq!(boundary_count, 3);
        assert!(body.contains(&format!("--{boundary}--\r\n")));
    }

    #[tokio::test]
    async fn streaming_with_stream_body() {
        let data = bytes::Bytes::from("streamed data");
        let stream_body: crate::body::RequestBodySend = http_body_util::Full::new(data)
            .map_err(|never| match never {})
            .boxed_unsync();

        let part = Part::stream("file", stream_body)
            .file_name("stream.bin")
            .mime_str("application/octet-stream");
        let mp = Multipart::new().part(part);
        let body = collect_streaming(mp).await;

        assert!(body.contains("filename=\"stream.bin\""));
        assert!(body.contains("Content-Type: application/octet-stream\r\n"));
        assert!(body.contains("streamed data"));
    }

    #[tokio::test]
    async fn streaming_mixed_buffered_and_stream() {
        let stream_body: crate::body::RequestBodySend =
            http_body_util::Full::new(bytes::Bytes::from("stream content"))
                .map_err(|never| match never {})
                .boxed_unsync();

        let mp = Multipart::new()
            .text("text_field", "text_value")
            .part(Part::stream("stream_field", stream_body).file_name("f.bin"));
        let boundary = mp
            .content_type()
            .split("boundary=")
            .nth(1)
            .unwrap()
            .trim_matches('"')
            .to_owned();
        let body = collect_streaming(mp).await;

        assert!(body.contains("text_value"));
        assert!(body.contains("stream content"));
        assert!(body.ends_with(&format!("--{boundary}--\r\n")));
    }

    #[tokio::test]
    async fn streaming_empty_multipart() {
        let mp = Multipart::new();
        let boundary = mp
            .content_type()
            .split("boundary=")
            .nth(1)
            .unwrap()
            .trim_matches('"')
            .to_owned();
        let body = collect_streaming(mp).await;

        assert_eq!(body, format!("--{boundary}--\r\n"));
    }

    #[tokio::test]
    async fn streaming_body_with_trailers_frame() {
        // Test the path where a streaming body returns a non-data frame (trailers).
        // The stream should skip it (continue) and eventually get the body data.
        use std::pin::Pin;
        use std::task::{Context, Poll};

        struct TrailerThenDataBody {
            sent_trailer: bool,
            sent_data: bool,
        }

        impl http_body::Body for TrailerThenDataBody {
            type Data = bytes::Bytes;
            type Error = crate::error::Error;

            fn poll_frame(
                mut self: Pin<&mut Self>,
                _cx: &mut Context<'_>,
            ) -> Poll<Option<Result<hyper::body::Frame<Self::Data>, Self::Error>>> {
                if !self.sent_trailer {
                    self.sent_trailer = true;
                    // Return a trailers frame (not data) - this triggers the `continue` path
                    let mut map = http::HeaderMap::new();
                    map.insert("x-trailer", http::HeaderValue::from_static("value"));
                    Poll::Ready(Some(Ok(hyper::body::Frame::trailers(map))))
                } else if !self.sent_data {
                    self.sent_data = true;
                    Poll::Ready(Some(Ok(hyper::body::Frame::data(bytes::Bytes::from(
                        "actual data",
                    )))))
                } else {
                    Poll::Ready(None)
                }
            }
        }

        let body: crate::body::RequestBodySend = TrailerThenDataBody {
            sent_trailer: false,
            sent_data: false,
        }
        .boxed_unsync();

        let part = Part::stream("field", body);
        let mp = Multipart::new().part(part);
        let body_out = collect_streaming(mp).await;

        assert!(
            body_out.contains("actual data"),
            "should contain the actual data after skipping trailer frame"
        );
    }

    #[tokio::test]
    async fn streaming_error_propagation() {
        use std::pin::Pin;
        use std::task::{Context, Poll};

        struct ErrorBody;
        impl http_body::Body for ErrorBody {
            type Data = bytes::Bytes;
            type Error = crate::error::Error;

            fn poll_frame(
                self: Pin<&mut Self>,
                _cx: &mut Context<'_>,
            ) -> Poll<Option<Result<hyper::body::Frame<Self::Data>, Self::Error>>> {
                Poll::Ready(Some(Err(crate::error::Error::Other("test error".into()))))
            }
        }

        let error_body: crate::body::RequestBodySend = ErrorBody.boxed_unsync();
        let part = Part::stream("err", error_body);
        let mp = Multipart::new().part(part);
        let body = mp.into_streaming_body();

        let result = body.collect().await;
        assert!(result.is_err());
    }
}