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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use crate::error::{CommonResponse, SdkError, SdkResult};
use async_trait::async_trait;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::time::SystemTime;
use tokio::sync::RwLock;
#[async_trait]
pub trait AccessTokenProvider: Sync + Send + Sized {
async fn get_access_token(&self) -> SdkResult<AccessToken>;
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct AccessToken {
pub access_token: String,
pub expires_in: i32,
}
#[derive(Clone)]
struct AccessTokenCache {
access_token: String,
expires_in: i32,
expires_at: u64,
}
impl From<AccessToken> for AccessTokenCache {
fn from(at: AccessToken) -> Self {
let timestamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default();
let secs = timestamp.as_secs();
let expires_at = secs + at.expires_in as u64;
AccessTokenCache {
access_token: at.access_token,
expires_in: at.expires_in,
expires_at,
}
}
}
impl From<AccessTokenCache> for AccessToken {
fn from(c: AccessTokenCache) -> Self {
AccessToken {
access_token: c.access_token,
expires_in: c.expires_in,
}
}
}
impl AccessTokenCache {
pub fn is_expires(&self) -> bool {
let timestamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default();
self.expires_at <= timestamp.as_secs() - 5
}
}
pub struct TokenClient {
app_id: String,
app_secret: String,
cache_token: RwLock<Option<AccessTokenCache>>,
}
impl TokenClient {
pub fn new(app_id: String, app_secret: String) -> Self {
TokenClient {
app_id,
app_secret,
cache_token: RwLock::new(None),
}
}
}
#[async_trait]
impl AccessTokenProvider for TokenClient {
async fn get_access_token(&self) -> SdkResult<AccessToken> {
let url = format!(
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}",
self.app_id.clone(),
self.app_secret.clone()
);
let locked = futures::executor::block_on(self.cache_token.read());
if let Some(cache) = &*locked {
if !cache.is_expires() {
let cloned = cache.clone();
return Ok(cloned.into());
}
};
let msg = reqwest::get(&url)
.await?
.json::<CommonResponse<AccessToken>>()
.await?;
match msg {
CommonResponse::Ok(at) => {
let mut locked = self.cache_token.write().await;
*locked = Some(at.clone().into());
Ok(at)
}
CommonResponse::Err(e) => Err(SdkError::AccessTokenError(e)),
}
}
}
#[cfg(test)]
mod tests {
use std::time::SystemTime;
use tokio::sync::RwLock;
use crate::{
access_token::{AccessTokenCache, AccessTokenProvider},
error::CommonResponse,
AccessToken, TokenClient,
};
#[test]
fn test() {
let input = r#"{"access_token":"ACCESS_TOKEN","expires_in":7200}"#;
let expected = CommonResponse::Ok(AccessToken {
access_token: "ACCESS_TOKEN".to_string(),
expires_in: 7200,
});
assert_eq!(expected, serde_json::from_str(input).unwrap());
let input = r#"{"errcode":40013,"errmsg":"invalid appid"}"#;
let expected = CommonResponse::<AccessToken>::Err(crate::error::CommonError {
errcode: 40013,
errmsg: "invalid appid".to_string(),
});
assert_eq!(expected, serde_json::from_str(input).unwrap());
}
#[tokio::test]
async fn test_get_from_cache() {
use std::thread::sleep;
use std::time::Duration;
let timestamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default();
let token_client = TokenClient {
app_id: "app_id".to_owned(),
app_secret: "app_secret".to_owned(),
cache_token: RwLock::new(Some(AccessTokenCache {
access_token: "ACCESS_TOKEN".to_owned(),
expires_in: 7200,
expires_at: timestamp.as_secs() + 7200,
})),
};
sleep(Duration::new(2, 0));
let res = token_client.get_access_token().await.unwrap();
assert_eq!(
res,
AccessToken {
access_token: "ACCESS_TOKEN".to_owned(),
expires_in: 7200,
}
);
}
}