Skip to main content

adk_kernel/stores/
agenda_neo4j.rs

1//! The Neo4j [`AgendaStore`] (spec 3.2 §7.1, §7.5, §13 Q8, feature `neo4j`).
2
3use async_trait::async_trait;
4use neo4rs::{Graph, Query, Row, query};
5
6use super::neo4j::{
7    column, connect, count, detached, json, limit_clause, order_key, retry, rows, run_schema,
8    txn_rows, where_clause,
9};
10use crate::agenda::{AgendaFilter, AgendaItem, AgendaStateKind, AgendaStore};
11use crate::error::Result;
12
13const PUT: &str = "\
14MERGE (a:AdkKernelAgendaItem {id: $id}) \
15SET a = {id: $id, order_key: $order_key, partition: $partition, state: $state, \
16    created_us: $created_us, item: $item}";
17
18/// Takes the item's write lock inside a transaction: Cypher locks a node before reading a
19/// property a `SET` updates from its own value.
20const LOCK: &str = "\
21MATCH (a:AdkKernelAgendaItem {id: $id}) SET a.lock_seq = coalesce(a.lock_seq, 0) + 1 \
22RETURN count(a) AS locked";
23
24const STATE: &str = "MATCH (a:AdkKernelAgendaItem {id: $id}) RETURN a.state AS state";
25
26const WRITE: &str = "\
27MATCH (a:AdkKernelAgendaItem {id: $id}) \
28SET a.partition = $partition, a.state = $state, a.created_us = $created_us, a.item = $item";
29
30/// An [`AgendaStore`] in Neo4j, shared by every replica (spec 3.2 §7.1, §7.5, §13 Q8,
31/// feature `neo4j`).
32///
33/// One `AdkKernelAgendaItem` node per item, unique by `id`: `partition`, `state` (its kind)
34/// and `created_us` (microseconds since the Unix epoch), the properties `list` filters and
35/// sorts on, `order_key` (the hex of the id, so ties order by the id's UTF-8 bytes whatever
36/// the database's collation), and `item`, the item as JSON text. `transition` write-locks
37/// the node inside a transaction before it reads the state, so of two replicas moving one
38/// item from the same state the second sees the first's write and moves nothing. Every call
39/// runs on a task of its own, as the [process store](crate::Neo4jProcessStore) explains.
40///
41/// # Example
42///
43/// ```rust,no_run
44/// # async fn example() -> adk_kernel::Result<()> {
45/// let store =
46///     adk_kernel::Neo4jAgendaStore::connect("bolt://localhost:7687", "neo4j", "password").await?;
47/// store.migrate().await?;
48/// # Ok(())
49/// # }
50/// ```
51#[derive(Clone)]
52pub struct Neo4jAgendaStore {
53    graph: Graph,
54}
55
56impl std::fmt::Debug for Neo4jAgendaStore {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("Neo4jAgendaStore").finish_non_exhaustive()
59    }
60}
61
62impl Neo4jAgendaStore {
63    /// A store over `graph`, such as the process store's.
64    pub fn from_graph(graph: Graph) -> Self {
65        Self { graph }
66    }
67
68    /// Connects to the server at `uri`.
69    ///
70    /// # Errors
71    ///
72    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the server cannot be
73    /// reached.
74    pub async fn connect(uri: &str, user: &str, password: &str) -> Result<Self> {
75        Ok(Self::from_graph(connect(uri, user, password).await?))
76    }
77
78    /// The connection the store uses.
79    pub fn graph(&self) -> &Graph {
80        &self.graph
81    }
82
83    /// Creates the constraint and indexes the store relies on; one that exists is kept.
84    ///
85    /// # Errors
86    ///
87    /// Returns [`KernelError::Store`](crate::KernelError::Store) when a schema statement
88    /// fails.
89    pub async fn migrate(&self) -> Result<()> {
90        let graph = self.graph.clone();
91        detached(async move {
92            run_schema(
93                &graph,
94                &[
95                    "CREATE CONSTRAINT adk_kernel_agenda_id IF NOT EXISTS \
96                     FOR (a:AdkKernelAgendaItem) REQUIRE a.id IS UNIQUE",
97                    "CREATE INDEX adk_kernel_agenda_partition IF NOT EXISTS \
98                     FOR (a:AdkKernelAgendaItem) ON (a.partition)",
99                    "CREATE INDEX adk_kernel_agenda_state IF NOT EXISTS \
100                     FOR (a:AdkKernelAgendaItem) ON (a.state)",
101                    "CREATE INDEX adk_kernel_agenda_created IF NOT EXISTS \
102                     FOR (a:AdkKernelAgendaItem) ON (a.created_us)",
103                ],
104            )
105            .await
106        })
107        .await
108    }
109}
110
111/// `statement` with the item's stored properties bound.
112fn bind(statement: Query, item: &AgendaItem) -> Result<Query> {
113    Ok(statement
114        .param("id", item.id.as_str())
115        .param("partition", item.partition.as_str())
116        .param("state", item.state.kind().as_str())
117        .param("created_us", item.created_at.timestamp_micros())
118        .param("item", serde_json::to_string(item)?))
119}
120
121/// Reads a row back into its item, or `None` for a node a concurrent `delete` removed after
122/// the statement matched it, whose properties then read as null.
123fn decode(row: &Row) -> Result<Option<AgendaItem>> {
124    column::<Option<String>>(row, "item")?.map(|item| json("agenda item", &item)).transpose()
125}
126
127/// Writes `write` over the item `id` when its state is `from`, in one transaction that
128/// write-locks the node first.
129async fn transition_once(
130    graph: &Graph,
131    id: &str,
132    from: &str,
133    write: Query,
134) -> std::result::Result<bool, neo4rs::Error> {
135    let mut txn = graph.start_txn().await?;
136    txn.run(query(LOCK).param("id", id)).await?;
137    let state = txn_rows(&mut txn, query(STATE).param("id", id))
138        .await?
139        .first()
140        .and_then(|row| row.get::<Option<String>>("state").ok().flatten());
141    if state.as_deref() != Some(from) {
142        txn.rollback().await?;
143        return Ok(false);
144    }
145    txn.run(write).await?;
146    txn.commit().await?;
147    Ok(true)
148}
149
150#[async_trait]
151impl AgendaStore for Neo4jAgendaStore {
152    async fn put(&self, item: AgendaItem) -> Result<()> {
153        let statement = bind(query(PUT), &item)?.param("order_key", order_key(&item.id));
154        let graph = self.graph.clone();
155        detached(async move {
156            rows(&graph, statement, "write the agenda").await?;
157            Ok(())
158        })
159        .await
160    }
161
162    async fn get(&self, id: &str) -> Result<Option<AgendaItem>> {
163        let statement =
164            query("MATCH (a:AdkKernelAgendaItem {id: $id}) RETURN a.item AS item").param("id", id);
165        let graph = self.graph.clone();
166        detached(async move {
167            Ok(match rows(&graph, statement, "read the agenda").await?.first() {
168                Some(row) => decode(row)?,
169                None => None,
170            })
171        })
172        .await
173    }
174
175    async fn list(&self, filter: &AgendaFilter) -> Result<Vec<AgendaItem>> {
176        let mut conditions = Vec::new();
177        if filter.partition.is_some() {
178            conditions.push("a.partition = $partition");
179        }
180        if !filter.states.is_empty() {
181            conditions.push("a.state IN $states");
182        }
183        let states: Vec<String> =
184            filter.states.iter().map(|state| state.as_str().to_string()).collect();
185        let (limit, limit_value) = limit_clause(filter.limit);
186        let statement = query(&format!(
187            "MATCH (a:AdkKernelAgendaItem){} RETURN a.item AS item \
188             ORDER BY a.created_us, a.order_key{limit}",
189            where_clause(&conditions)
190        ))
191        .param("partition", filter.partition.as_ref().map(|partition| partition.as_str()))
192        .param("states", states)
193        .param("limit", limit_value);
194        let graph = self.graph.clone();
195        detached(async move {
196            let rows = rows(&graph, statement, "list the agenda").await?;
197            rows.iter().filter_map(|row| decode(row).transpose()).collect()
198        })
199        .await
200    }
201
202    async fn transition(&self, item: AgendaItem, from: AgendaStateKind) -> Result<bool> {
203        let write = bind(query(WRITE), &item)?;
204        let (graph, id) = (self.graph.clone(), item.id.clone());
205        detached(async move {
206            retry("update the agenda", || {
207                transition_once(&graph, &id, from.as_str(), write.clone())
208            })
209            .await
210        })
211        .await
212    }
213
214    async fn delete(&self, id: &str) -> Result<bool> {
215        let statement =
216            query("MATCH (a:AdkKernelAgendaItem {id: $id}) DELETE a RETURN count(*) AS deleted")
217                .param("id", id);
218        let graph = self.graph.clone();
219        detached(async move {
220            Ok(count(&rows(&graph, statement, "delete from the agenda").await?, "deleted")? > 0)
221        })
222        .await
223    }
224}