use std::time::{Duration, Instant};
use axum::http::HeaderName;
use serde::{Deserialize, Serialize};
use crate::{
http::{
DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES, DEFAULT_IDEMPOTENCY_PROCESSING_TTL,
DEFAULT_IDEMPOTENCY_TTL, DEFAULT_MAX_IDEMPOTENCY_STORED_HEADER_BYTES, IdempotencyConfig,
},
settings::{SettingsIssues, SettingsValidationError},
};
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct HttpIdempotencySettings {
pub enabled: bool,
#[serde(with = "crate::settings::human_duration")]
pub ttl: Duration,
#[serde(with = "crate::settings::human_duration")]
pub processing_ttl: Duration,
pub max_request_body_bytes: usize,
pub max_response_body_bytes: usize,
pub fingerprint_headers: Vec<String>,
}
impl Default for HttpIdempotencySettings {
fn default() -> Self {
Self {
enabled: false,
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: Vec::new(),
}
}
}
impl HttpIdempotencySettings {
#[must_use]
pub const fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
#[must_use]
pub const fn with_ttl(mut self, ttl: Duration) -> Self {
self.ttl = ttl;
self
}
#[must_use]
pub const fn with_processing_ttl(mut self, processing_ttl: Duration) -> Self {
self.processing_ttl = processing_ttl;
self
}
#[must_use]
pub const fn with_max_request_body_bytes(mut self, max_request_body_bytes: usize) -> Self {
self.max_request_body_bytes = max_request_body_bytes;
self
}
#[must_use]
pub const fn with_max_response_body_bytes(mut self, max_response_body_bytes: usize) -> Self {
self.max_response_body_bytes = max_response_body_bytes;
self
}
#[must_use]
pub fn with_fingerprint_headers(
mut self,
headers: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
self.fingerprint_headers = headers.into_iter().map(Into::into).collect();
self
}
pub(in crate::http::layers) fn build_at(
&self,
path: &str,
) -> Result<Option<IdempotencyConfig>, SettingsValidationError> {
if !self.enabled {
return Ok(None);
}
let mut issues = SettingsIssues::new();
let now = Instant::now();
issues.require(
!self.ttl.is_zero() && now.checked_add(self.ttl).is_some(),
format!("{path}.ttl"),
"must be greater than zero and fit the clock range when idempotency is enabled",
);
issues.require(
!self.processing_ttl.is_zero() && now.checked_add(self.processing_ttl).is_some(),
format!("{path}.processing_ttl"),
"must be greater than zero and fit the clock range when idempotency is enabled",
);
issues.require(
self.max_request_body_bytes > 0,
format!("{path}.max_request_body_bytes"),
"must be greater than zero when idempotency is enabled",
);
issues.require(
self.max_response_body_bytes > 0
&& self
.max_response_body_bytes
.checked_add(DEFAULT_MAX_IDEMPOTENCY_STORED_HEADER_BYTES)
.is_some(),
format!("{path}.max_response_body_bytes"),
"must be greater than zero and fit with stored headers when idempotency is enabled",
);
let mut fingerprint_headers = Vec::with_capacity(self.fingerprint_headers.len());
for (index, name) in self.fingerprint_headers.iter().enumerate() {
match HeaderName::try_from(name.as_str()) {
Ok(name) => fingerprint_headers.push(name),
Err(_) => issues.push(
format!("{path}.fingerprint_headers[{index}]"),
"must be a valid HTTP header name",
),
}
}
issues.into_result()?;
IdempotencyConfig::new(
self.ttl,
self.processing_ttl,
self.max_request_body_bytes,
self.max_response_body_bytes,
)
.map(|config| Some(config.with_fingerprint_headers(fingerprint_headers)))
.map_err(|error| {
use crate::http::IdempotencyConfigError;
let field = match error {
IdempotencyConfigError::InvalidTtl => "ttl",
IdempotencyConfigError::InvalidProcessingTtl => "processing_ttl",
IdempotencyConfigError::InvalidRequestBodyLimit => "max_request_body_bytes",
IdempotencyConfigError::InvalidResponseBodyLimit => "max_response_body_bytes",
};
SettingsValidationError::single(format!("{path}.{field}"), error.to_string())
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::{HttpMiddlewareSettings, HttpMiddlewareStack, MemoryIdempotencyStore};
use axum::{
Router,
body::Body,
http::{Request, StatusCode},
routing::post,
};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use tower::ServiceExt;
#[test]
fn fingerprint_settings_validate_all_names_and_canonicalize_duplicates() {
let settings: HttpIdempotencySettings = serde_json::from_value(serde_json::json!({
"enabled": true,
"fingerprint_headers": ["Prefer", "If-Match", "prefer"],
}))
.unwrap();
let config = settings.build_at("http.idempotency").unwrap().unwrap();
assert_eq!(config.fingerprint_headers(), ["if-match", "prefer"]);
let encoded = serde_json::to_value(&settings).unwrap();
assert_eq!(
encoded["fingerprint_headers"],
serde_json::json!(["Prefer", "If-Match", "prefer"])
);
let invalid = settings.with_fingerprint_headers(["bad header", "", "if-match"]);
let error = invalid.build_at("http.idempotency").unwrap_err();
let paths: Vec<_> = error.issues().iter().map(|issue| issue.path()).collect();
assert_eq!(
paths,
[
"http.idempotency.fingerprint_headers[0]",
"http.idempotency.fingerprint_headers[1]"
]
);
}
#[tokio::test]
async fn configured_condition_header_replays_only_the_same_request() {
let config = HttpMiddlewareSettings::new()
.with_idempotency(
HttpIdempotencySettings::default()
.with_enabled(true)
.with_fingerprint_headers(["if-match"]),
)
.build()
.unwrap();
let executions = Arc::new(AtomicUsize::new(0));
let calls = executions.clone();
let app = HttpMiddlewareStack::builder(config)
.with_idempotency_store(Arc::new(MemoryIdempotencyStore::default()))
.build()
.unwrap()
.apply(Router::new().route(
"/orders",
post(move || {
let calls = calls.clone();
async move {
calls.fetch_add(1, Ordering::SeqCst);
StatusCode::CREATED
}
}),
));
for (condition, expected, replayed) in [
("\"version-1\"", StatusCode::CREATED, false),
("\"version-1\"", StatusCode::CREATED, true),
("\"version-2\"", StatusCode::CONFLICT, false),
] {
let response = app
.clone()
.oneshot(
Request::post("/orders")
.header("idempotency-key", "same")
.header("if-match", condition)
.body(Body::from("same operation"))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), expected);
assert_eq!(
response.headers().contains_key("idempotency-replayed"),
replayed
);
}
assert_eq!(executions.load(Ordering::SeqCst), 1);
}
}