use std::fmt;
use std::pin::Pin;
use std::sync::Arc;
use hatchet_proto::root::dispatcher_client::DispatcherClient;
use hatchet_proto::root::events_service_client::EventsServiceClient;
use hatchet_proto::root::workflow_service_client::WorkflowServiceClient;
use hatchet_proto::root::{GetVersionRequest, WorkflowRunEvent};
use hatchet_proto::v1::admin_service_client::AdminServiceClient;
use tokio_stream::Stream;
use tokio_util::sync::{CancellationToken, DropGuard};
use tonic::Status;
use tonic::codec::CompressionEncoding;
use crate::events::EventsClient;
use crate::rate_limits::RateLimitsClient;
use crate::runs::client::RunsClient;
use crate::runs::listener::{RequestStream, RunListener};
use crate::transport::{self, GrpcService};
use crate::worker::WorkerBuilder;
use crate::{ClientBuilder, ClientConfig, Result, retry, version};
#[derive(Clone)]
pub struct Client {
inner: Arc<Inner>,
}
struct Inner {
config: ClientConfig,
service: GrpcService,
runs: RunListener,
_stop: DropGuard,
#[cfg(feature = "rest")]
rest: std::sync::OnceLock<hatchet_rest::RestClient>,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client")
.field("config", &self.inner.config)
.finish_non_exhaustive()
}
}
impl Client {
pub fn builder() -> ClientBuilder {
ClientConfig::builder()
}
pub fn from_env() -> Result<Self> {
Self::new(ClientConfig::from_env()?)
}
pub fn new(config: ClientConfig) -> Result<Self> {
let gzip = config.gzip();
let service = transport::connect(&config)?;
let stop = CancellationToken::new();
let runs = RunListener::new(subscribing(service.clone(), gzip), stop.clone());
Ok(Self {
inner: Arc::new(Inner {
config,
service,
runs,
_stop: stop.drop_guard(),
#[cfg(feature = "rest")]
rest: std::sync::OnceLock::new(),
}),
})
}
pub fn config(&self) -> &ClientConfig {
&self.inner.config
}
pub async fn engine_version(&self) -> Result<String> {
let response = retry::unary(|| {
let mut dispatcher = self.dispatcher_grpc();
async move {
dispatcher
.get_version(retry::timed(GetVersionRequest {}))
.await
}
})
.await?;
Ok(response.into_inner().version)
}
pub async fn check_engine_version(&self) -> Result<()> {
version::ensure_supported(&self.engine_version().await?)
}
pub(crate) fn dispatcher_grpc(&self) -> DispatcherClient<GrpcService> {
dispatcher_grpc(self.grpc_service(), self.inner.config.gzip())
}
pub(crate) fn grpc_service(&self) -> GrpcService {
self.inner.service.clone()
}
pub(crate) fn run_listener(&self) -> &RunListener {
&self.inner.runs
}
pub(crate) fn admin_grpc(&self) -> AdminServiceClient<GrpcService> {
let client = AdminServiceClient::new(self.inner.service.clone())
.accept_compressed(CompressionEncoding::Gzip);
if self.inner.config.gzip() {
client.send_compressed(CompressionEncoding::Gzip)
} else {
client
}
}
pub(crate) fn events_grpc(&self) -> EventsServiceClient<GrpcService> {
let client = EventsServiceClient::new(self.inner.service.clone())
.accept_compressed(CompressionEncoding::Gzip);
if self.inner.config.gzip() {
client.send_compressed(CompressionEncoding::Gzip)
} else {
client
}
}
pub(crate) fn workflows_grpc(&self) -> WorkflowServiceClient<GrpcService> {
let client = WorkflowServiceClient::new(self.inner.service.clone())
.accept_compressed(CompressionEncoding::Gzip);
if self.inner.config.gzip() {
client.send_compressed(CompressionEncoding::Gzip)
} else {
client
}
}
pub fn events(&self) -> EventsClient {
EventsClient::new(self.clone())
}
pub fn rate_limits(&self) -> RateLimitsClient {
RateLimitsClient::new(self.clone())
}
pub fn runs(&self) -> RunsClient {
RunsClient::new(self.clone())
}
pub fn worker(&self, name: impl Into<String>) -> WorkerBuilder {
WorkerBuilder::new(self.clone(), name)
}
pub fn task<I, O>(&self, name: impl Into<String>) -> crate::TaskBuilder<I, O> {
crate::TaskBuilder::new(name)
}
pub fn workflow(&self, name: impl Into<String>) -> crate::Workflow {
crate::Workflow::new(name)
}
}
fn dispatcher_grpc(service: GrpcService, gzip: bool) -> DispatcherClient<GrpcService> {
let client = DispatcherClient::new(service).accept_compressed(CompressionEncoding::Gzip);
if gzip {
client.send_compressed(CompressionEncoding::Gzip)
} else {
client
}
}
type RunEventStream =
Pin<Box<dyn Stream<Item = std::result::Result<WorkflowRunEvent, Status>> + Send>>;
fn subscribing(
service: GrpcService,
gzip: bool,
) -> impl FnMut(
RequestStream,
) -> Pin<Box<dyn Future<Output = std::result::Result<RunEventStream, Status>> + Send>> {
move |requests| {
let mut dispatcher = dispatcher_grpc(service.clone(), gzip);
Box::pin(async move {
let events = dispatcher
.subscribe_to_workflow_runs(requests)
.await?
.into_inner();
Ok(Box::pin(events) as RunEventStream)
})
}
}
#[cfg(feature = "rest")]
impl Client {
pub fn rest(&self) -> hatchet_rest::Result<hatchet_rest::RestClient> {
if let Some(rest) = self.inner.rest.get() {
return Ok(rest.clone());
}
let config = &self.inner.config;
let mut builder = hatchet_rest::RestClient::builder()
.token(config.token())
.server_url(config.server_url())
.tenant_id(config.tenant_id())
.namespace(config.namespace());
if let Some(path) = config.tls_root_ca_file() {
builder = builder.tls_root_ca_file(path);
}
let rest = builder.build()?;
Ok(self.inner.rest.get_or_init(|| rest).clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Error, TlsStrategy};
const TOKEN: &str = "e30.eyJzdWIiOiJ0Iiwic2VydmVyX3VybCI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODg4OCIsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyJ9.sig";
#[tokio::test]
async fn builder_builds_a_client_exposing_its_config() {
let client = Client::builder()
.token(TOKEN)
.namespace("dev")
.tls(TlsStrategy::None)
.build()
.unwrap();
assert_eq!(client.config().host_port(), "localhost:7077");
assert_eq!(client.config().namespace(), "dev_");
let _cheap_clone = client.clone();
}
#[tokio::test]
async fn debug_output_does_not_contain_the_token() {
let client = Client::builder()
.token(TOKEN)
.tls(TlsStrategy::None)
.build()
.unwrap();
assert!(!format!("{client:?}").contains(TOKEN));
}
#[tokio::test]
async fn client_offers_the_declaration_entry_points() {
let client = Client::builder()
.token(TOKEN)
.tls(TlsStrategy::None)
.build()
.unwrap();
let task = client
.task::<serde_json::Value, serde_json::Value>("agent-run")
.handler(|_ctx, input| async move { Ok(input) });
let workflow = client.workflow("pipeline").task(&task);
assert_eq!(task.name(), "agent-run");
assert_eq!(workflow.name(), "pipeline");
}
#[tokio::test(start_paused = true)]
async fn engine_version_surfaces_a_grpc_error_when_nothing_listens() {
let client = Client::builder()
.token(TOKEN)
.host_port("127.0.0.1:1")
.tls(TlsStrategy::None)
.build()
.unwrap();
let err = client.check_engine_version().await.unwrap_err();
let Error::Grpc(status) = err else {
panic!("{err:?}")
};
assert!(
matches!(
status.code(),
tonic::Code::Unavailable | tonic::Code::DeadlineExceeded
),
"{status:?}"
);
}
}