pingora_core/modules/http/
compression.rs

1// Copyright 2024 Cloudflare, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! HTTP compression filter
16
17use super::*;
18use crate::protocols::http::compression::ResponseCompressionCtx;
19use std::ops::{Deref, DerefMut};
20
21/// HTTP response compression module
22pub struct ResponseCompression(ResponseCompressionCtx);
23
24impl Deref for ResponseCompression {
25    type Target = ResponseCompressionCtx;
26
27    fn deref(&self) -> &Self::Target {
28        &self.0
29    }
30}
31
32impl DerefMut for ResponseCompression {
33    fn deref_mut(&mut self) -> &mut Self::Target {
34        &mut self.0
35    }
36}
37
38#[async_trait]
39impl HttpModule for ResponseCompression {
40    fn as_any(&self) -> &dyn std::any::Any {
41        self
42    }
43    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
44        self
45    }
46
47    async fn request_header_filter(&mut self, req: &mut RequestHeader) -> Result<()> {
48        self.0.request_filter(req);
49        Ok(())
50    }
51
52    async fn response_header_filter(
53        &mut self,
54        resp: &mut ResponseHeader,
55        end_of_stream: bool,
56    ) -> Result<()> {
57        self.0.response_header_filter(resp, end_of_stream);
58        Ok(())
59    }
60
61    fn response_body_filter(
62        &mut self,
63        body: &mut Option<Bytes>,
64        end_of_stream: bool,
65    ) -> Result<()> {
66        if !self.0.is_enabled() {
67            return Ok(());
68        }
69        let compressed = self.0.response_body_filter(body.as_ref(), end_of_stream);
70        if compressed.is_some() {
71            *body = compressed;
72        }
73        Ok(())
74    }
75}
76
77/// The builder for HTTP response compression module
78pub struct ResponseCompressionBuilder {
79    level: u32,
80}
81
82impl ResponseCompressionBuilder {
83    /// Return a [ModuleBuilder] for [ResponseCompression] with the given compression level
84    pub fn enable(level: u32) -> ModuleBuilder {
85        Box::new(ResponseCompressionBuilder { level })
86    }
87}
88
89impl HttpModuleBuilder for ResponseCompressionBuilder {
90    fn init(&self) -> Module {
91        Box::new(ResponseCompression(ResponseCompressionCtx::new(
92            self.level, false, false,
93        )))
94    }
95
96    fn order(&self) -> i16 {
97        // run the response filter later than most others filters
98        i16::MIN / 2
99    }
100}