use crate::error::{NasaRedisError, Result};
use crate::job::model::JobState;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JobRun {
pub run_id: String,
pub job_name: String,
pub worker_name: String,
pub state: JobState,
pub logical_fire_at: i64,
pub triggered_at: i64,
pub attempt: i64,
pub attempt_token: String,
pub owner: String,
pub lease_until: i64,
pub result_code: String,
pub result_summary: String,
pub error_type: String,
pub error_summary: String,
pub parameter_payload: String,
pub schema_id: String,
pub wire_codec: String,
pub fanout_id: String,
pub snapshot_id: String,
pub root_attempt: i64,
pub create_deadline_at: i64,
}
impl JobRun {
pub(crate) fn from_fields(fields: &[redis::Value]) -> Result<Self> {
if fields.len() != 21 {
return Err(protocol("read_run 返回字段数不符合合同"));
}
let text = |index: usize| optional_text(&fields[index]);
let number = |index: usize| -> Result<i64> { optional_i64(&fields[index]) };
let state = JobState::parse(&text(3)).ok_or_else(|| protocol("read_run state 字段非法"))?;
Ok(Self {
run_id: text(0),
job_name: text(1),
worker_name: text(2),
state,
logical_fire_at: number(4)?,
triggered_at: number(5)?,
attempt: number(6)?,
attempt_token: text(7),
owner: text(8),
lease_until: number(9)?,
result_code: text(10),
result_summary: text(11),
error_type: text(12),
error_summary: text(13),
parameter_payload: text(14),
schema_id: text(15),
wire_codec: text(16),
fanout_id: text(17),
snapshot_id: text(18),
root_attempt: number(19)?,
create_deadline_at: number(20)?,
})
}
}
fn optional_text(value: &redis::Value) -> String {
match value {
redis::Value::Nil => String::new(),
redis::Value::Int(n) => n.to_string(),
redis::Value::BulkString(bytes) => String::from_utf8_lossy(bytes).into_owned(),
redis::Value::SimpleString(text) => text.clone(),
_ => String::new(),
}
}
fn optional_i64(value: &redis::Value) -> Result<i64> {
match value {
redis::Value::Nil => Ok(0),
redis::Value::Int(n) => Ok(*n),
redis::Value::BulkString(bytes) => {
let text = String::from_utf8_lossy(bytes);
if text.is_empty() {
Ok(0)
} else {
text.parse::<i64>()
.map_err(|_| protocol("read_run 数值字段非法"))
}
}
redis::Value::SimpleString(text) if text.is_empty() => Ok(0),
redis::Value::SimpleString(text) => text
.parse::<i64>()
.map_err(|_| protocol("read_run 数值字段非法")),
_ => Err(protocol("read_run 数值字段类型非法")),
}
}
fn protocol(message: &str) -> NasaRedisError {
crate::job::JobError::Protocol(message.to_owned()).into()
}