1use bytes::{Buf, Bytes, BytesMut};
30use futures_core::Stream;
31use http::HeaderValue;
32use http_body::{Body, Frame};
33use pin_project_lite::pin_project;
34use std::{
35 io,
36 pin::Pin,
37 task::{Context, Poll, ready},
38};
39use tokio::io::AsyncRead;
40use tokio_util::io::StreamReader;
41use tower_http::BoxError;
42
43use super::content_encoding::SupportedEncodings;
44
45#[derive(Debug, Clone, Copy)]
46pub(crate) struct AcceptEncoding {
47 pub(crate) gzip: bool,
48 pub(crate) deflate: bool,
49 pub(crate) br: bool,
50 pub(crate) zstd: bool,
51}
52
53impl AcceptEncoding {
54 #[expect(dead_code, reason = "potentially unused API helper")]
55 pub(crate) fn to_header_value(self) -> Option<HeaderValue> {
56 let accept = match (self.gzip, self.deflate, self.br, self.zstd) {
57 (true, true, true, false) => "gzip,deflate,br",
58 (true, true, false, false) => "gzip,deflate",
59 (true, false, true, false) => "gzip,br",
60 (true, false, false, false) => "gzip",
61 (false, true, true, false) => "deflate,br",
62 (false, true, false, false) => "deflate",
63 (false, false, true, false) => "br",
64 (true, true, true, true) => "zstd,gzip,deflate,br",
65 (true, true, false, true) => "zstd,gzip,deflate",
66 (true, false, true, true) => "zstd,gzip,br",
67 (true, false, false, true) => "zstd,gzip",
68 (false, true, true, true) => "zstd,deflate,br",
69 (false, true, false, true) => "zstd,deflate",
70 (false, false, true, true) => "zstd,br",
71 (false, false, false, true) => "zstd",
72 (false, false, false, false) => return None,
73 };
74 Some(HeaderValue::from_static(accept))
75 }
76
77 #[expect(dead_code, reason = "potentially unused API helper")]
78 pub(crate) fn set_gzip(&mut self, enable: bool) {
79 self.gzip = enable;
80 }
81
82 #[expect(dead_code, reason = "potentially unused API helper")]
83 pub(crate) fn set_deflate(&mut self, enable: bool) {
84 self.deflate = enable;
85 }
86
87 #[expect(dead_code, reason = "potentially unused API helper")]
88 pub(crate) fn set_br(&mut self, enable: bool) {
89 self.br = enable;
90 }
91
92 #[expect(dead_code, reason = "potentially unused API helper")]
93 pub(crate) fn set_zstd(&mut self, enable: bool) {
94 self.zstd = enable;
95 }
96}
97
98impl SupportedEncodings for AcceptEncoding {
99 fn gzip(&self) -> bool {
100 self.gzip
101 }
102
103 fn deflate(&self) -> bool {
104 self.deflate
105 }
106
107 fn br(&self) -> bool {
108 self.br
109 }
110
111 fn zstd(&self) -> bool {
112 self.zstd
113 }
114}
115
116impl Default for AcceptEncoding {
117 fn default() -> Self {
118 AcceptEncoding {
119 gzip: true,
120 deflate: true,
121 br: true,
122 zstd: false, }
124 }
125}
126
127pub(crate) type AsyncReadBody<B> = StreamReader<
129 StreamErrorIntoIoError<BodyIntoStream<B>, <B as Body>::Error>,
130 <B as Body>::Data,
131>;
132
133pub(crate) trait DecorateAsyncRead {
135 type Input: AsyncRead;
136 type Output: AsyncRead;
137
138 fn apply(input: Self::Input, quality: CompressionLevel) -> Self::Output;
140
141 fn get_pin_mut(pinned: Pin<&mut Self::Output>) -> Pin<&mut Self::Input>;
145}
146
147pin_project! {
148 pub(crate) struct WrapBody<M: DecorateAsyncRead> {
150 #[pin]
151 pub read: M::Output,
154 buf: BytesMut,
157 read_all_data: bool,
158 }
159}
160
161impl<M: DecorateAsyncRead> WrapBody<M> {
162 const INTERNAL_BUF_CAPACITY: usize = 4096;
163}
164
165impl<M: DecorateAsyncRead> WrapBody<M> {
166 #[expect(dead_code, reason = "potentially unused API helper")]
167 pub(crate) fn new<B>(body: B, quality: CompressionLevel) -> Self
168 where
169 B: Body,
170 M: DecorateAsyncRead<Input = AsyncReadBody<B>>,
171 {
172 let stream = BodyIntoStream::new(body);
174
175 let stream = StreamErrorIntoIoError::<_, B::Error>::new(stream);
178
179 let read = StreamReader::new(stream);
181
182 let read = M::apply(read, quality);
184
185 Self {
186 read,
187 buf: BytesMut::with_capacity(Self::INTERNAL_BUF_CAPACITY),
188 read_all_data: false,
189 }
190 }
191}
192
193impl<B, M> Body for WrapBody<M>
194where
195 B: Body,
196 B::Error: Into<BoxError>,
197 M: DecorateAsyncRead<Input = AsyncReadBody<B>>,
198{
199 type Data = Bytes;
200 type Error = BoxError;
201
202 fn poll_frame(
203 self: Pin<&mut Self>,
204 cx: &mut Context<'_>,
205 ) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
206 let mut this = self.project();
207
208 if !*this.read_all_data {
209 if this.buf.capacity() == 0 {
210 this.buf.reserve(Self::INTERNAL_BUF_CAPACITY);
211 }
212
213 let result = tokio_util::io::poll_read_buf(
214 this.read.as_mut(),
215 cx,
216 &mut this.buf,
217 );
218
219 match ready!(result) {
220 Ok(0) => {
221 *this.read_all_data = true;
222 }
223 Ok(_) => {
224 let chunk = this.buf.split().freeze();
225 return Poll::Ready(Some(Ok(Frame::data(chunk))));
226 }
227 Err(err) => {
228 let body_error: Option<B::Error> =
229 M::get_pin_mut(this.read.as_mut())
230 .get_pin_mut()
231 .project()
232 .error
233 .take();
234
235 let read_some_data = M::get_pin_mut(this.read.as_mut())
236 .get_pin_mut()
237 .project()
238 .read_some_data;
239
240 if let Some(body_error) = body_error {
241 return Poll::Ready(Some(Err(body_error.into())));
242 } else if err.raw_os_error() == Some(SENTINEL_ERROR_CODE) {
243 unreachable!()
246 } else if *read_some_data {
247 return Poll::Ready(Some(Err(err.into())));
248 }
249 }
250 }
251 }
252
253 let body = M::get_pin_mut(this.read).get_pin_mut().get_pin_mut();
255 match ready!(body.poll_frame(cx)) {
256 Some(Ok(frame)) => {
257 Poll::Ready(Some(Ok(frame.map_data(|mut data| {
258 data.copy_to_bytes(data.remaining())
259 }))))
260 }
261 Some(Err(err)) => Poll::Ready(Some(Err(err.into()))),
262 None => Poll::Ready(None),
263 }
264 }
265}
266
267pin_project! {
268 pub(crate) struct BodyIntoStream<B>
269 where
270 B: Body,
271 {
272 #[pin]
273 body: B,
274 yielded_all_data: bool,
275 non_data_frame: Option<Frame<B::Data>>,
276 }
277}
278
279#[expect(dead_code, reason = "potentially unused API helper")]
280impl<B> BodyIntoStream<B>
281where
282 B: Body,
283{
284 pub(crate) fn new(body: B) -> Self {
285 Self {
286 body,
287 yielded_all_data: false,
288 non_data_frame: None,
289 }
290 }
291
292 pub(crate) fn get_ref(&self) -> &B {
294 &self.body
295 }
296
297 pub(crate) fn get_mut(&mut self) -> &mut B {
299 &mut self.body
300 }
301
302 pub(crate) fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut B> {
304 self.project().body
305 }
306
307 pub(crate) fn into_inner(self) -> B {
309 self.body
310 }
311}
312
313impl<B> Stream for BodyIntoStream<B>
314where
315 B: Body,
316{
317 type Item = Result<B::Data, B::Error>;
318
319 fn poll_next(
320 mut self: Pin<&mut Self>,
321 cx: &mut Context<'_>,
322 ) -> Poll<Option<Self::Item>> {
323 loop {
324 let this = self.as_mut().project();
325
326 if *this.yielded_all_data {
327 return Poll::Ready(None);
328 }
329
330 match std::task::ready!(this.body.poll_frame(cx)) {
331 Some(Ok(frame)) => match frame.into_data() {
332 Ok(data) => return Poll::Ready(Some(Ok(data))),
333 Err(frame) => {
334 *this.yielded_all_data = true;
335 *this.non_data_frame = Some(frame);
336 }
337 },
338 Some(Err(err)) => return Poll::Ready(Some(Err(err))),
339 None => {
340 *this.yielded_all_data = true;
341 }
342 }
343 }
344 }
345}
346
347impl<B> Body for BodyIntoStream<B>
348where
349 B: Body,
350{
351 type Data = B::Data;
352 type Error = B::Error;
353
354 fn poll_frame(
355 mut self: Pin<&mut Self>,
356 cx: &mut Context<'_>,
357 ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
358 if let Some(frame) = std::task::ready!(self.as_mut().poll_next(cx)) {
361 return Poll::Ready(Some(frame.map(Frame::data)));
362 }
363
364 let this = self.project();
365
366 if let Some(frame) = this.non_data_frame.take() {
368 return Poll::Ready(Some(Ok(frame)));
369 }
370
371 this.body.poll_frame(cx)
374 }
375
376 #[inline]
377 fn size_hint(&self) -> http_body::SizeHint {
378 self.body.size_hint()
379 }
380}
381
382pin_project! {
383 pub(crate) struct StreamErrorIntoIoError<S, E> {
384 #[pin]
385 inner: S,
386 error: Option<E>,
387 read_some_data: bool
388 }
389}
390
391impl<S, E> StreamErrorIntoIoError<S, E> {
392 pub(crate) fn new(inner: S) -> Self {
393 Self {
394 inner,
395 error: None,
396 read_some_data: false,
397 }
398 }
399
400 pub(crate) fn get_ref(&self) -> &S {
402 &self.inner
403 }
404
405 pub(crate) fn get_mut(&mut self) -> &mut S {
407 &mut self.inner
408 }
409
410 pub(crate) fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut S> {
412 self.project().inner
413 }
414
415 pub(crate) fn into_inner(self) -> S {
417 self.inner
418 }
419}
420
421impl<S, T, E> Stream for StreamErrorIntoIoError<S, E>
422where
423 S: Stream<Item = Result<T, E>>,
424{
425 type Item = Result<T, io::Error>;
426
427 fn poll_next(
428 self: Pin<&mut Self>,
429 cx: &mut Context<'_>,
430 ) -> Poll<Option<Self::Item>> {
431 let this = self.project();
432 match ready!(this.inner.poll_next(cx)) {
433 None => Poll::Ready(None),
434 Some(Ok(value)) => {
435 *this.read_some_data = true;
436 Poll::Ready(Some(Ok(value)))
437 }
438 Some(Err(err)) => {
439 *this.error = Some(err);
440 Poll::Ready(Some(Err(io::Error::from_raw_os_error(
441 SENTINEL_ERROR_CODE,
442 ))))
443 }
444 }
445 }
446}
447
448pub(crate) const SENTINEL_ERROR_CODE: i32 = -837459418;
449
450#[non_exhaustive]
452#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
453pub enum CompressionLevel {
454 Fastest,
456 Best,
458 #[default]
461 Default,
462 Precise(i32),
470}
471
472use async_compression::Level as AsyncCompressionLevel;
473
474impl CompressionLevel {
475 pub(crate) fn into_async_compression(self) -> AsyncCompressionLevel {
476 match self {
477 CompressionLevel::Fastest => AsyncCompressionLevel::Fastest,
478 CompressionLevel::Best => AsyncCompressionLevel::Best,
479 CompressionLevel::Default => AsyncCompressionLevel::Default,
480 CompressionLevel::Precise(quality) => {
481 AsyncCompressionLevel::Precise(quality)
482 }
483 }
484 }
485}
486
487