tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
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
use std::{
    collections::VecDeque,
    path::Path,
    pin::Pin,
    task::{Context, Poll},
};

use http::{
    HeaderMap, HeaderValue,
    header::{CONTENT_DISPOSITION, CONTENT_TYPE},
};
use http_body::{Body as _, Frame};
use mime::Mime;

use crate::{Body, Bytes, Error, Result};

/// An owned `multipart/form-data` request body.
///
/// Parts are encoded in insertion order when the multipart is attached to a
/// request. Forms made only from buffered parts are buffered. A wrapped
/// streaming [`Part::body`] makes the encoded form one-shot and streaming.
pub struct Multipart {
    parts: Vec<(String, Part)>,
}

/// One field in a [`Multipart`] request body.
///
/// Use [`Part::text`] or [`Part::bytes`] for buffered data and [`Part::body`]
/// for a Tez [`Body`].
pub struct Part {
    content: Content,
    file_name: Option<String>,
    media_type: Option<String>,
    headers: HeaderMap,
}

enum Content {
    Text(String),
    Bytes(Bytes),
    Body(Body),
}

struct StreamPart {
    prefix: Bytes,
    body: Body,
}

struct PreparedPart {
    prefix: Bytes,
    content: PreparedContent,
}

enum PreparedContent {
    Buffered(Bytes),
    Streaming(Body),
}

struct MultipartStream {
    parts: VecDeque<StreamPart>,
    current: Option<Body>,
    tail: Option<Bytes>,
    failed: bool,
}

impl Multipart {
    /// Creates an empty multipart body.
    ///
    /// At least one part must be added before attaching it to a request.
    #[must_use]
    pub const fn new() -> Self {
        Self { parts: Vec::new() }
    }

    /// Appends a UTF-8 text field.
    #[must_use]
    pub fn text(self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.part(name, Part::text(value))
    }

    /// Appends a named part.
    ///
    /// Repeated names are preserved in insertion order. ASCII control
    /// characters in a field name are rejected when the request is built or
    /// sent.
    #[must_use]
    pub fn part(mut self, name: impl Into<String>, part: Part) -> Self {
        self.parts.push((name.into(), part));
        self
    }

    pub(crate) fn into_body(self) -> Result<(Body, HeaderValue)> {
        if self.parts.is_empty() {
            return Err(Error::request("multipart body requires at least one part"));
        }

        let boundary = boundary();
        let content_type = content_type(&boundary)?;
        let parts = self
            .parts
            .into_iter()
            .map(|(name, part)| part.into_prepared(&boundary, &name))
            .collect::<Result<Vec<_>>>()?;
        if parts
            .iter()
            .all(|part| matches!(part.content, PreparedContent::Buffered(_)))
        {
            return Ok((Body::from(encode_buffered(parts, &boundary)), content_type));
        }

        let length = encoded_length(&parts, &boundary);
        let parts = parts
            .into_iter()
            .map(PreparedPart::into_streaming)
            .collect::<VecDeque<_>>();
        let body = Body::from_http_body(
            MultipartStream {
                parts,
                current: None,
                tail: Some(Bytes::from(format!("--{boundary}--\r\n"))),
                failed: false,
            },
            |error| error,
        );
        let body = match length {
            Some(length) => body.validate_length(length),
            None => body,
        };
        Ok((body, content_type))
    }
}

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

impl Part {
    /// Creates a buffered UTF-8 text part.
    #[must_use]
    pub fn text(value: impl Into<String>) -> Self {
        Self::new(Content::Text(value.into()))
    }

    /// Creates a buffered byte part.
    #[must_use]
    pub fn bytes(value: impl Into<Bytes>) -> Self {
        Self::new(Content::Bytes(value.into()))
    }

    /// Creates a part from a Tez body.
    ///
    /// A wrapped streaming body makes its form one-shot and non-replayable.
    /// Only data frames are encoded; HTTP trailers are not part of a multipart
    /// field.
    #[must_use]
    pub fn body(body: Body) -> Self {
        Self::new(Content::Body(body))
    }

    /// Opens a file as a one-shot streaming part.
    ///
    /// The file length is captured when this future completes, allowing Tez to
    /// emit an exact multipart content length. The final path component becomes
    /// the reported filename when it is valid UTF-8.
    pub async fn file(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let file = async_fs::File::open(path)
            .await
            .map_err(|_| Error::request("multipart file could not be opened"))?;
        let length = file
            .metadata()
            .await
            .map_err(|_| Error::request("multipart file metadata could not be read"))?
            .len();
        let mut part = Self::body(Body::reader_with_length(file, length));
        if let Some(file_name) = path.file_name().and_then(|name| name.to_str()) {
            part.file_name = Some(file_name.to_owned());
        }
        Ok(part)
    }

    /// Sets the filename reported for this part.
    ///
    /// Filenames may contain Unicode, quotes, and backslashes. ASCII control
    /// characters are rejected when the request is built or sent.
    #[must_use]
    pub fn file_name(mut self, value: impl Into<String>) -> Self {
        self.file_name = Some(value.into());
        self
    }

    /// Sets the media type reported for this part.
    ///
    /// Invalid media types are reported when the request is built or sent.
    #[must_use]
    pub fn media_type(mut self, value: impl Into<String>) -> Self {
        self.media_type = Some(value.into());
        self
    }

    /// Sets additional headers for this part.
    ///
    /// `Content-Disposition` is generated from the field name and filename.
    /// `Content-Type` is generated by [`Part::media_type`]. Supplying either
    /// reserved header is reported when the request is built or sent.
    #[must_use]
    pub fn headers(mut self, headers: HeaderMap) -> Self {
        self.headers = headers;
        self
    }

    fn new(content: Content) -> Self {
        Self {
            content,
            file_name: None,
            media_type: None,
            headers: HeaderMap::new(),
        }
    }

    fn into_prepared(self, boundary: &str, name: &str) -> Result<PreparedPart> {
        let Part {
            content,
            file_name,
            media_type,
            headers,
        } = self;
        let prefix = part_prefix(
            boundary,
            name,
            file_name.as_deref(),
            media_type.as_deref(),
            &headers,
        )?;
        let content = match content {
            Content::Text(text) => PreparedContent::Buffered(Bytes::from(text.into_bytes())),
            Content::Bytes(bytes) => PreparedContent::Buffered(bytes),
            Content::Body(body) => match body.into_buffered_bytes() {
                Ok(bytes) => PreparedContent::Buffered(bytes),
                Err(body) => PreparedContent::Streaming(body),
            },
        };
        Ok(PreparedPart { prefix, content })
    }
}

impl PreparedPart {
    fn into_streaming(self) -> StreamPart {
        let body = match self.content {
            PreparedContent::Buffered(bytes) => Body::from(bytes),
            PreparedContent::Streaming(body) => body,
        };
        StreamPart {
            prefix: self.prefix,
            body,
        }
    }
}

impl http_body::Body for MultipartStream {
    type Data = Bytes;
    type Error = Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        context: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>>>> {
        let this = self.get_mut();
        if this.failed {
            return Poll::Ready(None);
        }

        loop {
            if let Some(body) = &mut this.current {
                match Pin::new(body).poll_frame(context) {
                    Poll::Ready(Some(Ok(frame))) => {
                        if let Ok(data) = frame.into_data()
                            && !data.is_empty()
                        {
                            return Poll::Ready(Some(Ok(Frame::data(data))));
                        }
                    }
                    Poll::Ready(Some(Err(error))) => {
                        this.failed = true;
                        return Poll::Ready(Some(Err(error)));
                    }
                    Poll::Ready(None) => {
                        this.current = None;
                        return Poll::Ready(Some(Ok(Frame::data(Bytes::from_static(b"\r\n")))));
                    }
                    Poll::Pending => return Poll::Pending,
                }
                continue;
            }

            if let Some(part) = this.parts.pop_front() {
                this.current = Some(part.body);
                return Poll::Ready(Some(Ok(Frame::data(part.prefix))));
            }
            return Poll::Ready(this.tail.take().map(|tail| Ok(Frame::data(tail))));
        }
    }

    fn is_end_stream(&self) -> bool {
        self.failed || (self.parts.is_empty() && self.current.is_none() && self.tail.is_none())
    }
}

fn boundary() -> String {
    format!("tez-{:016x}{:016x}", fastrand::u64(..), fastrand::u64(..))
}

fn content_type(boundary: &str) -> Result<HeaderValue> {
    format!("multipart/form-data; boundary={boundary}")
        .parse()
        .map_err(|_| Error::request("multipart content type is invalid"))
}

fn encode_buffered(parts: Vec<PreparedPart>, boundary: &str) -> Bytes {
    let capacity = encoded_length(&parts, boundary)
        .and_then(|length| usize::try_from(length).ok())
        .unwrap_or_default();
    let mut body = Vec::with_capacity(capacity);
    for part in parts {
        body.extend_from_slice(&part.prefix);
        let PreparedContent::Buffered(content) = part.content else {
            unreachable!("buffered multipart parts must contain buffered data");
        };
        body.extend_from_slice(&content);
        body.extend_from_slice(b"\r\n");
    }
    body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
    Bytes::from(body)
}

fn encoded_length(parts: &[PreparedPart], boundary: &str) -> Option<u64> {
    let mut length = u64::try_from(boundary.len() + 6).ok()?;
    for part in parts {
        length = length.checked_add(u64::try_from(part.prefix.len()).ok()?)?;
        length = length.checked_add(match &part.content {
            PreparedContent::Buffered(bytes) => u64::try_from(bytes.len()).ok()?,
            PreparedContent::Streaming(body) => body.size_hint().exact()?,
        })?;
        length = length.checked_add(2)?;
    }
    Some(length)
}

fn part_prefix(
    boundary: &str,
    name: &str,
    file_name: Option<&str>,
    media_type: Option<&str>,
    headers: &HeaderMap,
) -> Result<Bytes> {
    if headers.contains_key(CONTENT_DISPOSITION) || headers.contains_key(CONTENT_TYPE) {
        return Err(Error::request("multipart part contains a reserved header"));
    }

    let name = quoted(name, "multipart field name is invalid")?;
    let file_name = file_name
        .map(|file_name| quoted(file_name, "multipart part file name is invalid"))
        .transpose()?;
    if let Some(media_type) = media_type {
        media_type
            .parse::<Mime>()
            .map_err(|_| Error::request("multipart part media type is invalid"))?;
    }

    let mut prefix =
        format!("--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"").into_bytes();
    if let Some(file_name) = file_name {
        prefix.extend_from_slice(format!("; filename=\"{file_name}\"").as_bytes());
    }
    prefix.extend_from_slice(b"\r\n");
    if let Some(media_type) = media_type {
        prefix.extend_from_slice(b"Content-Type: ");
        prefix.extend_from_slice(media_type.as_bytes());
        prefix.extend_from_slice(b"\r\n");
    }
    for name in headers.keys() {
        for value in headers.get_all(name) {
            prefix.extend_from_slice(name.as_str().as_bytes());
            prefix.extend_from_slice(b": ");
            prefix.extend_from_slice(value.as_bytes());
            prefix.extend_from_slice(b"\r\n");
        }
    }
    prefix.extend_from_slice(b"\r\n");
    Ok(Bytes::from(prefix))
}

fn quoted(value: &str, error: &'static str) -> Result<String> {
    if value.bytes().any(|byte| byte.is_ascii_control()) {
        return Err(Error::request(error));
    }

    let mut quoted = String::with_capacity(value.len());
    for character in value.chars() {
        if matches!(character, '"' | '\\') {
            quoted.push('\\');
        }
        quoted.push(character);
    }
    Ok(quoted)
}