adk_kernel/stores/
agent_neo4j.rs1use async_trait::async_trait;
4use neo4rs::{Graph, Query, Row, query};
5
6use super::neo4j::{
7 column, connect, count, detached, json, order_key, retry, rows, run_schema, txn_rows,
8};
9use crate::agents::{AgentRecord, AgentStore};
10use crate::error::{KernelError, Result};
11
12const LOCK: &str = "\
16MERGE (a:AdkKernelAgent {id: $id}) ON CREATE SET a.version = 0, a.order_key = $order_key \
17SET a.lock_seq = coalesce(a.lock_seq, 0) + 1";
18
19const VERSION: &str = "MATCH (a:AdkKernelAgent {id: $id}) RETURN a.version AS version";
20
21const WRITE: &str = "\
22MATCH (a:AdkKernelAgent {id: $id}) \
23SET a.version = $version, a.state = $state, a.record = $record";
24
25#[derive(Clone)]
47pub struct Neo4jAgentStore {
48 graph: Graph,
49}
50
51impl std::fmt::Debug for Neo4jAgentStore {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 f.debug_struct("Neo4jAgentStore").finish_non_exhaustive()
54 }
55}
56
57impl Neo4jAgentStore {
58 pub fn from_graph(graph: Graph) -> Self {
60 Self { graph }
61 }
62
63 pub async fn connect(uri: &str, user: &str, password: &str) -> Result<Self> {
69 Ok(Self::from_graph(connect(uri, user, password).await?))
70 }
71
72 pub fn graph(&self) -> &Graph {
74 &self.graph
75 }
76
77 pub async fn migrate(&self) -> Result<()> {
83 let graph = self.graph.clone();
84 detached(async move {
85 run_schema(
86 &graph,
87 &["CREATE CONSTRAINT adk_kernel_agent_id IF NOT EXISTS \
88 FOR (a:AdkKernelAgent) REQUIRE a.id IS UNIQUE"],
89 )
90 .await
91 })
92 .await
93 }
94}
95
96fn stored_version(version: u64) -> Result<i64> {
97 i64::try_from(version).map_err(|_| KernelError::Store {
98 backend: super::neo4j::BACKEND,
99 reason: format!("agent version {version} exceeds a signed 64-bit integer"),
100 })
101}
102
103fn decode(row: &Row) -> Result<Option<AgentRecord>> {
107 column::<Option<String>>(row, "record")?.map(|record| json("agent", &record)).transpose()
108}
109
110async fn put_once(
113 graph: &Graph,
114 id: &str,
115 expected: i64,
116 write: Query,
117) -> std::result::Result<bool, neo4rs::Error> {
118 let mut txn = graph.start_txn().await?;
119 txn.run(query(LOCK).param("id", id).param("order_key", order_key(id))).await?;
120 let version = txn_rows(&mut txn, query(VERSION).param("id", id))
121 .await?
122 .first()
123 .and_then(|row| row.get::<Option<i64>>("version").ok().flatten())
124 .unwrap_or(0);
125 if version != expected {
126 txn.rollback().await?;
127 return Ok(false);
128 }
129 txn.run(write).await?;
130 txn.commit().await?;
131 Ok(true)
132}
133
134#[async_trait]
135impl AgentStore for Neo4jAgentStore {
136 async fn put_if_version(&self, record: AgentRecord, expected: u64) -> Result<bool> {
137 let write = query(WRITE)
138 .param("id", record.id.as_str())
139 .param("version", stored_version(record.version)?)
140 .param("state", record.state.as_str())
141 .param("record", serde_json::to_string(&record)?);
142 let expected = stored_version(expected)?;
143 let (graph, id) = (self.graph.clone(), record.id.clone());
144 detached(async move {
145 retry("write the agent table", || put_once(&graph, &id, expected, write.clone())).await
146 })
147 .await
148 }
149
150 async fn get(&self, id: &str) -> Result<Option<AgentRecord>> {
151 let statement =
152 query("MATCH (a:AdkKernelAgent {id: $id}) RETURN a.record AS record").param("id", id);
153 let graph = self.graph.clone();
154 detached(async move {
155 Ok(match rows(&graph, statement, "read the agent table").await?.first() {
156 Some(row) => decode(row)?,
157 None => None,
158 })
159 })
160 .await
161 }
162
163 async fn list(&self) -> Result<Vec<AgentRecord>> {
164 let statement = query(
165 "MATCH (a:AdkKernelAgent) WHERE a.record IS NOT NULL RETURN a.record AS record \
166 ORDER BY a.order_key",
167 );
168 let graph = self.graph.clone();
169 detached(async move {
170 let rows = rows(&graph, statement, "list the agent table").await?;
171 rows.iter().filter_map(|row| decode(row).transpose()).collect()
172 })
173 .await
174 }
175
176 async fn delete(&self, id: &str) -> Result<bool> {
177 let statement = query(
178 "MATCH (a:AdkKernelAgent {id: $id}) WHERE a.state = 'proposed' DELETE a \
179 RETURN count(*) AS deleted",
180 )
181 .param("id", id);
182 let graph = self.graph.clone();
183 detached(async move {
184 Ok(count(&rows(&graph, statement, "delete from the agent table").await?, "deleted")?
185 > 0)
186 })
187 .await
188 }
189}