footing 0.6.4

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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
//! Axum and Tower idempotency enforcement runtime.

use crate::http::IdempotencyRequestPolicy;

use std::{
    collections::HashSet,
    error::Error as _,
    fmt,
    future::Future,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

use axum::{
    body::{Body, Bytes},
    extract::{FromRequestParts, OriginalUri},
    http::{
        HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode,
        header::{AUTHORIZATION, CACHE_CONTROL, CONNECTION, CONTENT_LENGTH, CONTENT_TYPE, COOKIE},
        request::Parts,
        response,
    },
    response::{IntoResponse, Response},
};
use http_body_util::{BodyExt as _, Limited};
use sha2::{Digest, Sha256};
use thiserror::Error;
use tower::{Layer, Service};

use crate::{
    http::{ApiProblem, HttpRequestPolicy, ProblemCode, RequestContext, to_lower_hex},
    observability::{
        MetricLabels, MetricRecorder, RecordingFailures, metric_labels, metric_names,
        metric_outcomes,
    },
    result::{ClassifyError, ErrorKind},
};

use super::{
    memory::MemoryIdempotencyStore,
    model::{
        DEFAULT_MAX_IDEMPOTENCY_STORED_HEADER_BYTES, IDEMPOTENCY_KEY_HEADER_NAME,
        IDEMPOTENCY_REPLAYED_HEADER_NAME, IDEMPOTENCY_TERMINAL_FAILURE_BODY,
        IDEMPOTENCY_TERMINAL_FAILURE_MEDIA_TYPE, IdempotencyConfig, IdempotencyKey,
        IdempotencyLease, IdempotencyRequestHash, IdempotencyReservation, IdempotencyScope,
        IdempotencyStore, IdempotencyStoreError, StoredIdempotencyResponse, hash_length_prefixed,
        is_storable_response_header, validate_idempotency_key,
    },
};

const CANCELLED_EXECUTION_COMMIT_TIMEOUT: Duration = Duration::from_secs(5);

#[derive(Clone)]
#[non_exhaustive]
/// Runtime dependencies for idempotency enforcement.
pub struct IdempotencyRuntime {
    store: Arc<dyn IdempotencyStore>,
    config: IdempotencyConfig,
    metrics: Option<Arc<dyn MetricRecorder>>,
    recording_failures: RecordingFailures,
}

impl fmt::Debug for IdempotencyRuntime {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdempotencyRuntime")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

impl IdempotencyRuntime {
    #[must_use]
    /// Creates a runtime from an explicit store and validated policy.
    pub fn new(store: Arc<dyn IdempotencyStore>, config: IdempotencyConfig) -> Self {
        Self {
            store,
            config,
            metrics: None,
            recording_failures: RecordingFailures::default(),
        }
    }

    /// Creates a runtime backed by the bounded in-memory store.
    pub fn in_memory(config: IdempotencyConfig) -> Result<Self, IdempotencyStoreError> {
        let store =
            MemoryIdempotencyStore::for_response_body_limit(config.max_response_body_bytes())?;
        Ok(Self::new(Arc::new(store), config))
    }

    #[must_use]
    /// Configures reservation-decision and store-error metrics.
    /// Store errors are counted by fixed `stage` and stable `error_code`, including
    /// terminal response commits and cancellation cleanup. Backend messages and
    /// request keys are never metric labels. Failed writes increment [`Self::failed_recordings`].
    pub fn with_metrics(mut self, metrics: Option<Arc<dyn MetricRecorder>>) -> Self {
        self.metrics = metrics;
        self
    }

    #[must_use]
    /// Returns the store.
    pub fn store(&self) -> &Arc<dyn IdempotencyStore> {
        &self.store
    }

    #[must_use]
    /// Returns the validated policy.
    pub const fn config(&self) -> &IdempotencyConfig {
        &self.config
    }

    #[must_use]
    /// Returns the metrics.
    pub fn metrics(&self) -> Option<&Arc<dyn MetricRecorder>> {
        self.metrics.as_ref()
    }

    /// Returns failed metric writes across clones of this runtime.
    #[must_use]
    pub fn failed_recordings(&self) -> u64 {
        self.recording_failures.count()
    }

    fn record_store_error(&self, stage: &'static str, error_code: &str) {
        if let Some(metrics) = self.metrics() {
            self.recording_failures.record(
                MetricLabels::new([
                    (metric_labels::STAGE, stage),
                    (metric_labels::ERROR_CODE, error_code),
                ])
                .and_then(|labels| {
                    metrics.increment_counter(
                        metric_names::IDEMPOTENCY_STORE_ERRORS_TOTAL,
                        1,
                        labels,
                    )
                }),
                "idempotency",
            );
        }
    }
}

#[derive(Debug, Error)]
#[non_exhaustive]
/// Enumerates the supported idempotency rejection values.
pub enum IdempotencyRejection {
    #[error("idempotency key is invalid")]
    /// The key is invalid.
    InvalidKey,
    #[error("idempotency request is already processing")]
    /// Indicates processing.
    Processing,
    #[error("idempotency key was reused with a different request")]
    /// Indicates conflict.
    Conflict,
    #[error("idempotency request body is too large")]
    /// The request body exceeds the supported size.
    RequestBodyTooLarge,
    #[error("idempotency request body could not be read")]
    /// Reading the request body failed for a reason other than its size limit.
    RequestBodyReadFailed,
    #[error("idempotency requires a verified authentication scope")]
    /// Identity-bearing requests need a verified scope before entering the
    /// idempotency cache. Rejected with `403`; credential validation and `401`
    /// challenges belong to authentication middleware.
    UnverifiedAuthenticationScope,
    #[error("idempotency execution result is unavailable")]
    /// Indicates execution result unavailable.
    ExecutionResultUnavailable,
    #[error("idempotency store is unavailable")]
    /// Indicates store unavailable.
    StoreUnavailable,
    #[error("idempotency does not support request trailers")]
    /// The request contains trailing fields that cannot be fingerprinted and replayed.
    RequestTrailersUnsupported,
}

impl ClassifyError for IdempotencyRejection {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::InvalidKey
            | Self::RequestBodyTooLarge
            | Self::RequestBodyReadFailed
            | Self::RequestTrailersUnsupported => ErrorKind::Validation,
            Self::UnverifiedAuthenticationScope => ErrorKind::Authorization,
            Self::Processing | Self::Conflict => ErrorKind::Conflict,
            Self::ExecutionResultUnavailable => ErrorKind::Internal,
            Self::StoreUnavailable => ErrorKind::Unavailable,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidKey => "invalid_idempotency_key",
            Self::Processing => "idempotency_request_processing",
            Self::Conflict => "idempotency_key_conflict",
            Self::RequestBodyTooLarge => "idempotency_request_body_too_large",
            Self::RequestBodyReadFailed => "idempotency_request_body_read_failed",
            Self::RequestTrailersUnsupported => "idempotency_request_trailers_unsupported",
            Self::UnverifiedAuthenticationScope => "idempotency_authentication_scope_required",
            Self::ExecutionResultUnavailable => "idempotency_execution_result_unavailable",
            Self::StoreUnavailable => "idempotency_store_unavailable",
        })
    }
}

impl IntoResponse for IdempotencyRejection {
    fn into_response(self) -> Response {
        self.into_response_with_context(None)
    }
}

impl IdempotencyRejection {
    fn into_response_with_context(self, context: Option<&RequestContext>) -> Response {
        let mut problem = match self {
            Self::InvalidKey => ApiProblem::bad_request(
                ProblemCode::INVALID_IDEMPOTENCY_KEY,
                "idempotency key is invalid",
            ),
            Self::Processing => ApiProblem::conflict(
                ProblemCode::IDEMPOTENCY_REQUEST_PROCESSING,
                "an idempotency request with this key is already processing",
            ),
            Self::Conflict => ApiProblem::conflict(
                ProblemCode::IDEMPOTENCY_KEY_CONFLICT,
                "idempotency key was reused with a different request",
            ),
            Self::RequestBodyTooLarge => ApiProblem::payload_too_large(
                ProblemCode::IDEMPOTENCY_REQUEST_BODY_TOO_LARGE,
                "idempotency request body is too large",
            ),
            Self::RequestBodyReadFailed => ApiProblem::bad_request(
                ProblemCode::IDEMPOTENCY_REQUEST_BODY_READ_FAILED,
                "request body could not be read",
            ),
            Self::RequestTrailersUnsupported => ApiProblem::bad_request(
                ProblemCode::from_error_code(Self::RequestTrailersUnsupported.error_code()),
                "idempotency does not support request trailers",
            ),
            Self::UnverifiedAuthenticationScope => ApiProblem::forbidden(
                ProblemCode::IDEMPOTENCY_AUTHENTICATION_SCOPE_REQUIRED,
                "authentication must be verified before applying idempotency",
            ),
            Self::ExecutionResultUnavailable => return terminal_failure_response(),
            Self::StoreUnavailable => ApiProblem::service_unavailable(
                ProblemCode::IDEMPOTENCY_STORE_UNAVAILABLE,
                "idempotency store is unavailable",
            ),
        };
        if let Some(context) = context {
            problem = problem.with_request_context(context);
        }
        problem.into_response()
    }
}

#[derive(Clone)]
#[non_exhaustive]
/// Tower layer that applies idempotency.
/// An outer timeout must satisfy the requirements of [`run_idempotent_service`].
/// New rejections include correlation identifiers from an installed [`RequestContext`].
/// Stored status, replayable headers and body are retained; `Content-Length`
/// is not stored (see [`run_idempotent_service`]). Deterministic terminal failures
/// omit request-specific identifiers so the initial response and later replays agree.
/// An outer request-context layer can attach the current identifiers as response headers.
pub struct IdempotencyLayer {
    runtime: IdempotencyRuntime,
    request_policy: HttpRequestPolicy,
}

impl IdempotencyLayer {
    #[must_use]
    /// Creates a new instance.
    pub fn new(runtime: IdempotencyRuntime) -> Self {
        Self {
            runtime,
            request_policy: HttpRequestPolicy::default(),
        }
    }

    #[must_use]
    /// Configures request policy and returns the updated value.
    pub fn with_request_policy(mut self, request_policy: HttpRequestPolicy) -> Self {
        self.request_policy = request_policy;
        self
    }

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

    #[must_use]
    /// Returns the request policy.
    pub const fn request_policy(&self) -> &HttpRequestPolicy {
        &self.request_policy
    }
}

impl fmt::Debug for IdempotencyLayer {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdempotencyLayer")
            .field("runtime", &self.runtime)
            .finish()
    }
}

impl<S> Layer<S> for IdempotencyLayer {
    type Service = IdempotencyService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        IdempotencyService {
            inner,
            runtime: self.runtime.clone(),
            request_policy: self.request_policy.clone(),
        }
    }
}

#[derive(Clone)]
#[non_exhaustive]
/// Service for idempotency.
pub struct IdempotencyService<S> {
    inner: S,
    runtime: IdempotencyRuntime,
    request_policy: HttpRequestPolicy,
}

impl<S> fmt::Debug for IdempotencyService<S>
where
    S: fmt::Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IdempotencyService")
            .field("inner", &self.inner)
            .field("runtime", &self.runtime)
            .finish()
    }
}

impl<S> Service<Request<Body>> for IdempotencyService<S>
where
    S: Service<Request<Body>, Response = Response> + Clone + Send + 'static,
    S::Future: Send + 'static,
    S::Error: Send + 'static,
{
    type Response = Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(context)
    }

    fn call(&mut self, mut request: Request<Body>) -> Self::Future {
        if !should_run_idempotency(&self.request_policy, &mut request) {
            return Box::pin(self.inner.call(request));
        }
        let runtime = self.runtime.clone();
        let context = request.extensions().get::<RequestContext>().cloned();
        let clone = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, clone);

        Box::pin(async move {
            let response =
                match run_idempotent_service(runtime, request, |request| inner.call(request)).await
                {
                    Ok(response) => response?,
                    Err(rejection) => rejection.into_response_with_context(context.as_ref()),
                };
            Ok(response)
        })
    }
}

fn should_run_idempotency<B>(request_policy: &HttpRequestPolicy, request: &mut Request<B>) -> bool {
    match request_policy.resolve(request).idempotency() {
        IdempotencyRequestPolicy::Disabled => false,
        IdempotencyRequestPolicy::HeaderOptional => {
            request.headers().contains_key(IDEMPOTENCY_KEY_HEADER_NAME)
        }
        IdempotencyRequestPolicy::Required => true,
    }
}

/// Finalizes an owned reservation if protected execution is cancelled.
///
/// Created immediately before execution, this guard commits a small
/// deterministic terminal response within a bounded time, or deliberately
/// leaves the record in its processing state when that commit cannot be
/// completed. The processing TTL is the authoritative fallback during runtime
/// or store failures.
struct IdempotencyReservationGuard {
    runtime: IdempotencyRuntime,
    lease: IdempotencyLease,
    pending_key: Option<IdempotencyKey>,
}

impl IdempotencyReservationGuard {
    fn new(runtime: IdempotencyRuntime, key: IdempotencyKey, lease: IdempotencyLease) -> Self {
        Self {
            runtime,
            lease,
            pending_key: Some(key),
        }
    }

    async fn commit(
        &mut self,
        response: StoredIdempotencyResponse,
    ) -> Result<(), IdempotencyStoreError> {
        let key = self
            .pending_key
            .as_ref()
            .ok_or(IdempotencyStoreError::InconsistentRecord)?;
        let result = self
            .runtime
            .store
            .commit(key, self.lease, response, self.runtime.config.ttl)
            .await;
        // Keep the key across the await so cancellation still terminalizes.
        // A returned commit error leaves the processing lease untouched.
        self.pending_key = None;
        if let Err(error) = &result {
            self.runtime
                .record_store_error("commit", error.error_code().as_str());
        }
        result
    }

    async fn commit_terminal_failure(&mut self) -> Result<(), IdempotencyStoreError> {
        self.commit(terminal_failure_stored_response()).await
    }
}

impl Drop for IdempotencyReservationGuard {
    fn drop(&mut self) {
        let Some(key) = self.pending_key.take() else {
            return;
        };
        let Ok(handle) = tokio::runtime::Handle::try_current() else {
            // Leaving the reservation untouched is safe: its processing TTL
            // prevents an unbounded leak and delays any ambiguous retry.
            return;
        };
        let runtime = self.runtime.clone();
        let lease = self.lease;
        drop(handle.spawn(async move {
            // Never abort the lease: side effects may already have occurred.
            // A failed or timed-out commit leaves processing expiry in control.
            match tokio::time::timeout(
                CANCELLED_EXECUTION_COMMIT_TIMEOUT,
                runtime.store.commit(
                    &key,
                    lease,
                    terminal_failure_stored_response(),
                    runtime.config.ttl,
                ),
            )
            .await
            {
                Ok(Ok(())) => {}
                Ok(Err(error)) => {
                    runtime.record_store_error("cancel_commit", error.error_code().as_str());
                    tracing::warn!(
                        error_code = %error.error_code(),
                        "failed to terminalize a cancelled idempotent execution"
                    );
                }
                Err(_) => {
                    runtime.record_store_error("cancel_commit", "idempotency_store_timeout");
                    tracing::warn!("timed out terminalizing a cancelled idempotent execution")
                }
            }
        }));
    }
}

/// Runs idempotent service.
///
/// Callers must enforce a request timeout shorter than the runtime's processing
/// TTL, including response capture and storage. The HTTP middleware stack
/// validates this requirement; standalone callers must install an outer timeout.
/// Protected operations must be cancellation-safe and account for external side
/// effects that may outlive cancellation. Cancellation starts a best-effort
/// terminal response write with a five-second timeout; if it fails, the
/// processing reservation remains until its TTL expires.
///
/// Nonempty request trailers are rejected before reserving a key or executing
/// the service. Response trailers cannot be replayed by the storage format, so
/// responses containing them become a stored terminal failure. Use a route with
/// idempotency disabled for protocols that require trailers, such as gRPC.
///
/// `Content-Length` is not stored. Empty HEAD and 304 replays omit it because
/// their representation length cannot be inferred from the retained empty body.
pub async fn run_idempotent_service<F, Fut, E>(
    runtime: IdempotencyRuntime,
    request: Request<Body>,
    call: F,
) -> Result<Result<Response, E>, IdempotencyRejection>
where
    F: FnOnce(Request<Body>) -> Fut,
    Fut: Future<Output = Result<Response, E>>,
{
    let client_key = parse_required_idempotency_key(request.headers())?;
    let method = request.method().clone();
    let (parts, body) = request.into_parts();
    let store_key = scoped_store_key(&parts, &client_key)?;
    let collected = Limited::new(body, runtime.config.max_request_body_bytes)
        .collect()
        .await
        .map_err(axum::Error::new)
        .map_err(|error| {
            let mut source = error.source();
            while let Some(cause) = source {
                if cause.is::<http_body_util::LengthLimitError>() {
                    return IdempotencyRejection::RequestBodyTooLarge;
                }
                source = cause.source();
            }
            IdempotencyRejection::RequestBodyReadFailed
        })?;
    if collected
        .trailers()
        .is_some_and(|trailers| !trailers.is_empty())
    {
        return Err(IdempotencyRejection::RequestTrailersUnsupported);
    }
    let body = collected.to_bytes();
    let request_hash = request_hash_from_parts(&parts, &body, runtime.config.fingerprint_headers());
    let request = Request::from_parts(parts, Body::from(body));

    // Configuration validates that the body and header reservation fit together.
    let response_capacity_bytes =
        runtime.config.max_response_body_bytes + DEFAULT_MAX_IDEMPOTENCY_STORED_HEADER_BYTES;
    let reservation = runtime
        .store
        .reserve(
            store_key.clone(),
            request_hash,
            runtime.config.processing_ttl,
            response_capacity_bytes,
        )
        .await
        .map_err(|error| {
            runtime.record_store_error("reserve", error.error_code().as_str());
            IdempotencyRejection::StoreUnavailable
        })?;
    record_idempotency_metric(&runtime, reservation_metric_outcome(&reservation));

    match reservation {
        IdempotencyReservation::Reserved(lease) => {
            let mut reservation =
                IdempotencyReservationGuard::new(runtime.clone(), store_key, lease);
            let response = match call(request).await {
                Ok(response) => response,
                Err(error) => {
                    if let Err(commit_error) = reservation.commit_terminal_failure().await {
                        tracing::warn!(
                            error = %commit_error,
                            "failed to terminalize an idempotent service error"
                        );
                    }
                    return Ok(Err(error));
                }
            };
            store_and_return_response(&runtime, &mut reservation, response, &method)
                .await
                .map(Ok)
        }
        IdempotencyReservation::Processing => Err(IdempotencyRejection::Processing),
        IdempotencyReservation::Replay(stored) => response_from_stored(stored, &method).map(Ok),
        IdempotencyReservation::Conflict => Err(IdempotencyRejection::Conflict),
    }
}

fn reservation_metric_outcome(reservation: &IdempotencyReservation) -> &'static str {
    match reservation {
        IdempotencyReservation::Reserved(_) => metric_outcomes::RESERVED,
        IdempotencyReservation::Processing => metric_outcomes::PROCESSING,
        IdempotencyReservation::Replay(_) => metric_outcomes::REPLAY,
        IdempotencyReservation::Conflict => metric_outcomes::CONFLICT,
    }
}

fn record_idempotency_metric(runtime: &IdempotencyRuntime, outcome: &'static str) {
    if let Some(metrics) = runtime.metrics() {
        runtime.recording_failures.record(
            MetricLabels::new([(metric_labels::OUTCOME, outcome)]).and_then(|labels| {
                metrics.increment_counter(metric_names::IDEMPOTENCY_REQUESTS_TOTAL, 1, labels)
            }),
            "idempotency",
        );
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Represents required idempotency key.
pub struct RequiredIdempotencyKey(pub IdempotencyKey);

impl RequiredIdempotencyKey {
    #[must_use]
    /// Consumes this value and returns inner.
    pub fn into_inner(self) -> IdempotencyKey {
        self.0
    }
}

impl<S> FromRequestParts<S> for RequiredIdempotencyKey
where
    S: Send + Sync,
{
    type Rejection = ApiProblem;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        idempotency_key_from_headers(&parts.headers)
            .map(Self)
            .ok_or_else(|| {
                ApiProblem::bad_request(
                    ProblemCode::IDEMPOTENCY_KEY_REQUIRED,
                    "a valid Idempotency-Key header is required",
                )
                .with_request_context(RequestContext::from_parts(parts))
            })
    }
}

#[must_use]
/// Extracts exactly one valid idempotency key; missing or repeated headers are invalid.
/// Removes only surrounding HTTP optional whitespace (spaces and horizontal tabs).
pub fn idempotency_key_from_headers(headers: &HeaderMap) -> Option<IdempotencyKey> {
    let mut values = headers.get_all(IDEMPOTENCY_KEY_HEADER_NAME).iter();
    let value = values.next()?;
    if values.next().is_some() {
        return None;
    }
    IdempotencyKey::parse(value.to_str().ok()?.trim_matches([' ', '\t']))
}

/// Parses required idempotency key.
pub fn parse_required_idempotency_key(
    headers: &HeaderMap,
) -> Result<IdempotencyKey, IdempotencyRejection> {
    idempotency_key_from_headers(headers).ok_or(IdempotencyRejection::InvalidKey)
}

#[must_use]
/// Returns whether this value is valid idempotency key.
pub fn is_valid_idempotency_key(value: &str) -> bool {
    validate_idempotency_key(value).is_ok()
}

fn request_hash_from_parts(
    parts: &Parts,
    body: &[u8],
    fingerprint_headers: &[HeaderName],
) -> IdempotencyRequestHash {
    let mut hasher = Sha256::new();
    hasher.update(b"footing-idempotency-request-v3\0");
    hash_length_prefixed(&mut hasher, parts.method.as_str().as_bytes());
    // Nested Axum routers strip their prefix from `parts.uri`. Keep the full
    // request target so siblings sharing a store cannot replay each other's work.
    let uri = parts
        .extensions
        .get::<OriginalUri>()
        .map_or(&parts.uri, |original| &original.0);
    hash_length_prefixed(&mut hasher, uri.to_string().as_bytes());
    hash_header(&mut hasher, &parts.headers, &CONTENT_TYPE);
    hash_length_prefixed(&mut hasher, body);
    for name in fingerprint_headers {
        hash_header(&mut hasher, &parts.headers, name);
    }
    IdempotencyRequestHash(to_lower_hex(&hasher.finalize()))
}

fn hash_header(hasher: &mut Sha256, headers: &HeaderMap, name: &HeaderName) {
    hash_length_prefixed(hasher, name.as_str().as_bytes());
    let values = headers.get_all(name);
    hasher.update((values.iter().count() as u64).to_be_bytes());
    for value in values.iter() {
        hash_length_prefixed(hasher, value.as_bytes());
    }
}

fn scoped_store_key(
    parts: &Parts,
    client_key: &IdempotencyKey,
) -> Result<IdempotencyKey, IdempotencyRejection> {
    let mut hasher = Sha256::new();
    hasher.update(b"footing-idempotency-store-key-v2\0");
    if let Some(scope) = parts.extensions.get::<IdempotencyScope>() {
        hasher.update(b"explicit\0");
        hasher.update(scope.0);
    } else if parts.headers.contains_key(AUTHORIZATION)
        || parts.headers.contains_key(COOKIE)
        || parts
            .extensions
            .get::<RequestContext>()
            .and_then(RequestContext::principal)
            .is_some()
    {
        return Err(IdempotencyRejection::UnverifiedAuthenticationScope);
    } else {
        hasher.update(b"anonymous\0");
    }
    hash_length_prefixed(&mut hasher, client_key.as_str().as_bytes());

    Ok(IdempotencyKey(to_lower_hex(&hasher.finalize())))
}

async fn store_and_return_response(
    runtime: &IdempotencyRuntime,
    reservation: &mut IdempotencyReservationGuard,
    response: Response,
    method: &Method,
) -> Result<Response, IdempotencyRejection> {
    let capture = async {
        let (mut parts, body) = response.into_parts();
        if parts.status == StatusCode::NO_CONTENT {
            parts.headers.remove(CONTENT_LENGTH);
        }
        let collected = Limited::new(body, runtime.config.max_response_body_bytes)
            .collect()
            .await
            .map_err(|_| "response body exceeds the limit or could not be read")?;
        if collected
            .trailers()
            .is_some_and(|trailers| !trailers.is_empty())
        {
            return Err("response trailers cannot be replayed");
        }
        let body = collected.to_bytes();
        // Detach the stored bytes from any larger backing allocation supplied by
        // the handler. Subsequent replays share this bounded, immutable copy.
        let stored = stored_response_from_parts(&parts, body.to_vec())?;
        let body = captured_response_body(method, parts.status, body);
        Ok::<_, &'static str>((Response::from_parts(parts, body), stored))
    }
    .await;
    let (response, stored) = match capture {
        Ok(captured) => captured,
        Err(error) => {
            tracing::warn!(
                error = %error,
                "failed to capture an idempotent response; committing a terminal failure"
            );
            if let Err(commit_error) = reservation.commit_terminal_failure().await {
                // Returning the same deterministic response remains preferable
                // to exposing storage details. The guard deliberately leaves
                // the processing lease intact after this failed commit.
                tracing::warn!(
                    error = %commit_error,
                    "failed to persist an idempotent terminal failure"
                );
            }
            return Ok(terminal_failure_response());
        }
    };
    reservation
        .commit(stored)
        .await
        .map_err(|_| IdempotencyRejection::StoreUnavailable)?;
    Ok(response)
}

fn terminal_failure_stored_response() -> StoredIdempotencyResponse {
    StoredIdempotencyResponse {
        status: StatusCode::INTERNAL_SERVER_ERROR,
        headers: vec![
            (
                CONTENT_TYPE.as_str().to_owned(),
                IDEMPOTENCY_TERMINAL_FAILURE_MEDIA_TYPE.to_owned(),
            ),
            (CACHE_CONTROL.as_str().to_owned(), "no-store".to_owned()),
        ],
        body: Bytes::from_static(IDEMPOTENCY_TERMINAL_FAILURE_BODY),
    }
}

fn terminal_failure_response() -> Response {
    let mut response = Response::new(Body::from(IDEMPOTENCY_TERMINAL_FAILURE_BODY));
    *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
    response.headers_mut().insert(
        CONTENT_TYPE,
        HeaderValue::from_static(IDEMPOTENCY_TERMINAL_FAILURE_MEDIA_TYPE),
    );
    response
        .headers_mut()
        .insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
    response
}

pub(super) fn response_from_stored(
    stored: StoredIdempotencyResponse,
    method: &Method,
) -> Result<Response, IdempotencyRejection> {
    let mut builder = response::Builder::new().status(stored.status);
    for (name, value) in &stored.headers {
        builder = builder.header(name.as_str(), value.as_str());
    }
    builder = builder.header(IDEMPOTENCY_REPLAYED_HEADER_NAME, "true");
    builder
        .body(captured_response_body(method, stored.status, stored.body))
        .map_err(|_| IdempotencyRejection::StoreUnavailable)
}

fn captured_response_body(method: &Method, status: StatusCode, body: Bytes) -> Body {
    if body.is_empty()
        && (method == Method::HEAD
            || matches!(status, StatusCode::NO_CONTENT | StatusCode::NOT_MODIFIED))
    {
        // Axum derives Content-Length from an exact size hint. These responses
        // forbid that header or use it for representation metadata, not body size.
        Body::from_stream(Body::empty().into_data_stream())
    } else {
        Body::from(body)
    }
}

pub(super) fn stored_response_from_parts(
    parts: &response::Parts,
    body: Vec<u8>,
) -> Result<StoredIdempotencyResponse, &'static str> {
    let mut stored = StoredIdempotencyResponse::new(parts.status, body);
    let mut stored_header_bytes = 0usize;
    let connection_headers = connection_nominated_headers(&parts.headers);
    for (name, value) in &parts.headers {
        if is_storable_response_header(name) && !connection_headers.contains(name) {
            let value = value.to_str().map_err(|_| "response header is not text")?;
            stored_header_bytes = stored_header_bytes
                .checked_add(name.as_str().len())
                .and_then(|bytes| bytes.checked_add(value.len()))
                .filter(|bytes| *bytes <= DEFAULT_MAX_IDEMPOTENCY_STORED_HEADER_BYTES)
                .ok_or("response headers exceed the storage limit")?;
            stored
                .headers
                .push((name.as_str().to_owned(), value.to_owned()));
        }
    }
    Ok(stored)
}

fn connection_nominated_headers(headers: &HeaderMap) -> HashSet<HeaderName> {
    headers
        .get_all(CONNECTION)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .flat_map(|value| value.split(','))
        .filter_map(|name| HeaderName::try_from(name.trim()).ok())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn old_fingerprints_conflict_at_the_same_store_key_until_expiry() {
        use std::{
            convert::Infallible,
            sync::atomic::{AtomicUsize, Ordering},
        };

        // v1 and v2 fingerprints for POST /jobs?queue=1 with
        // Content-Type: application/json and body {"value":1}.
        for old_hash in [
            "109cc3e88b794f9f75bf4983f2f19cbe3ed895f1c694133c410b3b8ddc3f2980",
            "41aeb8652b277b479e751c45a1bf8f5e39c0b6457a588cb2c9df41e3e04ae736",
        ] {
            for completed in [false, true] {
                let clock = crate::clock::ManualClock::new();
                let store = Arc::new(MemoryIdempotencyStore::with_clock(clock.shared()));
                // Storage keys remain stable across request fingerprint versions.
                let key = IdempotencyKey::new(
                    "36ee884b2934e32826808ba2112233373faafb3a3b4fcc277d13192bc81ed988",
                )
                .unwrap();
                let old_hash = IdempotencyRequestHash::new(old_hash).unwrap();
                let IdempotencyReservation::Reserved(lease) = store
                    .reserve(key.clone(), old_hash, Duration::from_secs(60), 1024)
                    .await
                    .unwrap()
                else {
                    panic!("fixture should acquire a reservation");
                };
                if completed {
                    store
                        .commit(
                            &key,
                            lease,
                            StoredIdempotencyResponse::new(StatusCode::CREATED, "old"),
                            Duration::from_secs(60),
                        )
                        .await
                        .unwrap();
                }
                let runtime = IdempotencyRuntime::new(store.clone(), IdempotencyConfig::default());
                let request = || {
                    Request::post("/jobs?queue=1")
                        .header(CONTENT_TYPE, "application/json")
                        .header(IDEMPOTENCY_KEY_HEADER_NAME, "retry")
                        .body(Body::from(r#"{"value":1}"#))
                        .unwrap()
                };
                let executions = AtomicUsize::new(0);
                for expired in [false, true] {
                    if expired {
                        clock.advance(Duration::from_secs(61)).unwrap();
                    }
                    let result = run_idempotent_service(runtime.clone(), request(), |_| async {
                        executions.fetch_add(1, Ordering::SeqCst);
                        Ok::<_, Infallible>(StatusCode::CREATED.into_response())
                    })
                    .await;
                    if expired {
                        assert_eq!(result.unwrap().unwrap().status(), StatusCode::CREATED);
                    } else {
                        assert!(matches!(result, Err(IdempotencyRejection::Conflict)));
                        assert_eq!(executions.load(Ordering::SeqCst), 0);
                        assert_eq!(store.record_count().unwrap(), 1);
                    }
                }
                assert_eq!(executions.load(Ordering::SeqCst), 1);
            }
        }
    }
}