Skip to main content

hyperlane_plugin_compression/
impl.rs

1use super::*;
2
3impl Default for CompressionConfig {
4    /// Builds the configuration the compression plugin uses when none is given.
5    ///
6    /// # Returns
7    ///
8    /// - `Self` - The default configuration.
9    fn default() -> Self {
10        Self {
11            min_size: DEFAULT_MIN_SIZE,
12            encodings: vec![Compress::Gzip, Compress::Br],
13        }
14    }
15}
16
17impl CompressionConfig {
18    /// The rules the configuration works from.
19    ///
20    /// The encodings that are not known are left out, so the plugin never
21    /// answers with an encoding it cannot write.
22    ///
23    /// # Returns
24    ///
25    /// - `CompressionPolicy` - The rules of the configuration.
26    fn policy(&self) -> CompressionPolicy {
27        CompressionPolicy {
28            encodings: self
29                .get_encodings()
30                .iter()
31                .filter(|encoding: &&Compress| !encoding.is_unknown())
32                .map(|encoding: &Compress| encoding.to_string())
33                .collect(),
34            min_size: self.get_min_size(),
35        }
36    }
37
38    /// The encoding the client asked for, when one of the offered encodings
39    /// is accepted.
40    ///
41    /// The offered encodings are tried in the order they are preferred, so the
42    /// first one the client accepts is the one that is used.
43    ///
44    /// # Arguments
45    ///
46    /// - `&str` - The `accept-encoding` header of the request.
47    ///
48    /// # Returns
49    ///
50    /// - `Option<Compress>` - The encoding to answer with, when the client
51    ///   accepts one of the offered encodings.
52    pub fn pick(&self, accept: &str) -> Option<Compress> {
53        let encoding: String = self.policy().pick(accept)?;
54        encoding.parse::<Compress>().ok()
55    }
56
57    /// Whether a body of that content type is worth compressing.
58    ///
59    /// A body that is already compressed is sent as it is, and the stream of
60    /// events is never compressed.
61    ///
62    /// # Arguments
63    ///
64    /// - `&str` - The content type of the answer.
65    ///
66    /// # Returns
67    ///
68    /// - `bool` - Whether the body may be compressed.
69    pub fn is_compressible(&self, content_type: &str) -> bool {
70        CompressionPolicy::is_compressible(content_type)
71    }
72}
73
74impl CompressionPlugin {
75    /// Stores the configuration the plugin works from.
76    ///
77    /// # Arguments
78    ///
79    /// - `CompressionConfig` - The configuration to store.
80    ///
81    /// # Returns
82    ///
83    /// - `Result<(), String>` - Nothing, or the reason the configuration was
84    ///   refused.
85    pub fn init(config: CompressionConfig) -> Result<(), String> {
86        let policy: CompressionPolicy = config.policy();
87        CONFIG
88            .set(config)
89            .map_err(|_: CompressionConfig| MESSAGE_ALREADY_SET.to_owned())?;
90        POLICY
91            .set(policy)
92            .map_err(|_: CompressionPolicy| MESSAGE_ALREADY_SET.to_owned())
93    }
94
95    /// The configuration the plugin works from.
96    ///
97    /// # Returns
98    ///
99    /// - `Option<&'static CompressionConfig>` - The configuration, when it was
100    ///   set.
101    pub fn get() -> Option<&'static CompressionConfig> {
102        CONFIG.get()
103    }
104}
105
106impl ServerHook for CompressionMiddleware {
107    /// Builds the middleware.
108    ///
109    /// # Arguments
110    ///
111    /// - `&mut Stream` - The stream the request arrived on.
112    /// - `&mut Context` - The context of the request.
113    ///
114    /// # Returns
115    ///
116    /// - `Self` - The middleware.
117    async fn new(_: &mut Stream, _: &mut Context) -> Self {
118        Self
119    }
120
121    /// Marks the answer with the encoding the client asked for.
122    ///
123    /// The body is compressed when the answer is built, so the middleware only
124    /// writes the header that names the encoding.
125    ///
126    /// # Arguments
127    ///
128    /// - `Self` - The middleware.
129    /// - `&mut Stream` - The stream the request arrived on.
130    /// - `&mut Context` - The context of the request.
131    ///
132    /// # Returns
133    ///
134    /// - `Status` - Whether the pipeline continues.
135    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
136        let policy: &CompressionPolicy = match POLICY.get() {
137            Some(policy) => policy,
138            None => return Status::Continue,
139        };
140        let accept: String = match ctx.get_request().try_get_header(ACCEPT_ENCODING) {
141            Some(values) => match values.front() {
142                Some(value) => value.clone(),
143                None => return Status::Continue,
144            },
145            None => return Status::Continue,
146        };
147        let encoding: String = match policy.pick(&accept) {
148            Some(encoding) => encoding,
149            None => return Status::Continue,
150        };
151        let response: &mut Response = ctx.get_mut_response();
152        if response.try_get_header_back(CONTENT_ENCODING).is_some() {
153            return Status::Continue;
154        }
155        if response.get_body().len() < policy.get_min_size() {
156            return Status::Continue;
157        }
158        let content_type: String = response
159            .try_get_header_back(CONTENT_TYPE)
160            .unwrap_or_default();
161        if !CompressionPolicy::is_compressible(&content_type) {
162            return Status::Continue;
163        }
164        response.set_header(CONTENT_ENCODING, encoding);
165        response.set_header(VARY, VARY_ACCEPT_ENCODING);
166        Status::Continue
167    }
168}