hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! Pushing events to the engine.
//!
//! [`request`] is the pure part — assembling the wire request — shared by
//! [`EventsClient::push`] and [`EventsClient::bulk_push`], so both send the
//! same shape of request.

use std::time::SystemTime;

use hatchet_proto::prost_types::Timestamp;
use hatchet_proto::root::{BulkPushEventRequest, Event, PushEventRequest};
use serde::Serialize;
use serde_json::{Map, Value};
use tracing::{Instrument, Span};

use crate::config::namespace;
use crate::declare::Priority;
use crate::error::{Error, Result};
use crate::{Client, otel, retry};

/// Pushes events to the engine, one at a time or in bulk.
///
/// Get one from [`Client::events`].
///
/// ```no_run
/// # async fn example(client: hatchet_client::Client) -> hatchet_client::Result<()> {
/// use hatchet_client::PushOpts;
///
/// let event = client
///     .events()
///     .push("approval.granted", &serde_json::json!({"issue": "BLOG-12"}), PushOpts::default())
///     .await?;
/// println!("pushed {} as {}", event.key, event.id);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct EventsClient {
    client: Client,
}

impl EventsClient {
    pub(crate) fn new(client: Client) -> Self {
        Self { client }
    }

    /// Pushes one event under `key`, prefixed with the client's namespace
    /// unless it is already there.
    ///
    /// # Errors
    ///
    /// [`Error::Json`] when `payload` or a metadata value cannot be
    /// serialized, and [`Error::Grpc`] when the call fails.
    pub async fn push<P: Serialize>(
        &self,
        key: impl AsRef<str>,
        payload: &P,
        opts: PushOpts,
    ) -> Result<PushedEvent> {
        let key = key.as_ref();
        let span = otel::push_event(key);
        let pushed = self
            .push_under(&span, key, payload, &opts)
            .instrument(span.clone())
            .await;
        otel::record_result(&span, &pushed);
        pushed
    }

    /// [`push`](Self::push) under `span`, whose traceparent the event
    /// carries (with the `otel` feature), as Go's `Push` puts it into the
    /// event's metadata (`pkg/client/event.go:205-208`).
    async fn push_under<P: Serialize>(
        &self,
        span: &Span,
        key: &str,
        payload: &P,
        opts: &PushOpts,
    ) -> Result<PushedEvent> {
        let namespace = self.client.config().namespace();
        let mut request = request(namespace, key, payload, opts)?;
        otel::inject(span, &mut request.additional_metadata);
        let response = retry::unary(|| {
            let mut events = self.client.events_grpc();
            let request = retry::timed(request.clone());
            async move { events.push(request).await }
        })
        .await?;
        Ok(pushed(response.into_inner()))
    }

    /// Pushes every event in `events` in one `BulkPush` call. The returned
    /// events are in the same order as `events`.
    ///
    /// An empty `events` makes no call at all and returns `Ok(Vec::new())`
    /// straight away.
    ///
    /// # Errors
    ///
    /// [`Error::Json`] when an event's payload or metadata cannot be
    /// serialized, and [`Error::Grpc`] when the call fails.
    pub async fn bulk_push(
        &self,
        events: impl IntoIterator<Item = EventInput>,
    ) -> Result<Vec<PushedEvent>> {
        let events: Vec<EventInput> = events.into_iter().collect();
        let span = otel::bulk_push_event(events.len());
        let pushed = self
            .bulk_push_under(&span, &events)
            .instrument(span.clone())
            .await;
        otel::record_result(&span, &pushed);
        pushed
    }

    /// [`bulk_push`](Self::bulk_push) under `span`; every event carries its
    /// traceparent (with the `otel` feature), as Go's `BulkPush` puts it into
    /// each (`pkg/client/event.go:262`).
    async fn bulk_push_under(
        &self,
        span: &Span,
        events: &[EventInput],
    ) -> Result<Vec<PushedEvent>> {
        let namespace = self.client.config().namespace();
        let requests = events
            .iter()
            .map(|input| {
                let mut request = request(namespace, &input.key, &input.payload, &input.opts)?;
                otel::inject(span, &mut request.additional_metadata);
                Ok(request)
            })
            .collect::<Result<Vec<_>>>()?;
        if requests.is_empty() {
            return Ok(Vec::new());
        }
        let bulk_request = BulkPushEventRequest { events: requests };
        let response = retry::unary(|| {
            let mut events = self.client.events_grpc();
            let request = retry::timed(bulk_request.clone());
            async move { events.bulk_push(request).await }
        })
        .await?;
        Ok(response
            .into_inner()
            .events
            .into_iter()
            .map(pushed)
            .collect())
    }
}

/// Turns the engine's stored `Event` into what [`push`](EventsClient::push)
/// and [`bulk_push`](EventsClient::bulk_push) hand back.
fn pushed(event: Event) -> PushedEvent {
    PushedEvent {
        id: event.event_id,
        key: event.key,
    }
}

/// An event pushed to the engine.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PushedEvent {
    /// The id the engine gave this event.
    pub id: String,
    /// The event's key, including the namespace.
    pub key: String,
}

/// Options for a pushed event.
///
/// Every setter takes `self` by value and returns it, so calls chain:
///
/// ```
/// use hatchet_client::{Priority, PushOpts};
///
/// let opts = PushOpts::default()
///     .metadata("customer", "acme")
///     .priority(Priority::High)
///     .scope("acme");
/// ```
#[derive(Clone, Debug, Default)]
#[must_use = "push options change nothing until they are passed to `push` or `bulk_push`"]
pub struct PushOpts {
    metadata: Map<String, Value>,
    priority: Option<Priority>,
    scope: Option<String>,
}

impl PushOpts {
    /// Adds one key to the event's additional metadata. Calling this
    /// repeatedly accumulates keys; a later call with the same key
    /// overwrites the earlier value.
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Sets the priority tasks triggered by this event are scheduled at.
    pub fn priority(mut self, priority: Priority) -> Self {
        self.priority = Some(priority);
        self
    }

    /// Sets the scope used to subset candidate event filters at evaluation
    /// time.
    pub fn scope(mut self, scope: impl Into<String>) -> Self {
        self.scope = Some(scope.into());
        self
    }
}

/// One event for [`EventsClient::bulk_push`].
#[derive(Clone, Debug)]
#[must_use = "an event input is pushed by `bulk_push`, not by building it"]
pub struct EventInput {
    key: String,
    payload: Value,
    opts: PushOpts,
}

impl EventInput {
    /// An event under `key`, carrying `payload`, with default options.
    ///
    /// # Errors
    ///
    /// [`Error::Json`] when `payload` cannot be serialized.
    pub fn new<P: Serialize>(key: impl Into<String>, payload: &P) -> Result<Self> {
        let payload =
            serde_json::to_value(payload).map_err(|error| Error::Json(error.to_string()))?;
        Ok(Self {
            key: key.into(),
            payload,
            opts: PushOpts::default(),
        })
    }

    /// Sets this event's options.
    pub fn opts(mut self, opts: PushOpts) -> Self {
        self.opts = opts;
        self
    }
}

/// Builds the `Push`/`BulkPush` request for `key` (prefixed with `namespace`
/// unless it already carries it — **not lowercased**, since event keys are
/// never lowercased, matching how `on_events` triggers are registered) and
/// `payload`, applying `opts`.
pub(crate) fn request<P: Serialize>(
    namespace: &str,
    key: &str,
    payload: &P,
    opts: &PushOpts,
) -> Result<PushEventRequest> {
    let payload = serde_json::to_string(payload).map_err(|error| Error::Json(error.to_string()))?;
    let additional_metadata = if opts.metadata.is_empty() {
        None
    } else {
        Some(
            serde_json::to_string(&opts.metadata)
                .map_err(|error| Error::Json(error.to_string()))?,
        )
    };
    Ok(PushEventRequest {
        key: namespace::apply(namespace, key),
        payload,
        event_timestamp: Some(Timestamp::from(SystemTime::now())),
        additional_metadata,
        priority: opts.priority.map(Priority::to_proto),
        scope: opts.scope.clone(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn request_with_default_opts() {
        let request = request(
            "dev_",
            "approval.granted",
            &json!({"issue": "BLOG-12"}),
            &PushOpts::default(),
        )
        .unwrap();
        assert_eq!(request.key, "dev_approval.granted");
        assert_eq!(request.payload, r#"{"issue":"BLOG-12"}"#);
        assert!(request.event_timestamp.is_some());
        assert_eq!(request.additional_metadata, None);
        assert_eq!(request.priority, None);
        assert_eq!(request.scope, None);
    }

    #[test]
    fn request_does_not_double_prefix_an_already_namespaced_key() {
        let request = request(
            "dev_",
            "dev_approval.granted",
            &json!({}),
            &PushOpts::default(),
        )
        .unwrap();
        assert_eq!(request.key, "dev_approval.granted");
    }

    #[test]
    fn request_never_lowercases_the_key() {
        let request =
            request("dev_", "Approval.Granted", &json!({}), &PushOpts::default()).unwrap();
        assert_eq!(request.key, "dev_Approval.Granted");
    }

    #[test]
    fn request_with_no_namespace() {
        let request = request("", "approval.granted", &json!({}), &PushOpts::default()).unwrap();
        assert_eq!(request.key, "approval.granted");
    }

    #[test]
    fn request_carries_metadata_priority_and_scope() {
        let opts = PushOpts::default()
            .metadata("a", "b")
            .metadata("n", 1)
            .priority(Priority::High)
            .scope("acme");
        let request = request("dev_", "approval.granted", &json!({}), &opts).unwrap();
        let metadata: Value =
            serde_json::from_str(request.additional_metadata.as_ref().unwrap()).unwrap();
        assert_eq!(metadata, json!({"a": "b", "n": 1}));
        assert_eq!(request.priority, Some(3));
        assert_eq!(request.scope.as_deref(), Some("acme"));
    }

    #[test]
    fn payload_that_cannot_be_serialized_is_a_json_error() {
        use std::collections::HashMap;
        let payload: HashMap<(i32, i32), i32> = HashMap::from([((1, 2), 3)]);
        let error =
            request("dev_", "approval.granted", &payload, &PushOpts::default()).unwrap_err();
        assert!(matches!(error, Error::Json(_)), "{error:?}");
    }
}