use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use serde::de::DeserializeOwned;
use crate::error::Result;
use crate::job::coordinator::{FanoutBuilder, FanoutService};
use crate::job::model::{JobResultCode, JobWireCodec};
use crate::job::payload::decode_json_payload;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FanoutContext {
pub fanout_id: String,
pub root_run_id: String,
pub snapshot_id: String,
pub shard_index: i64,
pub shard_total: i64,
pub seq: i64,
pub execution_key: String,
pub target_node_identity: String,
pub assignment_epoch: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JobOutcome {
pub code: JobResultCode,
pub summary: String,
}
impl JobOutcome {
pub fn success() -> Self {
Self {
code: JobResultCode::Success,
summary: String::new(),
}
}
pub fn success_with_summary(summary: impl Into<String>) -> Self {
Self {
code: JobResultCode::Success,
summary: summary.into(),
}
}
pub fn retry(summary: impl Into<String>) -> Self {
Self {
code: JobResultCode::Retry,
summary: summary.into(),
}
}
pub fn fail_permanent(summary: impl Into<String>) -> Self {
Self {
code: JobResultCode::FailPermanent,
summary: summary.into(),
}
}
}
#[derive(Debug, Clone)]
pub struct JobExecution {
pub qualifier: String,
pub namespace: String,
pub run_id: String,
pub job_name: String,
pub worker_name: String,
pub logical_fire_at: i64,
pub triggered_at: i64,
pub attempt: i64,
pub attempt_token: i64,
pub schema_id: String,
pub wire_codec: String,
pub parameter_payload: Vec<u8>,
pub fanout: Option<FanoutContext>,
pub(crate) authority: Arc<JobExecutionAuthority>,
pub(crate) fanout_service: Option<Arc<FanoutService>>,
}
pub type JobResult = JobOutcome;
#[derive(Debug)]
pub(crate) struct JobExecutionAuthority {
active: AtomicBool,
cancellation_requested: AtomicBool,
fanout_transferred: AtomicBool,
deadline: Mutex<tokio::time::Instant>,
}
impl JobExecutionAuthority {
pub(crate) fn new(redis_now: i64, lease_until: i64, safety_ms: u64) -> Arc<Self> {
Arc::new(Self {
active: AtomicBool::new(true),
cancellation_requested: AtomicBool::new(false),
fanout_transferred: AtomicBool::new(false),
deadline: Mutex::new(local_deadline(redis_now, lease_until, safety_ms)),
})
}
pub(crate) fn renew(&self, redis_now: i64, lease_until: i64, safety_ms: u64) -> bool {
if !self.active.load(Ordering::Acquire) {
return false;
}
match self.deadline.lock() {
Ok(mut deadline) => {
*deadline = local_deadline(redis_now, lease_until, safety_ms);
true
}
Err(_) => {
self.active.store(false, Ordering::Release);
false
}
}
}
pub(crate) fn revoke(&self, cancelled: bool) {
if cancelled {
self.cancellation_requested.store(true, Ordering::Release);
}
self.active.store(false, Ordering::Release);
}
pub(crate) fn transfer_to_fanout(&self) {
self.fanout_transferred.store(true, Ordering::Release);
self.active.store(false, Ordering::Release);
}
pub(crate) fn is_fanout_transferred(&self) -> bool {
self.fanout_transferred.load(Ordering::Acquire)
}
fn still_owns(&self) -> bool {
if !self.active.load(Ordering::Acquire) {
return false;
}
self.deadline
.lock()
.map(|deadline| tokio::time::Instant::now() < *deadline)
.unwrap_or(false)
}
}
impl JobExecution {
pub fn qualifier(&self) -> &str {
&self.qualifier
}
pub fn namespace(&self) -> &str {
&self.namespace
}
pub fn payload(&self) -> &[u8] {
&self.parameter_payload
}
pub fn parameter<T: DeserializeOwned>(&self) -> Result<T> {
if self.wire_codec != JobWireCodec::Json.wire_name() {
return Err(crate::job::JobError::InvalidPayload(
"非 JSON 参数只能通过 payload() 按声明的线编码处理".to_owned(),
)
.into());
}
decode_json_payload(&self.parameter_payload)
.map_err(|error| crate::job::JobError::InvalidPayload(error).into())
}
pub fn fanout_context(&self) -> Option<&FanoutContext> {
self.fanout.as_ref()
}
pub fn fanout(&self, worker_name: impl Into<String>) -> Result<FanoutBuilder> {
let service = self.fanout_service.as_ref().ok_or_else(|| {
crate::error::NasaRedisError::from(crate::job::JobError::Config(
"当前 JobContext 不允许创建 Fanout".to_owned(),
))
})?;
service.builder(self, worker_name)
}
pub fn is_cancellation_requested(&self) -> bool {
self.authority
.cancellation_requested
.load(Ordering::Acquire)
}
pub fn still_owns_execution(&self) -> bool {
self.authority.still_owns()
}
pub fn checkpoint(&self) -> Result<()> {
if self.is_cancellation_requested() {
return Err(crate::job::JobError::ExecutionStopped(
"当前 attempt 已收到取消请求".to_owned(),
)
.into());
}
if !self.still_owns_execution() {
return Err(crate::job::JobError::ExecutionStopped(
"当前 attempt 已失权或超过本地保守截止".to_owned(),
)
.into());
}
Ok(())
}
}
pub type JobContext = JobExecution;
pub trait IntoJobHandlerResult {
fn into_job_handler_result(self) -> JobOutcome;
}
impl IntoJobHandlerResult for JobOutcome {
fn into_job_handler_result(self) -> JobOutcome {
self
}
}
impl IntoJobHandlerResult for () {
fn into_job_handler_result(self) -> JobOutcome {
JobOutcome::success()
}
}
impl<E> IntoJobHandlerResult for std::result::Result<JobOutcome, E>
where
E: std::fmt::Display,
{
fn into_job_handler_result(self) -> JobOutcome {
self.unwrap_or_else(|error| JobOutcome::retry(error.to_string()))
}
}
impl<E> IntoJobHandlerResult for std::result::Result<(), E>
where
E: std::fmt::Display,
{
fn into_job_handler_result(self) -> JobOutcome {
match self {
Ok(()) => JobOutcome::success(),
Err(error) => JobOutcome::retry(error.to_string()),
}
}
}
pub type JobHandlerFuture<'a> = Pin<Box<dyn Future<Output = JobOutcome> + Send + 'a>>;
pub trait JobHandler: Send + Sync {
fn handle<'a>(&'a self, execution: &'a JobExecution) -> JobHandlerFuture<'a>;
}
struct ClosureJobHandler<F>(F);
impl<F, Fut, R> JobHandler for ClosureJobHandler<F>
where
F: Fn(JobContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: IntoJobHandlerResult + Send + 'static,
{
fn handle<'a>(&'a self, execution: &'a JobExecution) -> JobHandlerFuture<'a> {
let future = (self.0)(execution.clone());
Box::pin(async move { future.await.into_job_handler_result() })
}
}
pub(crate) fn handler_from_fn<F, Fut, R>(handler: F) -> std::sync::Arc<dyn JobHandler>
where
F: Fn(JobContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: IntoJobHandlerResult + Send + 'static,
{
std::sync::Arc::new(ClosureJobHandler(handler))
}
fn local_deadline(redis_now: i64, lease_until: i64, safety_ms: u64) -> tokio::time::Instant {
let safety_ms = i64::try_from(safety_ms).unwrap_or(i64::MAX);
let usable_ms = lease_until
.saturating_sub(redis_now)
.saturating_sub(safety_ms)
.max(0) as u64;
tokio::time::Instant::now()
.checked_add(Duration::from_millis(usable_ms))
.unwrap_or_else(tokio::time::Instant::now)
}