Skip to main content

adk_kernel/stores/
driver_neo4j.rs

1//! The Neo4j [`DriverStore`] (spec 3.2 §7.7, §13 Q8; features `drivers`, `neo4j`).
2
3use adk_core::ApprovalScope;
4use async_trait::async_trait;
5use neo4rs::{Graph, Row, query};
6
7use super::neo4j::{column, connect, count, detached, json, order_key, rows, run_schema};
8use crate::drivers::store::park_key;
9use crate::drivers::{DriverPark, DriverRecord, DriverStore};
10use crate::error::Result;
11
12/// A [`DriverStore`] in Neo4j, shared by every replica (spec 3.2 §7.7, §13 Q8; features
13/// `drivers`, `neo4j`).
14///
15/// | Label | Key (unique) | Properties |
16/// |-------|--------------|------------|
17/// | `AdkKernelDriver` | `id` | `order_key` (the hex of the id) and `record`, the record as JSON text |
18/// | `AdkKernelDriverPark` | `key`: the hex of the scope's app, user and session and of the call id, joined by `.` | `driver` and `park`, the park as JSON text |
19///
20/// `.` sorts below every hex digit, so ordering by `key` orders parks by scope, then call
21/// id, and drivers order by `order_key`, each by UTF-8 bytes whatever the database's
22/// collation. Every call runs on a task of its own, as the
23/// [process store](crate::Neo4jProcessStore) explains.
24///
25/// # Example
26///
27/// ```rust,no_run
28/// # async fn example() -> adk_kernel::Result<()> {
29/// let store = adk_kernel::stores::Neo4jDriverStore::connect(
30///     "bolt://localhost:7687",
31///     "neo4j",
32///     "password",
33/// )
34/// .await?;
35/// store.migrate().await?;
36/// # Ok(())
37/// # }
38/// ```
39#[derive(Clone)]
40pub struct Neo4jDriverStore {
41    graph: Graph,
42}
43
44impl std::fmt::Debug for Neo4jDriverStore {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.debug_struct("Neo4jDriverStore").finish_non_exhaustive()
47    }
48}
49
50impl Neo4jDriverStore {
51    /// A store over `graph`, such as the process store's.
52    pub fn from_graph(graph: Graph) -> Self {
53        Self { graph }
54    }
55
56    /// Connects to the server at `uri`.
57    ///
58    /// # Errors
59    ///
60    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the server cannot be
61    /// reached.
62    pub async fn connect(uri: &str, user: &str, password: &str) -> Result<Self> {
63        Ok(Self::from_graph(connect(uri, user, password).await?))
64    }
65
66    /// The connection the store uses.
67    pub fn graph(&self) -> &Graph {
68        &self.graph
69    }
70
71    /// Creates the constraints and indexes the store relies on; one that exists is kept.
72    ///
73    /// # Errors
74    ///
75    /// Returns [`KernelError::Store`](crate::KernelError::Store) when a schema statement
76    /// fails.
77    pub async fn migrate(&self) -> Result<()> {
78        let graph = self.graph.clone();
79        detached(async move {
80            run_schema(
81                &graph,
82                &[
83                    "CREATE CONSTRAINT adk_kernel_driver_id IF NOT EXISTS \
84                     FOR (d:AdkKernelDriver) REQUIRE d.id IS UNIQUE",
85                    "CREATE INDEX adk_kernel_driver_order IF NOT EXISTS \
86                     FOR (d:AdkKernelDriver) ON (d.order_key)",
87                    "CREATE CONSTRAINT adk_kernel_driver_park_key IF NOT EXISTS \
88                     FOR (k:AdkKernelDriverPark) REQUIRE k.key IS UNIQUE",
89                    "CREATE INDEX adk_kernel_driver_park_driver IF NOT EXISTS \
90                     FOR (k:AdkKernelDriverPark) ON (k.driver)",
91                ],
92            )
93            .await
94        })
95        .await
96    }
97}
98
99/// Column `name` of `row` as `what`, or `None` for a node a concurrent delete removed after
100/// the statement matched it, whose properties then read as null.
101fn decode<T: serde::de::DeserializeOwned>(row: &Row, name: &str, what: &str) -> Result<Option<T>> {
102    column::<Option<String>>(row, name)?.map(|text| json(what, &text)).transpose()
103}
104
105/// The key of the park of `call_id` in `scope`.
106fn park_node_key(scope: &ApprovalScope, call_id: &str) -> String {
107    let (app, user, session, call) = park_key(scope, call_id);
108    [app, user, session, call].iter().map(|part| order_key(part)).collect::<Vec<_>>().join(".")
109}
110
111#[async_trait]
112impl DriverStore for Neo4jDriverStore {
113    async fn put(&self, record: DriverRecord) -> Result<()> {
114        let id = record.id().to_string();
115        let statement = query(
116            "MERGE (d:AdkKernelDriver {id: $id}) SET d.order_key = $order_key, d.record = $record",
117        )
118        .param("order_key", order_key(&id))
119        .param("record", serde_json::to_string(&record)?)
120        .param("id", id);
121        let graph = self.graph.clone();
122        detached(async move {
123            rows(&graph, statement, "write the driver table").await?;
124            Ok(())
125        })
126        .await
127    }
128
129    async fn get(&self, id: &str) -> Result<Option<DriverRecord>> {
130        let statement =
131            query("MATCH (d:AdkKernelDriver {id: $id}) RETURN d.record AS record").param("id", id);
132        let graph = self.graph.clone();
133        detached(async move {
134            rows(&graph, statement, "read the driver table")
135                .await?
136                .first()
137                .map_or(Ok(None), |row| decode(row, "record", "driver"))
138        })
139        .await
140    }
141
142    async fn list(&self) -> Result<Vec<DriverRecord>> {
143        let statement =
144            query("MATCH (d:AdkKernelDriver) RETURN d.record AS record ORDER BY d.order_key");
145        let graph = self.graph.clone();
146        detached(async move {
147            rows(&graph, statement, "list the driver table")
148                .await?
149                .iter()
150                .filter_map(|row| decode(row, "record", "driver").transpose())
151                .collect()
152        })
153        .await
154    }
155
156    async fn delete(&self, id: &str) -> Result<bool> {
157        let statement =
158            query("MATCH (d:AdkKernelDriver {id: $id}) DELETE d RETURN count(*) AS deleted")
159                .param("id", id);
160        let graph = self.graph.clone();
161        detached(async move {
162            Ok(count(&rows(&graph, statement, "delete from the driver table").await?, "deleted")?
163                > 0)
164        })
165        .await
166    }
167
168    async fn put_park(&self, park: DriverPark) -> Result<()> {
169        let statement = query(
170            "MERGE (k:AdkKernelDriverPark {key: $key}) SET k.driver = $driver, k.park = $park",
171        )
172        .param("key", park_node_key(&park.scope, &park.call_id))
173        .param("driver", park.driver.as_str())
174        .param("park", serde_json::to_string(&park)?);
175        let graph = self.graph.clone();
176        detached(async move {
177            rows(&graph, statement, "write the driver table").await?;
178            Ok(())
179        })
180        .await
181    }
182
183    async fn get_park(&self, scope: &ApprovalScope, call_id: &str) -> Result<Option<DriverPark>> {
184        let statement = query("MATCH (k:AdkKernelDriverPark {key: $key}) RETURN k.park AS park")
185            .param("key", park_node_key(scope, call_id));
186        let graph = self.graph.clone();
187        detached(async move {
188            rows(&graph, statement, "read the driver table")
189                .await?
190                .first()
191                .map_or(Ok(None), |row| decode(row, "park", "parked driver call"))
192        })
193        .await
194    }
195
196    async fn list_parks(&self, driver: Option<&str>) -> Result<Vec<DriverPark>> {
197        let filter = if driver.is_some() { " WHERE k.driver = $driver" } else { "" };
198        let statement = query(&format!(
199            "MATCH (k:AdkKernelDriverPark){filter} RETURN k.park AS park ORDER BY k.key"
200        ))
201        .param("driver", driver);
202        let graph = self.graph.clone();
203        detached(async move {
204            rows(&graph, statement, "list the driver table")
205                .await?
206                .iter()
207                .filter_map(|row| decode(row, "park", "parked driver call").transpose())
208                .collect()
209        })
210        .await
211    }
212
213    async fn delete_park(&self, scope: &ApprovalScope, call_id: &str) -> Result<bool> {
214        let statement =
215            query("MATCH (k:AdkKernelDriverPark {key: $key}) DELETE k RETURN count(*) AS deleted")
216                .param("key", park_node_key(scope, call_id));
217        let graph = self.graph.clone();
218        detached(async move {
219            Ok(count(&rows(&graph, statement, "delete from the driver table").await?, "deleted")?
220                > 0)
221        })
222        .await
223    }
224}