♻️ Removing unwraps

main
_ 2020-11-29 16:58:56 +00:00
parent 3e74f2b1ef
commit bf96d400b2
5 changed files with 62 additions and 45 deletions

View File

@ -6,28 +6,8 @@ use std::{
};
use serde::Deserialize;
use thiserror::Error;
#[derive (Error, Debug)]
pub enum ConfigError {
#[error ("I/O error")]
Io (#[from] std::io::Error),
#[error ("UTF-8 decoding failed")]
Utf8 (#[from] std::string::FromUtf8Error),
#[error ("TOML parsing failed")]
Toml (#[from] toml::de::Error),
#[error ("base64 decoding failed")]
Base64Decode (#[from] base64::DecodeError),
#[error ("tripcode not 32 bytes after decoding")]
TripcodeBadLength,
#[error ("unknown config error")]
Unknown,
}
use crate::errors::ConfigError;
// Stuff we need to load from the config file and use to
// set up the HTTP server

View File

@ -0,0 +1,36 @@
use thiserror::Error;
#[derive (Error, Debug)]
pub enum ConfigError {
#[error ("I/O error")]
Io (#[from] std::io::Error),
#[error ("UTF-8 decoding failed")]
Utf8 (#[from] std::string::FromUtf8Error),
#[error ("TOML parsing failed")]
Toml (#[from] toml::de::Error),
#[error ("base64 decoding failed")]
Base64Decode (#[from] base64::DecodeError),
#[error ("tripcode not 32 bytes after decoding")]
TripcodeBadLength,
#[error ("unknown config error")]
Unknown,
}
// I'm not sure how important this is, but it was already in the code
#[derive (Error, Debug)]
pub enum ShuttingDownError {
#[error ("Relay is shutting down")]
ShuttingDown,
}
#[derive (Error, Debug)]
pub enum RelayError {
#[error ("Handlebars template file error")]
TemplateFile (#[from] handlebars::TemplateFileError),
}

View File

@ -2,9 +2,10 @@ use std::{
borrow::Cow,
error::Error,
collections::*,
convert::Infallible,
convert::{Infallible, TryFrom},
iter::FromIterator,
net::SocketAddr,
path::{Path, PathBuf},
sync::{
Arc,
},
@ -48,9 +49,11 @@ use ptth_core::{
};
pub mod config;
pub mod errors;
pub mod git_version;
pub use config::{Config, ConfigError};
pub use config::Config;
pub use errors::*;
/*
@ -81,17 +84,12 @@ can be parked
*/
#[derive (Debug)]
enum RelayError {
RelayShuttingDown,
}
enum RequestRendezvous {
ParkedClients (Vec <http_serde::WrappedRequest>),
ParkedServer (oneshot::Sender <Result <http_serde::WrappedRequest, RelayError>>),
ParkedServer (oneshot::Sender <Result <http_serde::WrappedRequest, ShuttingDownError>>),
}
type ResponseRendezvous = oneshot::Sender <Result <(http_serde::ResponseParts, Body), RelayError>>;
type ResponseRendezvous = oneshot::Sender <Result <(http_serde::ResponseParts, Body), ShuttingDownError>>;
use chrono::{
DateTime,
@ -127,19 +125,21 @@ pub struct RelayState {
shutdown_watch_rx: watch::Receiver <bool>,
}
impl From <Config> for RelayState {
fn from (config: Config) -> Self {
impl TryFrom <Config> for RelayState {
type Error = RelayError;
fn try_from (config: Config) -> Result <Self, Self::Error> {
let (shutdown_watch_tx, shutdown_watch_rx) = watch::channel (false);
Self {
Ok (Self {
config: config.into (),
handlebars: Arc::new (load_templates (&PathBuf::new ()).unwrap ()),
handlebars: Arc::new (load_templates (&PathBuf::new ())?),
request_rendezvous: Default::default (),
server_status: Default::default (),
response_rendezvous: Default::default (),
shutdown_watch_tx,
shutdown_watch_rx,
}
})
}
}
@ -236,7 +236,7 @@ async fn handle_http_listen (
debug! ("Unparking server {}", watcher_code);
ok_reply (rmp_serde::to_vec (&vec! [one_req]).unwrap ())
},
Ok (Err (RelayError::RelayShuttingDown)) => error_reply (StatusCode::SERVICE_UNAVAILABLE, "Server is shutting down, try again soon"),
Ok (Err (ShuttingDownError::ShuttingDown)) => error_reply (StatusCode::SERVICE_UNAVAILABLE, "Server is shutting down, try again soon"),
Err (_) => error_reply (StatusCode::INTERNAL_SERVER_ERROR, "Server error"),
},
_ = delay_for (Duration::from_secs (30)).fuse () => {
@ -448,7 +448,7 @@ async fn handle_http_request (
resp.body (body)
.unwrap ()
},
Ok (Err (RelayError::RelayShuttingDown)) => {
Ok (Err (ShuttingDownError::ShuttingDown)) => {
error_reply (StatusCode::GATEWAY_TIMEOUT, "Relay shutting down")
},
Err (_) => {
@ -634,10 +634,8 @@ async fn handle_all (req: Request <Body>, state: Arc <RelayState>)
})
}
use std::path::{Path, PathBuf};
pub fn load_templates (asset_root: &Path)
-> Result <Handlebars <'static>, Box <dyn Error>>
-> Result <Handlebars <'static>, RelayError>
{
let mut handlebars = Handlebars::new ();
handlebars.set_strict_mode (true);
@ -712,7 +710,7 @@ pub async fn run_relay (
state.shutdown_watch_tx.broadcast (true).unwrap ();
use RelayError::*;
use ShuttingDownError::ShuttingDown;
let mut response_rendezvous = state.response_rendezvous.write ().await;
let mut swapped = DashMap::default ();
@ -720,7 +718,7 @@ pub async fn run_relay (
std::mem::swap (&mut swapped, &mut response_rendezvous);
for (_, sender) in swapped.into_iter () {
sender.send (Err (RelayShuttingDown)).ok ();
sender.send (Err (ShuttingDown)).ok ();
}
let mut request_rendezvous = state.request_rendezvous.lock ().await;
@ -730,7 +728,7 @@ pub async fn run_relay (
match x {
ParkedClients (_) => (),
ParkedServer (sender) => drop (sender.send (Err (RelayShuttingDown))),
ParkedServer (sender) => drop (sender.send (Err (ShuttingDown))),
}
}

View File

@ -1,4 +1,5 @@
use std::{
convert::TryFrom,
error::Error,
path::PathBuf,
sync::Arc,
@ -35,7 +36,7 @@ async fn main () -> Result <(), Box <dyn Error>> {
forced_shutdown.wrap_server (
run_relay (
Arc::new (RelayState::from (config)),
Arc::new (RelayState::try_from (config)?),
shutdown_rx,
Some (config_path)
)

View File

@ -41,7 +41,9 @@ fn end_to_end () {
},
};
let relay_state = Arc::new (ptth_relay::RelayState::from (ptth_relay::config::Config::try_from (config_file).unwrap ()));
let config = ptth_relay::config::Config::try_from (config_file).unwrap ();
let relay_state = Arc::new (ptth_relay::RelayState::try_from (config).unwrap ());
let relay_state_2 = relay_state.clone ();
let (stop_relay_tx, stop_relay_rx) = oneshot::channel ();