adk_graph/checkpointers/
mongodb.rs1use async_trait::async_trait;
4use mongodb::bson::{Bson, Document, doc};
5use mongodb::error::{ErrorKind, WriteFailure};
6use mongodb::options::{ClientOptions, FindOptions, IndexOptions};
7use mongodb::{Client, Collection, Database, IndexModel};
8
9use super::{decode, encode, storage_error};
10use crate::checkpoint::{Checkpointer, RetentionPolicy, conflict, duplicate_id, ensure_newer};
11use crate::error::Result;
12use crate::state::Checkpoint;
13
14const BACKEND: &str = "mongodb";
15const CHECKPOINTS: &str = "adk_graph_checkpoints";
16const THREADS: &str = "adk_graph_threads";
17const THREAD_VERSION_INDEX: &str = "adk_graph_checkpoints_thread_version";
18
19const DUPLICATE_KEY: i32 = 11000;
21
22fn duplicate_key_message(error: &mongodb::error::Error) -> Option<&str> {
23 match error.kind.as_ref() {
24 ErrorKind::Write(WriteFailure::WriteError(write)) if write.code == DUPLICATE_KEY => {
25 Some(&write.message)
26 }
27 ErrorKind::Command(command) if command.code == DUPLICATE_KEY => Some(&command.message),
28 _ => None,
29 }
30}
31
32fn version_param(version: u64) -> Result<i64> {
33 i64::try_from(version)
34 .map_err(|_| storage_error(BACKEND, format!("version {version} exceeds a 64-bit integer")))
35}
36
37#[derive(Debug, Clone)]
65pub struct MongoCheckpointer {
66 db: Database,
67}
68
69impl MongoCheckpointer {
70 pub async fn new(connection_string: &str, database_name: &str) -> Result<Self> {
76 let fail =
77 |e: mongodb::error::Error| storage_error(BACKEND, format!("connection failed: {e}"));
78 let options = ClientOptions::parse(connection_string).await.map_err(fail)?;
79 Ok(Self::from_database(
80 Client::with_options(options).map_err(fail)?.database(database_name),
81 ))
82 }
83
84 pub fn from_database(db: Database) -> Self {
86 Self { db }
87 }
88
89 pub async fn migrate(&self) -> Result<()> {
95 self.checkpoints()
96 .create_index(
97 IndexModel::builder()
98 .keys(doc! { "thread_id": 1, "version": -1 })
99 .options(
100 IndexOptions::builder()
101 .name(THREAD_VERSION_INDEX.to_string())
102 .unique(true)
103 .build(),
104 )
105 .build(),
106 )
107 .await
108 .map_err(|e| storage_error(BACKEND, format!("migration failed: {e}")))?;
109 Ok(())
110 }
111
112 fn checkpoints(&self) -> Collection<Document> {
113 self.db.collection(CHECKPOINTS)
114 }
115
116 fn threads(&self) -> Collection<Document> {
117 self.db.collection(THREADS)
118 }
119
120 async fn head(&self, thread_id: &str) -> Result<u64> {
121 let thread = self
122 .threads()
123 .find_one(doc! { "_id": thread_id })
124 .await
125 .map_err(|e| storage_error(BACKEND, e))?;
126 Ok(thread
127 .and_then(|thread| match thread.get("head") {
128 Some(Bson::Int64(head)) => Some(*head as u64),
129 Some(Bson::Int32(head)) => Some(*head as u64),
130 _ => None,
131 })
132 .unwrap_or(0))
133 }
134
135 async fn find(&self, filter: Document, options: FindOptions) -> Result<Vec<Checkpoint>> {
136 let mut cursor = self
137 .checkpoints()
138 .find(filter)
139 .with_options(options)
140 .await
141 .map_err(|e| storage_error(BACKEND, e))?;
142 let mut checkpoints = Vec::new();
143 while cursor.advance().await.map_err(|e| storage_error(BACKEND, e))? {
144 let document = cursor.deserialize_current().map_err(|e| storage_error(BACKEND, e))?;
145 let data = document
146 .get_str("data")
147 .map_err(|e| storage_error(BACKEND, format!("field 'data' is corrupt: {e}")))?;
148 checkpoints.push(decode(BACKEND, data)?);
149 }
150 Ok(checkpoints)
151 }
152}
153
154#[async_trait]
155impl Checkpointer for MongoCheckpointer {
156 async fn save(&self, checkpoint: &Checkpoint) -> Result<String> {
157 ensure_newer(checkpoint, None)?;
158 let version = version_param(checkpoint.version)?;
159 let document = doc! {
160 "_id": &checkpoint.checkpoint_id,
161 "thread_id": &checkpoint.thread_id,
162 "version": version,
163 "created_at": mongodb::bson::DateTime::from_millis(checkpoint.created_at.timestamp_millis()),
164 "data": encode(checkpoint)?,
165 };
166 if let Err(error) = self.checkpoints().insert_one(document).await {
167 return Err(match duplicate_key_message(&error) {
168 Some(message) if message.contains(THREAD_VERSION_INDEX) => {
169 conflict(checkpoint, self.head(&checkpoint.thread_id).await?)
170 }
171 Some(_) => duplicate_id(&checkpoint.checkpoint_id),
172 None => storage_error(BACKEND, error),
173 });
174 }
175 let advanced = self
176 .threads()
177 .update_one(
178 doc! { "_id": &checkpoint.thread_id, "head": { "$lt": version } },
179 doc! { "$set": { "head": version } },
180 )
181 .upsert(true)
182 .await;
183 match advanced {
184 Ok(_) => Ok(checkpoint.checkpoint_id.clone()),
185 Err(error) => {
186 self.checkpoints()
187 .delete_one(doc! { "_id": &checkpoint.checkpoint_id })
188 .await
189 .map_err(|e| storage_error(BACKEND, e))?;
190 match duplicate_key_message(&error) {
191 Some(_) => Err(conflict(checkpoint, self.head(&checkpoint.thread_id).await?)),
192 None => Err(storage_error(BACKEND, error)),
193 }
194 }
195 }
196 }
197
198 async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>> {
199 let options = FindOptions::builder().sort(doc! { "version": -1 }).limit(1).build();
200 Ok(self.find(doc! { "thread_id": thread_id }, options).await?.pop())
201 }
202
203 async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>> {
204 Ok(self.find(doc! { "_id": checkpoint_id }, FindOptions::default()).await?.pop())
205 }
206
207 async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>> {
208 let options = FindOptions::builder().sort(doc! { "version": 1 }).build();
209 self.find(doc! { "thread_id": thread_id }, options).await
210 }
211
212 async fn list_page(
213 &self,
214 thread_id: &str,
215 before: Option<u64>,
216 limit: usize,
217 ) -> Result<Vec<Checkpoint>> {
218 if limit == 0 {
219 return Ok(Vec::new());
220 }
221 let mut filter = doc! { "thread_id": thread_id };
222 if let Some(before) = before {
223 filter.insert("version", doc! { "$lt": version_param(before)? });
224 }
225 let options = FindOptions::builder()
226 .sort(doc! { "version": -1 })
227 .limit(i64::try_from(limit).unwrap_or(i64::MAX))
228 .build();
229 self.find(filter, options).await
230 }
231
232 async fn delete(&self, thread_id: &str) -> Result<()> {
233 self.checkpoints()
234 .delete_many(doc! { "thread_id": thread_id })
235 .await
236 .map_err(|e| storage_error(BACKEND, e))?;
237 self.threads()
238 .delete_one(doc! { "_id": thread_id })
239 .await
240 .map_err(|e| storage_error(BACKEND, e))?;
241 Ok(())
242 }
243
244 async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize> {
245 let expired = policy.expired(&self.list(thread_id).await?);
246 if expired.is_empty() {
247 return Ok(0);
248 }
249 let result = self
250 .checkpoints()
251 .delete_many(doc! { "thread_id": thread_id, "_id": { "$in": expired } })
252 .await
253 .map_err(|e| storage_error(BACKEND, e))?;
254 Ok(result.deleted_count as usize)
255 }
256}