Skip to content

Commit

Permalink
refactor: design error type
Browse files Browse the repository at this point in the history
Design error type.

Fixes: #23

Signed-off-by: yaoyinnan <35447132+yaoyinnan@users.noreply.github.com>
  • Loading branch information
yaoyinnan committed Jul 6, 2023
1 parent fdb73b9 commit d7fd993
Show file tree
Hide file tree
Showing 10 changed files with 91 additions and 44 deletions.
10 changes: 10 additions & 0 deletions src/error/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use thiserror::Error;
use toml;

pub type Result<T> = std::result::Result<T, ConfigError>;

#[derive(Debug, Error)]

Check warning on line 6 in src/error/config.rs

View check run for this annotation

Codecov / codecov/patch

src/error/config.rs#L6

Added line #L6 was not covered by tests
pub enum ConfigError {
#[error("parse toml error: {0}")]
ParseToml(#[from] toml::de::Error),
}
34 changes: 34 additions & 0 deletions src/error/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
pub mod config;
pub mod network;
pub mod redis;
pub mod server;

use std::io;

use crate::error::config::ConfigError;
use crate::error::network::NetWorkError;
use crate::error::redis::RedisError;
use crate::error::server::ServerError;

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, thiserror::Error)]

Check warning on line 15 in src/error/mod.rs

View check run for this annotation

Codecov / codecov/patch

src/error/mod.rs#L15

Added line #L15 was not covered by tests
pub enum Error {
#[error("unexpected error: {0}")]
Unexpected(String),

#[error("error on network: {0}")]
NetWork(#[from] NetWorkError),

#[error("IO error: {0}")]
IO(#[from] io::Error),

#[error("error on config: {0}")]
Config(#[from] ConfigError),

#[error("error on redis: {0}")]
Redis(#[from] RedisError),

#[error("error on server: {0}")]
Server(#[from] ServerError),
}
9 changes: 9 additions & 0 deletions src/error/network.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use thiserror::Error;

pub type Result<T> = std::result::Result<T, NetWorkError>;

#[derive(Debug, Error)]

Check warning on line 5 in src/error/network.rs

View check run for this annotation

Codecov / codecov/patch

src/error/network.rs#L5

Added line #L5 was not covered by tests
pub enum NetWorkError {
#[error("error on network: {0}")]
NetWork(String),
}
18 changes: 3 additions & 15 deletions src/utils/error.rs → src/error/redis.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,9 @@
use std::io;
use thiserror::Error;

// todo: 需要完成 Error 的具体设计
pub type Result<T> = std::result::Result<T, RedisError>;

#[derive(Debug, Error)]
pub enum PikaProxyError {
#[error("error on network: {0}")]
NetWorkError(String),
#[error("can't not open file: {0}")]
FailedOpenDB(String),
#[error("IO error: {0}")]
Io(#[from] io::Error),
#[error("Parsing error: {0}")]
ParseError(#[from] toml::de::Error),
#[error("unexpected error: {0}")]
UnexpectedError(String),
pub enum RedisError {
#[error("key or value size is invalid")]
InvalidKeyOrValue,
#[error("can't decode on empty entry")]
Expand All @@ -33,5 +23,3 @@ pub enum PikaProxyError {
#[error("merging")]
AtMerging,
}

pub type Result<T> = std::result::Result<T, PikaProxyError>;
9 changes: 9 additions & 0 deletions src/error/server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use thiserror::Error;

pub type Result<T> = std::result::Result<T, ServerError>;

#[derive(Debug, Error)]

Check warning on line 5 in src/error/server.rs

View check run for this annotation

Codecov / codecov/patch

src/error/server.rs#L5

Added line #L5 was not covered by tests
pub enum ServerError {
#[error("can't not open db: {0}")]
FailedOpenDB(String),
}
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod error;
pub mod models;
pub mod proxy;
pub mod utils;
Expand All @@ -24,7 +25,7 @@ fn main() {
.build() // 创建runtime
.unwrap();

let proxy = Proxy::from(&option);
let proxy = Proxy::new(&option).unwrap();

Check warning on line 28 in src/main.rs

View check run for this annotation

Codecov / codecov/patch

src/main.rs#L28

Added line #L28 was not covered by tests

rt.block_on(proxy.serve_proxy());
}
33 changes: 15 additions & 18 deletions src/proxy/config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::error::config::ConfigError;
use crate::error::Result;
use serde::{de, Deserialize, Deserializer, Serialize};
use std::{fs::File, io::Read, path::Path, time::Duration};

use crate::utils::error::Result as PikaProxyResult;
use std::{path::Path, time::Duration};

const KB: u64 = 1024;
const MB: u64 = 1024 * KB;
Expand Down Expand Up @@ -84,7 +84,7 @@ pub struct Config {
metrics_report_stats_prefix: String,
}

fn deserialize_string_to_size<'de, D>(deserializer: D) -> Result<u64, D::Error>
fn deserialize_string_to_size<'de, D>(deserializer: D) -> std::result::Result<u64, D::Error>
where
D: Deserializer<'de>,
{
Expand All @@ -100,7 +100,9 @@ where
}
}

fn deserialize_string_to_duration<'de, D>(deserializer: D) -> Result<Duration, D::Error>
fn deserialize_string_to_duration<'de, D>(
deserializer: D,
) -> std::result::Result<Duration, D::Error>
where
D: Deserializer<'de>,
{
Expand Down Expand Up @@ -134,12 +136,9 @@ fn parse_string_to_num_and_unit(str: &str) -> (u64, &str) {
}

impl Config {
pub fn from_path<P: AsRef<Path>>(path: P) -> PikaProxyResult<Self> {
let mut f = File::open(path)?;
let mut content = String::new();
f.read_to_string(&mut content)?;
let config: Config = toml::from_str(&content)?;
Ok(config)
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
let content = std::fs::read_to_string(path)?;
Ok(toml::from_str(&content).map_err(ConfigError::ParseToml)?)
}

pub fn proxy_addr(&self) -> &str {
Expand All @@ -151,17 +150,15 @@ impl Config {
}
}

#[cfg(test)]
mod tests {
use super::Config;

#[test]
fn test_config() {
let path = "config/proxy.toml";
let mut root_path = project_root::get_project_root().unwrap();
root_path.push(path);
let config = Config::from_path(root_path).unwrap();
assert_eq!(config.admin_addr, "0.0.0.0:11080");
assert_eq!(config.proxy_addr, "127.0.0.1:19000")
let mut config_path = project_root::get_project_root().unwrap();
config_path.push("config/proxy.toml");
let config = Config::from_path(config_path).unwrap();
assert_eq!(config.proxy_addr(), "127.0.0.1:19000");
assert_eq!(config.admin_addr(), "0.0.0.0:11080");
}
}
16 changes: 8 additions & 8 deletions src/proxy/proxy.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::config::Config;
use crate::utils::error::{PikaProxyError, Result};
use crate::error::Result;
use core::str::FromStr;
use std::net::SocketAddr;
use std::sync::Arc;
Expand Down Expand Up @@ -31,9 +31,9 @@ pub(crate) struct ProxyOptions {
pub(crate) config_path: String,
}

impl From<&ProxyOptions> for Proxy {
fn from(option: &ProxyOptions) -> Proxy {
let config = Config::from_path(&option.config_path).unwrap();
impl Proxy {
pub(crate) fn new(option: &ProxyOptions) -> Result<Self> {
let config = Config::from_path(&option.config_path)?;

Check warning on line 36 in src/proxy/proxy.rs

View check run for this annotation

Codecov / codecov/patch

src/proxy/proxy.rs#L35-L36

Added lines #L35 - L36 were not covered by tests
let proxy = RawProxy {
xauth: String::new(),

Expand All @@ -45,9 +45,9 @@ impl From<&ProxyOptions> for Proxy {

config: Arc::new(config),
};
Proxy {
Ok(Proxy {

Check warning on line 48 in src/proxy/proxy.rs

View check run for this annotation

Codecov / codecov/patch

src/proxy/proxy.rs#L48

Added line #L48 was not covered by tests
proxy: Arc::new(RwLock::new(proxy)),
}
})

Check warning on line 50 in src/proxy/proxy.rs

View check run for this annotation

Codecov / codecov/patch

src/proxy/proxy.rs#L50

Added line #L50 was not covered by tests
}
}

Expand Down Expand Up @@ -100,7 +100,7 @@ async fn listen(addr: &SocketAddr) {
}

// 简单的打印服务器
async fn do_task(mut stream: TcpStream) {
async fn do_task(stream: TcpStream) {

Check warning on line 103 in src/proxy/proxy.rs

View check run for this annotation

Codecov / codecov/patch

src/proxy/proxy.rs#L103

Added line #L103 was not covered by tests
let mut buf_stream = BufStream::new(stream);
let mut msg = vec![0; 1024];
loop {
Expand All @@ -112,7 +112,7 @@ async fn do_task(mut stream: TcpStream) {
buf_stream.flush().await.unwrap();
println!("write_size: {}", size);
}
Err(e) => break,
Err(_e) => break,

Check warning on line 115 in src/proxy/proxy.rs

View check run for this annotation

Codecov / codecov/patch

src/proxy/proxy.rs#L115

Added line #L115 was not covered by tests
}
}
}
2 changes: 1 addition & 1 deletion src/proxy/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use std::collections::HashMap;

use super::forward::ForwardMethod;
use super::request::Request;
use crate::error::{Error, Result};
use crate::models::slots::Slot;
use crate::utils::error::{PikaProxyError, Result};
use crate::utils::redis::InfoCache;

pub trait Router {
Expand Down
1 change: 0 additions & 1 deletion src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
pub mod defer;
pub mod error;
pub mod redis;

0 comments on commit d7fd993

Please sign in to comment.