hatchet_rest/runs.rs
1//! Workflow runs and the tasks in them: read (`get`, `status`, `list`),
2//! act on (`cancel`, `replay`, `restore`) and branch a durable task.
3//!
4//! `hatchet-client` reaches cancel, replay, restore and a run's details
5//! over gRPC as well (`RunsClient`). Both work; the REST calls here are the
6//! ones the official Go SDK's `RunsClient` makes
7//! (`sdks/go/features/runs.go`), and listing, the status alone, logs and
8//! durable branching exist only here. A process that only runs workers and
9//! triggers runs needs no REST client.
10
11use std::time::{SystemTime, UNIX_EPOCH};
12
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15
16use crate::time::{deserialize, deserialize_option, format_rfc3339};
17use crate::transport::{Query, metadata_pairs};
18use crate::types::string_enum;
19use crate::{Error, JsonObject, Operation, Page, ResourceMeta, RestClient, Result};
20
21// ---------------------------------------------------------------------------
22// Types.
23
24string_enum! {
25 /// A run's or task's status (`V1TaskStatus`). Unlike `hatchet-client`'s
26 /// gRPC `RunStatus` there is no `EVICTED` here — see
27 /// [`TaskSummary::is_evicted`].
28 TaskStatus {
29 /// Waiting for a worker.
30 Queued => "QUEUED",
31 /// On a worker.
32 Running => "RUNNING",
33 /// Finished with output.
34 Completed => "COMPLETED",
35 /// Stopped before it finished.
36 Cancelled => "CANCELLED",
37 /// Finished with an error.
38 Failed => "FAILED",
39 }
40}
41
42impl TaskStatus {
43 /// Whether the status is final (completed, cancelled or failed).
44 #[must_use]
45 pub fn is_done(&self) -> bool {
46 matches!(self, Self::Completed | Self::Cancelled | Self::Failed)
47 }
48}
49
50string_enum! {
51 /// Whether a listed row is a whole DAG or a single task
52 /// (`V1WorkflowType`).
53 RunKind {
54 /// A workflow of several tasks.
55 Dag => "DAG",
56 /// A task.
57 Task => "TASK",
58 }
59}
60
61string_enum! {
62 /// How several metadata pairs combine in a run list
63 /// (`V1AdditionalMetadataOperator`; not in the v0.80.0 spec).
64 MetadataOperator {
65 /// Runs carrying any of the pairs.
66 Or => "OR",
67 /// Runs carrying all of them.
68 And => "AND",
69 }
70}
71
72string_enum! {
73 /// Which running tasks a run list returns (`V1RunningFilter`).
74 RunningFilter {
75 /// On a worker or evicted.
76 All => "ALL",
77 /// Evicted only.
78 Evicted => "EVICTED",
79 /// On a worker only.
80 OnWorker => "ON_WORKER",
81 }
82}
83
84/// A task run (or a DAG run, in a list) as a list shows it
85/// (`V1TaskSummary`).
86///
87/// Optional timestamps the engine leaves unset arrive as Go's zero time and
88/// read as `None`.
89#[derive(Clone, Debug, Deserialize)]
90#[serde(rename_all = "camelCase")]
91#[non_exhaustive]
92pub struct TaskSummary {
93 /// Id and timestamps of the row.
94 pub metadata: ResourceMeta,
95 /// The task run's id — what [`RunsApi::cancel`], [`RunsApi::replay`],
96 /// [`RunsApi::restore`] and [`LogsApi::list`](crate::LogsApi::list)
97 /// take. For a DAG row it is the workflow run's id.
98 pub task_external_id: String,
99 /// The engine's internal task id.
100 pub task_id: i64,
101 /// The workflow run it belongs to.
102 pub workflow_run_external_id: String,
103 /// The workflow's id.
104 pub workflow_id: String,
105 /// The name the dashboard shows.
106 pub display_name: String,
107 /// Its status.
108 pub status: TaskStatus,
109 /// A DAG row or a task row.
110 #[serde(rename = "type")]
111 pub kind: RunKind,
112 /// The tenant.
113 pub tenant_id: String,
114 /// When it was created. The spec calls it required, but both supported
115 /// engines send Go's zero time for the tasks of
116 /// [`RunsApi::get`], which reads as `None`.
117 #[serde(default, deserialize_with = "deserialize_option")]
118 pub created_at: Option<SystemTime>,
119 /// When the task row was inserted.
120 #[serde(deserialize_with = "deserialize")]
121 pub task_inserted_at: SystemTime,
122 /// How many children it spawned.
123 #[serde(default)]
124 pub num_spawned_children: i64,
125 /// Its input (`{}` in a run list's rows unless payloads are included).
126 #[serde(default)]
127 pub input: Value,
128 /// Its output (`{}` until it has one).
129 #[serde(default)]
130 pub output: Value,
131 /// Additional metadata.
132 #[serde(default)]
133 pub additional_metadata: Option<JsonObject>,
134 /// The action id (`workflow:task`; empty on a DAG row).
135 #[serde(default)]
136 pub action_id: Option<String>,
137 /// Retries so far.
138 #[serde(default)]
139 pub retry_count: Option<i64>,
140 /// The attempt number.
141 #[serde(default)]
142 pub attempt: Option<i64>,
143 /// Child rows (a DAG's tasks), when the engine includes them.
144 #[serde(default)]
145 pub children: Vec<TaskSummary>,
146 /// Run time in milliseconds.
147 #[serde(default)]
148 pub duration: Option<i64>,
149 /// Whether it is a durable task (not sent by v0.80.0).
150 #[serde(default)]
151 pub is_durable: Option<bool>,
152 /// Whether it is evicted — the one way to see eviction over REST.
153 #[serde(default)]
154 pub is_evicted: Option<bool>,
155 /// The error, for a failed task; the engine sends `""` otherwise.
156 #[serde(default)]
157 pub error_message: Option<String>,
158 /// When it started.
159 #[serde(default, deserialize_with = "deserialize_option")]
160 pub started_at: Option<SystemTime>,
161 /// When it finished.
162 #[serde(default, deserialize_with = "deserialize_option")]
163 pub finished_at: Option<SystemTime>,
164 /// The step id.
165 #[serde(default)]
166 pub step_id: Option<String>,
167 /// The workflow's name.
168 #[serde(default)]
169 pub workflow_name: Option<String>,
170 /// The workflow version.
171 #[serde(default)]
172 pub workflow_version_id: Option<String>,
173 /// The parent task run, for a child.
174 #[serde(default)]
175 pub parent_task_external_id: Option<String>,
176 /// The idempotency key, when one applied (not sent by v0.80.0).
177 #[serde(default)]
178 pub idempotency_key: Option<String>,
179 /// Fields this crate does not model (`workflowConfig`,
180 /// `payloadsRestricted`, …), as the engine sent them.
181 #[serde(flatten)]
182 pub other: JsonObject,
183}
184
185/// A workflow run (`V1WorkflowRun`).
186#[derive(Clone, Debug, Deserialize)]
187#[serde(rename_all = "camelCase")]
188#[non_exhaustive]
189pub struct WorkflowRun {
190 /// Id and timestamps; `metadata.id` is the run id.
191 pub metadata: ResourceMeta,
192 /// Its status.
193 pub status: TaskStatus,
194 /// The tenant.
195 pub tenant_id: String,
196 /// The name the dashboard shows.
197 pub display_name: String,
198 /// The workflow's id.
199 pub workflow_id: String,
200 /// Its input.
201 #[serde(default)]
202 pub input: Value,
203 /// Its output.
204 #[serde(default)]
205 pub output: Value,
206 /// Additional metadata.
207 #[serde(default)]
208 pub additional_metadata: Option<JsonObject>,
209 /// The error, for a failed run; the engine sends `""` otherwise.
210 #[serde(default)]
211 pub error_message: Option<String>,
212 /// When it was created.
213 #[serde(default, deserialize_with = "deserialize_option")]
214 pub created_at: Option<SystemTime>,
215 /// When it started.
216 #[serde(default, deserialize_with = "deserialize_option")]
217 pub started_at: Option<SystemTime>,
218 /// When it finished.
219 #[serde(default, deserialize_with = "deserialize_option")]
220 pub finished_at: Option<SystemTime>,
221 /// Run time in milliseconds.
222 #[serde(default)]
223 pub duration: Option<i64>,
224 /// The workflow version.
225 #[serde(default)]
226 pub workflow_version_id: Option<String>,
227 /// The parent task run, for a child run.
228 #[serde(default)]
229 pub parent_task_external_id: Option<String>,
230 /// Fields this crate does not model, as the engine sent them.
231 #[serde(flatten)]
232 pub other: JsonObject,
233}
234
235/// One event in a task run's history (`V1TaskEvent`).
236#[derive(Clone, Debug, Deserialize)]
237#[serde(rename_all = "camelCase")]
238#[non_exhaustive]
239pub struct TaskEvent {
240 /// The event's id.
241 pub id: i64,
242 /// The task run it is about.
243 pub task_id: String,
244 /// When it happened.
245 #[serde(deserialize_with = "deserialize")]
246 pub timestamp: SystemTime,
247 /// What happened, as the spec's `V1TaskEventType` spells it
248 /// (`"STARTED"`, `"FINISHED"`, `"FAILED"`, …). The set grows between
249 /// engine versions, so it is kept as text.
250 pub event_type: String,
251 /// The engine's message.
252 #[serde(default)]
253 pub message: String,
254 /// The error, for a failure.
255 #[serde(default)]
256 pub error_message: Option<String>,
257 /// The output, as text.
258 #[serde(default)]
259 pub output: Option<String>,
260 /// The worker, when one was involved.
261 #[serde(default)]
262 pub worker_id: Option<String>,
263 /// The task's display name.
264 #[serde(default)]
265 pub task_display_name: Option<String>,
266 /// The retry it belongs to.
267 #[serde(default)]
268 pub retry_count: Option<i64>,
269 /// The attempt it belongs to.
270 #[serde(default)]
271 pub attempt: Option<i64>,
272 /// Fields this crate does not model, as the engine sent them.
273 #[serde(flatten)]
274 pub other: JsonObject,
275}
276
277/// A workflow run with its tasks and history (`V1WorkflowRunDetails`).
278#[derive(Clone, Debug, Deserialize)]
279#[serde(rename_all = "camelCase")]
280#[non_exhaustive]
281pub struct WorkflowRunDetails {
282 /// The run.
283 pub run: WorkflowRun,
284 /// Its tasks.
285 #[serde(default)]
286 pub tasks: Vec<TaskSummary>,
287 /// The events of its tasks.
288 #[serde(default)]
289 pub task_events: Vec<TaskEvent>,
290 /// The DAG's shape as the engine sends it: a list of task nodes
291 /// (`taskExternalId`, `stepId`, `taskName`, `childrenStepIds`).
292 #[serde(default)]
293 pub shape: Value,
294 /// Fields this crate does not model (`workflowConfig`, …), as the
295 /// engine sent them.
296 #[serde(flatten)]
297 pub other: JsonObject,
298}
299
300/// The answer to [`RunsApi::branch_durable_task`]
301/// (`V1BranchDurableTaskResponse`).
302#[derive(Clone, Debug, Deserialize)]
303#[serde(rename_all = "camelCase")]
304#[non_exhaustive]
305pub struct DurableBranch {
306 /// The durable task run.
307 pub task_external_id: String,
308 /// The node the branch replays from.
309 pub node_id: i64,
310 /// The branch.
311 pub branch_id: i64,
312}
313
314// ---------------------------------------------------------------------------
315// Requests.
316
317/// Which runs [`RunsApi::list`] returns. Only the settings given a value
318/// are sent, except `since` and `only_tasks`, which are always sent.
319///
320/// ```
321/// use std::time::{Duration, SystemTime};
322/// use hatchet_rest::{RunListQuery, TaskStatus};
323///
324/// let query = RunListQuery::new()
325/// .since(SystemTime::now() - Duration::from_secs(3600))
326/// .statuses([TaskStatus::Failed])
327/// .additional_metadata([("customer", "acme")])
328/// .limit(20);
329/// # let _ = query;
330/// ```
331#[derive(Clone, Debug, Default)]
332#[must_use]
333pub struct RunListQuery {
334 since: Option<SystemTime>,
335 until: Option<SystemTime>,
336 statuses: Vec<TaskStatus>,
337 workflow_ids: Vec<String>,
338 worker_id: Option<String>,
339 only_tasks: bool,
340 parent_task_external_id: Option<String>,
341 triggering_event_external_id: Option<String>,
342 additional_metadata: Vec<String>,
343 metadata_operator: Option<MetadataOperator>,
344 include_payloads: Option<bool>,
345 running_filter: Option<RunningFilter>,
346 idempotency_keys: Vec<String>,
347 offset: Option<i64>,
348 limit: Option<i64>,
349}
350
351impl RunListQuery {
352 /// Every run, DAG rows and task rows alike (`only_tasks=false`, as in
353 /// the official Python SDK).
354 ///
355 /// Without [`since`](Self::since) the query asks for runs since
356 /// 1970-01-01 — v0.107.0 refuses a run list without `since` (`400`),
357 /// so it is always sent.
358 pub fn new() -> Self {
359 Self::default()
360 }
361
362 /// Runs created at or after `since`.
363 pub fn since(mut self, since: SystemTime) -> Self {
364 self.since = Some(since);
365 self
366 }
367
368 /// Runs created before `until`.
369 pub fn until(mut self, until: SystemTime) -> Self {
370 self.until = Some(until);
371 self
372 }
373
374 /// Only these statuses.
375 pub fn statuses(mut self, statuses: impl IntoIterator<Item = TaskStatus>) -> Self {
376 self.statuses.extend(statuses);
377 self
378 }
379
380 /// Only these workflows (by id).
381 pub fn workflow_ids(mut self, ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
382 self.workflow_ids.extend(ids.into_iter().map(Into::into));
383 self
384 }
385
386 /// Only runs on this worker.
387 pub fn worker_id(mut self, id: impl Into<String>) -> Self {
388 self.worker_id = Some(id.into());
389 self
390 }
391
392 /// Task rows only, no DAG rows.
393 pub fn only_tasks(mut self, only_tasks: bool) -> Self {
394 self.only_tasks = only_tasks;
395 self
396 }
397
398 /// Only children of this task run.
399 pub fn parent_task_external_id(mut self, id: impl Into<String>) -> Self {
400 self.parent_task_external_id = Some(id.into());
401 self
402 }
403
404 /// Only runs this event triggered.
405 pub fn triggering_event_external_id(mut self, id: impl Into<String>) -> Self {
406 self.triggering_event_external_id = Some(id.into());
407 self
408 }
409
410 /// Only runs carrying these metadata pairs, sent as `"key:value"`.
411 /// How several pairs combine is the engine's default unless
412 /// [`metadata_operator`](Self::metadata_operator) says otherwise.
413 pub fn additional_metadata<K: AsRef<str>, V: AsRef<str>>(
414 mut self,
415 pairs: impl IntoIterator<Item = (K, V)>,
416 ) -> Self {
417 self.additional_metadata.extend(metadata_pairs(pairs));
418 self
419 }
420
421 /// How several metadata pairs combine. Not in the v0.80.0 spec.
422 pub fn metadata_operator(mut self, operator: MetadataOperator) -> Self {
423 self.metadata_operator = Some(operator);
424 self
425 }
426
427 /// Whether rows carry inputs and outputs.
428 pub fn include_payloads(mut self, include: bool) -> Self {
429 self.include_payloads = Some(include);
430 self
431 }
432
433 /// Which running tasks to return.
434 pub fn running_filter(mut self, filter: RunningFilter) -> Self {
435 self.running_filter = Some(filter);
436 self
437 }
438
439 /// Only runs with these idempotency keys. Not in the v0.80.0 spec, and
440 /// a v0.80.0 engine was observed to ignore it (every run is listed).
441 pub fn idempotency_keys(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
442 self.idempotency_keys
443 .extend(keys.into_iter().map(Into::into));
444 self
445 }
446
447 /// Skip this many.
448 pub fn offset(mut self, offset: i64) -> Self {
449 self.offset = Some(offset);
450 self
451 }
452
453 /// At most this many.
454 pub fn limit(mut self, limit: i64) -> Self {
455 self.limit = Some(limit);
456 self
457 }
458
459 fn query(&self) -> Query {
460 let mut query = Query::new();
461 query.push("since", format_rfc3339(self.since.unwrap_or(UNIX_EPOCH)));
462 query.push_opt("until", self.until.map(format_rfc3339));
463 query.push("only_tasks", self.only_tasks);
464 query.push_all("statuses", &self.statuses);
465 query.push_all("workflow_ids", &self.workflow_ids);
466 query.push_opt("worker_id", self.worker_id.as_deref());
467 query.push_opt(
468 "parent_task_external_id",
469 self.parent_task_external_id.as_deref(),
470 );
471 query.push_opt(
472 "triggering_event_external_id",
473 self.triggering_event_external_id.as_deref(),
474 );
475 query.push_all("additional_metadata", &self.additional_metadata);
476 query.push_opt(
477 "additional_metadata_operator",
478 self.metadata_operator.as_ref(),
479 );
480 query.push_opt("include_payloads", self.include_payloads);
481 query.push_opt("running_filter", self.running_filter.as_ref());
482 query.push_all("idempotency_keys", &self.idempotency_keys);
483 query.push_opt("offset", self.offset);
484 query.push_opt("limit", self.limit);
485 query
486 }
487}
488
489/// The filter half of a [`RunSelector`] (`V1TaskFilter`). Every condition
490/// set here has to hold.
491///
492/// **A filter that narrows nothing is refused.** With no statuses, no
493/// workflow ids and no metadata, the filter matches every run of the
494/// tenant in its time window; [`RunsApi::cancel`] and [`RunsApi::replay`]
495/// return [`Error::InvalidArgument`] instead of sending it. `since` and
496/// `until` alone do not count as narrowing. This is the SDK's rule, not the
497/// engine's — the same one `hatchet-client`'s `TasksFilter` applies.
498///
499/// ```
500/// use std::time::{Duration, SystemTime};
501/// use hatchet_rest::{TaskFilter, TaskStatus};
502///
503/// let filter = TaskFilter::new()
504/// .since(SystemTime::now() - Duration::from_secs(3600))
505/// .statuses([TaskStatus::Failed])
506/// .additional_metadata([("customer", "acme")]);
507/// # let _ = filter;
508/// ```
509#[derive(Clone, Debug, Default)]
510#[must_use]
511pub struct TaskFilter {
512 since: Option<SystemTime>,
513 until: Option<SystemTime>,
514 statuses: Vec<TaskStatus>,
515 workflow_ids: Vec<String>,
516 additional_metadata: Vec<String>,
517}
518
519impl TaskFilter {
520 /// A filter with no conditions yet. The API requires `since`; without
521 /// [`since`](Self::since) the filter is sent with 1970-01-01.
522 pub fn new() -> Self {
523 Self::default()
524 }
525
526 /// Runs created at or after `since`.
527 pub fn since(mut self, since: SystemTime) -> Self {
528 self.since = Some(since);
529 self
530 }
531
532 /// Runs created before `until`.
533 pub fn until(mut self, until: SystemTime) -> Self {
534 self.until = Some(until);
535 self
536 }
537
538 /// Only these statuses.
539 pub fn statuses(mut self, statuses: impl IntoIterator<Item = TaskStatus>) -> Self {
540 self.statuses.extend(statuses);
541 self
542 }
543
544 /// Only these workflows (by id).
545 pub fn workflow_ids(mut self, ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
546 self.workflow_ids.extend(ids.into_iter().map(Into::into));
547 self
548 }
549
550 /// Only runs carrying these metadata pairs, sent as `"key:value"`.
551 pub fn additional_metadata<K: AsRef<str>, V: AsRef<str>>(
552 mut self,
553 pairs: impl IntoIterator<Item = (K, V)>,
554 ) -> Self {
555 self.additional_metadata.extend(metadata_pairs(pairs));
556 self
557 }
558}
559
560/// Which task runs [`RunsApi::cancel`] and [`RunsApi::replay`] act on:
561/// named ones, or the ones a [`TaskFilter`] matches — never both.
562#[derive(Clone, Debug)]
563#[must_use]
564pub struct RunSelector {
565 ids: Vec<String>,
566 filter: Option<TaskFilter>,
567}
568
569impl RunSelector {
570 /// These runs, by id. The engine takes a task run's id
571 /// ([`TaskSummary::task_external_id`]) or a workflow run's id (the
572 /// whole run).
573 pub fn ids(ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
574 Self {
575 ids: ids.into_iter().map(Into::into).collect(),
576 filter: None,
577 }
578 }
579
580 /// The task runs `filter` matches.
581 pub fn filter(filter: TaskFilter) -> Self {
582 Self {
583 ids: Vec::new(),
584 filter: Some(filter),
585 }
586 }
587
588 fn body(&self) -> Result<SelectorBody<'_>> {
589 let Some(filter) = &self.filter else {
590 if self.ids.is_empty() {
591 return Err(Error::InvalidArgument(
592 "a run selector needs at least one id".into(),
593 ));
594 }
595 if self.ids.iter().any(String::is_empty) {
596 return Err(Error::InvalidArgument(
597 "a run selector's ids must not be empty".into(),
598 ));
599 }
600 return Ok(SelectorBody {
601 external_ids: &self.ids,
602 filter: None,
603 });
604 };
605 if filter.statuses.is_empty()
606 && filter.workflow_ids.is_empty()
607 && filter.additional_metadata.is_empty()
608 {
609 return Err(Error::InvalidArgument(
610 "a run filter must narrow by statuses, workflow ids or metadata; `since` and \
611 `until` alone would act on every run of the tenant in that window"
612 .into(),
613 ));
614 }
615 Ok(SelectorBody {
616 external_ids: &[],
617 filter: Some(FilterBody {
618 since: format_rfc3339(filter.since.unwrap_or(UNIX_EPOCH)),
619 until: filter.until.map(format_rfc3339),
620 statuses: &filter.statuses,
621 workflow_ids: &filter.workflow_ids,
622 additional_metadata: &filter.additional_metadata,
623 }),
624 })
625 }
626}
627
628#[derive(Serialize)]
629#[serde(rename_all = "camelCase")]
630struct SelectorBody<'a> {
631 #[serde(skip_serializing_if = "<[String]>::is_empty")]
632 external_ids: &'a [String],
633 #[serde(skip_serializing_if = "Option::is_none")]
634 filter: Option<FilterBody<'a>>,
635}
636
637#[derive(Serialize)]
638#[serde(rename_all = "camelCase")]
639struct FilterBody<'a> {
640 since: String,
641 #[serde(skip_serializing_if = "Option::is_none")]
642 until: Option<String>,
643 #[serde(skip_serializing_if = "<[TaskStatus]>::is_empty")]
644 statuses: &'a [TaskStatus],
645 #[serde(skip_serializing_if = "<[String]>::is_empty")]
646 workflow_ids: &'a [String],
647 #[serde(skip_serializing_if = "<[String]>::is_empty")]
648 additional_metadata: &'a [String],
649}
650
651#[derive(Deserialize)]
652struct Ids {
653 #[serde(default)]
654 ids: Vec<String>,
655}
656
657#[derive(Deserialize)]
658struct Requeued {
659 requeued: bool,
660}
661
662#[derive(Serialize)]
663#[serde(rename_all = "camelCase")]
664struct BranchBody<'a> {
665 task_external_id: &'a str,
666 node_id: i64,
667 branch_id: i64,
668}
669
670// ---------------------------------------------------------------------------
671// The endpoint.
672
673/// Workflow runs and task runs; from [`RestClient::runs`].
674#[derive(Clone, Copy, Debug)]
675pub struct RunsApi<'a> {
676 pub(crate) client: &'a RestClient,
677}
678
679impl RunsApi<'_> {
680 /// A workflow run with its tasks and events (`v1-workflow-run:get`).
681 ///
682 /// ```no_run
683 /// # async fn example(rest: hatchet_rest::RestClient, run_id: &str) -> hatchet_rest::Result<()> {
684 /// let details = rest.runs().get(run_id).await?;
685 /// println!("{}: {}", details.run.display_name, details.run.status);
686 /// for task in &details.tasks {
687 /// println!(" {} {}", task.display_name, task.status);
688 /// }
689 /// # Ok(())
690 /// # }
691 /// ```
692 ///
693 /// # Errors
694 ///
695 /// [`Error::NotFound`] for a run the engine does not know;
696 /// [`Error::InvalidArgument`] for an empty id, before anything is sent;
697 /// otherwise as for any call (see [`Error`]).
698 pub async fn get(&self, run_id: &str) -> Result<WorkflowRunDetails> {
699 self.client
700 .inner
701 .call(Operation::V1WorkflowRunGet, &[run_id], Query::new())
702 .await
703 }
704
705 /// Just a workflow run's status (`v1-workflow-run:get-status`).
706 ///
707 /// ```no_run
708 /// # async fn example(rest: hatchet_rest::RestClient, run_id: &str) -> hatchet_rest::Result<()> {
709 /// if rest.runs().status(run_id).await?.is_done() {
710 /// println!("finished");
711 /// }
712 /// # Ok(())
713 /// # }
714 /// ```
715 ///
716 /// # Errors
717 ///
718 /// As for [`get`](Self::get).
719 pub async fn status(&self, run_id: &str) -> Result<TaskStatus> {
720 self.client
721 .inner
722 .call(Operation::V1WorkflowRunGetStatus, &[run_id], Query::new())
723 .await
724 }
725
726 /// Lists runs, newest first (`v1-workflow-run:list`).
727 ///
728 /// The engine's own status bookkeeping trails what a handler has
729 /// already done, so a run that just finished may still list as
730 /// `RUNNING` for a moment; to find one run you just triggered, narrow
731 /// by a metadata tag rather than by status.
732 ///
733 /// ```no_run
734 /// # async fn example(rest: hatchet_rest::RestClient) -> hatchet_rest::Result<()> {
735 /// use hatchet_rest::{RunListQuery, TaskStatus};
736 ///
737 /// let page = rest
738 /// .runs()
739 /// .list(RunListQuery::new().statuses([TaskStatus::Failed]).limit(20))
740 /// .await?;
741 /// for run in &page.rows {
742 /// println!("{} {:?}", run.display_name, run.error_message);
743 /// }
744 /// # Ok(())
745 /// # }
746 /// ```
747 ///
748 /// # Errors
749 ///
750 /// As for any call (see [`Error`]).
751 pub async fn list(&self, query: RunListQuery) -> Result<Page<TaskSummary>> {
752 self.client
753 .inner
754 .call(Operation::V1WorkflowRunList, &[], query.query())
755 .await
756 }
757
758 /// Cancels runs (`v1-task:cancel`) and returns the ids the engine
759 /// reports as cancelled. Sent once, never retried. The engine answers
760 /// with the ids it accepted — including a run that had already
761 /// finished — so an id in the answer does not prove the run was still
762 /// going.
763 ///
764 /// ```no_run
765 /// # async fn example(rest: hatchet_rest::RestClient, run_id: &str) -> hatchet_rest::Result<()> {
766 /// use hatchet_rest::RunSelector;
767 ///
768 /// let cancelled = rest.runs().cancel(RunSelector::ids([run_id])).await?;
769 /// println!("cancelled {cancelled:?}");
770 /// # Ok(())
771 /// # }
772 /// ```
773 ///
774 /// # Errors
775 ///
776 /// [`Error::InvalidArgument`] for a selector with no ids, an empty id,
777 /// or a [`TaskFilter`] that narrows nothing, before anything is sent;
778 /// otherwise as for any call (see [`Error`]).
779 pub async fn cancel(&self, selector: RunSelector) -> Result<Vec<String>> {
780 let body = selector.body()?;
781 let ids: Ids = self
782 .client
783 .inner
784 .call_json(Operation::V1TaskCancel, &[], &body)
785 .await?;
786 Ok(ids.ids)
787 }
788
789 /// Replays runs (`v1-task:replay`) and returns the ids the engine
790 /// reports as replayed. Sent once, never retried.
791 ///
792 /// ```no_run
793 /// # async fn example(rest: hatchet_rest::RestClient) -> hatchet_rest::Result<()> {
794 /// use hatchet_rest::{RunSelector, TaskFilter, TaskStatus};
795 ///
796 /// let filter = TaskFilter::new()
797 /// .statuses([TaskStatus::Failed])
798 /// .additional_metadata([("batch", "2026-09-26")]);
799 /// let replayed = rest.runs().replay(RunSelector::filter(filter)).await?;
800 /// println!("replayed {}", replayed.len());
801 /// # Ok(())
802 /// # }
803 /// ```
804 ///
805 /// # Errors
806 ///
807 /// As for [`cancel`](Self::cancel).
808 pub async fn replay(&self, selector: RunSelector) -> Result<Vec<String>> {
809 let body = selector.body()?;
810 let ids: Ids = self
811 .client
812 .inner
813 .call_json(Operation::V1TaskReplay, &[], &body)
814 .await?;
815 Ok(ids.ids)
816 }
817
818 /// Requeues an evicted durable task run (`v1-task:restore`); `true`
819 /// when the engine reports it requeued. Sent once, never retried. Both
820 /// supported engines answer `true` for a task run that was not evicted
821 /// at all (one that had completed, say), so `true` is not proof that
822 /// anything was requeued.
823 ///
824 /// ```no_run
825 /// # async fn example(rest: hatchet_rest::RestClient, task_run_id: &str) -> hatchet_rest::Result<()> {
826 /// let requeued = rest.runs().restore(task_run_id).await?;
827 /// # let _ = requeued;
828 /// # Ok(())
829 /// # }
830 /// ```
831 ///
832 /// # Errors
833 ///
834 /// [`Error::NotFound`] for a task run the engine does not know;
835 /// otherwise as for [`get`](Self::get).
836 pub async fn restore(&self, task_run_id: &str) -> Result<bool> {
837 let answer: Requeued = self
838 .client
839 .inner
840 .call(Operation::V1TaskRestore, &[task_run_id], Query::new())
841 .await?;
842 Ok(answer.requeued)
843 }
844
845 /// Branches a durable task run: replays it from `node_id` of branch
846 /// `branch_id` (`v1-durable-task:branch`). Sent once, never retried.
847 ///
848 /// ```no_run
849 /// # async fn example(rest: hatchet_rest::RestClient, task_run_id: &str) -> hatchet_rest::Result<()> {
850 /// let branch = rest.runs().branch_durable_task(task_run_id, 3, 1).await?;
851 /// println!("branch {} from node {}", branch.branch_id, branch.node_id);
852 /// # Ok(())
853 /// # }
854 /// ```
855 ///
856 /// # Errors
857 ///
858 /// Both supported engines answer a task run that is not durable (or a
859 /// node or branch that does not exist) with `500`, which is
860 /// [`Error::Http`], not [`Error::InvalidArgument`] or
861 /// [`Error::NotFound`]; retrying does not help. [`Error::InvalidArgument`]
862 /// for an empty task run id, before anything is sent. Otherwise as for
863 /// any call (see [`Error`]).
864 pub async fn branch_durable_task(
865 &self,
866 task_run_id: &str,
867 node_id: i64,
868 branch_id: i64,
869 ) -> Result<DurableBranch> {
870 if task_run_id.is_empty() {
871 return Err(Error::InvalidArgument(
872 "branching a durable task needs a non-empty task run id".into(),
873 ));
874 }
875 let body = BranchBody {
876 task_external_id: task_run_id,
877 node_id,
878 branch_id,
879 };
880 self.client
881 .inner
882 .call_json(Operation::V1DurableTaskBranch, &[], &body)
883 .await
884 }
885}
886
887impl RestClient {
888 /// Workflow runs and task runs: `get`, `status`, `list`, `cancel`,
889 /// `replay`, `restore`, `branch_durable_task`.
890 pub fn runs(&self) -> RunsApi<'_> {
891 RunsApi { client: self }
892 }
893}