a2a_protocol_server/push/
postgres_config_store.rs1use std::future::Future;
11use std::pin::Pin;
12use std::sync::Arc;
13
14use a2a_protocol_types::error::{A2aError, A2aResult};
15use a2a_protocol_types::push::TaskPushNotificationConfig;
16use sqlx::postgres::PgPool;
17
18use super::cipher::{PushConfigCipher, Sealing};
19use super::config_store::PushConfigStore;
20
21#[derive(Debug, Clone)]
38pub struct PostgresPushConfigStore {
39 pool: PgPool,
40 sealing: Sealing,
42}
43
44#[allow(clippy::needless_pass_by_value)]
46fn to_a2a_error(e: sqlx::Error) -> A2aError {
47 crate::sql_error::sql_error(crate::sql_error::Db::Postgres, "postgres error", &e)
48}
49
50impl PostgresPushConfigStore {
51 pub async fn new(url: &str) -> Result<Self, sqlx::Error> {
57 Self::new_with_pool_size(url, crate::store::DEFAULT_POOL_SIZE).await
58 }
59
60 pub async fn new_with_pool_size(url: &str, size: u32) -> Result<Self, sqlx::Error> {
74 let size = size.max(1);
75 trace_info!(
76 pool_size = size,
77 "PostgreSQL push-config store: opening its pool"
78 );
79 let pool =
80 crate::store::pg_retry::recycling_after_failover(sqlx::postgres::PgPoolOptions::new())
81 .max_connections(size)
82 .connect(url)
83 .await?;
84 Self::from_pool(pool).await
85 }
86
87 #[must_use]
90 pub fn with_cipher(mut self, cipher: Arc<dyn PushConfigCipher>) -> Self {
91 self.sealing = self.sealing.with_cipher(cipher);
92 self
93 }
94
95 #[must_use]
99 pub fn accept_unsealed_rows(mut self) -> Self {
100 self.sealing = self.sealing.accepting_unsealed();
101 self
102 }
103
104 pub async fn from_pool(pool: PgPool) -> Result<Self, sqlx::Error> {
110 crate::store::pg_schema::apply(
113 &pool,
114 &["CREATE TABLE IF NOT EXISTS push_configs (
115 task_id TEXT NOT NULL,
116 id TEXT NOT NULL,
117 data JSONB NOT NULL,
118 PRIMARY KEY (task_id, id)
119 )"],
120 )
121 .await?;
122
123 Ok(Self {
124 pool,
125 sealing: Sealing::default(),
126 })
127 }
128}
129
130#[allow(clippy::manual_async_fn)]
131impl PushConfigStore for PostgresPushConfigStore {
132 fn set<'a>(
133 &'a self,
134 mut config: TaskPushNotificationConfig,
135 ) -> Pin<Box<dyn Future<Output = A2aResult<TaskPushNotificationConfig>> + Send + 'a>> {
136 Box::pin(async move {
137 let Some(task_id) = config.task_id.clone() else {
141 return Err(A2aError::invalid_params(
142 "taskId is required to store a push notification config",
143 ));
144 };
145 let id = config
146 .id
147 .clone()
148 .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
149 config.id = Some(id.clone());
150
151 let data = self
152 .sealing
153 .encode_json(&config, &Sealing::context("", &task_id, &id))
154 .await?;
155
156 sqlx::query(
157 "INSERT INTO push_configs (task_id, id, data)
158 VALUES ($1, $2, $3)
159 ON CONFLICT(task_id, id) DO UPDATE SET data = EXCLUDED.data",
160 )
161 .bind(&task_id)
162 .bind(&id)
163 .bind(&data)
164 .execute(&self.pool)
165 .await
166 .map_err(to_a2a_error)?;
167
168 Ok(config)
169 })
170 }
171
172 fn get<'a>(
173 &'a self,
174 task_id: &'a str,
175 id: &'a str,
176 ) -> Pin<Box<dyn Future<Output = A2aResult<Option<TaskPushNotificationConfig>>> + Send + 'a>>
177 {
178 Box::pin(async move {
179 let row: Option<(serde_json::Value,)> =
180 sqlx::query_as("SELECT data FROM push_configs WHERE task_id = $1 AND id = $2")
181 .bind(task_id)
182 .bind(id)
183 .fetch_optional(&self.pool)
184 .await
185 .map_err(to_a2a_error)?;
186
187 match row {
188 Some((data,)) => Ok(Some(
189 self.sealing
190 .decode_json(data, &Sealing::context("", task_id, id))
191 .await?,
192 )),
193 None => Ok(None),
194 }
195 })
196 }
197
198 fn list<'a>(
199 &'a self,
200 task_id: &'a str,
201 ) -> Pin<Box<dyn Future<Output = A2aResult<Vec<TaskPushNotificationConfig>>> + Send + 'a>> {
202 Box::pin(async move {
203 let rows: Vec<(String, serde_json::Value)> =
204 sqlx::query_as("SELECT id, data FROM push_configs WHERE task_id = $1")
205 .bind(task_id)
206 .fetch_all(&self.pool)
207 .await
208 .map_err(to_a2a_error)?;
209
210 let mut configs = Vec::with_capacity(rows.len());
211 for (id, data) in rows {
212 configs.push(
213 self.sealing
214 .decode_json(data, &Sealing::context("", task_id, &id))
215 .await?,
216 );
217 }
218 Ok(configs)
219 })
220 }
221
222 fn delete<'a>(
223 &'a self,
224 task_id: &'a str,
225 id: &'a str,
226 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
227 Box::pin(async move {
228 sqlx::query("DELETE FROM push_configs WHERE task_id = $1 AND id = $2")
229 .bind(task_id)
230 .bind(id)
231 .execute(&self.pool)
232 .await
233 .map_err(to_a2a_error)?;
234 Ok(())
235 })
236 }
237
238 fn count(&self) -> Pin<Box<dyn Future<Output = A2aResult<Option<usize>>> + Send + '_>> {
239 Box::pin(async move {
240 let (total,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM push_configs")
241 .fetch_one(&self.pool)
242 .await
243 .map_err(to_a2a_error)?;
244 Ok(Some(usize::try_from(total).unwrap_or(usize::MAX)))
245 })
246 }
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 #[tokio::test]
257 #[ignore = "needs a live PostgreSQL (A2A_TEST_POSTGRES_URL)"]
258 async fn the_pool_is_the_size_asked_for() {
259 let url = std::env::var("A2A_TEST_POSTGRES_URL").expect("A2A_TEST_POSTGRES_URL");
260 for (asked, opened) in [(3, 3), (0, 1)] {
261 let store = PostgresPushConfigStore::new_with_pool_size(&url, asked)
262 .await
263 .expect("store");
264 assert_eq!(
265 store.pool.options().get_max_connections(),
266 opened,
267 "{asked}"
268 );
269 store.pool.close().await;
270 }
271 let store = PostgresPushConfigStore::new(&url).await.expect("store");
272 assert_eq!(
273 store.pool.options().get_max_connections(),
274 crate::store::DEFAULT_POOL_SIZE
275 );
276 }
277
278 #[test]
279 fn to_a2a_error_formats_message() {
280 let pg_err = sqlx::Error::RowNotFound;
281 let a2a_err = to_a2a_error(pg_err);
282 let msg = format!("{a2a_err}");
283 assert!(
284 msg.contains("postgres error"),
285 "error message should contain 'postgres error': {msg}"
286 );
287 }
288}