hyperlane_plugin_maintenance/
impl.rs1use super::*;
2
3impl Default for MaintenanceConfig {
5 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
26impl MaintenanceConfig {
28 pub fn with_initial_mode(mut self, mode: MaintenanceMode) -> Self {
38 self.set_initial_mode(mode);
39 self
40 }
41
42 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 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 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 pub fn with_retry_after_secs(mut self, secs: Option<u64>) -> Self {
109 self.set_retry_after_secs(secs);
110 self
111 }
112
113 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
142impl MaintenancePlugin {
144 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 pub fn init(config: MaintenanceConfig) -> &'static Self {
223 MAINTENANCE_PLUGIN.get_or_init(|| Self::new(config))
224 }
225
226 #[inline(always)]
232 pub fn get() -> Option<&'static Self> {
233 MAINTENANCE_PLUGIN.get()
234 }
235
236 pub fn get_config(&self) -> &MaintenanceConfig {
242 let Self { config, .. } = self;
243 config
244 }
245
246 #[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 #[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 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 #[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 #[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 #[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 #[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
402impl ServerHook for MaintenanceHook {
404 #[inline(always)]
415 async fn new(_: &mut Stream, _: &mut Context) -> Self {
416 Self
417 }
418
419 #[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}