tez 0.0.2

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
use std::collections::VecDeque;

use futures_util::stream;
use http::{
    HeaderMap, HeaderValue,
    header::{CONTENT_DISPOSITION, CONTENT_TYPE},
};
use http_body::Frame;
use http_body_util::{BodyExt as _, StreamBody};
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 parts = parts
            .into_iter()
            .map(PreparedPart::into_streaming)
            .collect::<VecDeque<_>>();
        let stream = stream::unfold(
            MultipartStream {
                parts,
                current: None,
                tail: Some(Bytes::from(format!("--{boundary}--\r\n"))),
                failed: false,
            },
            |mut multipart| async move { multipart.next_frame().await.map(|frame| (frame, multipart)) },
        );
        Ok((Body::wrap(StreamBody::new(stream)), 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))
    }

    /// 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 MultipartStream {
    async fn next_frame(&mut self) -> Option<Result<Frame<Bytes>>> {
        if self.failed {
            return None;
        }

        loop {
            if let Some(body) = &mut self.current {
                match body.frame().await {
                    Some(Ok(frame)) => {
                        if let Ok(data) = frame.into_data()
                            && !data.is_empty()
                        {
                            return Some(Ok(Frame::data(data)));
                        }
                    }
                    Some(Err(error)) => {
                        self.failed = true;
                        return Some(Err(error));
                    }
                    None => {
                        self.current = None;
                        return Some(Ok(Frame::data(Bytes::from_static(b"\r\n"))));
                    }
                }
                continue;
            }

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

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 mut body = Vec::new();
    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 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)
}