Skip to main content

adk_kernel/stores/
agent_mongodb.rs

1//! The MongoDB [`AgentStore`] (spec 3.3 §5.7, §10 K7, feature `mongodb`).
2
3use 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/// An [`AgentStore`] in MongoDB, shared by every replica (spec 3.3 §5.7, §10 K7, feature
14/// `mongodb`).
15///
16/// One `adk_kernel_agents` document per agent, `_id` its id: `version` and `state`, the
17/// fields a write compares and a delete reads, beside `record`, the record as JSON text, so
18/// it reads back exactly as written. `list` sorts by `_id` under MongoDB's binary string
19/// comparison, so ids order by their UTF-8 bytes. A new agent is one insert, refused by the
20/// `_id` index when the id exists; a change is one update filtered on `_id` and `version`.
21/// Every write is a single-document write, so a standalone `mongod` serves it as a replica
22/// set does.
23///
24/// # Example
25///
26/// ```rust,no_run
27/// # async fn example() -> adk_kernel::Result<()> {
28/// let store = adk_kernel::stores::MongoAgentStore::connect("mongodb://localhost:27017", "adk").await?;
29/// store.migrate().await?;
30/// # Ok(())
31/// # }
32/// ```
33#[derive(Debug, Clone)]
34pub struct MongoAgentStore {
35    db: Database,
36}
37
38impl MongoAgentStore {
39    /// A store over `db`, such as the process store's.
40    pub fn from_database(db: Database) -> Self {
41        Self { db }
42    }
43
44    /// Connects to `connection_string` and uses the database `database_name`.
45    ///
46    /// # Errors
47    ///
48    /// Returns [`KernelError::Store`] when the connection string is invalid.
49    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    /// The database the store writes to.
54    pub fn database(&self) -> &Database {
55        &self.db
56    }
57
58    /// Prepares the store; `_id`, the only index it reads, always exists, so this does
59    /// nothing.
60    ///
61    /// # Errors
62    ///
63    /// Never returns an error.
64    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
80/// The fields of `record` other than `_id`.
81fn 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}