use async_trait::async_trait;
use neo4rs::{Graph, Query, Row, query};
use super::neo4j::{
column, connect, count, detached, json, order_key, retry, rows, run_schema, txn_rows,
};
use crate::agents::{AgentRecord, AgentStore};
use crate::error::{KernelError, Result};
const LOCK: &str = "\
MERGE (a:AdkKernelAgent {id: $id}) ON CREATE SET a.version = 0, a.order_key = $order_key \
SET a.lock_seq = coalesce(a.lock_seq, 0) + 1";
const VERSION: &str = "MATCH (a:AdkKernelAgent {id: $id}) RETURN a.version AS version";
const WRITE: &str = "\
MATCH (a:AdkKernelAgent {id: $id}) \
SET a.version = $version, a.state = $state, a.record = $record";
#[derive(Clone)]
pub struct Neo4jAgentStore {
graph: Graph,
}
impl std::fmt::Debug for Neo4jAgentStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Neo4jAgentStore").finish_non_exhaustive()
}
}
impl Neo4jAgentStore {
pub fn from_graph(graph: Graph) -> Self {
Self { graph }
}
pub async fn connect(uri: &str, user: &str, password: &str) -> Result<Self> {
Ok(Self::from_graph(connect(uri, user, password).await?))
}
pub fn graph(&self) -> &Graph {
&self.graph
}
pub async fn migrate(&self) -> Result<()> {
let graph = self.graph.clone();
detached(async move {
run_schema(
&graph,
&["CREATE CONSTRAINT adk_kernel_agent_id IF NOT EXISTS \
FOR (a:AdkKernelAgent) REQUIRE a.id IS UNIQUE"],
)
.await
})
.await
}
}
fn stored_version(version: u64) -> Result<i64> {
i64::try_from(version).map_err(|_| KernelError::Store {
backend: super::neo4j::BACKEND,
reason: format!("agent version {version} exceeds a signed 64-bit integer"),
})
}
fn decode(row: &Row) -> Result<Option<AgentRecord>> {
column::<Option<String>>(row, "record")?.map(|record| json("agent", &record)).transpose()
}
async fn put_once(
graph: &Graph,
id: &str,
expected: i64,
write: Query,
) -> std::result::Result<bool, neo4rs::Error> {
let mut txn = graph.start_txn().await?;
txn.run(query(LOCK).param("id", id).param("order_key", order_key(id))).await?;
let version = txn_rows(&mut txn, query(VERSION).param("id", id))
.await?
.first()
.and_then(|row| row.get::<Option<i64>>("version").ok().flatten())
.unwrap_or(0);
if version != expected {
txn.rollback().await?;
return Ok(false);
}
txn.run(write).await?;
txn.commit().await?;
Ok(true)
}
#[async_trait]
impl AgentStore for Neo4jAgentStore {
async fn put_if_version(&self, record: AgentRecord, expected: u64) -> Result<bool> {
let write = query(WRITE)
.param("id", record.id.as_str())
.param("version", stored_version(record.version)?)
.param("state", record.state.as_str())
.param("record", serde_json::to_string(&record)?);
let expected = stored_version(expected)?;
let (graph, id) = (self.graph.clone(), record.id.clone());
detached(async move {
retry("write the agent table", || put_once(&graph, &id, expected, write.clone())).await
})
.await
}
async fn get(&self, id: &str) -> Result<Option<AgentRecord>> {
let statement =
query("MATCH (a:AdkKernelAgent {id: $id}) RETURN a.record AS record").param("id", id);
let graph = self.graph.clone();
detached(async move {
Ok(match rows(&graph, statement, "read the agent table").await?.first() {
Some(row) => decode(row)?,
None => None,
})
})
.await
}
async fn list(&self) -> Result<Vec<AgentRecord>> {
let statement = query(
"MATCH (a:AdkKernelAgent) WHERE a.record IS NOT NULL RETURN a.record AS record \
ORDER BY a.order_key",
);
let graph = self.graph.clone();
detached(async move {
let rows = rows(&graph, statement, "list the agent table").await?;
rows.iter().filter_map(|row| decode(row).transpose()).collect()
})
.await
}
async fn delete(&self, id: &str) -> Result<bool> {
let statement = query(
"MATCH (a:AdkKernelAgent {id: $id}) WHERE a.state = 'proposed' DELETE a \
RETURN count(*) AS deleted",
)
.param("id", id);
let graph = self.graph.clone();
detached(async move {
Ok(count(&rows(&graph, statement, "delete from the agent table").await?, "deleted")?
> 0)
})
.await
}
}