Skip to main content

hatchet_rest/
rate_limits.rs

1//! Rate limits (`rate-limit:list`). Creating or raising one is
2//! `hatchet-client`'s `Client::rate_limits().put`, over gRPC — the official
3//! Go SDK splits them the same way (`sdks/go/features/ratelimits.go`).
4
5use std::time::SystemTime;
6
7use serde::Deserialize;
8
9use crate::transport::Query;
10use crate::types::string_enum;
11use crate::{Operation, Page, RestClient, Result};
12
13string_enum! {
14    /// What [`RateLimitListQuery::order_by`] sorts on.
15    RateLimitOrderBy {
16        /// The key.
17        Key => "key",
18        /// The current value.
19        Value => "value",
20        /// The limit.
21        LimitValue => "limitValue",
22    }
23}
24
25string_enum! {
26    /// Sort direction of the rate limit list (lower-case on this one list,
27    /// unlike every other list's `ASC`/`DESC`).
28    RateLimitOrderDirection {
29        /// Ascending.
30        Asc => "asc",
31        /// Descending.
32        Desc => "desc",
33    }
34}
35
36/// A rate limit (`RateLimit`).
37#[derive(Clone, Debug, Deserialize)]
38#[serde(rename_all = "camelCase")]
39#[non_exhaustive]
40pub struct RateLimit {
41    /// The key tasks spend.
42    pub key: String,
43    /// The tenant it belongs to.
44    pub tenant_id: String,
45    /// The allowance per window.
46    pub limit_value: i64,
47    /// What is left in the current window.
48    pub value: i64,
49    /// The window, as the engine spells it (e.g. `"1 second"`).
50    pub window: String,
51    /// When the allowance was last refilled.
52    #[serde(deserialize_with = "crate::time::deserialize")]
53    pub last_refill: SystemTime,
54    /// Fields this crate does not model, as the engine sent them.
55    #[serde(flatten)]
56    pub other: crate::JsonObject,
57}
58
59/// Which rate limits [`RateLimitsApi::list`] returns. Only the settings
60/// given a value are sent.
61#[derive(Clone, Debug, Default)]
62#[must_use]
63pub struct RateLimitListQuery {
64    offset: Option<i64>,
65    limit: Option<i64>,
66    search: Option<String>,
67    order_by: Option<(RateLimitOrderBy, RateLimitOrderDirection)>,
68}
69
70impl RateLimitListQuery {
71    /// Every rate limit, in the engine's default order and page size.
72    pub fn new() -> Self {
73        Self::default()
74    }
75
76    /// Skip this many.
77    pub fn offset(mut self, offset: i64) -> Self {
78        self.offset = Some(offset);
79        self
80    }
81
82    /// At most this many.
83    pub fn limit(mut self, limit: i64) -> Self {
84        self.limit = Some(limit);
85        self
86    }
87
88    /// Only keys matching this search text.
89    pub fn search(mut self, text: impl Into<String>) -> Self {
90        self.search = Some(text.into());
91        self
92    }
93
94    /// Sort order.
95    pub fn order_by(mut self, field: RateLimitOrderBy, direction: RateLimitOrderDirection) -> Self {
96        self.order_by = Some((field, direction));
97        self
98    }
99
100    fn query(&self) -> Query {
101        let mut query = Query::new();
102        query.push_opt("offset", self.offset);
103        query.push_opt("limit", self.limit);
104        query.push_opt("search", self.search.as_deref());
105        if let Some((field, direction)) = &self.order_by {
106            query.push("orderByField", field);
107            query.push("orderByDirection", direction);
108        }
109        query
110    }
111}
112
113/// The rate limit endpoint; from [`RestClient::rate_limits`].
114#[derive(Clone, Copy, Debug)]
115pub struct RateLimitsApi<'a> {
116    pub(crate) client: &'a RestClient,
117}
118
119impl RateLimitsApi<'_> {
120    /// Lists the tenant's rate limits (`rate-limit:list`).
121    ///
122    /// ```no_run
123    /// # async fn example(rest: hatchet_rest::RestClient) -> hatchet_rest::Result<()> {
124    /// use hatchet_rest::RateLimitListQuery;
125    ///
126    /// let page = rest.rate_limits().list(RateLimitListQuery::new().limit(20)).await?;
127    /// for limit in &page.rows {
128    ///     println!("{}: {}/{} per {}", limit.key, limit.value, limit.limit_value, limit.window);
129    /// }
130    /// # Ok(())
131    /// # }
132    /// ```
133    ///
134    /// # Errors
135    ///
136    /// As for any call; see [`Error`](crate::Error).
137    pub async fn list(&self, query: RateLimitListQuery) -> Result<Page<RateLimit>> {
138        self.client
139            .inner
140            .call(Operation::RateLimitList, &[], query.query())
141            .await
142    }
143}