-
Notifications
You must be signed in to change notification settings - Fork 16
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
Add cli to generate and install plugin bundle #6397
base: develop
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
pub(super) const AUTH_QUERY: &str = r#" | ||
query AuthToken($username: String!, $password: String) { | ||
root: authToken(password: $password, username: $username) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this root relates to the |
||
... on AuthToken { | ||
__typename | ||
token | ||
} | ||
... on AuthTokenError { | ||
__typename | ||
error { | ||
description | ||
} | ||
} | ||
} | ||
} | ||
"#; |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,172 @@ | ||||||
use std::{ | ||||||
io::{self, Read}, | ||||||
path::PathBuf, | ||||||
}; | ||||||
|
||||||
use auth::AUTH_QUERY; | ||||||
use reqwest::{multipart, RequestBuilder, Url}; | ||||||
use serde::{de::DeserializeOwned, Deserialize, Serialize}; | ||||||
|
||||||
#[derive(Debug)] | ||||||
pub struct Api { | ||||||
url: Url, | ||||||
token: String, | ||||||
} | ||||||
|
||||||
#[allow(dead_code)] | ||||||
#[derive(Debug, Deserialize, Serialize)] | ||||||
struct GraphQlResponse { | ||||||
data: Root, | ||||||
} | ||||||
|
||||||
#[allow(dead_code)] | ||||||
#[derive(Debug, Deserialize, Serialize)] | ||||||
struct Root { | ||||||
root: serde_json::Value, | ||||||
} | ||||||
|
||||||
mod auth; | ||||||
pub mod queries_mutations; | ||||||
|
||||||
#[derive(thiserror::Error, Debug)] | ||||||
pub enum ApiError { | ||||||
#[error("Error while sending request to {1}")] | ||||||
SendingRequest(#[source] reqwest::Error, Url), | ||||||
#[error("Error while getting text, status {1:?}")] | ||||||
GettingText(#[source] reqwest::Error, reqwest::StatusCode), | ||||||
#[error("Error parsing gql response: {1}")] | ||||||
ParsingJson(#[source] serde_json::Error, String), | ||||||
#[error("Error validating typename, expected typename {expected_typename}, result: {json}")] | ||||||
ValidatingTypename { | ||||||
expected_typename: String, | ||||||
json: String, | ||||||
}, | ||||||
#[error("Error opening file, {1}")] | ||||||
OpeningFile(#[source] io::Error, PathBuf), | ||||||
#[error("Error reading file, {1}")] | ||||||
ReadingFile(#[source] io::Error, PathBuf), | ||||||
} | ||||||
use service::UploadedFile; | ||||||
use ApiError as Error; | ||||||
|
||||||
impl Api { | ||||||
pub async fn new_with_token( | ||||||
url: Url, | ||||||
username: String, | ||||||
password: String, | ||||||
) -> Result<Self, Error> { | ||||||
let result = _gql( | ||||||
&url.join("graphql").unwrap(), | ||||||
AUTH_QUERY, | ||||||
serde_json::json! ({ | ||||||
"username": username, | ||||||
"password": password, | ||||||
}), | ||||||
None, | ||||||
Some("AuthToken"), | ||||||
) | ||||||
.await?; | ||||||
|
||||||
let token = result["token"].as_str().unwrap().to_string(); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. extracting and saving token, unwrap should be save as we've checked 'expected_typename' and query is const |
||||||
|
||||||
Ok(Api { url, token }) | ||||||
} | ||||||
|
||||||
pub async fn gql( | ||||||
&self, | ||||||
query: &str, | ||||||
variables: serde_json::Value, | ||||||
expected_typename: Option<&str>, | ||||||
) -> Result<serde_json::Value, Error> { | ||||||
_gql( | ||||||
&self.url.join("graphql").unwrap(), | ||||||
query, | ||||||
variables, | ||||||
Some(&self.token), | ||||||
expected_typename, | ||||||
) | ||||||
.await | ||||||
} | ||||||
|
||||||
pub async fn upload_file(&self, path: PathBuf) -> Result<UploadedFile, Error> { | ||||||
let url = self.url.join("upload").unwrap(); | ||||||
|
||||||
println!("{}", url); | ||||||
let auth_cooke_value = format!(r#"auth={{"token": "{}"}}"#, self.token); | ||||||
let built_request = reqwest::Client::new() | ||||||
.post(url.clone()) | ||||||
.header("Cookie", auth_cooke_value); | ||||||
|
||||||
// Add file to request | ||||||
let mut file_handle = | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Copied from open-msupply/server/service/src/sync/api_v6/upload_file.rs Lines 60 to 61 in 86be0d6
|
||||||
std::fs::File::open(path.clone()).map_err(|e| Error::OpeningFile(e, path.clone()))?; | ||||||
let mut file_bytes = Vec::new(); | ||||||
file_handle | ||||||
.read_to_end(&mut file_bytes) | ||||||
.map_err(|e| Error::ReadingFile(e, path))?; | ||||||
let file_part = multipart::Part::bytes(file_bytes).file_name("upload".to_string()); | ||||||
let multipart_form = multipart::Form::new().part("files", file_part); | ||||||
let built_request = built_request.multipart(multipart_form); | ||||||
|
||||||
// Send and return file_id | ||||||
|
||||||
send_and_parse(built_request, url).await | ||||||
} | ||||||
} | ||||||
|
||||||
async fn _gql( | ||||||
url: &Url, | ||||||
query: &str, | ||||||
variables: serde_json::Value, | ||||||
token: Option<&str>, | ||||||
expected_typename: Option<&str>, | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Will check typename at the 'root' if specified |
||||||
) -> Result<serde_json::Value, Error> { | ||||||
let body = serde_json::json!({ | ||||||
"query": query, | ||||||
"variables": variables | ||||||
}); | ||||||
|
||||||
println!("{}", url); | ||||||
let mut client = reqwest::Client::new().post(url.clone()); | ||||||
|
||||||
if let Some(token) = token { | ||||||
client = client.bearer_auth(token) | ||||||
}; | ||||||
|
||||||
let built_request = client.json(&body); | ||||||
|
||||||
let json_result: GraphQlResponse = send_and_parse(built_request, url.clone()).await?; | ||||||
|
||||||
let result = json_result.data.root; | ||||||
|
||||||
let Some(expected_typename) = expected_typename else { | ||||||
return Ok(result); | ||||||
}; | ||||||
|
||||||
if result["__typename"] != expected_typename { | ||||||
return Err(Error::ValidatingTypename { | ||||||
expected_typename: expected_typename.to_string(), | ||||||
json: serde_json::to_string(&result).unwrap(), | ||||||
}); | ||||||
} | ||||||
|
||||||
Ok(result) | ||||||
} | ||||||
|
||||||
async fn send_and_parse<T: DeserializeOwned>( | ||||||
built_request: RequestBuilder, | ||||||
url: Url, | ||||||
) -> Result<T, Error> { | ||||||
let response = built_request | ||||||
.send() | ||||||
.await | ||||||
.map_err(|e| Error::SendingRequest(e, url))?; | ||||||
|
||||||
let status = response.status(); | ||||||
let text_result = response | ||||||
.text() | ||||||
.await | ||||||
.map_err(|e| Error::GettingText(e, status))?; | ||||||
|
||||||
Ok(serde_json::from_str(&text_result).map_err(|e| Error::ParsingJson(e, text_result))?) | ||||||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
pub const INSTALL_PLUGINS: &'static str = r#" | ||
mutation Query($fileId: String!) { | ||
root: centralServer { | ||
__typename | ||
plugins { | ||
installUploadedPlugin(fileId: $fileId) { | ||
backendPluginCodes | ||
} | ||
} | ||
} | ||
}"#; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,10 @@ | ||
// To upload to server (from this dir): | ||
// cargo run --bin remote_server_cli -- generate-and-install-plugin-bundle -i './service/src/backend_plugin/examples/amc' -u 'http://localhost:8000' --username 'test' --password 'pass' | ||
// OR | ||
// cargo run --bin remote_server_cli -- generate-plugin-bundle -i './service/src/backend_plugin/examples/amc' -o 'check.json' | ||
// Can install via CLI | ||
// cargo run --bin remote_server_cli -- install-plugin-bundle --path 'check.json' -u 'http://localhost:8000' --username 'test' --password 'pass' | ||
// Or can install via curl | ||
// cargo run --bin remote_server_cli -- generate-plugin-bundle -i './service/src/backend_plugin/examples/amc' -o 'check.json' | ||
// curl -H 'Content-Type: application/json' --data '{"query":"query MyQuery {authToken(password: \"pass\", username: \"Admin\") {... on AuthToken {token}... on AuthTokenError {error {description}}}}","variables":{}}' 'http://localhost:8000/graphql' | ||
// TOKEN=token from above | ||
|
@@ -36,6 +42,9 @@ let plugins = { | |
const sql_result = sql(sql_statement); | ||
const response = {}; | ||
|
||
// Fill all item_ids with default | ||
item_ids.forEach((itemId) => (response[itemId] = { average_monthly_consumption: 1 })); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If there is not 'consumption' then it will be zero, changed to '1' to see effect of the plugin |
||
|
||
sql_result.forEach(({ item_id, consumption }) => { | ||
response[item_id] = { | ||
average_monthly_consumption: consumption / (DAY_LOOKBACK / DAYS_IN_MONTH), | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Was thinking maybe we just need generate and install, kept this one however as a manual was to install via CLI