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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use crate::error::Error;
use crate::token::Token;
use crate::token_source::TokenSource;
use async_trait::async_trait;
#[derive(Debug)]
pub struct ReuseTokenSource {
target: Box<dyn TokenSource>,
current_token: std::sync::RwLock<Token>,
guard: tokio::sync::Mutex<()>,
}
impl ReuseTokenSource {
pub(crate) fn new(target: Box<dyn TokenSource>, token: Token) -> ReuseTokenSource {
ReuseTokenSource {
target,
current_token: std::sync::RwLock::new(token),
guard: tokio::sync::Mutex::new(()),
}
}
}
#[async_trait]
impl TokenSource for ReuseTokenSource {
async fn token(&self) -> Result<Token, Error> {
if let Some(token) = self.r_lock_token() {
return Ok(token);
}
let _locking = self.guard.lock().await;
if let Some(token) = self.r_lock_token() {
return Ok(token);
}
let token = self.target.token().await?;
tracing::debug!("token refresh success : expiry={:?}", token.expiry);
*self.current_token.write().unwrap() = token.clone();
Ok(token)
}
}
impl ReuseTokenSource {
fn r_lock_token(&self) -> Option<Token> {
let token = self.current_token.read().unwrap();
if token.valid() {
Some(token.clone())
} else {
None
}
}
}
#[cfg(test)]
mod test {
use crate::error::Error;
use crate::token::Token;
use crate::{ReuseTokenSource, TokenSource};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use std::fmt::Debug;
use std::sync::Arc;
use tracing_subscriber::filter::LevelFilter;
#[derive(Debug)]
struct EmptyTokenSource {
pub expiry: DateTime<Utc>,
}
#[async_trait]
impl TokenSource for EmptyTokenSource {
async fn token(&self) -> Result<Token, Error> {
Ok(Token {
access_token: "empty".to_string(),
token_type: "empty".to_string(),
expiry: Some(self.expiry),
})
}
}
#[ctor::ctor]
fn init() {
let filter = tracing_subscriber::filter::EnvFilter::from_default_env().add_directive(LevelFilter::DEBUG.into());
let _ = tracing_subscriber::fmt().with_env_filter(filter).try_init();
}
#[tokio::test]
async fn test_all_valid() {
let ts = Box::new(EmptyTokenSource {
expiry: Utc::now() + chrono::Duration::seconds(100),
});
let token = ts.token().await.unwrap();
let results = run_task(ts, token).await;
for v in results {
assert!(v)
}
}
#[tokio::test]
async fn test_with_invalid() {
let mut ts = Box::new(EmptyTokenSource { expiry: Utc::now() });
let token = ts.token().await.unwrap();
ts.expiry = Utc::now() + chrono::Duration::seconds(100);
let results = run_task(ts, token).await;
for v in results {
assert!(v)
}
}
#[tokio::test]
async fn test_all_invalid() {
let ts = Box::new(EmptyTokenSource { expiry: Utc::now() });
let token = ts.token().await.unwrap();
let results = run_task(ts, token).await;
for v in results {
assert!(!v)
}
}
async fn run_task(ts: Box<EmptyTokenSource>, first_token: Token) -> Vec<bool> {
let ts = Arc::new(ReuseTokenSource::new(ts, first_token));
let mut tasks = Vec::with_capacity(100);
for _n in 1..100 {
let ts_clone = ts.clone();
let task = tokio::spawn(async move {
match ts_clone.token().await {
Ok(new_token) => new_token.valid(),
Err(_e) => false,
}
});
tasks.push(task)
}
let mut result = Vec::with_capacity(tasks.len());
for task in tasks {
result.push(task.await.unwrap());
}
result
}
}