footing 0.1.13

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

use std::{fmt, time::Duration};

use async_trait::async_trait;
use axum::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 without an explicit scope
/// are rejected instead of treating unverified header bytes as an authorization
/// boundary.
#[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, 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,
}

#[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: Vec<u8>,
}

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: body.into(),
        }
    }

    #[must_use]
    /// Appends a replayable header, silently ignoring invalid or excluded values.
    ///
    /// This compatibility helper is deliberately lossy. Prefer
    /// [`Self::try_with_header`] when loading persisted data or accepting caller
    /// input so validation failures can be reported.
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        let _ = self.append_header(name.into(), value.into());
        self
    }

    /// 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> {
        self.append_header(name.into(), value.into())?;
        Ok(self)
    }

    fn append_header(&mut self, name: String, value: String) -> Result<(), IdempotencyHeaderError> {
        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(())
    }

    #[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(Debug, 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,
}

impl ClassifyError for IdempotencyStoreError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::InvalidCapacity | Self::InvalidExpiry => ErrorKind::Validation,
            Self::CapacityExceeded | Self::LockPoisoned => 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 => "idempotency_store_unavailable",
            Self::InconsistentRecord => "idempotency_record_inconsistent",
        })
    }
}

#[async_trait]
/// Storage abstraction for idempotency.
pub trait IdempotencyStore: Send + Sync {
    /// Atomically reserves `key` for one execution attempt.
    ///
    /// A successful reservation must retain enough capacity to commit either
    /// the configured application response or the middleware's small terminal
    /// failure response. This prevents storage pressure after execution from
    /// reopening a key whose side effects may already have happened.
    async fn reserve(
        &self,
        key: IdempotencyKey,
        request_hash: IdempotencyRequestHash,
        processing_ttl: Duration,
    ) -> Result<IdempotencyReservation, IdempotencyStoreError>;

    /// Atomically reserves `key` with an explicit response-capacity requirement.
    ///
    /// Stores with dynamic capacity accounting should override this method.
    /// The default preserves compatibility with stores whose regular
    /// reservation already guarantees the configured maximum response.
    async fn reserve_with_capacity(
        &self,
        key: IdempotencyKey,
        request_hash: IdempotencyRequestHash,
        processing_ttl: Duration,
        _response_capacity_bytes: usize,
    ) -> Result<IdempotencyReservation, IdempotencyStoreError> {
        self.reserve(key, request_hash, processing_ttl).await
    }

    /// Atomically turns the matching processing lease into a replayable result.
    ///
    /// While the lease is still valid, an error must leave its processing
    /// reservation intact. Removing it would allow an immediate retry after
    /// the protected operation may already have produced side effects.
    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, Copy, 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,
}

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> {
        if ttl.is_zero() {
            return Err(IdempotencyConfigError::InvalidTtl);
        }
        if processing_ttl.is_zero() {
            return Err(IdempotencyConfigError::InvalidProcessingTtl);
        }
        if max_request_body_bytes == 0 {
            return Err(IdempotencyConfigError::InvalidRequestBodyLimit);
        }
        if max_response_body_bytes == 0 {
            return Err(IdempotencyConfigError::InvalidResponseBodyLimit);
        }
        Ok(Self {
            ttl,
            processing_ttl,
            max_request_body_bytes,
            max_response_body_bytes,
        })
    }

    #[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,
        }
    }
}

#[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")]
    /// The completed-response retention duration is invalid.
    InvalidTtl,
    #[error("idempotency processing_ttl must be greater than zero")]
    /// 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")]
    /// 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"
    )
}