hyperlane-plugin-timeout 23.3.1

A per-route and global request deadline budget plugin for the Hyperlane framework with X-Request-Timeout clamping, Context RequestDeadline propagation, timeout_future async helper, and 504 Gateway Timeout enforcement.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use super::*;

/// Formats [`TimeoutError`] for human-readable diagnostics.
impl Display for TimeoutError {
    /// Writes the timeout error message.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting result.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(ERR_DEADLINE_EXCEEDED)
    }
}

/// Marks [`TimeoutError`] as a standard error type.
impl Error for TimeoutError {}

/// Constructors for [`PrefixTimeout`].
impl PrefixTimeout {
    /// Creates a per-prefix timeout rule.
    ///
    /// # Arguments
    ///
    /// - `P` - Path prefix.
    /// - `u64` - Timeout budget in milliseconds (`0` = disabled).
    ///
    /// # Returns
    ///
    /// - `Self` - Prefix timeout rule.
    pub fn new<P>(prefix: P, timeout_ms: u64) -> Self
    where
        P: Into<String>,
    {
        Self {
            prefix: prefix.into(),
            timeout_ms,
        }
    }
}

/// Runtime deadline queries for [`RequestDeadline`].
impl RequestDeadline {
    /// Creates a [`RequestDeadline`] starting at `now` with `budget_ms` milliseconds.
    ///
    /// # Arguments
    ///
    /// - `Instant` - Start timestamp.
    /// - `u64` - Budget in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed deadline.
    #[inline(always)]
    pub fn from_instant(now: Instant, budget_ms: u64) -> Self {
        let dur: Duration = Duration::from_millis(budget_ms);
        let deadline: Instant = now.checked_add(dur).unwrap_or(now);
        Self {
            started_at: now,
            deadline,
            budget_ms,
        }
    }

    /// Retrieves the active [`RequestDeadline`] from `ctx`, if set.
    ///
    /// # Arguments
    ///
    /// - `&Context` - Active request context.
    ///
    /// # Returns
    ///
    /// - `Option<Self>` - Request deadline metadata.
    #[inline]
    pub fn from_context(ctx: &Context) -> Option<Self> {
        ctx.try_get_attribute::<Self, _>(ATTR_REQUEST_DEADLINE)
    }

    /// Returns the remaining duration before expiry (`Duration::ZERO` once expired).
    ///
    /// # Returns
    ///
    /// - `Duration` - Remaining time budget.
    #[inline(always)]
    pub fn remaining(&self) -> Duration {
        self.get_deadline()
            .saturating_duration_since(Instant::now())
    }

    /// Returns the elapsed duration since the request entered [`TimeoutRequestHook`].
    ///
    /// # Returns
    ///
    /// - `Duration` - Elapsed time.
    #[inline(always)]
    pub fn elapsed(&self) -> Duration {
        self.get_started_at().elapsed()
    }

    /// Reports whether the deadline has expired.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `Instant::now() >= deadline`.
    #[inline(always)]
    pub fn is_expired(&self) -> bool {
        Instant::now() >= self.get_deadline()
    }
}

/// Default construction for [`TimeoutConfig`].
impl Default for TimeoutConfig {
    /// Constructs a [`TimeoutConfig`] with a `30_000` ms default budget and `504` responses.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            default_timeout_ms: DEFAULT_TIMEOUT_MS,
            prefix_timeouts: Vec::new(),
            honor_client_header: true,
            client_header_name: DEFAULT_TIMEOUT_HEADER.to_owned(),
            expose_remaining_header: false,
            timeout_status: HttpStatus::GatewayTimeout,
            timeout_content_type: DEFAULT_TIMEOUT_CONTENT_TYPE.to_owned(),
            timeout_body: DEFAULT_TIMEOUT_BODY.to_vec(),
        }
    }
}

/// Fluent builder helpers for [`TimeoutConfig`].
impl TimeoutConfig {
    /// Sets the global default timeout budget in milliseconds (`0` = disabled).
    ///
    /// # Arguments
    ///
    /// - `u64` - Timeout budget in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_default_timeout_ms(mut self, timeout_ms: u64) -> Self {
        self.set_default_timeout_ms(timeout_ms);
        self
    }

    /// Adds a segment-bounded path prefix timeout override.
    ///
    /// # Arguments
    ///
    /// - `P` - Path prefix.
    /// - `u64` - Timeout budget in milliseconds (`0` = disabled).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_prefix_timeout<P>(mut self, prefix: P, timeout_ms: u64) -> Self
    where
        P: Into<String>,
    {
        self.get_mut_prefix_timeouts()
            .push(PrefixTimeout::new(prefix, timeout_ms));
        self
    }

    /// Enables or disables honoring tighter client `X-Request-Timeout` headers.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether client header clamping is enabled.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_honor_client_header(mut self, enabled: bool) -> Self {
        self.set_honor_client_header(enabled);
        self
    }

    /// Enables or disables emitting `x-timeout-remaining-ms` on non-expired responses.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether to expose remaining budget header.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_expose_remaining_header(mut self, enabled: bool) -> Self {
        self.set_expose_remaining_header(enabled);
        self
    }
}

/// Compiled budget resolution and response enforcement for [`TimeoutPlugin`].
impl TimeoutPlugin {
    /// Compiles a standalone [`TimeoutPlugin`] from `config`.
    ///
    /// # Arguments
    ///
    /// - `TimeoutConfig` - Timeout configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Compiled plugin.
    pub fn new(config: TimeoutConfig) -> Self {
        let mut prefix_rules: Vec<(String, u64)> = config
            .get_prefix_timeouts()
            .iter()
            .map(|r: &PrefixTimeout| (normalize_prefix(r.get_prefix()), r.get_timeout_ms()))
            .collect();
        prefix_rules.sort_by_key(|a: &(String, u64)| Reverse(a.0.len()));
        let client_header_lower: String =
            config.get_client_header_name().trim().to_ascii_lowercase();
        Self {
            config,
            prefix_rules: prefix_rules.into_boxed_slice(),
            client_header_lower,
        }
    }

    /// Initializes the global [`TimeoutPlugin`] singleton once.
    ///
    /// # Arguments
    ///
    /// - `TimeoutConfig` - Timeout configuration.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the global plugin.
    pub fn init(config: TimeoutConfig) -> &'static Self {
        TIMEOUT_PLUGIN.get_or_init(|| Self::new(config))
    }

    /// Returns the initialized global [`TimeoutPlugin`], if configured.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        TIMEOUT_PLUGIN.get()
    }

    /// Returns the retained source configuration.
    ///
    /// # Returns
    ///
    /// - `&TimeoutConfig` - Source configuration.
    pub fn get_config(&self) -> &TimeoutConfig {
        let Self { config, .. } = self;
        config
    }

    /// Resolves the effective timeout budget in milliseconds for `request` (`0` = no timeout).
    ///
    /// # Arguments
    ///
    /// - `&Request` - Incoming HTTP request.
    ///
    /// # Returns
    ///
    /// - `u64` - Effective budget in milliseconds.
    #[inline]
    pub fn resolve_budget_ms(&self, request: &Request) -> u64 {
        let Self {
            config,
            prefix_rules,
            client_header_lower,
            ..
        } = self;
        let mut base_ms: u64 = config.get_default_timeout_ms();
        if !prefix_rules.is_empty() {
            let path: &str = request.get_path();
            for (prefix, ms) in prefix_rules.iter() {
                if path_matches_prefix(path, prefix) {
                    base_ms = *ms;
                    break;
                }
            }
        }
        if base_ms == 0 {
            return 0;
        }
        if config.get_honor_client_header()
            && !client_header_lower.is_empty()
            && let Some(values) = request.get_headers().get(client_header_lower.as_str())
            && let Some(raw) = values.back()
            && let Some(client_ms) = parse_timeout_header_ms(raw)
        {
            return base_ms.min(client_ms);
        }
        base_ms
    }

    /// Applies timeout error status and body onto `response` when a request deadline has expired.
    ///
    /// # Arguments
    ///
    /// - `&mut Response` - Outgoing HTTP response.
    pub fn apply_timeout_response(&self, response: &mut Response) {
        let Self { config, .. } = self;
        response
            .set_status_code(config.get_timeout_status().code())
            .set_header(CONTENT_TYPE, config.get_timeout_content_type())
            .set_body(config.get_timeout_body().clone());
    }
}

/// Implements [`ServerHook`] for [`TimeoutRequestHook`].
impl ServerHook for TimeoutRequestHook {
    /// Constructs a per-request [`TimeoutRequestHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Computes and attaches [`RequestDeadline`] to `ctx`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Continue`.
    #[inline(always)]
    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = TimeoutPlugin::get() else {
            return Status::Continue;
        };
        let budget_ms: u64 = plugin.resolve_budget_ms(ctx.get_request());
        if budget_ms > 0 {
            let deadline: RequestDeadline =
                RequestDeadline::from_instant(Instant::now(), budget_ms);
            ctx.set_attribute(ATTR_REQUEST_DEADLINE, deadline);
        }
        Status::Continue
    }
}

/// Implements [`ServerHook`] for [`TimeoutResponseHook`].
impl ServerHook for TimeoutResponseHook {
    /// Constructs a per-response [`TimeoutResponseHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Checks deadline expiration and optionally attaches remaining-budget headers.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Continue`.
    #[inline(always)]
    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = TimeoutPlugin::get() else {
            return Status::Continue;
        };
        let Some(deadline) = ctx.try_get_attribute_ref::<RequestDeadline, _>(ATTR_REQUEST_DEADLINE)
        else {
            return Status::Continue;
        };
        if deadline.is_expired() {
            plugin.apply_timeout_response(ctx.get_mut_response());
        } else if plugin.get_config().get_expose_remaining_header() {
            let mut rem_ms: u64 = deadline.remaining().as_millis().min(u64::MAX as u128) as u64;
            let mut buf: [u8; 20] = [0u8; 20];
            let mut pos: usize = buf.len();
            if rem_ms == 0 {
                pos -= 1;
                buf[pos] = b'0';
            } else {
                while rem_ms > 0 {
                    pos -= 1;
                    buf[pos] = b'0' + ((rem_ms % 10) as u8);
                    rem_ms /= 10;
                }
            }
            if let Ok(rem_str) = from_utf8(&buf[pos..]) {
                ctx.get_mut_response()
                    .set_header(HEADER_TIMEOUT_REMAINING_MS, rem_str);
            }
        }
        Status::Continue
    }
}