Skip to main content

hyperlane_plugin_timeout/
impl.rs

1use super::*;
2
3/// Formats [`TimeoutError`] for human-readable diagnostics.
4impl Display for TimeoutError {
5    /// Writes the timeout error message.
6    ///
7    /// # Arguments
8    ///
9    /// - `&mut Formatter<'_>` - Output formatter.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - Formatting result.
14    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15        f.write_str(ERR_DEADLINE_EXCEEDED)
16    }
17}
18
19/// Marks [`TimeoutError`] as a standard error type.
20impl Error for TimeoutError {}
21
22/// Constructors for [`PrefixTimeout`].
23impl PrefixTimeout {
24    /// Creates a per-prefix timeout rule.
25    ///
26    /// # Arguments
27    ///
28    /// - `P` - Path prefix.
29    /// - `u64` - Timeout budget in milliseconds (`0` = disabled).
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Prefix timeout rule.
34    pub fn new<P>(prefix: P, timeout_ms: u64) -> Self
35    where
36        P: Into<String>,
37    {
38        Self {
39            prefix: prefix.into(),
40            timeout_ms,
41        }
42    }
43}
44
45/// Runtime deadline queries for [`RequestDeadline`].
46impl RequestDeadline {
47    /// Creates a [`RequestDeadline`] starting at `now` with `budget_ms` milliseconds.
48    ///
49    /// # Arguments
50    ///
51    /// - `Instant` - Start timestamp.
52    /// - `u64` - Budget in milliseconds.
53    ///
54    /// # Returns
55    ///
56    /// - `Self` - Constructed deadline.
57    #[inline(always)]
58    pub fn from_instant(now: Instant, budget_ms: u64) -> Self {
59        let dur: Duration = Duration::from_millis(budget_ms);
60        let deadline: Instant = now.checked_add(dur).unwrap_or(now);
61        Self {
62            started_at: now,
63            deadline,
64            budget_ms,
65        }
66    }
67
68    /// Retrieves the active [`RequestDeadline`] from `ctx`, if set.
69    ///
70    /// # Arguments
71    ///
72    /// - `&Context` - Active request context.
73    ///
74    /// # Returns
75    ///
76    /// - `Option<Self>` - Request deadline metadata.
77    #[inline]
78    pub fn from_context(ctx: &Context) -> Option<Self> {
79        ctx.try_get_attribute::<Self, _>(ATTR_REQUEST_DEADLINE)
80    }
81
82    /// Returns the remaining duration before expiry (`Duration::ZERO` once expired).
83    ///
84    /// # Returns
85    ///
86    /// - `Duration` - Remaining time budget.
87    #[inline(always)]
88    pub fn remaining(&self) -> Duration {
89        self.get_deadline()
90            .saturating_duration_since(Instant::now())
91    }
92
93    /// Returns the elapsed duration since the request entered [`TimeoutRequestHook`].
94    ///
95    /// # Returns
96    ///
97    /// - `Duration` - Elapsed time.
98    #[inline(always)]
99    pub fn elapsed(&self) -> Duration {
100        self.get_started_at().elapsed()
101    }
102
103    /// Reports whether the deadline has expired.
104    ///
105    /// # Returns
106    ///
107    /// - `bool` - `true` when `Instant::now() >= deadline`.
108    #[inline(always)]
109    pub fn is_expired(&self) -> bool {
110        Instant::now() >= self.get_deadline()
111    }
112}
113
114/// Default construction for [`TimeoutConfig`].
115impl Default for TimeoutConfig {
116    /// Constructs a [`TimeoutConfig`] with a `30_000` ms default budget and `504` responses.
117    ///
118    /// # Returns
119    ///
120    /// - `Self` - Default configuration.
121    fn default() -> Self {
122        Self {
123            default_timeout_ms: DEFAULT_TIMEOUT_MS,
124            prefix_timeouts: Vec::new(),
125            honor_client_header: true,
126            client_header_name: DEFAULT_TIMEOUT_HEADER.to_owned(),
127            expose_remaining_header: false,
128            timeout_status: HttpStatus::GatewayTimeout,
129            timeout_content_type: DEFAULT_TIMEOUT_CONTENT_TYPE.to_owned(),
130            timeout_body: DEFAULT_TIMEOUT_BODY.to_vec(),
131        }
132    }
133}
134
135/// Fluent builder helpers for [`TimeoutConfig`].
136impl TimeoutConfig {
137    /// Sets the global default timeout budget in milliseconds (`0` = disabled).
138    ///
139    /// # Arguments
140    ///
141    /// - `u64` - Timeout budget in milliseconds.
142    ///
143    /// # Returns
144    ///
145    /// - `Self` - Updated configuration.
146    pub fn with_default_timeout_ms(mut self, timeout_ms: u64) -> Self {
147        self.set_default_timeout_ms(timeout_ms);
148        self
149    }
150
151    /// Adds a segment-bounded path prefix timeout override.
152    ///
153    /// # Arguments
154    ///
155    /// - `P` - Path prefix.
156    /// - `u64` - Timeout budget in milliseconds (`0` = disabled).
157    ///
158    /// # Returns
159    ///
160    /// - `Self` - Updated configuration.
161    pub fn with_prefix_timeout<P>(mut self, prefix: P, timeout_ms: u64) -> Self
162    where
163        P: Into<String>,
164    {
165        self.get_mut_prefix_timeouts()
166            .push(PrefixTimeout::new(prefix, timeout_ms));
167        self
168    }
169
170    /// Enables or disables honoring tighter client `X-Request-Timeout` headers.
171    ///
172    /// # Arguments
173    ///
174    /// - `bool` - Whether client header clamping is enabled.
175    ///
176    /// # Returns
177    ///
178    /// - `Self` - Updated configuration.
179    pub fn with_honor_client_header(mut self, enabled: bool) -> Self {
180        self.set_honor_client_header(enabled);
181        self
182    }
183
184    /// Enables or disables emitting `x-timeout-remaining-ms` on non-expired responses.
185    ///
186    /// # Arguments
187    ///
188    /// - `bool` - Whether to expose remaining budget header.
189    ///
190    /// # Returns
191    ///
192    /// - `Self` - Updated configuration.
193    pub fn with_expose_remaining_header(mut self, enabled: bool) -> Self {
194        self.set_expose_remaining_header(enabled);
195        self
196    }
197}
198
199/// Compiled budget resolution and response enforcement for [`TimeoutPlugin`].
200impl TimeoutPlugin {
201    /// Compiles a standalone [`TimeoutPlugin`] from `config`.
202    ///
203    /// # Arguments
204    ///
205    /// - `TimeoutConfig` - Timeout configuration.
206    ///
207    /// # Returns
208    ///
209    /// - `Self` - Compiled plugin.
210    pub fn new(config: TimeoutConfig) -> Self {
211        let mut prefix_rules: Vec<(String, u64)> = config
212            .get_prefix_timeouts()
213            .iter()
214            .map(|r: &PrefixTimeout| (normalize_prefix(r.get_prefix()), r.get_timeout_ms()))
215            .collect();
216        prefix_rules.sort_by_key(|a: &(String, u64)| Reverse(a.0.len()));
217        let client_header_lower: String =
218            config.get_client_header_name().trim().to_ascii_lowercase();
219        Self {
220            config,
221            prefix_rules: prefix_rules.into_boxed_slice(),
222            client_header_lower,
223        }
224    }
225
226    /// Initializes the global [`TimeoutPlugin`] singleton once.
227    ///
228    /// # Arguments
229    ///
230    /// - `TimeoutConfig` - Timeout configuration.
231    ///
232    /// # Returns
233    ///
234    /// - `&'static Self` - Reference to the global plugin.
235    pub fn init(config: TimeoutConfig) -> &'static Self {
236        TIMEOUT_PLUGIN.get_or_init(|| Self::new(config))
237    }
238
239    /// Returns the initialized global [`TimeoutPlugin`], if configured.
240    ///
241    /// # Returns
242    ///
243    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
244    #[inline(always)]
245    pub fn get() -> Option<&'static Self> {
246        TIMEOUT_PLUGIN.get()
247    }
248
249    /// Returns the retained source configuration.
250    ///
251    /// # Returns
252    ///
253    /// - `&TimeoutConfig` - Source configuration.
254    pub fn get_config(&self) -> &TimeoutConfig {
255        let Self { config, .. } = self;
256        config
257    }
258
259    /// Resolves the effective timeout budget in milliseconds for `request` (`0` = no timeout).
260    ///
261    /// # Arguments
262    ///
263    /// - `&Request` - Incoming HTTP request.
264    ///
265    /// # Returns
266    ///
267    /// - `u64` - Effective budget in milliseconds.
268    #[inline]
269    pub fn resolve_budget_ms(&self, request: &Request) -> u64 {
270        let Self {
271            config,
272            prefix_rules,
273            client_header_lower,
274            ..
275        } = self;
276        let mut base_ms: u64 = config.get_default_timeout_ms();
277        if !prefix_rules.is_empty() {
278            let path: &str = request.get_path();
279            for (prefix, ms) in prefix_rules.iter() {
280                if path_matches_prefix(path, prefix) {
281                    base_ms = *ms;
282                    break;
283                }
284            }
285        }
286        if base_ms == 0 {
287            return 0;
288        }
289        if config.get_honor_client_header()
290            && !client_header_lower.is_empty()
291            && let Some(values) = request.get_headers().get(client_header_lower.as_str())
292            && let Some(raw) = values.back()
293            && let Some(client_ms) = parse_timeout_header_ms(raw)
294        {
295            return base_ms.min(client_ms);
296        }
297        base_ms
298    }
299
300    /// Applies timeout error status and body onto `response` when a request deadline has expired.
301    ///
302    /// # Arguments
303    ///
304    /// - `&mut Response` - Outgoing HTTP response.
305    pub fn apply_timeout_response(&self, response: &mut Response) {
306        let Self { config, .. } = self;
307        response
308            .set_status_code(config.get_timeout_status().code())
309            .set_header(CONTENT_TYPE, config.get_timeout_content_type())
310            .set_body(config.get_timeout_body().clone());
311    }
312}
313
314/// Implements [`ServerHook`] for [`TimeoutRequestHook`].
315impl ServerHook for TimeoutRequestHook {
316    /// Constructs a per-request [`TimeoutRequestHook`].
317    ///
318    /// # Arguments
319    ///
320    /// - `&mut Stream` - Connection stream.
321    /// - `&mut Context` - Request context.
322    ///
323    /// # Returns
324    ///
325    /// - `Self` - Hook instance.
326    #[inline(always)]
327    async fn new(_: &mut Stream, _: &mut Context) -> Self {
328        Self
329    }
330
331    /// Computes and attaches [`RequestDeadline`] to `ctx`.
332    ///
333    /// # Arguments
334    ///
335    /// - `Self` - Hook instance.
336    /// - `&mut Stream` - Connection stream.
337    /// - `&mut Context` - Request context.
338    ///
339    /// # Returns
340    ///
341    /// - `Status` - Always `Status::Continue`.
342    #[inline(always)]
343    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
344        let Some(plugin) = TimeoutPlugin::get() else {
345            return Status::Continue;
346        };
347        let budget_ms: u64 = plugin.resolve_budget_ms(ctx.get_request());
348        if budget_ms > 0 {
349            let deadline: RequestDeadline =
350                RequestDeadline::from_instant(Instant::now(), budget_ms);
351            ctx.set_attribute(ATTR_REQUEST_DEADLINE, deadline);
352        }
353        Status::Continue
354    }
355}
356
357/// Implements [`ServerHook`] for [`TimeoutResponseHook`].
358impl ServerHook for TimeoutResponseHook {
359    /// Constructs a per-response [`TimeoutResponseHook`].
360    ///
361    /// # Arguments
362    ///
363    /// - `&mut Stream` - Connection stream.
364    /// - `&mut Context` - Request context.
365    ///
366    /// # Returns
367    ///
368    /// - `Self` - Hook instance.
369    #[inline(always)]
370    async fn new(_: &mut Stream, _: &mut Context) -> Self {
371        Self
372    }
373
374    /// Checks deadline expiration and optionally attaches remaining-budget headers.
375    ///
376    /// # Arguments
377    ///
378    /// - `Self` - Hook instance.
379    /// - `&mut Stream` - Connection stream.
380    /// - `&mut Context` - Request context.
381    ///
382    /// # Returns
383    ///
384    /// - `Status` - Always `Status::Continue`.
385    #[inline(always)]
386    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
387        let Some(plugin) = TimeoutPlugin::get() else {
388            return Status::Continue;
389        };
390        let Some(deadline) = ctx.try_get_attribute_ref::<RequestDeadline, _>(ATTR_REQUEST_DEADLINE)
391        else {
392            return Status::Continue;
393        };
394        if deadline.is_expired() {
395            plugin.apply_timeout_response(ctx.get_mut_response());
396        } else if plugin.get_config().get_expose_remaining_header() {
397            let mut rem_ms: u64 = deadline.remaining().as_millis().min(u64::MAX as u128) as u64;
398            let mut buf: [u8; 20] = [0u8; 20];
399            let mut pos: usize = buf.len();
400            if rem_ms == 0 {
401                pos -= 1;
402                buf[pos] = b'0';
403            } else {
404                while rem_ms > 0 {
405                    pos -= 1;
406                    buf[pos] = b'0' + ((rem_ms % 10) as u8);
407                    rem_ms /= 10;
408                }
409            }
410            if let Ok(rem_str) = from_utf8(&buf[pos..]) {
411                ctx.get_mut_response()
412                    .set_header(HEADER_TIMEOUT_REMAINING_MS, rem_str);
413            }
414        }
415        Status::Continue
416    }
417}