-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathapi_client.rs
More file actions
473 lines (436 loc) · 14.5 KB
/
api_client.rs
File metadata and controls
473 lines (436 loc) · 14.5 KB
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use std::fmt::Display;
use crate::executor::ExecutorName;
use crate::prelude::*;
use crate::run_environment::RepositoryProvider;
use crate::{cli::Cli, config::CodSpeedConfig};
use console::style;
use gql_client::{Client as GQLClient, ClientConfig};
use nestify::nest;
use serde::{Deserialize, Serialize};
pub struct CodSpeedAPIClient {
gql_client: GQLClient,
unauthenticated_gql_client: GQLClient,
}
impl TryFrom<(&Cli, &CodSpeedConfig)> for CodSpeedAPIClient {
type Error = Error;
fn try_from((args, codspeed_config): (&Cli, &CodSpeedConfig)) -> Result<Self> {
Ok(Self {
gql_client: build_gql_api_client(codspeed_config, args.api_url.clone(), true),
unauthenticated_gql_client: build_gql_api_client(
codspeed_config,
args.api_url.clone(),
false,
),
})
}
}
fn build_gql_api_client(
codspeed_config: &CodSpeedConfig,
api_url: String,
with_auth: bool,
) -> GQLClient {
let headers = if with_auth && codspeed_config.auth.token.is_some() {
let mut headers = std::collections::HashMap::new();
headers.insert(
"Authorization".to_string(),
codspeed_config.auth.token.clone().unwrap(),
);
headers
} else {
Default::default()
};
GQLClient::new_with_config(ClientConfig {
endpoint: api_url,
// Slightly high to account for cold starts
timeout: Some(20),
headers: Some(headers),
proxy: None,
})
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
struct CreateLoginSessionData {
create_login_session: pub struct CreateLoginSessionPayload {
pub callback_url: String,
pub session_id: String,
}
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ConsumeLoginSessionVars {
session_id: String,
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
struct ConsumeLoginSessionData {
consume_login_session: pub struct ConsumeLoginSessionPayload {
pub token: Option<String>
}
}
}
#[derive(Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct FetchLocalRunVars {
pub owner: String,
pub name: String,
pub run_id: String,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RunStatus {
Completed,
Failure,
Pending,
Processing,
}
// Custom deserializer to convert string values to i64
fn deserialize_i64_from_string<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de;
let s = String::deserialize(deserializer)?;
s.parse().map_err(de::Error::custom)
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
pub struct BenchmarkIssues {
pub callgraph_generation_failure: Option<String>,
}
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
pub struct FetchLocalRunRun {
pub id: String,
pub status: RunStatus,
pub url: String,
pub results: Vec<pub struct FetchLocalRunBenchmarkResult {
pub value: f64,
pub benchmark: pub struct FetchLocalRunBenchmark {
pub name: String,
pub executor: ExecutorName,
},
pub issues: Option<BenchmarkIssues>,
pub valgrind: Option<pub struct ValgrindResult {
pub time_distribution: Option<pub struct TimeDistribution {
pub ir: f64,
pub l1m: f64,
pub llm: f64,
pub sys: f64,
}>,
}>,
pub walltime: Option<pub struct WallTimeResult {
pub iterations: f64,
pub stdev: f64,
pub total_time: f64,
}>,
pub memory: Option<pub struct MemoryResult {
#[serde(deserialize_with = "deserialize_i64_from_string")]
pub peak_memory: i64,
#[serde(deserialize_with = "deserialize_i64_from_string")]
pub total_allocated: i64,
#[serde(deserialize_with = "deserialize_i64_from_string")]
pub alloc_calls: i64,
}>,
}>,
}
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
struct FetchLocalRunData {
repository: struct FetchLocalRunRepository {
run: FetchLocalRunRun,
}
}
}
pub struct FetchLocalRunResponse {
pub run: FetchLocalRunRun,
}
#[derive(Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CompareRunsVars {
pub owner: String,
pub name: String,
pub base_run_id: String,
pub head_run_id: String,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum ResultComparisonCategory {
Acknowledged,
Archived,
Ignored,
Improvement,
New,
Regression,
Skipped,
Untouched,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub enum BenchmarkReportStatus {
Improvement,
Missing,
New,
NoChange,
Regression,
}
impl Display for BenchmarkReportStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BenchmarkReportStatus::Improvement => {
write!(f, "{}", style("Improvement").green().bold())
}
BenchmarkReportStatus::Missing => write!(f, "{}", style("Missing").yellow().bold()),
BenchmarkReportStatus::New => write!(f, "{}", style("New").cyan().bold()),
BenchmarkReportStatus::NoChange => write!(f, "{}", style("No Change").dim()),
BenchmarkReportStatus::Regression => write!(f, "{}", style("Regression").red().bold()),
}
}
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
pub struct CompareRunsBenchmarkResult {
pub value: Option<f64>,
pub base_value: Option<f64>,
pub change: Option<f64>,
pub category: ResultComparisonCategory,
pub status: BenchmarkReportStatus,
pub benchmark: pub struct CompareRunsBenchmark {
pub name: String,
pub executor: ExecutorName,
},
pub result: Option<pub struct CompareRunsBenchmarkResultDetail {
pub issues: Option<BenchmarkIssues>,
}>,
}
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
pub struct CompareRunsHeadRun {
pub id: String,
pub status: RunStatus,
}
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
struct CompareRunsData {
repository: struct CompareRunsRepository {
paginated_compare_runs: pub struct CompareRunsComparison {
pub impact: Option<f64>,
pub url: String,
pub head_run: CompareRunsHeadRun,
pub result_comparisons: Vec<CompareRunsBenchmarkResult>,
},
}
}
}
pub struct CompareRunsResponse {
pub comparison: CompareRunsComparison,
}
pub enum CompareRunsOutcome {
Success(CompareRunsResponse),
BaseRunNotFound,
ExecutorMismatch,
}
#[derive(Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GetOrCreateProjectRepositoryVars {
pub name: String,
}
nest! {
#[derive(Debug, Deserialize, Serialize, Clone)]*
#[serde(rename_all = "camelCase")]*
struct GetOrCreateProjectRepositoryData {
get_or_create_project_repository: pub struct GetOrCreateProjectRepositoryPayload {
pub provider: RepositoryProvider,
pub owner: String,
pub name: String,
}
}
}
#[derive(Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GetRepositoryVars {
pub owner: String,
pub name: String,
pub provider: RepositoryProvider,
}
nest! {
#[derive(Debug, Deserialize, Serialize, Clone)]*
#[serde(rename_all = "camelCase")]*
struct GetRepositoryData {
repository_overview: Option<pub struct GetRepositoryPayload {
pub id: String,
}>,
user: Option<pub struct GetRepositoryUser {
pub id: String,
}>,
}
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
struct CurrentUserData {
user: Option<pub struct CurrentUserPayload {
pub login: String,
pub provider: RepositoryProvider,
}>,
}
}
impl CodSpeedAPIClient {
pub async fn get_current_user(&self) -> Result<Option<CurrentUserPayload>> {
let response = self
.gql_client
.query_unwrap::<CurrentUserData>(include_str!("queries/CurrentUser.gql"))
.await;
match response {
Ok(data) => Ok(data.user),
Err(err) => bail!("Failed to get current user: {err}"),
}
}
pub async fn create_login_session(&self) -> Result<CreateLoginSessionPayload> {
let response = self
.unauthenticated_gql_client
.query_unwrap::<CreateLoginSessionData>(include_str!("queries/CreateLoginSession.gql"))
.await;
match response {
Ok(response) => Ok(response.create_login_session),
Err(err) => bail!("Failed to create login session: {err}"),
}
}
pub async fn consume_login_session(
&self,
session_id: &str,
) -> Result<ConsumeLoginSessionPayload> {
let response = self
.unauthenticated_gql_client
.query_with_vars_unwrap::<ConsumeLoginSessionData, ConsumeLoginSessionVars>(
include_str!("queries/ConsumeLoginSession.gql"),
ConsumeLoginSessionVars {
session_id: session_id.to_string(),
},
)
.await;
match response {
Ok(response) => Ok(response.consume_login_session),
Err(err) => bail!("Failed to use login session: {err}"),
}
}
pub async fn compare_runs(&self, vars: CompareRunsVars) -> Result<CompareRunsOutcome> {
let response = self
.gql_client
.query_with_vars_unwrap::<CompareRunsData, CompareRunsVars>(
include_str!("queries/CompareRuns.gql"),
vars,
)
.await;
match response {
Ok(response) => Ok(CompareRunsOutcome::Success(CompareRunsResponse {
comparison: response.repository.paginated_compare_runs,
})),
Err(err) if err.contains_error_code("UNAUTHENTICATED") => {
bail!("Your session has expired, please login again using `codspeed auth login`")
}
Err(err) if err.contains_error_code("RUN_NOT_FOUND") => {
Ok(CompareRunsOutcome::BaseRunNotFound)
}
Err(err) if err.contains_error_code("NOT_FOUND") => {
Ok(CompareRunsOutcome::ExecutorMismatch)
}
Err(err) => bail!("Failed to compare runs: {err:?}"),
}
}
pub async fn fetch_local_run(&self, vars: FetchLocalRunVars) -> Result<FetchLocalRunResponse> {
let response = self
.gql_client
.query_with_vars_unwrap::<FetchLocalRunData, FetchLocalRunVars>(
include_str!("queries/FetchLocalRun.gql"),
vars,
)
.await;
match response {
Ok(response) => Ok(FetchLocalRunResponse {
run: response.repository.run,
}),
Err(err) if err.contains_error_code("UNAUTHENTICATED") => {
bail!("Your session has expired, please login again using `codspeed auth login`")
}
Err(err) => bail!("Failed to fetch local run: {err}"),
}
}
pub async fn get_or_create_project_repository(
&self,
vars: GetOrCreateProjectRepositoryVars,
) -> Result<GetOrCreateProjectRepositoryPayload> {
let response = self
.gql_client
.query_with_vars_unwrap::<
GetOrCreateProjectRepositoryData,
GetOrCreateProjectRepositoryVars,
>(
include_str!("queries/GetOrCreateProjectRepository.gql"),
vars.clone(),
)
.await;
match response {
Ok(response) => Ok(response.get_or_create_project_repository),
Err(err) if err.contains_error_code("UNAUTHENTICATED") => {
bail!("Your session has expired, please login again using `codspeed auth login`")
}
Err(err) => bail!("Failed to get or create project repository: {err}"),
}
}
/// Check if a repository exists in CodSpeed.
/// Returns Some(payload) if the repository exists, None otherwise.
pub async fn get_repository(
&self,
vars: GetRepositoryVars,
) -> Result<Option<GetRepositoryPayload>> {
let response = self
.gql_client
.query_with_vars_unwrap::<GetRepositoryData, GetRepositoryVars>(
include_str!("queries/GetRepository.gql"),
vars.clone(),
)
.await;
match response {
Ok(response) => {
if response.user.is_none() {
bail!(
"Your session has expired, please login again using `codspeed auth login`"
);
}
Ok(response.repository_overview)
}
Err(err) if err.contains_error_code("REPOSITORY_NOT_FOUND") => Ok(None),
Err(err) if err.contains_error_code("UNAUTHENTICATED") => {
bail!("Your session has expired, please login again using `codspeed auth login`")
}
Err(err) => {
bail!("Failed to get repository: {err}")
}
}
}
}
impl CodSpeedAPIClient {
/// Create a test API client for use in tests
#[cfg(test)]
pub fn create_test_client() -> Self {
Self::create_test_client_with_url("http://localhost:8000/graphql".to_owned())
}
/// Create a test API client with a custom URL for use in tests
#[cfg(test)]
pub fn create_test_client_with_url(api_url: String) -> Self {
let codspeed_config = CodSpeedConfig::default();
Self::try_from((&Cli::test_with_url(api_url), &codspeed_config)).unwrap()
}
}