use crate::{DbError, RedisClient, RedisValue, Result};
use redis::FromRedisValue;
use std::time::Duration;
pub struct RedisTransaction {
client: RedisClient,
pipe: redis::Pipeline,
watched_keys: Vec<String>,
}
fn is_watch_conflict(raw: &redis::Value, has_watched_keys: bool) -> bool {
has_watched_keys && matches!(raw, redis::Value::Nil)
}
fn transaction_backoff(base_ms: u64, retries: u32) -> Duration {
Duration::from_millis(base_ms.saturating_mul(u64::from(retries)))
}
impl RedisTransaction {
pub fn new(client: RedisClient) -> Self {
let mut pipe = redis::pipe();
pipe.atomic();
Self {
client,
pipe,
watched_keys: Vec::new(),
}
}
pub fn watch(&mut self, keys: &[String]) -> &mut Self {
self.watched_keys.extend_from_slice(keys);
self
}
pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
self.pipe.set(key.into(), value.into());
self
}
pub fn get(&mut self, key: impl Into<String>) -> &mut Self {
self.pipe.get(key.into());
self
}
pub fn del(&mut self, keys: &[String]) -> &mut Self {
self.pipe.del(keys);
self
}
pub fn incr(&mut self, key: impl Into<String>) -> &mut Self {
self.pipe.incr(key.into(), 1);
self
}
pub fn decrby(&mut self, key: impl Into<String>, decrement: i64) -> &mut Self {
self.pipe.decr(key.into(), decrement);
self
}
pub fn hset(
&mut self,
key: impl Into<String>,
field: impl Into<String>,
value: impl Into<String>,
) -> &mut Self {
self.pipe.hset(key.into(), field.into(), value.into());
self
}
pub fn hget(&mut self, key: impl Into<String>, field: impl Into<String>) -> &mut Self {
self.pipe.hget(key.into(), field.into());
self
}
pub fn lpush(&mut self, key: impl Into<String>, values: &[String]) -> &mut Self {
if !values.is_empty() {
self.pipe.lpush(key.into(), values);
}
self
}
pub fn rpush(&mut self, key: impl Into<String>, values: &[String]) -> &mut Self {
if !values.is_empty() {
self.pipe.rpush(key.into(), values);
}
self
}
pub fn sadd(&mut self, key: impl Into<String>, members: &[String]) -> &mut Self {
if !members.is_empty() {
self.pipe.sadd(key.into(), members);
}
self
}
pub fn zadd(&mut self, key: impl Into<String>, members: &[(f64, String)]) -> &mut Self {
if !members.is_empty() {
let pairs: Vec<(f64, &str)> = members.iter().map(|(s, m)| (*s, m.as_str())).collect();
self.pipe.zadd_multiple(key.into(), &pairs);
}
self
}
pub fn cmd(&mut self, cmd: redis::Cmd) -> &mut Self {
self.pipe.add_command(cmd);
self
}
#[tracing::instrument(
name = "db.query",
skip_all,
fields(db.system = "redis", db.operation = "transaction", otel.kind = "client")
)]
pub async fn exec<T: FromRedisValue>(self) -> Result<T> {
let max_retries = self.client.config().transaction_retries;
let backoff_ms = self.client.config().transaction_retry_backoff_ms;
let mut conn = self.client.connection().await?;
let mut retries = 0u32;
loop {
if !self.watched_keys.is_empty() {
let mut watch_cmd = redis::cmd("WATCH");
for key in &self.watched_keys {
watch_cmd.arg(key);
}
conn.query::<()>(&watch_cmd).await.map_err(DbError::from)?;
}
match conn.query_pipeline::<redis::Value>(&self.pipe).await {
Ok(raw) => {
if is_watch_conflict(&raw, !self.watched_keys.is_empty()) {
retries += 1;
if retries >= max_retries {
return Err(DbError::RedisCommandError(format!(
"事务执行失败:WATCH 冲突已重试 {} 次",
max_retries
)));
}
drop(conn);
tokio::time::sleep(transaction_backoff(backoff_ms, retries)).await;
conn = self.client.connection().await?;
continue;
}
return T::from_redis_value(&raw).map_err(|_| {
DbError::RedisTypeConversionError(
"事务结果类型与调用方期望不匹配(原始响应已省略)".to_string(),
)
});
}
Err(error) => {
return Err(DbError::from(error));
}
}
}
}
#[tracing::instrument(
name = "db.query",
skip_all,
fields(db.system = "redis", db.operation = "transaction", otel.kind = "client")
)]
pub async fn execute(self) -> Result<Vec<RedisValue>> {
let results: Vec<redis::Value> = self.exec().await?;
Ok(results.into_iter().map(RedisValue::from).collect())
}
pub fn len(&self) -> usize {
self.pipe.cmd_iter().count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[cfg(test)]
mod tests {
use super::is_watch_conflict;
#[test]
fn test_transaction_creation() {
}
#[test]
fn test_is_watch_conflict() {
assert!(is_watch_conflict(&redis::Value::Nil, true));
assert!(!is_watch_conflict(&redis::Value::Nil, false));
assert!(!is_watch_conflict(&redis::Value::Int(1), true));
assert!(!is_watch_conflict(
&redis::Value::Array(vec![redis::Value::Int(1)]),
true
));
}
}