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>
impl<I, O> TaskBuilder<I, O>
Sourcepub fn new(name: impl Into<String>) -> Self
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.
Sourcepub fn retries(self, retries: u32) -> Self
pub fn retries(self, retries: u32) -> Self
How many times Hatchet retries the task after a retryable failure.
Sourcepub fn retry_backoff(self, factor: f32, max_seconds: u32) -> Self
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.
Sourcepub fn execution_timeout(self, timeout: Duration) -> Self
pub fn execution_timeout(self, timeout: Duration) -> Self
How long a run may execute before the engine times it out.
Sourcepub fn schedule_timeout(self, timeout: Duration) -> Self
pub fn schedule_timeout(self, timeout: Duration) -> Self
How long a run may wait for a worker before the engine gives up.
Sourcepub fn concurrency(self, concurrency: Concurrency) -> Self
pub fn concurrency(self, concurrency: Concurrency) -> Self
Adds a concurrency limit on this task.
Sourcepub fn wait_for(self, conditions: impl Into<ConditionSet>) -> Self
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);Sourcepub fn skip_if(self, conditions: impl Into<ConditionSet>) -> Self
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);Sourcepub fn cancel_if(self, conditions: impl Into<ConditionSet>) -> Self
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(()) });Sourcepub fn workflow_concurrency(self, concurrency: Concurrency) -> Self
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(()) });Sourcepub fn rate_limit(self, rate_limit: RateLimit) -> Self
pub fn rate_limit(self, rate_limit: RateLimit) -> Self
Makes each run consume units of a static rate limit.
Sourcepub fn worker_label(self, key: impl Into<String>, label: DesiredLabel) -> Self
pub fn worker_label(self, key: impl Into<String>, label: DesiredLabel) -> Self
Asks for a worker whose label key satisfies label.
Sourcepub fn description(self, description: impl Into<String>) -> Self
pub fn description(self, description: impl Into<String>) -> Self
Describes the task. Standalone registration only.
Sourcepub fn version(self, version: impl Into<String>) -> Self
pub fn version(self, version: impl Into<String>) -> Self
Labels this version of the task. Standalone registration only.
Sourcepub fn on_events(
self,
keys: impl IntoIterator<Item = impl Into<String>>,
) -> Self
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.
Sourcepub fn cron(self, expression: impl Into<String>) -> Self
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.
Sourcepub fn cron_input(self, input: Value) -> Self
pub fn cron_input(self, input: Value) -> Self
The input given to cron-triggered runs. Standalone registration only.
Sourcepub fn default_priority(self, priority: Priority) -> Self
pub fn default_priority(self, priority: Priority) -> Self
The priority of runs that do not specify one. Standalone registration only.
Sourcepub fn sticky(self, strategy: StickyStrategy) -> Self
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(()) });Sourcepub fn idempotency(self, idempotency: Idempotency) -> Self
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(()) });Sourcepub fn eviction_policy(self, policy: EvictionPolicy) -> Self
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(())
});Sourcepub fn handler<F, Fut>(self, handler: F) -> Task<I, O>
pub fn handler<F, Fut>(self, handler: F) -> Task<I, O>
Attaches the handler and finishes the declaration.
Sourcepub fn durable_handler<F, Fut>(self, handler: F) -> Task<I, O>
pub fn durable_handler<F, Fut>(self, handler: F) -> Task<I, O>
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)
});Sourcepub 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,
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
Ifails on its own, without being shown to the handler and without touching the rest. - A member the handler leaves out of the
BatchOutputis reported failed rather than left alone. Measured against a real engine, an unreported member staysRunninguntil the task times out and is never assigned again. - A handler that returns
Errfails 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::buildrefuses an older one, which would take the registration and then never batch anything. - It cannot set
retries: the declaration is refused withError::InvalidDeclarationrather than quietly forced to zero, as the official SDKs do. Failing a member with a retryableTaskErrorstill has the engine re-batch that member on its own. - It cannot be an
on_failureoron_successhook: 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)
},
);Sourcepub fn batch_broadcast_handler<F, Fut>(
self,
config: BatchConfig,
handler: F,
) -> Task<I, O>
pub fn batch_broadcast_handler<F, Fut>( self, config: BatchConfig, handler: F, ) -> Task<I, O>
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§
Auto Trait Implementations§
impl<I, O> Forget for TaskBuilder<I, O>
impl<I, O> Freeze for TaskBuilder<I, O>
impl<I, O> Move for TaskBuilder<I, O>
impl<I, O> RefUnwindSafe for TaskBuilder<I, O>
impl<I, O> Send for TaskBuilder<I, O>
impl<I, O> Sync for TaskBuilder<I, O>
impl<I, O> Unpin for TaskBuilder<I, O>
impl<I, O> UnsafeUnpin for TaskBuilder<I, O>
impl<I, O> UnwindSafe for TaskBuilder<I, O>
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> FutureExt for T
impl<T> FutureExt for T
Source§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
Source§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
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