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
use std::{
path::PathBuf,
sync::{Arc, Mutex},
time::Instant,
};
use crate::source::{self, find_default, from_file, from_json, BoxSource};
pub struct Token {
inner: Mutex<Inner>,
}
impl Token {
pub fn new() -> crate::Result<Self> {
Builder::new().build()
}
pub fn header_value(&self) -> crate::Result<Arc<String>> {
let mut inner = self.inner.lock().unwrap();
let v = match inner.curr {
Some(ref c) if !c.token.expired(Instant::now()) => c.header.clone(),
_ => {
let token = inner.source.token()?;
let cache = Cache::from(token);
let ret = cache.header.clone();
inner.curr = Some(cache);
ret
}
};
Ok(v)
}
}
impl From<Inner> for Token {
fn from(v: Inner) -> Self {
Self {
inner: Mutex::new(v),
}
}
}
struct Inner {
source: BoxSource,
curr: Option<Cache>,
}
impl From<BoxSource> for Inner {
fn from(v: BoxSource) -> Self {
Self {
source: v,
curr: None,
}
}
}
struct Cache {
token: source::Token,
header: Arc<String>,
}
impl From<source::Token> for Cache {
fn from(v: source::Token) -> Self {
let header = format!("{} {}", v.type_, v.token);
Self {
token: v,
header: Arc::new(header),
}
}
}
enum SourceType {
Default,
Json(String),
File(PathBuf),
}
impl Default for SourceType {
fn default() -> Self {
Self::Default
}
}
pub struct Builder {
type_: SourceType,
scopes: Vec<String>,
}
impl Default for Builder {
fn default() -> Self {
Self {
type_: Default::default(),
scopes: vec!["https://www.googleapis.com/auth/cloud-platform".into()],
}
}
}
impl Builder {
pub fn new() -> Self {
Self::default()
}
pub fn json(mut self, json: impl AsRef<str>) -> Self {
self.type_ = SourceType::Json(json.as_ref().to_owned());
self
}
pub fn file(mut self, path: impl Into<PathBuf>) -> Self {
self.type_ = SourceType::File(path.into());
self
}
pub fn scopes<T: AsRef<str>>(mut self, scopes: &[T]) -> Self {
self.scopes = scopes
.iter()
.map(AsRef::as_ref)
.map(ToOwned::to_owned)
.collect();
self
}
pub fn build(self) -> crate::Result<Token> {
use SourceType::*;
let source: BoxSource = match self.type_ {
Default => find_default(&self.scopes)?,
Json(json) => from_json(json.as_bytes(), &self.scopes)?.into(),
File(path) => from_file(path, &self.scopes)?.into(),
};
Ok(Token::from(Inner::from(source)))
}
}