⎇ ca75ba185f880d431eb118250d3931a91d354b2e
crates/ente-zero/src/graph/capabilities.rs
History
Who touched what
raw
Cristales temporales, replay, lease/renew y audit streaming
1//! Mediación de capabilities: emisión, renovación, revocación de tokens.
2//!
3//! Los grants tienen TTL (`DEFAULT_GRANT_TTL`). El cliente debe renovarlos
4//! periódicamente con `renew_grant(token)`; en caso contrario, el background
5//! task `purge_expired_grants` los revoca al vencimiento.
6
7use super::{EnteGraph, GrantedCapability, DEFAULT_GRANT_TTL};
8use crate::events::CapabilityGrant;
9use ente_card::Capability;
10use std::time::Instant;
11use tokio::sync::oneshot;
12use tracing::debug;
13use ulid::Ulid;
14
15impl EnteGraph {
16 pub async fn mediate_capability(
17 &mut self,
18 from: Ulid,
19 cap: Capability,
20 reply: oneshot::Sender<CapabilityGrant>,
21 ) {
22 let grant = match self.providers.get(&cap).and_then(|s| s.iter().next().copied()) {
23 None => CapabilityGrant::NoProvider,
24 Some(provider) => {
25 let token = self.next_token;
26 self.next_token += 1;
27 let expires_at = Instant::now() + DEFAULT_GRANT_TTL;
28 self.grants.insert(token, GrantedCapability {
29 cap: cap.clone(),
30 provider,
31 holder: from,
32 expires_at,
33 });
34 CapabilityGrant::Granted { token }
35 }
36 };
37 let _ = reply.send(grant);
38 }
39
40 /// Extiende un grant existente. Devuelve `true` si renovó. Si el token
41 /// no existe o ya expiró, `false` (el cliente debe re-acquire).
42 pub fn renew_grant(&mut self, token: u64) -> bool {
43 let now = Instant::now();
44 if let Some(g) = self.grants.get_mut(&token) {
45 if g.expires_at > now {
46 g.expires_at = now + DEFAULT_GRANT_TTL;
47 return true;
48 }
49 // Expired — purgamos aquí mismo.
50 self.grants.remove(&token);
51 }
52 false
53 }
54
55 /// GC: elimina grants vencidos. Devuelve cuántos fueron purgados.
56 pub fn purge_expired_grants(&mut self) -> usize {
57 let now = Instant::now();
58 let expired: Vec<u64> = self.grants.iter()
59 .filter(|(_, g)| g.expires_at <= now)
60 .map(|(t, _)| *t)
61 .collect();
62 for t in &expired {
63 self.grants.remove(t);
64 }
65 if !expired.is_empty() {
66 debug!(count = expired.len(), "grants expirados purgados");
67 }
68 expired.len()
69 }
70
71 /// Cuenta de grants vivos (no expirados). Usado por métricas.
72 pub fn active_grants_count(&self) -> usize {
73 let now = Instant::now();
74 self.grants.values().filter(|g| g.expires_at > now).count()
75 }
76}
77