Skip to main content

hatchet_rest/
logs.rs

1//! A task run's log lines — what `hatchet-client`'s `Context::log` wrote
2//! (`v1-log-line:list`).
3
4use std::time::SystemTime;
5
6use serde::Deserialize;
7
8use crate::time::{deserialize, format_rfc3339};
9use crate::transport::Query;
10use crate::types::{SortDirection, string_enum};
11use crate::{JsonObject, Operation, Page, RestClient, Result};
12
13string_enum! {
14    /// A log line's level (`V1LogLineLevel`).
15    LogLevel {
16        /// Debug.
17        Debug => "DEBUG",
18        /// Info.
19        Info => "INFO",
20        /// Warning.
21        Warn => "WARN",
22        /// Error.
23        Error => "ERROR",
24    }
25}
26
27/// One log line (`V1LogLine`).
28#[derive(Clone, Debug, Deserialize)]
29#[serde(rename_all = "camelCase")]
30#[non_exhaustive]
31pub struct LogLine {
32    /// When it was written.
33    #[serde(deserialize_with = "deserialize")]
34    pub created_at: SystemTime,
35    /// The text.
36    pub message: String,
37    /// Structured metadata.
38    #[serde(default)]
39    pub metadata: JsonObject,
40    /// Its level.
41    #[serde(default)]
42    pub level: Option<LogLevel>,
43    /// The retry it came from.
44    #[serde(default)]
45    pub retry_count: Option<i64>,
46    /// The attempt it came from.
47    #[serde(default)]
48    pub attempt: Option<i64>,
49    /// The task run (not sent by v0.80.0).
50    #[serde(default)]
51    pub task_external_id: Option<String>,
52    /// The task run's display name (not sent by v0.80.0).
53    #[serde(default)]
54    pub task_display_name: Option<String>,
55    /// Fields this crate does not model, as the engine sent them.
56    #[serde(flatten)]
57    pub other: JsonObject,
58}
59
60/// Which lines [`LogsApi::list`] returns. Only the settings given a value
61/// are sent, except `since`. The API pages logs by time and count, not by
62/// offset, and the engine reports all-zero pagination for them, so
63/// [`Page::has_next`] is always `false` here: to read on, ask again with
64/// [`since`](Self::since) or [`until`](Self::until) past the last line.
65#[derive(Clone, Debug, Default)]
66#[must_use]
67pub struct LogListQuery {
68    limit: Option<i64>,
69    since: Option<SystemTime>,
70    until: Option<SystemTime>,
71    search: Option<String>,
72    levels: Vec<LogLevel>,
73    direction: Option<SortDirection>,
74    attempt: Option<i64>,
75}
76
77impl LogListQuery {
78    /// Every line, in the engine's default order and page size. Without
79    /// [`since`](Self::since) the query asks for lines since 1970-01-01.
80    pub fn new() -> Self {
81        Self::default()
82    }
83
84    /// At most this many.
85    pub fn limit(mut self, limit: i64) -> Self {
86        self.limit = Some(limit);
87        self
88    }
89
90    /// Written at or after `since`.
91    pub fn since(mut self, since: SystemTime) -> Self {
92        self.since = Some(since);
93        self
94    }
95
96    /// Written before `until`.
97    pub fn until(mut self, until: SystemTime) -> Self {
98        self.until = Some(until);
99        self
100    }
101
102    /// Containing this text.
103    pub fn search(mut self, text: impl Into<String>) -> Self {
104        self.search = Some(text.into());
105        self
106    }
107
108    /// Only these levels.
109    pub fn levels(mut self, levels: impl IntoIterator<Item = LogLevel>) -> Self {
110        self.levels.extend(levels);
111        self
112    }
113
114    /// Oldest or newest first.
115    pub fn direction(mut self, direction: SortDirection) -> Self {
116        self.direction = Some(direction);
117        self
118    }
119
120    /// Only this attempt.
121    pub fn attempt(mut self, attempt: i64) -> Self {
122        self.attempt = Some(attempt);
123        self
124    }
125
126    fn query(&self) -> Query {
127        let mut query = Query::new();
128        query.push_opt("limit", self.limit);
129        query.push_opt("since", self.since.map(format_rfc3339));
130        query.push_opt("until", self.until.map(format_rfc3339));
131        query.push_opt("search", self.search.as_deref());
132        query.push_all("levels", &self.levels);
133        query.push_opt("order_by_direction", self.direction.as_ref());
134        query.push_opt("attempt", self.attempt);
135        query
136    }
137}
138
139/// Log lines; from [`RestClient::logs`].
140#[derive(Clone, Copy, Debug)]
141pub struct LogsApi<'a> {
142    pub(crate) client: &'a RestClient,
143}
144
145impl LogsApi<'_> {
146    /// A task run's log lines (`v1-log-line:list`). `task_run_id` is a
147    /// [`TaskSummary::task_external_id`](crate::TaskSummary::task_external_id).
148    ///
149    /// ```no_run
150    /// # async fn example(rest: hatchet_rest::RestClient, task_run_id: &str) -> hatchet_rest::Result<()> {
151    /// use hatchet_rest::{LogLevel, LogListQuery, SortDirection};
152    ///
153    /// let page = rest
154    ///     .logs()
155    ///     .list(
156    ///         task_run_id,
157    ///         LogListQuery::new()
158    ///             .levels([LogLevel::Warn, LogLevel::Error])
159    ///             .direction(SortDirection::Asc)
160    ///             .limit(100),
161    ///     )
162    ///     .await?;
163    /// for line in &page.rows {
164    ///     println!("{:?} {}", line.level, line.message);
165    /// }
166    /// # Ok(())
167    /// # }
168    /// ```
169    ///
170    /// # Errors
171    ///
172    /// [`Error::InvalidArgument`](crate::Error::InvalidArgument) for an
173    /// empty id, before anything is sent; otherwise as for any call (see
174    /// [`Error`](crate::Error)).
175    pub async fn list(&self, task_run_id: &str, query: LogListQuery) -> Result<Page<LogLine>> {
176        self.client
177            .inner
178            .call(Operation::V1LogLineList, &[task_run_id], query.query())
179            .await
180    }
181}
182
183impl RestClient {
184    /// A task run's log lines (`v1-log-line:list`).
185    pub fn logs(&self) -> LogsApi<'_> {
186        LogsApi { client: self }
187    }
188}