Skip to main content

grow_better_stack_logs/logging/
query.rs

1// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
2//! Log query model (SPEC §4 `LogQueryClient`) and polling helpers.
3
4use std::fmt;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::Arc;
7use std::time::{Duration, SystemTime};
8
9use async_trait::async_trait;
10use serde::Serialize;
11use tokio::sync::Notify;
12
13use super::LogRecord;
14use crate::core::{poll_until, Error, PollOptions, Result};
15
16/// Result ordering.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum SortOrder {
19    /// Newest first (default).
20    #[default]
21    Desc,
22    /// Oldest first.
23    Asc,
24}
25
26/// Options for [`LogQueryClient::search`].
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct SearchOptions {
29    /// Earliest timestamp (inclusive).
30    pub start: Option<SystemTime>,
31    /// Latest timestamp (inclusive).
32    pub end: Option<SystemTime>,
33    /// Maximum records (default 100).
34    pub limit: usize,
35    /// Ordering (default newest first).
36    pub order: SortOrder,
37    /// Cursor from a previous [`LogSearchResult::next_cursor`].
38    pub cursor: Option<String>,
39}
40
41impl Default for SearchOptions {
42    fn default() -> Self {
43        SearchOptions {
44            start: None,
45            end: None,
46            limit: 100,
47            order: SortOrder::Desc,
48            cursor: None,
49        }
50    }
51}
52
53impl SearchOptions {
54    /// Sets the limit.
55    pub fn limit(mut self, limit: usize) -> Self {
56        self.limit = limit;
57        self
58    }
59    /// Sets the time range.
60    pub fn range(mut self, start: Option<SystemTime>, end: Option<SystemTime>) -> Self {
61        self.start = start;
62        self.end = end;
63        self
64    }
65    /// Sets the order.
66    pub fn order(mut self, order: SortOrder) -> Self {
67        self.order = order;
68        self
69    }
70    /// Sets the cursor.
71    pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
72        self.cursor = Some(cursor.into());
73        self
74    }
75}
76
77/// One page of search results (SPEC §4 `LogSearchResult`).
78#[derive(Debug, Clone, Default, PartialEq, Serialize)]
79#[serde(rename_all = "camelCase")]
80pub struct LogSearchResult {
81    /// Matching records.
82    pub records: Vec<LogRecord>,
83    /// Cursor for the next page.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub next_cursor: Option<String>,
86    /// Total matches when the service reports it.
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub total: Option<u64>,
89}
90
91/// Callback receiving tailed records.
92pub type RecordCallback = Arc<dyn Fn(LogRecord) + Send + Sync>;
93
94/// Filter for [`WaitOptions::predicate`].
95pub type RecordPredicate = Arc<dyn Fn(&LogRecord) -> bool + Send + Sync>;
96
97/// Options for [`LogQueryClient::tail`].
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct TailOptions {
100    /// Poll interval for polling implementations (default 1 s).
101    pub interval: Duration,
102    /// Only records at or after this time (default now).
103    pub start: Option<SystemTime>,
104}
105
106impl Default for TailOptions {
107    fn default() -> Self {
108        TailOptions {
109            interval: TailOptions::DEFAULT_INTERVAL,
110            start: None,
111        }
112    }
113}
114
115impl TailOptions {
116    /// The template default poll interval (1 s).
117    pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(1);
118
119    /// The poll interval, with `service_default` in place of the template default: an
120    /// `interval` equal to [`DEFAULT_INTERVAL`](Self::DEFAULT_INTERVAL) (or zero) counts as
121    /// unset. For services whose API needs a different polling pace.
122    pub fn interval_or(&self, service_default: Duration) -> Duration {
123        if self.interval.is_zero() || self.interval == Self::DEFAULT_INTERVAL {
124            service_default
125        } else {
126            self.interval
127        }
128    }
129}
130
131/// Stops a running tail; `stop` is idempotent and dropping the handle does **not** stop it.
132#[derive(Clone)]
133pub struct TailHandle {
134    stopped: Arc<AtomicBool>,
135    notify: Arc<Notify>,
136}
137
138impl fmt::Debug for TailHandle {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        f.debug_struct("TailHandle")
141            .field("stopped", &self.is_stopped())
142            .finish()
143    }
144}
145
146impl Default for TailHandle {
147    fn default() -> Self {
148        Self::new()
149    }
150}
151
152impl TailHandle {
153    /// A fresh, running handle (for service implementations).
154    pub fn new() -> Self {
155        TailHandle {
156            stopped: Arc::new(AtomicBool::new(false)),
157            notify: Arc::new(Notify::new()),
158        }
159    }
160
161    /// Stops the tail.
162    pub fn stop(&self) {
163        self.stopped.store(true, Ordering::SeqCst);
164        self.notify.notify_waiters();
165    }
166
167    /// Whether `stop` was called.
168    pub fn is_stopped(&self) -> bool {
169        self.stopped.load(Ordering::SeqCst)
170    }
171
172    /// Resolves once `stop` was called (for service implementations).
173    pub async fn stopped(&self) {
174        loop {
175            let notified = self.notify.notified();
176            tokio::pin!(notified);
177            notified.as_mut().enable();
178            if self.is_stopped() {
179                return;
180            }
181            notified.await;
182        }
183    }
184}
185
186/// Options for [`wait_for_log`].
187#[derive(Clone)]
188pub struct WaitOptions {
189    /// Give up after this long (default 30 s) with `TIMEOUT`.
190    pub timeout: Duration,
191    /// Delay between searches (default 1 s).
192    pub interval: Duration,
193    /// Extra filter on candidate records.
194    pub predicate: Option<RecordPredicate>,
195}
196
197impl Default for WaitOptions {
198    fn default() -> Self {
199        WaitOptions {
200            timeout: Duration::from_secs(30),
201            interval: Duration::from_secs(1),
202            predicate: None,
203        }
204    }
205}
206
207impl fmt::Debug for WaitOptions {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        f.debug_struct("WaitOptions")
210            .field("timeout", &self.timeout)
211            .field("interval", &self.interval)
212            .field("predicate", &self.predicate.is_some())
213            .finish()
214    }
215}
216
217impl WaitOptions {
218    /// Sets the timeout.
219    pub fn timeout(mut self, d: Duration) -> Self {
220        self.timeout = d;
221        self
222    }
223    /// Sets the interval.
224    pub fn interval(mut self, d: Duration) -> Self {
225        self.interval = d;
226        self
227    }
228    /// Sets the predicate.
229    pub fn predicate(mut self, f: impl Fn(&LogRecord) -> bool + Send + Sync + 'static) -> Self {
230        self.predicate = Some(Arc::new(f));
231        self
232    }
233}
234
235/// Queries a logging service (SPEC §4). Methods a service cannot serve return `UNSUPPORTED`.
236#[async_trait]
237pub trait LogQueryClient: Send + Sync {
238    /// Searches with the service's query language.
239    async fn search(&self, query: &str, opts: SearchOptions) -> Result<LogSearchResult>;
240
241    /// Streams matching records to `on_record` until the handle is stopped.
242    async fn tail(
243        &self,
244        query: &str,
245        on_record: RecordCallback,
246        opts: TailOptions,
247    ) -> Result<TailHandle> {
248        let _ = (query, on_record, opts);
249        Err(Error::unsupported(
250            "logs.tail: not supported by this service",
251        ))
252    }
253
254    /// Streams / indexes known to the service.
255    async fn list_streams(&self) -> Result<Vec<String>> {
256        Err(Error::unsupported(
257            "logs.listStreams: not supported by this service",
258        ))
259    }
260
261    /// Labels / fields known to the service.
262    async fn list_labels(&self) -> Result<Vec<String>> {
263        Err(Error::unsupported(
264            "logs.listLabels: not supported by this service",
265        ))
266    }
267
268    /// Polls [`search`](Self::search) until a record matches; see [`wait_for_log`].
269    async fn wait_for_log(&self, query: &str, opts: WaitOptions) -> Result<LogRecord> {
270        wait_for_log(self, query, opts).await
271    }
272}
273
274/// Polls `client.search(query)` until a record matches `opts.predicate` (or any record).
275pub async fn wait_for_log<C>(client: &C, query: &str, opts: WaitOptions) -> Result<LogRecord>
276where
277    C: LogQueryClient + ?Sized,
278{
279    let predicate = opts.predicate.clone();
280    let poll = PollOptions {
281        timeout: opts.timeout,
282        interval: opts.interval,
283    };
284    poll_until("logs.waitForLog", poll, || async {
285        let page = client.search(query, SearchOptions::default()).await?;
286        Ok(page
287            .records
288            .into_iter()
289            .find(|r| predicate.as_ref().is_none_or(|p| p(r))))
290    })
291    .await
292}
293
294/// Generic `tail` on top of `search`: polls oldest-first from `opts.start` (default now) and
295/// delivers each record once (by timestamp). Services without streaming can return this.
296pub fn poll_tail(
297    client: Arc<dyn LogQueryClient>,
298    query: &str,
299    on_record: RecordCallback,
300    opts: TailOptions,
301) -> TailHandle {
302    let handle = TailHandle::new();
303    let h = handle.clone();
304    let query = query.to_string();
305    tokio::spawn(async move {
306        let mut since = opts.start.unwrap_or_else(SystemTime::now);
307        let mut seen_at_since: Vec<String> = Vec::new();
308        while !h.is_stopped() {
309            let search = SearchOptions::default()
310                .range(Some(since), None)
311                .order(SortOrder::Asc)
312                .limit(1000);
313            let page = tokio::select! {
314                _ = h.stopped() => break,
315                page = client.search(&query, search) => page,
316            };
317            if let Ok(page) = page {
318                for r in page.records {
319                    if h.is_stopped() {
320                        break;
321                    }
322                    let key = r.to_json();
323                    if r.timestamp < since || (r.timestamp == since && seen_at_since.contains(&key))
324                    {
325                        continue;
326                    }
327                    if r.timestamp > since {
328                        since = r.timestamp;
329                        seen_at_since.clear();
330                    }
331                    seen_at_since.push(key);
332                    on_record(r);
333                }
334            }
335            tokio::select! {
336                _ = h.stopped() => break,
337                _ = tokio::time::sleep(opts.interval) => {}
338            }
339        }
340    });
341    handle
342}