Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move api-client out of the cli #308

Merged
merged 2 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 27 additions & 0 deletions api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,30 @@ context = { path = "../context" }
serde = { version = "1.0.215", default-features = false, features = ["derive"] }
serde_json = "1.0.133"
bundle = { path = "../bundle" }
sentry = { version = "0.34.0", features = ["debug-images"] }
tokio = { version = "*", default-features = false, features = [
"rt-multi-thread",
"macros",
] }
anyhow = "1.0.44"
reqwest = { version = "0.12.5", default-features = false, features = [
"rustls-tls-native-roots",
"stream",
"json",
] }
log = "0.4.14"
http = "1.1.0"
tokio-retry = { version = "0.3", default-features = false }
constants = { version = "0.0.0", path = "../constants" }

[dev-dependencies]
axum = { version = "0.7.5", features = ["macros"] }
tokio = { version = "*", default-features = false, features = [
"rt-multi-thread",
"macros",
"test-util",
"time",
] }
tempfile = "3.2.0"
test_utils = { path = "../test_utils" }
lazy_static = "1.5.0"
2 changes: 1 addition & 1 deletion cli/src/api_client/call_api.rs → api/src/call_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ where
}
});

let result = Retry::spawn(default_delay(), || (&mut self.action).run()).await;
let result = Retry::spawn(default_delay(), || self.action.run()).await;
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clippy changed this

report_slow_progress_handle.abort();
check_progress_handle.abort();

Expand Down
53 changes: 32 additions & 21 deletions cli/src/api_client/mod.rs → api/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
use std::path::Path;

use crate::call_api::CallApi;
use crate::message;
use anyhow::Context;
use api;
use call_api::CallApi;
use constants::{DEFAULT_ORIGIN, TRUNK_PUBLIC_API_ADDRESS_ENV};
use http::{header::HeaderMap, HeaderValue};
use reqwest::{header, Client, Response, StatusCode};
use tokio::fs;

mod call_api;

pub struct ApiClient {
host: String,
s3_client: Client,
Expand All @@ -26,7 +24,7 @@ impl ApiClient {
if api_token.trim().is_empty() {
return Err(anyhow::anyhow!("Trunk API token is required."));
}
let api_token_header_value = HeaderValue::from_str(&api_token)
let api_token_header_value = HeaderValue::from_str(api_token)
.map_err(|_| anyhow::Error::msg("Trunk API token is not ASCII"))?;

let host = std::env::var(TRUNK_PUBLIC_API_ADDRESS_ENV)
Expand Down Expand Up @@ -69,7 +67,10 @@ impl ApiClient {
})
}

pub async fn create_trunk_repo(&self, request: &api::CreateRepoRequest) -> anyhow::Result<()> {
pub async fn create_repo(
&self,
request: &message::CreateRepoRequest,
) -> anyhow::Result<message::CreateRepoResponse> {
CallApi {
action: || async {
let response = self
Expand All @@ -83,8 +84,13 @@ impl ApiClient {
&response,
CheckUnauthorized::Check,
CheckNotFound::DoNotCheck,
|_| format!("Failed to create repo."),
)
|_| "Failed to create repo.".to_string(),
)?;

response
.json::<message::CreateRepoResponse>()
.await
.context("Failed to get response body as json.")
},
log_progress_message: |time_elapsed, _| {
format!("Communicating with Trunk services is taking longer than expected. It has taken {} seconds so far.", time_elapsed.as_secs())
Expand All @@ -97,10 +103,10 @@ impl ApiClient {
.await
}

pub async fn create_bundle_upload_intent(
pub async fn create_bundle_upload(
&self,
request: &api::CreateBundleUploadRequest,
) -> anyhow::Result<api::CreateBundleUploadResponse> {
request: &message::CreateBundleUploadRequest,
) -> anyhow::Result<message::CreateBundleUploadResponse> {
CallApi {
action: || async {
let response = self
Expand All @@ -118,7 +124,7 @@ impl ApiClient {
)?;

response
.json::<api::CreateBundleUploadResponse>()
.json::<message::CreateBundleUploadResponse>()
.await
.context("Failed to get response body as json.")
},
Expand All @@ -135,8 +141,8 @@ impl ApiClient {

pub async fn get_quarantining_config(
&self,
request: &api::GetQuarantineBulkTestStatusRequest,
) -> anyhow::Result<api::QuarantineConfig> {
request: &message::GetQuarantineConfigRequest,
) -> anyhow::Result<message::GetQuarantineConfigResponse> {
CallApi {
action: || async {
let response = self
Expand All @@ -160,7 +166,7 @@ impl ApiClient {
)?;

response
.json::<api::QuarantineConfig>()
.json::<message::GetQuarantineConfigResponse>()
.await
.context("Failed to get response body as json.")
},
Expand Down Expand Up @@ -211,10 +217,10 @@ impl ApiClient {
.await
}

pub async fn update_bundle_upload_status(
pub async fn update_bundle_upload(
&self,
request: &api::UpdateBundleUploadRequest,
) -> anyhow::Result<()> {
request: &message::UpdateBundleUploadRequest,
) -> anyhow::Result<message::UpdateBundleUploadResponse> {
CallApi {
action: || async {
let response = self
Expand All @@ -234,7 +240,11 @@ impl ApiClient {
request.upload_status
)
},
)
)?;
response
.json::<message::UpdateBundleUploadResponse>()
.await
.context("Failed to get response body as json.")
},
log_progress_message: |time_elapsed, _| {
format!("Communicating with Trunk services is taking longer than expected. It has taken {} seconds so far.", time_elapsed.as_secs())
Expand Down Expand Up @@ -292,6 +302,7 @@ fn status_code_help<T: FnMut(&Response) -> String>(
mod tests {
use std::time::Duration;

use crate::message;
use axum::{http::StatusCode, response::Response};
use tempfile::NamedTempFile;
use test_utils::{mock_logger, mock_sentry, mock_server::MockServerBuilder};
Expand Down Expand Up @@ -329,8 +340,8 @@ mod tests {
.unwrap()
.iter()
.filter(|(_, message)| message.starts_with("Uploading bundle to S3"))
.cloned()
.take(2)
.cloned()
Comment on lines -332 to +344
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was also changed by clippy.

.collect::<Vec<_>>();
assert_eq!(first_two_slow_s3_upload_logs, vec![
(log::Level::Info, String::from("Uploading bundle to S3 is taking longer than expected. It has taken 2 seconds so far.")),
Expand Down Expand Up @@ -368,7 +379,7 @@ mod tests {
api_client.host.clone_from(&state.host);

assert!(api_client
.get_quarantining_config(&api::GetQuarantineBulkTestStatusRequest {
.get_quarantining_config(&message::GetQuarantineConfigRequest {
repo: context::repo::RepoUrlParts {
host: String::from("host"),
owner: String::from("owner"),
Expand Down
69 changes: 3 additions & 66 deletions api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,66 +1,3 @@
use bundle::Test;
use context::repo::RepoUrlParts;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Clone, Deserialize, PartialEq, Eq)]
pub struct CreateBundleUploadRequest {
pub repo: RepoUrlParts,
#[serde(rename = "orgUrlSlug")]
pub org_url_slug: String,
#[serde(rename = "clientVersion")]
pub client_version: String,
}

#[derive(Debug, Serialize, Clone, Deserialize)]
pub struct CreateBundleUploadResponse {
pub id: String,
#[serde(rename = "idV2")]
pub id_v2: String,
pub url: String,
pub key: String,
}

#[derive(Debug, Serialize, Clone, Deserialize, PartialEq, Eq)]
pub enum BundleUploadStatus {
#[serde(rename = "PENDING")]
Pending,
#[serde(rename = "UPLOAD_COMPLETE")]
UploadComplete,
#[serde(rename = "UPLOAD_FAILED")]
UploadFailed,
#[serde(rename = "DRY_RUN")]
DryRun,
}

#[derive(Debug, Serialize, Clone, Deserialize, PartialEq, Eq)]
pub struct UpdateBundleUploadRequest {
pub id: String,
#[serde(rename = "uploadStatus")]
pub upload_status: BundleUploadStatus,
}

#[derive(Debug, Serialize, Clone, Deserialize, PartialEq, Eq)]
pub struct CreateRepoRequest {
pub repo: RepoUrlParts,
#[serde(rename = "orgUrlSlug")]
pub org_url_slug: String,
#[serde(rename = "remoteUrls")]
pub remote_urls: Vec<String>,
}

#[derive(Debug, Serialize, Clone, Deserialize, PartialEq, Eq)]
pub struct GetQuarantineBulkTestStatusRequest {
pub repo: RepoUrlParts,
#[serde(rename = "orgUrlSlug")]
pub org_url_slug: String,
#[serde(rename = "testIdentifiers")]
pub test_identifiers: Vec<Test>,
}

#[derive(Debug, Serialize, Clone, Deserialize, Default)]
pub struct QuarantineConfig {
#[serde(rename = "isDisabled")]
pub is_disabled: bool,
#[serde(rename = "testIds")]
pub quarantined_tests: Vec<String>,
}
mod call_api;
pub mod client;
pub mod message;
Loading
Loading