Skip to main content

RunsClient

Struct RunsClient 

Source
pub struct RunsClient { /* private fields */ }
Expand description

Cancels, replays and inspects runs the engine already knows about.

Get one from Client::runs. Everything here is v1.AdminService over the same gRPC connection the rest of the SDK uses — no REST client and no extra credentials. The official Go and Python SDKs cancel and replay over the REST API instead (sdks/go/features/runs.go:130-147), which is why their argument shapes differ from these.

let run = task
    .run_no_wait(&client, &(), hatchet_client::RunOpts::default())
    .await?;

// Somewhere else, later: stop it.
let cancelled = client.runs().cancel([run.id()]).await?;
println!("cancelled {} run(s)", cancelled.len());

Implementations§

Source§

impl RunsClient

Source

pub async fn cancel( &self, ids: impl IntoIterator<Item = impl Into<String>>, ) -> Result<Vec<String>>

Cancels the runs named by ids, and hands back the ids the engine says it cancelled.

ids are workflow run ids — the same ids a RunHandle::id or WorkflowRunHandle::id hands back, or a run_id you got from RunsClient::details.

The answer is an echo of the request, not a report of effect: both supported engine versions echoed back an id they did not know, an already-cancelled run and an already-finished run alike, and refused only a malformed id (InvalidArgument). To learn whether a run was actually stopped, wait on its handle (it ends as Error::RunCancelled) or ask RunsClient::details.

§Errors

Error::InvalidArgument when ids is empty or holds a blank id — checked before any call, because an empty request is not a no-op to the engine. Otherwise Error::Grpc.

Source

pub async fn replay( &self, ids: impl IntoIterator<Item = impl Into<String>>, ) -> Result<Vec<String>>

Replays the runs named by ids — the engine runs them again from the start — and hands back the ids it says it replayed.

A replayed run keeps the id it was given here; it is not handed a new one.

§Retries

Like every unary call, a replay whose answer is lost to a transport error is retried, and the engine may then have replayed the run twice. Go’s REST client refuses to retry anything but a GET for the same reason; if a double replay would hurt, call details before retrying yourself.

§Errors

Those of cancel.

Source

pub async fn cancel_matching(&self, filter: TasksFilter) -> Result<Vec<String>>

Cancels every run that matches filter, and hands back the ids the engine says it cancelled.

The engine decides what “matches” means and the answer is the only record of what was hit, so read it: this is the one call in the SDK whose blast radius is not bounded by its arguments.

§Errors

Error::InvalidArgument when the filter contradicts itself (an until before its since) or holds a blank id or metadata key, and Error::Grpc when the call fails.

Source

pub async fn replay_matching(&self, filter: TasksFilter) -> Result<Vec<String>>

Replays every run that matches filter, and hands back the ids the engine says it replayed.

§Errors

Those of cancel_matching.

Source

pub async fn restore_evicted(&self, task_run_id: &str) -> Result<bool>

Asks the engine to queue an evicted task run again, now.

A task run is evicted when the worker holding it hands it back while it waits, because of the EvictionPolicy its task declared. The engine queues such a run again by itself as soon as what it was waiting for happens — measured at 0.7 to 1.5 seconds after the event, on both supported engines — so this is for the other case: an operator unsticking a run whose wait may never end.

task_run_id is a task run id, not a workflow run id — a TaskRunDetail::id, which details hands back through RunDetails::tasks. The same detail’s is_evicted is how to tell an evicted task run from a running one: an evicted one’s status stays RunStatus::Running.

§The answer is not proof

It is the engine’s requeued flag, and both supported versions were measured answering true unconditionally — including for a random UUID naming no run at all. So a true says the call was accepted, not that anything was queued; read details to learn what actually happened. It is returned rather than swallowed because the engine may one day mean something by it.

§Retries

Like every unary call, one whose answer is lost to a transport error is retried. Queueing a run that is already queued is what the engine was measured doing anyway, so a repeat costs nothing.

§Errors

Error::InvalidArgument when task_run_id is blank — checked before any call — and Error::Grpc when the call fails.

let details = client.runs().details(run_id).await?;
for (_name, task) in details.tasks() {
    if task.is_evicted() {
        client.runs().restore_evicted(task.id()).await?;
    }
}
Source

pub async fn details(&self, run_id: &str) -> Result<RunDetails>

What the engine remembers about the run called run_id.

Works for a run this process never triggered and for one that is still going — RunDetails::is_done says which.

§Errors

Error::InvalidArgument when run_id is blank; Error::UnsupportedFeature when the engine does not have the GetRunDetails RPC (answered Unimplemented); Error::UnknownRunStatus when it reports a status this SDK has no name for; and Error::Grpc otherwise.

Source

pub async fn stream(&self, run_id: &str) -> Result<OutputStream>

The output stream of the run called run_id: the chunks its handlers publish with Context::put_stream, in order.

Chunks are not replayed, so a subscription only ever sees what is published after the engine registers it. Opening one needs a run id, and a run id only exists once the run has been triggered — so this call cannot be made before the run starts, and a handler that publishes immediately may be a chunk or two ahead by the time the subscription is in place. That is not theoretical: against a v0.80.0 engine, a subscription opened four seconds after the trigger began at chunk 1 and chunk 0 was never delivered. When that matters, subscribe by metadata before triggering — see stream_by_metadata, the only race-free way to read a run’s output from the start.

This call waits up to five seconds for the engine to answer, and then hands back a stream that may still be being opened. That is the ordinary case rather than a failure: neither supported engine sends anything at all on a fresh subscription — not even response headers — until it has an event for it, which has been measured at nineteen seconds and more. The subscription is registered engine-side long before that, and it is that same one the stream goes on with, so nothing published in the meantime is lost.

The stream ends when the engine hangs up, when it fails in a way reconnecting cannot fix (the failure is the last item), or when it is dropped. Anything else — a dropped connection, a restarting engine — is resubscribed under the SDK’s stream backoff, and chunks already delivered are not delivered again. A hang-up means the engine closed this subscription, not that every chunk was delivered: a multi-task run on v0.80.0 hung up before its chunks arrived, and subscribing again then delivered them.

let mut chunks = client.runs().stream(run_id).await?;
while let Some(chunk) = chunks.next().await {
    print!("{}", chunk?.payload);
}
§Errors

Error::InvalidArgument when run_id is blank — checked before any call — and Error::Grpc when the engine refuses the subscription in a way reconnecting cannot fix: a rejected token, or a run id it does not know (NotFound). A failure that is worth retrying is not reported here: the stream is handed back and retries in the background, and gives up as Error::ResultStream on the stream itself.

Source

pub async fn stream_by_metadata( &self, key: &str, value: &str, ) -> Result<OutputStream>

The output streams of every run whose additional metadata has key set to value, on one subscription.

This is the race-free way to read a run’s output, because it does not need a run id: open the subscription, then trigger, and nothing can be published before the engine knows you are listening. StreamChunk::run_id is what tells the runs apart.

// A tag only this call will use, so the subscription matches this run
// and no other.
let tag = uuid_of_your_choosing();

// Listening first is the whole point: chunks are not replayed.
let mut chunks = client.runs().stream_by_metadata("job", &tag).await?;
let run = summarise
    .run_no_wait(
        &client,
        &"the document".to_string(),
        RunOpts::default().metadata("job", tag.as_str()),
    )
    .await?;

while let Some(chunk) = chunks.next().await {
    let chunk = chunk?;
    if chunk.run_id == run.id() {
        print!("{}", chunk.payload);
    }
}

value is matched as text against the run’s metadata value, so a metadata value that is not a string (a number, an object) has no text form to give here.

This call waits up to five seconds for the engine to answer, as stream does — and here it nearly always uses the whole five, because a subscription opened before anything is triggered has nothing to match yet and the engine answers it only when it does. The wait costs latency, not chunks: the subscription is registered before the answer comes, and the stream carries on with that same one.

Nothing ends this stream on its own by design — it covers runs that have not been triggered yet, so there is no point at which the engine can say there will be no more — but the engine does hang up on it once the runs it matched are over, and a hang-up ends the stream. Open a new one to keep watching, drop it when you are done, and keep a time limit of your own around a wait for a chunk that may never come.

§Errors

Error::InvalidArgument when key or value is blank, and Error::Grpc as for stream.

Trait Implementations§

Source§

impl Clone for RunsClient

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RunsClient

Source§

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

Formats the value using the given formatter. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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