adk_kernel/stores/
agenda_firestore.rs1use std::sync::Arc;
4
5use async_trait::async_trait;
6use firestore::FirestoreDb;
7use serde::{Deserialize, Serialize};
8
9use super::firestore::{
10 TxFuture, connect, delete_where, doc_id, json, store_error, transaction_error,
11 transaction_options, tx_fail,
12};
13use crate::agenda::{AgendaFilter, AgendaItem, AgendaStateKind, AgendaStore};
14use crate::error::Result;
15
16const AGENDA: &str = "adk_kernel_agenda";
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
20struct AgendaDoc {
21 id: String,
22 partition: String,
23 state: String,
24 created_us: i64,
25 item: String,
26}
27
28impl AgendaDoc {
29 fn new(item: &AgendaItem) -> Result<Self> {
30 Ok(Self {
31 id: item.id.clone(),
32 partition: item.partition.as_str().to_string(),
33 state: item.state.kind().as_str().to_string(),
34 created_us: item.created_at.timestamp_micros(),
35 item: serde_json::to_string(item)?,
36 })
37 }
38
39 fn decode(&self) -> Result<AgendaItem> {
40 json("agenda item", &self.item)
41 }
42}
43
44#[derive(Clone)]
67pub struct FirestoreAgendaStore {
68 db: FirestoreDb,
69}
70
71impl std::fmt::Debug for FirestoreAgendaStore {
72 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 f.debug_struct("FirestoreAgendaStore").finish_non_exhaustive()
74 }
75}
76
77impl FirestoreAgendaStore {
78 pub fn from_db(db: FirestoreDb) -> Self {
80 Self { db }
81 }
82
83 pub async fn connect(project_id: &str) -> Result<Self> {
90 Ok(Self::from_db(connect(project_id).await?))
91 }
92
93 pub fn db(&self) -> &FirestoreDb {
95 &self.db
96 }
97
98 pub async fn migrate(&self) -> Result<()> {
104 Ok(())
105 }
106}
107
108#[async_trait]
109impl AgendaStore for FirestoreAgendaStore {
110 async fn put(&self, item: AgendaItem) -> Result<()> {
111 let doc = AgendaDoc::new(&item)?;
112 self.db
113 .fluent()
114 .update()
115 .in_col(AGENDA)
116 .document_id(doc_id("agenda item", &item.id)?)
117 .object(&doc)
118 .execute::<AgendaDoc>()
119 .await
120 .map(|_| ())
121 .map_err(|error| store_error("write the agenda", &error))
122 }
123
124 async fn get(&self, id: &str) -> Result<Option<AgendaItem>> {
125 let Ok(doc_name) = doc_id("agenda item", id) else {
126 return Ok(None);
127 };
128 let doc: Option<AgendaDoc> = self
129 .db
130 .fluent()
131 .select()
132 .by_id_in(AGENDA)
133 .obj()
134 .one(doc_name)
135 .await
136 .map_err(|error| store_error("read the agenda", &error))?;
137 doc.filter(|doc| doc.id == id).as_ref().map(AgendaDoc::decode).transpose()
138 }
139
140 async fn list(&self, filter: &AgendaFilter) -> Result<Vec<AgendaItem>> {
141 if filter.limit == Some(0) {
142 return Ok(Vec::new());
143 }
144 let states: Vec<&str> = filter.states.iter().map(|state| state.as_str()).collect();
145 let mut docs: Vec<AgendaDoc> = self
146 .db
147 .fluent()
148 .select()
149 .from(AGENDA)
150 .filter(|q| {
151 q.for_all([
152 filter.partition.as_ref().and_then(|p| q.field("partition").eq(p.as_str())),
153 if states.is_empty() { None } else { q.field("state").is_in(states.clone()) },
154 ])
155 })
156 .obj()
157 .query()
158 .await
159 .map_err(|error| store_error("list the agenda", &error))?;
160 docs.sort_by(|a, b| (a.created_us, &a.id).cmp(&(b.created_us, &b.id)));
161 docs.truncate(filter.limit.unwrap_or(usize::MAX));
162 docs.iter().map(AgendaDoc::decode).collect()
163 }
164
165 async fn transition(&self, item: AgendaItem, from: AgendaStateKind) -> Result<bool> {
166 let doc_name = Arc::new(doc_id("agenda item", &item.id)?);
167 let doc = Arc::new(AgendaDoc::new(&item)?);
168 self.db
169 .run_transaction_with_options(
170 move |db, transaction| -> TxFuture<'_, bool> {
171 let (doc_name, doc) = (doc_name.clone(), doc.clone());
172 Box::pin(async move {
173 let stored: Option<AgendaDoc> = db
174 .fluent()
175 .select()
176 .by_id_in(AGENDA)
177 .obj()
178 .one(doc_name.as_str())
179 .await
180 .map_err(tx_fail("read the agenda"))?;
181 if stored.is_none_or(|stored| {
182 stored.id != doc.id || stored.state != from.as_str()
183 }) {
184 return Ok(false);
185 }
186 db.fluent()
187 .update()
188 .in_col(AGENDA)
189 .document_id(doc_name.as_str())
190 .object(doc.as_ref())
191 .add_to_transaction(transaction)
192 .map_err(tx_fail("update the agenda"))?;
193 Ok(true)
194 })
195 },
196 transaction_options(),
197 )
198 .await
199 .map_err(|error| transaction_error(error, "update the agenda"))
200 }
201
202 async fn delete(&self, id: &str) -> Result<bool> {
203 let Ok(doc_name) = doc_id("agenda item", id) else {
204 return Ok(false);
205 };
206 let id = id.to_string();
207 let matches = move |doc: &AgendaDoc| doc.id == id;
208 delete_where(&self.db, AGENDA, doc_name, matches, "delete from the agenda").await
209 }
210}