adk_core/lease.rs
1//! Leases with fencing epochs: one owner of a named resource at a time.
2//!
3//! A [`LeaseStore`] grants a time-limited lease on a resource name (a scheduler
4//! leadership slot, a session, a queue shard). Each grant carries an `epoch` that is one
5//! higher than the resource's previous epoch, so a holder that stalls past its expiry
6//! and wakes up after another owner took over holds a lower epoch and is refused —
7//! the fencing rule. Writes made on behalf of a lease carry its epoch, and a store
8//! refuses a stale one.
9//!
10//! | Operation | Free or expired resource | Held by the caller | Held by another owner |
11//! |-----------|--------------------------|--------------------|-----------------------|
12//! | [`acquire`](LeaseStore::acquire) | Granted, epoch + 1 | Granted again, epoch + 1 | `None` |
13//! | [`renew`](LeaseStore::renew) | Extended while the epoch is current and not released | Extended | `lease.stale_epoch` |
14//! | [`release`](LeaseStore::release) | No-op when stale | Released | No-op |
15//!
16//! A lease that expired but was not taken by anyone keeps its epoch, so its holder may
17//! still renew it. A released lease cannot be renewed. Epochs never repeat: a store
18//! keeps one record per resource after release, so the next grant continues the count.
19//!
20//! # Backend primitives
21//!
22//! | Backend | Primitive for a single winner |
23//! |---------|-------------------------------|
24//! | SQL | `INSERT ... ON CONFLICT DO UPDATE ... WHERE expires_at <= now OR owner = $owner RETURNING` (one row per resource) |
25//! | Redis | One Lua script reading and writing the resource hash |
26//! | MongoDB | `findOneAndUpdate` with an expiry filter and `upsert` |
27//! | Neo4j, Firestore | A transaction that reads the resource record and writes the new epoch |
28
29use std::collections::HashMap;
30use std::sync::Arc;
31use std::time::Duration;
32
33use async_trait::async_trait;
34use chrono::{DateTime, Utc};
35use serde::{Deserialize, Serialize};
36use tokio::sync::Mutex;
37
38use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
39
40/// Error code returned when a lease or run write carries an epoch that is no longer current.
41pub const LEASE_STALE_EPOCH_CODE: &str = "lease.stale_epoch";
42
43/// A time-limited grant of a resource to one owner.
44///
45/// # Example
46///
47/// ```rust
48/// use adk_core::lease::Lease;
49/// use chrono::Utc;
50///
51/// let lease = Lease { resource: "scheduler".into(), owner: "w1".into(), epoch: 1, expires_at: Utc::now() };
52/// assert_eq!(serde_json::to_value(&lease).unwrap()["expiresAt"], serde_json::to_value(lease.expires_at).unwrap());
53/// ```
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub struct Lease {
57 /// The leased resource name.
58 pub resource: String,
59 /// The owner the lease was granted to.
60 pub owner: String,
61 /// The fencing epoch: one higher than the resource's previous grant.
62 pub epoch: u64,
63 /// When the lease lapses unless renewed.
64 pub expires_at: DateTime<Utc>,
65}
66
67/// Grants, renews, and releases leases on named resources.
68///
69/// Every backend passes `adk_core::lease_store_conformance_tests!` (feature `conformance`).
70#[async_trait]
71pub trait LeaseStore: Send + Sync {
72 /// Grants `resource` to `owner` for `ttl`.
73 ///
74 /// Returns `Some(lease)` when the resource is free, its lease expired or was
75 /// released, or `owner` already holds it; the epoch is the previous epoch plus one
76 /// (1 for a resource never leased). Returns `None` when another owner holds an
77 /// unexpired lease.
78 ///
79 /// # Errors
80 ///
81 /// Returns `lease.invalid_ttl` for a zero `ttl`, or a backend error.
82 async fn acquire(&self, resource: &str, owner: &str, ttl: Duration) -> Result<Option<Lease>>;
83
84 /// Extends `lease` to `ttl` from now, keeping its epoch.
85 ///
86 /// # Errors
87 ///
88 /// Returns [`LEASE_STALE_EPOCH_CODE`] when the resource's current epoch or owner
89 /// differs from `lease`, or the lease was released.
90 async fn renew(&self, lease: &Lease, ttl: Duration) -> Result<Lease>;
91
92 /// Releases `lease` if it is still current; a stale lease is a no-op.
93 async fn release(&self, lease: &Lease) -> Result<()>;
94
95 /// Returns the unexpired, unreleased lease on `resource`, if any.
96 async fn current(&self, resource: &str) -> Result<Option<Lease>>;
97}
98
99/// Builds the error a lease store returns when a lease is no longer current.
100///
101/// # Example
102///
103/// ```rust
104/// let error = adk_core::lease::lease_stale_epoch_error("scheduler", 3);
105/// assert_eq!(error.code, adk_core::lease::LEASE_STALE_EPOCH_CODE);
106/// ```
107pub fn lease_stale_epoch_error(resource: &str, epoch: u64) -> AdkError {
108 AdkError::new(
109 ErrorComponent::Agent,
110 ErrorCategory::Conflict,
111 LEASE_STALE_EPOCH_CODE,
112 format!(
113 "lease on '{resource}' at epoch {epoch} is no longer held; stop work done under it \
114 and acquire the resource again"
115 ),
116 )
117}
118
119/// Returns `now + ttl`, refusing a zero or overflowing `ttl` with error `code`.
120pub(crate) fn deadline(
121 now: DateTime<Utc>,
122 ttl: Duration,
123 code: &'static str,
124) -> Result<DateTime<Utc>> {
125 chrono::Duration::from_std(ttl)
126 .ok()
127 .filter(|_| !ttl.is_zero())
128 .and_then(|ttl| now.checked_add_signed(ttl))
129 .ok_or_else(|| {
130 AdkError::new(
131 ErrorComponent::Agent,
132 ErrorCategory::InvalidInput,
133 code,
134 format!("time to live {ttl:?} must be greater than zero and fit in a timestamp"),
135 )
136 })
137}
138
139#[derive(Debug, Clone)]
140struct LeaseSlot {
141 lease: Lease,
142 released: bool,
143}
144
145/// Process-local [`LeaseStore`].
146///
147/// Leases do not survive a restart and are not shared between processes, so it fences
148/// only tasks within one process. Use a durable backend across replicas.
149///
150/// # Example
151///
152/// ```rust
153/// use std::time::Duration;
154/// use adk_core::lease::{InMemoryLeaseStore, LeaseStore};
155///
156/// # futures::executor::block_on(async {
157/// let store = InMemoryLeaseStore::new();
158/// let lease = store.acquire("scheduler", "w1", Duration::from_secs(30)).await?.unwrap();
159/// assert_eq!(lease.epoch, 1);
160/// assert!(store.acquire("scheduler", "w2", Duration::from_secs(30)).await?.is_none());
161/// # Ok::<(), adk_core::AdkError>(())
162/// # }).unwrap();
163/// ```
164#[derive(Debug)]
165pub struct InMemoryLeaseStore {
166 slots: Mutex<HashMap<String, LeaseSlot>>,
167 clock: Arc<dyn Clock>,
168}
169
170impl Default for InMemoryLeaseStore {
171 fn default() -> Self {
172 Self::new()
173 }
174}
175
176impl InMemoryLeaseStore {
177 /// Creates an empty store that reads the system clock.
178 pub fn new() -> Self {
179 Self { slots: Mutex::new(HashMap::new()), clock: Arc::new(SystemClock) }
180 }
181
182 /// Sets the clock that decides expiry.
183 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
184 self.clock = clock;
185 self
186 }
187}
188
189#[async_trait]
190impl LeaseStore for InMemoryLeaseStore {
191 async fn acquire(&self, resource: &str, owner: &str, ttl: Duration) -> Result<Option<Lease>> {
192 let now = self.clock.now();
193 let expires_at = deadline(now, ttl, "lease.invalid_ttl")?;
194 let mut slots = self.slots.lock().await;
195 let previous = match slots.get(resource) {
196 Some(slot) => {
197 let live = !slot.released && slot.lease.expires_at > now;
198 if live && slot.lease.owner != owner {
199 return Ok(None);
200 }
201 slot.lease.epoch
202 }
203 None => 0,
204 };
205 let lease = Lease {
206 resource: resource.to_string(),
207 owner: owner.to_string(),
208 epoch: previous + 1,
209 expires_at,
210 };
211 slots.insert(resource.to_string(), LeaseSlot { lease: lease.clone(), released: false });
212 Ok(Some(lease))
213 }
214
215 async fn renew(&self, lease: &Lease, ttl: Duration) -> Result<Lease> {
216 let expires_at = deadline(self.clock.now(), ttl, "lease.invalid_ttl")?;
217 let mut slots = self.slots.lock().await;
218 match slots.get_mut(&lease.resource) {
219 Some(slot)
220 if !slot.released
221 && slot.lease.epoch == lease.epoch
222 && slot.lease.owner == lease.owner =>
223 {
224 slot.lease.expires_at = expires_at;
225 Ok(slot.lease.clone())
226 }
227 _ => Err(lease_stale_epoch_error(&lease.resource, lease.epoch)),
228 }
229 }
230
231 async fn release(&self, lease: &Lease) -> Result<()> {
232 let mut slots = self.slots.lock().await;
233 if let Some(slot) = slots.get_mut(&lease.resource)
234 && slot.lease.epoch == lease.epoch
235 && slot.lease.owner == lease.owner
236 {
237 slot.released = true;
238 }
239 Ok(())
240 }
241
242 async fn current(&self, resource: &str) -> Result<Option<Lease>> {
243 let now = self.clock.now();
244 let slots = self.slots.lock().await;
245 Ok(slots
246 .get(resource)
247 .filter(|slot| !slot.released && slot.lease.expires_at > now)
248 .map(|slot| slot.lease.clone()))
249 }
250}