footing 0.5.1

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
//! Idempotency domain types, validated policy, and store contract.

use std::{
    fmt,
    sync::Arc,
    time::{Duration, Instant},
};

use async_trait::async_trait;
use axum::{
    body::Bytes,
    http::{HeaderName, HeaderValue, StatusCode},
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use thiserror::Error;
use uuid::Uuid;

use crate::result::{ClassifyError, ErrorKind};

/// Idempotency key header name.
pub const IDEMPOTENCY_KEY_HEADER_NAME: &str = "idempotency-key";
/// Idempotency replayed header name.
pub const IDEMPOTENCY_REPLAYED_HEADER_NAME: &str = "idempotency-replayed";
/// Maximum supported idempotency key length.
pub const MAX_IDEMPOTENCY_KEY_LENGTH: usize = 128;
/// Default idempotency TTL.
pub const DEFAULT_IDEMPOTENCY_TTL: Duration = Duration::from_secs(60 * 60 * 24);
/// Default idempotency processing TTL.
pub const DEFAULT_IDEMPOTENCY_PROCESSING_TTL: Duration = Duration::from_secs(5 * 60);
/// Default idempotency maximum body bytes.
pub const DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES: usize = 1024 * 1024;
/// Default maximum idempotency records.
pub const DEFAULT_MAX_IDEMPOTENCY_RECORDS: usize = 1_024;
/// Default maximum idempotency stored response bytes.
pub const DEFAULT_MAX_IDEMPOTENCY_STORED_RESPONSE_BYTES: usize = 64 * 1024 * 1024;
/// Default maximum idempotency stored header bytes.
pub const DEFAULT_MAX_IDEMPOTENCY_STORED_HEADER_BYTES: usize = 16 * 1024;

pub(super) const IDEMPOTENCY_TERMINAL_FAILURE_MEDIA_TYPE: &str = "application/problem+json";
pub(super) const IDEMPOTENCY_TERMINAL_FAILURE_BODY: &[u8] = br#"{"type":"about:blank","title":"Internal Server Error","status":500,"code":"internal_error","detail":"internal server error","details":{"code":"idempotency_execution_result_unavailable"}}"#;

/// An authentication or tenant boundary for idempotency records.
///
/// The value is immediately reduced to a one-way fingerprint so credentials or
/// tenant identifiers are never retained in the in-memory store. Authentication
/// middleware must install this extension only after it has validated the
/// credential. Requests carrying credential headers or an installed principal
/// without an explicit scope are rejected instead of sharing anonymous records.
/// Use [`crate::http::VerifiedAuthentication`] to install a principal and its
/// scope together, including authentication that does not use HTTP headers.
#[derive(Clone, PartialEq, Eq)]
pub struct IdempotencyScope(pub(super) [u8; 32]);

impl IdempotencyScope {
    #[must_use]
    /// Creates a new instance.
    pub fn new(value: impl AsRef<[u8]>) -> Self {
        Self(Sha256::digest(value.as_ref()).into())
    }

    /// Creates a domain-separated scope without concatenating sensitive input
    /// into a temporary string.
    #[must_use]
    pub fn namespaced(namespace: impl AsRef<[u8]>, value: impl AsRef<[u8]>) -> Self {
        let mut hasher = Sha256::new();
        hasher.update(b"footing-idempotency-scope-v1\0");
        hash_length_prefixed(&mut hasher, namespace.as_ref());
        hash_length_prefixed(&mut hasher, value.as_ref());
        Self(hasher.finalize().into())
    }
}

impl fmt::Debug for IdempotencyScope {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("IdempotencyScope([REDACTED])")
    }
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// Policy controlling idempotency request.
pub enum IdempotencyRequestPolicy {
    #[default]
    /// Indicates header optional.
    HeaderOptional,
    /// Indicates required.
    Required,
    /// The capability is disabled.
    Disabled,
}

impl IdempotencyRequestPolicy {
    /// Returns the policy name used in settings and endpoint contracts.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::HeaderOptional => "header_optional",
            Self::Required => "required",
            Self::Disabled => "disabled",
        }
    }
}

#[derive(Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Represents idempotency key.
pub struct IdempotencyKey(pub(super) String);

impl IdempotencyKey {
    /// Creates a new instance.
    pub fn new(value: impl Into<String>) -> Result<Self, IdempotencyKeyError> {
        let value = value.into().trim().to_owned();
        validate_idempotency_key(&value)?;
        Ok(Self(value))
    }

    #[must_use]
    /// Parses the value.
    pub fn parse(value: &str) -> Option<Self> {
        Self::new(value).ok()
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for IdempotencyKey {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("[REDACTED]")
    }
}

impl fmt::Display for IdempotencyKey {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("[REDACTED]")
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling idempotency key.
pub enum IdempotencyKeyError {
    #[error("idempotency key must not be empty")]
    /// Indicates empty.
    Empty,
    #[error("idempotency key must be less than or equal to {max} bytes")]
    /// The value exceeds the supported length.
    TooLong {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("idempotency key contains unsupported characters")]
    /// The characters is invalid.
    InvalidCharacters,
}

impl ClassifyError for IdempotencyKeyError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::Empty => "idempotency_key_empty",
            Self::TooLong { .. } => "idempotency_key_too_long",
            Self::InvalidCharacters => "idempotency_key_invalid_characters",
        })
    }
}

#[derive(Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Represents idempotency request hash.
pub struct IdempotencyRequestHash(pub(super) String);

impl IdempotencyRequestHash {
    /// Creates a new instance.
    pub fn new(value: impl Into<String>) -> Result<Self, IdempotencyKeyError> {
        let value = value.into().trim().to_owned();
        validate_idempotency_key(&value)?;
        Ok(Self(value))
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for IdempotencyRequestHash {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("[REDACTED]")
    }
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
/// A response containing stored idempotency.
pub struct StoredIdempotencyResponse {
    pub(super) status: StatusCode,
    pub(super) headers: Vec<(String, String)>,
    pub(super) body: Bytes,
}

impl fmt::Debug for StoredIdempotencyResponse {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("StoredIdempotencyResponse")
            .field("status", &self.status)
            .field("header_count", &self.headers.len())
            .field("body_bytes", &self.body.len())
            .finish()
    }
}

impl StoredIdempotencyResponse {
    #[must_use]
    /// Creates a replayable response with no stored headers.
    pub fn new(status: StatusCode, body: impl Into<Vec<u8>>) -> Self {
        Self {
            status,
            headers: Vec::new(),
            body: Bytes::from(body.into()),
        }
    }

    /// Appends a validated replayable header, preserving duplicate values.
    ///
    /// Rejects invalid HTTP names, values that cannot be represented as visible
    /// ASCII header text, and headers excluded from replay: `connection`,
    /// `content-length`, `date`, `keep-alive`, `proxy-authenticate`,
    /// `proxy-authorization`, `server`, `set-cookie`, `te`, `trailer`,
    /// `transfer-encoding`, `upgrade`, and `idempotency-replayed`.
    /// Callers capturing a response must also remove headers named by its
    /// `Connection` header; this method validates only the supplied pair.
    pub fn try_with_header(
        mut self,
        name: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Self, IdempotencyHeaderError> {
        let name = name.into();
        let value = value.into();
        let name =
            HeaderName::try_from(name.as_str()).map_err(|_| IdempotencyHeaderError::InvalidName)?;
        let value = HeaderValue::try_from(value.as_str())
            .map_err(|_| IdempotencyHeaderError::InvalidValue)?;
        let value = value
            .to_str()
            .map_err(|_| IdempotencyHeaderError::InvalidValue)?;
        if !is_storable_response_header(&name) {
            return Err(IdempotencyHeaderError::ExcludedFromReplay);
        }

        self.headers
            .push((name.as_str().to_owned(), value.to_owned()));
        Ok(self)
    }

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

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

    #[must_use]
    /// Returns the headers.
    pub fn headers(&self) -> &[(String, String)] {
        &self.headers
    }
}

/// Validation failures when adding a header to a stored response.
///
/// Errors do not retain names or values that might contain credentials.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum IdempotencyHeaderError {
    /// The name is not a valid HTTP header name.
    #[error("invalid idempotency response header name")]
    InvalidName,
    /// The value is not valid replayable HTTP header text.
    #[error("invalid idempotency response header value")]
    InvalidValue,
    /// The header is intentionally excluded from stored responses.
    #[error("idempotency response header is excluded from replay")]
    ExcludedFromReplay,
}

impl ClassifyError for IdempotencyHeaderError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidName => "idempotency_header_invalid_name",
            Self::InvalidValue => "idempotency_header_invalid_value",
            Self::ExcludedFromReplay => "idempotency_header_excluded_from_replay",
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Enumerates the supported idempotency reservation values.
pub enum IdempotencyReservation {
    /// This caller owns the lease and may execute the protected operation.
    Reserved(IdempotencyLease),
    /// Another execution holds an unexpired processing lease.
    Processing,
    /// Return this retained response without executing the operation again.
    Replay(StoredIdempotencyResponse),
    /// The key already belongs to a different request fingerprint.
    Conflict,
}

/// An opaque ownership token for one processing reservation.
///
/// Stores use the lease to prevent a slow or cancelled request from committing
/// into a newer reservation that reused the same client key after expiry.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct IdempotencyLease(pub(super) Uuid);

impl fmt::Debug for IdempotencyLease {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("IdempotencyLease([REDACTED])")
    }
}

impl IdempotencyLease {
    #[must_use]
    /// Generates a fresh ownership token for a new reservation.
    pub fn new() -> Self {
        Self(Uuid::now_v7())
    }

    /// Exports the exact 16-byte UUID representation for persistent storage.
    ///
    /// Treat these bytes as ownership data and avoid logging them. Store commits
    /// and aborts must compare the whole token atomically with the stored lease.
    #[must_use]
    pub const fn to_bytes(self) -> [u8; 16] {
        *self.0.as_bytes()
    }

    /// Restores a token previously exported with [`Self::to_bytes`].
    ///
    /// This performs no ownership verification. Use only trusted stored data;
    /// create fresh reservations with [`Self::new`] instead of reusing bytes.
    #[must_use]
    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
        Self(Uuid::from_bytes(bytes))
    }
}

impl Default for IdempotencyLease {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while handling idempotency store.
pub enum IdempotencyStoreError {
    #[error("idempotency store capacity must be greater than zero")]
    /// The capacity is invalid.
    InvalidCapacity,
    #[error("idempotency store capacity is exhausted")]
    /// Indicates capacity exceeded.
    CapacityExceeded,
    #[error("idempotency record expiry is out of range")]
    /// The expiry is invalid.
    InvalidExpiry,
    #[error("idempotency store lock is poisoned")]
    /// Indicates lock poisoned.
    LockPoisoned,
    #[error("idempotency store record is inconsistent")]
    /// Indicates inconsistent record.
    InconsistentRecord,
    /// The backend failed. The source is available for explicit diagnostics,
    /// but is omitted from this error's display and debug output.
    #[error("idempotency store backend is unavailable")]
    Store(#[source] crate::result::BoxError),
}

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

impl ClassifyError for IdempotencyStoreError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::InvalidCapacity | Self::InvalidExpiry => ErrorKind::Validation,
            Self::CapacityExceeded | Self::LockPoisoned | Self::Store(_) => ErrorKind::Unavailable,
            Self::InconsistentRecord => ErrorKind::Internal,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidCapacity => "idempotency_store_invalid_capacity",
            Self::CapacityExceeded => "idempotency_store_capacity_exceeded",
            Self::InvalidExpiry => "idempotency_record_invalid_expiry",
            Self::LockPoisoned | Self::Store(_) => "idempotency_store_unavailable",
            Self::InconsistentRecord => "idempotency_record_inconsistent",
        })
    }
}

#[async_trait]
/// Atomic reservations and retained HTTP responses, independent of the backend.
///
/// # Persistent backends
///
/// Use a unique `(namespace, key)` identity and serialize transitions for that
/// identity across all instances. Persist the request fingerprint, processing
/// lease, state, reserved response capacity and expiry. Use one backend-owned
/// clock for TTLs, sampled after acquiring locks. An expired lease must not commit
/// over or abort a newer reservation, even when its request fingerprint matches.
/// Return success only after the state transition is durable. A lost connection
/// or cancelled future may have an unknown commit outcome; never interpret that
/// as permission to delete the reservation or rerun the protected operation.
///
/// Reserve response capacity before granting execution. A logical storage quota
/// can enforce this budget, but cannot guarantee availability during disk, WAL or
/// network failures. On those failures, retain the processing state or completed
/// result. Cleanup and capacity accounting must be atomic with reservations.
///
/// A backend can encode or encrypt [`StoredIdempotencyResponse`] through its
/// status, headers and body accessors, then reconstruct it with [`StoredIdempotencyResponse::new`]
/// and [`StoredIdempotencyResponse::try_with_header`]. Preserve duplicate headers
/// and binary bodies. Budget encoding overhead separately from the requested
/// plaintext capacity. Bind encrypted records to their namespace, key, request
/// fingerprint and format version; key management belongs to the adapter.
///
/// # Business transaction boundary
///
/// The HTTP handler and this store's commit are separate operations. A process
/// can finish a business mutation and crash before retaining its response. A
/// persistent store enables replay of completed records after restart, but does
/// not make the business operation exactly-once: after a processing lease expires,
/// another execution can start. Applications needing stronger guarantees must
/// record their business result or idempotency identity in the same business
/// transaction and recover that outcome on retries. External side effects need
/// their own idempotency protocol or transactional outbox. Do not hold a database
/// transaction open across the HTTP handler merely to lock this store's row.
pub trait IdempotencyStore: Send + Sync {
    /// Atomically reserves `key` for one execution attempt.
    ///
    /// A successful reservation must guarantee `response_capacity_bytes` of
    /// response headers and body storage. The middleware supplies enough for
    /// either its configured application response or its terminal failure
    /// response. Reject insufficient capacity before granting a lease, so
    /// storage pressure after execution cannot reopen an executed key.
    async fn reserve(
        &self,
        key: IdempotencyKey,
        request_hash: IdempotencyRequestHash,
        processing_ttl: Duration,
        response_capacity_bytes: usize,
    ) -> Result<IdempotencyReservation, IdempotencyStoreError>;

    /// Atomically turns the matching processing lease into a replayable result.
    ///
    /// Errors and cancellation must leave either the processing reservation or
    /// the completed result intact while the lease is valid. Removing it would
    /// allow an immediate retry after the protected operation may already have
    /// produced side effects. Middleware may cancel a commit when its timeout
    /// expires.
    async fn commit(
        &self,
        key: &IdempotencyKey,
        lease: IdempotencyLease,
        response: StoredIdempotencyResponse,
        retention_ttl: Duration,
    ) -> Result<(), IdempotencyStoreError>;

    /// Releases a processing reservation before protected execution begins.
    ///
    /// Callers must never abort once execution has started: cancellation,
    /// service errors, and response-capture failures all have an unknown
    /// side-effect outcome and must instead be terminalized or left processing
    /// until the lease expires. Implementations must not remove a newer or
    /// completed lease.
    async fn abort(
        &self,
        key: &IdempotencyKey,
        lease: IdempotencyLease,
    ) -> Result<(), IdempotencyStoreError>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Validated idempotency policy.
pub struct IdempotencyConfig {
    pub(super) ttl: Duration,
    pub(super) processing_ttl: Duration,
    pub(super) max_request_body_bytes: usize,
    pub(super) max_response_body_bytes: usize,
    fingerprint_headers: Arc<[HeaderName]>,
}

impl IdempotencyConfig {
    /// Creates a validated idempotency policy.
    pub fn new(
        ttl: Duration,
        processing_ttl: Duration,
        max_request_body_bytes: usize,
        max_response_body_bytes: usize,
    ) -> Result<Self, IdempotencyConfigError> {
        let now = Instant::now();
        if ttl.is_zero() || now.checked_add(ttl).is_none() {
            return Err(IdempotencyConfigError::InvalidTtl);
        }
        if processing_ttl.is_zero() || now.checked_add(processing_ttl).is_none() {
            return Err(IdempotencyConfigError::InvalidProcessingTtl);
        }
        if max_request_body_bytes == 0 {
            return Err(IdempotencyConfigError::InvalidRequestBodyLimit);
        }
        if max_response_body_bytes == 0
            || max_response_body_bytes
                .checked_add(DEFAULT_MAX_IDEMPOTENCY_STORED_HEADER_BYTES)
                .is_none()
        {
            return Err(IdempotencyConfigError::InvalidResponseBodyLimit);
        }
        Ok(Self {
            ttl,
            processing_ttl,
            max_request_body_bytes,
            max_response_body_bytes,
            fingerprint_headers: Arc::default(),
        })
    }

    /// Includes selected request headers in addition to the method, original URI,
    /// content type and body when detecting reuse of a key for a different request.
    ///
    /// Select headers that affect the operation or its response, such as `If-Match`,
    /// `Prefer`, or an API-version header. Names are sorted and deduplicated. Values
    /// use their original bytes and order: missing, empty, repeated, and comma-joined
    /// values are distinct. Values are neither trimmed nor interpreted.
    ///
    /// All policies use the same versioned, length-prefixed fingerprint format.
    /// Records written with older fingerprint formats conflict until they expire;
    /// their storage keys are retained so an upgrade cannot bypass existing leases
    /// or completed operations. Changing this policy can also produce conflicts.
    /// Keep versions and policies consistent across instances sharing a store.
    /// Credentials, request IDs and transport negotiation headers are not included
    /// by default.
    ///
    /// ```
    /// use axum::http::{HeaderName, header::IF_MATCH};
    /// use footing::http::IdempotencyConfig;
    ///
    /// let config = IdempotencyConfig::default().with_fingerprint_headers([
    ///     IF_MATCH,
    ///     HeaderName::from_static("prefer"),
    /// ]);
    /// assert_eq!(config.fingerprint_headers().len(), 2);
    /// ```
    #[must_use]
    pub fn with_fingerprint_headers(
        mut self,
        headers: impl IntoIterator<Item = HeaderName>,
    ) -> Self {
        let mut headers: Vec<_> = headers.into_iter().collect();
        headers.sort_unstable_by(|left, right| left.as_str().cmp(right.as_str()));
        headers.dedup();
        self.fingerprint_headers = headers.into();
        self
    }

    /// Returns the additional request headers included in the fingerprint.
    #[must_use]
    pub fn fingerprint_headers(&self) -> &[HeaderName] {
        &self.fingerprint_headers
    }

    #[must_use]
    /// Returns the completed-response retention duration.
    pub const fn ttl(&self) -> Duration {
        self.ttl
    }

    #[must_use]
    /// Returns the in-flight reservation duration.
    pub const fn processing_ttl(&self) -> Duration {
        self.processing_ttl
    }

    #[must_use]
    /// Returns the maximum request body size.
    pub const fn max_request_body_bytes(&self) -> usize {
        self.max_request_body_bytes
    }

    #[must_use]
    /// Returns the maximum response body size.
    pub const fn max_response_body_bytes(&self) -> usize {
        self.max_response_body_bytes
    }
}

impl Default for IdempotencyConfig {
    fn default() -> Self {
        Self {
            ttl: DEFAULT_IDEMPOTENCY_TTL,
            processing_ttl: DEFAULT_IDEMPOTENCY_PROCESSING_TTL,
            max_request_body_bytes: DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES,
            max_response_body_bytes: DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES,
            fingerprint_headers: Arc::default(),
        }
    }
}

#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Errors returned while constructing an idempotency policy.
pub enum IdempotencyConfigError {
    #[error("idempotency ttl must be greater than zero and fit the clock range")]
    /// The completed-response retention duration is invalid.
    InvalidTtl,
    #[error("idempotency processing_ttl must be greater than zero and fit the clock range")]
    /// The in-flight reservation duration is invalid.
    InvalidProcessingTtl,
    #[error("idempotency request body limit must be greater than zero")]
    /// The request body limit is invalid.
    InvalidRequestBodyLimit,
    #[error(
        "idempotency response body limit must be greater than zero and fit with stored headers"
    )]
    /// The response body limit is invalid.
    InvalidResponseBodyLimit,
}

impl ClassifyError for IdempotencyConfigError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidTtl => "idempotency_invalid_ttl",
            Self::InvalidProcessingTtl => "idempotency_invalid_processing_ttl",
            Self::InvalidRequestBodyLimit => "idempotency_invalid_request_body_limit",
            Self::InvalidResponseBodyLimit => "idempotency_invalid_response_body_limit",
        })
    }
}

pub(super) fn validate_idempotency_key(value: &str) -> Result<(), IdempotencyKeyError> {
    if value.is_empty() {
        return Err(IdempotencyKeyError::Empty);
    }
    if value.len() > MAX_IDEMPOTENCY_KEY_LENGTH {
        return Err(IdempotencyKeyError::TooLong {
            max: MAX_IDEMPOTENCY_KEY_LENGTH,
        });
    }
    if !value
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
    {
        return Err(IdempotencyKeyError::InvalidCharacters);
    }
    Ok(())
}

pub(super) fn hash_length_prefixed(hasher: &mut Sha256, value: &[u8]) {
    hasher.update(u64::try_from(value.len()).unwrap_or(u64::MAX).to_be_bytes());
    hasher.update(value);
}

pub(super) fn is_storable_response_header(name: &HeaderName) -> bool {
    if name.as_str() == IDEMPOTENCY_REPLAYED_HEADER_NAME {
        return false;
    }
    !matches!(
        name.as_str(),
        "connection"
            | "content-length"
            | "date"
            | "keep-alive"
            | "proxy-authenticate"
            | "proxy-authorization"
            | "server"
            | "set-cookie"
            | "te"
            | "trailer"
            | "transfer-encoding"
            | "upgrade"
    )
}