Skip to main content

naidempotency_redis/
lib.rs

1//! 幂等 store 的 Redis 后端。
2//!
3//! 实现 [`naidempotency::IdempotencyStore`],**response-cache 语义**(:非资金/幂等重放场景;
4//! 资金强幂等应落业务 DB 唯一键同事务,见 `naidempotency-mysql`)。
5//!
6//! - `begin`:`SET key <inflight> NX PX <ttl>` **原子占位**——成功=首次;已存在则 `GET` 现有值裁决
7//!   重放/并发/指纹冲突。in-flight 键带较短 TTL,进程崩溃后自动过期使重试可继续。
8//! - `complete`:二进制 `EVAL` **原子 check-and-set**——仅当现值仍 in-flight 才覆写为 completed(保留
9//!   原 fingerprint),带较长 TTL 作重放窗口。避免 GET-then-SET 的覆写竞态。
10//!
11//! 所有键经 [`RedisClient::execute_raw`] 直发(不走 nadis namespace 前缀,SET/GET/EVAL 完全一致);
12//! 底层错误一律脱敏为 [`IdempotencyError`](不回显命令/凭据/请求体)。
13//!
14//! 值编码(二进制,Redis 值二进制安全):in-flight 为
15//! `[state:1][fingerprint:32][lease:16]`;completed 保存指纹与 status/header/body,响应上限由调用方约束。
16
17#![forbid(unsafe_code)]
18
19use std::sync::Arc;
20use std::time::Duration;
21
22use async_trait::async_trait;
23use nadis::RedisClient;
24use naidempotency::{
25    ExecutionLease, IdempotencyError, IdempotencyKey, IdempotencyOutcome, IdempotencyStore,
26    RequestFingerprint, StoredResponse,
27};
28use sha2::{Digest as _, Sha256};
29
30/// 记录状态:进行中。
31const STATE_IN_FLIGHT: u8 = 0;
32/// 记录状态:已完成。
33const STATE_COMPLETED: u8 = 1;
34
35/// in-flight 占位默认 TTL(应大于最长请求处理时间;崩溃后自动过期解锁重试)。
36const DEFAULT_INFLIGHT_TTL: Duration = Duration::from_secs(5 * 60);
37/// completed 记录默认 TTL(重放窗口)。
38const DEFAULT_COMPLETED_TTL: Duration = Duration::from_secs(24 * 3600);
39
40/// complete 的原子 Lua:现值必须与调用方持有的完整 in-flight(fingerprint + lease)逐字节一致。
41const COMPLETE_LUA: &str = "\
42local v = redis.call('GET', KEYS[1]) \
43if not v then return 0 end \
44if v ~= ARGV[1] then return 0 end \
45local fp = string.sub(v, 2, 33) \
46redis.call('SET', KEYS[1], string.char(1) .. fp .. ARGV[2], 'PX', ARGV[3]) \
47return 1";
48
49/// 只删除仍属于调用方的 in-flight 租约。
50const ABORT_LUA: &str = "\
51local v = redis.call('GET', KEYS[1]) \
52if not v or v ~= ARGV[1] then return 0 end \
53return redis.call('DEL', KEYS[1])";
54
55/// Redis 幂等 store。持注入的 [`RedisClient`];可配 in-flight / completed 两档 TTL。
56#[derive(Clone)]
57pub struct RedisIdempotencyStore {
58    client: Arc<RedisClient>,
59    inflight_ttl: Duration,
60    completed_ttl: Duration,
61}
62
63impl RedisIdempotencyStore {
64    /// 业务作用:用默认 TTL(in-flight 5min / completed 24h)构造。
65    ///
66    /// 参数说明:
67    /// - `client`:用于直发幂等 SET、GET 和 EVAL 的共享 Redis 客户端。
68    ///
69    /// 返回:返回持有该客户端且使用默认两档 TTL 的 store,不发送 Redis 命令或验证连接。
70    pub fn new(client: Arc<RedisClient>) -> Self {
71        Self {
72            client,
73            inflight_ttl: DEFAULT_INFLIGHT_TTL,
74            completed_ttl: DEFAULT_COMPLETED_TTL,
75        }
76    }
77
78    /// 业务作用:用自定义 TTL 构造(in-flight 应大于最长处理时间;completed 为重放窗口)。
79    ///
80    /// 参数说明:
81    /// - `client`:用于直发命令的共享 Redis 客户端。
82    /// - `inflight_ttl`:在途占位过期时间,调用方应覆盖最长处理时间。
83    /// - `completed_ttl`:完成响应的重放保留窗口。
84    ///
85    /// 返回:返回保存客户端与 TTL 原值的 store;构造时不校验 TTL,首次相关操作才验证可转换的毫秒范围。
86    pub fn with_ttls(
87        client: Arc<RedisClient>,
88        inflight_ttl: Duration,
89        completed_ttl: Duration,
90    ) -> Self {
91        Self {
92            client,
93            inflight_ttl,
94            completed_ttl,
95        }
96    }
97
98    /// 业务作用:按完整幂等命名空间构造 Redis 键;普通段采用 U+001F 分隔,含分隔符的输入采用长度定界摘要避免分段歧义。
99    ///
100    /// 参数说明:
101    /// - `key`:需要隔离的租户、主体、路由与客户端幂等键。
102    ///
103    /// 返回:无分隔符时返回 idem: 与四段原文的分隔组合;任一段含 U+001F 时返回 idem:v2: 与带长度输入的 SHA-256 摘要。不会套用客户端 namespace,也不验证各段业务合法性。
104    fn redis_key(key: &IdempotencyKey) -> String {
105        const SEPARATOR: char = '\u{1f}';
106        let components = [
107            key.tenant.as_str(),
108            key.subject.as_str(),
109            key.route_id.as_str(),
110            key.client_key.as_str(),
111        ];
112        if components
113            .iter()
114            .all(|component| !component.contains(SEPARATOR))
115        {
116            return format!(
117                "idem:{}{SEPARATOR}{}{SEPARATOR}{}{SEPARATOR}{}",
118                key.tenant, key.subject, key.route_id, key.client_key
119            );
120        }
121        let mut digest = Sha256::new();
122        for component in components.map(str::as_bytes) {
123            digest.update((component.len() as u64).to_be_bytes());
124            digest.update(component);
125        }
126        let digest = digest.finalize();
127        let mut encoded = String::with_capacity("idem:v2:".len() + digest.len() * 2);
128        encoded.push_str("idem:v2:");
129        for byte in digest {
130            use std::fmt::Write as _;
131            let _ = write!(encoded, "{byte:02x}");
132        }
133        encoded
134    }
135}
136
137/// 业务作用:把过期时长转为 Redis 正 i64 毫秒范围,拒绝零毫秒与数值溢出。
138///
139/// 参数说明:
140/// - `ttl`:待写入 Redis PX 参数的持续时间。
141///
142/// 返回:向下取整为毫秒后处于 1..=i64::MAX 时成功;不足一毫秒、零或超出范围时报错。小于一毫秒的余数会舍弃。
143fn ttl_millis(ttl: Duration) -> Result<u64, IdempotencyError> {
144    let millis =
145        u64::try_from(ttl.as_millis()).map_err(|_| IdempotencyError::new("invalid ttl"))?;
146    if millis == 0 || millis > i64::MAX as u64 {
147        return Err(IdempotencyError::new("invalid ttl"));
148    }
149    Ok(millis)
150}
151
152/// 业务作用:in-flight 值编码:`[0][fingerprint:32][lease:16]`。
153///
154/// 参数说明:
155/// - `fingerprint`:本次请求的 32 字节等价类指纹。
156/// - `lease`:调用方生成的 16 字节执行租约。
157///
158/// 返回:返回恰好 49 字节的状态、指纹与租约编码,不生成随机值或取得 Redis 占位。
159fn encode_inflight(fingerprint: RequestFingerprint, lease: ExecutionLease) -> Vec<u8> {
160    let mut value = Vec::with_capacity(49);
161    value.push(STATE_IN_FLIGHT);
162    value.extend_from_slice(&fingerprint.0);
163    value.extend_from_slice(&lease.0);
164    value
165}
166
167/// 业务作用:编码幂等请求已完成响应的二进制后缀,供状态记录持久保存。
168///
169/// 参数说明:
170/// - `response`:需要重放的状态码、响应头和正文。
171///
172/// 返回:成功返回依次含 2 字节小端状态码、4 字节小端头部 JSON 长度、头部 JSON 与原正文的字节;头部序列化或长度超出 u32 时失败,不写入 Redis。
173fn encode_completed_suffix(response: &StoredResponse) -> Result<Vec<u8>, IdempotencyError> {
174    let headers = serde_json::to_vec(&response.headers).map_err(map_err)?;
175    let header_len =
176        u32::try_from(headers.len()).map_err(|_| IdempotencyError::new("headers too large"))?;
177    let mut suffix = Vec::with_capacity(6 + headers.len() + response.body.len());
178    suffix.extend_from_slice(&response.status.to_le_bytes());
179    suffix.extend_from_slice(&header_len.to_le_bytes());
180    suffix.extend_from_slice(&headers);
181    suffix.extend_from_slice(&response.body);
182    Ok(suffix)
183}
184
185/// 解出的现有记录。
186struct Decoded {
187    state: u8,
188    fingerprint: RequestFingerprint,
189    response: Option<StoredResponse>,
190}
191
192/// 业务作用:解码存储值;长度不足视为损坏返回 `None`。
193///
194/// 参数说明:
195/// - `bytes`:Redis GET 得到的完整二进制记录。
196///
197/// 返回:有效在途长度或可解码完成状态时返回指纹与可选响应;未知状态、长度、状态码或头部 JSON 不合法时返回 None。无正文容量或 header 白名单检查,不验证租约内容。
198fn decode(bytes: &[u8]) -> Option<Decoded> {
199    if bytes.len() < 33 {
200        return None;
201    }
202    let state = bytes[0];
203    if !matches!(state, STATE_IN_FLIGHT | STATE_COMPLETED) {
204        return None;
205    }
206    if state == STATE_IN_FLIGHT && bytes.len() != 49 {
207        return None;
208    }
209    let fingerprint = RequestFingerprint(bytes[1..33].try_into().ok()?);
210    let response = if state == STATE_COMPLETED {
211        if bytes.len() < 39 {
212            return None;
213        }
214        let status = u16::from_le_bytes(bytes[33..35].try_into().ok()?);
215        if !(100..=599).contains(&status) {
216            return None;
217        }
218        let headers_len = u32::from_le_bytes(bytes[35..39].try_into().ok()?) as usize;
219        let body_start = 39usize.checked_add(headers_len)?;
220        if body_start > bytes.len() {
221            return None;
222        }
223        let headers = serde_json::from_slice(&bytes[39..body_start]).ok()?;
224        Some(StoredResponse {
225            status,
226            body: bytes[body_start..].to_vec(),
227            headers,
228        })
229    } else {
230        None
231    };
232    Some(Decoded {
233        state,
234        fingerprint,
235        response,
236    })
237}
238
239#[async_trait]
240impl IdempotencyStore for RedisIdempotencyStore {
241    /// 业务作用:用 `SET NX PX` 原子占位;已有值按二进制状态裁决重放、在途或指纹冲突。
242    ///
243    /// 参数说明:
244    /// - `key`:租户、主体、路由与客户端幂等键组成的完整命名空间。
245    /// - `fingerprint`:本次请求等价类的固定指纹。
246    /// - `lease`:调用方生成并在完成或放弃时原样携带的执行租约。
247    ///
248    /// 返回:占位成功返回首次执行;已有值按指纹与状态裁决,SET 与 GET 之间过期时保守返回在途。TTL、记录损坏或 I/O 失败返回错误,I/O 失败可能留下已执行的占位,不保证后端持久化或业务 exactly-once。
249    async fn begin(
250        &self,
251        key: &IdempotencyKey,
252        fingerprint: RequestFingerprint,
253        lease: ExecutionLease,
254    ) -> Result<IdempotencyOutcome, IdempotencyError> {
255        let redis_key = Self::redis_key(key);
256
257        // 原子占位:SET key <inflight> NX PX ttl。成功=首次。
258        let mut set = redis::cmd("SET");
259        set.arg(&redis_key)
260            .arg(encode_inflight(fingerprint, lease).as_slice())
261            .arg("NX")
262            .arg("PX")
263            .arg(ttl_millis(self.inflight_ttl)?);
264        let claimed: Option<String> = self.client.execute_raw(&set).await.map_err(map_err)?;
265        if claimed.is_some() {
266            return Ok(IdempotencyOutcome::FirstExecution);
267        }
268
269        // 首次占位未取得时只能读取现值裁决;不从相同请求指纹推导当前执行权。
270        let mut get = redis::cmd("GET");
271        get.arg(&redis_key);
272        let existing: Option<Vec<u8>> = self.client.execute_raw(&get).await.map_err(map_err)?;
273
274        // SET-NX 与 GET 之间键过期(极罕见):保守判并发,让上层重试(下次占位即首次)。
275        let Some(bytes) = existing else {
276            return Ok(IdempotencyOutcome::ConcurrentInFlight);
277        };
278        let Some(decoded) = decode(&bytes) else {
279            return Err(IdempotencyError::new("corrupt idempotency record"));
280        };
281        if decoded.fingerprint != fingerprint {
282            return Ok(IdempotencyOutcome::FingerprintConflict);
283        }
284        if decoded.state == STATE_COMPLETED {
285            let response = decoded
286                .response
287                .ok_or_else(|| IdempotencyError::new("corrupt idempotency record"))?;
288            Ok(IdempotencyOutcome::Replay(response))
289        } else {
290            Ok(IdempotencyOutcome::ConcurrentInFlight)
291        }
292    }
293
294    /// 业务作用:通过 Lua compare-and-set 将仍匹配 fingerprint/lease 的在途值替换为完成值。
295    ///
296    /// 参数说明:
297    /// - `key`:租户、主体、路由与客户端幂等键组成的完整命名空间。
298    /// - `fingerprint`:本次请求等价类的固定指纹。
299    /// - `lease`:调用方生成并在完成或放弃时原样携带的执行租约。
300    /// - `response`:需要保存重放的响应;大小、状态码和 header 白名单由调用方限制。
301    ///
302    /// 返回:原子比较整段 InFlight 编码后写入完成记录并重设 TTL,脚本返回 1 时 true,其它数值 false;编码、TTL 或 I/O 失败返回错误,I/O 失败不能证明远端未写入。
303    async fn complete(
304        &self,
305        key: &IdempotencyKey,
306        fingerprint: RequestFingerprint,
307        lease: ExecutionLease,
308        response: StoredResponse,
309    ) -> Result<bool, IdempotencyError> {
310        let redis_key = Self::redis_key(key);
311        // 必须同时匹配指纹和租约,防止过期后重新占位的新请求被旧持有者覆盖。
312        // 二进制 ARGV 经 execute_raw 直发(nadis eval 只收 &str,承载不了任意 body 字节)。
313        let mut eval = redis::cmd("EVAL");
314        eval.arg(COMPLETE_LUA)
315            .arg(1)
316            .arg(&redis_key)
317            .arg(encode_inflight(fingerprint, lease).as_slice())
318            .arg(encode_completed_suffix(&response)?.as_slice())
319            .arg(ttl_millis(self.completed_ttl)?);
320        let completed: i64 = self.client.execute_raw(&eval).await.map_err(map_err)?;
321        Ok(completed == 1)
322    }
323
324    /// 业务作用:通过 Lua compare-and-delete 释放仍属于调用方的在途占位。
325    ///
326    /// 参数说明:
327    /// - `key`:租户、主体、路由与客户端幂等键组成的完整命名空间。
328    /// - `fingerprint`:本次请求等价类的固定指纹。
329    /// - `lease`:调用方生成并在完成或放弃时原样携带的执行租约。
330    ///
331    /// 返回:脚本原子删除完全匹配的 InFlight,返回 1 时 true,其它数值 false;I/O 错误返回固定 store 错误,远端是否已删除可能未知,不撤销业务副作用。
332    async fn abort(
333        &self,
334        key: &IdempotencyKey,
335        fingerprint: RequestFingerprint,
336        lease: ExecutionLease,
337    ) -> Result<bool, IdempotencyError> {
338        let redis_key = Self::redis_key(key);
339        // 放弃只能删除本次完整租约仍持有的占位,不能清除重新占位者或完成响应。
340        let mut eval = redis::cmd("EVAL");
341        eval.arg(ABORT_LUA)
342            .arg(1)
343            .arg(&redis_key)
344            .arg(encode_inflight(fingerprint, lease).as_slice());
345        let deleted: i64 = self.client.execute_raw(&eval).await.map_err(map_err)?;
346        Ok(deleted == 1)
347    }
348}
349
350/// 业务作用:把任意底层错误映射为脱敏的 [`IdempotencyError`](绝不回显命令/凭据/请求体)。
351///
352/// 参数说明:
353/// - `_error`:仅用于触发错误分类、不向公开错误转存的底层值。
354///
355/// 返回:丢弃输入错误并返回固定 redis error,不保留后端文本。
356fn map_err<E>(_error: E) -> IdempotencyError {
357    IdempotencyError::new("redis error")
358}