use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
pub const LEASE_STALE_EPOCH_CODE: &str = "lease.stale_epoch";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Lease {
pub resource: String,
pub owner: String,
pub epoch: u64,
pub expires_at: DateTime<Utc>,
}
#[async_trait]
pub trait LeaseStore: Send + Sync {
async fn acquire(&self, resource: &str, owner: &str, ttl: Duration) -> Result<Option<Lease>>;
async fn renew(&self, lease: &Lease, ttl: Duration) -> Result<Lease>;
async fn release(&self, lease: &Lease) -> Result<()>;
async fn current(&self, resource: &str) -> Result<Option<Lease>>;
}
pub fn lease_stale_epoch_error(resource: &str, epoch: u64) -> AdkError {
AdkError::new(
ErrorComponent::Agent,
ErrorCategory::Conflict,
LEASE_STALE_EPOCH_CODE,
format!(
"lease on '{resource}' at epoch {epoch} is no longer held; stop work done under it \
and acquire the resource again"
),
)
}
pub(crate) fn deadline(
now: DateTime<Utc>,
ttl: Duration,
code: &'static str,
) -> Result<DateTime<Utc>> {
chrono::Duration::from_std(ttl)
.ok()
.filter(|_| !ttl.is_zero())
.and_then(|ttl| now.checked_add_signed(ttl))
.ok_or_else(|| {
AdkError::new(
ErrorComponent::Agent,
ErrorCategory::InvalidInput,
code,
format!("time to live {ttl:?} must be greater than zero and fit in a timestamp"),
)
})
}
#[derive(Debug, Clone)]
struct LeaseSlot {
lease: Lease,
released: bool,
}
#[derive(Debug)]
pub struct InMemoryLeaseStore {
slots: Mutex<HashMap<String, LeaseSlot>>,
clock: Arc<dyn Clock>,
}
impl Default for InMemoryLeaseStore {
fn default() -> Self {
Self::new()
}
}
impl InMemoryLeaseStore {
pub fn new() -> Self {
Self { slots: Mutex::new(HashMap::new()), clock: Arc::new(SystemClock) }
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
}
#[async_trait]
impl LeaseStore for InMemoryLeaseStore {
async fn acquire(&self, resource: &str, owner: &str, ttl: Duration) -> Result<Option<Lease>> {
let now = self.clock.now();
let expires_at = deadline(now, ttl, "lease.invalid_ttl")?;
let mut slots = self.slots.lock().await;
let previous = match slots.get(resource) {
Some(slot) => {
let live = !slot.released && slot.lease.expires_at > now;
if live && slot.lease.owner != owner {
return Ok(None);
}
slot.lease.epoch
}
None => 0,
};
let lease = Lease {
resource: resource.to_string(),
owner: owner.to_string(),
epoch: previous + 1,
expires_at,
};
slots.insert(resource.to_string(), LeaseSlot { lease: lease.clone(), released: false });
Ok(Some(lease))
}
async fn renew(&self, lease: &Lease, ttl: Duration) -> Result<Lease> {
let expires_at = deadline(self.clock.now(), ttl, "lease.invalid_ttl")?;
let mut slots = self.slots.lock().await;
match slots.get_mut(&lease.resource) {
Some(slot)
if !slot.released
&& slot.lease.epoch == lease.epoch
&& slot.lease.owner == lease.owner =>
{
slot.lease.expires_at = expires_at;
Ok(slot.lease.clone())
}
_ => Err(lease_stale_epoch_error(&lease.resource, lease.epoch)),
}
}
async fn release(&self, lease: &Lease) -> Result<()> {
let mut slots = self.slots.lock().await;
if let Some(slot) = slots.get_mut(&lease.resource)
&& slot.lease.epoch == lease.epoch
&& slot.lease.owner == lease.owner
{
slot.released = true;
}
Ok(())
}
async fn current(&self, resource: &str) -> Result<Option<Lease>> {
let now = self.clock.now();
let slots = self.slots.lock().await;
Ok(slots
.get(resource)
.filter(|slot| !slot.released && slot.lease.expires_at > now)
.map(|slot| slot.lease.clone()))
}
}