Skip to content

Commit f85329c

Browse files
committed
-srefactor fruther token cache
1 parent 018da6c commit f85329c

File tree

1 file changed

+34
-16
lines changed

1 file changed

+34
-16
lines changed

src/token_cache.rs

+34-16
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,20 @@ pub enum RegistryOperation {
6262
// Types to allow better naming
6363
type Registry = String;
6464
type Repository = String;
65-
type TokenCacheKey = (Registry, Repository, RegistryOperation);
65+
66+
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
67+
struct TokenCacheKey {
68+
registry: Registry,
69+
repository: Repository,
70+
operation: RegistryOperation,
71+
}
72+
6673
type TokenExpiration = u64;
67-
type TokenCacheValue = (RegistryTokenType, TokenExpiration);
74+
75+
struct TokenCacheValue {
76+
token: RegistryTokenType,
77+
expiration: TokenExpiration,
78+
}
6879

6980
// (registry, repository, scope) -> (token, expiration)
7081
type CacheType = BTreeMap<TokenCacheKey, TokenCacheValue>;
@@ -121,10 +132,14 @@ impl TokenCache {
121132
let registry = reference.resolve_registry().to_string();
122133
let repository = reference.repository().to_string();
123134
debug!(%registry, %repository, ?op, %expiration, "Inserting token");
124-
self.tokens
125-
.write()
126-
.await
127-
.insert((registry, repository, op), (token, expiration));
135+
self.tokens.write().await.insert(
136+
TokenCacheKey {
137+
registry,
138+
repository,
139+
operation: op,
140+
},
141+
TokenCacheValue { token, expiration },
142+
);
128143
}
129144

130145
pub(crate) async fn get(
@@ -134,28 +149,31 @@ impl TokenCache {
134149
) -> Option<RegistryTokenType> {
135150
let registry = reference.resolve_registry().to_string();
136151
let repository = reference.repository().to_string();
137-
match self
138-
.tokens
139-
.read()
140-
.await
141-
.get(&(registry.clone(), repository.clone(), op))
142-
{
143-
Some((ref token, expiration)) => {
152+
let key = TokenCacheKey {
153+
registry,
154+
repository,
155+
operation: op,
156+
};
157+
match self.tokens.read().await.get(&key) {
158+
Some(TokenCacheValue {
159+
ref token,
160+
expiration,
161+
}) => {
144162
let now = SystemTime::now();
145163
let epoch = now
146164
.duration_since(UNIX_EPOCH)
147165
.expect("Time went backwards")
148166
.as_secs();
149167
if epoch > *expiration {
150-
debug!(%registry, %repository, ?op, %expiration, miss=false, expired=true, "Fetching token");
168+
debug!(?key, %expiration, miss=false, expired=true, "Fetching token");
151169
None
152170
} else {
153-
debug!(%registry, %repository, ?op, %expiration, miss=false, expired=false, "Fetching token");
171+
debug!(?key, %expiration, miss=false, expired=false, "Fetching token");
154172
Some(token.clone())
155173
}
156174
}
157175
None => {
158-
debug!(%registry, %repository, ?op, miss=true, "Fetching token");
176+
debug!(?key, miss = true, "Fetching token");
159177
None
160178
}
161179
}

0 commit comments

Comments
 (0)