use crate::error::{Error, Result};
use serde::Serialize;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::mpsc;
pub struct TaskContext {
workflow_id: String,
run_id: String,
task_id: String,
attempt: i32,
heartbeat_timeout: Option<Duration>,
heartbeat_tx: Option<mpsc::UnboundedSender<HeartbeatMessage>>,
cancellation_token: Arc<tokio_util::sync::CancellationToken>,
driver_heartbeat: Option<orcher_sdk_core::poller::TaskHeartbeat>,
}
#[derive(Debug, Clone)]
#[allow(dead_code)] pub(crate) struct HeartbeatMessage {
pub task_id: String,
pub details: Option<Vec<u8>>,
pub timestamp: SystemTime,
}
fn counted_from_one(attempt: i32) -> i32 {
attempt.max(1)
}
impl TaskContext {
#[cfg_attr(not(test), allow(dead_code))] pub(crate) fn new(
workflow_id: String,
run_id: String,
task_id: String,
attempt: i32,
heartbeat_timeout: Option<Duration>,
) -> Self {
Self {
workflow_id,
run_id,
task_id,
attempt: counted_from_one(attempt),
heartbeat_timeout,
heartbeat_tx: None,
cancellation_token: Arc::new(tokio_util::sync::CancellationToken::new()),
driver_heartbeat: None,
}
}
pub(crate) fn with_heartbeat(
workflow_id: String,
run_id: String,
task_id: String,
attempt: i32,
heartbeat_timeout: Option<Duration>,
heartbeat: orcher_sdk_core::poller::TaskHeartbeat,
) -> Self {
Self {
workflow_id,
run_id,
task_id,
attempt: counted_from_one(attempt),
heartbeat_timeout,
heartbeat_tx: None,
cancellation_token: Arc::new(heartbeat.cancellation_token()),
driver_heartbeat: Some(heartbeat),
}
}
#[allow(dead_code)] pub(crate) fn with_heartbeat_channel(
workflow_id: String,
run_id: String,
task_id: String,
attempt: i32,
heartbeat_timeout: Option<Duration>,
heartbeat_tx: mpsc::UnboundedSender<HeartbeatMessage>,
cancellation_token: Arc<tokio_util::sync::CancellationToken>,
) -> Self {
Self {
workflow_id,
run_id,
task_id,
attempt: counted_from_one(attempt),
heartbeat_timeout,
heartbeat_tx: Some(heartbeat_tx),
cancellation_token,
driver_heartbeat: None,
}
}
pub async fn heartbeat(&self) -> Result<()> {
self.heartbeat_with_details::<()>(None).await
}
pub async fn heartbeat_with_details<T>(&self, details: Option<T>) -> Result<()>
where
T: Serialize,
{
if self.cancellation_token.is_cancelled() {
return Err(Error::Task(crate::error::TaskError::Canceled));
}
let details_bytes = match details {
Some(d) => {
let bytes = serde_json::to_vec(&d).map_err(|e| {
Error::Serialization(format!("Failed to serialize heartbeat details: {}", e))
})?;
Some(bytes)
}
None => None,
};
if let Some(heartbeat) = &self.driver_heartbeat {
heartbeat.record(details_bytes);
} else if let Some(tx) = &self.heartbeat_tx {
let has_details = details_bytes.is_some();
let message = HeartbeatMessage {
task_id: self.task_id.clone(),
details: details_bytes,
timestamp: SystemTime::now(),
};
tx.send(message).map_err(|_| {
Error::Task(crate::error::TaskError::HeartbeatFailed(
"Heartbeat channel closed".to_string(),
))
})?;
tracing::debug!(
task_id = %self.task_id,
workflow_id = %self.workflow_id,
has_details = has_details,
"Heartbeat sent"
);
} else {
tracing::trace!(
task_id = %self.task_id,
"Heartbeat called but no channel configured (testing mode)"
);
}
Ok(())
}
pub fn workflow_id(&self) -> &str {
&self.workflow_id
}
pub fn run_id(&self) -> &str {
&self.run_id
}
pub fn task_id(&self) -> &str {
&self.task_id
}
pub fn attempt(&self) -> i32 {
self.attempt
}
pub fn heartbeat_timeout(&self) -> Option<Duration> {
self.heartbeat_timeout
}
pub fn is_retry(&self) -> bool {
self.attempt > 1
}
pub fn is_cancelled(&self) -> bool {
self.cancellation_token.is_cancelled()
}
pub fn cancellation_token(&self) -> Arc<tokio_util::sync::CancellationToken> {
Arc::clone(&self.cancellation_token)
}
pub fn logger(&self) -> TaskLogger {
TaskLogger {
workflow_id: self.workflow_id.clone(),
run_id: self.run_id.clone(),
task_id: self.task_id.clone(),
attempt: self.attempt,
}
}
}
pub struct TaskLogger {
workflow_id: String,
run_id: String,
task_id: String,
attempt: i32,
}
impl TaskLogger {
pub fn target(&self) -> String {
format!("orcher_sdk::task::{}", self.task_id)
}
pub fn workflow_id(&self) -> &str {
&self.workflow_id
}
pub fn run_id(&self) -> &str {
&self.run_id
}
pub fn task_id(&self) -> &str {
&self.task_id
}
pub fn attempt(&self) -> i32 {
self.attempt
}
}