use std::sync::Arc;
use serde::{Deserialize, Serialize};
use super::KeyLayout;
use crate::client::RedisClient;
use crate::error::{NasaRedisError, Result};
pub const ADMIN_GROUP: &str = "nasa-park-admin";
pub fn cmd_stream_key(layout: &KeyLayout, p: u32) -> String {
format!("{}:park-cmd:{}", layout.prefix, p)
}
pub fn result_key(layout: &KeyLayout, p: u32, operation_id: &str) -> String {
format!("{}:park-cmd-result:{}:{}", layout.prefix, p, operation_id)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CmdAction {
Resume,
Drop,
Force,
Dlq,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CmdResult {
pub state: CmdState,
pub action: CmdAction,
pub digest: String,
pub created_at: u64,
pub timeout_ms: u64,
#[serde(default)]
pub detail: String,
#[serde(default)]
pub marker_version_before: u64,
#[serde(default)]
pub marker_version_after: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CmdState {
Pending,
Executing,
Succeeded,
Rejected,
}
pub(crate) async fn redis_now(client: &Arc<RedisClient>) -> Result<u64> {
let v: Vec<String> = redis::cmd("TIME").query_async(&mut client.conn()).await?;
if v.len() != 2 {
return Err(NasaRedisError::ProtocolMarker(
"TIME 响应必须包含秒与微秒两个分量".into(),
));
}
let sec: u64 = v
.first()
.and_then(|s| s.parse().ok())
.ok_or_else(|| NasaRedisError::ProtocolMarker("TIME 响应缺/坏秒位".into()))?;
let usec: u64 = v
.get(1)
.and_then(|s| s.parse().ok())
.ok_or_else(|| NasaRedisError::ProtocolMarker("TIME 响应缺/坏微秒位".into()))?;
if usec >= 1_000_000 {
return Err(NasaRedisError::ProtocolMarker(
"TIME 微秒分量超出合法范围".into(),
));
}
sec.checked_mul(1_000)
.and_then(|millis| millis.checked_add(usec / 1_000))
.ok_or_else(|| NasaRedisError::ProtocolMarker("TIME 毫秒值超出整数范围".into()))
}
fn digest_of(action: CmdAction, p: u32, timeout_ms: u64) -> String {
format!(
"{:04x}",
crate::keytag::crc16(format!("{action:?}|{p}|{timeout_ms}").as_bytes())
)
}
pub async fn submit(
client: &Arc<RedisClient>,
layout: &KeyLayout,
p: u32,
operation_id: &str,
action: CmdAction,
timeout_ms: u64,
) -> Result<CmdResult> {
let rkey = result_key(layout, p, operation_id);
let digest = digest_of(action, p, timeout_ms);
let now = redis_now(client).await?;
let fresh = CmdResult {
state: CmdState::Pending,
action,
digest: digest.clone(),
created_at: now,
timeout_ms,
detail: String::new(),
marker_version_before: 0,
marker_version_after: 0,
};
let payload =
serde_json::to_string(&fresh).map_err(|e| NasaRedisError::Codec(e.to_string()))?;
let created: Option<String> = redis::cmd("SET")
.arg(&rkey)
.arg(&payload)
.arg("NX")
.query_async(&mut client.conn())
.await?;
if created.is_none() {
let existing: CmdResult = query(client, layout, p, operation_id)
.await?
.ok_or_else(|| NasaRedisError::Config("result 消失(竞态)".into()))?;
if existing.digest != digest
|| existing.action != action
|| existing.timeout_ms != timeout_ms
{
return Err(NasaRedisError::Config(format!(
"OperationIdConflict: op={operation_id} 已绑定 {:?},本次 {action:?}",
existing.action
)));
}
if !matches!(existing.state, CmdState::Succeeded | CmdState::Rejected) {
let _: String = redis::cmd("XADD")
.arg(cmd_stream_key(layout, p))
.arg("*")
.arg("op")
.arg(operation_id)
.query_async(&mut client.conn())
.await?;
}
return Ok(existing);
}
let _: String = redis::cmd("XADD")
.arg(cmd_stream_key(layout, p))
.arg("*")
.arg("op")
.arg(operation_id)
.query_async(&mut client.conn())
.await?;
Ok(fresh)
}
pub async fn query(
client: &Arc<RedisClient>,
layout: &KeyLayout,
p: u32,
operation_id: &str,
) -> Result<Option<CmdResult>> {
let raw: Option<String> = client.get(&result_key(layout, p, operation_id)).await?;
match raw {
None => Ok(None),
Some(s) => Ok(Some(serde_json::from_str(&s).map_err(|e| {
NasaRedisError::Codec(format!("result 解析失败: {e}"))
})?)),
}
}
async fn put_result(
client: &Arc<RedisClient>,
layout: &KeyLayout,
p: u32,
operation_id: &str,
r: &CmdResult,
) -> Result<()> {
let rkey = result_key(layout, p, operation_id);
let payload = serde_json::to_string(r).map_err(|e| NasaRedisError::Codec(e.to_string()))?;
if matches!(r.state, CmdState::Succeeded | CmdState::Rejected) {
let _: redis::Value = redis::cmd("SET")
.arg(&rkey)
.arg(payload.as_str())
.arg("EX")
.arg(24 * 3600)
.query_async(&mut client.conn())
.await?;
} else {
client.set(&rkey, payload.as_str()).await?;
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CmdAck {
Finalize,
Retry,
}
pub async fn execute_one(
rt_client: &Arc<RedisClient>,
layout: &KeyLayout,
p: u32,
operation_id: &str,
do_action: impl std::future::Future<Output = Result<Vec<String>>>,
action_hint: CmdAction,
) -> Result<CmdAck> {
let Some(mut r) = query(rt_client, layout, p, operation_id).await? else {
tracing::warn!(
p,
operation_id,
"命令无 result 记录(producer 违规),清理孤儿 command"
);
return Ok(CmdAck::Finalize);
};
if action_hint != r.action {
return Err(NasaRedisError::ProtocolMarker(
"管理动作与持久结果不一致,拒绝执行或确认命令".into(),
));
}
if matches!(r.state, CmdState::Succeeded | CmdState::Rejected) {
return Ok(CmdAck::Finalize);
}
if matches!(r.state, CmdState::Pending) {
let now = redis_now(rt_client).await?;
if now.saturating_sub(r.created_at) > r.timeout_ms {
r.state = CmdState::Rejected;
r.detail = "DeadlineExceeded".into();
put_result(rt_client, layout, p, operation_id, &r).await?;
tracing::warn!(p, operation_id, "管理命令(Pending)超时,已写 Rejected");
return Ok(CmdAck::Finalize);
}
}
r.marker_version_before = super::disposition::marker_version(rt_client, layout, p)
.await
.unwrap_or(0);
r.state = CmdState::Executing;
put_result(rt_client, layout, p, operation_id, &r).await?;
match do_action.await {
Ok(ids) => {
r.state = CmdState::Succeeded;
r.detail = ids.join(",");
r.marker_version_after = super::disposition::marker_version(rt_client, layout, p)
.await
.unwrap_or(r.marker_version_before);
put_result(rt_client, layout, p, operation_id, &r).await?;
Ok(CmdAck::Finalize)
}
Err(NasaRedisError::OperationConflict(msg)) => {
let now = redis_now(rt_client).await?;
if now.saturating_sub(r.created_at) > r.timeout_ms {
r.state = CmdState::Rejected;
r.detail = format!("OperationConflict(超 producer 窗口,需异 op takeover): {msg}");
r.marker_version_after = r.marker_version_before;
put_result(rt_client, layout, p, operation_id, &r).await?;
tracing::warn!(
p,
operation_id,
"operation 冲突超 producer 窗口,写 Rejected 终态停忙等"
);
Ok(CmdAck::Finalize)
} else {
tracing::warn!(
p,
operation_id,
"operation 冲突(窗口内),保留 PEL 候原 op 重提"
);
Ok(CmdAck::Retry)
}
}
Err(e) if e.is_infra_retryable() => {
tracing::warn!(p, operation_id, err = %e, "管理动作基础设施错误,保留 PEL 重试(不终结)");
Ok(CmdAck::Retry)
}
Err(e) => {
r.state = CmdState::Rejected;
r.detail = e.to_string();
r.marker_version_after = super::disposition::marker_version(rt_client, layout, p)
.await
.unwrap_or(r.marker_version_before);
put_result(rt_client, layout, p, operation_id, &r).await?;
Ok(CmdAck::Finalize)
}
}
}