use std::{fmt, time::Duration};
use async_trait::async_trait;
use axum::http::{HeaderName, HeaderValue, StatusCode};
use sha2::{Digest, Sha256};
use thiserror::Error;
use uuid::Uuid;
use crate::result::{ClassifyError, ErrorKind};
pub const IDEMPOTENCY_KEY_HEADER_NAME: &str = "idempotency-key";
pub const IDEMPOTENCY_REPLAYED_HEADER_NAME: &str = "idempotency-replayed";
pub const MAX_IDEMPOTENCY_KEY_LENGTH: usize = 128;
pub const DEFAULT_IDEMPOTENCY_TTL: Duration = Duration::from_secs(60 * 60 * 24);
pub const DEFAULT_IDEMPOTENCY_PROCESSING_TTL: Duration = Duration::from_secs(5 * 60);
pub const DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES: usize = 1024 * 1024;
pub const DEFAULT_MAX_IDEMPOTENCY_RECORDS: usize = 1_024;
pub const DEFAULT_MAX_IDEMPOTENCY_STORED_RESPONSE_BYTES: usize = 64 * 1024 * 1024;
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"}}"#;
#[derive(Clone, PartialEq, Eq)]
pub struct IdempotencyScope(pub(super) [u8; 32]);
impl IdempotencyScope {
#[must_use]
pub fn new(value: impl AsRef<[u8]>) -> Self {
Self(Sha256::digest(value.as_ref()).into())
}
#[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])")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IdempotencyRequestPolicy {
Disabled,
HeaderOptional,
Required,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct IdempotencyKey(pub(super) String);
impl IdempotencyKey {
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]
pub fn parse(value: &str) -> Option<Self> {
Self::new(value).ok()
}
#[must_use]
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]
pub enum IdempotencyKeyError {
#[error("idempotency key must not be empty")]
Empty,
#[error("idempotency key must be less than or equal to {max} bytes")]
TooLong {
#[doc = "The configured upper bound."]
max: usize,
},
#[error("idempotency key contains unsupported characters")]
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]
pub struct IdempotencyRequestHash(pub(super) String);
impl IdempotencyRequestHash {
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]
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]
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]
pub fn new(status: StatusCode, body: impl Into<Vec<u8>>) -> Self {
Self {
status,
headers: Vec::new(),
body: body.into(),
}
}
#[must_use]
pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
let _ = self.append_header(name.into(), value.into());
self
}
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]
pub const fn status(&self) -> StatusCode {
self.status
}
#[must_use]
pub fn body(&self) -> &[u8] {
&self.body
}
#[must_use]
pub fn headers(&self) -> &[(String, String)] {
&self.headers
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum IdempotencyHeaderError {
#[error("invalid idempotency response header name")]
InvalidName,
#[error("invalid idempotency response header value")]
InvalidValue,
#[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]
pub enum IdempotencyReservation {
Reserved(IdempotencyLease),
Processing,
Replay(StoredIdempotencyResponse),
Conflict,
}
#[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]
pub fn new() -> Self {
Self(Uuid::now_v7())
}
#[must_use]
pub const fn to_bytes(self) -> [u8; 16] {
*self.0.as_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, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IdempotencyState {
Processing,
Completed,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum IdempotencyStoreError {
#[error("idempotency store capacity must be greater than zero")]
InvalidCapacity,
#[error("idempotency store capacity is exhausted")]
CapacityExceeded,
#[error("idempotency record expiry is out of range")]
InvalidExpiry,
#[error("idempotency store lock is poisoned")]
LockPoisoned,
#[error("idempotency store record is inconsistent")]
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]
pub trait IdempotencyStore: Send + Sync {
async fn reserve(
&self,
key: IdempotencyKey,
request_hash: IdempotencyRequestHash,
processing_ttl: Duration,
) -> Result<IdempotencyReservation, IdempotencyStoreError>;
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
}
async fn commit(
&self,
key: &IdempotencyKey,
lease: IdempotencyLease,
response: StoredIdempotencyResponse,
retention_ttl: Duration,
) -> Result<(), IdempotencyStoreError>;
async fn abort(
&self,
key: &IdempotencyKey,
lease: IdempotencyLease,
) -> Result<(), IdempotencyStoreError>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
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 {
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]
pub const fn ttl(&self) -> Duration {
self.ttl
}
#[must_use]
pub const fn processing_ttl(&self) -> Duration {
self.processing_ttl
}
#[must_use]
pub const fn max_request_body_bytes(&self) -> usize {
self.max_request_body_bytes
}
#[must_use]
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]
pub enum IdempotencyConfigError {
#[error("idempotency ttl must be greater than zero")]
InvalidTtl,
#[error("idempotency processing_ttl must be greater than zero")]
InvalidProcessingTtl,
#[error("idempotency request body limit must be greater than zero")]
InvalidRequestBodyLimit,
#[error("idempotency response body limit must be greater than zero")]
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"
)
}