hyperlane-plugin-idempotency 23.1.0

A production HTTP Idempotency-Key middleware plugin for the Hyperlane framework featuring XxHash3_64 request fingerprinting (422 mismatch), 64-way sharded bounded InMemoryIdempotencyStore + async IdempotencyStore trait, InFlight concurrent duplicate guard (409 Conflict), and zero-copy cached response replay with Idempotent-Replayed headers.
Documentation
use super::*;

/// Cached idempotent HTTP response carrying pre-serialized zero-copy replay wire bytes.
#[derive(Clone, Data, Debug)]
pub struct StoredIdempotentResponse {
    /// HTTP status code recorded from the original execution.
    #[get(type(copy))]
    pub(crate) status_code: usize,
    /// Response headers preserved from the original execution.
    pub(crate) headers: Vec<(String, String)>,
    /// Response payload bytes.
    pub(crate) body: Vec<u8>,
    /// Pre-serialized HTTP wire bytes including `Idempotent-Replayed: true` for zero-copy replay.
    pub(crate) replayed_wire: Vec<u8>,
    /// Unix epoch timestamp in milliseconds when stored.
    #[get(type(copy))]
    pub(crate) stored_at_ms: u64,
}

/// Configuration controlling TTLs, memory limits, methods, and required prefixes for [`IdempotencyPlugin`].
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct IdempotencyConfig {
    /// Incoming header name carrying the client idempotency key (default `"idempotency-key"`).
    pub(crate) header_name: String,
    /// Cached response TTL in milliseconds.
    #[get(type(copy))]
    pub(crate) ttl_ms: u64,
    /// Maximum duration an `InFlight` guard stays locked if abandoned.
    #[get(type(copy))]
    pub(crate) in_flight_ttl_ms: u64,
    /// Maximum tracked keys across all 64 shards.
    #[get(type(copy))]
    pub(crate) max_entries: usize,
    /// Maximum total memory budget across all 64 shards in bytes.
    #[get(type(copy))]
    pub(crate) max_bytes: usize,
    /// Maximum individual response body length cached for replay in bytes.
    #[get(type(copy))]
    pub(crate) max_body_bytes: usize,
    /// Maximum accepted byte length for the `Idempotency-Key` header.
    #[get(type(copy))]
    pub(crate) max_key_len: usize,
    /// HTTP methods subject to idempotency enforcement (default `POST`/`PUT`/`PATCH`/`DELETE`).
    pub(crate) methods: Vec<Method>,
    /// Optional path prefixes where missing `Idempotency-Key` returns `400 Bad Request`.
    pub(crate) require_key_prefixes: Vec<String>,
    /// Whether to cache `5xx` server error responses (default `false` so callers may safely retry).
    #[get(type(copy))]
    pub(crate) cache_server_errors: bool,
}

/// One record inside a shard of [`InMemoryIdempotencyStore`].
#[derive(Clone)]
pub(crate) struct IdempotencySlot {
    /// `XxHash3_64` fingerprint of `(method, path, body)`.
    pub(crate) fingerprint: u64,
    /// Current slot state (`InFlight` or `Completed`).
    pub(crate) state: IdempotencySlotState,
    /// Expiration timestamp in Unix epoch milliseconds.
    pub(crate) expires_at_ms: u64,
    /// Approximate memory footprint in bytes.
    pub(crate) footprint_bytes: usize,
}

/// Cache-line-padded lock-striped shard preventing false sharing between adjacent shards.
#[repr(align(64))]
pub(crate) struct IdempotencyShard {
    /// Per-shard read-write locked hash table.
    pub(crate) map: RwLock<HashMapXxHash3_64<String, IdempotencySlot>>,
}

/// Shared interior state of [`InMemoryIdempotencyStore`].
pub(crate) struct InMemoryIdempotencyStoreInner {
    /// Maximum tracked keys across all 64 shards.
    pub(crate) max_entries: usize,
    /// Maximum total byte footprint across all 64 shards.
    pub(crate) max_bytes: usize,
    /// Lock-free active entry count.
    pub(crate) entry_count: AtomicUsize,
    /// Lock-free approximate byte usage.
    pub(crate) total_bytes: AtomicUsize,
    /// 64-way lock-striped key tables.
    pub(crate) shards: Box<[IdempotencyShard; IDEMPOTENCY_SHARD_COUNT]>,
}

/// High-concurrency 64-way sharded bounded in-memory [`IdempotencyStore`].
#[derive(Clone)]
pub struct InMemoryIdempotencyStore {
    /// Shared sharded store interior.
    pub(crate) inner: Arc<InMemoryIdempotencyStoreInner>,
}

/// Interior RAII guard ensuring abandoned `InFlight` locks release on panic, early reject, or drop.
pub(crate) struct IdempotencyInFlightGuardInner {
    /// Atomic completion flag preventing cleanup once [`IdempotencyResponseHook`] finishes.
    pub(crate) settled: AtomicBool,
    /// Scoped storage key (`"<method>|<path>|<client_key>"`).
    pub(crate) storage_key: String,
    /// Request `(method, path, body)` fingerprint.
    pub(crate) fingerprint: u64,
    /// Backing store notified on early abandonment.
    pub(crate) store: Arc<dyn IdempotencyStore>,
}

/// Leak-proof RAII guard stored in Hyperlane [`Context`] under [`ATTR_IDEMPOTENCY_GUARD`].
#[derive(Clone)]
pub struct IdempotencyInFlightGuard {
    /// Shared single-settlement guard state.
    pub(crate) inner: Arc<IdempotencyInFlightGuardInner>,
}

/// Process-wide [`IdempotencyPlugin`] singleton holding policy, store, and prebuilt error wire buffers.
#[derive(Clone)]
pub struct IdempotencyPlugin {
    /// Active idempotency configuration.
    pub(crate) config: IdempotencyConfig,
    /// Precomputed bitmask of guarded standard HTTP methods for `O(1)` dispatch.
    pub(crate) guarded_method_mask: u16,
    /// `true` when `config.methods` contains at least one `Method::Unknown` variant.
    pub(crate) has_unknown_method: bool,
    /// Normalized prefixes requiring an explicit `Idempotency-Key`.
    pub(crate) require_prefixes: Box<[String]>,
    /// Pluggable backing store.
    pub(crate) store: Arc<dyn IdempotencyStore>,
    /// Direct zero-boxing handle when initialized with the built-in [`InMemoryIdempotencyStore`].
    pub(crate) local_store: Option<InMemoryIdempotencyStore>,
    /// Prebuilt `400 Bad Request` wire bytes for missing/invalid keys.
    pub(crate) prebuilt_bad_key_wire: Vec<u8>,
    /// Prebuilt `409 Conflict` + `Retry-After: 1` wire bytes for concurrent duplicates.
    pub(crate) prebuilt_in_flight_wire: Vec<u8>,
    /// Prebuilt `422 Unprocessable Entity` wire bytes for payload fingerprint mismatches.
    pub(crate) prebuilt_mismatch_wire: Vec<u8>,
}

/// Opt-in request middleware validating `Idempotency-Key`, checking fingerprints, and replaying cached responses.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::request_middleware(-78)]
pub struct IdempotencyRequestHook;

/// Opt-in response middleware storing completed responses and prebuilding zero-copy replay wire bytes.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::response_middleware(-60)]
pub struct IdempotencyResponseHook;