Skip to main content

adk_kernel/stores/
watermark_neo4j.rs

1//! The Neo4j [`CronWatermarkStore`] (spec 3.2 §7.4, §13 Q8, feature `neo4j`).
2
3use async_trait::async_trait;
4use chrono::{DateTime, Utc};
5use neo4rs::{Graph, query};
6
7use super::neo4j::{column, connect, count, detached, rows, run_schema, store_error};
8use crate::error::Result;
9use crate::watermark::CronWatermarkStore;
10
11/// Keeps the later cursor in one statement. The `SET` reads the property it updates, so
12/// Cypher write-locks the node before reading it, and concurrent advances apply one at a
13/// time.
14const ADVANCE: &str = "\
15MERGE (w:AdkKernelCronWatermark {source: $source}) \
16ON CREATE SET w.cursor_us = $cursor_us \
17SET w.cursor_us = CASE WHEN w.cursor_us < $cursor_us THEN $cursor_us ELSE w.cursor_us END \
18RETURN w.cursor_us AS cursor_us";
19
20/// A [`CronWatermarkStore`] in Neo4j, shared by every replica (spec 3.2 §7.4, §13 Q8,
21/// feature `neo4j`).
22///
23/// | Label | Key (unique) | Properties |
24/// |-------|--------------|------------|
25/// | `AdkKernelCronWatermark` | `source` | `cursor_us`, the cursor in microseconds since the Unix epoch |
26///
27/// An advance is one `MERGE` whose `SET` keeps the later of the stored cursor and the one
28/// given, under the write lock Cypher takes on a property updated from its own value, so
29/// replicas writing in any order never move a cursor back. Every call runs on a task of
30/// its own, as the [process store](crate::Neo4jProcessStore) explains. Call
31/// [`migrate`](Self::migrate) once per database to create the uniqueness constraint.
32///
33/// # Example
34///
35/// ```rust,no_run
36/// # async fn example() -> adk_kernel::Result<()> {
37/// let store =
38///     adk_kernel::Neo4jCronWatermarkStore::connect("bolt://localhost:7687", "neo4j", "password")
39///         .await?;
40/// store.migrate().await?;
41/// # Ok(())
42/// # }
43/// ```
44#[derive(Clone)]
45pub struct Neo4jCronWatermarkStore {
46    graph: Graph,
47}
48
49impl std::fmt::Debug for Neo4jCronWatermarkStore {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        f.debug_struct("Neo4jCronWatermarkStore").finish_non_exhaustive()
52    }
53}
54
55impl Neo4jCronWatermarkStore {
56    /// A store over `graph`, such as the process store's.
57    pub fn from_graph(graph: Graph) -> Self {
58        Self { graph }
59    }
60
61    /// Connects to the server at `uri`.
62    ///
63    /// # Errors
64    ///
65    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the server cannot be
66    /// reached.
67    pub async fn connect(uri: &str, user: &str, password: &str) -> Result<Self> {
68        Ok(Self::from_graph(connect(uri, user, password).await?))
69    }
70
71    /// The connection the store uses.
72    pub fn graph(&self) -> &Graph {
73        &self.graph
74    }
75
76    /// Creates the uniqueness constraint on the source's name; one that exists is kept.
77    ///
78    /// # Errors
79    ///
80    /// Returns [`KernelError::Store`](crate::KernelError::Store) when a schema statement
81    /// fails.
82    pub async fn migrate(&self) -> Result<()> {
83        let graph = self.graph.clone();
84        detached(async move {
85            run_schema(
86                &graph,
87                &["CREATE CONSTRAINT adk_kernel_cron_watermark_source IF NOT EXISTS \
88                   FOR (w:AdkKernelCronWatermark) REQUIRE w.source IS UNIQUE"],
89            )
90            .await
91        })
92        .await
93    }
94}
95
96/// The instant `micros` microseconds after the Unix epoch.
97fn instant(micros: i64) -> Result<DateTime<Utc>> {
98    DateTime::from_timestamp_micros(micros).ok_or_else(|| {
99        store_error("read a cron watermark", &format!("the cursor {micros} is out of range"))
100    })
101}
102
103#[async_trait]
104impl CronWatermarkStore for Neo4jCronWatermarkStore {
105    async fn read(&self, source: &str) -> Result<Option<DateTime<Utc>>> {
106        let statement = query(
107            "MATCH (w:AdkKernelCronWatermark {source: $source}) RETURN w.cursor_us AS cursor_us",
108        )
109        .param("source", source);
110        let graph = self.graph.clone();
111        detached(async move {
112            let rows = rows(&graph, statement, "read a cron watermark").await?;
113            // A node a concurrent delete removed after the match reads as null: no cursor.
114            match rows.first() {
115                Some(row) => column::<Option<i64>>(row, "cursor_us")?.map(instant).transpose(),
116                None => Ok(None),
117            }
118        })
119        .await
120    }
121
122    async fn advance(&self, source: &str, cursor: DateTime<Utc>) -> Result<DateTime<Utc>> {
123        let statement =
124            query(ADVANCE).param("source", source).param("cursor_us", cursor.timestamp_micros());
125        let graph = self.graph.clone();
126        detached(async move {
127            let rows = rows(&graph, statement, "advance a cron watermark").await?;
128            let stored = match rows.first() {
129                Some(row) => column::<Option<i64>>(row, "cursor_us")?,
130                None => None,
131            };
132            stored.map(instant).transpose()?.ok_or_else(|| {
133                store_error("advance a cron watermark", &"the statement returned no cursor")
134            })
135        })
136        .await
137    }
138
139    async fn delete(&self, source: &str) -> Result<bool> {
140        let statement = query(
141            "MATCH (w:AdkKernelCronWatermark {source: $source}) DELETE w \
142             RETURN count(*) AS deleted",
143        )
144        .param("source", source);
145        let graph = self.graph.clone();
146        detached(async move {
147            Ok(count(&rows(&graph, statement, "delete a cron watermark").await?, "deleted")? > 0)
148        })
149        .await
150    }
151}