ctb_io_webui/middleware/compression_with_range/
compression_utils.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from from tower-http: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Derived from tower-http (https://github.com/tower-rs/tower-http):
22
23// Copyright (c) 2019-2021 Tower Contributors
24
25// See additional licensing details at end of file.
26
27//! Types used by compression and decompression middleware.
28
29use 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, // disable zstd since there is no solid native rust implementation yet
123        }
124    }
125}
126
127/// A `Body` that has been converted into an `AsyncRead`.
128pub(crate) type AsyncReadBody<B> = StreamReader<
129    StreamErrorIntoIoError<BodyIntoStream<B>, <B as Body>::Error>,
130    <B as Body>::Data,
131>;
132
133/// Trait for applying some decorator to an `AsyncRead`
134pub(crate) trait DecorateAsyncRead {
135    type Input: AsyncRead;
136    type Output: AsyncRead;
137
138    /// Apply the decorator
139    fn apply(input: Self::Input, quality: CompressionLevel) -> Self::Output;
140
141    /// Get a pinned mutable reference to the original input.
142    ///
143    /// This is necessary to implement `Body::poll_trailers`.
144    fn get_pin_mut(pinned: Pin<&mut Self::Output>) -> Pin<&mut Self::Input>;
145}
146
147pin_project! {
148    /// `Body` that has been decorated by an `AsyncRead`
149    pub(crate) struct WrapBody<M: DecorateAsyncRead> {
150        #[pin]
151        // rust-analyer thinks this field is private if its `pub(crate)` but works fine when its
152        // `pub`
153        pub read: M::Output,
154        // A buffer to temporarily store the data read from the underlying body.
155        // Reused as much as possible to optimize allocations.
156        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        // convert `Body` into a `Stream`
173        let stream = BodyIntoStream::new(body);
174
175        // an adapter that converts the error type into `io::Error` while storing the actual error
176        // `StreamReader` requires the error type is `io::Error`
177        let stream = StreamErrorIntoIoError::<_, B::Error>::new(stream);
178
179        // convert `Stream` into an `AsyncRead`
180        let read = StreamReader::new(stream);
181
182        // apply decorator to `AsyncRead` yielding another `AsyncRead`
183        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                        // SENTINEL_ERROR_CODE only gets used when storing
244                        // an underlying body error
245                        unreachable!()
246                    } else if *read_some_data {
247                        return Poll::Ready(Some(Err(err.into())));
248                    }
249                }
250            }
251        }
252
253        // poll any remaining frames, such as trailers
254        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    /// Get a reference to the inner body
293    pub(crate) fn get_ref(&self) -> &B {
294        &self.body
295    }
296
297    /// Get a mutable reference to the inner body
298    pub(crate) fn get_mut(&mut self) -> &mut B {
299        &mut self.body
300    }
301
302    /// Get a pinned mutable reference to the inner body
303    pub(crate) fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut B> {
304        self.project().body
305    }
306
307    /// Consume `self`, returning the inner body
308    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        // First drive the stream impl. This consumes all data frames and buffer at most one
359        // trailers frame.
360        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        // Yield the trailers frame `poll_next` hit.
367        if let Some(frame) = this.non_data_frame.take() {
368            return Poll::Ready(Some(Ok(frame)));
369        }
370
371        // Yield any remaining frames in the body. There shouldn't be any after the trailers but
372        // you never know.
373        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    /// Get a reference to the inner body
401    pub(crate) fn get_ref(&self) -> &S {
402        &self.inner
403    }
404
405    /// Get a mutable reference to the inner inner
406    pub(crate) fn get_mut(&mut self) -> &mut S {
407        &mut self.inner
408    }
409
410    /// Get a pinned mutable reference to the inner inner
411    pub(crate) fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut S> {
412        self.project().inner
413    }
414
415    /// Consume `self`, returning the inner inner
416    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/// Level of compression data should be compressed with.
451#[non_exhaustive]
452#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
453pub enum CompressionLevel {
454    /// Fastest quality of compression, usually produces bigger size.
455    Fastest,
456    /// Best quality of compression, usually produces the smallest size.
457    Best,
458    /// Default quality of compression defined by the selected compression
459    /// algorithm.
460    #[default]
461    Default,
462    /// Precise quality based on the underlying compression algorithms'
463    /// qualities.
464    ///
465    /// The interpretation of this depends on the algorithm chosen and the
466    /// specific implementation backing it.
467    ///
468    /// Qualities are implicitly clamped to the algorithm's maximum.
469    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/*
488Code from tower-http is used under the following license:
489======
490
491Copyright (c) 2019-2021 Tower Contributors
492
493Permission is hereby granted, free of charge, to any
494person obtaining a copy of this software and associated
495documentation files (the "Software"), to deal in the
496Software without restriction, including without
497limitation the rights to use, copy, modify, merge,
498publish, distribute, sublicense, and/or sell copies of
499the Software, and to permit persons to whom the Software
500is furnished to do so, subject to the following
501conditions:
502
503The above copyright notice and this permission notice
504shall be included in all copies or substantial portions
505of the Software.
506
507THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
508ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
509TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
510PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
511SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
512CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
513OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
514IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
515DEALINGS IN THE SOFTWARE.
516
517
518*/