hyprstream_workers/events/
token_manager.rs1use std::sync::Arc;
7use std::time::Duration;
8
9use tokio::sync::RwLock;
10use tokio::task::JoinHandle;
11use tokio_util::sync::CancellationToken;
12
13pub struct EventTokenManager {
18 current_token: Arc<RwLock<String>>,
20 scope: String,
22 audience: String,
24 ttl_secs: u64,
26 refresh_handle: Option<JoinHandle<()>>,
28 cancel: CancellationToken,
30}
31
32impl EventTokenManager {
33 pub fn new(initial_token: String, scope: String, audience: String, ttl_secs: u64) -> Self {
35 Self {
36 current_token: Arc::new(RwLock::new(initial_token)),
37 scope,
38 audience,
39 ttl_secs,
40 refresh_handle: None,
41 cancel: CancellationToken::new(),
42 }
43 }
44
45 pub async fn token(&self) -> String {
47 self.current_token.read().await.clone()
48 }
49
50 pub fn scope(&self) -> &str {
52 &self.scope
53 }
54
55 pub fn audience(&self) -> &str {
57 &self.audience
58 }
59
60 pub fn start_refresh_loop<F, Fut>(&mut self, refresh_fn: F)
69 where
70 F: Fn(String, String, u64) -> Fut + Send + Sync + 'static,
71 Fut: std::future::Future<Output = Result<String, String>> + Send + 'static,
72 {
73 let token = Arc::clone(&self.current_token);
74 let scope = self.scope.clone();
75 let audience = self.audience.clone();
76 let ttl_secs = self.ttl_secs;
77 let cancel = self.cancel.clone();
78
79 let refresh_interval = Duration::from_secs(std::cmp::max(
81 1,
82 std::cmp::max(ttl_secs * 3 / 4, ttl_secs.saturating_sub(60)),
83 ));
84
85 let handle = tokio::spawn(async move {
86 loop {
87 tokio::select! {
88 _ = cancel.cancelled() => break,
89 _ = tokio::time::sleep(refresh_interval) => {
90 match refresh_fn(scope.clone(), audience.clone(), ttl_secs).await {
91 Ok(new_token) => {
92 *token.write().await = new_token;
93 tracing::debug!(scope = %scope, "Refreshed event token");
94 }
95 Err(e) => {
96 tracing::warn!(
97 scope = %scope,
98 error = %e,
99 "Failed to refresh event token, will retry"
100 );
101 }
102 }
103 }
104 }
105 }
106 });
107
108 self.refresh_handle = Some(handle);
109 }
110
111 pub fn stop(&self) {
113 self.cancel.cancel();
114 }
115
116 pub async fn set_token(&self, token: String) {
118 *self.current_token.write().await = token;
119 }
120}
121
122impl Drop for EventTokenManager {
123 fn drop(&mut self) {
124 self.cancel.cancel();
125 }
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131 use std::sync::atomic::{AtomicU32, Ordering};
132
133 #[tokio::test]
134 async fn test_initial_token() {
135 let mgr = EventTokenManager::new(
136 "initial-jwt".to_owned(),
137 "publish:events:worker.*".to_owned(),
138 "events".to_owned(),
139 600,
140 );
141 assert_eq!(mgr.token().await, "initial-jwt");
142 }
143
144 #[tokio::test]
145 async fn test_set_token() {
146 let mgr =
147 EventTokenManager::new("old".to_owned(), "scope".to_owned(), "aud".to_owned(), 600);
148 mgr.set_token("new".to_owned()).await;
149 assert_eq!(mgr.token().await, "new");
150 }
151
152 #[tokio::test]
153 async fn test_refresh_loop_calls_callback() {
154 let counter = Arc::new(AtomicU32::new(0));
155 let counter_clone = counter.clone();
156
157 let mut mgr = EventTokenManager::new(
158 "initial".to_owned(),
159 "scope".to_owned(),
160 "aud".to_owned(),
161 2, );
163
164 mgr.start_refresh_loop(move |_scope, _aud, _ttl| {
165 let c = counter_clone.clone();
166 async move {
167 c.fetch_add(1, Ordering::SeqCst);
168 Ok(format!("token-{}", c.load(Ordering::SeqCst)))
169 }
170 });
171
172 tokio::time::sleep(Duration::from_secs(3)).await;
174 mgr.stop();
175
176 assert!(counter.load(Ordering::SeqCst) >= 1);
177 assert!(mgr.token().await.starts_with("token-"));
178 }
179
180 #[tokio::test]
181 async fn test_stop_cancels_refresh() {
182 let mut mgr = EventTokenManager::new(
183 "initial".to_owned(),
184 "scope".to_owned(),
185 "aud".to_owned(),
186 600,
187 );
188
189 mgr.start_refresh_loop(|_s, _a, _t| async { Ok("refreshed".to_owned()) });
190 mgr.stop();
191
192 assert_eq!(mgr.token().await, "initial");
194 }
195}