Skip to main content

IdempotencyCache

Struct IdempotencyCache 

Source
pub struct IdempotencyCache { /* private fields */ }
Expand description

订单幂等 cache。线程安全(DashMap + Instant)。

v1.4.106 codex 0920 F1 (P1) namespace fix: cache key 必须 namespace 隔离 跨 (endpoint, caller_key_id, acc_id, op). 否则:

  1. Cross-pollination: PlaceOrder 后 ModifyOrder 用同一 Idempotency-Key 会拿回 PlaceOrder response (严重交易 bug —— 用户以为改完了但实际没发).
  2. Cross-account leak: 不同 caller (key_id A vs B) 用同一 key 会跨账户 串 response (隐私 + 资金安全).
  3. Cross-acc/env leak: 同 caller 在 acc_id=A 下单后立刻在 acc_id=B 用 同 key 改单, 会拿到 acc_id=A 的 PlaceOrder response.

Namespace 设计: endpoint|caller|acc_id|op|raw_key

  • endpoint = place_order / modify_order / cancel_order / reconfirm_order
  • caller = caller_key_id (Some) 或 <no_key> (TCP/legacy)
  • acc_id = c2s.header.acc_id (u64 decimal)
  • op = PLACE / MODIFY=N / CANCEL / RECONFIRM=N (etc.)
  • raw_key = 用户 Idempotency-Key 或 tcp-pkt-{conn_id}-{serial_no}

同时所有 5 轴都不同的请求, key 不会撞.

Implementations§

Source§

impl IdempotencyCache

Source

pub fn new(ttl_secs: u64) -> Self

Source

pub fn with_default_ttl() -> Self

默认 TTL。

Source

pub fn get(&self, key: &str) -> Option<Vec<u8>>

查询 cache:

  • Some(cached_response):TTL 内命中,返回缓存结果
  • None:未命中 / 已过期(调用方应真执行 + Self::put

⚠️ 过期的 entry 不在此清理(避免抢锁),由周期性 Self::purge_expired 清。cache hit 判断只看 inserted_at.elapsed() < ttl

Source

pub fn put(&self, key: String, response: Vec<u8>)

插入新结果。相同 key 覆盖(但实际上调用方应在 get=None 之后才 put, 避免并发两次 put 覆盖)。

Source

pub fn put_finished_response( &self, key: &str, guard: &mut Option<IdempotencyFlightGuard<'_>>, response: Vec<u8>, )

Store the terminal response for a key that was guarded by Self::begin.

Call sites keep the fallback put path because older code may still construct a cache key without acquiring a guard. New trade-write paths should normally pass the guard returned by begin.

Source

pub async fn begin(&self, key: String) -> IdempotencyBegin<'_>

Per-key singleflight gate for idempotent trade writes.

The old pattern was get -> await backend -> put, so two concurrent requests with the same key could both miss and both execute the backend write. This method serializes executions for the same namespaced key: followers wait until the leader stores a response or drops the guard.

Source

pub fn purge_expired(&self) -> usize

清理已过期 entry。建议 spawn 一个 tokio::time::interval 每 60s 调一次。 即使不调也无正确性问题(get 自己会判 TTL),只是 cache 内存会累积。

Source

pub fn len(&self) -> usize

当前 cache 大小(含未过期 + 已过期未清理的)。仅用于 metrics。

Source

pub fn is_empty(&self) -> bool

Trait Implementations§

Source§

impl Default for IdempotencyCache

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more