Skip to content

The platform for continuously improving AI agents.

2.2 KB
Raw Blame
use std::io::Read;

use axum::http::{HeaderMap, header};
use bytes::Bytes;
use flate2::read::GzDecoder;
use serde::{Serialize, de::DeserializeOwned};

const MAX_DECOMPRESSED_BYTES: u64 = 64 * 1024 * 1024;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    Proto,
    Json,
}

impl Format {
    /// `proto_types` lists the protobuf media types the endpoint accepts.
    pub fn from_headers(headers: &HeaderMap, proto_types: &[&str]) -> Option<Self> {
        let content_type = headers
            .get(header::CONTENT_TYPE)?
            .to_str()
            .ok()?
            .split(';')
            .next()?
            .trim()
            .to_ascii_lowercase();
        if content_type == "application/json" {
            Some(Self::Json)
        } else if proto_types.contains(&content_type.as_str()) {
            Some(Self::Proto)
        } else {
            None
        }
    }

    pub fn decode<M: prost::Message + Default + DeserializeOwned>(
        self,
        body: &[u8],
    ) -> Result<M, String> {
        match self {
            Self::Proto => M::decode(body).map_err(|e| e.to_string()),
            Self::Json => serde_json::from_slice(body).map_err(|e| e.to_string()),
        }
    }

    pub fn encode<M: prost::Message + Serialize>(self, message: &M) -> Vec<u8> {
        match self {
            Self::Proto => message.encode_to_vec(),
            Self::Json => serde_json::to_vec(message).expect("protobuf messages serialize to JSON"),
        }
    }
}

/// The body with any `content_encoding_header` gzip removed.
pub fn decompress(
    headers: &HeaderMap,
    content_encoding_header: &str,
    body: Bytes,
) -> Result<Bytes, String> {
    let encoding = headers
        .get(content_encoding_header)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("identity")
        .trim()
        .to_ascii_lowercase();
    match encoding.as_str() {
        "" | "identity" => Ok(body),
        "gzip" => {
            let mut out = Vec::new();
            GzDecoder::new(body.as_ref())
                .take(MAX_DECOMPRESSED_BYTES)
                .read_to_end(&mut out)
                .map_err(|e| format!("invalid gzip body: {e}"))?;
            Ok(out.into())
        }
        other => Err(format!("unsupported encoding {other}")),
    }
}