Skip to main content

hyperlane_plugin_maintenance/
impl.rs

1use super::*;
2
3/// Default construction for [`MaintenanceConfig`].
4impl Default for MaintenanceConfig {
5    /// Builds an active default [`MaintenanceConfig`] with JSON `503` wire templates.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default configuration.
10    fn default() -> Self {
11        Self {
12            initial_mode: MaintenanceMode::Active,
13            exempt_paths: Vec::new(),
14            exempt_prefixes: Vec::new(),
15            bypass_header: DEFAULT_BYPASS_HEADER.to_owned(),
16            bypass_tokens: Vec::new(),
17            status: HttpStatus::ServiceUnavailable,
18            retry_after_secs: Some(DEFAULT_RETRY_AFTER_SECS),
19            content_type: DEFAULT_MAINTENANCE_CONTENT_TYPE.to_owned(),
20            maintenance_body: DEFAULT_MAINTENANCE_BODY.to_vec(),
21            read_only_body: DEFAULT_READ_ONLY_BODY.to_vec(),
22        }
23    }
24}
25
26/// Fluent builder helpers for [`MaintenanceConfig`].
27impl MaintenanceConfig {
28    /// Sets the initial operating mode.
29    ///
30    /// # Arguments
31    ///
32    /// - `MaintenanceMode` - Initial mode on plugin initialization.
33    ///
34    /// # Returns
35    ///
36    /// - `Self` - Updated configuration.
37    pub fn with_initial_mode(mut self, mode: MaintenanceMode) -> Self {
38        self.set_initial_mode(mode);
39        self
40    }
41
42    /// Sets exact exempt paths that bypass maintenance enforcement.
43    ///
44    /// # Arguments
45    ///
46    /// - `I` - Iterator of exact paths.
47    ///
48    /// # Returns
49    ///
50    /// - `Self` - Updated configuration.
51    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
52    where
53        I: IntoIterator<Item = S>,
54        S: Into<String>,
55    {
56        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
57        self
58    }
59
60    /// Sets segment-bounded path prefixes exempted from maintenance enforcement.
61    ///
62    /// # Arguments
63    ///
64    /// - `I` - Iterator of path prefixes.
65    ///
66    /// # Returns
67    ///
68    /// - `Self` - Updated configuration.
69    pub fn with_exempt_prefixes<I, S>(mut self, prefixes: I) -> Self
70    where
71        I: IntoIterator<Item = S>,
72        S: Into<String>,
73    {
74        self.set_exempt_prefixes(prefixes.into_iter().map(Into::into).collect());
75        self
76    }
77
78    /// Configures the bypass header name and allowed secret tokens.
79    ///
80    /// # Arguments
81    ///
82    /// - `H` - Bypass header name.
83    /// - `I` - Iterator of secret bypass tokens.
84    ///
85    /// # Returns
86    ///
87    /// - `Self` - Updated configuration.
88    pub fn with_bypass_tokens<H, I, S>(mut self, header_name: H, tokens: I) -> Self
89    where
90        H: Into<String>,
91        I: IntoIterator<Item = S>,
92        S: Into<String>,
93    {
94        self.set_bypass_header(header_name.into())
95            .set_bypass_tokens(tokens.into_iter().map(Into::into).collect());
96        self
97    }
98
99    /// Configures the optional `Retry-After` header duration in seconds.
100    ///
101    /// # Arguments
102    ///
103    /// - `Option<u64>` - Seconds until retry, or `None` to omit `Retry-After`.
104    ///
105    /// # Returns
106    ///
107    /// - `Self` - Updated configuration.
108    pub fn with_retry_after_secs(mut self, secs: Option<u64>) -> Self {
109        self.set_retry_after_secs(secs);
110        self
111    }
112
113    /// Configures custom rejection bodies and `Content-Type`.
114    ///
115    /// # Arguments
116    ///
117    /// - `C` - Content-Type header value.
118    /// - `B1` - Full maintenance rejection body.
119    /// - `B2` - Read-only rejection body.
120    ///
121    /// # Returns
122    ///
123    /// - `Self` - Updated configuration.
124    pub fn with_bodies<C, B1, B2>(
125        mut self,
126        content_type: C,
127        maintenance_body: B1,
128        read_only_body: B2,
129    ) -> Self
130    where
131        C: Into<String>,
132        B1: Into<Vec<u8>>,
133        B2: Into<Vec<u8>>,
134    {
135        self.set_content_type(content_type.into())
136            .set_maintenance_body(maintenance_body.into())
137            .set_read_only_body(read_only_body.into());
138        self
139    }
140}
141
142/// Compiled evaluation and runtime switching methods for [`MaintenancePlugin`].
143impl MaintenancePlugin {
144    /// Compiles a standalone [`MaintenancePlugin`] from `config`.
145    ///
146    /// # Arguments
147    ///
148    /// - `MaintenanceConfig` - Maintenance policy.
149    ///
150    /// # Returns
151    ///
152    /// - `Self` - Compiled lock-free maintenance gate.
153    pub fn new(config: MaintenanceConfig) -> Self {
154        let initial: u8 = mode_to_u8(config.get_initial_mode());
155        let bypass_header_lower: String = config.get_bypass_header().trim().to_ascii_lowercase();
156        let bypass_tokens: Box<[Box<[u8]>]> = config
157            .get_bypass_tokens()
158            .iter()
159            .filter(|t: &&String| !t.is_empty())
160            .map(|t: &String| t.as_bytes().to_vec().into_boxed_slice())
161            .collect::<Vec<Box<[u8]>>>()
162            .into_boxed_slice();
163        let mut unique_exempt: Vec<String> = config
164            .get_exempt_paths()
165            .iter()
166            .filter(|p: &&String| !p.is_empty())
167            .cloned()
168            .collect();
169        unique_exempt.sort_unstable();
170        unique_exempt.dedup();
171        let (exempt_small, exempt_set): (Box<[String]>, Option<HashSetXxHash3_64<String>>) =
172            if unique_exempt.len() <= EXEMPT_SET_THRESHOLD {
173                (unique_exempt.into_boxed_slice(), None)
174            } else {
175                let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
176                for path in unique_exempt {
177                    set.insert(path);
178                }
179                (Box::new([]), Some(set))
180            };
181        let exempt_prefixes: Box<[String]> = config
182            .get_exempt_prefixes()
183            .iter()
184            .filter(|p: &&String| !p.trim().is_empty())
185            .map(|p: &String| normalize_prefix(p))
186            .collect::<Vec<String>>()
187            .into_boxed_slice();
188        let maintenance_wire: Vec<u8> = build_reject_wire(
189            config.get_status(),
190            config.get_content_type(),
191            config.try_get_retry_after_secs(),
192            config.get_maintenance_body(),
193        );
194        let read_only_wire: Vec<u8> = build_reject_wire(
195            config.get_status(),
196            config.get_content_type(),
197            config.try_get_retry_after_secs(),
198            config.get_read_only_body(),
199        );
200        Self {
201            config,
202            mode: AtomicU8::new(initial),
203            bypass_header_lower,
204            bypass_tokens,
205            exempt_small,
206            exempt_set,
207            exempt_prefixes,
208            maintenance_wire,
209            read_only_wire,
210        }
211    }
212
213    /// Initializes the global [`MaintenancePlugin`] singleton once.
214    ///
215    /// # Arguments
216    ///
217    /// - `MaintenanceConfig` - Maintenance configuration.
218    ///
219    /// # Returns
220    ///
221    /// - `&'static Self` - Reference to the global plugin.
222    pub fn init(config: MaintenanceConfig) -> &'static Self {
223        MAINTENANCE_PLUGIN.get_or_init(|| Self::new(config))
224    }
225
226    /// Returns the initialized global [`MaintenancePlugin`], if configured.
227    ///
228    /// # Returns
229    ///
230    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
231    #[inline(always)]
232    pub fn get() -> Option<&'static Self> {
233        MAINTENANCE_PLUGIN.get()
234    }
235
236    /// Returns the retained source configuration.
237    ///
238    /// # Returns
239    ///
240    /// - `&MaintenanceConfig` - Source configuration.
241    pub fn get_config(&self) -> &MaintenanceConfig {
242        let Self { config, .. } = self;
243        config
244    }
245
246    /// Reads the current live [`MaintenanceMode`] with lock-free atomic acquire semantics.
247    ///
248    /// # Returns
249    ///
250    /// - `MaintenanceMode` - Active operating mode.
251    #[inline(always)]
252    pub fn current_mode(&self) -> MaintenanceMode {
253        let Self { mode, .. } = self;
254        mode_from_u8(mode.load(Ordering::Acquire))
255    }
256
257    /// Atomically switches the live [`MaintenanceMode`] without restarting the server.
258    ///
259    /// # Arguments
260    ///
261    /// - `MaintenanceMode` - New operating mode.
262    #[inline(always)]
263    pub fn set_mode(&self, next: MaintenanceMode) {
264        let Self { mode, .. } = self;
265        mode.store(mode_to_u8(next), Ordering::Release);
266    }
267
268    /// Convenience helper updating the global singleton mode when initialized.
269    ///
270    /// # Arguments
271    ///
272    /// - `MaintenanceMode` - New operating mode.
273    ///
274    /// # Returns
275    ///
276    /// - `bool` - `true` when the global plugin was initialized and updated.
277    pub fn switch_global_mode(next: MaintenanceMode) -> bool {
278        if let Some(plugin) = Self::get() {
279            plugin.set_mode(next);
280            true
281        } else {
282            false
283        }
284    }
285
286    /// Reports whether `path` matches an exempt exact path or prefix.
287    ///
288    /// # Arguments
289    ///
290    /// - `&str` - Incoming request path.
291    ///
292    /// # Returns
293    ///
294    /// - `bool` - `true` when exempted.
295    #[inline]
296    pub fn is_path_exempt(&self, path: &str) -> bool {
297        let Self {
298            exempt_small,
299            exempt_set,
300            exempt_prefixes,
301            ..
302        } = self;
303        for exact in exempt_small.iter() {
304            if exact.as_str() == path {
305                return true;
306            }
307        }
308        if let Some(set) = exempt_set
309            && set.contains(path)
310        {
311            return true;
312        }
313        exempt_prefixes
314            .iter()
315            .any(|prefix: &String| path_matches_prefix(path, prefix))
316    }
317
318    /// Reports whether `request` presents a valid bypass secret token.
319    ///
320    /// # Arguments
321    ///
322    /// - `&Request` - Incoming HTTP request.
323    ///
324    /// # Returns
325    ///
326    /// - `bool` - `true` when a configured bypass token matches in constant time.
327    #[inline]
328    pub fn has_valid_bypass_token(&self, request: &Request) -> bool {
329        let Self {
330            bypass_header_lower,
331            bypass_tokens,
332            ..
333        } = self;
334        if bypass_tokens.is_empty() || bypass_header_lower.is_empty() {
335            return false;
336        }
337        let Some(values) = request.get_headers().get(bypass_header_lower.as_str()) else {
338            return false;
339        };
340        let Some(candidate) = values.back() else {
341            return false;
342        };
343        let cand_bytes: &[u8] = candidate.trim().as_bytes();
344        let mut matched: bool = false;
345        for secret in bypass_tokens.iter() {
346            matched |= constant_time_eq(cand_bytes, secret);
347        }
348        matched
349    }
350
351    /// Evaluates whether `request` is allowed, bypassed, or rejected.
352    ///
353    /// # Arguments
354    ///
355    /// - `&Request` - Incoming HTTP request.
356    ///
357    /// # Returns
358    ///
359    /// - `MaintenanceDecision` - Admission decision.
360    #[inline]
361    pub fn evaluate(&self, request: &Request) -> MaintenanceDecision {
362        let current: MaintenanceMode = self.current_mode();
363        if current == MaintenanceMode::Active {
364            return MaintenanceDecision::Allow;
365        }
366        if current == MaintenanceMode::ReadOnly && is_read_only_method(request.get_method()) {
367            return MaintenanceDecision::Allow;
368        }
369        if self.is_path_exempt(request.get_path()) || self.has_valid_bypass_token(request) {
370            return MaintenanceDecision::Bypassed;
371        }
372        match current {
373            MaintenanceMode::ReadOnly => MaintenanceDecision::RejectReadOnly,
374            MaintenanceMode::Maintenance => MaintenanceDecision::RejectMaintenance,
375            MaintenanceMode::Active => MaintenanceDecision::Allow,
376        }
377    }
378
379    /// Returns the prebuilt rejection wire bytes for a rejected [`MaintenanceDecision`].
380    ///
381    /// # Arguments
382    ///
383    /// - `MaintenanceDecision` - Rejection decision.
384    ///
385    /// # Returns
386    ///
387    /// - `&[u8]` - Pre-serialized HTTP wire bytes.
388    #[inline]
389    pub fn reject_wire(&self, decision: MaintenanceDecision) -> &[u8] {
390        let Self {
391            maintenance_wire,
392            read_only_wire,
393            ..
394        } = self;
395        match decision {
396            MaintenanceDecision::RejectReadOnly => read_only_wire,
397            _ => maintenance_wire,
398        }
399    }
400}
401
402/// Implements [`ServerHook`] for [`MaintenanceHook`].
403impl ServerHook for MaintenanceHook {
404    /// Constructs a per-request [`MaintenanceHook`].
405    ///
406    /// # Arguments
407    ///
408    /// - `&mut Stream` - Connection stream.
409    /// - `&mut Context` - Request context.
410    ///
411    /// # Returns
412    ///
413    /// - `Self` - Hook instance.
414    #[inline(always)]
415    async fn new(_: &mut Stream, _: &mut Context) -> Self {
416        Self
417    }
418
419    /// Fast-path checks the atomic maintenance mode and short-circuits blocked requests with prebuilt `503` wire bytes.
420    ///
421    /// # Arguments
422    ///
423    /// - `Self` - Hook instance.
424    /// - `&mut Stream` - Connection stream.
425    /// - `&mut Context` - Request context.
426    ///
427    /// # Returns
428    ///
429    /// - `Status` - `Status::Continue` when admitted; `Status::Reject` when blocked.
430    #[inline(always)]
431    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
432        let Some(plugin) = MaintenancePlugin::get() else {
433            return Status::Continue;
434        };
435        let decision: MaintenanceDecision = plugin.evaluate(ctx.get_request());
436        match decision {
437            MaintenanceDecision::Allow | MaintenanceDecision::Bypassed => Status::Continue,
438            MaintenanceDecision::RejectReadOnly | MaintenanceDecision::RejectMaintenance => {
439                let wire: &[u8] = plugin.reject_wire(decision);
440                let _: Result<(), ResponseError> = stream.try_send(wire).await;
441                Status::Reject
442            }
443        }
444    }
445}