Skip to main content

hatchet_rest/
filters.rs

1//! Event filters: CEL expressions that decide, per scope, whether an event
2//! triggers a workflow (`v1-filter:*`).
3
4use serde::{Deserialize, Serialize};
5
6use crate::transport::Query;
7use crate::types::to_object;
8use crate::{Error, JsonObject, Operation, Page, ResourceMeta, RestClient, Result};
9
10/// A filter (`V1Filter`).
11#[derive(Clone, Debug, Deserialize)]
12#[serde(rename_all = "camelCase")]
13#[non_exhaustive]
14pub struct Filter {
15    /// Id and timestamps; `metadata.id` is the filter id.
16    pub metadata: ResourceMeta,
17    /// The tenant.
18    pub tenant_id: String,
19    /// The workflow it applies to (by id).
20    pub workflow_id: String,
21    /// The scope it applies in.
22    pub scope: String,
23    /// The CEL expression.
24    pub expression: String,
25    /// The payload handed to the runs it lets through.
26    #[serde(default)]
27    pub payload: Option<JsonObject>,
28    /// Whether it was declared with the workflow rather than created
29    /// through the API.
30    #[serde(default)]
31    pub is_declarative: Option<bool>,
32    /// Fields this crate does not model, as the engine sent them.
33    #[serde(flatten)]
34    pub other: JsonObject,
35}
36
37/// A filter to create; for [`FiltersApi::create`].
38#[derive(Clone, Debug)]
39#[must_use]
40pub struct FilterSpec {
41    workflow_id: String,
42    scope: String,
43    expression: String,
44    payload: Option<std::result::Result<JsonObject, String>>,
45}
46
47impl FilterSpec {
48    /// A filter on `workflow_id` (the workflow's id, not its name) in
49    /// `scope`, letting through the events for which the CEL `expression`
50    /// is true.
51    pub fn new(
52        workflow_id: impl Into<String>,
53        scope: impl Into<String>,
54        expression: impl Into<String>,
55    ) -> Self {
56        Self {
57            workflow_id: workflow_id.into(),
58            scope: scope.into(),
59            expression: expression.into(),
60            payload: None,
61        }
62    }
63
64    /// A payload for the runs it lets through; must serialize to a JSON
65    /// object ([`FiltersApi::create`] refuses anything else).
66    pub fn payload(mut self, payload: &impl Serialize) -> Self {
67        self.payload = Some(to_object(payload, "the payload"));
68        self
69    }
70}
71
72#[derive(Serialize)]
73#[serde(rename_all = "camelCase")]
74struct CreateBody<'a> {
75    workflow_id: &'a str,
76    scope: &'a str,
77    expression: &'a str,
78    #[serde(skip_serializing_if = "Option::is_none")]
79    payload: Option<JsonObject>,
80}
81
82/// What to change in a filter; for [`FiltersApi::update`]. Only the fields
83/// given a value are sent, and at least one is required.
84#[derive(Clone, Debug, Default, Serialize)]
85#[serde(rename_all = "camelCase")]
86#[must_use]
87pub struct FilterUpdate {
88    #[serde(skip_serializing_if = "Option::is_none")]
89    expression: Option<String>,
90    #[serde(skip_serializing_if = "Option::is_none")]
91    scope: Option<String>,
92    #[serde(skip_serializing_if = "Option::is_none")]
93    payload: Option<JsonObject>,
94    #[serde(skip)]
95    error: Option<String>,
96}
97
98impl FilterUpdate {
99    /// No change yet.
100    pub fn new() -> Self {
101        Self::default()
102    }
103
104    /// A new CEL expression.
105    pub fn expression(mut self, expression: impl Into<String>) -> Self {
106        self.expression = Some(expression.into());
107        self
108    }
109
110    /// A new scope.
111    pub fn scope(mut self, scope: impl Into<String>) -> Self {
112        self.scope = Some(scope.into());
113        self
114    }
115
116    /// A new payload; must serialize to a JSON object.
117    pub fn payload(mut self, payload: &impl Serialize) -> Self {
118        match to_object(payload, "the payload") {
119            Ok(object) => self.payload = Some(object),
120            Err(message) => self.error = Some(message),
121        }
122        self
123    }
124}
125
126/// Which filters [`FiltersApi::list`] returns. Only the settings given a
127/// value are sent.
128#[derive(Clone, Debug, Default)]
129#[must_use]
130pub struct FilterListQuery {
131    offset: Option<i64>,
132    limit: Option<i64>,
133    workflow_ids: Vec<String>,
134    scopes: Vec<String>,
135}
136
137impl FilterListQuery {
138    /// Every filter, in the engine's default page size.
139    pub fn new() -> Self {
140        Self::default()
141    }
142
143    /// Skip this many.
144    pub fn offset(mut self, offset: i64) -> Self {
145        self.offset = Some(offset);
146        self
147    }
148
149    /// At most this many.
150    pub fn limit(mut self, limit: i64) -> Self {
151        self.limit = Some(limit);
152        self
153    }
154
155    /// Only these workflows' filters (by id).
156    pub fn workflow_ids(mut self, ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
157        self.workflow_ids.extend(ids.into_iter().map(Into::into));
158        self
159    }
160
161    /// Only these scopes.
162    pub fn scopes(mut self, scopes: impl IntoIterator<Item = impl Into<String>>) -> Self {
163        self.scopes.extend(scopes.into_iter().map(Into::into));
164        self
165    }
166
167    fn query(&self) -> Query {
168        let mut query = Query::new();
169        query.push_opt("offset", self.offset);
170        query.push_opt("limit", self.limit);
171        query.push_all("workflowIds", &self.workflow_ids);
172        query.push_all("scopes", &self.scopes);
173        query
174    }
175}
176
177/// Event filters; from [`RestClient::filters`].
178#[derive(Clone, Copy, Debug)]
179pub struct FiltersApi<'a> {
180    pub(crate) client: &'a RestClient,
181}
182
183impl RestClient {
184    /// Event filters (`v1-filter:list`, `:get`, `:create`, `:update`,
185    /// `:delete`).
186    pub fn filters(&self) -> FiltersApi<'_> {
187        FiltersApi { client: self }
188    }
189}
190
191impl FiltersApi<'_> {
192    /// Lists filters (`v1-filter:list`).
193    ///
194    /// # Errors
195    ///
196    /// As for any call; see [`Error`].
197    pub async fn list(&self, query: FilterListQuery) -> Result<Page<Filter>> {
198        self.client
199            .inner
200            .call(Operation::V1FilterList, &[], query.query())
201            .await
202    }
203
204    /// One filter, by id (`v1-filter:get`).
205    ///
206    /// # Errors
207    ///
208    /// [`Error::NotFound`] for an id the engine does not know (both
209    /// supported engines answer `404` `{"message":"not found"}`);
210    /// [`Error::InvalidArgument`] for an empty id; otherwise as for any
211    /// call.
212    pub async fn get(&self, filter_id: &str) -> Result<Filter> {
213        self.client
214            .inner
215            .call(Operation::V1FilterGet, &[filter_id], Query::new())
216            .await
217    }
218
219    /// Creates a filter (`v1-filter:create`).
220    ///
221    /// ```no_run
222    /// # async fn example(rest: hatchet_rest::RestClient, workflow_id: &str) -> hatchet_rest::Result<()> {
223    /// use hatchet_rest::FilterSpec;
224    ///
225    /// let filter = rest
226    ///     .filters()
227    ///     .create(
228    ///         FilterSpec::new(workflow_id, "customer-42", "input.amount > 100")
229    ///             .payload(&serde_json::json!({"tier": "gold"})),
230    ///     )
231    ///     .await?;
232    /// println!("created filter {}", filter.metadata.id);
233    /// # Ok(())
234    /// # }
235    /// ```
236    ///
237    /// # Errors
238    ///
239    /// [`Error::InvalidArgument`] for a payload that is not a JSON object,
240    /// before anything is sent; otherwise as for any call. Sent once, never
241    /// retried.
242    pub async fn create(&self, spec: FilterSpec) -> Result<Filter> {
243        let payload = spec
244            .payload
245            .clone()
246            .transpose()
247            .map_err(Error::InvalidArgument)?;
248        let body = CreateBody {
249            workflow_id: &spec.workflow_id,
250            scope: &spec.scope,
251            expression: &spec.expression,
252            payload,
253        };
254        self.client
255            .inner
256            .call_json(Operation::V1FilterCreate, &[], &body)
257            .await
258    }
259
260    /// Changes a filter (`v1-filter:update`) and returns it as it now is.
261    ///
262    /// # Errors
263    ///
264    /// [`Error::InvalidArgument`] for an update that changes nothing or a
265    /// payload that is not a JSON object, before anything is sent;
266    /// otherwise as for [`get`](Self::get). Sent once, never retried.
267    pub async fn update(&self, filter_id: &str, update: FilterUpdate) -> Result<Filter> {
268        if let Some(message) = &update.error {
269            return Err(Error::InvalidArgument(message.clone()));
270        }
271        if update.expression.is_none() && update.scope.is_none() && update.payload.is_none() {
272            return Err(Error::InvalidArgument(
273                "a filter update must change something".into(),
274            ));
275        }
276        self.client
277            .inner
278            .call_json(Operation::V1FilterUpdate, &[filter_id], &update)
279            .await
280    }
281
282    /// Deletes a filter and returns what was deleted (`v1-filter:delete`):
283    /// unlike the cron, scheduled-run and workflow deletes, which answer
284    /// `204`, both supported engines answer this one `200` with the filter.
285    ///
286    /// # Errors
287    ///
288    /// As for [`get`](Self::get). Sent once, never retried.
289    pub async fn delete(&self, filter_id: &str) -> Result<Filter> {
290        self.client
291            .inner
292            .call(Operation::V1FilterDelete, &[filter_id], Query::new())
293            .await
294    }
295}