Skip to main content

hatchet_rest/
metrics.rs

1//! Metrics: a workflow's concurrency groups and the tenant's queues
2//! (`workflow:get:metrics`, `tenant:get:queue-metrics`,
3//! `tenant:get:step-run-queue-metrics`).
4
5use std::collections::BTreeMap;
6
7use serde::Deserialize;
8
9use crate::transport::{Query, metadata_pairs};
10use crate::{JsonObject, Operation, RestClient, Result, WorkflowRunStatus};
11
12/// A workflow's concurrency-group counts (`WorkflowMetrics`).
13#[derive(Clone, Debug, Deserialize)]
14#[serde(rename_all = "camelCase")]
15#[non_exhaustive]
16pub struct WorkflowMetrics {
17    /// Runs in the group asked about.
18    #[serde(default)]
19    pub group_key_runs_count: Option<i64>,
20    /// Distinct group keys.
21    #[serde(default)]
22    pub group_key_count: Option<i64>,
23    /// Fields this crate does not model, as the engine sent them.
24    #[serde(flatten)]
25    pub other: JsonObject,
26}
27
28/// Which runs [`MetricsApi::workflow`] counts. Only the settings given a
29/// value are sent.
30#[derive(Clone, Debug, Default)]
31#[must_use]
32pub struct WorkflowMetricsQuery {
33    status: Option<WorkflowRunStatus>,
34    group_key: Option<String>,
35}
36
37impl WorkflowMetricsQuery {
38    /// All of them.
39    pub fn new() -> Self {
40        Self::default()
41    }
42
43    /// Only runs in this status.
44    pub fn status(mut self, status: WorkflowRunStatus) -> Self {
45        self.status = Some(status);
46        self
47    }
48
49    /// Only this concurrency group.
50    pub fn group_key(mut self, key: impl Into<String>) -> Self {
51        self.group_key = Some(key.into());
52        self
53    }
54}
55
56/// Counts of one queue (`QueueMetrics`).
57#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
58#[serde(rename_all = "camelCase")]
59#[non_exhaustive]
60pub struct QueueMetrics {
61    /// Queued.
62    pub num_queued: i64,
63    /// Running.
64    pub num_running: i64,
65    /// Pending.
66    pub num_pending: i64,
67}
68
69/// The tenant's queue counts (`TenantQueueMetrics`).
70#[derive(Clone, Debug, Deserialize)]
71#[non_exhaustive]
72pub struct TenantQueueMetrics {
73    /// Across the tenant.
74    #[serde(default)]
75    pub total: Option<QueueMetrics>,
76    /// Per workflow.
77    #[serde(default)]
78    pub workflow: BTreeMap<String, QueueMetrics>,
79    /// Per queue.
80    #[serde(default)]
81    pub queues: BTreeMap<String, i64>,
82    /// Fields this crate does not model, as the engine sent them.
83    #[serde(flatten)]
84    pub other: JsonObject,
85}
86
87/// Which queues [`MetricsApi::queue`] counts. Only the settings given a
88/// value are sent.
89#[derive(Clone, Debug, Default)]
90#[must_use]
91pub struct QueueMetricsQuery {
92    workflows: Vec<String>,
93    additional_metadata: Vec<String>,
94}
95
96impl QueueMetricsQuery {
97    /// All of them.
98    pub fn new() -> Self {
99        Self::default()
100    }
101
102    /// Only these workflows (by id).
103    pub fn workflows(mut self, ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
104        self.workflows.extend(ids.into_iter().map(Into::into));
105        self
106    }
107
108    /// Only runs carrying these metadata pairs, sent as `key:value`.
109    pub fn additional_metadata<K: AsRef<str>, V: AsRef<str>>(
110        mut self,
111        pairs: impl IntoIterator<Item = (K, V)>,
112    ) -> Self {
113        self.additional_metadata.extend(metadata_pairs(pairs));
114        self
115    }
116}
117
118/// The tenant's task queue counts (`TenantStepRunQueueMetrics`), e.g.
119/// `{"queues": {"greet:greet": 1}}` as both supported engines answer. The
120/// spec gives `queues` no value schema, so it stays JSON.
121#[derive(Clone, Debug, Deserialize)]
122#[non_exhaustive]
123pub struct TaskQueueMetrics {
124    /// Per queue (a task's action id), as the engine sends it.
125    #[serde(default)]
126    pub queues: JsonObject,
127    /// Fields this crate does not model, as the engine sent them.
128    #[serde(flatten)]
129    pub other: JsonObject,
130}
131
132/// Metrics; from [`RestClient::metrics`].
133#[derive(Clone, Copy, Debug)]
134pub struct MetricsApi<'a> {
135    pub(crate) client: &'a RestClient,
136}
137
138impl RestClient {
139    /// Metrics (`workflow:get:metrics`, `tenant:get:queue-metrics`,
140    /// `tenant:get:step-run-queue-metrics`).
141    pub fn metrics(&self) -> MetricsApi<'_> {
142        MetricsApi { client: self }
143    }
144}
145
146impl MetricsApi<'_> {
147    /// A workflow's concurrency-group counts (`workflow:get:metrics`).
148    /// Takes the workflow's **id**, not its name.
149    ///
150    /// # Errors
151    ///
152    /// [`Error::InvalidArgument`](crate::Error::InvalidArgument) for an
153    /// empty id; otherwise as for any call. Both supported engines
154    /// answered `500` `{"message":"Internal Server Error"}` (an
155    /// [`Error::Http`](crate::Error::Http)) for the workflow probed while
156    /// planning, so a successful answer has **not been verified against a
157    /// real engine**.
158    pub async fn workflow(
159        &self,
160        workflow_id: &str,
161        query: WorkflowMetricsQuery,
162    ) -> Result<WorkflowMetrics> {
163        let mut params = Query::new();
164        params.push_opt("status", query.status.as_ref());
165        params.push_opt("groupKey", query.group_key.as_deref());
166        self.client
167            .inner
168            .call(Operation::WorkflowGetMetrics, &[workflow_id], params)
169            .await
170    }
171
172    /// The tenant's queue counts (`tenant:get:queue-metrics`).
173    ///
174    /// # Errors
175    ///
176    /// Both supported engines (v0.80.0 and v0.107.0) refuse this
177    /// deprecated operation with `400`
178    /// `{"errors":[{"description":"TenantGetQueueMetrics is deprecated"}]}`,
179    /// which is an [`Error::Api`](crate::Error::Api). It is here because the
180    /// official Go SDK still calls it; [`task_queue`](Self::task_queue) is
181    /// the one that answers. Otherwise as for any call.
182    pub async fn queue(&self, query: QueueMetricsQuery) -> Result<TenantQueueMetrics> {
183        let mut params = Query::new();
184        params.push_all("workflows", &query.workflows);
185        params.push_all("additionalMetadata", &query.additional_metadata);
186        self.client
187            .inner
188            .call(Operation::TenantGetQueueMetrics, &[], params)
189            .await
190    }
191
192    /// The tenant's task queue counts (`tenant:get:step-run-queue-metrics`).
193    ///
194    /// ```no_run
195    /// # async fn example(rest: hatchet_rest::RestClient) -> hatchet_rest::Result<()> {
196    /// let metrics = rest.metrics().task_queue().await?;
197    /// for (queue, count) in &metrics.queues {
198    ///     println!("{queue}: {count}");
199    /// }
200    /// # Ok(())
201    /// # }
202    /// ```
203    ///
204    /// # Errors
205    ///
206    /// As for any call; see [`Error`](crate::Error).
207    pub async fn task_queue(&self) -> Result<TaskQueueMetrics> {
208        self.client
209            .inner
210            .call(Operation::TenantGetStepRunQueueMetrics, &[], Query::new())
211            .await
212    }
213}