1use a2a_protocol_types::audit::{AuditRecord, Checkpoint};
9use a2a_protocol_types::error::A2aResult;
10use sqlx::Row;
11use sqlx::postgres::PgPool;
12
13use super::store::{
14 Appended, AuditStore, BoxFuture, LegalHold, NamedAppend, Sealer, SubjectKey, record_millis,
15};
16
17mod fence;
18mod sql;
19use sql::{INSERT_SQL, LOCK_CHAIN_SQL, SCHEMA, db, i64_of, json, parse, u64_of};
20
21#[derive(Debug, Clone)]
42pub struct PostgresAuditStore {
43 pool: PgPool,
44}
45
46impl PostgresAuditStore {
47 pub async fn new(url: &str) -> Result<Self, sqlx::Error> {
53 Self::from_pool(crate::store::postgres_store::pool::pg_pool(url).await?).await
54 }
55
56 pub async fn from_pool(pool: PgPool) -> Result<Self, sqlx::Error> {
62 crate::store::pg_schema::apply(&pool, &SCHEMA).await?;
65 Ok(Self { pool })
66 }
67}
68
69impl AuditStore for PostgresAuditStore {
70 fn head<'a>(&'a self, chain: &'a str) -> BoxFuture<'a, A2aResult<Option<(u64, String)>>> {
71 Box::pin(async move {
72 let row = sqlx::query(
73 "SELECT seq, hash FROM a2a_audit_records WHERE chain = $1 ORDER BY seq DESC LIMIT 1",
74 )
75 .bind(chain)
76 .fetch_optional(&self.pool)
77 .await
78 .map_err(|e| db(&e))?;
79 Ok(row.map(|r| (u64_of(r.get::<i64, _>(0)), r.get::<String, _>(1))))
80 })
81 }
82
83 fn append<'a>(&'a self, record: &'a AuditRecord) -> BoxFuture<'a, A2aResult<Appended>> {
84 Box::pin(async move {
85 let done = sqlx::query(INSERT_SQL)
86 .bind(&record.chain)
87 .bind(i64_of(record.seq))
88 .bind(record_millis(record))
89 .bind(&record.hash)
90 .bind(json(record)?)
91 .execute(&self.pool)
92 .await
93 .map_err(|e| db(&e))?;
94 Ok(if done.rows_affected() == 1 {
95 Appended::Stored
96 } else {
97 Appended::Conflict
98 })
99 })
100 }
101
102 fn append_next<'a>(
112 &'a self,
113 chain: &'a str,
114 seal: &'a Sealer<'a>,
115 ) -> BoxFuture<'a, A2aResult<Option<AuditRecord>>> {
116 Box::pin(async move {
117 Ok(
118 match fence::append_next(&self.pool, chain, &[], seal).await? {
119 NamedAppend::Stored(record) => Some(*record),
120 _ => None,
121 },
122 )
123 })
124 }
125
126 fn read<'a>(
127 &'a self,
128 chain: &'a str,
129 after: u64,
130 limit: usize,
131 ) -> BoxFuture<'a, A2aResult<Vec<AuditRecord>>> {
132 Box::pin(async move {
133 let rows = sqlx::query(
134 "SELECT record FROM a2a_audit_records WHERE chain = $1 AND seq > $2
135 ORDER BY seq LIMIT $3",
136 )
137 .bind(chain)
138 .bind(i64_of(after))
139 .bind(i64::try_from(limit).unwrap_or(i64::MAX))
140 .fetch_all(&self.pool)
141 .await
142 .map_err(|e| db(&e))?;
143 rows.iter().map(|r| parse(&r.get::<String, _>(0))).collect()
144 })
145 }
146
147 fn chains(&self) -> BoxFuture<'_, A2aResult<Vec<String>>> {
148 Box::pin(async move {
149 let rows = sqlx::query(
150 "SELECT chain FROM a2a_audit_records UNION SELECT chain FROM a2a_audit_checkpoints
151 ORDER BY chain",
152 )
153 .fetch_all(&self.pool)
154 .await
155 .map_err(|e| db(&e))?;
156 Ok(rows.iter().map(|r| r.get::<String, _>(0)).collect())
157 })
158 }
159
160 fn put_checkpoint<'a>(&'a self, checkpoint: &'a Checkpoint) -> BoxFuture<'a, A2aResult<()>> {
161 Box::pin(async move {
162 sqlx::query(
163 "INSERT INTO a2a_audit_checkpoints (chain, seq, kind, checkpoint) VALUES ($1, $2, $3, $4)
164 ON CONFLICT (chain, seq, kind) DO UPDATE SET checkpoint = excluded.checkpoint",
165 )
166 .bind(&checkpoint.chain)
167 .bind(i64_of(checkpoint.seq))
168 .bind(&checkpoint.kind)
169 .bind(json(checkpoint)?)
170 .execute(&self.pool)
171 .await
172 .map_err(|e| db(&e))?;
173 Ok(())
174 })
175 }
176
177 fn checkpoints<'a>(&'a self, chain: &'a str) -> BoxFuture<'a, A2aResult<Vec<Checkpoint>>> {
178 Box::pin(async move {
179 let rows = sqlx::query(
180 "SELECT checkpoint FROM a2a_audit_checkpoints WHERE chain = $1 ORDER BY seq, kind",
181 )
182 .bind(chain)
183 .fetch_all(&self.pool)
184 .await
185 .map_err(|e| db(&e))?;
186 rows.iter().map(|r| parse(&r.get::<String, _>(0))).collect()
187 })
188 }
189
190 fn last_before<'a>(
191 &'a self,
192 chain: &'a str,
193 cutoff_ms: i64,
194 ) -> BoxFuture<'a, A2aResult<Option<(u64, String)>>> {
195 Box::pin(async move {
196 let row = sqlx::query(
200 "SELECT seq, hash FROM a2a_audit_records
201 WHERE chain = $1 AND seq < COALESCE(
202 (SELECT MIN(seq) FROM a2a_audit_records WHERE chain = $1 AND time_ms >= $2),
203 9223372036854775807::BIGINT)
204 ORDER BY seq DESC LIMIT 1",
205 )
206 .bind(chain)
207 .bind(cutoff_ms)
208 .fetch_optional(&self.pool)
209 .await
210 .map_err(|e| db(&e))?;
211 Ok(row.map(|r| (u64_of(r.get::<i64, _>(0)), r.get::<String, _>(1))))
212 })
213 }
214
215 fn delete_through<'a>(&'a self, chain: &'a str, seq: u64) -> BoxFuture<'a, A2aResult<u64>> {
216 Box::pin(async move {
217 let mut tx = self.pool.begin().await.map_err(|e| db(&e))?;
218 let done = sqlx::query("DELETE FROM a2a_audit_records WHERE chain = $1 AND seq <= $2")
219 .bind(chain)
220 .bind(i64_of(seq))
221 .execute(&mut *tx)
222 .await
223 .map_err(|e| db(&e))?;
224 sqlx::query("DELETE FROM a2a_audit_checkpoints WHERE chain = $1 AND seq < $2")
225 .bind(chain)
226 .bind(i64_of(seq))
227 .execute(&mut *tx)
228 .await
229 .map_err(|e| db(&e))?;
230 tx.commit().await.map_err(|e| db(&e))?;
231 Ok(done.rows_affected())
232 })
233 }
234
235 fn delete_through_unless_held<'a>(
239 &'a self,
240 chain: &'a str,
241 seq: u64,
242 ) -> BoxFuture<'a, A2aResult<Option<u64>>> {
243 Box::pin(async move {
244 let mut tx = self.pool.begin().await.map_err(|e| db(&e))?;
245 sqlx::query(LOCK_CHAIN_SQL)
246 .bind(chain)
247 .execute(&mut *tx)
248 .await
249 .map_err(|e| db(&e))?;
250 let held: bool = sqlx::query_scalar(
251 "SELECT EXISTS (SELECT 1 FROM a2a_audit_holds WHERE chain = $1)",
252 )
253 .bind(chain)
254 .fetch_one(&mut *tx)
255 .await
256 .map_err(|e| db(&e))?;
257 if held {
258 tx.rollback().await.map_err(|e| db(&e))?;
259 return Ok(None);
260 }
261 let done = sqlx::query("DELETE FROM a2a_audit_records WHERE chain = $1 AND seq <= $2")
262 .bind(chain)
263 .bind(i64_of(seq))
264 .execute(&mut *tx)
265 .await
266 .map_err(|e| db(&e))?;
267 sqlx::query("DELETE FROM a2a_audit_checkpoints WHERE chain = $1 AND seq < $2")
268 .bind(chain)
269 .bind(i64_of(seq))
270 .execute(&mut *tx)
271 .await
272 .map_err(|e| db(&e))?;
273 tx.commit().await.map_err(|e| db(&e))?;
274 Ok(Some(done.rows_affected()))
275 })
276 }
277
278 fn place_hold<'a>(&'a self, hold: &'a LegalHold) -> BoxFuture<'a, A2aResult<()>> {
279 Box::pin(async move {
280 let mut tx = self.pool.begin().await.map_err(|e| db(&e))?;
283 sqlx::query(LOCK_CHAIN_SQL)
284 .bind(&hold.chain)
285 .execute(&mut *tx)
286 .await
287 .map_err(|e| db(&e))?;
288 sqlx::query(
289 "INSERT INTO a2a_audit_holds (chain, reason, placed_at) VALUES ($1, $2, $3)
290 ON CONFLICT (chain) DO UPDATE SET reason = excluded.reason, placed_at = excluded.placed_at",
291 )
292 .bind(&hold.chain)
293 .bind(&hold.reason)
294 .bind(&hold.placed_at)
295 .execute(&mut *tx)
296 .await
297 .map_err(|e| db(&e))?;
298 tx.commit().await.map_err(|e| db(&e))?;
299 Ok(())
300 })
301 }
302
303 fn release_hold<'a>(&'a self, chain: &'a str) -> BoxFuture<'a, A2aResult<bool>> {
304 Box::pin(async move {
305 let done = sqlx::query("DELETE FROM a2a_audit_holds WHERE chain = $1")
306 .bind(chain)
307 .execute(&self.pool)
308 .await
309 .map_err(|e| db(&e))?;
310 Ok(done.rows_affected() > 0)
311 })
312 }
313
314 fn holds(&self) -> BoxFuture<'_, A2aResult<Vec<LegalHold>>> {
315 Box::pin(async move {
316 let rows =
317 sqlx::query("SELECT chain, reason, placed_at FROM a2a_audit_holds ORDER BY chain")
318 .fetch_all(&self.pool)
319 .await
320 .map_err(|e| db(&e))?;
321 Ok(rows
322 .iter()
323 .map(|r| LegalHold {
324 chain: r.get(0),
325 reason: r.get(1),
326 placed_at: r.get(2),
327 })
328 .collect())
329 })
330 }
331
332 fn supports_subject_keys(&self) -> bool {
333 true
334 }
335
336 fn subject_key<'a>(
337 &'a self,
338 chain: &'a str,
339 lookup: &'a str,
340 ) -> BoxFuture<'a, A2aResult<Option<SubjectKey>>> {
341 Box::pin(async move { self.subject_key_where("lookup", chain, lookup).await })
342 }
343
344 fn subject_key_by_sid<'a>(
345 &'a self,
346 chain: &'a str,
347 sid: &'a str,
348 ) -> BoxFuture<'a, A2aResult<Option<SubjectKey>>> {
349 Box::pin(async move { self.subject_key_where("sid", chain, sid).await })
350 }
351
352 fn subject_keys<'a>(&'a self, chain: &'a str) -> BoxFuture<'a, A2aResult<Vec<SubjectKey>>> {
353 Box::pin(async move {
354 let rows = sqlx::query(
355 "SELECT lookup, sid, wrapped FROM a2a_audit_subject_keys WHERE chain = $1 ORDER BY sid",
356 )
357 .bind(chain)
358 .fetch_all(&self.pool)
359 .await
360 .map_err(|e| db(&e))?;
361 Ok(rows
362 .iter()
363 .map(|r| {
364 SubjectKey::new(
365 r.get::<String, _>(0),
366 r.get::<String, _>(1),
367 r.get::<String, _>(2),
368 )
369 })
370 .collect())
371 })
372 }
373
374 fn put_subject_key<'a>(
375 &'a self,
376 chain: &'a str,
377 key: &'a SubjectKey,
378 ) -> BoxFuture<'a, A2aResult<bool>> {
379 Box::pin(async move {
380 let done = sqlx::query(
381 "INSERT INTO a2a_audit_subject_keys (chain, lookup, sid, wrapped) VALUES ($1, $2, $3, $4)
382 ON CONFLICT (chain, lookup) DO NOTHING",
383 )
384 .bind(chain)
385 .bind(&key.lookup)
386 .bind(&key.sid)
387 .bind(&key.wrapped)
388 .execute(&self.pool)
389 .await
390 .map_err(|e| db(&e))?;
391 Ok(done.rows_affected() == 1)
392 })
393 }
394
395 fn delete_subject_key<'a>(
396 &'a self,
397 chain: &'a str,
398 lookup: &'a str,
399 ) -> BoxFuture<'a, A2aResult<Option<String>>> {
400 Box::pin(async move {
401 let row = sqlx::query(
402 "DELETE FROM a2a_audit_subject_keys WHERE chain = $1 AND lookup = $2 RETURNING sid",
403 )
404 .bind(chain)
405 .bind(lookup)
406 .fetch_optional(&self.pool)
407 .await
408 .map_err(|e| db(&e))?;
409 Ok(row.map(|r| r.get(0)))
410 })
411 }
412
413 fn append_next_naming<'a>(
415 &'a self,
416 chain: &'a str,
417 sids: &'a [String],
418 seal: &'a Sealer<'a>,
419 ) -> BoxFuture<'a, A2aResult<NamedAppend>> {
420 Box::pin(fence::append_next(&self.pool, chain, sids, seal))
421 }
422
423 fn delete_subject_key_unless_named<'a>(
424 &'a self,
425 chain: &'a str,
426 lookup: &'a str,
427 sid: &'a str,
428 scanned_through: u64,
429 ) -> BoxFuture<'a, A2aResult<bool>> {
430 Box::pin(fence::delete_key_unless_named(
431 &self.pool,
432 chain,
433 lookup,
434 sid,
435 scanned_through,
436 ))
437 }
438
439 fn delete_subject_keys_unless_held<'a>(
440 &'a self,
441 chain: &'a str,
442 lookups: &'a [String],
443 ) -> BoxFuture<'a, A2aResult<Option<Vec<String>>>> {
444 Box::pin(fence::delete_keys_unless_held(&self.pool, chain, lookups))
445 }
446}
447
448impl PostgresAuditStore {
449 async fn subject_key_where(
451 &self,
452 column: &'static str,
453 chain: &str,
454 value: &str,
455 ) -> A2aResult<Option<SubjectKey>> {
456 let sql = format!(
457 "SELECT lookup, sid, wrapped FROM a2a_audit_subject_keys WHERE chain = $1 AND {column} = $2"
458 );
459 let row = sqlx::query(sqlx::AssertSqlSafe(sql))
461 .bind(chain)
462 .bind(value)
463 .fetch_optional(&self.pool)
464 .await
465 .map_err(|e| db(&e))?;
466 Ok(row.map(|r| {
467 SubjectKey::new(
468 r.get::<String, _>(0),
469 r.get::<String, _>(1),
470 r.get::<String, _>(2),
471 )
472 }))
473 }
474}