-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathapi_client.rs
More file actions
355 lines (328 loc) · 11.1 KB
/
api_client.rs
File metadata and controls
355 lines (328 loc) · 11.1 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
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 FetchLocalRunReportVars {
pub owner: String,
pub name: String,
pub run_id: String,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub enum ReportConclusion {
AcknowledgedFailure,
Failure,
MissingBaseRun,
Success,
}
impl Display for ReportConclusion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ReportConclusion::AcknowledgedFailure => {
write!(f, "{}", style("Acknowledged Failure").yellow().bold())
}
ReportConclusion::Failure => write!(f, "{}", style("Failure").red().bold()),
ReportConclusion::MissingBaseRun => {
write!(f, "{}", style("Missing Base Run").yellow().bold())
}
ReportConclusion::Success => write!(f, "{}", style("Success").green().bold()),
}
}
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RunStatus {
Completed,
Failure,
Pending,
Processing,
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
pub struct FetchLocalRunReportRun {
pub id: String,
pub status: RunStatus,
pub url: String,
pub head_reports: Vec<pub struct FetchLocalRunReportHeadReport {
pub id: String,
pub impact: Option<f64>,
pub conclusion: ReportConclusion,
}>,
pub results: Vec<pub struct FetchLocalRunBenchmarkResult {
pub value: f64,
pub benchmark: pub struct FetchLocalRunBenchmark {
pub name: String,
pub executor: ExecutorName,
},
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,
}>,
}>,
}
}
// 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")]*
struct FetchLocalRunReportData {
repository: pub struct FetchLocalRunReportRepository {
settings: struct FetchLocalRunReportSettings {
allowed_regression: f64,
},
run: FetchLocalRunReportRun,
}
}
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[serde(rename_all = "camelCase")]*
struct FetchLocalExecReportData {
project: pub struct FetchLocalExecReportProject {
run: FetchLocalRunReportRun,
}
}
}
pub struct FetchLocalRunReportResponse {
pub allowed_regression: f64,
pub run: FetchLocalRunReportRun,
}
#[derive(Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GetOrCreateProjectRepositoryVars {
pub name: String,
}
nest! {
#[derive(Debug, Deserialize, Serialize)]*
#[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)]*
#[serde(rename_all = "camelCase")]*
struct GetRepositoryData {
repository_overview: Option<pub struct GetRepositoryPayload {
pub id: String,
}>
}
}
impl CodSpeedAPIClient {
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 fetch_local_run_report(
&self,
vars: FetchLocalRunReportVars,
) -> Result<FetchLocalRunReportResponse> {
let response = self
.gql_client
.query_with_vars_unwrap::<FetchLocalRunReportData, FetchLocalRunReportVars>(
include_str!("queries/FetchLocalRunReport.gql"),
vars.clone(),
)
.await;
match response {
Ok(response) => Ok(FetchLocalRunReportResponse {
allowed_regression: response.repository.settings.allowed_regression,
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 report: {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) => 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()
}
}