aioduct 0.1.10

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
use bytes::{BufMut, Bytes, BytesMut};

/// Builder for multipart/form-data request bodies.
pub struct Multipart {
    boundary: 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::error::AioductBody),
}

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::error::AioductBody) -> 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(),
            parts: Vec::new(),
        }
    }

    /// 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())
    }

    pub(crate) fn content_type(&self) -> String {
        format!("multipart/form-data; boundary={}", 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());

            match (&part.filename, &part.content_type) {
                (Some(filename), Some(ct)) => {
                    buf.put_slice(
                        format!(
                            "Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
                            part.name, filename
                        )
                        .as_bytes(),
                    );
                    buf.put_slice(format!("Content-Type: {ct}\r\n").as_bytes());
                }
                (Some(filename), None) => {
                    buf.put_slice(
                        format!(
                            "Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
                            part.name, filename
                        )
                        .as_bytes(),
                    );
                }
                (None, Some(ct)) => {
                    buf.put_slice(
                        format!("Content-Disposition: form-data; name=\"{}\"\r\n", part.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", part.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::error::AioductBody {
        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::error::AioductBody>,
}

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());

                        match (&part.filename, &part.content_type) {
                            (Some(filename), Some(ct)) => {
                                header_buf.put_slice(
                                    format!(
                                        "Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
                                        part.name, filename
                                    )
                                    .as_bytes(),
                                );
                                header_buf.put_slice(format!("Content-Type: {ct}\r\n").as_bytes());
                            }
                            (Some(filename), None) => {
                                header_buf.put_slice(
                                    format!(
                                        "Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
                                        part.name, filename
                                    )
                                    .as_bytes(),
                                );
                            }
                            (None, Some(ct)) => {
                                header_buf.put_slice(
                                    format!(
                                        "Content-Disposition: form-data; name=\"{}\"\r\n",
                                        part.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",
                                        part.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 generate_boundary() -> String {
    use std::time::SystemTime;
    let nanos = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    format!("----aioduct{nanos:x}")
}

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

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

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

    #[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::error::AioductBody = 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());
    }

    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::error::AioductBody = 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);
    }
}

#[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()
            .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_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()
            .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::error::AioductBody = 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::error::AioductBody =
            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()
            .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()
            .to_owned();
        let body = collect_streaming(mp).await;

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

    #[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::error::AioductBody = 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());
    }
}