1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use tokio::time::Instant;
use crate::error::CortexResult;
use super::{ResilientClient, TOKEN_REFRESH_INTERVAL};
impl ResilientClient {
/// Returns the current Cortex token (for advanced use cases).
pub async fn cortex_token(&self) -> String {
self.state.read().await.cortex_token.clone()
}
/// Check if the token should be refreshed and do so if needed.
///
/// Authentication I/O runs *outside* the state lock so a slow refresh
/// cannot block concurrent operations or reconnection. The result is
/// applied only if the connection was not replaced in the meantime
/// (a reconnect already obtains a fresh token of its own).
pub(super) async fn maybe_refresh_token(&self) -> CortexResult<()> {
let refresh_client = {
let state = self.state.read().await;
if state.token_obtained_at.elapsed() <= TOKEN_REFRESH_INTERVAL {
return Ok(());
}
std::sync::Arc::clone(&state.client)
};
tracing::info!("Proactively refreshing Cortex token");
match refresh_client
.authenticate(&self.config.client_id, &self.config.client_secret)
.await
{
Ok(new_token) => {
let mut state = self.state.write().await;
// Apply only if this is still the active connection and no
// concurrent refresh beat us to it.
if std::sync::Arc::ptr_eq(&state.client, &refresh_client)
&& state.token_obtained_at.elapsed() > TOKEN_REFRESH_INTERVAL
{
state.cortex_token = new_token;
state.token_obtained_at = Instant::now();
tracing::info!("Token refreshed successfully");
} else {
tracing::debug!("Discarding stale token refresh result");
}
}
Err(e) => {
tracing::warn!(
error_category = e.category(),
api_code = ?e.api_code(),
"Token refresh failed, will retry on next call"
);
}
}
Ok(())
}
/// Generate a new cortex token (or refresh an existing one).
///
/// On success, also updates the internal token and refresh timestamp.
///
/// # Errors
/// Returns any error produced by the underlying Cortex API call,
/// including connection, authentication, protocol, timeout, and configuration errors.
pub async fn generate_new_token(&self) -> CortexResult<String> {
let client_id = self.config.client_id.clone();
let client_secret = self.config.client_secret.clone();
let (new_token, source_client) = self
.exec_with_token_tracked(move |c, token| {
let id = client_id.clone();
let secret = client_secret.clone();
async move { c.generate_new_token(&token, &id, &secret).await }
})
.await?;
// Commit only to the client generation that produced the token. If a
// reconnect installed a newer client in the meantime, its freshly
// authenticated token wins and is returned to the caller.
let mut state = self.state.write().await;
if std::sync::Arc::ptr_eq(&state.client, &source_client) {
state.cortex_token.clone_from(&new_token);
state.token_obtained_at = Instant::now();
Ok(new_token)
} else {
tracing::debug!("Discarding token generated by stale client");
Ok(state.cortex_token.clone())
}
}
}