subspace_shell/account/
lease.rs1use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::time::Duration;
6use subspace_account::{Account, Error, Provider, ServiceToken};
7
8#[derive(Default)]
11pub(crate) struct LeaseGate(AtomicBool);
12
13impl LeaseGate {
14 pub(super) fn close(&self) {
15 self.0.store(true, Ordering::SeqCst);
16 }
17
18 pub(super) fn open(&self) {
19 self.0.store(false, Ordering::SeqCst);
20 }
21
22 pub(super) fn is_open(&self) -> bool {
23 !self.0.load(Ordering::SeqCst)
24 }
25}
26
27pub struct AccountSession {
29 pub(super) manager: Arc<dyn Provider>,
30 pub(super) gate: Arc<LeaseGate>,
31 pub(super) account: Account,
32 pub(super) generation: u64,
33}
34
35#[derive(Clone)]
40pub struct AccountTokenSource {
41 manager: Arc<dyn Provider>,
42 gate: Arc<LeaseGate>,
43}
44
45impl AccountTokenSource {
46 pub(crate) fn new(manager: Arc<dyn Provider>, gate: Arc<LeaseGate>) -> Self {
47 Self { manager, gate }
48 }
49
50 pub fn generation(&self) -> u64 {
51 self.manager.generation()
52 }
53
54 pub fn token_for(&self, resource: &str, minimum: Duration) -> Result<ServiceToken, Error> {
58 lease(
59 &self.manager,
60 &self.gate,
61 self.generation(),
62 resource,
63 minimum,
64 )
65 }
66}
67
68impl AccountSession {
69 pub fn generation(&self) -> u64 {
70 self.generation
71 }
72
73 pub fn is_current(&self) -> bool {
75 self.gate.is_open() && self.manager.generation() == self.generation
76 }
77
78 pub fn token_for(&self, resource: &str, minimum: Duration) -> Result<ServiceToken, Error> {
82 let grant = lease(
83 &self.manager,
84 &self.gate,
85 self.generation,
86 resource,
87 minimum,
88 )?;
89 if grant.account.tenant != self.account.tenant || grant.account.id != self.account.id {
90 return Err(Error::Cancelled);
91 }
92 Ok(grant)
93 }
94}
95
96fn lease(
99 manager: &Arc<dyn Provider>,
100 gate: &LeaseGate,
101 generation: u64,
102 resource: &str,
103 minimum: Duration,
104) -> Result<ServiceToken, Error> {
105 let current = || gate.is_open() && manager.generation() == generation;
106 if !current() {
107 return Err(Error::Cancelled);
108 }
109 let grant = manager.token_with_validity(resource, minimum)?;
110 if !current() {
111 return Err(Error::Cancelled);
112 }
113 Ok(grant)
114}