a2a_protocol_server/store/lease/
postgres.rs1use std::future::Future;
17use std::pin::Pin;
18
19use a2a_protocol_types::error::{A2aError, A2aResult};
20use sqlx::postgres::PgPool;
21
22use super::{LapsedLeases, LeaseStore};
23
24const CREATE_TABLE_SQL: &str = "CREATE TABLE IF NOT EXISTS a2a_leases (
25 tenant TEXT NOT NULL,
26 task_id TEXT NOT NULL,
27 ttl_ms BIGINT NOT NULL,
28 deadline_ms BIGINT NOT NULL,
29 PRIMARY KEY (tenant, task_id)
30)";
31
32macro_rules! now_ms {
34 () => {
35 "floor(extract(epoch from now()) * 1000)::bigint"
36 };
37}
38
39macro_rules! deadline_after {
44 ($ttl:expr) => {
45 concat!(
46 now_ms!(),
47 " + LEAST(",
48 $ttl,
49 ", 9223372036854775807 - ",
50 now_ms!(),
51 ")"
52 )
53 };
54}
55
56const GRANT_SQL: &str = concat!(
57 "INSERT INTO a2a_leases (tenant, task_id, ttl_ms, deadline_ms)
58 VALUES ($1, $2, $3, ",
59 deadline_after!("$3::bigint"),
60 ")
61 ON CONFLICT (tenant, task_id) DO UPDATE
62 SET ttl_ms = EXCLUDED.ttl_ms, deadline_ms = EXCLUDED.deadline_ms"
63);
64
65const RENEW_SQL: &str = concat!(
66 "UPDATE a2a_leases SET deadline_ms = ",
67 deadline_after!("ttl_ms"),
68 "
69 WHERE tenant = $1 AND task_id = $2"
70);
71
72const LAPSED_SQL: &str = concat!(
75 "SELECT ",
76 now_ms!(),
77 " > deadline_ms FROM a2a_leases WHERE tenant = $1 AND task_id = $2"
78);
79
80const LAPSED_MANY_SQL: &str = concat!(
83 "SELECT l.tenant, l.task_id, ",
84 now_ms!(),
85 " > l.deadline_ms FROM a2a_leases l
86 JOIN unnest($1::text[], $2::text[]) AS k(tenant, task_id)
87 ON l.tenant = k.tenant AND l.task_id = k.task_id"
88);
89
90const SWEEP_SQL: &str = concat!(
93 "DELETE FROM a2a_leases WHERE deadline_ms < ",
94 now_ms!(),
95 " - $1"
96);
97
98#[derive(Debug, Clone)]
100pub struct PostgresLeaseStore {
101 pool: PgPool,
102}
103
104impl PostgresLeaseStore {
105 pub async fn from_pool(pool: PgPool) -> A2aResult<Self> {
112 crate::store::pg_schema::apply(&pool, &[CREATE_TABLE_SQL])
113 .await
114 .map_err(|e| A2aError::internal(format!("lease store migrate: {e}")))?;
115 Ok(Self { pool })
116 }
117}
118
119fn failed(what: &str, e: &sqlx::Error) -> A2aError {
120 A2aError::internal(format!("lease store {what}: {e}"))
121}
122
123impl LeaseStore for PostgresLeaseStore {
124 fn grant<'a>(
125 &'a self,
126 tenant: &'a str,
127 task: &'a str,
128 ttl_ms: i64,
129 _deadline_ms: i64,
130 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
131 Box::pin(async move {
132 crate::store::pg_retry::checked(
135 sqlx::query(GRANT_SQL)
136 .bind(tenant)
137 .bind(task)
138 .bind(ttl_ms)
139 .execute(&self.pool),
140 )
141 .await
142 .map_err(|e| failed("grant", &e))?;
143 Ok(())
144 })
145 }
146
147 fn renew<'a>(
148 &'a self,
149 tenant: &'a str,
150 task: &'a str,
151 _now_ms: i64,
152 ) -> Pin<Box<dyn Future<Output = A2aResult<bool>> + Send + 'a>> {
153 Box::pin(async move {
154 let done = crate::store::pg_retry::retry(&crate::metrics::NoopMetrics, || {
155 sqlx::query(RENEW_SQL)
156 .bind(tenant)
157 .bind(task)
158 .execute(&self.pool)
159 })
160 .await
161 .map_err(|e| failed("renew", &e))?;
162 Ok(done.rows_affected() > 0)
163 })
164 }
165
166 fn deadline<'a>(
167 &'a self,
168 tenant: &'a str,
169 task: &'a str,
170 ) -> Pin<Box<dyn Future<Output = A2aResult<Option<i64>>> + Send + 'a>> {
171 Box::pin(async move {
172 let row: Option<(i64,)> =
173 crate::store::pg_retry::retry(&crate::metrics::NoopMetrics, || {
174 sqlx::query_as(
175 "SELECT deadline_ms FROM a2a_leases WHERE tenant = $1 AND task_id = $2",
176 )
177 .bind(tenant)
178 .bind(task)
179 .fetch_optional(&self.pool)
180 })
181 .await
182 .map_err(|e| failed("read", &e))?;
183 Ok(row.map(|(deadline,)| deadline))
184 })
185 }
186
187 fn lapsed<'a>(
188 &'a self,
189 tenant: &'a str,
190 task: &'a str,
191 ) -> Pin<Box<dyn Future<Output = A2aResult<Option<bool>>> + Send + 'a>> {
192 Box::pin(async move {
193 let row: Option<(bool,)> =
194 crate::store::pg_retry::retry(&crate::metrics::NoopMetrics, || {
195 sqlx::query_as(LAPSED_SQL)
196 .bind(tenant)
197 .bind(task)
198 .fetch_optional(&self.pool)
199 })
200 .await
201 .map_err(|e| failed("read", &e))?;
202 Ok(row.map(|(lapsed,)| lapsed))
203 })
204 }
205
206 fn lapsed_many<'a>(
207 &'a self,
208 leases: &'a [(String, String)],
209 ) -> Pin<Box<dyn Future<Output = A2aResult<LapsedLeases>> + Send + 'a>> {
210 Box::pin(async move {
211 let (tenants, tasks): (Vec<&str>, Vec<&str>) = leases
212 .iter()
213 .map(|(tenant, task)| (tenant.as_str(), task.as_str()))
214 .unzip();
215 let rows: Vec<(String, String, bool)> =
216 crate::store::pg_retry::retry(&crate::metrics::NoopMetrics, || {
217 sqlx::query_as(LAPSED_MANY_SQL)
218 .bind(&tenants)
219 .bind(&tasks)
220 .fetch_all(&self.pool)
221 })
222 .await
223 .map_err(|e| failed("read", &e))?;
224 Ok(rows
225 .into_iter()
226 .map(|(tenant, task, lapsed)| ((tenant, task), lapsed))
227 .collect())
228 })
229 }
230
231 fn release<'a>(
232 &'a self,
233 tenant: &'a str,
234 task: &'a str,
235 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
236 Box::pin(async move {
237 crate::store::pg_retry::checked(
240 sqlx::query("DELETE FROM a2a_leases WHERE tenant = $1 AND task_id = $2")
241 .bind(tenant)
242 .bind(task)
243 .execute(&self.pool),
244 )
245 .await
246 .map_err(|e| failed("release", &e))?;
247 Ok(())
248 })
249 }
250
251 fn sweep(
252 &self,
253 _now_ms: i64,
254 lapsed_for_ms: i64,
255 ) -> Pin<Box<dyn Future<Output = A2aResult<u64>> + Send + '_>> {
256 Box::pin(async move {
257 let done = crate::store::pg_retry::retry(&crate::metrics::NoopMetrics, || {
260 sqlx::query(SWEEP_SQL)
261 .bind(lapsed_for_ms)
262 .execute(&self.pool)
263 })
264 .await
265 .map_err(|e| failed("sweep", &e))?;
266 Ok(done.rows_affected())
267 })
268 }
269}