Skip to main content

hatchet_client/runs/
details.rs

1//! What the engine remembers about a run.
2
3use std::collections::BTreeMap;
4
5use hatchet_proto::v1;
6use serde::de::DeserializeOwned;
7
8use crate::Task;
9use crate::error::{Error, Result};
10use crate::runs::filter::RunStatus;
11
12/// Everything `GetRunDetails` knows about one run.
13///
14/// Get one from [`RunsClient::details`](crate::RunsClient::details). Unlike
15/// a [`WorkflowResult`](crate::WorkflowResult), which only exists for a run
16/// this process waited for, this can be asked for at any time — including
17/// for a run started by another process, or one that is still going.
18///
19/// ```no_run
20/// # use hatchet_client::{Client, Task};
21/// # async fn example(client: &Client, publish: &Task<(), ()>) -> hatchet_client::Result<()> {
22/// let details = client.runs().details("some-run-id").await?;
23/// println!("{}: done={}", details.status(), details.is_done());
24/// if let Some(task) = details.task(publish) {
25///     println!("{}: {:?}", task.name(), task.error());
26/// }
27/// # Ok(())
28/// # }
29/// ```
30#[derive(Clone, Debug)]
31pub struct RunDetails {
32    run_id: String,
33    status: RunStatus,
34    done: bool,
35    is_evicted: bool,
36    input: Vec<u8>,
37    additional_metadata: Vec<u8>,
38    /// Keyed by readable id (the task's declared name). The proto comment on
39    /// `GetRunDetailsResponse.task_runs` calls the map key the task run's
40    /// external id, but both the official Go and Python SDKs read it as the
41    /// readable id (`pkg/client/admin.go:734-755`,
42    /// `sdks/python/hatchet_sdk/clients/admin.py:716-730`) — so the map key
43    /// on the wire is not trusted here either; this is keyed by each value's
44    /// own `readable_id` field, which is right regardless of what the key
45    /// turns out to mean.
46    tasks: BTreeMap<String, TaskRunDetail>,
47}
48
49/// What the engine knows about one task of a run.
50///
51/// Get one from [`RunDetails::task`], [`RunDetails::task_by_name`] or
52/// [`RunDetails::tasks`].
53///
54/// ```no_run
55/// # use hatchet_client::RunDetails;
56/// # fn example(details: &RunDetails) {
57/// for (name, task) in details.tasks() {
58///     println!("{name}: {} (evicted: {})", task.status(), task.is_evicted());
59/// }
60/// # }
61/// ```
62#[derive(Clone, Debug)]
63pub struct TaskRunDetail {
64    external_id: String,
65    readable_id: String,
66    status: RunStatus,
67    error: Option<String>,
68    output: Option<Vec<u8>>,
69    is_evicted: bool,
70}
71
72impl RunDetails {
73    pub(crate) fn from_proto(run_id: &str, response: v1::GetRunDetailsResponse) -> Result<Self> {
74        let unknown = |status: i32| Error::UnknownRunStatus {
75            run_id: run_id.to_string(),
76            status,
77        };
78        let mut tasks = BTreeMap::new();
79        for detail in response.task_runs.into_values() {
80            let task = TaskRunDetail {
81                readable_id: detail.readable_id.clone(),
82                external_id: detail.external_id,
83                status: RunStatus::from_proto(detail.status)
84                    .ok_or_else(|| unknown(detail.status))?,
85                // An empty error is reported even on success (measured
86                // against both supported engines); an empty string is not
87                // an error, so it is normalized away here.
88                error: detail.error.filter(|error| !error.is_empty()),
89                output: detail.output,
90                is_evicted: detail.is_evicted,
91            };
92            tasks.insert(detail.readable_id, task);
93        }
94        Ok(Self {
95            run_id: run_id.to_string(),
96            status: RunStatus::from_proto(response.status)
97                .ok_or_else(|| unknown(response.status))?,
98            done: response.done,
99            is_evicted: response.is_evicted,
100            input: response.input,
101            additional_metadata: response.additional_metadata,
102            tasks,
103        })
104    }
105
106    /// The engine's id for this run.
107    pub fn run_id(&self) -> &str {
108        &self.run_id
109    }
110
111    /// The run's state as a whole.
112    pub fn status(&self) -> RunStatus {
113        self.status
114    }
115
116    /// Whether the engine considers the run over.
117    pub fn is_done(&self) -> bool {
118        self.done
119    }
120
121    /// The engine's `is_evicted` flag for the run (what exactly it covers
122    /// was not measured; it was `false` in every observed run).
123    pub fn is_evicted(&self) -> bool {
124        self.is_evicted
125    }
126
127    /// The input the run was triggered with, as a `T`.
128    ///
129    /// # Errors
130    ///
131    /// [`Error::RunOutput`] when the engine recorded no input, or it is not
132    /// a `T`.
133    pub fn input<T: DeserializeOwned>(&self) -> Result<T> {
134        self.decode(&self.input, "input")
135    }
136
137    /// The metadata the run was triggered with
138    /// ([`RunOpts::metadata`](crate::RunOpts::metadata)), as a `T` —
139    /// `serde_json::Value` for a plain map.
140    ///
141    /// # Errors
142    ///
143    /// [`Error::RunOutput`] when there was none, or it is not a `T`.
144    pub fn additional_metadata<T: DeserializeOwned>(&self) -> Result<T> {
145        self.decode(&self.additional_metadata, "additional metadata")
146    }
147
148    /// What the engine knows about `task`, by the name it was declared with.
149    pub fn task<I, O>(&self, task: &Task<I, O>) -> Option<&TaskRunDetail> {
150        self.task_by_name(task.name())
151    }
152
153    /// [`task`](RunDetails::task), by name — matched as declared first and
154    /// then without regard to case, because the engine knows a task by the
155    /// lowercased name it was registered under.
156    pub fn task_by_name(&self, name: &str) -> Option<&TaskRunDetail> {
157        self.tasks.get(name).or_else(|| {
158            self.tasks
159                .values()
160                .find(|task| task.readable_id.eq_ignore_ascii_case(name))
161        })
162    }
163
164    /// Every task of the run, by name, in name order.
165    pub fn tasks(&self) -> impl Iterator<Item = (&str, &TaskRunDetail)> {
166        self.tasks.iter().map(|(name, task)| (name.as_str(), task))
167    }
168
169    /// The output `task` produced, deserialized into the type it was
170    /// declared with.
171    ///
172    /// # Errors
173    ///
174    /// [`Error::RunOutput`] when the run has no such task, the task recorded
175    /// no output, or the output is not an `O`.
176    pub fn output_of<I, O: DeserializeOwned>(&self, task: &Task<I, O>) -> Result<O> {
177        let detail = self.task(task).ok_or_else(|| Error::RunOutput {
178            run_id: self.run_id.clone(),
179            reason: format!("the run has no task {:?}", task.name()),
180        })?;
181        let output = detail.output.as_deref().ok_or_else(|| Error::RunOutput {
182            run_id: self.run_id.clone(),
183            reason: format!("task {:?} recorded no output", detail.readable_id),
184        })?;
185        self.decode(
186            output,
187            &format!("the output of task {:?}", detail.readable_id),
188        )
189    }
190
191    fn decode<T: DeserializeOwned>(&self, bytes: &[u8], what: &str) -> Result<T> {
192        if bytes.is_empty() {
193            return Err(Error::RunOutput {
194                run_id: self.run_id.clone(),
195                reason: format!("the engine recorded no {what} for this run"),
196            });
197        }
198        serde_json::from_slice(bytes).map_err(|error| Error::RunOutput {
199            run_id: self.run_id.clone(),
200            reason: format!("{what}: {error}"),
201        })
202    }
203}
204
205impl TaskRunDetail {
206    /// The engine's id for this task run — what
207    /// [`RunsClient::cancel`](crate::RunsClient::cancel) takes.
208    pub fn id(&self) -> &str {
209        &self.external_id
210    }
211
212    /// The task's declared name.
213    pub fn name(&self) -> &str {
214        &self.readable_id
215    }
216
217    /// This task's state.
218    pub fn status(&self) -> RunStatus {
219        self.status
220    }
221
222    /// What went wrong, if anything. `None` both when nothing was recorded
223    /// and when the engine recorded an empty error string — an empty string
224    /// was observed even on tasks that succeeded, so it does not mean "an
225    /// error happened".
226    pub fn error(&self) -> Option<&str> {
227        self.error.as_deref()
228    }
229
230    /// Whether this task was taken off its worker.
231    pub fn is_evicted(&self) -> bool {
232        self.is_evicted
233    }
234
235    /// This task's output, as a `T`.
236    ///
237    /// # Errors
238    ///
239    /// [`Error::RunOutput`] when the task recorded no output or it is not a
240    /// `T`.
241    pub fn output<T: DeserializeOwned>(&self) -> Result<T> {
242        let output = self.output.as_deref().ok_or_else(|| Error::RunOutput {
243            run_id: self.external_id.clone(),
244            reason: format!("task {:?} recorded no output", self.readable_id),
245        })?;
246        serde_json::from_slice(output).map_err(|error| Error::RunOutput {
247            run_id: self.external_id.clone(),
248            reason: format!("task {:?}: {error}", self.readable_id),
249        })
250    }
251}