pub struct TaskContext { /* private fields */ }Expand description
The context a task runs in.
Through it a task reports progress with heartbeats, learns that it has been canceled, reads metadata about the attempt, and gets a logger.
§Heartbeats
The worker heartbeats every task it runs on its own, at a third of the
task’s heartbeat timeout, so a long task needs no heartbeat code to stay
alive, and one whose worker dies is timed out and retried. A task calls
heartbeat to report progress: the details are sent with the next
heartbeat due. They are not handed to a later attempt; a retried task
starts without them, so keep anything it must resume from in its own
storage. The heartbeat’s answer is also how the engine asks a task to stop; see
is_cancelled.
async fn long_task(ctx: &TaskContext, items: Vec<String>) -> Result<()> {
for (i, item) in items.iter().enumerate() {
// Process item
process_item(item).await?;
// Report progress every 10 items.
if i % 10 == 0 {
ctx.heartbeat().await?;
}
}
Ok(())
}Implementations§
Source§impl TaskContext
impl TaskContext
Sourcepub async fn heartbeat(&self) -> Result<()>
pub async fn heartbeat(&self) -> Result<()>
Send a heartbeat to indicate the task is still running.
The worker already heartbeats the task on its own while it runs; this adds one from the task’s code, folded into the same stream: it never waits, and however often it is called no more heartbeats are sent than the worker’s timer sends. Fails once the task has been cancelled.
§Example
async fn my_task(ctx: &TaskContext) -> Result<()> {
for i in 0..100 {
// Do some work
heavy_operation(i).await?;
// Report progress on every iteration.
ctx.heartbeat().await?;
}
Ok(())
}Sourcepub async fn heartbeat_with_details<T>(&self, details: Option<T>) -> Result<()>where
T: Serialize,
pub async fn heartbeat_with_details<T>(&self, details: Option<T>) -> Result<()>where
T: Serialize,
Send a heartbeat with optional progress details.
The details can be any serializable value. They report progress only: a retried attempt does not receive them.
§Example
#[derive(Serialize)]
struct Progress {
current: u32,
total: u32,
}
async fn my_task(ctx: &TaskContext) -> Result<()> {
let total = 100;
for current in 0..total {
// Do work
process_item(current).await?;
// Report how far the task has got.
ctx.heartbeat_with_details(Some(Progress { current, total })).await?;
}
Ok(())
}Sourcepub fn workflow_id(&self) -> &str
pub fn workflow_id(&self) -> &str
Get the workflow ID this task belongs to.
Sourcepub fn attempt(&self) -> i32
pub fn attempt(&self) -> i32
Get the current attempt number, starting at 1.
Useful for behaving differently on retries.
Sourcepub fn heartbeat_timeout(&self) -> Option<Duration>
pub fn heartbeat_timeout(&self) -> Option<Duration>
Get the heartbeat timeout, if configured.
Sourcepub fn is_cancelled(&self) -> bool
pub fn is_cancelled(&self) -> bool
Check if the task has been cancelled.
A long-running task should check this periodically and return early once it is set.
§Example
use orcher_sdk::error::TaskError;
async fn long_task(ctx: &TaskContext) -> Result<()> {
for i in 0..1000 {
// Check for cancellation
if ctx.is_cancelled() {
return Err(Error::Task(TaskError::Canceled));
}
// Do work...
process_item(i).await?;
}
Ok(())
}Sourcepub fn cancellation_token(&self) -> Arc<CancellationToken> ⓘ
pub fn cancellation_token(&self) -> Arc<CancellationToken> ⓘ
Get the task’s cancellation token.
Use it with tokio::select! to stop waiting on work as soon as the
task is canceled.
§Example
use orcher_sdk::error::TaskError;
async fn cancellable_task(ctx: &TaskContext) -> Result<()> {
let token = ctx.cancellation_token();
let work = async {
// Do long-running work
tokio::time::sleep(std::time::Duration::from_secs(3600)).await;
Ok(())
};
tokio::select! {
result = work => result,
_ = token.cancelled() => {
Err(Error::Task(TaskError::Canceled))
}
}
}Sourcepub fn logger(&self) -> TaskLogger
pub fn logger(&self) -> TaskLogger
Get a logger for this task.
The logger carries the task’s metadata.
§Example
async fn my_task(ctx: &TaskContext) -> Result<()> {
let logger = ctx.logger();
tracing::info!(
workflow_id = logger.workflow_id(),
task_id = logger.task_id(),
attempt = logger.attempt(),
"task started"
);
Ok(())
}Auto Trait Implementations§
impl !RefUnwindSafe for TaskContext
impl !UnwindSafe for TaskContext
impl Forget for TaskContext
impl Freeze for TaskContext
impl Move for TaskContext
impl Send for TaskContext
impl Sync for TaskContext
impl Unpin for TaskContext
impl UnsafeUnpin for TaskContext
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request