Skip to main content

hatchet_client/
events.rs

1//! Pushing events to the engine.
2//!
3//! [`request`] is the pure part — assembling the wire request — shared by
4//! [`EventsClient::push`] and [`EventsClient::bulk_push`], so both send the
5//! same shape of request.
6
7use std::time::SystemTime;
8
9use hatchet_proto::prost_types::Timestamp;
10use hatchet_proto::root::{BulkPushEventRequest, Event, PushEventRequest};
11use serde::Serialize;
12use serde_json::{Map, Value};
13use tracing::{Instrument, Span};
14
15use crate::config::namespace;
16use crate::declare::Priority;
17use crate::error::{Error, Result};
18use crate::{Client, otel, retry};
19
20/// Pushes events to the engine, one at a time or in bulk.
21///
22/// Get one from [`Client::events`].
23///
24/// ```no_run
25/// # async fn example(client: hatchet_client::Client) -> hatchet_client::Result<()> {
26/// use hatchet_client::PushOpts;
27///
28/// let event = client
29///     .events()
30///     .push("approval.granted", &serde_json::json!({"issue": "BLOG-12"}), PushOpts::default())
31///     .await?;
32/// println!("pushed {} as {}", event.key, event.id);
33/// # Ok(())
34/// # }
35/// ```
36#[derive(Clone, Debug)]
37pub struct EventsClient {
38    client: Client,
39}
40
41impl EventsClient {
42    pub(crate) fn new(client: Client) -> Self {
43        Self { client }
44    }
45
46    /// Pushes one event under `key`, prefixed with the client's namespace
47    /// unless it is already there.
48    ///
49    /// # Errors
50    ///
51    /// [`Error::Json`] when `payload` or a metadata value cannot be
52    /// serialized, and [`Error::Grpc`] when the call fails.
53    pub async fn push<P: Serialize>(
54        &self,
55        key: impl AsRef<str>,
56        payload: &P,
57        opts: PushOpts,
58    ) -> Result<PushedEvent> {
59        let key = key.as_ref();
60        let span = otel::push_event(key);
61        let pushed = self
62            .push_under(&span, key, payload, &opts)
63            .instrument(span.clone())
64            .await;
65        otel::record_result(&span, &pushed);
66        pushed
67    }
68
69    /// [`push`](Self::push) under `span`, whose traceparent the event
70    /// carries (with the `otel` feature), as Go's `Push` puts it into the
71    /// event's metadata (`pkg/client/event.go:205-208`).
72    async fn push_under<P: Serialize>(
73        &self,
74        span: &Span,
75        key: &str,
76        payload: &P,
77        opts: &PushOpts,
78    ) -> Result<PushedEvent> {
79        let namespace = self.client.config().namespace();
80        let mut request = request(namespace, key, payload, opts)?;
81        otel::inject(span, &mut request.additional_metadata);
82        let response = retry::unary(|| {
83            let mut events = self.client.events_grpc();
84            let request = retry::timed(request.clone());
85            async move { events.push(request).await }
86        })
87        .await?;
88        Ok(pushed(response.into_inner()))
89    }
90
91    /// Pushes every event in `events` in one `BulkPush` call. The returned
92    /// events are in the same order as `events`.
93    ///
94    /// An empty `events` makes no call at all and returns `Ok(Vec::new())`
95    /// straight away.
96    ///
97    /// # Errors
98    ///
99    /// [`Error::Json`] when an event's payload or metadata cannot be
100    /// serialized, and [`Error::Grpc`] when the call fails.
101    pub async fn bulk_push(
102        &self,
103        events: impl IntoIterator<Item = EventInput>,
104    ) -> Result<Vec<PushedEvent>> {
105        let events: Vec<EventInput> = events.into_iter().collect();
106        let span = otel::bulk_push_event(events.len());
107        let pushed = self
108            .bulk_push_under(&span, &events)
109            .instrument(span.clone())
110            .await;
111        otel::record_result(&span, &pushed);
112        pushed
113    }
114
115    /// [`bulk_push`](Self::bulk_push) under `span`; every event carries its
116    /// traceparent (with the `otel` feature), as Go's `BulkPush` puts it into
117    /// each (`pkg/client/event.go:262`).
118    async fn bulk_push_under(
119        &self,
120        span: &Span,
121        events: &[EventInput],
122    ) -> Result<Vec<PushedEvent>> {
123        let namespace = self.client.config().namespace();
124        let requests = events
125            .iter()
126            .map(|input| {
127                let mut request = request(namespace, &input.key, &input.payload, &input.opts)?;
128                otel::inject(span, &mut request.additional_metadata);
129                Ok(request)
130            })
131            .collect::<Result<Vec<_>>>()?;
132        if requests.is_empty() {
133            return Ok(Vec::new());
134        }
135        let bulk_request = BulkPushEventRequest { events: requests };
136        let response = retry::unary(|| {
137            let mut events = self.client.events_grpc();
138            let request = retry::timed(bulk_request.clone());
139            async move { events.bulk_push(request).await }
140        })
141        .await?;
142        Ok(response
143            .into_inner()
144            .events
145            .into_iter()
146            .map(pushed)
147            .collect())
148    }
149}
150
151/// Turns the engine's stored `Event` into what [`push`](EventsClient::push)
152/// and [`bulk_push`](EventsClient::bulk_push) hand back.
153fn pushed(event: Event) -> PushedEvent {
154    PushedEvent {
155        id: event.event_id,
156        key: event.key,
157    }
158}
159
160/// An event pushed to the engine.
161#[derive(Clone, Debug, PartialEq, Eq)]
162pub struct PushedEvent {
163    /// The id the engine gave this event.
164    pub id: String,
165    /// The event's key, including the namespace.
166    pub key: String,
167}
168
169/// Options for a pushed event.
170///
171/// Every setter takes `self` by value and returns it, so calls chain:
172///
173/// ```
174/// use hatchet_client::{Priority, PushOpts};
175///
176/// let opts = PushOpts::default()
177///     .metadata("customer", "acme")
178///     .priority(Priority::High)
179///     .scope("acme");
180/// ```
181#[derive(Clone, Debug, Default)]
182#[must_use = "push options change nothing until they are passed to `push` or `bulk_push`"]
183pub struct PushOpts {
184    metadata: Map<String, Value>,
185    priority: Option<Priority>,
186    scope: Option<String>,
187}
188
189impl PushOpts {
190    /// Adds one key to the event's additional metadata. Calling this
191    /// repeatedly accumulates keys; a later call with the same key
192    /// overwrites the earlier value.
193    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
194        self.metadata.insert(key.into(), value.into());
195        self
196    }
197
198    /// Sets the priority tasks triggered by this event are scheduled at.
199    pub fn priority(mut self, priority: Priority) -> Self {
200        self.priority = Some(priority);
201        self
202    }
203
204    /// Sets the scope used to subset candidate event filters at evaluation
205    /// time.
206    pub fn scope(mut self, scope: impl Into<String>) -> Self {
207        self.scope = Some(scope.into());
208        self
209    }
210}
211
212/// One event for [`EventsClient::bulk_push`].
213#[derive(Clone, Debug)]
214#[must_use = "an event input is pushed by `bulk_push`, not by building it"]
215pub struct EventInput {
216    key: String,
217    payload: Value,
218    opts: PushOpts,
219}
220
221impl EventInput {
222    /// An event under `key`, carrying `payload`, with default options.
223    ///
224    /// # Errors
225    ///
226    /// [`Error::Json`] when `payload` cannot be serialized.
227    pub fn new<P: Serialize>(key: impl Into<String>, payload: &P) -> Result<Self> {
228        let payload =
229            serde_json::to_value(payload).map_err(|error| Error::Json(error.to_string()))?;
230        Ok(Self {
231            key: key.into(),
232            payload,
233            opts: PushOpts::default(),
234        })
235    }
236
237    /// Sets this event's options.
238    pub fn opts(mut self, opts: PushOpts) -> Self {
239        self.opts = opts;
240        self
241    }
242}
243
244/// Builds the `Push`/`BulkPush` request for `key` (prefixed with `namespace`
245/// unless it already carries it — **not lowercased**, since event keys are
246/// never lowercased, matching how `on_events` triggers are registered) and
247/// `payload`, applying `opts`.
248pub(crate) fn request<P: Serialize>(
249    namespace: &str,
250    key: &str,
251    payload: &P,
252    opts: &PushOpts,
253) -> Result<PushEventRequest> {
254    let payload = serde_json::to_string(payload).map_err(|error| Error::Json(error.to_string()))?;
255    let additional_metadata = if opts.metadata.is_empty() {
256        None
257    } else {
258        Some(
259            serde_json::to_string(&opts.metadata)
260                .map_err(|error| Error::Json(error.to_string()))?,
261        )
262    };
263    Ok(PushEventRequest {
264        key: namespace::apply(namespace, key),
265        payload,
266        event_timestamp: Some(Timestamp::from(SystemTime::now())),
267        additional_metadata,
268        priority: opts.priority.map(Priority::to_proto),
269        scope: opts.scope.clone(),
270    })
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276    use serde_json::json;
277
278    #[test]
279    fn request_with_default_opts() {
280        let request = request(
281            "dev_",
282            "approval.granted",
283            &json!({"issue": "BLOG-12"}),
284            &PushOpts::default(),
285        )
286        .unwrap();
287        assert_eq!(request.key, "dev_approval.granted");
288        assert_eq!(request.payload, r#"{"issue":"BLOG-12"}"#);
289        assert!(request.event_timestamp.is_some());
290        assert_eq!(request.additional_metadata, None);
291        assert_eq!(request.priority, None);
292        assert_eq!(request.scope, None);
293    }
294
295    #[test]
296    fn request_does_not_double_prefix_an_already_namespaced_key() {
297        let request = request(
298            "dev_",
299            "dev_approval.granted",
300            &json!({}),
301            &PushOpts::default(),
302        )
303        .unwrap();
304        assert_eq!(request.key, "dev_approval.granted");
305    }
306
307    #[test]
308    fn request_never_lowercases_the_key() {
309        let request =
310            request("dev_", "Approval.Granted", &json!({}), &PushOpts::default()).unwrap();
311        assert_eq!(request.key, "dev_Approval.Granted");
312    }
313
314    #[test]
315    fn request_with_no_namespace() {
316        let request = request("", "approval.granted", &json!({}), &PushOpts::default()).unwrap();
317        assert_eq!(request.key, "approval.granted");
318    }
319
320    #[test]
321    fn request_carries_metadata_priority_and_scope() {
322        let opts = PushOpts::default()
323            .metadata("a", "b")
324            .metadata("n", 1)
325            .priority(Priority::High)
326            .scope("acme");
327        let request = request("dev_", "approval.granted", &json!({}), &opts).unwrap();
328        let metadata: Value =
329            serde_json::from_str(request.additional_metadata.as_ref().unwrap()).unwrap();
330        assert_eq!(metadata, json!({"a": "b", "n": 1}));
331        assert_eq!(request.priority, Some(3));
332        assert_eq!(request.scope.as_deref(), Some("acme"));
333    }
334
335    #[test]
336    fn payload_that_cannot_be_serialized_is_a_json_error() {
337        use std::collections::HashMap;
338        let payload: HashMap<(i32, i32), i32> = HashMap::from([((1, 2), 3)]);
339        let error =
340            request("dev_", "approval.granted", &payload, &PushOpts::default()).unwrap_err();
341        assert!(matches!(error, Error::Json(_)), "{error:?}");
342    }
343}