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>,
host: Option<(orcher_sdk_core::EncodedHost, Vec<u8>)>,
}
#[derive(Debug, Clone)]
#[allow(dead_code)] pub(crate) struct HeartbeatMessage {
pub task_id: String,
pub details: Option<Vec<u8>>,
pub timestamp: SystemTime,
}
fn heartbeat_through(
host: &orcher_sdk_core::EncodedHost,
token: &[u8],
details: Option<Vec<u8>>,
) -> Result<orcher_proto::host::v1::HeartbeatAnswer> {
use orcher_proto::prost::Message;
let heartbeat = orcher_proto::host::v1::TaskHeartbeat {
token: token.to_vec(),
details: details.map(|data| orcher_proto::kernel::v1::Payload {
data,
metadata: [("encoding".to_string(), b"json".to_vec())].into(),
..Default::default()
}),
..Default::default()
};
let failed = |message: String| {
tracing::error!("{message}");
Error::Task(crate::error::TaskError::HeartbeatFailed(message))
};
let answer = host
.heartbeat(&heartbeat.encode_to_vec())
.map_err(|e| failed(format!("The worker host refused the heartbeat: {e}")))?;
orcher_proto::host::v1::HeartbeatAnswer::decode(answer.as_slice()).map_err(|e| {
failed(format!(
"The worker host answered the heartbeat with bytes that are not a HeartbeatAnswer: {e}"
))
})
}
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()),
host: None,
}
}
pub(crate) fn with_host(
workflow_id: String,
run_id: String,
task_id: String,
attempt: i32,
heartbeat_timeout: Option<Duration>,
host: orcher_sdk_core::EncodedHost,
token: Vec<u8>,
) -> Self {
let cancellation_token = tokio_util::sync::CancellationToken::new();
{
let (host, token, cancel) = (host.clone(), token.clone(), cancellation_token.clone());
tokio::spawn(async move {
if host.task_cancelled(&token).await {
cancel.cancel();
}
});
}
Self {
workflow_id,
run_id,
task_id,
attempt: counted_from_one(attempt),
heartbeat_timeout,
heartbeat_tx: None,
cancellation_token: Arc::new(cancellation_token),
host: Some((host, token)),
}
}
#[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,
host: 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((host, token)) = &self.host {
if heartbeat_through(host, token, details_bytes)?.cancel_requested {
self.cancellation_token.cancel();
}
} 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
}
}