Skip to main content

hatchet_rest/
types.rs

1//! Types every part of the API shares.
2
3use std::time::SystemTime;
4
5use serde::{Deserialize, Serialize};
6
7/// A JSON object as the engine sends it (inputs, outputs, metadata,
8/// payloads, fields this crate does not model).
9pub type JsonObject = serde_json::Map<String, serde_json::Value>;
10
11/// A string enum of the spec whose value set may grow: every known value
12/// is a variant, and anything else is kept in `Other` rather than failing
13/// to parse.
14macro_rules! string_enum {
15    (
16        $(#[$meta:meta])*
17        $name:ident {
18            $( $(#[$variant_meta:meta])* $variant:ident => $wire:literal, )+
19        }
20    ) => {
21        $(#[$meta])*
22        #[derive(Clone, Debug, PartialEq, Eq, Hash)]
23        #[non_exhaustive]
24        pub enum $name {
25            $( $(#[$variant_meta])* $variant, )+
26            /// A value this version of the crate does not know, exactly as
27            /// the engine spelled it.
28            Other(String),
29        }
30
31        impl $name {
32            /// The value as the engine spells it.
33            #[must_use]
34            pub fn as_str(&self) -> &str {
35                match self {
36                    $( Self::$variant => $wire, )+
37                    Self::Other(other) => other,
38                }
39            }
40        }
41
42        impl std::fmt::Display for $name {
43            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44                f.write_str(self.as_str())
45            }
46        }
47
48        impl serde::Serialize for $name {
49            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
50                serializer.serialize_str(self.as_str())
51            }
52        }
53
54        impl<'de> serde::Deserialize<'de> for $name {
55            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
56                let text = <String as serde::Deserialize>::deserialize(deserializer)?;
57                Ok(match text.as_str() {
58                    $( $wire => Self::$variant, )+
59                    _ => Self::Other(text),
60                })
61            }
62        }
63    };
64}
65pub(crate) use string_enum;
66
67string_enum! {
68    /// Sort direction of the log, cron and scheduled-run lists.
69    SortDirection {
70        /// Ascending.
71        Asc => "ASC",
72        /// Descending.
73        Desc => "DESC",
74    }
75}
76
77/// `value` as a JSON object, or why it is not one. Shared by the filter
78/// payload, the webhook static payload and the CEL input.
79pub(crate) fn to_object(
80    value: &impl Serialize,
81    what: &str,
82) -> std::result::Result<JsonObject, String> {
83    match serde_json::to_value(value) {
84        Ok(serde_json::Value::Object(object)) => Ok(object),
85        Ok(other) => Err(format!("{what} must be a JSON object, not {other}")),
86        Err(error) => Err(format!("{what} could not be serialized: {error}")),
87    }
88}
89
90/// The `metadata` every resource carries.
91#[derive(Clone, Debug, Deserialize)]
92#[serde(rename_all = "camelCase")]
93#[non_exhaustive]
94pub struct ResourceMeta {
95    /// The resource's id.
96    pub id: String,
97    /// When it was created.
98    #[serde(deserialize_with = "crate::time::deserialize")]
99    pub created_at: SystemTime,
100    /// When it last changed.
101    #[serde(deserialize_with = "crate::time::deserialize")]
102    pub updated_at: SystemTime,
103}
104
105/// One page of a list.
106#[derive(Clone, Debug, Deserialize)]
107#[non_exhaustive]
108pub struct Page<T> {
109    /// The items on this page.
110    #[serde(default = "Vec::new")]
111    pub rows: Vec<T>,
112    /// Where this page sits. Some lists never say (the webhook list on
113    /// every engine, the worker list on v0.80.0), so this is `None` there.
114    #[serde(default)]
115    pub pagination: Option<Pagination>,
116}
117
118impl<T> Page<T> {
119    /// Whether the engine reports a page after this one. `false` when the
120    /// list does not report pagination at all.
121    #[must_use]
122    pub fn has_next(&self) -> bool {
123        self.pagination.is_some_and(Pagination::has_next)
124    }
125}
126
127/// The engine's `PaginationResponse`. Pages count from 1; `next_page` keeps
128/// counting past the last page, so compare `current_page` with `num_pages`
129/// (as [`has_next`](Pagination::has_next) does) rather than trusting it.
130#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
131#[non_exhaustive]
132pub struct Pagination {
133    /// The page this is, counting from 1.
134    #[serde(default)]
135    pub current_page: Option<i64>,
136    /// The page after it, as the engine counts.
137    #[serde(default)]
138    pub next_page: Option<i64>,
139    /// How many pages there are.
140    #[serde(default)]
141    pub num_pages: Option<i64>,
142}
143
144impl Pagination {
145    /// Whether there is a page after the current one.
146    #[must_use]
147    pub fn has_next(self) -> bool {
148        matches!((self.current_page, self.num_pages), (Some(current), Some(pages)) if current < pages)
149    }
150}
151
152/// Reads an explicit `null` as the type's default. The engine writes `null`
153/// for list fields it has nothing for (`worker:update` answers with
154/// `"actions": null`), and `#[serde(default)]` alone only covers a key that
155/// is absent.
156pub(crate) fn null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
157where
158    D: serde::Deserializer<'de>,
159    T: Default + serde::Deserialize<'de>,
160{
161    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    string_enum! {
169        /// A test enum.
170        Colour {
171            /// Red.
172            Red => "RED",
173        }
174    }
175
176    #[test]
177    fn a_string_enum_round_trips_known_and_unknown_values() {
178        assert_eq!(
179            serde_json::from_str::<Colour>(r#""RED""#).unwrap(),
180            Colour::Red
181        );
182        let other: Colour = serde_json::from_str(r#""MAUVE""#).unwrap();
183        assert_eq!(other, Colour::Other("MAUVE".into()));
184        assert_eq!(serde_json::to_string(&other).unwrap(), r#""MAUVE""#);
185        assert_eq!(Colour::Red.to_string(), "RED");
186    }
187
188    #[test]
189    fn a_page_tolerates_missing_rows_and_pagination() {
190        let page: Page<u8> = serde_json::from_str("{}").unwrap();
191        assert!(page.rows.is_empty());
192        assert!(page.pagination.is_none());
193        assert!(!page.has_next());
194        let page: Page<u8> = serde_json::from_str(
195            r#"{"rows":[1,2],"pagination":{"current_page":1,"next_page":2,"num_pages":3}}"#,
196        )
197        .unwrap();
198        assert_eq!(page.rows, [1, 2]);
199        assert!(page.has_next());
200    }
201
202    #[test]
203    fn the_last_page_has_no_next_even_though_next_page_counts_on() {
204        // Observed on both engines (Task 0 (e)): offset past the last page.
205        let page: Page<u8> = serde_json::from_str(
206            r#"{"rows":[],"pagination":{"current_page":2,"next_page":3,"num_pages":2}}"#,
207        )
208        .unwrap();
209        assert!(!page.has_next());
210        // The log list reports all zeros.
211        let page: Page<u8> = serde_json::from_str(
212            r#"{"rows":[],"pagination":{"current_page":0,"next_page":0,"num_pages":0}}"#,
213        )
214        .unwrap();
215        assert!(!page.has_next());
216    }
217}