Skip to main content

hatchet_client/
client.rs

1//! The entry point: one shared connection, handed to every generated client.
2
3use std::fmt;
4use std::pin::Pin;
5use std::sync::Arc;
6
7use hatchet_proto::root::dispatcher_client::DispatcherClient;
8use hatchet_proto::root::events_service_client::EventsServiceClient;
9use hatchet_proto::root::workflow_service_client::WorkflowServiceClient;
10use hatchet_proto::root::{GetVersionRequest, WorkflowRunEvent};
11use hatchet_proto::v1::admin_service_client::AdminServiceClient;
12use tokio_stream::Stream;
13use tokio_util::sync::{CancellationToken, DropGuard};
14use tonic::Status;
15use tonic::codec::CompressionEncoding;
16
17use crate::events::EventsClient;
18use crate::rate_limits::RateLimitsClient;
19use crate::runs::client::RunsClient;
20use crate::runs::listener::{RequestStream, RunListener};
21use crate::transport::{self, GrpcService};
22use crate::worker::WorkerBuilder;
23use crate::{ClientBuilder, ClientConfig, Result, retry, version};
24
25/// A connection to a Hatchet engine. Cheap to clone; clones share the
26/// underlying gRPC channel.
27///
28/// One client is both sides of the SDK: it builds the [`Worker`](crate::Worker)
29/// that runs declared tasks, and it triggers runs and pushes events. Hold on
30/// to it for as long as anything might wait on a run — a
31/// [`RunHandle`](crate::RunHandle) does not keep its client alive.
32///
33/// ```no_run
34/// # use hatchet_client::{Client, RunOpts, TaskBuilder};
35/// # async fn example() -> hatchet_client::Result<()> {
36/// // Reads HATCHET_CLIENT_TOKEN and friends; see `ClientBuilder` to set
37/// // them in code instead.
38/// let client = Client::from_env()?;
39///
40/// let greet = TaskBuilder::<String, String>::new("greet")
41///     .handler(|_ctx, name: String| async move { Ok(format!("Hello, {name}!")) });
42///
43/// // The worker side.
44/// let worker = client.worker("greeter-1").register(&greet).build().await?;
45/// let shutdown = worker.shutdown_handle();
46/// let running = tokio::spawn(worker.run());
47///
48/// // The trigger side, from the same client.
49/// let greeting = greet
50///     .run(&client, &"Hatchet".to_string(), RunOpts::default())
51///     .await?;
52/// println!("{greeting}");
53///
54/// shutdown.shutdown();
55/// running.await.expect("the worker task panicked")
56/// # }
57/// ```
58#[derive(Clone)]
59pub struct Client {
60    inner: Arc<Inner>,
61}
62
63struct Inner {
64    config: ClientConfig,
65    service: GrpcService,
66    /// Waits for run results on one shared subscription. It holds only a
67    /// clone of the gRPC service, never a `Client`: a listener that kept its
68    /// client alive would be a cycle no drop could break.
69    runs: RunListener,
70    /// Cancelled when the last clone of this client is dropped, which is what
71    /// ends the listener's task. A clone of the service handle cannot tell
72    /// the listener that: the channel it wraps stays perfectly usable.
73    _stop: DropGuard,
74    /// The REST client, built on first use by [`Client::rest`].
75    #[cfg(feature = "rest")]
76    rest: std::sync::OnceLock<hatchet_rest::RestClient>,
77}
78
79impl fmt::Debug for Client {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.debug_struct("Client")
82            .field("config", &self.inner.config)
83            .finish_non_exhaustive()
84    }
85}
86
87impl Client {
88    /// Starts configuring a client. Equivalent to [`ClientConfig::builder`].
89    pub fn builder() -> ClientBuilder {
90        ClientConfig::builder()
91    }
92
93    /// Configures a client from `HATCHET_CLIENT_*` environment variables.
94    ///
95    /// # Errors
96    ///
97    /// Those of [`ClientConfig::from_env`] and [`Client::new`]:
98    /// [`Error::Config`](crate::Error::Config) when `HATCHET_CLIENT_TOKEN` is
99    /// unset or a setting is contradictory,
100    /// [`Error::InvalidToken`](crate::Error::InvalidToken) when the token
101    /// carries neither the needed claims nor their environment overrides, and
102    /// [`Error::Transport`](crate::Error::Transport) when the address or the
103    /// TLS material will not make a channel.
104    ///
105    /// # Panics
106    ///
107    /// Panics if called outside a tokio runtime.
108    pub fn from_env() -> Result<Self> {
109        Self::new(ClientConfig::from_env()?)
110    }
111
112    /// Creates a client. The connection is established lazily, on the first
113    /// call, so this succeeds even while the engine is unreachable. TLS
114    /// material (system roots, certificate files) is loaded eagerly here, so
115    /// TLS misconfiguration fails at construction rather than on the first
116    /// call.
117    ///
118    /// The shared listener that waits for run results is built here but not
119    /// started: a client that never waits for a run spawns no task and opens
120    /// no stream.
121    ///
122    /// Nothing here checks the engine's version — a client that only triggers
123    /// runs makes no call of its own. Call
124    /// [`check_engine_version`](Client::check_engine_version) if you want that
125    /// checked.
126    ///
127    /// # Errors
128    ///
129    /// [`Error::Transport`](crate::Error::Transport) when `host_port` is not a
130    /// usable address or the TLS material is not accepted, and
131    /// [`Error::Config`](crate::Error::Config) when the token cannot go in a
132    /// header, a certificate or key file cannot be read, `mtls` was asked for
133    /// without a certificate and key, or `tls`/`mtls` was asked for in a build
134    /// with no crypto provider or no root store compiled in (see the crate's
135    /// `tls-*` cargo features).
136    ///
137    /// # Panics
138    ///
139    /// Panics if called outside a tokio runtime.
140    pub fn new(config: ClientConfig) -> Result<Self> {
141        let gzip = config.gzip();
142        let service = transport::connect(&config)?;
143        let stop = CancellationToken::new();
144        let runs = RunListener::new(subscribing(service.clone(), gzip), stop.clone());
145        Ok(Self {
146            inner: Arc::new(Inner {
147                config,
148                service,
149                runs,
150                _stop: stop.drop_guard(),
151                #[cfg(feature = "rest")]
152                rest: std::sync::OnceLock::new(),
153            }),
154        })
155    }
156
157    /// The resolved configuration.
158    pub fn config(&self) -> &ClientConfig {
159        &self.inner.config
160    }
161
162    /// The engine's version string, e.g. `"v0.107.0"`.
163    ///
164    /// # Errors
165    ///
166    /// [`Error::Grpc`](crate::Error::Grpc) when the call fails — including
167    /// when the engine cannot be reached, since the connection is made
168    /// lazily and this is often the first call to touch it.
169    pub async fn engine_version(&self) -> Result<String> {
170        let response = retry::unary(|| {
171            let mut dispatcher = self.dispatcher_grpc();
172            async move {
173                dispatcher
174                    .get_version(retry::timed(GetVersionRequest {}))
175                    .await
176            }
177        })
178        .await?;
179        Ok(response.into_inner().version)
180    }
181
182    /// Asks the engine for its version and checks it against
183    /// [`MIN_ENGINE_VERSION`](crate::MIN_ENGINE_VERSION).
184    ///
185    /// [`WorkerBuilder::build`](crate::WorkerBuilder::build) does this on its
186    /// own; call it yourself in a process that only triggers runs and would
187    /// otherwise never find out.
188    ///
189    /// # Errors
190    ///
191    /// [`Error::UnsupportedEngine`](crate::Error::UnsupportedEngine) when the
192    /// engine is older than the minimum,
193    /// [`Error::InvalidEngineVersion`](crate::Error::InvalidEngineVersion)
194    /// when what it reported is not `vMAJOR.MINOR.PATCH`, and those of
195    /// [`engine_version`](Client::engine_version).
196    pub async fn check_engine_version(&self) -> Result<()> {
197        version::ensure_supported(&self.engine_version().await?)
198    }
199
200    pub(crate) fn dispatcher_grpc(&self) -> DispatcherClient<GrpcService> {
201        dispatcher_grpc(self.grpc_service(), self.inner.config.gzip())
202    }
203
204    /// The gRPC channel every generated client is built on, for the durable
205    /// stream's own connect function.
206    pub(crate) fn grpc_service(&self) -> GrpcService {
207        self.inner.service.clone()
208    }
209
210    /// The listener every wait for a run result goes through. One per client,
211    /// however many runs are waited for.
212    ///
213    /// Named `run_listener` rather than `runs` because [`Client::runs`] is
214    /// the public run-control client.
215    pub(crate) fn run_listener(&self) -> &RunListener {
216        &self.inner.runs
217    }
218
219    pub(crate) fn admin_grpc(&self) -> AdminServiceClient<GrpcService> {
220        let client = AdminServiceClient::new(self.inner.service.clone())
221            .accept_compressed(CompressionEncoding::Gzip);
222        if self.inner.config.gzip() {
223            client.send_compressed(CompressionEncoding::Gzip)
224        } else {
225            client
226        }
227    }
228
229    /// The v0 `EventsService`: where a running task's logs and stream events
230    /// go.
231    pub(crate) fn events_grpc(&self) -> EventsServiceClient<GrpcService> {
232        let client = EventsServiceClient::new(self.inner.service.clone())
233            .accept_compressed(CompressionEncoding::Gzip);
234        if self.inner.config.gzip() {
235            client.send_compressed(CompressionEncoding::Gzip)
236        } else {
237            client
238        }
239    }
240
241    /// The v0 `WorkflowService`: where runs are triggered. Its
242    /// `TriggerWorkflow` takes the *v1* request message.
243    pub(crate) fn workflows_grpc(&self) -> WorkflowServiceClient<GrpcService> {
244        let client = WorkflowServiceClient::new(self.inner.service.clone())
245            .accept_compressed(CompressionEncoding::Gzip);
246        if self.inner.config.gzip() {
247            client.send_compressed(CompressionEncoding::Gzip)
248        } else {
249            client
250        }
251    }
252
253    /// Pushes events to the engine, one at a time or in bulk.
254    pub fn events(&self) -> EventsClient {
255        EventsClient::new(self.clone())
256    }
257
258    /// Creates and raises the tenant's rate limits.
259    pub fn rate_limits(&self) -> RateLimitsClient {
260        RateLimitsClient::new(self.clone())
261    }
262
263    /// Cancels, replays and inspects runs the engine already knows about.
264    pub fn runs(&self) -> RunsClient {
265        RunsClient::new(self.clone())
266    }
267
268    /// Starts configuring a worker named `name`. The name is how the engine's
269    /// dashboard identifies it; it does not have to be unique.
270    pub fn worker(&self, name: impl Into<String>) -> WorkerBuilder {
271        WorkerBuilder::new(self.clone(), name)
272    }
273
274    /// Starts declaring a task with input `I` and output `O`. Shorthand for
275    /// [`TaskBuilder::new`](crate::TaskBuilder::new); the declaration is not
276    /// tied to this client.
277    pub fn task<I, O>(&self, name: impl Into<String>) -> crate::TaskBuilder<I, O> {
278        crate::TaskBuilder::new(name)
279    }
280
281    /// Starts declaring a workflow. Shorthand for
282    /// [`Workflow::new`](crate::Workflow::new).
283    pub fn workflow(&self, name: impl Into<String>) -> crate::Workflow {
284        crate::Workflow::new(name)
285    }
286}
287
288fn dispatcher_grpc(service: GrpcService, gzip: bool) -> DispatcherClient<GrpcService> {
289    let client = DispatcherClient::new(service).accept_compressed(CompressionEncoding::Gzip);
290    if gzip {
291        client.send_compressed(CompressionEncoding::Gzip)
292    } else {
293        client
294    }
295}
296
297/// The run events one subscription is answered with.
298type RunEventStream =
299    Pin<Box<dyn Stream<Item = std::result::Result<WorkflowRunEvent, Status>> + Send>>;
300
301/// The listener's connect function: opens one `SubscribeToWorkflowRuns`
302/// stream, with `requests` as the ids it is asked about.
303///
304/// No `set_timeout` and no [`retry::unary`], for the same reasons as the
305/// worker's action stream: a deadline would cut off a run that is simply
306/// taking its time, and reconnecting is the listener's own job.
307fn subscribing(
308    service: GrpcService,
309    gzip: bool,
310) -> impl FnMut(
311    RequestStream,
312) -> Pin<Box<dyn Future<Output = std::result::Result<RunEventStream, Status>> + Send>> {
313    move |requests| {
314        let mut dispatcher = dispatcher_grpc(service.clone(), gzip);
315        Box::pin(async move {
316            let events = dispatcher
317                .subscribe_to_workflow_runs(requests)
318                .await?
319                .into_inner();
320            Ok(Box::pin(events) as RunEventStream)
321        })
322    }
323}
324
325#[cfg(feature = "rest")]
326impl Client {
327    /// A client for Hatchet's REST management API (the `hatchet-rest`
328    /// crate, re-exported as [`hatchet_rest`](crate::hatchet_rest)), built
329    /// from this client's resolved configuration: the same token, tenant,
330    /// namespace, server URL (explicit, `HATCHET_CLIENT_SERVER_URL`, or the
331    /// token's claim) and root CA file. The [`TlsStrategy`](crate::TlsStrategy)
332    /// does not apply to it: the server URL's scheme decides, and the root CA
333    /// file is used only for an `https://` URL. Needs the `rest` feature.
334    ///
335    /// Built on the first successful call and cached in this client (and its
336    /// clones); later calls hand out a clone of it, which shares its
337    /// connection pool.
338    ///
339    /// Part of what the REST API does, this crate already does over gRPC —
340    /// [`Client::runs`]' cancel, replay and details, and
341    /// [`Client::rate_limits`]' upsert. The REST client is for the rest:
342    /// listing runs, logs, crons, scheduled runs, workers, workflows,
343    /// filters, webhooks and metrics.
344    ///
345    /// ```no_run
346    /// # async fn example(client: hatchet_client::Client) -> Result<(), Box<dyn std::error::Error>> {
347    /// let workers = client.rest()?.workers().list(Default::default()).await?;
348    /// for worker in workers.rows {
349    ///     println!("{} {:?}", worker.name, worker.status);
350    /// }
351    /// # Ok(())
352    /// # }
353    /// ```
354    ///
355    /// # Errors
356    ///
357    /// Those of [`RestClientBuilder::build`](hatchet_rest::RestClientBuilder::build).
358    /// The gRPC configuration being complete does not make the REST one
359    /// usable: a server URL that is not `http://` or `https://`, an
360    /// `https://` one in a build with no crypto provider or root store, or
361    /// an unreadable root CA file fail here, not at [`Client::new`]. A failed
362    /// build is not cached; the next call tries again.
363    pub fn rest(&self) -> hatchet_rest::Result<hatchet_rest::RestClient> {
364        if let Some(rest) = self.inner.rest.get() {
365            return Ok(rest.clone());
366        }
367        let config = &self.inner.config;
368        let mut builder = hatchet_rest::RestClient::builder()
369            .token(config.token())
370            .server_url(config.server_url())
371            .tenant_id(config.tenant_id())
372            .namespace(config.namespace());
373        if let Some(path) = config.tls_root_ca_file() {
374            builder = builder.tls_root_ca_file(path);
375        }
376        let rest = builder.build()?;
377        // Two first calls racing each build one; the first stored wins and
378        // both hand out that one.
379        Ok(self.inner.rest.get_or_init(|| rest).clone())
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use crate::{Error, TlsStrategy};
387
388    const TOKEN: &str = "e30.eyJzdWIiOiJ0Iiwic2VydmVyX3VybCI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODg4OCIsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyJ9.sig";
389
390    #[tokio::test]
391    async fn builder_builds_a_client_exposing_its_config() {
392        let client = Client::builder()
393            .token(TOKEN)
394            .namespace("dev")
395            .tls(TlsStrategy::None)
396            .build()
397            .unwrap();
398        assert_eq!(client.config().host_port(), "localhost:7077");
399        assert_eq!(client.config().namespace(), "dev_");
400        let _cheap_clone = client.clone();
401    }
402
403    #[tokio::test]
404    async fn debug_output_does_not_contain_the_token() {
405        let client = Client::builder()
406            .token(TOKEN)
407            .tls(TlsStrategy::None)
408            .build()
409            .unwrap();
410        assert!(!format!("{client:?}").contains(TOKEN));
411    }
412
413    #[tokio::test]
414    async fn client_offers_the_declaration_entry_points() {
415        let client = Client::builder()
416            .token(TOKEN)
417            .tls(TlsStrategy::None)
418            .build()
419            .unwrap();
420        let task = client
421            .task::<serde_json::Value, serde_json::Value>("agent-run")
422            .handler(|_ctx, input| async move { Ok(input) });
423        let workflow = client.workflow("pipeline").task(&task);
424        assert_eq!(task.name(), "agent-run");
425        assert_eq!(workflow.name(), "pipeline");
426    }
427
428    #[tokio::test(start_paused = true)]
429    async fn engine_version_surfaces_a_grpc_error_when_nothing_listens() {
430        let client = Client::builder()
431            .token(TOKEN)
432            .host_port("127.0.0.1:1")
433            .tls(TlsStrategy::None)
434            .build()
435            .unwrap();
436        let err = client.check_engine_version().await.unwrap_err();
437        let Error::Grpc(status) = err else {
438            panic!("{err:?}")
439        };
440        assert!(
441            matches!(
442                status.code(),
443                tonic::Code::Unavailable | tonic::Code::DeadlineExceeded
444            ),
445            "{status:?}"
446        );
447    }
448}