Skip to main content

TaskContext

Struct TaskContext 

Source
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

Source

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(())
}
Source

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(())
}
Source

pub fn workflow_id(&self) -> &str

Get the workflow ID this task belongs to.

Source

pub fn run_id(&self) -> &str

Get the workflow run ID.

Source

pub fn task_id(&self) -> &str

Get the unique task ID.

Source

pub fn attempt(&self) -> i32

Get the current attempt number, starting at 1.

Useful for behaving differently on retries.

Source

pub fn heartbeat_timeout(&self) -> Option<Duration>

Get the heartbeat timeout, if configured.

Source

pub fn is_retry(&self) -> bool

Check if this is a retry attempt.

Source

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(())
}
Source

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))
        }
    }
}
Source

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§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more