-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
lib.rs
337 lines (292 loc) · 9.62 KB
/
lib.rs
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
use std::{env, future::Future};
use anyhow::{anyhow, Result};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use crate::retry::retry_future;
mod retry;
#[derive(Debug, Clone, Deserialize)]
pub struct VerifiedSsoUser {
pub token: String,
pub team_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VerificationResponse {
pub token: String,
pub team_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CachingStatus {
Disabled,
Enabled,
OverLimit,
Paused,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachingStatusResponse {
pub status: CachingStatus,
}
/// Membership is the relationship between the logged-in user and a particular
/// team
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Membership {
role: Role,
}
impl Membership {
#[allow(dead_code)]
pub fn new(role: Role) -> Self {
Self { role }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Role {
Member,
Owner,
Viewer,
Developer,
Billing,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Team {
pub id: String,
pub slug: String,
pub name: String,
#[serde(rename = "createdAt")]
pub created_at: u64,
pub created: chrono::DateTime<chrono::Utc>,
pub membership: Membership,
}
impl Team {
pub fn is_owner(&self) -> bool {
matches!(self.membership.role, Role::Owner)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Space {
pub id: String,
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeamsResponse {
pub teams: Vec<Team>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpacesResponse {
pub spaces: Vec<Space>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: String,
pub username: String,
pub email: String,
pub name: Option<String>,
#[serde(rename = "createdAt")]
pub created_at: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserResponse {
pub user: User,
}
pub struct APIClient {
client: reqwest::Client,
base_url: String,
user_agent: String,
}
impl APIClient {
pub async fn get_user(&self, token: &str) -> Result<UserResponse> {
let response = self
.make_retryable_request(|| {
let url = self.make_url("/v2/user");
let request_builder = self
.client
.get(url)
.header("User-Agent", self.user_agent.clone())
.header("Authorization", format!("Bearer {}", token))
.header("Content-Type", "application/json");
request_builder.send()
})
.await?
.error_for_status()?;
response.json().await.map_err(|err| {
anyhow!(
"Error getting user: {}",
err.status()
.and_then(|status| status.canonical_reason())
.unwrap_or(&err.to_string())
)
})
}
pub async fn get_teams(&self, token: &str) -> Result<TeamsResponse> {
let response = self
.make_retryable_request(|| {
let request_builder = self
.client
.get(self.make_url("/v2/teams?limit=100"))
.header("User-Agent", self.user_agent.clone())
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", token));
request_builder.send()
})
.await?
.error_for_status()?;
response.json().await.map_err(|err| {
anyhow!(
"Error getting teams: {}",
err.status()
.and_then(|status| status.canonical_reason())
.unwrap_or(&err.to_string())
)
})
}
pub async fn get_team(&self, token: &str, team_id: &str) -> Result<Option<Team>> {
let response = self
.client
.get(self.make_url("/v2/team"))
.query(&[("teamId", team_id)])
.header("User-Agent", self.user_agent.clone())
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", token))
.send()
.await?
.error_for_status()?;
response.json().await.map_err(|err| {
anyhow!(
"Error getting team: {}",
err.status()
.and_then(|status| status.canonical_reason())
.unwrap_or(&err.to_string())
)
})
}
pub async fn get_caching_status(
&self,
token: &str,
team_id: &str,
team_slug: Option<&str>,
) -> Result<CachingStatusResponse> {
let response = self
.make_retryable_request(|| {
let mut request_builder = self
.client
.get(self.make_url("/v8/artifacts/status"))
.header("User-Agent", self.user_agent.clone())
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", token));
if let Some(slug) = team_slug {
request_builder = request_builder.query(&[("teamSlug", slug)]);
}
if team_id.starts_with("team_") {
request_builder = request_builder.query(&[("teamId", team_id)]);
}
request_builder.send()
})
.await?
.error_for_status()?;
response.json().await.map_err(|err| {
anyhow!(
"Error getting caching status: {}",
err.status()
.and_then(|status| status.canonical_reason())
.unwrap_or(&err.to_string())
)
})
}
pub async fn get_spaces(&self, token: &str, team_id: Option<&str>) -> Result<SpacesResponse> {
// create url with teamId if provided
let endpoint = match team_id {
Some(team_id) => format!("/v0/spaces?limit=100&teamId={}", team_id),
None => "/v0/spaces?limit=100".to_string(),
};
let response = self
.make_retryable_request(|| {
let request_builder = self
.client
.get(self.make_url(endpoint.as_str()))
.header("User-Agent", self.user_agent.clone())
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", token));
request_builder.send()
})
.await?
.error_for_status()?;
response.json().await.map_err(|err| {
anyhow!(
"Error getting spaces: {}",
err.status()
.and_then(|status| status.canonical_reason())
.unwrap_or(&err.to_string())
)
})
}
pub async fn verify_sso_token(&self, token: &str, token_name: &str) -> Result<VerifiedSsoUser> {
let response = self
.make_retryable_request(|| {
let request_builder = self
.client
.get(self.make_url("/registration/verify"))
.query(&[("token", token), ("tokenName", token_name)])
.header("User-Agent", self.user_agent.clone());
request_builder.send()
})
.await?
.error_for_status()?;
let verification_response: VerificationResponse = response.json().await.map_err(|err| {
anyhow!(
"Error verifying token: {}",
err.status()
.and_then(|status| status.canonical_reason())
.unwrap_or(&err.to_string())
)
})?;
Ok(VerifiedSsoUser {
token: verification_response.token,
team_id: verification_response.team_id,
})
}
const RETRY_MAX: u32 = 2;
async fn make_retryable_request<
F: Future<Output = Result<reqwest::Response, reqwest::Error>>,
>(
&self,
request_builder: impl Fn() -> F,
) -> Result<reqwest::Response> {
retry_future(Self::RETRY_MAX, request_builder, Self::should_retry_request).await
}
fn should_retry_request(error: &reqwest::Error) -> bool {
if let Some(status) = error.status() {
if status == StatusCode::TOO_MANY_REQUESTS {
return true;
}
if status.as_u16() >= 500 && status.as_u16() != 501 {
return true;
}
}
false
}
pub fn new(base_url: impl AsRef<str>, timeout: u64, version: &'static str) -> Result<Self> {
let client = if timeout != 0 {
reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(timeout))
.build()?
} else {
reqwest::Client::builder().build()?
};
let user_agent = format!(
"turbo {} {} {} {}",
version,
rustc_version_runtime::version(),
env::consts::OS,
env::consts::ARCH
);
Ok(APIClient {
client,
base_url: base_url.as_ref().to_string(),
user_agent,
})
}
fn make_url(&self, endpoint: &str) -> String {
format!("{}{}", self.base_url, endpoint)
}
}