use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use subspace_account::{Account, Error, Provider, ServiceToken};
#[derive(Default)]
pub(crate) struct LeaseGate(AtomicBool);
impl LeaseGate {
pub(super) fn close(&self) {
self.0.store(true, Ordering::SeqCst);
}
pub(super) fn open(&self) {
self.0.store(false, Ordering::SeqCst);
}
pub(super) fn is_open(&self) -> bool {
!self.0.load(Ordering::SeqCst)
}
}
pub struct AccountSession {
pub(super) manager: Arc<dyn Provider>,
pub(super) gate: Arc<LeaseGate>,
pub(super) account: Account,
pub(super) generation: u64,
}
#[derive(Clone)]
pub struct AccountTokenSource {
manager: Arc<dyn Provider>,
gate: Arc<LeaseGate>,
}
impl AccountTokenSource {
pub(crate) fn new(manager: Arc<dyn Provider>, gate: Arc<LeaseGate>) -> Self {
Self { manager, gate }
}
pub fn generation(&self) -> u64 {
self.manager.generation()
}
pub fn token_for(&self, resource: &str, minimum: Duration) -> Result<ServiceToken, Error> {
lease(
&self.manager,
&self.gate,
self.generation(),
resource,
minimum,
)
}
}
impl AccountSession {
pub fn generation(&self) -> u64 {
self.generation
}
pub fn is_current(&self) -> bool {
self.gate.is_open() && self.manager.generation() == self.generation
}
pub fn token_for(&self, resource: &str, minimum: Duration) -> Result<ServiceToken, Error> {
let grant = lease(
&self.manager,
&self.gate,
self.generation,
resource,
minimum,
)?;
if grant.account.tenant != self.account.tenant || grant.account.id != self.account.id {
return Err(Error::Cancelled);
}
Ok(grant)
}
}
fn lease(
manager: &Arc<dyn Provider>,
gate: &LeaseGate,
generation: u64,
resource: &str,
minimum: Duration,
) -> Result<ServiceToken, Error> {
let current = || gate.is_open() && manager.generation() == generation;
if !current() {
return Err(Error::Cancelled);
}
let grant = manager.token_with_validity(resource, minimum)?;
if !current() {
return Err(Error::Cancelled);
}
Ok(grant)
}