Skip to main content

hyperlane_plugin_timeout/
fn.rs

1use super::*;
2
3/// Normalizes a path prefix by ensuring a leading `/` and trimming trailing `/`.
4///
5/// # Arguments
6///
7/// - `&str` - Raw prefix path.
8///
9/// # Returns
10///
11/// - `String` - Normalized prefix.
12pub(crate) fn normalize_prefix(raw: &str) -> String {
13    let trimmed: &str = raw.trim().trim_end_matches('/');
14    if trimmed.is_empty() || trimmed == ROOT_SLASH {
15        return ROOT_SLASH.to_owned();
16    }
17    if trimmed.starts_with('/') {
18        trimmed.to_owned()
19    } else {
20        format!("/{trimmed}")
21    }
22}
23
24/// Reports whether `path` matches a normalized `prefix` on a segment boundary.
25///
26/// # Arguments
27///
28/// - `&str` - Incoming request path.
29/// - `&str` - Normalized path prefix.
30///
31/// # Returns
32///
33/// - `bool` - `true` when matched.
34#[inline]
35pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
36    if prefix == ROOT_SLASH {
37        return true;
38    }
39    if let Some(rest) = path.strip_prefix(prefix) {
40        rest.is_empty() || rest.starts_with('/')
41    } else {
42        false
43    }
44}
45
46/// Parses a client timeout header value (`"5000"`, `"500ms"`, `"5s"`) into milliseconds.
47///
48/// # Arguments
49///
50/// - `&str` - Raw header value.
51///
52/// # Returns
53///
54/// - `Option<u64>` - Parsed positive duration in milliseconds.
55pub fn parse_timeout_header_ms(raw: &str) -> Option<u64> {
56    let trimmed: &str = raw.trim();
57    if trimmed.is_empty() {
58        return None;
59    }
60    let ms: u64 = if let Some(s) = trimmed.strip_suffix("ms") {
61        s.trim().parse::<u64>().ok()?
62    } else if let Some(s) = trimmed.strip_suffix('s') {
63        s.trim().parse::<u64>().ok()?.saturating_mul(1000)
64    } else {
65        trimmed.parse::<u64>().ok()?
66    };
67    if ms == 0 { None } else { Some(ms) }
68}
69
70/// Executes `future` bounded by the [`RequestDeadline`] attached to `ctx`.
71///
72/// If no deadline is attached to `ctx`, `future` runs without an extra timeout wrapper.
73///
74/// # Arguments
75///
76/// - `&Context` - Active Hyperlane request context.
77/// - `F` - Async operation to bound.
78///
79/// # Returns
80///
81/// - `Result<T, TimeoutError>` - Future output or [`TimeoutError::DeadlineExceeded`].
82pub async fn timeout_future<F, T>(ctx: &Context, future: F) -> Result<T, TimeoutError>
83where
84    F: Future<Output = T>,
85{
86    let Some(deadline) = RequestDeadline::from_context(ctx) else {
87        return Ok(future.await);
88    };
89    let remaining: Duration = deadline.remaining();
90    if remaining.is_zero() {
91        return Err(TimeoutError::DeadlineExceeded);
92    }
93    timeout(remaining, future)
94        .await
95        .map_err(|_| TimeoutError::DeadlineExceeded)
96}