Skip to main content

hatchet_rest/
lib.rs

1//! A client for the [Hatchet](https://hatchet.run) REST management API.
2//!
3//! `hatchet-client` runs workers and triggers runs over gRPC; this crate is
4//! the other half of what the official SDKs offer: listing and inspecting
5//! runs, managing crons and scheduled runs, workers, workflows, filters and
6//! webhooks, and reading logs, metrics, rate limits and the tenant. It is
7//! built to call exactly the 37 REST operations the official Go SDK's feature
8//! clients call; [`Operation::ALL`] lists them.
9//!
10//! Each one is sent by a method of a bundle [`RestClient`] hands out —
11//! [`runs`](RestClient::runs), [`logs`](RestClient::logs),
12//! [`crons`](RestClient::crons), [`schedules`](RestClient::schedules),
13//! [`workflows`](RestClient::workflows), [`workers`](RestClient::workers),
14//! [`metrics`](RestClient::metrics), [`rate_limits`](RestClient::rate_limits),
15//! [`tenant`](RestClient::tenant), [`filters`](RestClient::filters),
16//! [`webhooks`](RestClient::webhooks) and [`cel`](RestClient::cel).
17//!
18//! ```no_run
19//! # async fn example() -> hatchet_rest::Result<()> {
20//! // HATCHET_CLIENT_TOKEN, and optionally HATCHET_CLIENT_SERVER_URL /
21//! // HATCHET_CLIENT_TENANT_ID (otherwise taken from the token's claims).
22//! let rest = hatchet_rest::RestClient::from_env()?;
23//! let tenant = rest.tenant().get().await?;
24//! println!("{} ({})", tenant.name, tenant.metadata.id);
25//! # Ok(())
26//! # }
27//! ```
28//!
29//! # Requests
30//!
31//! Every request carries `Authorization: Bearer <token>` and
32//! `Accept: application/json`. Only a bodiless `GET` is retried — on a
33//! transport error or a `429`/`502`/`503`/`504`, five attempts in all, with
34//! full-jitter backoff from 250 ms up to 5 s (or a `Retry-After` of at most
35//! 5 s) — which is the official Go SDK's REST policy. A `POST`, `PATCH` or
36//! `DELETE` is sent once. Each attempt may take 30 s
37//! ([`RestClientBuilder::timeout`]). What an answer outside 2xx becomes is
38//! tabled on [`Error`].
39//!
40//! ## Configuration
41//!
42//! [`RestClient::from_env`] resolves five settings — token, server URL,
43//! tenant id, namespace, TLS root CA file — each an explicit builder value,
44//! then a `HATCHET_CLIENT_*` environment variable, then (for server URL and
45//! tenant id) a claim of the token. See [`RestClientBuilder`] for the full
46//! table. `HATCHET_CLIENT_TLS_STRATEGY` and mTLS, which `hatchet-client`'s
47//! gRPC side reads, do not apply here — the server URL's scheme decides TLS.
48//!
49//! ## Errors
50//!
51//! See [`Error`] for the full table from HTTP status to error variant. None
52//! of them ever contain the API token or a webhook secret.
53//!
54//! ## Retries
55//!
56//! Covered under Requests above; a `GET` that exhausts its five attempts, or
57//! any request whose connection fails outright, becomes
58//! [`Error::Transport`]. A real engine was not observed to answer `429` in
59//! this crate's integration tests, so the retry-then-succeed path is
60//! verified against `hatchet-testkit`'s mock server only.
61//!
62//! ## Tracing
63//!
64//! [`SchedulesApi::create`] opens a `tracing` span, `hatchet.schedule_workflow`,
65//! named and attributed as the official Go SDK's schedules client opens it:
66//! `instrumentor`, `hatchet.workflow_name` (as the caller named it) and
67//! `hatchet.trigger_at` (RFC 3339), with the `otel.kind`/`otel.status_*`
68//! fields a `tracing-opentelemetry` layer turns into a producer span and its
69//! status. Like Go, it puts no trace context into the scheduled run's
70//! metadata, and this crate links no OpenTelemetry crate. No other call opens
71//! a span.
72//!
73//! ## Engine versions
74//!
75//! v0.80.0 and v0.107.0 were both observed to serve all 37 operations, with
76//! no per-operation version gate; smaller differences (an optional vs.
77//! required `since`, ignored filters, absent response fields) are noted on
78//! the affected types and methods.
79//!
80//! ## Relationship to `hatchet-client`
81//!
82//! `hatchet-client`'s `rest` feature builds a cached [`RestClient`] from the
83//! same configuration as its gRPC `Client` (`Client::rest()`). Cancel,
84//! replay, a run's details and status, and restoring an evicted task are
85//! available over gRPC too; everything else this crate sends has no gRPC
86//! equivalent.
87
88#![warn(missing_docs)]
89
90mod cel;
91mod config;
92mod crons;
93mod error;
94mod filters;
95mod logs;
96mod metrics;
97mod rate_limits;
98mod retry;
99mod routes;
100mod runs;
101mod schedules;
102mod tenant;
103mod time;
104mod tls;
105mod token;
106mod transport;
107mod types;
108mod webhooks;
109mod workers;
110mod workflows;
111
112use std::fmt;
113use std::sync::Arc;
114
115pub use cel::{CelApi, CelDebugOutput, CelDebugRequest, CelDebugStatus};
116pub use config::RestClientBuilder;
117pub use crons::{Cron, CronListQuery, CronOrderBy, CronsApi, TriggerOpts, TriggerOrigin};
118pub use error::{ApiError, Error, Result};
119pub use filters::{Filter, FilterListQuery, FilterSpec, FilterUpdate, FiltersApi};
120pub use logs::{LogLevel, LogLine, LogListQuery, LogsApi};
121pub use metrics::{
122    MetricsApi, QueueMetrics, QueueMetricsQuery, TaskQueueMetrics, TenantQueueMetrics,
123    WorkflowMetrics, WorkflowMetricsQuery,
124};
125pub use rate_limits::{
126    RateLimit, RateLimitListQuery, RateLimitOrderBy, RateLimitOrderDirection, RateLimitsApi,
127};
128pub use routes::{Method, Operation, Route};
129pub use runs::{
130    DurableBranch, MetadataOperator, RunKind, RunListQuery, RunSelector, RunningFilter, RunsApi,
131    TaskEvent, TaskFilter, TaskStatus, TaskSummary, WorkflowRun, WorkflowRunDetails,
132};
133pub use schedules::{
134    ScheduleListQuery, ScheduleOrderBy, ScheduledRun, ScheduledRunStatus, SchedulesApi,
135    WorkflowRunStatus,
136};
137pub use tenant::{Tenant, TenantApi, TenantEnvironment, TenantVersion};
138pub use types::{JsonObject, Page, Pagination, ResourceMeta, SortDirection};
139pub use webhooks::{
140    HmacAlgorithm, HmacEncoding, Webhook, WebhookAuth, WebhookAuthType, WebhookListQuery,
141    WebhookSource, WebhookSpec, WebhookUpdate, WebhooksApi,
142};
143pub use workers::{
144    RegisteredWorkflow, SlotCapacity, Worker, WorkerKind, WorkerLabel, WorkerListQuery,
145    WorkerRuntime, WorkerStatus, WorkersApi,
146};
147pub use workflows::{Workflow, WorkflowListQuery, WorkflowTag, WorkflowsApi};
148
149/// A client for the Hatchet REST API. Cheap to clone; clones share one
150/// connection pool. Its `Debug` output never shows the token.
151///
152/// ```no_run
153/// # async fn example() -> hatchet_rest::Result<()> {
154/// let rest = hatchet_rest::RestClient::from_env()?;
155/// let tenant = rest.tenant().get().await?;
156/// println!("{} ({})", tenant.name, tenant.metadata.id);
157/// # Ok(())
158/// # }
159/// ```
160#[derive(Clone)]
161pub struct RestClient {
162    inner: Arc<transport::Inner>,
163}
164
165impl fmt::Debug for RestClient {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.debug_struct("RestClient")
168            .field("base_url", &self.inner.base.as_str())
169            .field("tenant_id", &self.inner.tenant_id)
170            .field("namespace", &self.inner.namespace)
171            .finish_non_exhaustive()
172    }
173}
174
175impl RestClient {
176    /// Starts configuring a client.
177    pub fn builder() -> RestClientBuilder {
178        RestClientBuilder::default()
179    }
180
181    /// A client configured from the `HATCHET_CLIENT_*` variables and the
182    /// token's claims.
183    ///
184    /// # Errors
185    ///
186    /// Those of [`RestClientBuilder::build`].
187    pub fn from_env() -> Result<Self> {
188        Self::builder().build()
189    }
190
191    pub(crate) fn from_resolved(resolved: config::Resolved) -> Result<Self> {
192        Ok(Self {
193            inner: Arc::new(transport::Inner::new(resolved)?),
194        })
195    }
196
197    /// The REST base URL requests go to, e.g. `http://localhost:8888/`.
198    #[must_use]
199    pub fn base_url(&self) -> &str {
200        self.inner.base.as_str()
201    }
202
203    /// The tenant every call acts for.
204    #[must_use]
205    pub fn tenant_id(&self) -> &str {
206        &self.inner.tenant_id
207    }
208
209    /// The normalised namespace (`"dev_"`), or `""`.
210    #[must_use]
211    pub fn namespace(&self) -> &str {
212        &self.inner.namespace
213    }
214
215    /// The name the engine knows a workflow by: lowercased, then prefixed
216    /// with the namespace — the same rule `hatchet-client` registers
217    /// workflows under.
218    #[must_use]
219    pub fn workflow_name(&self, declared: &str) -> String {
220        config::workflow_name(&self.inner.namespace, declared)
221    }
222
223    /// The tenant (`tenant:get`).
224    pub fn tenant(&self) -> TenantApi<'_> {
225        TenantApi { client: self }
226    }
227
228    /// Rate limits (`rate-limit:list`).
229    pub fn rate_limits(&self) -> RateLimitsApi<'_> {
230        RateLimitsApi { client: self }
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::Operation;
237
238    /// Every bundle's source, without its tests.
239    const BUNDLES: &[(&str, &str)] = &[
240        ("runs", include_str!("runs.rs")),
241        ("logs", include_str!("logs.rs")),
242        ("crons", include_str!("crons.rs")),
243        ("schedules", include_str!("schedules.rs")),
244        ("workflows", include_str!("workflows.rs")),
245        ("workers", include_str!("workers.rs")),
246        ("metrics", include_str!("metrics.rs")),
247        ("rate_limits", include_str!("rate_limits.rs")),
248        ("tenant", include_str!("tenant.rs")),
249        ("filters", include_str!("filters.rs")),
250        ("webhooks", include_str!("webhooks.rs")),
251        ("cel", include_str!("cel.rs")),
252    ];
253
254    /// The bundle and the public method(s) that send each operation.
255    /// Exhaustive, so an operation added to the table without an entry
256    /// fails to compile.
257    fn methods_for(operation: Operation) -> (&'static str, &'static [&'static str]) {
258        match operation {
259            Operation::V1WorkflowRunGet => ("runs", &["get"]),
260            Operation::V1WorkflowRunGetStatus => ("runs", &["status"]),
261            Operation::V1WorkflowRunList => ("runs", &["list"]),
262            Operation::V1TaskCancel => ("runs", &["cancel"]),
263            Operation::V1TaskReplay => ("runs", &["replay"]),
264            Operation::V1TaskRestore => ("runs", &["restore"]),
265            Operation::V1DurableTaskBranch => ("runs", &["branch_durable_task"]),
266            Operation::V1LogLineList => ("logs", &["list"]),
267            Operation::CronWorkflowTriggerCreate => ("crons", &["create"]),
268            Operation::CronWorkflowList => ("crons", &["list"]),
269            Operation::WorkflowCronGet => ("crons", &["get"]),
270            Operation::WorkflowCronDelete => ("crons", &["delete"]),
271            Operation::ScheduledWorkflowRunCreate => ("schedules", &["create"]),
272            Operation::WorkflowScheduledList => ("schedules", &["list"]),
273            Operation::WorkflowScheduledGet => ("schedules", &["get"]),
274            Operation::WorkflowScheduledDelete => ("schedules", &["delete"]),
275            Operation::WorkerList => ("workers", &["list"]),
276            Operation::WorkerGet => ("workers", &["get"]),
277            Operation::WorkerUpdate => ("workers", &["pause", "unpause"]),
278            Operation::WorkflowList => ("workflows", &["list", "find"]),
279            Operation::WorkflowDelete => ("workflows", &["delete"]),
280            Operation::WorkflowGetMetrics => ("metrics", &["workflow"]),
281            Operation::TenantGetQueueMetrics => ("metrics", &["queue"]),
282            Operation::TenantGetStepRunQueueMetrics => ("metrics", &["task_queue"]),
283            Operation::RateLimitList => ("rate_limits", &["list"]),
284            Operation::TenantGet => ("tenant", &["get"]),
285            Operation::V1FilterList => ("filters", &["list"]),
286            Operation::V1FilterGet => ("filters", &["get"]),
287            Operation::V1FilterCreate => ("filters", &["create"]),
288            Operation::V1FilterUpdate => ("filters", &["update"]),
289            Operation::V1FilterDelete => ("filters", &["delete"]),
290            Operation::V1WebhookList => ("webhooks", &["list"]),
291            Operation::V1WebhookGet => ("webhooks", &["get"]),
292            Operation::V1WebhookCreate => ("webhooks", &["create"]),
293            Operation::V1WebhookUpdate => ("webhooks", &["update"]),
294            Operation::V1WebhookDelete => ("webhooks", &["delete"]),
295            Operation::V1CelDebug => ("cel", &["debug"]),
296        }
297    }
298
299    /// `source` up to its test module, without comment lines.
300    fn code(source: &str) -> String {
301        let library = source.split("#[cfg(test)]").next().unwrap_or(source);
302        library
303            .lines()
304            .filter(|line| !line.trim_start().starts_with("//"))
305            .collect::<Vec<_>>()
306            .join("\n")
307    }
308
309    #[test]
310    fn every_operation_has_a_public_method() {
311        let lib = code(include_str!("lib.rs"));
312        let mut claimed = std::collections::HashSet::new();
313        for &operation in Operation::ALL {
314            let (bundle, methods) = methods_for(operation);
315            let variant = format!("Operation::{operation:?}");
316            // Sent from its own bundle, and from no other.
317            let senders: Vec<&str> = BUNDLES
318                .iter()
319                .filter(|(_, source)| {
320                    code(source)
321                        .split(|c: char| !(c.is_alphanumeric() || c == '_' || c == ':'))
322                        .any(|word| word == variant)
323                })
324                .map(|(name, _)| *name)
325                .collect();
326            assert_eq!(
327                senders,
328                [bundle],
329                "{variant} is referenced by these bundles"
330            );
331            // The bundle and its public methods exist.
332            let source = code(BUNDLES.iter().find(|(name, _)| *name == bundle).unwrap().1);
333            let accessor = format!("pub fn {bundle}(&self)");
334            assert!(
335                source.contains(&accessor) || lib.contains(&accessor),
336                "RestClient::{bundle} is missing"
337            );
338            for method in methods {
339                assert!(
340                    source.contains(&format!("pub async fn {method}(")),
341                    "{bundle}().{method} (for {variant}) is missing"
342                );
343                assert!(
344                    claimed.insert((bundle, *method)),
345                    "{bundle}().{method} is listed for two operations"
346                );
347            }
348        }
349    }
350}