Skip to main content

TaskBuilder

Struct TaskBuilder 

Source
pub struct TaskBuilder<I, O> { /* private fields */ }
Expand description

Configures a task before its handler is attached.

I is the input the handler receives and O the output it returns; both cross the wire as JSON. handler finishes the declaration and hands back a Task, which a worker registers and a client triggers.

The options set here are per task. The ones marked “standalone registration only” — on_events, cron, cron_input, description, version, default_priority, workflow_concurrency, sticky, idempotency — belong to the workflow a standalone task implies; setting them on a task that is then added to a Workflow is an Error::InvalidDeclaration at registration.

use std::time::Duration;

use hatchet_client::{Concurrency, ConcurrencyLimitStrategy, DesiredLabel, TaskBuilder};

let agent_run = TaskBuilder::<String, String>::new("agent-run")
    .retries(1)
    .retry_backoff(2.0, 60)
    .execution_timeout(Duration::from_secs(2 * 3600))
    .concurrency(
        Concurrency::expr("input.device_id")
            .max_runs(1)
            .strategy(ConcurrencyLimitStrategy::GroupRoundRobin),
    )
    .worker_label("os", DesiredLabel::eq("macos").required())
    .on_events(["approval.granted"])
    .handler(|_ctx, repo: String| async move { Ok(format!("reviewed {repo}")) });

assert_eq!(agent_run.name(), "agent-run");

Implementations§

Source§

impl<I, O> TaskBuilder<I, O>

Source

pub fn new(name: impl Into<String>) -> Self

Starts declaring a task. Registered on its own, the task name is also the workflow name used to trigger it.

Source

pub fn retries(self, retries: u32) -> Self

How many times Hatchet retries the task after a retryable failure.

Source

pub fn retry_backoff(self, factor: f32, max_seconds: u32) -> Self

Exponential backoff between retries: multiply the delay by factor each time, up to max_seconds.

Source

pub fn execution_timeout(self, timeout: Duration) -> Self

How long a run may execute before the engine times it out.

Source

pub fn schedule_timeout(self, timeout: Duration) -> Self

How long a run may wait for a worker before the engine gives up.

Source

pub fn concurrency(self, concurrency: Concurrency) -> Self

Adds a concurrency limit on this task.

Source

pub fn wait_for(self, conditions: impl Into<ConditionSet>) -> Self

Holds the task back until these conditions are satisfied.

May be called repeatedly; everything given must be satisfied for the task to start. Use any_of for “whichever comes first”.

A Condition::parent condition may only name a task this one runs after — set the parents with Task::parent after the handler, as usual:

use std::time::Duration;

use hatchet_client::{Condition, TaskBuilder, Workflow, any_of};

let fetch = TaskBuilder::<(), u32>::new("fetch").handler(|_ctx, _input| async { Ok(1) });
let publish = TaskBuilder::<(), ()>::new("publish")
    .wait_for(any_of([
        Condition::on_event("publish.approved"),
        Condition::sleep(Duration::from_secs(600)),
    ]))
    .skip_if(Condition::parent(&fetch).expression("output == 0"))
    .handler(|_ctx, _input| async { Ok(()) })
    .parent(&fetch);

let pipeline = Workflow::new("pipeline").task(&fetch).task(&publish);
Source

pub fn skip_if(self, conditions: impl Into<ConditionSet>) -> Self

Skips the task — without failing the workflow — when these conditions are satisfied.

A skipped task runs nothing and produces no output of its own: the engine records {"skipped": true} for it instead, and skips everything downstream of it too, including the on_success task; the run itself still succeeds. Read that marker rather than the output — a downstream handler tells a skipped parent apart from one that ran with Context::was_skipped, and a caller waiting on the run does the same with WorkflowResult::was_skipped.

A sleep or event condition here is weighed only while the task waits to be queued, so it must be paired with a wait_for on a sleep or an event — otherwise the task would wait for ever, and the declaration is rejected. Neither having parents nor a wait_for made only of parent conditions counts: a task in that shape was measured, on both supported engines, never to start while an otherwise identical sibling did. A parent condition needs no pairing at all: it is weighed as soon as the parent finishes.

May be called repeatedly; everything given must be satisfied.

use hatchet_client::{Condition, TaskBuilder, Workflow};

let fetch = TaskBuilder::<(), u32>::new("fetch").handler(|_ctx, _input| async { Ok(0) });
let publish = TaskBuilder::<(), ()>::new("publish")
    // Nothing was fetched, so there is nothing to publish.
    .skip_if(Condition::parent(&fetch).expression("output == 0"))
    .handler(|_ctx, _input| async { Ok(()) })
    .parent(&fetch);

let pipeline = Workflow::new("pipeline").task(&fetch).task(&publish);
Source

pub fn cancel_if(self, conditions: impl Into<ConditionSet>) -> Self

Cancels the task when these conditions are satisfied.

What was measured, on both supported engines: the engine weighs the condition while the task is waiting to start, and when it fired the task was cancelled before its handler ever ran — so the handler’s Context::cancelled token never triggered either. A caller waiting on the run then gets Error::RunCancelled.

This is a queuing gate, not a stop button. A condition that becomes true after the handler has started does not interrupt it: measured on both supported engines, a task that had reported itself started ran to completion and its run succeeded, with Context::cancelled never triggering. For a handler that has to be able to stop what it is doing, cancel the run — RunHandle::cancel, RunsClient::cancel, or the dashboard — and watch Context::cancelled.

The same pairing rule as skip_if applies, and for the same reason.

The current official Go SDK exposes no equivalent option — only WithWaitFor and WithSkipIf; a CancelIf field survives on the deprecated pkg/client/create task struct. This follows the official Python SDK.

May be called repeatedly; everything given must be satisfied.

use std::time::Duration;

use hatchet_client::{Condition, TaskBuilder};

let deploy = TaskBuilder::<(), ()>::new("deploy")
    // Deploy five minutes from now, unless someone calls it off.
    .wait_for(Condition::sleep(Duration::from_secs(300)))
    .cancel_if(Condition::on_event("deploy.aborted"))
    .handler(|_ctx, _input| async { Ok(()) });
Source

pub fn workflow_concurrency(self, concurrency: Concurrency) -> Self

Adds a concurrency limit across runs of this task as a workflow, rather than on the task itself — CreateWorkflowVersionRequest’s concurrency_arr instead of CreateTaskOpts.concurrency. Standalone registration only; inside a Workflow, use Workflow::concurrency.

use hatchet_client::{Concurrency, ConcurrencyLimitStrategy, TaskBuilder};

// One run per tenant at a time; the rest wait their turn.
let agent_run = TaskBuilder::<(), ()>::new("agent-run")
    .workflow_concurrency(
        Concurrency::expr("input.tenant")
            .max_runs(1)
            .strategy(ConcurrencyLimitStrategy::GroupRoundRobin),
    )
    .handler(|_ctx, _input| async move { Ok(()) });
Source

pub fn rate_limit(self, rate_limit: RateLimit) -> Self

Makes each run consume units of a static rate limit.

Source

pub fn worker_label(self, key: impl Into<String>, label: DesiredLabel) -> Self

Asks for a worker whose label key satisfies label.

Source

pub fn description(self, description: impl Into<String>) -> Self

Describes the task. Standalone registration only.

Source

pub fn version(self, version: impl Into<String>) -> Self

Labels this version of the task. Standalone registration only.

Source

pub fn on_events( self, keys: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Runs the task whenever one of these event keys is pushed. May be called repeatedly; event keys accumulate. Standalone registration only; inside a workflow, set triggers on the workflow.

Source

pub fn cron(self, expression: impl Into<String>) -> Self

Runs the task on a cron schedule. May be called repeatedly; cron expressions accumulate. Standalone registration only.

Source

pub fn cron_input(self, input: Value) -> Self

The input given to cron-triggered runs. Standalone registration only.

Source

pub fn default_priority(self, priority: Priority) -> Self

The priority of runs that do not specify one. Standalone registration only.

Source

pub fn sticky(self, strategy: StickyStrategy) -> Self

Pins this task’s runs to one worker. Standalone registration only; inside a Workflow, use Workflow::sticky.

use hatchet_client::{StickyStrategy, TaskBuilder};

let warm = TaskBuilder::<(), ()>::new("warm")
    .sticky(StickyStrategy::Soft)
    .handler(|_ctx, _input| async { Ok(()) });
Source

pub fn idempotency(self, idempotency: Idempotency) -> Self

Makes the engine refuse a second run whose key matches a claimed one. Standalone registration only; inside a Workflow, use Workflow::idempotency.

use std::time::Duration;

use hatchet_client::{Idempotency, TaskBuilder};

let send = TaskBuilder::<(), ()>::new("send-receipt")
    .idempotency(Idempotency::until_run_ends("input.order_id", Duration::from_secs(60)))
    .handler(|_ctx, _input| async { Ok(()) });
Source

pub fn eviction_policy(self, policy: EvictionPolicy) -> Self

Lets this task’s runs be handed back to the engine while they wait.

Durable tasks only. A policy on an ordinary handler is an Error::InvalidDeclaration at registration rather than a policy that silently never fires: an ordinary run is never parked on the engine, so a policy on one nearly always means the handler was meant to be a durable_handler.

Nothing about the policy is sent anywhere — the registration request is byte for byte the one this task would send without it. See EvictionPolicy for what the worker does with it.

A ttl of Duration::ZERO is refused for the same reason: it would leave a policy that can only ever fire under capacity pressure, which is not what a zero usually means.

use std::time::Duration;

use hatchet_client::{EvictionPolicy, TaskBuilder};

let approve = TaskBuilder::<(), ()>::new("approve")
    .eviction_policy(EvictionPolicy::ttl(Duration::from_secs(60)))
    .durable_handler(|ctx, _input| async move {
        ctx.wait_for_event("approved").await?;
        Ok(())
    });
Source

pub fn handler<F, Fut>(self, handler: F) -> Task<I, O>
where F: Fn(Context, I) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<O, TaskError>> + Send + 'static, I: DeserializeOwned + Send + 'static, O: Serialize + 'static,

Attaches the handler and finishes the declaration.

Source

pub fn durable_handler<F, Fut>(self, handler: F) -> Task<I, O>
where F: Fn(DurableContext, I) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<O, TaskError>> + Send + 'static, I: DeserializeOwned + Send + 'static, O: Serialize + 'static,

Attaches a durable handler and finishes the declaration.

A durable task may pause on the engine rather than on the worker: DurableContext::sleep_for and wait_for_event record the wait in the engine’s event log, so a worker that dies while waiting does not lose it — the task is assigned again and the handler is run from the top, with the waits that already finished answered at once.

That replay is what makes determinism a rule rather than a nicety: the handler must reach the same durable operations in the same order on every attempt, or the engine answers Error::Nondeterminism and the run fails without a retry. Anything that must not be recomputed goes through memo or now; see DurableContext for the whole of the bargain.

The task asks the engine for a durable slot rather than a default one, and its worker registers a durable slot pool (WorkerBuilder::durable_slots, 1000 by default) — a waiting durable task is not doing any work, so those slots are cheap.

use std::time::Duration;

use hatchet_client::TaskBuilder;

let approve = TaskBuilder::<(), String>::new("approve")
    .durable_handler(|ctx, _input| async move {
        ctx.sleep_for(Duration::from_secs(60)).await?;
        let event = ctx.wait_for_event("approved").await?;
        Ok(event.key)
    });
Source

pub fn batch_handler<F, Fut>( self, config: BatchConfig, handler: F, ) -> Task<I, O>
where F: Fn(Context, BatchInput<I>) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<BatchOutput<O>, TaskError>> + Send + 'static, I: DeserializeOwned + Send + 'static, O: Serialize + Send + 'static,

Attaches a batch handler and finishes the declaration.

The engine buffers concurrent runs of this task and hands the whole group to one worker at once: the handler is called once with every buffered input, keyed by BatchMemberId, and answers with one output per input. Each member’s output is reported separately, so the runs behind them complete — or fail — independently.

Three rules keep a member from waiting on an answer that never comes:

  • A member whose input does not deserialize into I fails on its own, without being shown to the handler and without touching the rest.
  • A member the handler leaves out of the BatchOutput is reported failed rather than left alone. Measured against a real engine, an unreported member stays Running until the task times out and is never assigned again.
  • A handler that returns Err fails every member of the batch with that error, since there is no way to tell which member it was about.

Both official SDKs instead fail the whole batch when a member is missing, throwing away the outputs the handler did produce; this SDK keeps them. A handler that panics fails every member the same way an Err does.

§How a batch runs on the worker

A batch is one run of the worker, however many task runs it answers for: it takes one default slot, and the STARTED naming every member is reported before the handler is called. What comes back is at most two reports — the members that succeeded, then the ones that failed — because one event type covers a whole report.

The Context the handler is given is the batch’s: its per-run accessors are empty, as Context’s own documentation sets out, and everything about the batch is on BatchInput. Cancellation is the batch’s too: the worker shutting down cancels the whole batch and nothing terminal is reported for any member, and there is no way to cancel one member of a batch that is already running.

§Rules a batch task is held to
  • It needs an engine of at least BATCH_MIN_ENGINE_VERSION; WorkerBuilder::build refuses an older one, which would take the registration and then never batch anything.
  • It cannot set retries: the declaration is refused with Error::InvalidDeclaration rather than quietly forced to zero, as the official SDKs do. Failing a member with a retryable TaskError still has the engine re-batch that member on its own.
  • It cannot be an on_failure or on_success hook: a hook runs because one particular run ended, so there is nothing to batch it with.
  • It cannot be durable — a durable handler is a different method, so that one is a compile error rather than a rule.
use hatchet_client::{BatchConfig, BatchOutput, TaskBuilder, TaskError};

let lengths = TaskBuilder::<String, usize>::new("lengths").batch_handler(
    BatchConfig::max_size(16),
    |_ctx, batch| async move {
        let mut output = BatchOutput::new();
        for (id, text) in batch.iter() {
            if text.is_empty() {
                output = output.fail(id.clone(), TaskError::non_retryable("empty"));
            } else {
                output = output.ok(id.clone(), text.len());
            }
        }
        Ok(output)
    },
);
Source

pub fn batch_broadcast_handler<F, Fut>( self, config: BatchConfig, handler: F, ) -> Task<I, O>
where F: Fn(Context, BatchInput<I>) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<O, TaskError>> + Send + 'static, I: DeserializeOwned + Send + 'static, O: Serialize + Send + 'static,

Attaches a batch handler that answers with one value for the whole batch, which every buffered run then receives as its own output.

For work that is the same for every caller — a cache warm-up, a shared lookup — where per-member outputs would be one value repeated. The registration says so (broadcast_output), so the engine and the handler can never disagree about the shape of the answer: which of the two builder methods was called decides both.

A member whose input does not deserialize into I still fails on its own and does not receive the broadcast value. Everything else in batch_handler — the engine floor, no retries, no hooks — applies here too.

use hatchet_client::{BatchConfig, TaskBuilder};

let refresh = TaskBuilder::<String, String>::new("refresh").batch_broadcast_handler(
    BatchConfig::max_size(64),
    |_ctx, batch| async move { Ok(format!("refreshed for {} callers", batch.len())) },
);

Trait Implementations§

Source§

impl<I, O> Debug for TaskBuilder<I, O>

Shows what a declaration is, not what it does: the handler is a closure with nothing to print, and the options are the caller’s own values.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<I, O> Forget for TaskBuilder<I, O>

§

impl<I, O> Freeze for TaskBuilder<I, O>
where PhantomData<fn(I) -> O>: Freeze,

§

impl<I, O> Move for TaskBuilder<I, O>

§

impl<I, O> RefUnwindSafe for TaskBuilder<I, O>
where PhantomData<fn(I) -> O>: RefUnwindSafe,

§

impl<I, O> Send for TaskBuilder<I, O>
where PhantomData<fn(I) -> O>: Send,

§

impl<I, O> Sync for TaskBuilder<I, O>
where PhantomData<fn(I) -> O>: Sync,

§

impl<I, O> Unpin for TaskBuilder<I, O>
where PhantomData<fn(I) -> O>: Unpin,

§

impl<I, O> UnsafeUnpin for TaskBuilder<I, O>
where PhantomData<fn(I) -> O>: UnsafeUnpin,

§

impl<I, O> UnwindSafe for TaskBuilder<I, O>
where PhantomData<fn(I) -> O>: UnwindSafe,

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> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

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

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