| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| use futures_util::StreamExt; | |
| use maka_capabilities::http::{self, Bytes}; | |
| use zstd::stream::raw::{Encoder, InBuffer, Operation, OutBuffer}; | |
| const ZSTD_LEVEL: i32 = 3; | |
| const CHUNK_BYTES: usize = 16 * 1024; | |
| /// Stream-compress an HTTP request body with zstd without buffering the full | |
| /// payload in memory. Preserves upload cleanup and replay sources. | |
| pub fn zstd_request_body(body: http::RequestBody) -> http::RequestBody { | |
| body.map_stream(zstd_stream) | |
| } | |
| struct ZstdState { | |
| upstream: futures_util::stream::BoxStream<'static, Result<Bytes, http::Error>>, | |
| encoder: Option<Encoder<'static>>, | |
| pending: Bytes, | |
| out: Vec<u8>, | |
| finishing: bool, | |
| done: bool, | |
| } | |
| fn zstd_stream( | |
| upstream: futures_util::stream::BoxStream<'static, Result<Bytes, http::Error>>, | |
| ) -> impl futures_util::Stream<Item = Result<Bytes, http::Error>> + Send + 'static { | |
| let state = ZstdState { | |
| upstream, | |
| encoder: None, | |
| pending: Bytes::new(), | |
| out: vec![0_u8; CHUNK_BYTES], | |
| finishing: false, | |
| done: false, | |
| }; | |
| futures_util::stream::unfold(state, |mut state| async move { | |
| if state.done { | |
| return None; | |
| } | |
| if state.encoder.is_none() { | |
| match Encoder::new(ZSTD_LEVEL) { | |
| Ok(encoder) => state.encoder = Some(encoder), | |
| Err(error) => { | |
| state.done = true; | |
| return Some(( | |
| Err(http::Error::Failed(format!( | |
| "zstd request compression initialization failed: {error}" | |
| ))), | |
| state, | |
| )); | |
| } | |
| } | |
| } | |
| loop { | |
| if state.finishing { | |
| let encoder = state.encoder.as_mut().expect("encoder initialized"); | |
| let mut out_buf = OutBuffer::around(&mut state.out); | |
| match encoder.finish(&mut out_buf, true) { | |
| Ok(remaining) => { | |
| let written = out_buf.pos(); | |
| if remaining == 0 { | |
| state.done = true; | |
| } | |
| if written > 0 { | |
| let chunk = Bytes::copy_from_slice(&state.out[..written]); | |
| return Some((Ok(chunk), state)); | |
| } | |
| if remaining == 0 { | |
| return None; | |
| } | |
| tokio::task::coop::consume_budget().await; | |
| continue; | |
| } | |
| Err(error) => { | |
| state.done = true; | |
| return Some(( | |
| Err(http::Error::Failed(format!( | |
| "zstd request compression failed: {error}" | |
| ))), | |
| state, | |
| )); | |
| } | |
| } | |
| } | |
| if state.pending.is_empty() { | |
| match state.upstream.next().await { | |
| Some(Ok(chunk)) => { | |
| if chunk.is_empty() { | |
| continue; | |
| } | |
| state.pending = chunk; | |
| } | |
| Some(Err(error)) => { | |
| state.done = true; | |
| return Some((Err(error), state)); | |
| } | |
| None => { | |
| state.finishing = true; | |
| continue; | |
| } | |
| } | |
| } | |
| let slice_len = state.pending.len().min(CHUNK_BYTES); | |
| let encoder = state.encoder.as_mut().expect("encoder initialized"); | |
| let mut in_buf = InBuffer::around(&state.pending[..slice_len]); | |
| let mut out_buf = OutBuffer::around(&mut state.out); | |
| let status = encoder.run(&mut in_buf, &mut out_buf); | |
| let consumed = in_buf.pos(); | |
| let written = out_buf.pos(); | |
| match status { | |
| Ok(_) => { | |
| if consumed == 0 && written == 0 { | |
| state.done = true; | |
| return Some(( | |
| Err(http::Error::Failed( | |
| "zstd request compression made no progress".into(), | |
| )), | |
| state, | |
| )); | |
| } | |
| if consumed > 0 { | |
| let _ = state.pending.split_to(consumed); | |
| } | |
| tokio::task::coop::consume_budget().await; | |
| if written > 0 { | |
| let chunk = Bytes::copy_from_slice(&state.out[..written]); | |
| return Some((Ok(chunk), state)); | |
| } | |
| } | |
| Err(error) => { | |
| state.done = true; | |
| return Some(( | |
| Err(http::Error::Failed(format!( | |
| "zstd request compression failed: {error}" | |
| ))), | |
| state, | |
| )); | |
| } | |
| } | |
| } | |
| }) | |
| } |