Skip to content

Commit

Permalink
refactor(anyhow): use anyhow instead of std
Browse files Browse the repository at this point in the history
  • Loading branch information
fu050409 committed Apr 11, 2024
1 parent 811d3f5 commit 79ece6e
Show file tree
Hide file tree
Showing 7 changed files with 67 additions and 89 deletions.
18 changes: 7 additions & 11 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//! # Oblivion API Interface
//!
//! Oblivion provides methods for making direct GET, POST, PUT, etc. requests.
use anyhow::Result;
use serde_json::Value;

use crate::{exceptions::OblivionException, models::client::Response};
use crate::models::client::Response;

use super::sessions::Session;

Expand All @@ -25,30 +26,25 @@ pub async fn request(
data: Option<Value>,
file: Option<Vec<u8>>,
tfo: bool,
) -> Result<Response, OblivionException> {
) -> Result<Response> {
let session = Session::new();
session
.request(method.to_string(), olps.to_string(), data, file, tfo)
.await
}

/// GET method
pub async fn get(olps: &str, tfo: bool) -> Result<Response, OblivionException> {
pub async fn get(olps: &str, tfo: bool) -> Result<Response> {
request("get", olps, None, None, tfo).await
}

/// POST method
pub async fn post(olps: &str, data: Value, tfo: bool) -> Result<Response, OblivionException> {
pub async fn post(olps: &str, data: Value, tfo: bool) -> Result<Response> {
request("post", olps, Some(data), None, tfo).await
}

/// PUT method
pub async fn put(
olps: &str,
data: Option<Value>,
file: Vec<u8>,
tfo: bool,
) -> Result<Response, OblivionException> {
pub async fn put(olps: &str, data: Option<Value>, file: Vec<u8>, tfo: bool) -> Result<Response> {
request("put", olps, data, Some(file), tfo).await
}

Expand All @@ -58,6 +54,6 @@ pub async fn forward(
data: Option<Value>,
file: Vec<u8>,
tfo: bool,
) -> Result<Response, OblivionException> {
) -> Result<Response> {
request("forward", olps, data, Some(file), tfo).await
}
33 changes: 13 additions & 20 deletions src/models/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::utils::gear::Socket;
use crate::utils::generator::generate_key_pair;
use crate::utils::parser::{length, Oblivion, OblivionPath};

use anyhow::{Error, Result};
use p256::ecdh::EphemeralSecret;
use p256::PublicKey;
use tokio::net::TcpStream;
Expand Down Expand Up @@ -54,20 +55,12 @@ impl Response {
self.status_code < 400
}

pub fn text(&mut self) -> Result<String, OblivionException> {
match String::from_utf8(self.content.to_vec()) {
Ok(text) => Ok(text),
Err(_) => Err(OblivionException::InvalidOblivion {
olps: self.olps.to_string(),
}),
}
pub fn text(&mut self) -> Result<String> {
Ok(String::from_utf8(self.content.to_vec())?)
}

pub fn json(&mut self) -> Result<Value, OblivionException> {
match from_str::<Value>(&self.text()?) {
Ok(json) => Ok(json),
Err(_) => Err(OblivionException::BadBytes),
}
pub fn json(&mut self) -> Result<Value> {
Ok(from_str::<Value>(&self.text()?)?)
}
}

Expand Down Expand Up @@ -143,7 +136,7 @@ impl Request {
})
}

pub async fn prepare(&mut self) -> Result<(), OblivionException> {
pub async fn prepare(&mut self) -> Result<()> {
let (private_key, public_key) = generate_key_pair()?;
(self.private_key, self.public_key) = (Some(private_key), Some(public_key));

Expand All @@ -152,10 +145,10 @@ impl Request {
.await
{
Ok(tcp) => {
tcp.set_ttl(20).unwrap();
tcp.set_ttl(20)?;
tcp
}
Err(_) => return Err(OblivionException::ConnectionRefusedError),
Err(_) => return Err(Error::from(OblivionException::ConnectionRefusedError)),
};
self.tcp = Some(Socket::new(tcp));

Expand Down Expand Up @@ -183,7 +176,7 @@ impl Request {
Ok(())
}

pub async fn send(&mut self) -> Result<(), OblivionException> {
pub async fn send(&mut self) -> Result<()> {
if self.method == "GET" {
return Ok(());
};
Expand Down Expand Up @@ -216,20 +209,20 @@ impl Request {
oed.from_bytes(self.file.clone().unwrap())?;
oed
} else {
return Err(OblivionException::UnsupportedMethod {
return Err(Error::from(OblivionException::UnsupportedMethod {
method: self.method.to_string(),
});
}));
};

oed.to_stream(tcp, 5).await?;
Ok(())
}

pub async fn recv(&mut self) -> Result<Response, OblivionException> {
pub async fn recv(&mut self) -> Result<Response> {
let tcp = self.tcp.as_mut().unwrap();

if !self.prepared {
Err(OblivionException::ErrorNotPrepared)
Err(Error::from(OblivionException::ErrorNotPrepared))
} else {
let mut oed = OED::new(self.aes_key.clone());
oed.from_stream(tcp, 5).await?;
Expand Down
45 changes: 19 additions & 26 deletions src/models/packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::utils::gear::Socket;
use crate::utils::generator::{generate_random_salt, generate_shared_key};
use crate::utils::parser::length;

use anyhow::{Error, Result};
use p256::ecdh::EphemeralSecret;
use p256::PublicKey;
use rand::Rng;
Expand All @@ -16,25 +17,25 @@ pub struct ACK {
}

impl ACK {
pub fn new() -> Result<Self, OblivionException> {
pub fn new() -> Self {
let mut rng = rand::thread_rng();
let random_number: u16 = rng.gen_range(1000..=9999);
Ok(Self {
Self {
sequence: random_number.to_string(),
})
}
}

pub fn equal_bytes(&mut self, __value: &[u8]) -> bool {
__value == self.sequence.clone().into_bytes()
}

pub async fn from_stream(&mut self, stream: &mut Socket) -> Result<Self, OblivionException> {
pub async fn from_stream(&mut self, stream: &mut Socket) -> Result<Self> {
Ok(Self {
sequence: stream.recv_str(4).await?,
})
}

pub async fn to_stream(&mut self, stream: &mut Socket) -> Result<(), OblivionException> {
pub async fn to_stream(&mut self, stream: &mut Socket) -> Result<()> {
stream.send(&self.plain_data()).await?;
Ok(())
}
Expand All @@ -49,20 +50,16 @@ pub struct OSC {
}

impl OSC {
pub fn from_int(status_code: i32) -> Result<Self, OblivionException> {
Ok(Self {
status_code: status_code,
})
pub fn from_int(status_code: i32) -> Self {
Self { status_code }
}

pub async fn from_stream(stream: &mut Socket) -> Result<Self, OblivionException> {
pub async fn from_stream(stream: &mut Socket) -> Result<Self> {
let status_code = stream.recv_int(3).await?;
Ok(Self {
status_code: status_code,
})
Ok(Self { status_code })
}

pub async fn to_stream(&mut self, stream: &mut Socket) -> Result<(), OblivionException> {
pub async fn to_stream(&mut self, stream: &mut Socket) -> Result<()> {
stream.send(&self.plain_data()).await?;
Ok(())
}
Expand Down Expand Up @@ -260,12 +257,12 @@ impl OED {
&mut self,
stream: &mut Socket,
total_attemps: i32,
) -> Result<&mut Self, OblivionException> {
) -> Result<&mut Self> {
let mut attemp = 0;
let mut ack = false;

while attemp < total_attemps {
let mut ack_packet = ACK::new()?;
let mut ack_packet = ACK::new();
let mut ack_packet = ack_packet.from_stream(stream).await?;

let len_nonce = stream.recv_len().await?;
Expand Down Expand Up @@ -315,24 +312,20 @@ impl OED {
}
if !ack {
stream.close().await?;
return Err(OblivionException::AllAttemptsRetryFailed {
return Err(Error::from(OblivionException::AllAttemptsRetryFailed {
times: total_attemps,
});
}));
}

Ok(self)
}

pub async fn to_stream(
&mut self,
stream: &mut Socket,
total_attemps: i32,
) -> Result<(), OblivionException> {
pub async fn to_stream(&mut self, stream: &mut Socket, total_attemps: i32) -> Result<()> {
let attemp = 0;
let mut ack = false;

while attemp <= total_attemps {
let mut ack_packet = ACK::new()?;
let mut ack_packet = ACK::new();
ack_packet.to_stream(stream).await?;

stream.send(&self.plain_data()).await?;
Expand All @@ -354,9 +347,9 @@ impl OED {

if !ack {
stream.close().await?;
return Err(OblivionException::AllAttemptsRetryFailed {
return Err(Error::from(OblivionException::AllAttemptsRetryFailed {
times: total_attemps,
});
}));
}

Ok(())
Expand Down
21 changes: 9 additions & 12 deletions src/models/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ pub struct TextResponse {
}

impl TextResponse {
pub fn new(text: &str, status_code: i32) -> Result<Self, OblivionException> {
Ok(Self {
pub fn new(text: &str, status_code: i32) -> Self {
Self {
status_code,
text: text.to_string(),
})
}
}

pub fn as_bytes(&mut self) -> Vec<u8> {
Expand All @@ -44,11 +44,8 @@ pub struct JsonResponse {
}

impl JsonResponse {
pub fn new(data: Value, status_code: i32) -> Result<Self, OblivionException> {
Ok(Self {
data: data,
status_code: status_code,
})
pub fn new(data: Value, status_code: i32) -> Self {
Self { data, status_code }
}

pub fn as_bytes(&mut self) -> Vec<u8> {
Expand All @@ -67,11 +64,11 @@ impl BaseResponse {
method: "FileResponse".to_string(),
}),
Self::TextResponse(text, status_code) => {
let mut tres = TextResponse::new(&text, *status_code)?;
let mut tres = TextResponse::new(&text, *status_code);
Ok(tres.as_bytes())
}
Self::JsonResponse(data, status_code) => {
let mut jres = JsonResponse::new(data.clone(), *status_code)?;
let mut jres = JsonResponse::new(data.clone(), *status_code);
Ok(jres.as_bytes())
}
}
Expand All @@ -83,11 +80,11 @@ impl BaseResponse {
method: "FileResponse".to_string(),
}),
Self::TextResponse(text, status_code) => {
let mut tres = TextResponse::new(&text, *status_code)?;
let mut tres = TextResponse::new(&text, *status_code);
Ok(tres.get_status_code())
}
Self::JsonResponse(data, status_code) => {
let mut jres = JsonResponse::new(data.clone(), *status_code)?;
let mut jres = JsonResponse::new(data.clone(), *status_code);
Ok(jres.get_status_code())
}
}
Expand Down
21 changes: 11 additions & 10 deletions src/models/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use super::handler::not_found;
use super::render::Response;
use crate::utils::parser::OblivionRequest;
use anyhow::Result;
use regex::Regex;
use std::collections::HashMap;

Expand Down Expand Up @@ -43,18 +44,18 @@ impl RoutePath {
pub fn new(route: &str, route_type: RouteType) -> Self {
Self {
route: route.trim_end_matches("/").to_string(),
route_type: route_type,
route_type,
}
}

pub fn check(&mut self, olps: &str) -> bool {
pub fn check(&mut self, olps: &str) -> Result<bool> {
if self.route_type == RouteType::RegexPath {
let regex = Regex::new(&self.route).unwrap();
regex.is_match(olps)
let regex = Regex::new(&self.route)?;
Ok(regex.is_match(olps))
} else if self.route_type == RouteType::StartswithPath {
olps.starts_with(&self.route)
Ok(olps.starts_with(&self.route))
} else {
self.route == olps.trim_end_matches("/")
Ok(self.route == olps.trim_end_matches("/"))
}
}
}
Expand Down Expand Up @@ -85,13 +86,13 @@ impl Router {
self.routes.insert(path.clone(), route);
}

pub fn get_handler(&self, path: &str) -> Route {
pub fn get_handler(&self, path: &str) -> Result<Route> {
for (route_path, route) in &self.routes {
let mut route_path = route_path.clone();
if route_path.check(path) {
return route.clone();
if route_path.check(path)? {
return Ok(route.clone());
};
}
Route::new(not_found)
Ok(Route::new(not_found))
}
}
4 changes: 2 additions & 2 deletions src/models/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ pub async fn response(
oed.from_bytes(callback.as_bytes()?)?;
oed.to_stream(stream, 5).await?;

let mut osc = OSC::from_int(callback.get_status_code()?)?;
let mut osc = OSC::from_int(callback.get_status_code()?);
osc.to_stream(stream).await?;
Ok(callback.get_status_code()?)
}
Expand All @@ -123,7 +123,7 @@ async fn _handle(
}
};

let mut route = router.get_handler(&request.olps);
let mut route = router.get_handler(&request.olps)?;
let status_code = match response(
&mut route,
stream,
Expand Down
Loading

0 comments on commit 79ece6e

Please sign in to comment.