a2a_protocol_server/push/
tenant_postgres_config_store.rs1mod caller_keys;
14
15use std::future::Future;
16use std::pin::Pin;
17use std::sync::Arc;
18
19use a2a_protocol_types::error::{A2aError, A2aResult};
20use a2a_protocol_types::push::TaskPushNotificationConfig;
21use sqlx::postgres::PgPool;
22
23use super::cipher::{PushConfigCipher, Sealing};
24use super::config_store::PushConfigStore;
25use crate::store::tenant::TenantContext;
26
27#[derive(Debug, Clone)]
45pub struct TenantAwarePostgresPushConfigStore {
46 pool: PgPool,
47 sealing: Sealing,
49}
50
51fn to_a2a_error(e: &sqlx::Error) -> A2aError {
52 crate::sql_error::sql_error(crate::sql_error::Db::Postgres, "postgres error", e)
53}
54
55impl TenantAwarePostgresPushConfigStore {
56 pub async fn new(url: &str) -> Result<Self, sqlx::Error> {
62 Self::new_with_pool_size(url, crate::store::DEFAULT_POOL_SIZE).await
63 }
64
65 pub async fn new_with_pool_size(url: &str, size: u32) -> Result<Self, sqlx::Error> {
79 let size = size.max(1);
80 trace_info!(
81 pool_size = size,
82 "PostgreSQL tenant push-config store: opening its pool"
83 );
84 let pool =
85 crate::store::pg_retry::recycling_after_failover(sqlx::postgres::PgPoolOptions::new())
86 .max_connections(size)
87 .connect(url)
88 .await?;
89 Self::from_pool(pool).await
90 }
91
92 #[must_use]
95 pub fn with_cipher(mut self, cipher: Arc<dyn PushConfigCipher>) -> Self {
96 self.sealing = self.sealing.with_cipher(cipher);
97 self
98 }
99
100 #[must_use]
104 pub fn accept_unsealed_rows(mut self) -> Self {
105 self.sealing = self.sealing.accepting_unsealed();
106 self
107 }
108
109 pub async fn from_pool(pool: PgPool) -> Result<Self, sqlx::Error> {
115 crate::store::pg_schema::apply(
118 &pool,
119 &["CREATE TABLE IF NOT EXISTS tenant_push_configs (
120 tenant_id TEXT NOT NULL DEFAULT '',
121 task_id TEXT NOT NULL,
122 id TEXT NOT NULL,
123 data JSONB NOT NULL,
124 PRIMARY KEY (tenant_id, task_id, id)
125 )"],
126 )
127 .await?;
128
129 Ok(Self {
130 pool,
131 sealing: Sealing::default(),
132 })
133 }
134}
135
136#[allow(clippy::manual_async_fn)]
137impl PushConfigStore for TenantAwarePostgresPushConfigStore {
138 fn isolates_tenants(&self) -> bool {
139 true
140 }
141
142 fn set<'a>(
143 &'a self,
144 mut config: TaskPushNotificationConfig,
145 ) -> Pin<Box<dyn Future<Output = A2aResult<TaskPushNotificationConfig>> + Send + 'a>> {
146 Box::pin(async move {
147 let tenant = TenantContext::partition();
148 let Some(task_id) = config.task_id.clone() else {
152 return Err(A2aError::invalid_params(
153 "taskId is required to store a push notification config",
154 ));
155 };
156 let id = config
157 .id
158 .clone()
159 .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
160 config.id = Some(id.clone());
161
162 let data = self
163 .sealing
164 .encode_json(&config, &Sealing::context(&tenant, &task_id, &id))
165 .await?;
166
167 sqlx::query(
168 "INSERT INTO tenant_push_configs (tenant_id, task_id, id, data)
169 VALUES ($1, $2, $3, $4)
170 ON CONFLICT(tenant_id, task_id, id) DO UPDATE SET data = EXCLUDED.data",
171 )
172 .bind(&tenant)
173 .bind(&task_id)
174 .bind(&id)
175 .bind(&data)
176 .execute(&self.pool)
177 .await
178 .map_err(|e| to_a2a_error(&e))?;
179
180 Ok(config)
181 })
182 }
183
184 fn get<'a>(
185 &'a self,
186 task_id: &'a str,
187 id: &'a str,
188 ) -> Pin<Box<dyn Future<Output = A2aResult<Option<TaskPushNotificationConfig>>> + Send + 'a>>
189 {
190 Box::pin(async move {
191 let tenant = TenantContext::partition();
192 let row: Option<(serde_json::Value,)> = sqlx::query_as(
193 "SELECT data FROM tenant_push_configs WHERE tenant_id = $1 AND task_id = $2 AND id = $3",
194 )
195 .bind(&tenant)
196 .bind(task_id)
197 .bind(id)
198 .fetch_optional(&self.pool)
199 .await
200 .map_err(|e| to_a2a_error(&e))?;
201
202 match row {
203 Some((data,)) => Ok(Some(
204 self.sealing
205 .decode_json(data, &Sealing::context(&tenant, task_id, id))
206 .await?,
207 )),
208 None => Ok(None),
209 }
210 })
211 }
212
213 fn list<'a>(
214 &'a self,
215 task_id: &'a str,
216 ) -> Pin<Box<dyn Future<Output = A2aResult<Vec<TaskPushNotificationConfig>>> + Send + 'a>> {
217 Box::pin(async move {
218 let tenant = TenantContext::partition();
219 let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(
220 "SELECT id, data FROM tenant_push_configs WHERE tenant_id = $1 AND task_id = $2",
221 )
222 .bind(&tenant)
223 .bind(task_id)
224 .fetch_all(&self.pool)
225 .await
226 .map_err(|e| to_a2a_error(&e))?;
227
228 let mut configs = Vec::with_capacity(rows.len());
229 for (id, data) in rows {
230 configs.push(
231 self.sealing
232 .decode_json(data, &Sealing::context(&tenant, task_id, &id))
233 .await?,
234 );
235 }
236 Ok(configs)
237 })
238 }
239
240 fn delete<'a>(
241 &'a self,
242 task_id: &'a str,
243 id: &'a str,
244 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
245 Box::pin(async move {
246 let tenant = TenantContext::partition();
247 sqlx::query(
248 "DELETE FROM tenant_push_configs WHERE tenant_id = $1 AND task_id = $2 AND id = $3",
249 )
250 .bind(&tenant)
251 .bind(task_id)
252 .bind(id)
253 .execute(&self.pool)
254 .await
255 .map_err(|e| to_a2a_error(&e))?;
256 Ok(())
257 })
258 }
259
260 fn count(&self) -> Pin<Box<dyn Future<Output = A2aResult<Option<usize>>> + Send + '_>> {
261 Box::pin(async move {
262 let tenant = TenantContext::partition();
264 let (total,): (i64,) =
265 sqlx::query_as("SELECT COUNT(*) FROM tenant_push_configs WHERE tenant_id = $1")
266 .bind(&tenant)
267 .fetch_one(&self.pool)
268 .await
269 .map_err(|e| to_a2a_error(&e))?;
270 Ok(Some(usize::try_from(total).unwrap_or(usize::MAX)))
271 })
272 }
273}
274
275#[cfg(test)]
276mod tests {
277 use super::*;
278
279 #[test]
280 fn to_a2a_error_formats_message() {
281 let pg_err = sqlx::Error::RowNotFound;
282 let a2a_err = to_a2a_error(&pg_err);
283 let msg = format!("{a2a_err}");
284 assert!(
285 msg.contains("postgres error"),
286 "error message should contain 'postgres error': {msg}"
287 );
288 }
289}