use redis::{ErrorKind, ServerErrorKind, Value};
use crate::client::{Conn, RedisClient};
use crate::error::{NasaRedisError, Result};
use crate::keytag::redis_slot;
pub(crate) struct JobScript {
pub(crate) text: &'static str,
sha: std::sync::OnceLock<String>,
}
impl JobScript {
pub(crate) const fn new(text: &'static str) -> Self {
Self {
text,
sha: std::sync::OnceLock::new(),
}
}
fn sha(&self) -> &str {
self.sha
.get_or_init(|| redis::Script::new(self.text).get_hash().to_owned())
}
}
pub(crate) async fn eval(
client: &RedisClient,
script: &JobScript,
keys: &[Vec<u8>],
argv: &[Vec<u8>],
) -> Result<Vec<Value>> {
ensure_same_slot(keys)?;
let mut conn = client.job_control_conn().await?;
match run(&mut conn, "EVALSHA", script.sha().as_bytes(), keys, argv).await {
Ok(values) => Ok(values),
Err(error) if is_noscript(&error) => {
let values = run(&mut conn, "EVAL", script.text.as_bytes(), keys, argv)
.await
.map_err(classify_execution_error)?;
client.record_job_script_reload();
Ok(values)
}
Err(error) => Err(classify_execution_error(error)),
}
}
pub(crate) async fn eval_retry_safe(
client: &RedisClient,
script: &JobScript,
keys: &[Vec<u8>],
argv: &[Vec<u8>],
) -> Result<Vec<Value>> {
ensure_same_slot(keys)?;
let mut conn = client.job_heartbeat_conn().await?;
match run(&mut conn, "EVALSHA", script.sha().as_bytes(), keys, argv).await {
Ok(values) => Ok(values),
Err(error) if is_noscript(&error) => {
let values = run(&mut conn, "EVAL", script.text.as_bytes(), keys, argv)
.await
.map_err(NasaRedisError::Redis)?;
client.record_job_script_reload();
Ok(values)
}
Err(error) => Err(NasaRedisError::Redis(error)),
}
}
fn classify_execution_error(error: redis::RedisError) -> NasaRedisError {
if matches!(error.kind(), ErrorKind::Server(_)) {
NasaRedisError::Redis(error)
} else {
crate::job::JobError::ExecutionUnknown(
"状态脚本可能已执行,必须读取权威状态后再决定后续动作".to_owned(),
)
.into()
}
}
fn ensure_same_slot(keys: &[Vec<u8>]) -> Result<()> {
let mut slot: Option<u16> = None;
for key in keys {
let current = redis_slot(key);
match slot {
None => slot = Some(current),
Some(expected) if expected != current => {
return Err(crate::job::JobError::Protocol(
"脚本的 KEYS 不在同一 Redis slot".to_owned(),
)
.into());
}
_ => {}
}
}
Ok(())
}
async fn run(
conn: &mut Conn,
verb: &str,
body: &[u8],
keys: &[Vec<u8>],
argv: &[Vec<u8>],
) -> std::result::Result<Vec<Value>, redis::RedisError> {
let mut cmd = redis::cmd(verb);
cmd.arg(body).arg(keys.len());
for key in keys {
cmd.arg(key.as_slice());
}
for arg in argv {
cmd.arg(arg.as_slice());
}
cmd.query_async(conn).await
}
fn is_noscript(error: &redis::RedisError) -> bool {
error.kind() == ErrorKind::Server(ServerErrorKind::NoScript)
}
pub(crate) fn value_to_string(value: &Value) -> String {
match value {
Value::Nil => String::new(),
Value::Int(n) => n.to_string(),
Value::BulkString(bytes) => String::from_utf8_lossy(bytes).into_owned(),
Value::SimpleString(text) => text.clone(),
_ => String::new(),
}
}