hyperlane_plugin_etag/impl.rs
1use super::*;
2
3/// Default construction for [`EtagConfig`].
4impl Default for EtagConfig {
5 /// Constructs an [`EtagConfig`] generating strong ETags with `If-Match` validation enabled.
6 ///
7 /// # Returns
8 ///
9 /// - `Self` - Default configuration.
10 fn default() -> Self {
11 Self {
12 strength: EtagStrength::Strong,
13 min_body_bytes: DEFAULT_MIN_ETAG_BYTES,
14 exempt_prefixes: Vec::new(),
15 enforce_if_match: true,
16 }
17 }
18}
19
20/// Fluent builder helpers for [`EtagConfig`].
21impl EtagConfig {
22 /// Selects strong or weak entity-tag generation.
23 ///
24 /// # Arguments
25 ///
26 /// - `EtagStrength` - Desired tag strength.
27 ///
28 /// # Returns
29 ///
30 /// - `Self` - Updated configuration.
31 pub fn with_strength(mut self, strength: EtagStrength) -> Self {
32 self.set_strength(strength);
33 self
34 }
35
36 /// Sets the minimum response body length eligible for automatic ETag computation.
37 ///
38 /// # Arguments
39 ///
40 /// - `usize` - Minimum body size in bytes.
41 ///
42 /// # Returns
43 ///
44 /// - `Self` - Updated configuration.
45 pub fn with_min_body_bytes(mut self, min_bytes: usize) -> Self {
46 self.set_min_body_bytes(min_bytes);
47 self
48 }
49
50 /// Configures path prefixes excluded from ETag processing.
51 ///
52 /// # Arguments
53 ///
54 /// - `I` - Iterator of exempt path prefixes.
55 ///
56 /// # Returns
57 ///
58 /// - `Self` - Updated configuration.
59 pub fn with_exempt_prefixes<I, S>(mut self, prefixes: I) -> Self
60 where
61 I: IntoIterator<Item = S>,
62 S: Into<String>,
63 {
64 self.set_exempt_prefixes(prefixes.into_iter().map(Into::into).collect());
65 self
66 }
67}
68
69/// Request precondition and response conditional evaluation methods for [`EtagPlugin`].
70impl EtagPlugin {
71 /// Compiles a standalone [`EtagPlugin`] with an optional [`EtagValidator`].
72 ///
73 /// # Arguments
74 ///
75 /// - `EtagConfig` - ETag configuration.
76 /// - `Option<Arc<dyn EtagValidator>>` - Optional validator for `If-Match` checks.
77 ///
78 /// # Returns
79 ///
80 /// - `Self` - Compiled plugin.
81 pub fn new(config: EtagConfig, validator: Option<Arc<dyn EtagValidator>>) -> Self {
82 let exempt_prefixes: Box<[String]> = config
83 .get_exempt_prefixes()
84 .iter()
85 .filter(|p: &&String| !p.trim().is_empty())
86 .map(|p: &String| normalize_prefix(p))
87 .collect::<Vec<String>>()
88 .into_boxed_slice();
89 let mut r412: Response = Response::default();
90 r412.set_status_code(HttpStatus::PreconditionFailed.code())
91 .set_header(CONTENT_TYPE, DEFAULT_PRECONDITION_CONTENT_TYPE)
92 .set_body(DEFAULT_PRECONDITION_BODY);
93 let precondition_failed_wire: Vec<u8> = r412.build();
94 Self {
95 config,
96 exempt_prefixes,
97 validator,
98 precondition_failed_wire,
99 }
100 }
101
102 /// Initializes the global [`EtagPlugin`] singleton once.
103 ///
104 /// # Arguments
105 ///
106 /// - `EtagConfig` - ETag configuration.
107 ///
108 /// # Returns
109 ///
110 /// - `&'static Self` - Reference to the global plugin.
111 pub fn init(config: EtagConfig) -> &'static Self {
112 ETAG_PLUGIN.get_or_init(|| Self::new(config, None))
113 }
114
115 /// Initializes the global [`EtagPlugin`] singleton with a custom [`EtagValidator`].
116 ///
117 /// # Arguments
118 ///
119 /// - `EtagConfig` - ETag configuration.
120 /// - `Arc<dyn EtagValidator>` - Optimistic concurrency validator.
121 ///
122 /// # Returns
123 ///
124 /// - `&'static Self` - Reference to the global plugin.
125 pub fn init_with_validator(
126 config: EtagConfig,
127 validator: Arc<dyn EtagValidator>,
128 ) -> &'static Self {
129 ETAG_PLUGIN.get_or_init(|| Self::new(config, Some(validator)))
130 }
131
132 /// Returns the initialized global [`EtagPlugin`], if configured.
133 ///
134 /// # Returns
135 ///
136 /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
137 #[inline(always)]
138 pub fn get() -> Option<&'static Self> {
139 ETAG_PLUGIN.get()
140 }
141
142 /// Evaluates `If-Match` precondition on a mutating request; returns `false` when `412` must be sent.
143 ///
144 /// # Arguments
145 ///
146 /// - `&Request` - Incoming HTTP request.
147 ///
148 /// # Returns
149 ///
150 /// - `bool` - `true` when precondition passes or does not apply; `false` when violated.
151 #[inline]
152 pub fn check_if_match(&self, request: &Request) -> bool {
153 let Self {
154 config,
155 exempt_prefixes,
156 validator,
157 ..
158 } = self;
159 if !config.get_enforce_if_match() {
160 return true;
161 }
162 let Some(val_impl) = validator else {
163 return true;
164 };
165 let method: &Method = request.get_method();
166 if method.is_get() || method.is_head() || method.is_options() {
167 return true;
168 }
169 if exempt_prefixes
170 .iter()
171 .any(|p: &String| path_matches_prefix(request.get_path(), p))
172 {
173 return true;
174 }
175 let Some(if_match_val) = request
176 .get_headers()
177 .get(IF_MATCH)
178 .and_then(|vals: &VecDeque<String>| vals.back())
179 else {
180 return true;
181 };
182 let current: Option<String> = val_impl.current_etag(request);
183 matches_if_match_strong(if_match_val, current.as_deref())
184 }
185
186 /// Generates an ETag if absent and converts matching `If-None-Match` GET/HEAD responses to `304`.
187 ///
188 /// # Arguments
189 ///
190 /// - `&mut Context` - Active request/response context.
191 ///
192 /// # Returns
193 ///
194 /// - `bool` - `true` if the response was converted to `304 Not Modified`.
195 #[inline]
196 pub fn apply_response(&self, ctx: &mut Context) -> bool {
197 let Self {
198 config,
199 exempt_prefixes,
200 ..
201 } = self;
202 let request: &Request = ctx.get_request();
203 let method: &Method = request.get_method();
204 if !method.is_get() && !method.is_head() {
205 return false;
206 }
207 if exempt_prefixes
208 .iter()
209 .any(|p: &String| path_matches_prefix(request.get_path(), p))
210 {
211 return false;
212 }
213 let response: &Response = ctx.get_response();
214 let status: usize = response.get_status_code();
215 if !(200..300).contains(&status) || status_has_no_body(status) {
216 return false;
217 }
218 let existing_tag: Option<&str> = response
219 .get_headers()
220 .get(ETAG)
221 .and_then(|vals: &VecDeque<String>| vals.back().map(String::as_str));
222 let matched: bool = if let Some(tag) = existing_tag {
223 request.matches_if_none_match(tag)
224 } else {
225 let body: &[u8] = response.get_body();
226 if body.len() < config.get_min_body_bytes() {
227 return false;
228 }
229 let digest: u64 = hash_entity_bytes(body);
230 match config.get_strength() {
231 EtagStrength::Strong => {
232 let buf: [u8; 18] = format_strong_etag_stack(digest);
233 let tag: &str = from_utf8(&buf).unwrap_or_default();
234 let is_match: bool = request.matches_if_none_match(tag);
235 ctx.get_mut_response().set_header(ETAG, tag);
236 is_match
237 }
238 EtagStrength::Weak => {
239 let buf: [u8; 20] = format_weak_etag_stack(digest);
240 let tag: &str = from_utf8(&buf).unwrap_or_default();
241 let is_match: bool = request.matches_if_none_match(tag);
242 ctx.get_mut_response().set_header(ETAG, tag);
243 is_match
244 }
245 }
246 };
247 if matched {
248 let resp: &mut Response = ctx.get_mut_response();
249 resp.set_status_code(HttpStatus::NotModified.code());
250 resp.get_mut_body().clear();
251 return true;
252 }
253 false
254 }
255}
256
257/// Implements [`ServerHook`] for [`EtagRequestHook`].
258impl ServerHook for EtagRequestHook {
259 /// Constructs a per-request [`EtagRequestHook`].
260 ///
261 /// # Arguments
262 ///
263 /// - `&mut Stream` - Connection stream.
264 /// - `&mut Context` - Request context.
265 ///
266 /// # Returns
267 ///
268 /// - `Self` - Hook instance.
269 #[inline(always)]
270 async fn new(_: &mut Stream, _: &mut Context) -> Self {
271 Self
272 }
273
274 /// Enforces `If-Match` preconditions on mutating requests when an [`EtagValidator`] is configured.
275 ///
276 /// # Arguments
277 ///
278 /// - `Self` - Hook instance.
279 /// - `&mut Stream` - Connection stream.
280 /// - `&mut Context` - Request context.
281 ///
282 /// # Returns
283 ///
284 /// - `Status` - `Status::Continue` when satisfied; `Status::Reject` after sending `412`.
285 #[inline(always)]
286 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
287 let Some(plugin) = EtagPlugin::get() else {
288 return Status::Continue;
289 };
290 if !plugin.check_if_match(ctx.get_request()) {
291 let EtagPlugin {
292 precondition_failed_wire,
293 ..
294 } = plugin;
295 let _: Result<(), ResponseError> = stream.try_send(precondition_failed_wire).await;
296 return Status::Reject;
297 }
298 Status::Continue
299 }
300}
301
302/// Implements [`ServerHook`] for [`EtagResponseHook`].
303impl ServerHook for EtagResponseHook {
304 /// Constructs a per-response [`EtagResponseHook`].
305 ///
306 /// # Arguments
307 ///
308 /// - `&mut Stream` - Connection stream.
309 /// - `&mut Context` - Request context.
310 ///
311 /// # Returns
312 ///
313 /// - `Self` - Hook instance.
314 #[inline(always)]
315 async fn new(_: &mut Stream, _: &mut Context) -> Self {
316 Self
317 }
318
319 /// Generates `ETag` headers and converts matching `If-None-Match` responses to `304 Not Modified`.
320 ///
321 /// # Arguments
322 ///
323 /// - `Self` - Hook instance.
324 /// - `&mut Stream` - Connection stream.
325 /// - `&mut Context` - Request context.
326 ///
327 /// # Returns
328 ///
329 /// - `Status` - Always `Status::Continue`.
330 #[inline(always)]
331 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
332 let Some(plugin) = EtagPlugin::get() else {
333 return Status::Continue;
334 };
335 let _: bool = plugin.apply_response(ctx);
336 Status::Continue
337 }
338}