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_or_else(|p| p.into_inner()).clone())
}
pub(crate) fn set_renewed_token(token: String) {
if let Ok(arc) = CURRENT_RENEWED_TOKEN.try_get() {
*arc.lock().unwrap_or_else(|p| p.into_inner()) = 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_or_else(|p| p.into_inner()) = 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()))
}
tokio::task_local! {
static CURRENT_LOGIN_ID: std::sync::Arc<std::sync::Mutex<Option<(String, String)>>>;
}
pub async fn with_login_id_scope<R>(f: impl Future<Output = R>) -> R {
CURRENT_LOGIN_ID.scope(Arc::new(Mutex::new(None)), f).await
}
pub(crate) fn cache_login_identity(token: &str, login_id: &str) {
if let Ok(arc) = CURRENT_LOGIN_ID.try_get() {
*arc.lock().unwrap_or_else(|p| p.into_inner()) =
Some((token.to_string(), login_id.to_string()));
}
}
pub(crate) fn cached_login_id_for(token: &str) -> Option<String> {
let arc = CURRENT_LOGIN_ID.try_get().ok()?;
let guard = arc.lock().unwrap_or_else(|p| p.into_inner());
let (cached_token, login_id) = guard.as_ref()?;
(cached_token == token).then(|| login_id.clone())
}
pub(crate) fn invalidate_login_identity_by_token(token: &str) {
if let Ok(arc) = CURRENT_LOGIN_ID.try_get() {
let mut guard = arc.lock().unwrap_or_else(|p| p.into_inner());
if guard.as_ref().map(|(t, _)| t == token).unwrap_or(false) {
*guard = None;
}
}
}
pub(crate) fn invalidate_login_identity_by_login_id(login_id: &str) {
if let Ok(arc) = CURRENT_LOGIN_ID.try_get() {
let mut guard = arc.lock().unwrap_or_else(|p| p.into_inner());
if guard
.as_ref()
.map(|(_, id)| id == login_id)
.unwrap_or(false)
{
*guard = None;
}
}
}
tokio::task_local! {
pub static CURRENT_IP: String;
}
pub async fn with_current_ip<R>(ip: String, f: impl Future<Output = R>) -> R {
CURRENT_IP.scope(ip, f).await
}
#[allow(clippy::map_clone)]
pub fn current_ip() -> Option<String> {
CURRENT_IP.try_get().ok().map(|ip| ip.clone())
}
#[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;
}
#[tokio::test]
async fn renewed_token_recovers_from_poisoned_mutex() {
let poisoned = Arc::new(Mutex::new(Some("kept".to_string())));
let p2 = poisoned.clone();
let handle = std::thread::spawn(move || {
let _guard = p2.lock().unwrap();
panic!("inject poison");
});
let _ = handle.join();
let got = CURRENT_RENEWED_TOKEN
.scope(poisoned.clone(), async { current_renewed_token() })
.await;
assert_eq!(
got,
Some("kept".to_string()),
"锁中毒时应通过 into_inner 恢复内部值而非 panic"
);
}
#[tokio::test]
async fn with_current_ip_and_current_ip_roundtrip() {
let result = with_current_ip("192.168.1.1".to_string(), async { current_ip() }).await;
assert_eq!(result, Some("192.168.1.1".to_string()));
}
#[test]
fn current_ip_outside_scope_returns_none() {
assert_eq!(current_ip(), None);
}
#[test]
fn set_renewed_token_outside_scope_is_noop() {
let result = std::panic::catch_unwind(|| set_renewed_token("tok".to_string()));
assert!(result.is_ok(), "作用域外 set_renewed_token 不应 panic");
}
#[test]
fn clear_renewed_token_outside_scope_is_noop() {
let result = std::panic::catch_unwind(clear_renewed_token);
assert!(result.is_ok(), "作用域外 clear_renewed_token 不应 panic");
}
#[tokio::test]
async fn garrison_context_capture_with_token() {
with_current_token("test-token-xyz".to_string(), async {
let ctx = GarrisonContext::capture();
assert_eq!(ctx.token.as_deref(), Some("test-token-xyz"));
})
.await;
}
#[test]
fn garrison_context_capture_without_token() {
let ctx = GarrisonContext::capture();
assert!(ctx.token.is_none(), "无 token 作用域时 token 应为 None");
}
#[tokio::test]
async fn garrison_context_within_restores_token() {
let ctx = with_current_token("captured-tok".to_string(), async {
GarrisonContext::capture()
})
.await;
let recovered = ctx.within(async { current_token().ok() }).await;
assert_eq!(recovered.as_deref(), Some("captured-tok"));
}
#[tokio::test]
async fn garrison_context_within_no_token_runs_f() {
let ctx = GarrisonContext { token: None };
let result = ctx.within(async { 42 }).await;
assert_eq!(result, 42, "无 token 时应直接执行 f");
}
}