Skip to content

Commit

Permalink
applying code formating using
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelnikonorov committed Jun 24, 2024
1 parent e0bdcf5 commit a1cd3bf
Show file tree
Hide file tree
Showing 7 changed files with 98 additions and 72 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,4 @@ jobs:
- name: Format
run: |
. $HOME/.cargo/env
cargo fmt -- --check
cargo fmt
11 changes: 6 additions & 5 deletions lib/src/configuration.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@


#[derive(Debug, Clone)]
pub struct Configuration {
pub base_path: String,
Expand All @@ -19,9 +17,12 @@ pub struct ApiKey {
pub key: String,
}


impl Configuration {
pub fn new(base_path: String, user_agent: Option<String>, oauth_access_token: Option<String>) -> Self {
pub fn new(
base_path: String,
user_agent: Option<String>,
oauth_access_token: Option<String>,
) -> Self {
Configuration {
base_path,
user_agent,
Expand Down Expand Up @@ -49,4 +50,4 @@ impl Default for Configuration {
api_key: None,
}
}
}
}
4 changes: 2 additions & 2 deletions lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ extern crate serde_derive;
#[cfg(test)]
mod test_utils;

pub mod configuration;
pub mod serviceinfo;
pub mod tes;
pub mod transport;
pub mod serviceinfo;
pub mod configuration;
29 changes: 12 additions & 17 deletions lib/src/serviceinfo/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod models;
use crate::transport::Transport;
use crate::configuration::Configuration;
use crate::transport::Transport;

#[derive(Clone)]
pub struct ServiceInfo {
Expand All @@ -19,31 +19,26 @@ impl ServiceInfo {
pub async fn get(&self) -> Result<models::Service, Box<dyn std::error::Error>> {
let response = self.transport.get("/service-info", None).await;
match response {
Ok(response_body) => {
match serde_json::from_str::<models::Service>(&response_body) {
Ok(tes_create_task_response) => Ok(tes_create_task_response),
Err(e) => {
log::error!("Failed to deserialize response: {}", e);
Err("Failed to deserialize response".into())
},
Ok(response_body) => match serde_json::from_str::<models::Service>(&response_body) {
Ok(tes_create_task_response) => Ok(tes_create_task_response),
Err(e) => {
log::error!("Failed to deserialize response: {}", e);
Err("Failed to deserialize response".into())
}
},
Err(e) => {
log::error!("Error: {}", e);
Err(e)
},
}
}
}

}



#[cfg(test)]
mod tests {
use crate::test_utils::{setup, ensure_funnel_running};
use crate::serviceinfo::ServiceInfo;
use crate::configuration::Configuration;
use crate::serviceinfo::ServiceInfo;
use crate::test_utils::{ensure_funnel_running, setup};
use tokio;

#[tokio::test]
Expand All @@ -62,7 +57,7 @@ mod tests {
// assert_eq!(result.unwrap().id, "test");
// assert_eq!(result.unwrap().name, "test");
}
#[tokio::test]
#[tokio::test]
async fn test_get_service_info_from_funnel() {
setup();
let mut config = Configuration::default();
Expand All @@ -74,10 +69,10 @@ mod tests {
match service_info.get().await {
Ok(service) => {
println!("Service Info: {:?}", service);
},
}
Err(e) => {
println!("Failed to get service info: {}", e);
},
}
}
}
}
69 changes: 39 additions & 30 deletions lib/src/tes/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
pub mod models;
use crate::transport::Transport;
use crate::configuration::Configuration;
use crate::serviceinfo::models::Service;
use serde_json;
use serde_json::json;
use crate::serviceinfo::ServiceInfo;
use crate::configuration::Configuration;
use crate::tes::models::TesTask;
use crate::tes::models::TesCreateTaskResponse;
use crate::tes::models::TesState;
use crate::tes::models::TesTask;
use crate::transport::Transport;
use serde_json;
use serde_json::json;

// ***
// should TES.create return Task? which in turn can do status() and other existing-task-related stuff
Expand Down Expand Up @@ -59,57 +59,65 @@ impl TES {

fn check(&self) -> bool {
let resp = &self.service;
return resp.as_ref().unwrap().r#type.artifact == "tes"
return resp.as_ref().unwrap().r#type.artifact == "tes";
}

pub async fn create(&self, task: TesTask/*, params: models::TesTask*/) -> Result<TesCreateTaskResponse, Box<dyn std::error::Error>> {
pub async fn create(
&self,
task: TesTask, /*, params: models::TesTask*/
) -> Result<TesCreateTaskResponse, Box<dyn std::error::Error>> {
// First, check if the service is of TES class
if !self.check() {
// If check fails, log an error and return an Err immediately
log::error!("Service check failed");
return Err("Service check failed".into());
// If check fails, log an error and return an Err immediately
log::error!("Service check failed");
return Err("Service check failed".into());
}
// todo: version in url based on serviceinfo or user config
let response = self.transport.post("/ga4gh/tes/v1/tasks", json!(task)).await;
let response = self
.transport
.post("/ga4gh/tes/v1/tasks", json!(task))
.await;
match response {
Ok(response_body) => {
match serde_json::from_str::<TesCreateTaskResponse>(&response_body) {
Ok(tes_create_task_response) => Ok(tes_create_task_response),
Err(e) => {
log::error!("Failed to deserialize response: {}", e);
Err("Failed to deserialize response".into())
},
}
}
},
}
Err(e) => {
log::error!("Error: {}", e);
Err(e)
},
}
}
}

// pub async fn status(&self, task: &TesCreateTaskResponse) -> Result<TesState, Box<dyn std::error::Error>> {
pub async fn status(&self, task_id: &str, view: &str) -> Result<TesState, Box<dyn std::error::Error>> {
pub async fn status(
&self,
task_id: &str,
view: &str,
) -> Result<TesState, Box<dyn std::error::Error>> {
// ?? move to Task::status()
// todo: version in url based on serviceinfo or user config
let url = format!("/ga4gh/tes/v1/tasks/{}", task_id);
let params = [("view", view)];
let params_value = serde_json::json!(params);
let response = self.transport.get(&url, Some(params_value)).await;
match response {
Ok(response_body) => {
match serde_json::from_str::<TesState>(&response_body) {
Ok(tes_state) => Ok(tes_state),
Err(e) => {
log::error!("Failed to deserialize response: {}", e);
Err("Failed to deserialize response".into())
},
Ok(response_body) => match serde_json::from_str::<TesState>(&response_body) {
Ok(tes_state) => Ok(tes_state),
Err(e) => {
log::error!("Failed to deserialize response: {}", e);
Err("Failed to deserialize response".into())
}
},
Err(e) => {
log::error!("Error: {}", e);
Err(e)
},
}
}
}

Expand All @@ -118,10 +126,10 @@ impl TES {

#[cfg(test)]
mod tests {
use crate::test_utils::{setup, ensure_funnel_running, FUNNEL_PORT};
use crate::tes::TES;
use crate::configuration::Configuration;
use crate::tes::models::TesTask;
use crate::tes::TES;
use crate::test_utils::{ensure_funnel_running, setup, FUNNEL_PORT};
// use crate::tes::models::TesCreateTaskResponse;

async fn create_task() -> Result<String, Box<dyn std::error::Error>> {
Expand All @@ -130,10 +138,11 @@ mod tests {
let funnel_url = ensure_funnel_running().await;
config.set_base_path(&funnel_url);
let tes = TES::new(&config).await;

let task_json = std::fs::read_to_string("./lib/sample/grape.tes").expect("Unable to read file");

let task_json =
std::fs::read_to_string("./lib/sample/grape.tes").expect("Unable to read file");
let task: TesTask = serde_json::from_str(&task_json).expect("JSON was not well-formatted");

let task = tes?.create(task).await?;
Ok(task.id)
}
Expand All @@ -142,15 +151,15 @@ mod tests {
async fn test_task_create() {
setup();
ensure_funnel_running().await;

let task = create_task().await.expect("Failed to create task");
assert!(!task.is_empty(), "Task ID should not be empty"); // doube check if it's a correct assertion
}

// #[tokio::test]
// async fn test_task_status() {
// setup();

// let task = create_task().await.expect("Failed to create task");
// // Now use task to get the task status...
// // todo: assert_eq!(task.status().await, which status?);
Expand Down
4 changes: 2 additions & 2 deletions lib/src/test_utils.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use log::info;
use std::env;
use std::process::Command;
use std::str;
use log::info;
use std::sync::Once;

pub const FUNNEL_HOST: &str = "http://localhost";
Expand Down Expand Up @@ -32,4 +32,4 @@ pub async fn ensure_funnel_running() -> String {

let funnel_url = format!("{}:{}", FUNNEL_HOST, FUNNEL_PORT);
funnel_url
}
}
51 changes: 36 additions & 15 deletions lib/src/transport.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::configuration::Configuration;
use log::error;
use reqwest::Client;
use serde_json::Value;
use std::error::Error;
use crate::configuration::Configuration;
use log::error;

// note: could implement custom certs handling, such as in-TEE generated ephemerial certs
#[derive(Clone)]
Expand All @@ -29,13 +29,23 @@ impl Transport {
let full_url = format!("{}{}", self.config.base_path, endpoint);
let url = reqwest::Url::parse(&full_url);
if url.is_err() {
error!("Invalid endpoint (shouldn't contain base url): {}", endpoint);
return Err(Box::new(std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid endpoint")));
error!(
"Invalid endpoint (shouldn't contain base url): {}",
endpoint
);
return Err(Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Invalid endpoint",
)));
}

let resp = self.client
let resp = self
.client
.request(method, &full_url)
.header(reqwest::header::USER_AGENT, self.config.user_agent.clone().unwrap_or_default())
.header(
reqwest::header::USER_AGENT,
self.config.user_agent.clone().unwrap_or_default(),
)
.json(&data)
.query(&params)
.send()
Expand All @@ -47,33 +57,44 @@ impl Transport {
if status.is_success() {
Ok(content)
} else {
Err(Box::new(std::io::Error::new(std::io::ErrorKind::Other, content)))
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
content,
)))
}
}

pub async fn get(&self, endpoint: &str, params: Option<Value>) -> Result<String, Box<dyn Error>> {
self.request(reqwest::Method::GET, endpoint, None, params).await
pub async fn get(
&self,
endpoint: &str,
params: Option<Value>,
) -> Result<String, Box<dyn Error>> {
self.request(reqwest::Method::GET, endpoint, None, params)
.await
}

pub async fn post(&self, endpoint: &str, data: Value) -> Result<String, Box<dyn Error>> {
self.request(reqwest::Method::POST, endpoint, Some(data), None).await
self.request(reqwest::Method::POST, endpoint, Some(data), None)
.await
}

pub async fn put(&self, endpoint: &str, data: Value) -> Result<String, Box<dyn Error>> {
self.request(reqwest::Method::PUT, endpoint, Some(data), None).await
self.request(reqwest::Method::PUT, endpoint, Some(data), None)
.await
}

pub async fn delete(&self, endpoint: &str) -> Result<String, Box<dyn Error>> {
self.request(reqwest::Method::DELETE, endpoint, None, None).await
self.request(reqwest::Method::DELETE, endpoint, None, None)
.await
}

// other HTTP methods can be added here
}

#[cfg(test)]
mod tests {
use crate::test_utils::setup;
use crate::configuration::Configuration;
use crate::test_utils::setup;
use crate::transport::Transport;
use mockito::mock;

Expand All @@ -86,7 +107,7 @@ mod tests {
let _m = mock("GET", "/test")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"message": "success"}"#)
.with_body(r#"{"message": "success"}"#)
.create();

let config = Configuration::new(base_url.clone(), None, None);
Expand All @@ -97,4 +118,4 @@ mod tests {
let body = response.unwrap();
assert_eq!(body, r#"{"message": "success"}"#);
}
}
}

0 comments on commit a1cd3bf

Please sign in to comment.