Skip to main content

adk_kernel/stores/
partition_neo4j.rs

1//! The Neo4j [`PartitionStore`] (spec 3.2 §7.8, §13 Q8, feature `neo4j`).
2
3use async_trait::async_trait;
4use neo4rs::{Graph, Row, query};
5
6use super::neo4j::{
7    column, connect, count, detached, json, limit_clause, order_key, rows, run_schema, where_clause,
8};
9use crate::error::Result;
10use crate::partition::{CrossingFilter, CrossingRecord, Partition, PartitionId, PartitionStore};
11
12const RECORD_CROSSING: &str = "\
13CREATE (c:AdkKernelCrossing {id: $id, order_key: $order_key, at_us: $at_us, run: $run, \
14    source: $source, target: $target, fingerprint: $fingerprint, outcome: $outcome, record: $record})";
15
16const GRANT: &str = "\
17MERGE (g:AdkKernelCrossingGrant {key: $key}) \
18ON CREATE SET g.run = $run, g.fingerprint = $fingerprint, g.order_key = $order_key";
19
20/// A [`PartitionStore`] in Neo4j, shared by every replica (spec 3.2 §7.1, §7.8, §13 Q8,
21/// feature `neo4j`).
22///
23/// | Label | Key (unique) | Properties |
24/// |-------|--------------|------------|
25/// | `AdkKernelPartition` | `id` | `order_key` (the hex of the id) and `record`, the partition as JSON text |
26/// | `AdkKernelCrossing` | `id` | `order_key` (the hex of the id), `at_us` (microseconds since the Unix epoch), `run`, `source`, `target`, `fingerprint` and `outcome`, the properties `crossings` filters on, and `record`, the crossing as JSON text |
27/// | `AdkKernelCrossingGrant` | `key`: the hex of the run and of the fingerprint, joined by `.` | `run`, `fingerprint` and `order_key` (the hex of the fingerprint) |
28///
29/// Ordering by `order_key` follows the ids' UTF-8 bytes whatever the database's collation,
30/// so partitions order by id, crossings by time, then id, and a run's grants by
31/// fingerprint, as on every backend. A crossing is created once and never changed; a grant
32/// is a `MERGE` on its key, so granting twice keeps one grant. Every call runs on a task of
33/// its own, as the [process store](crate::Neo4jProcessStore) explains.
34///
35/// # Example
36///
37/// ```rust,no_run
38/// # async fn example() -> adk_kernel::Result<()> {
39/// let store =
40///     adk_kernel::Neo4jPartitionStore::connect("bolt://localhost:7687", "neo4j", "password")
41///         .await?;
42/// store.migrate().await?;
43/// # Ok(())
44/// # }
45/// ```
46#[derive(Clone)]
47pub struct Neo4jPartitionStore {
48    graph: Graph,
49}
50
51impl std::fmt::Debug for Neo4jPartitionStore {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        f.debug_struct("Neo4jPartitionStore").finish_non_exhaustive()
54    }
55}
56
57impl Neo4jPartitionStore {
58    /// A store over `graph`, such as the process store's.
59    pub fn from_graph(graph: Graph) -> Self {
60        Self { graph }
61    }
62
63    /// Connects to the server at `uri`.
64    ///
65    /// # Errors
66    ///
67    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the server cannot be
68    /// reached.
69    pub async fn connect(uri: &str, user: &str, password: &str) -> Result<Self> {
70        Ok(Self::from_graph(connect(uri, user, password).await?))
71    }
72
73    /// The connection the store uses.
74    pub fn graph(&self) -> &Graph {
75        &self.graph
76    }
77
78    /// Creates the constraints and indexes the store relies on; one that exists is kept.
79    ///
80    /// # Errors
81    ///
82    /// Returns [`KernelError::Store`](crate::KernelError::Store) when a schema statement
83    /// fails.
84    pub async fn migrate(&self) -> Result<()> {
85        let graph = self.graph.clone();
86        detached(async move {
87            run_schema(
88                &graph,
89                &[
90                    "CREATE CONSTRAINT adk_kernel_partition_id IF NOT EXISTS \
91                     FOR (p:AdkKernelPartition) REQUIRE p.id IS UNIQUE",
92                    "CREATE INDEX adk_kernel_partition_order IF NOT EXISTS \
93                     FOR (p:AdkKernelPartition) ON (p.order_key)",
94                    "CREATE CONSTRAINT adk_kernel_crossing_id IF NOT EXISTS \
95                     FOR (c:AdkKernelCrossing) REQUIRE c.id IS UNIQUE",
96                    "CREATE INDEX adk_kernel_crossing_at IF NOT EXISTS \
97                     FOR (c:AdkKernelCrossing) ON (c.at_us)",
98                    "CREATE INDEX adk_kernel_crossing_run IF NOT EXISTS \
99                     FOR (c:AdkKernelCrossing) ON (c.run)",
100                    "CREATE INDEX adk_kernel_crossing_source IF NOT EXISTS \
101                     FOR (c:AdkKernelCrossing) ON (c.source)",
102                    "CREATE INDEX adk_kernel_crossing_target IF NOT EXISTS \
103                     FOR (c:AdkKernelCrossing) ON (c.target)",
104                    "CREATE CONSTRAINT adk_kernel_crossing_grant_key IF NOT EXISTS \
105                     FOR (g:AdkKernelCrossingGrant) REQUIRE g.key IS UNIQUE",
106                    "CREATE INDEX adk_kernel_crossing_grant_run IF NOT EXISTS \
107                     FOR (g:AdkKernelCrossingGrant) ON (g.run)",
108                ],
109            )
110            .await
111        })
112        .await
113    }
114}
115
116/// Column `name` of `row` as `what`, or `None` for a node a concurrent delete removed after
117/// the statement matched it, whose properties then read as null.
118fn decode<T: serde::de::DeserializeOwned>(row: &Row, name: &str, what: &str) -> Result<Option<T>> {
119    column::<Option<String>>(row, name)?.map(|text| json(what, &text)).transpose()
120}
121
122#[async_trait]
123impl PartitionStore for Neo4jPartitionStore {
124    async fn put(&self, partition: Partition) -> Result<()> {
125        let statement = query(
126            "MERGE (p:AdkKernelPartition {id: $id}) SET p.order_key = $order_key, \
127             p.record = $record",
128        )
129        .param("id", partition.id.as_str())
130        .param("order_key", order_key(partition.id.as_str()))
131        .param("record", serde_json::to_string(&partition)?);
132        let graph = self.graph.clone();
133        detached(async move {
134            rows(&graph, statement, "write the partition table").await?;
135            Ok(())
136        })
137        .await
138    }
139
140    async fn get(&self, id: &PartitionId) -> Result<Option<Partition>> {
141        let statement = query("MATCH (p:AdkKernelPartition {id: $id}) RETURN p.record AS record")
142            .param("id", id.as_str());
143        let graph = self.graph.clone();
144        detached(async move {
145            rows(&graph, statement, "read the partition table")
146                .await?
147                .first()
148                .map_or(Ok(None), |row| decode(row, "record", "partition"))
149        })
150        .await
151    }
152
153    async fn list(&self) -> Result<Vec<Partition>> {
154        let statement =
155            query("MATCH (p:AdkKernelPartition) RETURN p.record AS record ORDER BY p.order_key");
156        let graph = self.graph.clone();
157        detached(async move {
158            rows(&graph, statement, "list the partition table")
159                .await?
160                .iter()
161                .filter_map(|row| decode(row, "record", "partition").transpose())
162                .collect()
163        })
164        .await
165    }
166
167    async fn delete(&self, id: &PartitionId) -> Result<bool> {
168        let statement =
169            query("MATCH (p:AdkKernelPartition {id: $id}) DELETE p RETURN count(*) AS deleted")
170                .param("id", id.as_str());
171        let graph = self.graph.clone();
172        detached(async move {
173            Ok(count(
174                &rows(&graph, statement, "delete from the partition table").await?,
175                "deleted",
176            )? > 0)
177        })
178        .await
179    }
180
181    async fn record_crossing(&self, record: CrossingRecord) -> Result<()> {
182        let statement = query(RECORD_CROSSING)
183            .param("id", record.id.as_str())
184            .param("order_key", order_key(&record.id))
185            .param("at_us", record.at.timestamp_micros())
186            .param("run", record.run.as_str())
187            .param("source", record.from.as_str())
188            .param("target", record.to.as_str())
189            .param("fingerprint", record.fingerprint.as_str())
190            .param("outcome", record.outcome.as_str())
191            .param("record", serde_json::to_string(&record)?);
192        let graph = self.graph.clone();
193        detached(async move {
194            rows(&graph, statement, "record a crossing").await?;
195            Ok(())
196        })
197        .await
198    }
199
200    async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>> {
201        let mut conditions = Vec::new();
202        if filter.from.is_some() {
203            conditions.push("c.source = $source");
204        }
205        if filter.to.is_some() {
206            conditions.push("c.target = $target");
207        }
208        if filter.run.is_some() {
209            conditions.push("c.run = $run");
210        }
211        if filter.fingerprint.is_some() {
212            conditions.push("c.fingerprint = $fingerprint");
213        }
214        if !filter.outcomes.is_empty() {
215            conditions.push("c.outcome IN $outcomes");
216        }
217        if filter.since.is_some() {
218            conditions.push("c.at_us >= $since");
219        }
220        let outcomes: Vec<String> =
221            filter.outcomes.iter().map(|outcome| outcome.as_str().to_string()).collect();
222        let (limit, limit_value) = limit_clause(filter.limit);
223        let statement = query(&format!(
224            "MATCH (c:AdkKernelCrossing){} RETURN c.record AS record \
225             ORDER BY c.at_us, c.order_key{limit}",
226            where_clause(&conditions)
227        ))
228        .param("source", filter.from.as_ref().map(|from| from.as_str()))
229        .param("target", filter.to.as_ref().map(|to| to.as_str()))
230        .param("run", filter.run.clone())
231        .param("fingerprint", filter.fingerprint.clone())
232        .param("outcomes", outcomes)
233        .param("since", filter.since.map(|since| since.timestamp_micros()))
234        .param("limit", limit_value);
235        let graph = self.graph.clone();
236        detached(async move {
237            rows(&graph, statement, "read the crossings")
238                .await?
239                .iter()
240                .filter_map(|row| decode(row, "record", "crossing record").transpose())
241                .collect()
242        })
243        .await
244    }
245
246    async fn grant(&self, run: &str, fingerprint: &str) -> Result<()> {
247        let statement = query(GRANT)
248            .param("key", format!("{}.{}", order_key(run), order_key(fingerprint)))
249            .param("run", run)
250            .param("fingerprint", fingerprint)
251            .param("order_key", order_key(fingerprint));
252        let graph = self.graph.clone();
253        detached(async move {
254            rows(&graph, statement, "record a crossing grant").await?;
255            Ok(())
256        })
257        .await
258    }
259
260    async fn grants(&self, run: &str) -> Result<Vec<String>> {
261        let statement = query(
262            "MATCH (g:AdkKernelCrossingGrant {run: $run}) RETURN g.fingerprint AS fingerprint \
263             ORDER BY g.order_key",
264        )
265        .param("run", run);
266        let graph = self.graph.clone();
267        detached(async move {
268            let rows = rows(&graph, statement, "read the crossing grants").await?;
269            let mut grants = Vec::with_capacity(rows.len());
270            for row in &rows {
271                if let Some(fingerprint) = column::<Option<String>>(row, "fingerprint")? {
272                    grants.push(fingerprint);
273                }
274            }
275            Ok(grants)
276        })
277        .await
278    }
279
280    async fn release_run(&self, run: &str) -> Result<u64> {
281        let statement = query(
282            "MATCH (g:AdkKernelCrossingGrant {run: $run}) DELETE g RETURN count(*) AS released",
283        )
284        .param("run", run);
285        let graph = self.graph.clone();
286        let released = detached(async move {
287            count(&rows(&graph, statement, "release the crossing grants").await?, "released")
288        })
289        .await?;
290        Ok(u64::try_from(released).unwrap_or(0))
291    }
292}