From 611a9a92d8b79f8c2f1e463a15d9077c36d47001 Mon Sep 17 00:00:00 2001 From: Filip Tibell Date: Sun, 27 Apr 2025 13:09:37 +0200 Subject: [PATCH] Implement decompression for incoming bodies --- crates/lune-std-net/src/shared/incoming.rs | 30 ++++++++++++++++++---- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/lune-std-net/src/shared/incoming.rs b/crates/lune-std-net/src/shared/incoming.rs index 3743710..eabf16e 100644 --- a/crates/lune-std-net/src/shared/incoming.rs +++ b/crates/lune-std-net/src/shared/incoming.rs @@ -2,20 +2,23 @@ use futures_lite::prelude::*; use http_body_util::BodyStream; use hyper::{ body::{Body as _, Bytes, Incoming}, + header::CONTENT_ENCODING, HeaderMap, }; use mlua::prelude::*; +use lune_std_serde::{decompress, CompressDecompressFormat}; + pub async fn handle_incoming_body( - _headers: &HeaderMap, + headers: &HeaderMap, body: Incoming, - _decompress: bool, + should_decompress: bool, ) -> LuaResult<(Bytes, bool)> { let size = body.size_hint().lower() as usize; let buffer = Vec::::with_capacity(size); - let body = BodyStream::new(body) + let mut body = BodyStream::new(body) .try_fold(buffer, |mut body, chunk| { if let Some(chunk) = chunk.data_ref() { body.extend_from_slice(chunk); @@ -25,7 +28,24 @@ pub async fn handle_incoming_body( .await .into_lua_err()?; - // TODO: Decompress the body if necessary + let was_decompressed = if should_decompress { + let decompress_format = headers + .iter() + .find(|(name, _)| { + name.as_str() + .eq_ignore_ascii_case(CONTENT_ENCODING.as_str()) + }) + .and_then(|(_, value)| value.to_str().ok()) + .and_then(CompressDecompressFormat::detect_from_header_str); + if let Some(format) = decompress_format { + body = decompress(body, format).await?; + true + } else { + false + } + } else { + false + }; - Ok((Bytes::from(body), false)) + Ok((Bytes::from(body), was_decompressed)) }