footing 0.6.3

Feature-gated foundations for Rust backend services
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! Validated CORS and route-aware HTTP request policies.

use std::{num::NonZeroUsize, sync::Arc, time::Duration};

use serde::{Deserialize, Serialize};

use crate::http::{
    IdempotencyConfig, IdempotencyRequestPolicy, RateLimitConfig, RateLimitKeySource,
    RateLimitRequestPolicy, SecurityHeadersConfig,
};
use axum::{
    extract::MatchedPath,
    http::{HeaderName, HeaderValue, Method, Request},
};

use super::error::HttpMiddlewareError;
use crate::http::trusted_proxy::ForwardedHeadersPolicy;

/// Default HTTP timeout.
pub const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
/// Default HTTP request body limit.
pub const DEFAULT_HTTP_REQUEST_BODY_LIMIT: usize = 2 * 1024 * 1024;
/// Default HSTS maximum age.
pub const DEFAULT_HSTS_MAX_AGE: Duration = Duration::from_secs(31_536_000);

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling CORS.
pub enum CorsPolicy {
    /// The capability is disabled.
    Disabled,
    /// Any origin is accepted; the remaining CORS rules come from the configuration.
    AnyOrigin(CorsConfig),
    /// Only the configured origins are accepted.
    Restricted(CorsConfig),
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Validated CORS rules, independent of the origin matching mode.
pub struct CorsConfig {
    pub(super) allowed_origins: Vec<HeaderValue>,
    pub(super) allowed_methods: Vec<Method>,
    pub(super) allowed_headers: Vec<HeaderName>,
    pub(super) exposed_headers: Vec<HeaderName>,
    pub(super) allow_credentials: bool,
    pub(super) max_age: Option<Duration>,
}

impl CorsConfig {
    #[must_use]
    /// Returns the explicit origins for [`CorsPolicy::Restricted`].
    /// Empty for [`CorsPolicy::AnyOrigin`]; consult the enclosing policy for the mode.
    pub fn allowed_origins(&self) -> &[HeaderValue] {
        &self.allowed_origins
    }

    #[must_use]
    /// Returns the allowed methods.
    pub fn allowed_methods(&self) -> &[Method] {
        &self.allowed_methods
    }

    #[must_use]
    /// Returns the allowed headers.
    pub fn allowed_headers(&self) -> &[HeaderName] {
        &self.allowed_headers
    }

    #[must_use]
    /// Returns the exposed headers.
    pub fn exposed_headers(&self) -> &[HeaderName] {
        &self.exposed_headers
    }

    #[must_use]
    /// Returns the credentials allowed.
    pub const fn credentials_allowed(&self) -> bool {
        self.allow_credentials
    }

    #[must_use]
    /// Returns the maximum age value.
    pub const fn max_age_value(&self) -> Option<Duration> {
        self.max_age
    }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
/// Immutable HTTP policy produced by [`crate::http::HttpMiddlewareSettings::build`].
///
/// Runtime stores and telemetry are injected separately through
/// [`crate::http::HttpMiddlewareStackBuilder`].
pub struct HttpMiddlewareConfig {
    pub(super) request_context: bool,
    pub(super) forwarded_headers: ForwardedHeadersPolicy,
    pub(super) trace: bool,
    pub(super) cors: CorsPolicy,
    pub(super) security_headers: Option<SecurityHeadersConfig>,
    pub(super) max_concurrent_requests: Option<NonZeroUsize>,
    pub(super) compression: bool,
    pub(super) rate_limit: Option<HttpRateLimitConfig>,
    pub(super) idempotency: Option<IdempotencyConfig>,
    pub(super) request_policy: HttpRequestPolicy,
}

#[derive(Debug, Clone)]
#[non_exhaustive]
/// Validated HTTP rate-limit policy.
pub struct HttpRateLimitConfig {
    pub(super) limiter_config: RateLimitConfig,
    pub(super) key_source: RateLimitKeySource,
}

impl HttpRateLimitConfig {
    #[must_use]
    /// Creates a policy from validated token-bucket configuration and a key source.
    pub const fn new(limiter_config: RateLimitConfig, key_source: RateLimitKeySource) -> Self {
        Self {
            limiter_config,
            key_source,
        }
    }

    #[must_use]
    /// Returns the token-bucket configuration.
    pub const fn limiter_config(&self) -> RateLimitConfig {
        self.limiter_config
    }

    #[must_use]
    /// Returns the request key source.
    pub const fn key_source(&self) -> &RateLimitKeySource {
        &self.key_source
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling request body limit.
pub enum RequestBodyLimitPolicy {
    /// The capability is disabled.
    Disabled,
    /// Enforces a non-zero byte limit.
    Bytes(NonZeroUsize),
}

impl RequestBodyLimitPolicy {
    /// Creates a non-zero byte limit.
    pub fn bytes(value: usize) -> Result<Self, HttpMiddlewareError> {
        NonZeroUsize::new(value)
            .map(Self::Bytes)
            .ok_or(HttpMiddlewareError::InvalidRequestBodyLimit)
    }

    /// Creates a policy from an optional byte limit.
    pub fn from_optional(value: Option<usize>) -> Result<Self, HttpMiddlewareError> {
        match value {
            Some(value) => Self::bytes(value),
            None => Ok(Self::Disabled),
        }
    }

    #[must_use]
    /// Returns this value as optional.
    pub const fn as_optional(self) -> Option<usize> {
        match self {
            Self::Disabled => None,
            Self::Bytes(value) => Some(value.get()),
        }
    }
}

/// Deadline for producing an HTTP response, excluding its streaming body.
///
/// Settings validate that enabled durations are nonzero and fit the clock range.
/// Serialized as `{"mode":"after","duration":"30s"}` or `{"mode":"disabled"}`.
/// A route rule without a timeout override inherits the request policy's default.
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    rename_all = "snake_case",
    tag = "mode",
    content = "duration",
    deny_unknown_fields
)]
#[non_exhaustive]
pub enum ResponseTimeout {
    /// No response deadline.
    Disabled,
    /// Cancel request processing after this duration and return a `503` problem
    /// with code `response_timeout`. This bounds service execution, not receipt
    /// of a complete HTTP request (`408`) or an upstream gateway wait (`504`).
    /// It does not bound streaming response bodies or promise that cancelled
    /// application work has rolled back. No `Retry-After` is guessed.
    After(#[serde(with = "crate::settings::human_duration")] Duration),
}

impl ResponseTimeout {
    /// Returns the configured duration, or `None` when disabled.
    #[must_use]
    pub const fn duration(self) -> Option<Duration> {
        match self {
            Self::Disabled => None,
            Self::After(duration) => Some(duration),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Default request policies with ordered route overrides.
///
/// The last matching rule is selected as a whole. Fields omitted by that rule
/// inherit the global defaults, never fields from earlier matching rules.
/// This keeps each route's timeout and idempotency policy independently valid.
///
/// Matchers use Axum's `MatchedPath` when available (for example `/jobs/{id}`),
/// otherwise the request URI path. Method filters are exact: `GET` does not
/// implicitly include `HEAD`. Register policies for the final mounted paths.
///
/// ```
/// use std::time::Duration;
/// use footing::http::{
///     HttpIdempotencySettings, HttpMiddlewareSettings, HttpRequestPolicy,
///     HttpRequestPolicySettings, HttpRouteRule, IdempotencyRequestPolicy,
///     ResponseTimeout,
/// };
///
/// let policy = HttpRequestPolicy::default()
///     .with_default_timeout(ResponseTimeout::After(Duration::from_secs(5)))
///     .with_rule(HttpRouteRule::prefix("/exports")?
///         .idempotency(IdempotencyRequestPolicy::Disabled)
///         .timeout(ResponseTimeout::After(Duration::from_secs(90))))
///     .with_rule(HttpRouteRule::exact("/notifications/poll")?
///         .idempotency(IdempotencyRequestPolicy::Disabled)
///         .timeout(ResponseTimeout::Disabled));
/// let config = HttpMiddlewareSettings::new()
///     .with_request_policy(HttpRequestPolicySettings::from(policy))
///     .with_idempotency(HttpIdempotencySettings::default()
///         .with_enabled(true)
///         .with_processing_ttl(Duration::from_secs(30)))
///     .build()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Settings validate every policy, including rules shadowed by later ones.
/// When the idempotency store is enabled, a policy permitting idempotency must
/// have a finite response timeout strictly shorter than its processing lease.
/// Explicitly disable idempotency on routes needing a longer or absent deadline.
/// Response timeouts release the request future; they do not roll back external
/// effects or stop detached tasks. Streaming response bodies are outside this budget.
pub struct HttpRequestPolicy {
    default_rate_limit: RateLimitRequestPolicy,
    default_idempotency: IdempotencyRequestPolicy,
    default_request_body_limit: RequestBodyLimitPolicy,
    default_timeout: ResponseTimeout,
    rules: Arc<Vec<HttpRouteRule>>,
}

#[derive(Clone)]
struct ResolvedRequestPolicy {
    source: HttpRequestPolicy,
    method: Method,
    path: String,
    effective: EffectiveHttpRequestPolicy,
}

impl Default for HttpRequestPolicy {
    fn default() -> Self {
        Self {
            default_rate_limit: RateLimitRequestPolicy::Enabled,
            default_idempotency: IdempotencyRequestPolicy::HeaderOptional,
            default_request_body_limit: RequestBodyLimitPolicy::Bytes(
                const {
                    NonZeroUsize::new(DEFAULT_HTTP_REQUEST_BODY_LIMIT)
                        .expect("default body limit is nonzero")
                },
            ),
            default_timeout: ResponseTimeout::After(DEFAULT_HTTP_TIMEOUT),
            rules: Arc::default(),
        }
    }
}

impl HttpRequestPolicy {
    #[must_use]
    /// Creates disabled.
    pub fn disabled() -> Self {
        Self {
            default_rate_limit: RateLimitRequestPolicy::Disabled,
            default_idempotency: IdempotencyRequestPolicy::Disabled,
            default_request_body_limit: RequestBodyLimitPolicy::Disabled,
            default_timeout: ResponseTimeout::Disabled,
            rules: Arc::default(),
        }
    }

    #[must_use]
    /// Configures default rate limit and returns the updated value.
    pub const fn with_default_rate_limit(mut self, policy: RateLimitRequestPolicy) -> Self {
        self.default_rate_limit = policy;
        self
    }

    #[must_use]
    /// Configures default idempotency and returns the updated value.
    pub const fn with_default_idempotency(mut self, policy: IdempotencyRequestPolicy) -> Self {
        self.default_idempotency = policy;
        self
    }

    #[must_use]
    /// Configures default request body limit and returns the updated value.
    pub const fn with_default_request_body_limit(mut self, policy: RequestBodyLimitPolicy) -> Self {
        self.default_request_body_limit = policy;
        self
    }

    /// Sets the response deadline used before route overrides are applied.
    #[must_use]
    pub const fn with_default_timeout(mut self, timeout: ResponseTimeout) -> Self {
        self.default_timeout = timeout;
        self
    }

    #[must_use]
    /// Configures rule and returns the updated value.
    pub fn with_rule(mut self, rule: HttpRouteRule) -> Self {
        Arc::make_mut(&mut self.rules).push(rule);
        self
    }

    #[must_use]
    /// Configures rules and returns the updated value.
    pub fn with_rules(mut self, rules: impl IntoIterator<Item = HttpRouteRule>) -> Self {
        Arc::make_mut(&mut self.rules).extend(rules);
        self
    }

    #[must_use]
    /// Returns the rules.
    pub fn rules(&self) -> &[HttpRouteRule] {
        &self.rules
    }

    #[must_use]
    /// Returns the default rate limit.
    pub const fn default_rate_limit(&self) -> RateLimitRequestPolicy {
        self.default_rate_limit
    }

    #[must_use]
    /// Returns the default idempotency.
    pub const fn default_idempotency(&self) -> IdempotencyRequestPolicy {
        self.default_idempotency
    }

    #[must_use]
    /// Returns the default request body limit.
    pub const fn default_request_body_limit(&self) -> RequestBodyLimitPolicy {
        self.default_request_body_limit
    }

    /// Returns the response deadline used before route overrides are applied.
    #[must_use]
    pub const fn default_timeout(&self) -> ResponseTimeout {
        self.default_timeout
    }

    #[must_use]
    /// Returns the policy for.
    pub fn policy_for<B>(&self, request: &Request<B>) -> EffectiveHttpRequestPolicy {
        self.policy_for_route(request.method(), request_path(request))
    }

    // Layers sharing a policy resolve its rules only once per request. Check
    // the source and route so independently composed layers cannot reuse a
    // result from another policy or an earlier request rewrite.
    pub(crate) fn resolve<B>(&self, request: &mut Request<B>) -> EffectiveHttpRequestPolicy {
        if let Some(cached) = request.extensions().get::<ResolvedRequestPolicy>()
            && Arc::ptr_eq(&self.rules, &cached.source.rules)
            && self.default_rate_limit == cached.source.default_rate_limit
            && self.default_idempotency == cached.source.default_idempotency
            && self.default_request_body_limit == cached.source.default_request_body_limit
            && self.default_timeout == cached.source.default_timeout
            && request.method() == cached.method
            && request_path(request) == cached.path
        {
            return cached.effective;
        }
        let effective = self.policy_for(request);
        let cached = ResolvedRequestPolicy {
            source: self.clone(),
            method: request.method().clone(),
            path: request_path(request).to_owned(),
            effective,
        };
        request.extensions_mut().insert(cached);
        effective
    }

    #[must_use]
    /// Resolves effective policy for a registered method and matched route path.
    pub fn policy_for_route(&self, method: &Method, path: &str) -> EffectiveHttpRequestPolicy {
        self.policy_with_rule(
            self.rules
                .iter()
                .rev()
                .find(|rule| rule.matches_route(method, path)),
        )
    }

    pub(super) fn policy_with_rule(
        &self,
        rule: Option<&HttpRouteRule>,
    ) -> EffectiveHttpRequestPolicy {
        let mut policy = EffectiveHttpRequestPolicy {
            rate_limit: self.default_rate_limit,
            idempotency: self.default_idempotency,
            request_body_limit: self.default_request_body_limit,
            timeout: self.default_timeout,
        };

        if let Some(rule) = rule {
            if let Some(rate_limit) = rule.rate_limit {
                policy.rate_limit = rate_limit;
            }
            if let Some(idempotency) = rule.idempotency {
                policy.idempotency = idempotency;
            }
            if let Some(request_body_limit) = rule.request_body_limit {
                policy.request_body_limit = request_body_limit;
            }
            if let Some(timeout) = rule.timeout {
                policy.timeout = timeout;
            }
        }

        policy
    }

    #[must_use]
    /// Returns whether any request body size limit is enabled.
    pub fn has_request_body_limits(&self) -> bool {
        !matches!(
            self.default_request_body_limit,
            RequestBodyLimitPolicy::Disabled
        ) || self.rules.iter().any(|rule| {
            matches!(
                rule.request_body_limit,
                Some(RequestBodyLimitPolicy::Bytes(_))
            )
        })
    }

    pub(super) fn has_timeouts(&self) -> bool {
        self.default_timeout.duration().is_some()
            || self.rules.iter().any(|rule| {
                rule.timeout
                    .is_some_and(|timeout| timeout.duration().is_some())
            })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Represents HTTP route rule.
pub struct HttpRouteRule {
    pub(super) matcher: RouteMatcher,
    pub(super) methods: Vec<Method>,
    pub(super) rate_limit: Option<RateLimitRequestPolicy>,
    pub(super) idempotency: Option<IdempotencyRequestPolicy>,
    pub(super) request_body_limit: Option<RequestBodyLimitPolicy>,
    pub(super) timeout: Option<ResponseTimeout>,
}

impl HttpRouteRule {
    #[must_use]
    /// Creates any.
    pub fn any() -> Self {
        Self::new(RouteMatcher::any())
    }

    /// Creates exact.
    pub fn exact(path: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
        RouteMatcher::exact(path).map(Self::new)
    }

    /// Creates prefix.
    pub fn prefix(prefix: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
        RouteMatcher::prefix(prefix).map(Self::new)
    }

    /// Creates raw prefix.
    pub fn raw_prefix(prefix: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
        RouteMatcher::raw_prefix(prefix).map(Self::new)
    }

    #[must_use]
    /// Creates a new instance.
    pub fn new(matcher: RouteMatcher) -> Self {
        Self {
            matcher,
            methods: Vec::new(),
            rate_limit: None,
            idempotency: None,
            request_body_limit: None,
            timeout: None,
        }
    }

    #[must_use]
    /// Returns the methods.
    pub fn methods(mut self, methods: impl IntoIterator<Item = Method>) -> Self {
        self.methods = methods.into_iter().collect();
        self
    }

    #[must_use]
    /// Returns the rate limit.
    pub const fn rate_limit(mut self, policy: RateLimitRequestPolicy) -> Self {
        self.rate_limit = Some(policy);
        self
    }

    #[must_use]
    /// Returns the idempotency.
    pub const fn idempotency(mut self, policy: IdempotencyRequestPolicy) -> Self {
        self.idempotency = Some(policy);
        self
    }

    #[must_use]
    /// Returns the request body limit.
    pub const fn request_body_limit(mut self, policy: RequestBodyLimitPolicy) -> Self {
        self.request_body_limit = Some(policy);
        self
    }

    /// Overrides the response deadline for matching requests.
    ///
    /// The last matching rule wins; omitted fields inherit global defaults. Use
    /// [`ResponseTimeout::Disabled`] for routes that must have no response deadline.
    #[must_use]
    pub const fn timeout(mut self, timeout: ResponseTimeout) -> Self {
        self.timeout = Some(timeout);
        self
    }

    #[must_use]
    /// Returns the matcher.
    pub const fn matcher(&self) -> &RouteMatcher {
        &self.matcher
    }

    #[must_use]
    /// Returns the methods slice.
    pub fn methods_slice(&self) -> &[Method] {
        &self.methods
    }

    fn matches_route(&self, method: &Method, path: &str) -> bool {
        (self.methods.is_empty() || self.methods.iter().any(|expected| expected == method))
            && self.matcher.matches(path)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Validated route matcher.
pub struct RouteMatcher(pub(super) RouteMatcherKind);

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum RouteMatcherKind {
    Any,
    Exact(String),
    Prefix(String),
    RawPrefix(String),
}

impl RouteMatcher {
    #[must_use]
    /// Matches every route.
    pub const fn any() -> Self {
        Self(RouteMatcherKind::Any)
    }

    /// Matches one exact absolute ASCII path, including route templates.
    /// Whitespace, controls, queries, fragments and backslashes are rejected.
    pub fn exact(path: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
        Self::path(RouteMatcherKind::Exact, path)
    }

    /// Matches an absolute path on segment boundaries.
    pub fn prefix(path: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
        Self::path(RouteMatcherKind::Prefix, path)
    }

    /// Matches an absolute path using raw string-prefix semantics.
    pub fn raw_prefix(path: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
        Self::path(RouteMatcherKind::RawPrefix, path)
    }

    fn path(
        constructor: impl FnOnce(String) -> RouteMatcherKind,
        path: impl Into<String>,
    ) -> Result<Self, HttpMiddlewareError> {
        let path = path.into();
        if !crate::http::is_valid_route_path(&path) {
            return Err(HttpMiddlewareError::InvalidRouteMatcher);
        }
        Ok(Self(constructor(path)))
    }

    #[must_use]
    /// Returns whether this value matches the value.
    pub fn matches(&self, path: &str) -> bool {
        match &self.0 {
            RouteMatcherKind::Any => true,
            RouteMatcherKind::Exact(expected) => path == expected,
            RouteMatcherKind::Prefix(prefix) => path_matches_segment_prefix(path, prefix),
            RouteMatcherKind::RawPrefix(prefix) => path.starts_with(prefix),
        }
    }
}

fn path_matches_segment_prefix(path: &str, prefix: &str) -> bool {
    if path == prefix {
        return true;
    }
    let Some(rest) = path.strip_prefix(prefix) else {
        return false;
    };
    prefix.ends_with('/') || rest.starts_with('/')
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling effective HTTP request.
pub struct EffectiveHttpRequestPolicy {
    rate_limit: RateLimitRequestPolicy,
    idempotency: IdempotencyRequestPolicy,
    request_body_limit: RequestBodyLimitPolicy,
    timeout: ResponseTimeout,
}

impl EffectiveHttpRequestPolicy {
    /// Returns the response deadline selected by the matching route policy.
    #[must_use]
    pub const fn timeout(self) -> ResponseTimeout {
        self.timeout
    }

    #[must_use]
    /// Returns the rate limit.
    pub const fn rate_limit(self) -> RateLimitRequestPolicy {
        self.rate_limit
    }

    #[must_use]
    /// Returns the idempotency.
    pub const fn idempotency(self) -> IdempotencyRequestPolicy {
        self.idempotency
    }

    #[must_use]
    /// Returns the request body limit.
    pub const fn request_body_limit(self) -> RequestBodyLimitPolicy {
        self.request_body_limit
    }
}

fn request_path<B>(request: &Request<B>) -> &str {
    request
        .extensions()
        .get::<MatchedPath>()
        .map(MatchedPath::as_str)
        .unwrap_or_else(|| request.uri().path())
}