Skip to content

Commit

Permalink
cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
G8XSU committed Apr 26, 2023
1 parent f66c748 commit 993038e
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 139 deletions.
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ hard_tabs = true # use tab characters for indentation, spaces for alignment
use_field_init_shorthand = true
max_width = 120
use_small_heuristics = "Max"
chain_width = 80
fn_args_layout = "Compressed"
20 changes: 11 additions & 9 deletions vss-accessor/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@ use std::fs::File;
use std::path::Path;

fn main() {
download_file("https://raw.githubusercontent.com/lightningdevkit/vss-server/main/app/src/main/proto/vss.proto",
"src/proto/vss.proto").unwrap();
download_file(
"https://raw.githubusercontent.com/lightningdevkit/vss-server/main/app/src/main/proto/vss.proto",
"src/proto/vss.proto",
)
.unwrap();

prost_build::compile_protos(&["src/proto/vss.proto"],
&["src/"]).unwrap();
prost_build::compile_protos(&["src/proto/vss.proto"], &["src/"]).unwrap();
}

fn download_file(url: &str, save_to: &str) -> Result<(), Box<dyn std::error::Error>> {
let mut response = reqwest::blocking::get(url)?;
fs::create_dir_all(Path::new(save_to).parent().unwrap())?;
let mut out_file = File::create(save_to)?;
response.copy_to(&mut out_file)?;
Ok(())
let mut response = reqwest::blocking::get(url)?;
fs::create_dir_all(Path::new(save_to).parent().unwrap())?;
let mut out_file = File::create(save_to)?;
response.copy_to(&mut out_file)?;
Ok(())
}
156 changes: 78 additions & 78 deletions vss-accessor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,93 +3,93 @@ use reqwest;
use reqwest::Client;
use std::error::Error;

use crate::vss::{GetObjectRequest, GetObjectResponse, KeyValue, ListKeyVersionsRequest, ListKeyVersionsResponse, PutObjectRequest, PutObjectResponse};
use crate::vss::{
GetObjectRequest, GetObjectResponse, KeyValue, ListKeyVersionsRequest, ListKeyVersionsResponse, PutObjectRequest,
PutObjectResponse,
};
use crate::vss_error::VssError;

mod vss_error;

pub mod vss {
include!(concat!(env!("OUT_DIR"), "/org.vss.rs"));
include!(concat!(env!("OUT_DIR"), "/org.vss.rs"));
}

pub struct VssAccessor {
base_url: String,
client: Client,
base_url: String,
client: Client,
}

impl VssAccessor {
pub fn new(base_url: &str) -> Result<Self, Box<dyn Error>> {
let client = Client::new();
Ok(Self { base_url: String::from(base_url), client })
}

pub async fn get(&self, store: &str, key: &str) -> Result<GetObjectResponse, VssError> {
let url = format!("{}/getObject", self.base_url);

let request = GetObjectRequest { store_id: store.into(), key: key.to_string() };

let response_raw = self.client.post(url)
.body(request.encode_to_vec())
.send().await?;
let status = response_raw.status();
let payload = &response_raw.bytes().await?;

if status.is_success() {
let response = GetObjectResponse::decode(&payload[..])?;
Ok(response)
} else {
Err(VssError::new(status, &payload))
}
}

pub async fn put(&self, store: &str, global_version: Option<i64>, key: &str, version: i64, value: &[u8])
-> Result<PutObjectResponse, VssError> {
let kv = KeyValue { key: String::from(key), version, value: value.to_vec() };
return self.put_tx(store, global_version, vec![kv]).await;
}

pub async fn put_tx(&self, store: &str, global_version: Option<i64>, transaction_items: Vec<KeyValue>)
-> Result<PutObjectResponse, VssError> {
let url = format!("{}/putObjects", self.base_url);

let request = PutObjectRequest { store_id: store.into(), global_version, transaction_items };

let response_raw = self.client.post(url)
.body(request.encode_to_vec())
.send().await?;
let status = response_raw.status();
let payload = &response_raw.bytes().await?;

if status.is_success() {
let response = PutObjectResponse::decode(&payload[..])?;
Ok(response)
} else {
Err(VssError::new(status, &payload))
}
}

pub async fn list_key_versions(&self, store: &str, key_prefix: &str, page_size: Option<i32>, page_token: Option<String>)
-> Result<ListKeyVersionsResponse, VssError> {
let url = format!("{}/listKeyVersions", self.base_url);

let request = ListKeyVersionsRequest {
store_id: store.to_string(),
key_prefix: Some(key_prefix.to_string()),
page_size,
page_token,
};

let response_raw = self.client.post(url)
.body(request.encode_to_vec())
.send().await?;
let status = response_raw.status();
let payload = &response_raw.bytes().await?;

if status.is_success() {
let response = ListKeyVersionsResponse::decode(&payload[..])?;
Ok(response)
} else {
Err(VssError::new(status, &payload))
}
}
pub fn new(base_url: &str) -> Result<Self, Box<dyn Error>> {
let client = Client::new();
Ok(Self { base_url: String::from(base_url), client })
}

pub async fn get(&self, store: &str, key: &str) -> Result<GetObjectResponse, VssError> {
let url = format!("{}/getObject", self.base_url);

let request = GetObjectRequest { store_id: store.into(), key: key.to_string() };

let response_raw = self.client.post(url).body(request.encode_to_vec()).send().await?;
let status = response_raw.status();
let payload = &response_raw.bytes().await?;

if status.is_success() {
let response = GetObjectResponse::decode(&payload[..])?;
Ok(response)
} else {
Err(VssError::new(status, &payload))
}
}

pub async fn put(
&self, store: &str, global_version: Option<i64>, key: &str, version: i64, value: &[u8],
) -> Result<PutObjectResponse, VssError> {
let kv = KeyValue { key: String::from(key), version, value: value.to_vec() };
return self.put_tx(store, global_version, vec![kv]).await;
}

pub async fn put_tx(
&self, store: &str, global_version: Option<i64>, transaction_items: Vec<KeyValue>,
) -> Result<PutObjectResponse, VssError> {
let url = format!("{}/putObjects", self.base_url);

let request = PutObjectRequest { store_id: store.into(), global_version, transaction_items };

let response_raw = self.client.post(url).body(request.encode_to_vec()).send().await?;
let status = response_raw.status();
let payload = &response_raw.bytes().await?;

if status.is_success() {
let response = PutObjectResponse::decode(&payload[..])?;
Ok(response)
} else {
Err(VssError::new(status, &payload))
}
}

pub async fn list_key_versions(
&self, store: &str, key_prefix: &str, page_size: Option<i32>, page_token: Option<String>,
) -> Result<ListKeyVersionsResponse, VssError> {
let url = format!("{}/listKeyVersions", self.base_url);

let request = ListKeyVersionsRequest {
store_id: store.to_string(),
key_prefix: Some(key_prefix.to_string()),
page_size,
page_token,
};

let response_raw = self.client.post(url).body(request.encode_to_vec()).send().await?;
let status = response_raw.status();
let payload = &response_raw.bytes().await?;

if status.is_success() {
let response = ListKeyVersionsResponse::decode(&payload[..])?;
Ok(response)
} else {
Err(VssError::new(status, &payload))
}
}
}
104 changes: 52 additions & 52 deletions vss-accessor/src/vss_error.rs
Original file line number Diff line number Diff line change
@@ -1,75 +1,75 @@
use std::error::Error;
use std::fmt::{Display, Formatter};
use prost::{DecodeError, Message};
use crate::vss::{ErrorCode, ErrorResponse};
use prost::bytes::Bytes;
use prost::{DecodeError, Message};
use reqwest::StatusCode;
use crate::vss::{ErrorCode, ErrorResponse};
use std::error::Error;
use std::fmt::{Display, Formatter};

#[derive(Debug)]
pub enum VssError {
InvalidRequestError(ErrorResponse),
ConflictError(ErrorResponse),
InternalServerError(ErrorResponse),
InternalError(String),
InvalidRequestError(ErrorResponse),
ConflictError(ErrorResponse),
InternalServerError(ErrorResponse),
InternalError(String),
}

impl VssError {
pub fn new(status: StatusCode, payload: &&Bytes) -> VssError {
match ErrorResponse::decode(&payload[..]) {
Ok(error_response) => VssError::from(error_response),
Err(e) => {
let message = format!(
"Unable to decode ErrorResponse from server, HttpStatusCode: {}, DecodeErr: {}",
status, e);
VssError::InternalError(message)
}
}
}
pub fn new(status: StatusCode, payload: &&Bytes) -> VssError {
match ErrorResponse::decode(&payload[..]) {
Ok(error_response) => VssError::from(error_response),
Err(e) => {
let message =
format!("Unable to decode ErrorResponse from server, HttpStatusCode: {}, DecodeErr: {}", status, e);
VssError::InternalError(message)
}
}
}
}

impl Display for VssError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match *self {
VssError::InvalidRequestError(ref error_response) => {
write!(f, "Request sent to VSS Server was invalid : {}", error_response.message)
}
VssError::ConflictError(ref error_response) => {
write!(f, "Potential version conflict in write operation : {}", error_response.message)
}
VssError::InternalServerError(ref error_response) => {
write!(f, "InternalServerError : {}", error_response.message)
}
VssError::InternalError(ref message) => {
write!(f, "InternalError : {}", message)
}
}
}
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match *self {
VssError::InvalidRequestError(ref error_response) => {
write!(f, "Request sent to VSS Server was invalid : {}", error_response.message)
}
VssError::ConflictError(ref error_response) => {
write!(f, "Potential version conflict in write operation : {}", error_response.message)
}
VssError::InternalServerError(ref error_response) => {
write!(f, "InternalServerError : {}", error_response.message)
}
VssError::InternalError(ref message) => {
write!(f, "InternalError : {}", message)
}
}
}
}

impl Error for VssError {}

impl From<ErrorResponse> for VssError {
fn from(error_response: ErrorResponse) -> Self {
return match error_response.error_code() {
ErrorCode::InvalidRequestException => { VssError::InvalidRequestError(error_response) }
ErrorCode::ConflictException => { VssError::ConflictError(error_response) }
ErrorCode::InternalServerException => { VssError::InternalServerError(error_response) }
_ => {
VssError::InternalError(format!("Server responded with an unknown error code: {}, \
message: {}", error_response.error_code, error_response.message))
}
};
}
fn from(error_response: ErrorResponse) -> Self {
return match error_response.error_code() {
ErrorCode::InvalidRequestException => VssError::InvalidRequestError(error_response),
ErrorCode::ConflictException => VssError::ConflictError(error_response),
ErrorCode::InternalServerException => VssError::InternalServerError(error_response),
_ => VssError::InternalError(format!(
"Server responded with an unknown error code: {}, \
message: {}",
error_response.error_code, error_response.message
)),
};
}
}

impl From<DecodeError> for VssError {
fn from(err: DecodeError) -> Self {
VssError::InternalError(err.to_string())
}
fn from(err: DecodeError) -> Self {
VssError::InternalError(err.to_string())
}
}

impl From<reqwest::Error> for VssError {
fn from(err: reqwest::Error) -> Self {
VssError::InternalError(err.to_string())
}
fn from(err: reqwest::Error) -> Self {
VssError::InternalError(err.to_string())
}
}

0 comments on commit 993038e

Please sign in to comment.