Skip to main content

adk_kernel/stores/
ledger_neo4j.rs

1//! The Neo4j [`LedgerStore`] (spec 3.2 §7.10, §13 Q8, features `proc` and `neo4j`).
2
3use async_trait::async_trait;
4use neo4rs::{Graph, Row, query};
5
6use super::day_number;
7use super::neo4j::{
8    BACKEND, column, connect, detached, json, limit_clause, order_key, rows, run_schema,
9    where_clause,
10};
11use crate::error::{KernelError, Result};
12use crate::partition::PartitionId;
13use crate::proc::{
14    LedgerEntry, LedgerQuery, LedgerStore, Observation, ObservationQuery, PassState,
15};
16
17/// Takes the next sequence number and creates the row under it in one statement: the
18/// counter's `SET` from its own value write-locks it, so appends commit in number order.
19const APPEND: &str = "\
20MERGE (c:AdkKernelLedgerCounter {name: 'ledger'}) \
21SET c.seq = coalesce(c.seq, 0) + 1 \
22CREATE (r:AdkKernelLedgerRow {seq: c.seq, ts_ms: $ts_ms, partition: $partition, agent: $agent, \
23    kind: $kind, row: $row}) \
24RETURN r.seq AS seq";
25
26const PUT_OBSERVATION: &str = "\
27MERGE (o:AdkKernelObservation {id: $id}) \
28SET o.order_key = $order_key, o.partition = $partition, o.as_of = $as_of, o.body = $body";
29
30const PUT_PASS_STATE: &str = "\
31MERGE (s:AdkKernelPassState {partition: $partition}) \
32SET s.order_key = $order_key, s.body = $body";
33
34/// A [`LedgerStore`] in Neo4j, shared by every replica (spec 3.2 §7.1, §7.10, §13 Q8,
35/// features `proc` and `neo4j`).
36///
37/// | Label | Key (unique) | Properties |
38/// |-------|--------------|------------|
39/// | `AdkKernelLedgerRow` | `seq` | `ts_ms` (the instant in UTC milliseconds), `partition`, `agent` and `kind`, the properties `list` filters on, and `row`, the row as JSON text |
40/// | `AdkKernelLedgerCounter` | `name` (`ledger`) | `seq`, the last sequence number taken |
41/// | `AdkKernelObservation` | `id` | `order_key` (the hex of the id), `partition`, `as_of` (days from the common era) and `body`, the observation as JSON text |
42/// | `AdkKernelPassState` | `partition` | `order_key` (the hex of the partition) and `body`, the pass state as JSON text |
43///
44/// An append is one statement: it raises the counter, which write-locks it until the
45/// statement commits, and creates the row under the new number, so rows commit in number
46/// order and a reader paging with `after` never passes a row that lands later. Every call
47/// runs on a task of its own, as the [process store](crate::Neo4jProcessStore) explains.
48///
49/// # Example
50///
51/// ```rust,no_run
52/// # async fn example() -> adk_kernel::Result<()> {
53/// let store = adk_kernel::proc::Neo4jLedgerStore::connect(
54///     "bolt://localhost:7687",
55///     "neo4j",
56///     "password",
57/// )
58/// .await?;
59/// store.migrate().await?;
60/// # Ok(())
61/// # }
62/// ```
63#[derive(Clone)]
64pub struct Neo4jLedgerStore {
65    graph: Graph,
66}
67
68impl std::fmt::Debug for Neo4jLedgerStore {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        f.debug_struct("Neo4jLedgerStore").finish_non_exhaustive()
71    }
72}
73
74impl Neo4jLedgerStore {
75    /// A store over `graph`, such as the process store's.
76    pub fn from_graph(graph: Graph) -> Self {
77        Self { graph }
78    }
79
80    /// Connects to the server at `uri`.
81    ///
82    /// # Errors
83    ///
84    /// Returns [`KernelError::Store`] when the server cannot be reached.
85    pub async fn connect(uri: &str, user: &str, password: &str) -> Result<Self> {
86        Ok(Self::from_graph(connect(uri, user, password).await?))
87    }
88
89    /// The connection the store uses.
90    pub fn graph(&self) -> &Graph {
91        &self.graph
92    }
93
94    /// Creates the constraints and indexes the store relies on; one that exists is kept.
95    ///
96    /// # Errors
97    ///
98    /// Returns [`KernelError::Store`] when a schema statement fails.
99    pub async fn migrate(&self) -> Result<()> {
100        let graph = self.graph.clone();
101        detached(async move {
102            run_schema(
103                &graph,
104                &[
105                    "CREATE CONSTRAINT adk_kernel_ledger_seq IF NOT EXISTS \
106                     FOR (r:AdkKernelLedgerRow) REQUIRE r.seq IS UNIQUE",
107                    "CREATE INDEX adk_kernel_ledger_ts IF NOT EXISTS \
108                     FOR (r:AdkKernelLedgerRow) ON (r.ts_ms)",
109                    "CREATE INDEX adk_kernel_ledger_partition IF NOT EXISTS \
110                     FOR (r:AdkKernelLedgerRow) ON (r.partition)",
111                    "CREATE INDEX adk_kernel_ledger_kind IF NOT EXISTS \
112                     FOR (r:AdkKernelLedgerRow) ON (r.kind)",
113                    "CREATE CONSTRAINT adk_kernel_ledger_counter IF NOT EXISTS \
114                     FOR (c:AdkKernelLedgerCounter) REQUIRE c.name IS UNIQUE",
115                    "CREATE CONSTRAINT adk_kernel_observation_id IF NOT EXISTS \
116                     FOR (o:AdkKernelObservation) REQUIRE o.id IS UNIQUE",
117                    "CREATE INDEX adk_kernel_observation_partition IF NOT EXISTS \
118                     FOR (o:AdkKernelObservation) ON (o.partition)",
119                    "CREATE CONSTRAINT adk_kernel_pass_state_partition IF NOT EXISTS \
120                     FOR (s:AdkKernelPassState) REQUIRE s.partition IS UNIQUE",
121                ],
122            )
123            .await
124        })
125        .await
126    }
127}
128
129fn decode_row(row: &Row) -> Result<LedgerEntry> {
130    let seq = u64::try_from(column::<i64>(row, "seq")?).map_err(|_| KernelError::Store {
131        backend: BACKEND,
132        reason: "a ledger row has a negative sequence number".into(),
133    })?;
134    let mut entry: LedgerEntry = json("ledger row", &column::<String>(row, "row")?)?;
135    entry.seq = seq;
136    Ok(entry)
137}
138
139#[async_trait]
140impl LedgerStore for Neo4jLedgerStore {
141    async fn append(&self, mut entry: LedgerEntry) -> Result<LedgerEntry> {
142        entry.seq = 0;
143        let statement = query(APPEND)
144            .param("ts_ms", entry.ts.timestamp_millis())
145            .param("partition", entry.partition.as_str())
146            .param("agent", entry.agent.as_str())
147            .param("kind", entry.kind.as_str())
148            .param("row", serde_json::to_string(&entry)?);
149        let graph = self.graph.clone();
150        let seq = detached(async move {
151            let rows = rows(&graph, statement, "append to the ledger").await?;
152            let row = rows.first().ok_or_else(|| KernelError::Store {
153                backend: BACKEND,
154                reason: "an append returned no sequence number".into(),
155            })?;
156            column::<i64>(row, "seq")
157        })
158        .await?;
159        entry.seq = u64::try_from(seq).map_err(|_| KernelError::Store {
160            backend: BACKEND,
161            reason: format!("the ledger counter holds a negative sequence number {seq}"),
162        })?;
163        Ok(entry)
164    }
165
166    async fn list(&self, filter: &LedgerQuery) -> Result<Vec<LedgerEntry>> {
167        let mut conditions = Vec::new();
168        if filter.partition.is_some() {
169            conditions.push("r.partition = $partition");
170        }
171        if !filter.kinds.is_empty() {
172            conditions.push("r.kind IN $kinds");
173        }
174        if filter.agent.is_some() {
175            conditions.push("r.agent = $agent");
176        }
177        if filter.from.is_some() {
178            conditions.push("r.ts_ms >= $from");
179        }
180        if filter.to.is_some() {
181            conditions.push("r.ts_ms < $to");
182        }
183        if filter.after.is_some() {
184            conditions.push("r.seq > $after");
185        }
186        let (limit, limit_value) = limit_clause(filter.limit);
187        let statement = query(&format!(
188            "MATCH (r:AdkKernelLedgerRow){} RETURN r.seq AS seq, r.row AS row ORDER BY r.seq{limit}",
189            where_clause(&conditions)
190        ))
191        .param("partition", filter.partition.as_ref().map(|partition| partition.as_str()))
192        .param("kinds", filter.kinds.clone())
193        .param("agent", filter.agent.clone())
194        .param("from", filter.from.map(|from| from.timestamp_millis()))
195        .param("to", filter.to.map(|to| to.timestamp_millis()))
196        .param("after", filter.after.map(|after| i64::try_from(after).unwrap_or(i64::MAX)))
197        .param("limit", limit_value);
198        let graph = self.graph.clone();
199        detached(async move {
200            rows(&graph, statement, "read the ledger").await?.iter().map(decode_row).collect()
201        })
202        .await
203    }
204
205    async fn put_observation(&self, observation: Observation) -> Result<()> {
206        let statement = query(PUT_OBSERVATION)
207            .param("id", observation.id.as_str())
208            .param("order_key", order_key(&observation.id))
209            .param("partition", observation.partition.as_str())
210            .param("as_of", day_number(observation.as_of))
211            .param("body", serde_json::to_string(&observation)?);
212        let graph = self.graph.clone();
213        detached(async move {
214            rows(&graph, statement, "write an observation").await?;
215            Ok(())
216        })
217        .await
218    }
219
220    async fn observations(&self, filter: &ObservationQuery) -> Result<Vec<Observation>> {
221        let mut conditions = Vec::new();
222        if filter.partition.is_some() {
223            conditions.push("o.partition = $partition");
224        }
225        if filter.since.is_some() {
226            conditions.push("o.as_of >= $since");
227        }
228        let (limit, limit_value) = limit_clause(filter.limit);
229        let statement = query(&format!(
230            "MATCH (o:AdkKernelObservation){} RETURN o.body AS body \
231             ORDER BY o.as_of DESC, o.order_key{limit}",
232            where_clause(&conditions)
233        ))
234        .param("partition", filter.partition.as_ref().map(|partition| partition.as_str()))
235        .param("since", filter.since.map(day_number))
236        .param("limit", limit_value);
237        let graph = self.graph.clone();
238        detached(async move {
239            rows(&graph, statement, "read the observations")
240                .await?
241                .iter()
242                .map(|row| json("observation", &column::<String>(row, "body")?))
243                .collect()
244        })
245        .await
246    }
247
248    async fn pass_state(&self, partition: &PartitionId) -> Result<Option<PassState>> {
249        let statement =
250            query("MATCH (s:AdkKernelPassState {partition: $partition}) RETURN s.body AS body")
251                .param("partition", partition.as_str());
252        let graph = self.graph.clone();
253        detached(async move {
254            rows(&graph, statement, "read the pass state")
255                .await?
256                .first()
257                .map(|row| json("pass state", &column::<String>(row, "body")?))
258                .transpose()
259        })
260        .await
261    }
262
263    async fn pass_states(&self) -> Result<Vec<PassState>> {
264        let statement =
265            query("MATCH (s:AdkKernelPassState) RETURN s.body AS body ORDER BY s.order_key");
266        let graph = self.graph.clone();
267        detached(async move {
268            rows(&graph, statement, "read the pass states")
269                .await?
270                .iter()
271                .map(|row| json("pass state", &column::<String>(row, "body")?))
272                .collect()
273        })
274        .await
275    }
276
277    async fn put_pass_state(&self, state: PassState) -> Result<()> {
278        let statement = query(PUT_PASS_STATE)
279            .param("partition", state.partition.as_str())
280            .param("order_key", order_key(state.partition.as_str()))
281            .param("body", serde_json::to_string(&state)?);
282        let graph = self.graph.clone();
283        detached(async move {
284            rows(&graph, statement, "write the pass state").await?;
285            Ok(())
286        })
287        .await
288    }
289}