1use std::sync::Arc;
16use std::time::Duration;
17
18use adk_core::{
19 Clock, DEFAULT_RESERVATION_TTL, ReservationId, Result, SpendError, SpendKey, SpendLedger,
20 SpendLimits, SpendPeriod, SystemClock,
21};
22use chrono::{DateTime, Utc};
23
24const STATE_RESERVED: &str = "reserved";
25const STATE_COMMITTED: &str = "committed";
26const STATE_RELEASED: &str = "released";
27
28fn unavailable(error: impl std::fmt::Display) -> adk_core::AdkError {
29 SpendError::Unavailable(error.to_string()).into()
30}
31
32fn stored_amount(amount_micro_usd: u64) -> Result<i64> {
33 i64::try_from(amount_micro_usd).map_err(|_| SpendError::AmountTooLarge(amount_micro_usd).into())
34}
35
36fn window_start_micros(period: SpendPeriod, now: DateTime<Utc>) -> i64 {
38 period.window_start(now).map_or(i64::MIN, |start| start.timestamp_micros())
39}
40
41fn expires_at_micros(now: DateTime<Utc>, ttl: Duration) -> i64 {
42 let ttl = i64::try_from(ttl.as_micros()).unwrap_or(i64::MAX);
43 now.timestamp_micros().saturating_add(ttl)
44}
45
46fn limit_exceeded(
47 limit: &adk_core::SpendLimit,
48 consumed: i64,
49 requested: u64,
50) -> Option<adk_core::AdkError> {
51 let consumed = u64::try_from(consumed).unwrap_or(0);
52 (consumed.saturating_add(requested) > limit.max_micro_usd).then(|| {
53 SpendError::LimitExceeded {
54 limit: limit.key.clone(),
55 max_micro_usd: limit.max_micro_usd,
56 consumed_micro_usd: consumed,
57 requested_micro_usd: requested,
58 }
59 .into()
60 })
61}
62
63#[cfg(feature = "sqlite")]
64mod sqlite {
65 use super::*;
66 use sqlx::{Row, sqlite::SqlitePool};
67
68 const REGISTRY_TABLE: &str = "_adk_spend_migrations";
69
70 const MIGRATIONS: &[(i64, &str, &str)] = &[(
71 1,
72 "create spend ledger entries",
73 "\
74CREATE TABLE IF NOT EXISTS adk_spend_entries (\
75 id TEXT PRIMARY KEY, \
76 org TEXT NOT NULL, \
77 agent TEXT, \
78 vendor TEXT, \
79 state TEXT NOT NULL, \
80 reserved_micro_usd INTEGER NOT NULL, \
81 committed_micro_usd INTEGER, \
82 created_at_us INTEGER NOT NULL, \
83 expires_at_us INTEGER NOT NULL, \
84 settled_at_us INTEGER\
85);\
86CREATE INDEX IF NOT EXISTS adk_spend_entries_org_state ON adk_spend_entries (org, state);",
87 )];
88
89 const CONSUMED: &str = "\
91SELECT COALESCE(SUM(CASE \
92 WHEN state = 'committed' AND settled_at_us >= ?1 THEN committed_micro_usd \
93 WHEN state = 'reserved' AND expires_at_us > ?2 THEN reserved_micro_usd \
94 ELSE 0 END), 0) AS consumed \
95FROM adk_spend_entries \
96WHERE org = ?3 AND (?4 IS NULL OR agent = ?4) AND (?5 IS NULL OR vendor = ?5)";
97
98 const SPENT: &str = "\
99SELECT COALESCE(SUM(committed_micro_usd), 0) AS spent \
100FROM adk_spend_entries \
101WHERE state = 'committed' AND settled_at_us >= ?1 \
102 AND org = ?2 AND (?3 IS NULL OR agent = ?3) AND (?4 IS NULL OR vendor = ?4)";
103
104 #[derive(Debug)]
123 pub struct SqliteSpendLedger {
124 pool: SqlitePool,
125 limits: SpendLimits,
126 ttl: Duration,
127 clock: Arc<dyn Clock>,
128 }
129
130 impl SqliteSpendLedger {
131 pub async fn new(database_url: &str) -> Result<Self> {
137 let pool = SqlitePool::connect(database_url).await.map_err(unavailable)?;
138 Ok(Self::from_pool(pool))
139 }
140
141 pub fn from_pool(pool: SqlitePool) -> Self {
143 Self {
144 pool,
145 limits: SpendLimits::new(),
146 ttl: DEFAULT_RESERVATION_TTL,
147 clock: Arc::new(SystemClock),
148 }
149 }
150
151 pub fn with_limits(mut self, limits: SpendLimits) -> Self {
153 self.limits = limits;
154 self
155 }
156
157 pub fn with_reservation_ttl(mut self, ttl: Duration) -> Self {
159 self.ttl = ttl;
160 self
161 }
162
163 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
165 self.clock = clock;
166 self
167 }
168
169 pub async fn migrate(&self) -> Result<()> {
175 crate::migration::sqlite_runner::run_sql_migrations(
176 &self.pool,
177 REGISTRY_TABLE,
178 MIGRATIONS,
179 || async { Ok(false) },
180 )
181 .await
182 }
183 }
184
185 #[async_trait::async_trait]
186 impl SpendLedger for SqliteSpendLedger {
187 async fn reserve(&self, key: &SpendKey, amount_micro_usd: u64) -> Result<ReservationId> {
188 let amount = stored_amount(amount_micro_usd)?;
189 let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await.map_err(unavailable)?;
192 let now = self.clock.now();
193 let now_us = now.timestamp_micros();
194 for limit in self.limits.applicable(key) {
195 let consumed: i64 = sqlx::query(CONSUMED)
196 .bind(window_start_micros(limit.key.period, now))
197 .bind(now_us)
198 .bind(&limit.key.org)
199 .bind(limit.key.agent.as_deref())
200 .bind(limit.key.vendor.as_deref())
201 .fetch_one(&mut *tx)
202 .await
203 .and_then(|row| row.try_get("consumed"))
204 .map_err(unavailable)?;
205 if let Some(error) = limit_exceeded(limit, consumed, amount_micro_usd) {
206 return Err(error);
207 }
208 }
209 let id = ReservationId::generate();
210 sqlx::query(
211 "INSERT INTO adk_spend_entries \
212 (id, org, agent, vendor, state, reserved_micro_usd, created_at_us, expires_at_us) \
213 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
214 )
215 .bind(id.as_str())
216 .bind(&key.org)
217 .bind(key.agent.as_deref())
218 .bind(key.vendor.as_deref())
219 .bind(STATE_RESERVED)
220 .bind(amount)
221 .bind(now_us)
222 .bind(expires_at_micros(now, self.ttl))
223 .execute(&mut *tx)
224 .await
225 .map_err(unavailable)?;
226 tx.commit().await.map_err(unavailable)?;
227 Ok(id)
228 }
229
230 async fn commit(&self, id: ReservationId, actual_micro_usd: u64) -> Result<()> {
231 let amount = stored_amount(actual_micro_usd)?;
232 let updated = sqlx::query(
233 "UPDATE adk_spend_entries \
234 SET state = ?1, committed_micro_usd = ?2, settled_at_us = ?3 \
235 WHERE id = ?4 AND state = ?5",
236 )
237 .bind(STATE_COMMITTED)
238 .bind(amount)
239 .bind(self.clock.now().timestamp_micros())
240 .bind(id.as_str())
241 .bind(STATE_RESERVED)
242 .execute(&self.pool)
243 .await
244 .map_err(unavailable)?;
245 if updated.rows_affected() == 0 {
246 return Err(SpendError::UnknownReservation(id).into());
247 }
248 Ok(())
249 }
250
251 async fn release(&self, id: ReservationId) -> Result<()> {
252 let updated = sqlx::query(
253 "UPDATE adk_spend_entries SET state = ?1, settled_at_us = ?2 \
254 WHERE id = ?3 AND state = ?4",
255 )
256 .bind(STATE_RELEASED)
257 .bind(self.clock.now().timestamp_micros())
258 .bind(id.as_str())
259 .bind(STATE_RESERVED)
260 .execute(&self.pool)
261 .await
262 .map_err(unavailable)?;
263 if updated.rows_affected() == 0 {
264 return Err(SpendError::UnknownReservation(id).into());
265 }
266 Ok(())
267 }
268
269 async fn spent(&self, key: &SpendKey, period: SpendPeriod) -> Result<u64> {
270 let spent: i64 = sqlx::query(SPENT)
271 .bind(window_start_micros(period, self.clock.now()))
272 .bind(&key.org)
273 .bind(key.agent.as_deref())
274 .bind(key.vendor.as_deref())
275 .fetch_one(&self.pool)
276 .await
277 .and_then(|row| row.try_get("spent"))
278 .map_err(unavailable)?;
279 Ok(u64::try_from(spent).unwrap_or(0))
280 }
281 }
282}
283
284#[cfg(feature = "sqlite")]
285pub use sqlite::SqliteSpendLedger;
286
287#[cfg(feature = "postgres")]
288mod postgres {
289 use super::*;
290 use sqlx::{Row, postgres::PgPool};
291
292 const REGISTRY_TABLE: &str = "_adk_spend_migrations";
293
294 const MIGRATIONS: &[(i64, &str, &str)] = &[(
295 1,
296 "create spend ledger entries",
297 "\
298CREATE TABLE IF NOT EXISTS adk_spend_orgs (org TEXT PRIMARY KEY);\
299CREATE TABLE IF NOT EXISTS adk_spend_entries (\
300 id TEXT PRIMARY KEY, \
301 org TEXT NOT NULL, \
302 agent TEXT, \
303 vendor TEXT, \
304 state TEXT NOT NULL, \
305 reserved_micro_usd BIGINT NOT NULL, \
306 committed_micro_usd BIGINT, \
307 created_at_us BIGINT NOT NULL, \
308 expires_at_us BIGINT NOT NULL, \
309 settled_at_us BIGINT\
310);\
311CREATE INDEX IF NOT EXISTS adk_spend_entries_org_state ON adk_spend_entries (org, state);",
312 )];
313
314 const CONSUMED: &str = "\
315SELECT COALESCE(SUM(CASE \
316 WHEN state = 'committed' AND settled_at_us >= $1 THEN committed_micro_usd \
317 WHEN state = 'reserved' AND expires_at_us > $2 THEN reserved_micro_usd \
318 ELSE 0 END), 0)::BIGINT AS consumed \
319FROM adk_spend_entries \
320WHERE org = $3 AND ($4::TEXT IS NULL OR agent = $4) AND ($5::TEXT IS NULL OR vendor = $5)";
321
322 const SPENT: &str = "\
323SELECT COALESCE(SUM(committed_micro_usd), 0)::BIGINT AS spent \
324FROM adk_spend_entries \
325WHERE state = 'committed' AND settled_at_us >= $1 \
326 AND org = $2 AND ($3::TEXT IS NULL OR agent = $3) AND ($4::TEXT IS NULL OR vendor = $4)";
327
328 #[derive(Debug)]
347 pub struct PostgresSpendLedger {
348 pool: PgPool,
349 limits: SpendLimits,
350 ttl: Duration,
351 clock: Arc<dyn Clock>,
352 }
353
354 impl PostgresSpendLedger {
355 pub async fn new(database_url: &str) -> Result<Self> {
361 let pool = PgPool::connect(database_url).await.map_err(unavailable)?;
362 Ok(Self::from_pool(pool))
363 }
364
365 pub fn from_pool(pool: PgPool) -> Self {
367 Self {
368 pool,
369 limits: SpendLimits::new(),
370 ttl: DEFAULT_RESERVATION_TTL,
371 clock: Arc::new(SystemClock),
372 }
373 }
374
375 pub fn with_limits(mut self, limits: SpendLimits) -> Self {
377 self.limits = limits;
378 self
379 }
380
381 pub fn with_reservation_ttl(mut self, ttl: Duration) -> Self {
383 self.ttl = ttl;
384 self
385 }
386
387 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
389 self.clock = clock;
390 self
391 }
392
393 pub async fn migrate(&self) -> Result<()> {
400 crate::migration::run_pg_migrations_locked(&self.pool, REGISTRY_TABLE, MIGRATIONS).await
401 }
402 }
403
404 #[async_trait::async_trait]
405 impl SpendLedger for PostgresSpendLedger {
406 async fn reserve(&self, key: &SpendKey, amount_micro_usd: u64) -> Result<ReservationId> {
407 let amount = stored_amount(amount_micro_usd)?;
408 let mut tx = self.pool.begin().await.map_err(unavailable)?;
409 sqlx::query("INSERT INTO adk_spend_orgs (org) VALUES ($1) ON CONFLICT DO NOTHING")
412 .bind(&key.org)
413 .execute(&mut *tx)
414 .await
415 .map_err(unavailable)?;
416 sqlx::query("SELECT org FROM adk_spend_orgs WHERE org = $1 FOR UPDATE")
417 .bind(&key.org)
418 .fetch_one(&mut *tx)
419 .await
420 .map_err(unavailable)?;
421 let now = self.clock.now();
422 let now_us = now.timestamp_micros();
423 for limit in self.limits.applicable(key) {
424 let consumed: i64 = sqlx::query(CONSUMED)
425 .bind(window_start_micros(limit.key.period, now))
426 .bind(now_us)
427 .bind(&limit.key.org)
428 .bind(limit.key.agent.as_deref())
429 .bind(limit.key.vendor.as_deref())
430 .fetch_one(&mut *tx)
431 .await
432 .and_then(|row| row.try_get("consumed"))
433 .map_err(unavailable)?;
434 if let Some(error) = limit_exceeded(limit, consumed, amount_micro_usd) {
435 return Err(error);
436 }
437 }
438 let id = ReservationId::generate();
439 sqlx::query(
440 "INSERT INTO adk_spend_entries \
441 (id, org, agent, vendor, state, reserved_micro_usd, created_at_us, expires_at_us) \
442 VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
443 )
444 .bind(id.as_str())
445 .bind(&key.org)
446 .bind(key.agent.as_deref())
447 .bind(key.vendor.as_deref())
448 .bind(STATE_RESERVED)
449 .bind(amount)
450 .bind(now_us)
451 .bind(expires_at_micros(now, self.ttl))
452 .execute(&mut *tx)
453 .await
454 .map_err(unavailable)?;
455 tx.commit().await.map_err(unavailable)?;
456 Ok(id)
457 }
458
459 async fn commit(&self, id: ReservationId, actual_micro_usd: u64) -> Result<()> {
460 let amount = stored_amount(actual_micro_usd)?;
461 let updated = sqlx::query(
462 "UPDATE adk_spend_entries \
463 SET state = $1, committed_micro_usd = $2, settled_at_us = $3 \
464 WHERE id = $4 AND state = $5",
465 )
466 .bind(STATE_COMMITTED)
467 .bind(amount)
468 .bind(self.clock.now().timestamp_micros())
469 .bind(id.as_str())
470 .bind(STATE_RESERVED)
471 .execute(&self.pool)
472 .await
473 .map_err(unavailable)?;
474 if updated.rows_affected() == 0 {
475 return Err(SpendError::UnknownReservation(id).into());
476 }
477 Ok(())
478 }
479
480 async fn release(&self, id: ReservationId) -> Result<()> {
481 let updated = sqlx::query(
482 "UPDATE adk_spend_entries SET state = $1, settled_at_us = $2 \
483 WHERE id = $3 AND state = $4",
484 )
485 .bind(STATE_RELEASED)
486 .bind(self.clock.now().timestamp_micros())
487 .bind(id.as_str())
488 .bind(STATE_RESERVED)
489 .execute(&self.pool)
490 .await
491 .map_err(unavailable)?;
492 if updated.rows_affected() == 0 {
493 return Err(SpendError::UnknownReservation(id).into());
494 }
495 Ok(())
496 }
497
498 async fn spent(&self, key: &SpendKey, period: SpendPeriod) -> Result<u64> {
499 let spent: i64 = sqlx::query(SPENT)
500 .bind(window_start_micros(period, self.clock.now()))
501 .bind(&key.org)
502 .bind(key.agent.as_deref())
503 .bind(key.vendor.as_deref())
504 .fetch_one(&self.pool)
505 .await
506 .and_then(|row| row.try_get("spent"))
507 .map_err(unavailable)?;
508 Ok(u64::try_from(spent).unwrap_or(0))
509 }
510 }
511}
512
513#[cfg(feature = "postgres")]
514pub use postgres::PostgresSpendLedger;