agentmux_srv_core/identity/aws_broker/
sessions.rs1use std::collections::{HashMap, VecDeque};
11use std::future::Future;
12use std::sync::{Arc, Mutex};
13
14use chrono::{DateTime, Duration, Utc};
15
16use super::mint::{Minted, MintError};
17
18pub const REUSE_MARGIN: Duration = Duration::minutes(10);
20const WINDOW: Duration = Duration::hours(1);
21const PRUNE_ABOVE: usize = 32;
23
24#[derive(Clone, PartialEq, Eq, Hash)]
25struct Key {
26 agent: String,
27 grant: String,
28 reason: String,
29}
30
31struct Slot {
32 session: Option<Minted>,
33}
34
35#[derive(Debug, PartialEq, Eq)]
36pub enum SessionError {
37 TooMany { cap: u32 },
39 Mint(MintError),
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Source {
45 Fresh,
46 Reused,
48}
49
50#[derive(Default)]
51pub struct Sessions {
52 slots: Mutex<HashMap<Key, Arc<tokio::sync::Mutex<Slot>>>>,
53 attempts: Mutex<HashMap<(String, String), VecDeque<DateTime<Utc>>>>,
54}
55
56impl Sessions {
57 fn slot(&self, key: &Key, now: DateTime<Utc>) -> Arc<tokio::sync::Mutex<Slot>> {
60 let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
61 if slots.len() >= PRUNE_ABOVE {
62 slots.retain(|_, s| s.try_lock().map_or(true, |g| g.session.as_ref().is_some_and(|m| m.expiration > now)));
64 }
65 slots.entry(key.clone()).or_insert_with(|| Arc::new(tokio::sync::Mutex::new(Slot { session: None }))).clone()
66 }
67
68 fn forget_if_empty(&self, key: &Key) {
70 let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
71 if slots.get(key).is_some_and(|s| s.try_lock().is_ok_and(|g| g.session.is_none())) {
72 slots.remove(key);
73 }
74 }
75
76 fn allow_attempt(&self, agent: &str, grant: &str, cap: u32, now: DateTime<Utc>) -> bool {
78 let mut all = self.attempts.lock().unwrap_or_else(|e| e.into_inner());
79 let times = all.entry((agent.to_string(), grant.to_string())).or_default();
80 while times.front().is_some_and(|t| now - *t >= WINDOW) {
81 times.pop_front();
82 }
83 if times.len() >= cap as usize {
84 return false;
85 }
86 times.push_back(now);
87 true
88 }
89
90 pub async fn get_or_mint<F, Fut>(
94 &self,
95 agent: &str,
96 grant: &str,
97 reason: &str,
98 cap: u32,
99 now: DateTime<Utc>,
100 mint: F,
101 ) -> Result<(Minted, Source), SessionError>
102 where
103 F: FnOnce() -> Fut,
104 Fut: Future<Output = Result<Minted, MintError>>,
105 {
106 let key = Key { agent: agent.to_string(), grant: grant.to_string(), reason: reason.to_string() };
107 let slot = self.slot(&key, now);
108 let outcome = {
109 let mut held = slot.lock().await;
110 if let Some(session) = held.session.as_ref().filter(|s| s.expiration - now >= REUSE_MARGIN) {
111 return Ok((session.clone(), Source::Reused));
112 }
113 held.session = None;
114 if !self.allow_attempt(agent, grant, cap, now) {
115 Err(SessionError::TooMany { cap })
116 } else {
117 match mint().await {
118 Ok(minted) => {
119 held.session = Some(minted.clone());
120 Ok((minted, Source::Fresh))
121 }
122 Err(e) => Err(SessionError::Mint(e)),
123 }
124 }
125 };
126 if outcome.is_err() {
127 drop(slot);
128 self.forget_if_empty(&key);
129 }
130 outcome
131 }
132
133 pub fn revoke_agent(&self, agent: &str) {
135 self.slots.lock().unwrap_or_else(|e| e.into_inner()).retain(|k, _| k.agent != agent);
136 }
138
139 #[cfg(test)]
140 pub fn held(&self, agent: &str) -> usize {
141 self.slots.lock().unwrap().keys().filter(|k| k.agent == agent).count()
142 }
143}
144
145pub fn global() -> &'static Sessions {
147 static SESSIONS: std::sync::OnceLock<Sessions> = std::sync::OnceLock::new();
148 SESSIONS.get_or_init(Sessions::default)
149}
150
151#[cfg(test)]
152#[path = "sessions_tests.rs"]
153mod tests;