Skip to main content

adk_session/
lease.rs

1//! SQL-backed [`LeaseStore`](adk_core::LeaseStore) implementations.
2//!
3//! One row per resource in `adk_leases` holds the current owner, epoch, and expiry. The
4//! row stays after release, so the next grant continues the epoch count.
5//!
6//! | Operation | Statement | Why it has one winner |
7//! |-----------|-----------|-----------------------|
8//! | `acquire` | `INSERT ... ON CONFLICT (resource) DO UPDATE SET epoch = epoch + 1 ... WHERE released OR expires_at_us <= now OR owner = $owner RETURNING epoch` | The upsert is one atomic statement; a concurrent grant makes the row live, so the `WHERE` of every later upsert is false |
9//! | `renew` | `UPDATE ... WHERE resource = $r AND owner = $o AND epoch = $e AND NOT released` | The epoch is compared inside the write |
10//! | `release` | `UPDATE ... SET released = TRUE WHERE resource = $r AND owner = $o AND epoch = $e` | Same |
11//!
12//! | Backend | Feature | Serialization |
13//! |---------|---------|---------------|
14//! | [`SqliteLeaseStore`](crate::SqliteLeaseStore) | `sqlite` | SQLite's single writer |
15//! | `PostgresLeaseStore` | `postgres` | The row lock the upsert takes; a waiting upsert re-checks its `WHERE` against the committed row |
16
17use std::sync::Arc;
18use std::time::Duration;
19
20use adk_core::lease::lease_stale_epoch_error;
21use adk_core::{Clock, Lease, LeaseStore, Result, SystemClock};
22
23use crate::durable_sql::{deadline, from_micros, now, storage_error, to_u64};
24
25const CODE: &str = "session.lease_store.storage";
26
27const REGISTRY_TABLE: &str = "_adk_lease_migrations";
28
29const MIGRATIONS: &[(i64, &str, &str)] = &[(
30    1,
31    "create lease table",
32    "\
33CREATE TABLE IF NOT EXISTS adk_leases (\
34    resource TEXT PRIMARY KEY, \
35    owner TEXT NOT NULL, \
36    epoch BIGINT NOT NULL, \
37    expires_at_us BIGINT NOT NULL, \
38    released BOOLEAN NOT NULL\
39);",
40)];
41
42// Parameters appear in ascending order in every statement, so SQLite, which numbers
43// `$N` parameters by first appearance, binds them as PostgreSQL does.
44const ACQUIRE: &str = "\
45INSERT INTO adk_leases (resource, owner, epoch, expires_at_us, released) \
46VALUES ($1, $2, 1, $3, FALSE) \
47ON CONFLICT (resource) DO UPDATE SET \
48    owner = excluded.owner, \
49    epoch = adk_leases.epoch + 1, \
50    expires_at_us = excluded.expires_at_us, \
51    released = FALSE \
52WHERE adk_leases.released OR adk_leases.expires_at_us <= $4 OR adk_leases.owner = excluded.owner \
53RETURNING epoch";
54
55const RENEW: &str = "\
56UPDATE adk_leases SET expires_at_us = $1 \
57WHERE resource = $2 AND owner = $3 AND epoch = $4 AND NOT released";
58
59const RELEASE: &str = "\
60UPDATE adk_leases SET released = TRUE \
61WHERE resource = $1 AND owner = $2 AND epoch = $3";
62
63const CURRENT: &str = "\
64SELECT owner, epoch, expires_at_us FROM adk_leases \
65WHERE resource = $1 AND NOT released AND expires_at_us > $2";
66
67macro_rules! sql_lease_store {
68    (
69        $(#[$doc:meta])*
70        $name:ident, $pool:ty, $migrate:expr
71    ) => {
72        $(#[$doc])*
73        #[derive(Debug, Clone)]
74        pub struct $name {
75            pool: $pool,
76            clock: Arc<dyn Clock>,
77        }
78
79        impl $name {
80            /// Connects to `database_url` and creates a connection pool.
81            ///
82            /// Call [`migrate`](Self::migrate) before first use.
83            ///
84            /// # Errors
85            ///
86            /// Returns `session.lease_store.storage` when the database cannot be reached.
87            pub async fn new(database_url: &str) -> Result<Self> {
88                let pool = <$pool>::connect(database_url)
89                    .await
90                    .map_err(|e| storage_error(CODE, format!("lease store connection failed: {e}")))?;
91                Ok(Self::from_pool(pool))
92            }
93
94            /// Uses an existing pool, such as the one the session service holds.
95            pub fn from_pool(pool: $pool) -> Self {
96                Self { pool, clock: Arc::new(SystemClock) }
97            }
98
99            /// Sets the clock that decides expiry.
100            pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
101                self.clock = clock;
102                self
103            }
104
105            /// Creates or upgrades the lease table.
106            ///
107            /// # Errors
108            ///
109            /// Returns an error when a migration statement fails.
110            pub async fn migrate(&self) -> Result<()> {
111                let migrate = $migrate;
112                migrate(&self.pool).await
113            }
114        }
115
116        #[async_trait::async_trait]
117        impl LeaseStore for $name {
118            async fn acquire(
119                &self,
120                resource: &str,
121                owner: &str,
122                ttl: Duration,
123            ) -> Result<Option<Lease>> {
124                let (now, now_us) = now(&*self.clock);
125                let (expires_at, expires_us) = deadline(now, ttl, "lease.invalid_ttl")?;
126                let epoch: Option<i64> = sqlx::query_scalar(ACQUIRE)
127                    .bind(resource)
128                    .bind(owner)
129                    .bind(expires_us)
130                    .bind(now_us)
131                    .fetch_optional(&self.pool)
132                    .await
133                    .map_err(|e| storage_error(CODE, format!("lease acquire failed: {e}")))?;
134                epoch
135                    .map(|epoch| {
136                        Ok(Lease {
137                            resource: resource.to_string(),
138                            owner: owner.to_string(),
139                            epoch: to_u64(CODE, "epoch", epoch)?,
140                            expires_at,
141                        })
142                    })
143                    .transpose()
144            }
145
146            async fn renew(&self, lease: &Lease, ttl: Duration) -> Result<Lease> {
147                let (now, _) = now(&*self.clock);
148                let (expires_at, expires_us) = deadline(now, ttl, "lease.invalid_ttl")?;
149                // An epoch past BIGINT was never granted.
150                let epoch = i64::try_from(lease.epoch)
151                    .map_err(|_| lease_stale_epoch_error(&lease.resource, lease.epoch))?;
152                let updated = sqlx::query(RENEW)
153                    .bind(expires_us)
154                    .bind(&lease.resource)
155                    .bind(&lease.owner)
156                    .bind(epoch)
157                    .execute(&self.pool)
158                    .await
159                    .map_err(|e| storage_error(CODE, format!("lease renew failed: {e}")))?;
160                if updated.rows_affected() == 0 {
161                    return Err(lease_stale_epoch_error(&lease.resource, lease.epoch));
162                }
163                Ok(Lease { expires_at, ..lease.clone() })
164            }
165
166            async fn release(&self, lease: &Lease) -> Result<()> {
167                // An epoch past BIGINT was never granted, so there is nothing to release.
168                let Ok(epoch) = i64::try_from(lease.epoch) else { return Ok(()) };
169                sqlx::query(RELEASE)
170                    .bind(&lease.resource)
171                    .bind(&lease.owner)
172                    .bind(epoch)
173                    .execute(&self.pool)
174                    .await
175                    .map_err(|e| storage_error(CODE, format!("lease release failed: {e}")))?;
176                Ok(())
177            }
178
179            async fn current(&self, resource: &str) -> Result<Option<Lease>> {
180                let (_, now_us) = now(&*self.clock);
181                let row: Option<(String, i64, i64)> = sqlx::query_as(CURRENT)
182                    .bind(resource)
183                    .bind(now_us)
184                    .fetch_optional(&self.pool)
185                    .await
186                    .map_err(|e| storage_error(CODE, format!("lease read failed: {e}")))?;
187                row.map(|(owner, epoch, expires_us)| {
188                    Ok(Lease {
189                        resource: resource.to_string(),
190                        owner,
191                        epoch: to_u64(CODE, "epoch", epoch)?,
192                        expires_at: from_micros(CODE, "expires_at_us", expires_us)?,
193                    })
194                })
195                .transpose()
196            }
197        }
198    };
199}
200
201#[cfg(feature = "sqlite")]
202sql_lease_store! {
203    /// SQLite-backed [`LeaseStore`].
204    ///
205    /// Every operation is one statement, and SQLite runs one writer at a time, so two
206    /// processes sharing the database file never both hold a resource.
207    ///
208    /// # Example
209    ///
210    /// ```rust,no_run
211    /// use std::time::Duration;
212    /// use adk_core::LeaseStore;
213    /// use adk_session::SqliteLeaseStore;
214    ///
215    /// # async fn example() -> adk_core::Result<()> {
216    /// let store = SqliteLeaseStore::new("sqlite://runtime.db?mode=rwc").await?;
217    /// store.migrate().await?;
218    /// if let Some(lease) = store.acquire("scheduler", "replica-1", Duration::from_secs(30)).await? {
219    ///     store.renew(&lease, Duration::from_secs(30)).await?;
220    /// }
221    /// # Ok(())
222    /// # }
223    /// ```
224    SqliteLeaseStore, sqlx::SqlitePool,
225    |pool: &sqlx::SqlitePool| {
226        let pool = pool.clone();
227        async move {
228            crate::migration::sqlite_runner::run_sql_migrations(
229                &pool,
230                REGISTRY_TABLE,
231                MIGRATIONS,
232                || async { Ok(false) },
233            )
234            .await
235        }
236    }
237}
238
239#[cfg(feature = "postgres")]
240sql_lease_store! {
241    /// PostgreSQL-backed [`LeaseStore`]. [`migrate`](Self::migrate) takes an advisory
242    /// lock, so concurrent processes can call it at startup.
243    ///
244    /// `acquire` is a single `INSERT ... ON CONFLICT DO UPDATE ... WHERE` statement: of
245    /// any number of concurrent acquirers across processes, one is granted the next
246    /// epoch and the rest see the live lease and get `None`.
247    ///
248    /// # Example
249    ///
250    /// ```rust,no_run
251    /// use std::time::Duration;
252    /// use adk_core::LeaseStore;
253    /// use adk_session::PostgresLeaseStore;
254    ///
255    /// # async fn example() -> adk_core::Result<()> {
256    /// let store = PostgresLeaseStore::new("postgres://localhost/app").await?;
257    /// store.migrate().await?;
258    /// if let Some(lease) = store.acquire("scheduler", "replica-1", Duration::from_secs(30)).await? {
259    ///     store.release(&lease).await?;
260    /// }
261    /// # Ok(())
262    /// # }
263    /// ```
264    PostgresLeaseStore, sqlx::PgPool,
265    |pool: &sqlx::PgPool| {
266        let pool = pool.clone();
267        async move {
268            crate::migration::run_pg_migrations_locked(&pool, REGISTRY_TABLE, MIGRATIONS).await
269        }
270    }
271}