use super::{GarrisonContext, CURRENT_TOKEN};
use crate::error::{GarrisonError, GarrisonResult};
use std::future::Future;
use std::sync::{Arc, Mutex};
tokio::task_local! {
pub static CURRENT_RENEWED_TOKEN: Arc<Mutex<Option<String>>>;
}
pub async fn with_renewed_token_scope<R>(f: impl std::future::Future<Output = R>) -> R {
CURRENT_RENEWED_TOKEN
.scope(Arc::new(Mutex::new(None)), f)
.await
}
pub fn current_renewed_token() -> Option<String> {
CURRENT_RENEWED_TOKEN
.try_get()
.ok()
.and_then(|arc| arc.lock().unwrap().clone())
}
pub(crate) fn set_renewed_token(token: String) {
if let Ok(arc) = CURRENT_RENEWED_TOKEN.try_get() {
*arc.lock().unwrap() = Some(token);
}
}
pub fn get_renewed_token() -> Option<String> {
current_renewed_token()
}
pub fn clear_renewed_token() {
if let Ok(arc) = CURRENT_RENEWED_TOKEN.try_get() {
*arc.lock().unwrap() = None;
}
}
impl GarrisonContext {
pub fn capture() -> Self {
Self {
token: current_token().ok(),
}
}
pub async fn within<F, R>(self, f: F) -> R
where
F: Future<Output = R>,
{
match self.token {
Some(token) => CURRENT_TOKEN.scope(token, f).await,
None => f.await,
}
}
}
pub async fn with_current_token<R>(token: String, f: impl Future<Output = R>) -> R {
CURRENT_TOKEN.scope(token, f).await
}
#[allow(clippy::map_clone)]
pub fn current_token() -> GarrisonResult<String> {
CURRENT_TOKEN
.try_get()
.map(|t| t.clone())
.map_err(|_| GarrisonError::Session("stp-context-not-set::".to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn get_renewed_token_returns_some_when_set() {
with_renewed_token_scope(async {
set_renewed_token("new-token-123".to_string());
assert_eq!(
get_renewed_token(),
Some("new-token-123".to_string()),
"设置续签 token 后应返回 Some"
);
})
.await;
}
#[tokio::test]
async fn get_renewed_token_returns_none_when_not_set() {
with_renewed_token_scope(async {
assert_eq!(get_renewed_token(), None, "未设置续签 token 时应返回 None");
})
.await;
}
#[tokio::test]
async fn get_renewed_token_returns_none_after_clear() {
with_renewed_token_scope(async {
set_renewed_token("new-token-456".to_string());
clear_renewed_token();
assert_eq!(get_renewed_token(), None, "clear 后应返回 None");
})
.await;
}
#[test]
fn get_renewed_token_returns_none_outside_scope() {
let result = std::panic::catch_unwind(get_renewed_token);
assert!(result.is_ok(), "作用域外调用不应 panic");
assert_eq!(result.unwrap(), None, "作用域外应返回 None");
}
#[tokio::test]
async fn set_get_clear_get_returns_none() {
with_renewed_token_scope(async {
set_renewed_token("token-abc".to_string());
assert_eq!(
get_renewed_token(),
Some("token-abc".to_string()),
"设置后应返回 Some"
);
clear_renewed_token();
assert_eq!(get_renewed_token(), None, "清除后应返回 None");
})
.await;
}
}