a2a_protocol_server/store/
database.rs1#[derive(Debug, Clone, PartialEq, Eq)]
16#[non_exhaustive]
17pub struct StoreDatabase {
18 pub system: String,
21 pub namespace: Option<String>,
23 pub address: Option<String>,
26 pub port: Option<u16>,
29}
30
31impl StoreDatabase {
32 #[must_use]
34 pub fn new(system: impl Into<String>) -> Self {
35 Self {
36 system: system.into(),
37 namespace: None,
38 address: None,
39 port: None,
40 }
41 }
42
43 #[must_use]
45 pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
46 self.namespace = Some(namespace.into());
47 self
48 }
49
50 #[must_use]
52 pub fn with_server(mut self, address: impl Into<String>, port: Option<u16>) -> Self {
53 self.address = Some(address.into());
54 self.port = port;
55 self
56 }
57
58 #[cfg(feature = "postgres")]
61 pub(crate) fn postgres(pool: &sqlx::PgPool) -> Self {
62 let options = pool.connect_options();
63 let mut db = Self::new("postgresql");
64 if let Some(name) = options.get_database() {
65 db = db.with_namespace(name);
66 }
67 let address = options.get_socket().map_or_else(
68 || options.get_host().to_owned(),
69 |s| s.display().to_string(),
70 );
71 let port = Some(options.get_port()).filter(|p| *p != 5432);
72 db.with_server(address, port)
73 }
74
75 #[cfg(feature = "sqlite")]
78 pub(crate) fn sqlite() -> Self {
79 Self::new("sqlite")
80 }
81}
82
83#[cfg(all(
86 test,
87 any(feature = "tracing", feature = "audit", feature = "encryption")
88))]
89pub struct DeclaresDatabase(pub super::InMemoryTaskStore);
90
91#[cfg(all(
92 test,
93 any(feature = "tracing", feature = "audit", feature = "encryption")
94))]
95impl DeclaresDatabase {
96 pub fn declared() -> StoreDatabase {
97 StoreDatabase::new("redis").with_server("cache.internal", None)
98 }
99}
100
101#[cfg(all(
102 test,
103 any(feature = "tracing", feature = "audit", feature = "encryption")
104))]
105impl super::TaskStore for DeclaresDatabase {
106 fn save<'a>(
107 &'a self,
108 task: &'a a2a_protocol_types::task::Task,
109 ) -> std::pin::Pin<
110 Box<dyn std::future::Future<Output = a2a_protocol_types::error::A2aResult<()>> + Send + 'a>,
111 > {
112 self.0.save(task)
113 }
114 fn get<'a>(
115 &'a self,
116 id: &'a a2a_protocol_types::task::TaskId,
117 ) -> std::pin::Pin<
118 Box<
119 dyn std::future::Future<
120 Output = a2a_protocol_types::error::A2aResult<
121 Option<a2a_protocol_types::task::Task>,
122 >,
123 > + Send
124 + 'a,
125 >,
126 > {
127 self.0.get(id)
128 }
129 fn list<'a>(
130 &'a self,
131 params: &'a a2a_protocol_types::params::ListTasksParams,
132 ) -> std::pin::Pin<
133 Box<
134 dyn std::future::Future<
135 Output = a2a_protocol_types::error::A2aResult<
136 a2a_protocol_types::responses::TaskListResponse,
137 >,
138 > + Send
139 + 'a,
140 >,
141 > {
142 self.0.list(params)
143 }
144 fn insert_if_absent<'a>(
145 &'a self,
146 task: &'a a2a_protocol_types::task::Task,
147 ) -> std::pin::Pin<
148 Box<
149 dyn std::future::Future<Output = a2a_protocol_types::error::A2aResult<bool>>
150 + Send
151 + 'a,
152 >,
153 > {
154 self.0.insert_if_absent(task)
155 }
156 fn delete<'a>(
157 &'a self,
158 id: &'a a2a_protocol_types::task::TaskId,
159 ) -> std::pin::Pin<
160 Box<dyn std::future::Future<Output = a2a_protocol_types::error::A2aResult<()>> + Send + 'a>,
161 > {
162 self.0.delete(id)
163 }
164 fn database(&self) -> Option<StoreDatabase> {
165 Some(Self::declared())
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 #[cfg(any(feature = "tracing", feature = "audit", feature = "encryption"))]
177 #[tokio::test]
178 async fn the_declaring_test_store_forwards_every_operation() {
179 use a2a_protocol_types::params::ListTasksParams;
180 use a2a_protocol_types::task::{Task, TaskId, TaskState, TaskStatus};
181
182 use crate::store::TaskStore as _;
183
184 let store = DeclaresDatabase(crate::store::InMemoryTaskStore::new());
185 let task = Task::new("t-1", "c-1", TaskStatus::new(TaskState::Working));
186 let id = TaskId::new("t-1");
187 assert!(store.insert_if_absent(&task).await.unwrap());
188 assert!(
189 !store.insert_if_absent(&task).await.unwrap(),
190 "already there"
191 );
192 assert_eq!(
193 store.get(&id).await.unwrap().map(|t| t.id),
194 Some(id.clone())
195 );
196 let mut done = task.clone();
197 done.status = TaskStatus::new(TaskState::Completed);
198 store.save(&done).await.unwrap();
199 let stored = store.get(&id).await.unwrap().expect("stored");
200 assert_eq!(stored.status.state, TaskState::Completed);
201 let listed = store.list(&ListTasksParams::default()).await.unwrap();
202 assert_eq!(listed.tasks.len(), 1);
203 store.delete(&id).await.unwrap();
204 assert_eq!(store.get(&id).await.unwrap(), None);
205 }
206
207 #[test]
208 fn a_database_carries_what_it_was_given() {
209 let db = StoreDatabase::new("redis")
210 .with_namespace("0")
211 .with_server("cache.internal", Some(6380));
212 assert_eq!(db.system, "redis");
213 assert_eq!(db.namespace.as_deref(), Some("0"));
214 assert_eq!(db.address.as_deref(), Some("cache.internal"));
215 assert_eq!(db.port, Some(6380));
216 assert_eq!(StoreDatabase::new("redis").namespace, None);
217 }
218
219 #[cfg(feature = "sqlite")]
220 #[tokio::test]
221 async fn the_sqlite_stores_name_sqlite() {
222 use crate::store::TaskStore as _;
223 let plain = crate::store::SqliteTaskStore::new("sqlite::memory:")
224 .await
225 .unwrap();
226 assert_eq!(plain.database(), Some(StoreDatabase::new("sqlite")));
227 let tenants = crate::store::TenantAwareSqliteTaskStore::new("sqlite::memory:")
228 .await
229 .unwrap();
230 assert_eq!(tenants.database(), Some(StoreDatabase::new("sqlite")));
231 }
232
233 #[test]
234 fn the_in_memory_stores_name_no_database() {
235 use crate::store::TaskStore as _;
236 assert_eq!(crate::store::InMemoryTaskStore::new().database(), None);
237 assert_eq!(
238 crate::store::TenantAwareInMemoryTaskStore::new().database(),
239 None
240 );
241 }
242
243 #[cfg(feature = "postgres")]
244 #[tokio::test]
245 async fn a_postgres_pool_names_its_database_host_and_a_non_default_port() {
246 let at = |url: &str| StoreDatabase::postgres(&sqlx::PgPool::connect_lazy(url).unwrap());
247 let db = at("postgres://u:[email protected]:6543/a2a");
248 assert_eq!(db.system, "postgresql");
249 assert_eq!(db.namespace.as_deref(), Some("a2a"));
250 assert_eq!(db.address.as_deref(), Some("db.internal"));
251 assert_eq!(db.port, Some(6543));
252 let db = at("postgres://u:[email protected]/a2a");
253 assert_eq!(db.port, None, "5432 is PostgreSQL's default");
254 }
255}