1use 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
18const 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#[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 pub fn from_graph(graph: Graph) -> Self {
65 Self { graph }
66 }
67
68 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 pub fn graph(&self) -> &Graph {
80 &self.graph
81 }
82
83 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
111fn 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
121fn decode(row: &Row) -> Result<Option<AgendaItem>> {
124 column::<Option<String>>(row, "item")?.map(|item| json("agenda item", &item)).transpose()
125}
126
127async 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}