adk_kernel/stores/
agent_mongodb.rs1use async_trait::async_trait;
4use mongodb::bson::{Document, doc};
5use mongodb::{Collection, Database};
6
7use super::mongodb::{collect, connect, is_duplicate_key, json, sorted, store_error, text};
8use crate::agents::{AgentRecord, AgentStore};
9use crate::error::{KernelError, Result};
10
11const AGENTS: &str = "adk_kernel_agents";
12
13#[derive(Debug, Clone)]
34pub struct MongoAgentStore {
35 db: Database,
36}
37
38impl MongoAgentStore {
39 pub fn from_database(db: Database) -> Self {
41 Self { db }
42 }
43
44 pub async fn connect(connection_string: &str, database_name: &str) -> Result<Self> {
50 Ok(Self::from_database(connect(connection_string, database_name).await?))
51 }
52
53 pub fn database(&self) -> &Database {
55 &self.db
56 }
57
58 pub async fn migrate(&self) -> Result<()> {
65 Ok(())
66 }
67
68 fn agents(&self) -> Collection<Document> {
69 self.db.collection(AGENTS)
70 }
71}
72
73fn stored_version(version: u64) -> Result<i64> {
74 i64::try_from(version).map_err(|_| KernelError::Store {
75 backend: super::mongodb::BACKEND,
76 reason: format!("agent version {version} exceeds a signed 64-bit integer"),
77 })
78}
79
80fn fields(record: &AgentRecord) -> Result<Document> {
82 Ok(doc! {
83 "version": stored_version(record.version)?,
84 "state": record.state.as_str(),
85 "record": serde_json::to_string(record)?,
86 })
87}
88
89fn decode(document: &Document) -> Result<AgentRecord> {
90 json("agent", text(document, "record")?)
91}
92
93#[async_trait]
94impl AgentStore for MongoAgentStore {
95 async fn put_if_version(&self, record: AgentRecord, expected: u64) -> Result<bool> {
96 if expected == 0 {
97 let mut document = doc! { "_id": &record.id };
98 document.extend(fields(&record)?);
99 return match self.agents().insert_one(document).await {
100 Ok(_) => Ok(true),
101 Err(error) if is_duplicate_key(&error) => Ok(false),
102 Err(error) => Err(store_error("write the agent table", &error)),
103 };
104 }
105 let result = self
106 .agents()
107 .update_one(
108 doc! { "_id": &record.id, "version": stored_version(expected)? },
109 doc! { "$set": fields(&record)? },
110 )
111 .await
112 .map_err(|error| store_error("update the agent table", &error))?;
113 Ok(result.matched_count == 1)
114 }
115
116 async fn get(&self, id: &str) -> Result<Option<AgentRecord>> {
117 let document = self
118 .agents()
119 .find_one(doc! { "_id": id })
120 .await
121 .map_err(|error| store_error("read the agent table", &error))?;
122 document.as_ref().map(decode).transpose()
123 }
124
125 async fn list(&self) -> Result<Vec<AgentRecord>> {
126 let cursor = self
127 .agents()
128 .find(doc! {})
129 .with_options(sorted(doc! { "_id": 1 }, None))
130 .await
131 .map_err(|error| store_error("list the agent table", &error))?;
132 collect(cursor, "list the agent table").await?.iter().map(decode).collect()
133 }
134
135 async fn delete(&self, id: &str) -> Result<bool> {
136 let result = self
137 .agents()
138 .delete_one(doc! { "_id": id, "state": "proposed" })
139 .await
140 .map_err(|error| store_error("delete from the agent table", &error))?;
141 Ok(result.deleted_count == 1)
142 }
143}