Skip to main content

schedr_db/
named_events.rs

1//! Events posted through the API (decision 354): `POST /api/v1/events`. Each post is an event of
2//! its own, a repeat of a name and key too; a trigger starts a run per key it hasn't seen, and a
3//! step waiting in a run matches one posted since its run started.
4
5use jiff::{SignedDuration, Timestamp};
6use uuid::Uuid;
7
8use crate::database::{Database, DbError};
9use crate::query::{db_time, from_json, in_tx, on_pool, parse_time, sql, sql_text, to_json};
10
11/// An event to post.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct NewNamedEvent<'a> {
14    /// Its name.
15    pub name: &'a str,
16    /// Its key.
17    pub key: &'a str,
18    /// Its data, as JSON.
19    pub data: &'a serde_json::Value,
20    /// When it happened; a run it starts is planned for it.
21    pub at: Timestamp,
22}
23
24/// An event as stored.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct NamedEvent {
27    /// Its ID.
28    pub id: String,
29    /// Its name.
30    pub name: String,
31    /// Its key.
32    pub key: String,
33    /// Its data.
34    pub data: serde_json::Value,
35    /// When it happened.
36    pub at: Timestamp,
37    /// When it was posted.
38    pub posted_at: Timestamp,
39    /// Who posted it.
40    pub posted_by: String,
41}
42
43/// What a post did.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum Posted {
46    /// Stored, under this ID.
47    New(String),
48    /// Sent again with its `Idempotency-Key`: the event it stored then.
49    Again(String),
50    /// The key was used for another event.
51    KeyTaken,
52}
53
54/// The columns read, in [`row`]'s order.
55const COLUMNS: &str =
56    "id{text}, name, key, data{text}, {ts<}at{>ts}, {ts<}posted_at{>ts}, posted_by";
57
58type Row = (String, String, String, String, String, String, String);
59
60fn row((id, name, key, data, at, posted_at, posted_by): Row) -> Result<NamedEvent, DbError> {
61    Ok(NamedEvent {
62        id,
63        name,
64        key,
65        data: from_json("named_events.data", &data)?,
66        at: parse_time("named_events.at", &at)?,
67        posted_at: parse_time("named_events.posted_at", &posted_at)?,
68        posted_by,
69    })
70}
71
72impl Database {
73    /// Posts `event` for `posted_by` at `now`, once per `request_key` (the client's
74    /// `Idempotency-Key`): sent again after its answer was lost, it finds the event it stored, as
75    /// long as the same person sends the same event.
76    ///
77    /// # Errors
78    ///
79    /// [`DbError`] if a statement fails or the stored event doesn't read.
80    pub async fn post_named_event(
81        &self,
82        event: &NewNamedEvent<'_>,
83        posted_by: &str,
84        request_key: Option<&str>,
85        now: Timestamp,
86    ) -> Result<Posted, DbError> {
87        const INSERT: &str = "INSERT INTO named_events \
88            (id, name, key, data, at, posted_at, posted_by, request_key) \
89            VALUES ($1{uuid}, $2, $3, $4{json}, $5{ts}, $6{ts}, $7, $8) \
90            ON CONFLICT (posted_by, request_key) WHERE request_key IS NOT NULL DO NOTHING";
91        const BY_KEY: &str = "SELECT id{text}, name, key, data{text} FROM named_events \
92            WHERE posted_by = $1 AND request_key = $2";
93        // Its listeners looked at by the master's trigger loop (decision 486): their stored
94        // next time cleared, once until the loop has looked (a burst writes each row once).
95        const LISTENERS: &str = "UPDATE dag_triggers SET next_fire_at = NULL \
96            WHERE event_name = $1 AND next_fire_at IS NOT NULL";
97        // And the `wait_for` steps waiting for it (decision 487): looked at by the next round.
98        const WAITERS: &str = "UPDATE task_instances SET look_at = NULL \
99            WHERE waits_event = $1 AND look_at IS NOT NULL";
100        let id = Uuid::now_v7().to_string();
101        let data = to_json(event.data);
102        // What it woke (decision 486): its triggers' listeners, its waiting steps.
103        let mut woke = (false, false);
104        let earlier: Option<(String, String, String, String)> = in_tx!(self, |tx, backend| {
105            let inserted = sqlx::query(sql(backend, INSERT))
106                .bind(&id)
107                .bind(event.name)
108                .bind(event.key)
109                .bind(&data)
110                .bind(db_time(event.at))
111                .bind(db_time(now))
112                .bind(posted_by)
113                .bind(request_key)
114                .execute(&mut *tx)
115                .await?
116                .rows_affected();
117            if inserted == 1 {
118                let listeners = sqlx::query(sql(backend, LISTENERS))
119                    .bind(event.name)
120                    .execute(&mut *tx)
121                    .await?
122                    .rows_affected();
123                let waiters = sqlx::query(sql(backend, WAITERS))
124                    .bind(event.name)
125                    .execute(&mut *tx)
126                    .await?
127                    .rows_affected();
128                woke = (listeners > 0, waiters > 0);
129                None
130            } else {
131                Some(
132                    sqlx::query_as(sql(backend, BY_KEY))
133                        .bind(posted_by)
134                        .bind(request_key)
135                        .fetch_one(&mut *tx)
136                        .await?,
137                )
138            }
139        });
140        let Some((earlier, name, key, stored)) = earlier else {
141            // The waiting steps are the round's: told at once in this process (a standalone);
142            // the master elsewhere by the notification, which says what to look at. Nobody
143            // waiting, nothing sent.
144            if woke.1 {
145                self.waits_woken();
146            }
147            let payload = match woke {
148                (true, true) => Some("tw"),
149                (true, false) => Some("t"),
150                (false, true) => Some("w"),
151                (false, false) => None,
152            };
153            if let Some(payload) = payload {
154                self.notify(crate::commands::EVENTS_CHANNEL, payload).await;
155            }
156            return Ok(Posted::New(id));
157        };
158        let stored: serde_json::Value = from_json("named_events.data", &stored)?;
159        Ok(
160            if name == event.name && key == event.key && &stored == event.data {
161                Posted::Again(earlier)
162            } else {
163                Posted::KeyTaken
164            },
165        )
166    }
167
168    /// The events named `name` posted from `since` on whose key `dag_id`'s events don't have,
169    /// oldest first, at most `limit`: what an `EventNamed` trigger starts runs for (decision 354).
170    /// Read by the keys a DAG has, not strictly after the last one seen, so one stored late
171    /// (its time taken before its commit) is still found; `since` bounds the look back.
172    ///
173    /// # Errors
174    ///
175    /// [`DbError`] if the query fails or a row doesn't read.
176    pub async fn named_events_unseen(
177        &self,
178        name: &str,
179        dag_id: &str,
180        since: Timestamp,
181        limit: u32,
182    ) -> Result<Vec<NamedEvent>, DbError> {
183        let query = format!(
184            "SELECT {COLUMNS} FROM named_events n WHERE n.name = $1 AND n.posted_at >= $2{{ts}} \
185             AND NOT EXISTS (SELECT 1 FROM events e WHERE e.dag_id = $3 AND e.key = n.key) \
186             ORDER BY n.posted_at, n.id LIMIT $4"
187        );
188        let rows: Vec<Row> = on_pool!(self, |pool, backend| {
189            sqlx::query_as(sql_text(backend, &query))
190                .bind(name)
191                .bind(db_time(since))
192                .bind(dag_id)
193                .bind(i64::from(limit))
194                .fetch_all(pool)
195                .await?
196        });
197        rows.into_iter().map(row).collect()
198    }
199
200    /// The first event named `name` posted from `since` on that `dag_id`'s `@trigger(wait_for=
201    /// EventNamed(...))` hasn't passed (decision 354): read by what it passed, not strictly after
202    /// the last one, so one stored late is still called for, once.
203    ///
204    /// # Errors
205    ///
206    /// [`DbError`] if the query fails or the row doesn't read.
207    pub async fn named_event_unpassed(
208        &self,
209        name: &str,
210        dag_id: &str,
211        since: Timestamp,
212    ) -> Result<Option<NamedEvent>, DbError> {
213        let query = format!(
214            "SELECT {COLUMNS} FROM named_events n WHERE n.name = $1 AND n.posted_at >= $2{{ts}} \
215             AND NOT EXISTS (SELECT 1 FROM trigger_progress_passed p WHERE p.dag_id = $3 \
216             AND p.item = n.id{{text}}) ORDER BY n.posted_at, n.id LIMIT 1"
217        );
218        let found: Option<Row> = on_pool!(self, |pool, backend| {
219            sqlx::query_as(sql_text(backend, &query))
220                .bind(name)
221                .bind(db_time(since))
222                .bind(dag_id)
223                .fetch_optional(pool)
224                .await?
225        });
226        found.map(row).transpose()
227    }
228
229    /// Forgets what `dag_id`'s trigger passed of the events named `name` posted before `before`:
230    /// read back only from a lookback behind its last (B186). Gives how many.
231    ///
232    /// # Errors
233    ///
234    /// [`DbError::Sqlx`] if the statement fails.
235    pub async fn forget_passed_before(
236        &self,
237        dag_id: &str,
238        name: &str,
239        before: Timestamp,
240    ) -> Result<u64, DbError> {
241        // Its own few rows, each looked up by ID, not the name's whole history (Codex's review).
242        const FORGET: &str = "DELETE FROM trigger_progress_passed WHERE dag_id = $1 AND EXISTS \
243            (SELECT 1 FROM named_events e WHERE e.id = trigger_progress_passed.item{uuid} \
244            AND e.name = $2 AND e.posted_at < $3{ts})";
245        // Never read below again, however the lookback changes (Grok's review).
246        const FLOOR: &str = "UPDATE trigger_progress SET passed_floor = $2{ts} WHERE dag_id = $1 \
247            AND (passed_floor IS NULL OR passed_floor < $2{ts})";
248        let forgotten = in_tx!(self, |tx, backend| {
249            sqlx::query(sql(backend, FLOOR))
250                .bind(dag_id)
251                .bind(db_time(before))
252                .execute(&mut *tx)
253                .await?;
254            sqlx::query(sql(backend, FORGET))
255                .bind(dag_id)
256                .bind(name)
257                .bind(db_time(before))
258                .execute(&mut *tx)
259                .await?
260                .rows_affected()
261        });
262        Ok(forgotten)
263    }
264
265    /// Below what `dag_id`'s trigger no longer reads events: what it passed there is forgotten.
266    ///
267    /// # Errors
268    ///
269    /// [`DbError`] if the query fails or the time doesn't read.
270    pub async fn passed_floor(&self, dag_id: &str) -> Result<Option<Timestamp>, DbError> {
271        const FLOOR: &str = "SELECT {ts<}passed_floor{>ts} FROM trigger_progress WHERE dag_id = $1";
272        let floor: Option<Option<String>> = on_pool!(self, |pool, backend| {
273            sqlx::query_scalar(sql(backend, FLOOR))
274                .bind(dag_id)
275                .fetch_optional(pool)
276                .await?
277        });
278        floor
279            .flatten()
280            .map(|at| parse_time("trigger_progress.passed_floor", &at))
281            .transpose()
282    }
283
284    /// The first event named `name` with `key` (any, if `None`) posted from `since` on, and
285    /// strictly after `after` (a `(posted_at, id)` cursor: one a sensor's function said
286    /// `NOT_YET` to) when given: what a step waiting in a run started at `since` gets (decision
287    /// 354: one posted before the step began waiting, but after its run started, counts).
288    ///
289    /// # Errors
290    ///
291    /// [`DbError`] if the query fails or the row doesn't read.
292    pub async fn first_named_event(
293        &self,
294        name: &str,
295        key: Option<&str>,
296        since: Timestamp,
297        after: Option<(Timestamp, &str)>,
298    ) -> Result<Option<NamedEvent>, DbError> {
299        let query = format!(
300            "SELECT {COLUMNS} FROM named_events WHERE name = $1 AND ($2 IS NULL OR key = $2) \
301             AND posted_at >= $3{{ts}} AND ($4{{ts}} IS NULL OR posted_at > $4{{ts}} \
302             OR (posted_at = $4{{ts}} AND id > $5{{uuid}})) ORDER BY posted_at, id LIMIT 1"
303        );
304        let (after_at, after_id) = after.map_or((None, None), |(at, id)| (Some(at), Some(id)));
305        let found: Option<Row> = on_pool!(self, |pool, backend| {
306            sqlx::query_as(sql_text(backend, &query))
307                .bind(name)
308                .bind(key)
309                .bind(db_time(since))
310                .bind(after_at.map(db_time))
311                .bind(after_id)
312                .fetch_optional(pool)
313                .await?
314        });
315        found.map(row).transpose()
316    }
317
318    /// The first event of `name` (and `key`) posted since `since` that the sensor of
319    /// `instance_id` wasn't handed and said `NOT_YET` to, posted no earlier than `back` before
320    /// its cursor `after` (B185): one committed late, its time taken before its commit, sits
321    /// behind the cursor, and is found still within that lookback.
322    ///
323    /// # Errors
324    ///
325    /// [`DbError`] if the query fails or the row doesn't read.
326    pub async fn next_named_event_for(
327        &self,
328        (name, key): (&str, Option<&str>),
329        since: Timestamp,
330        after: Timestamp,
331        (back, instance_id): (SignedDuration, &str),
332    ) -> Result<Option<NamedEvent>, DbError> {
333        let query = format!(
334            "SELECT {COLUMNS} FROM named_events WHERE name = $1 AND ($2 IS NULL OR key = $2) \
335             AND posted_at >= $3{{ts}} AND posted_at >= $4{{ts}} AND NOT EXISTS \
336             (SELECT 1 FROM sensor_passed p WHERE p.instance_id = $5{{uuid}} \
337             AND p.item = named_events.id) ORDER BY posted_at, id LIMIT 1"
338        );
339        let from = after.checked_sub(back).unwrap_or(Timestamp::MIN);
340        let found: Option<Row> = on_pool!(self, |pool, backend| {
341            sqlx::query_as(sql_text(backend, &query))
342                .bind(name)
343                .bind(key)
344                .bind(db_time(since))
345                .bind(db_time(from))
346                .bind(instance_id)
347                .fetch_optional(pool)
348                .await?
349        });
350        found.map(row).transpose()
351    }
352
353    /// One event, by its ID.
354    ///
355    /// # Errors
356    ///
357    /// [`DbError`] if the query fails or the row doesn't read.
358    pub async fn named_events_by_id(&self, id: &str) -> Result<Option<NamedEvent>, DbError> {
359        let query = format!("SELECT {COLUMNS} FROM named_events WHERE id = $1{{uuid}}");
360        let found: Option<Row> = on_pool!(self, |pool, backend| {
361            sqlx::query_as(sql_text(backend, &query))
362                .bind(id)
363                .fetch_optional(pool)
364                .await?
365        });
366        found.map(row).transpose()
367    }
368
369    /// The newest events, of `name` if given, at most `limit`.
370    ///
371    /// # Errors
372    ///
373    /// [`DbError`] if the query fails or a row doesn't read.
374    pub async fn named_events(
375        &self,
376        name: Option<&str>,
377        limit: u32,
378    ) -> Result<Vec<NamedEvent>, DbError> {
379        let query = format!(
380            "SELECT {COLUMNS} FROM named_events WHERE ($1 IS NULL OR name = $1) \
381             ORDER BY posted_at DESC, id DESC LIMIT $2"
382        );
383        let rows: Vec<Row> = on_pool!(self, |pool, backend| {
384            sqlx::query_as(sql_text(backend, &query))
385                .bind(name)
386                .bind(i64::from(limit))
387                .fetch_all(pool)
388                .await?
389        });
390        rows.into_iter().map(row).collect()
391    }
392}
393
394#[cfg(test)]
395mod tests;