♻️ 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 serde::Deserialize;
use thiserror::Error;
#[derive (Error, Debug)] use crate::errors::ConfigError;
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,
}
// Stuff we need to load from the config file and use to // Stuff we need to load from the config file and use to
// set up the HTTP server // 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, borrow::Cow,
error::Error, error::Error,
collections::*, collections::*,
convert::Infallible, convert::{Infallible, TryFrom},
iter::FromIterator, iter::FromIterator,
net::SocketAddr, net::SocketAddr,
path::{Path, PathBuf},
sync::{ sync::{
Arc, Arc,
}, },
@ -48,9 +49,11 @@ use ptth_core::{
}; };
pub mod config; pub mod config;
pub mod errors;
pub mod git_version; 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 { enum RequestRendezvous {
ParkedClients (Vec <http_serde::WrappedRequest>), 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::{ use chrono::{
DateTime, DateTime,
@ -127,19 +125,21 @@ pub struct RelayState {
shutdown_watch_rx: watch::Receiver <bool>, shutdown_watch_rx: watch::Receiver <bool>,
} }
impl From <Config> for RelayState { impl TryFrom <Config> for RelayState {
fn from (config: Config) -> Self { type Error = RelayError;
fn try_from (config: Config) -> Result <Self, Self::Error> {
let (shutdown_watch_tx, shutdown_watch_rx) = watch::channel (false); let (shutdown_watch_tx, shutdown_watch_rx) = watch::channel (false);
Self { Ok (Self {
config: config.into (), config: config.into (),
handlebars: Arc::new (load_templates (&PathBuf::new ()).unwrap ()), handlebars: Arc::new (load_templates (&PathBuf::new ())?),
request_rendezvous: Default::default (), request_rendezvous: Default::default (),
server_status: Default::default (), server_status: Default::default (),
response_rendezvous: Default::default (), response_rendezvous: Default::default (),
shutdown_watch_tx, shutdown_watch_tx,
shutdown_watch_rx, shutdown_watch_rx,
} })
} }
} }
@ -236,7 +236,7 @@ async fn handle_http_listen (
debug! ("Unparking server {}", watcher_code); debug! ("Unparking server {}", watcher_code);
ok_reply (rmp_serde::to_vec (&vec! [one_req]).unwrap ()) 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"), Err (_) => error_reply (StatusCode::INTERNAL_SERVER_ERROR, "Server error"),
}, },
_ = delay_for (Duration::from_secs (30)).fuse () => { _ = delay_for (Duration::from_secs (30)).fuse () => {
@ -448,7 +448,7 @@ async fn handle_http_request (
resp.body (body) resp.body (body)
.unwrap () .unwrap ()
}, },
Ok (Err (RelayError::RelayShuttingDown)) => { Ok (Err (ShuttingDownError::ShuttingDown)) => {
error_reply (StatusCode::GATEWAY_TIMEOUT, "Relay shutting down") error_reply (StatusCode::GATEWAY_TIMEOUT, "Relay shutting down")
}, },
Err (_) => { 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) pub fn load_templates (asset_root: &Path)
-> Result <Handlebars <'static>, Box <dyn Error>> -> Result <Handlebars <'static>, RelayError>
{ {
let mut handlebars = Handlebars::new (); let mut handlebars = Handlebars::new ();
handlebars.set_strict_mode (true); handlebars.set_strict_mode (true);
@ -712,7 +710,7 @@ pub async fn run_relay (
state.shutdown_watch_tx.broadcast (true).unwrap (); state.shutdown_watch_tx.broadcast (true).unwrap ();
use RelayError::*; use ShuttingDownError::ShuttingDown;
let mut response_rendezvous = state.response_rendezvous.write ().await; let mut response_rendezvous = state.response_rendezvous.write ().await;
let mut swapped = DashMap::default (); let mut swapped = DashMap::default ();
@ -720,7 +718,7 @@ pub async fn run_relay (
std::mem::swap (&mut swapped, &mut response_rendezvous); std::mem::swap (&mut swapped, &mut response_rendezvous);
for (_, sender) in swapped.into_iter () { 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; let mut request_rendezvous = state.request_rendezvous.lock ().await;
@ -730,7 +728,7 @@ pub async fn run_relay (
match x { match x {
ParkedClients (_) => (), ParkedClients (_) => (),
ParkedServer (sender) => drop (sender.send (Err (RelayShuttingDown))), ParkedServer (sender) => drop (sender.send (Err (ShuttingDown))),
} }
} }

View File

@ -1,4 +1,5 @@
use std::{ use std::{
convert::TryFrom,
error::Error, error::Error,
path::PathBuf, path::PathBuf,
sync::Arc, sync::Arc,
@ -35,7 +36,7 @@ async fn main () -> Result <(), Box <dyn Error>> {
forced_shutdown.wrap_server ( forced_shutdown.wrap_server (
run_relay ( run_relay (
Arc::new (RelayState::from (config)), Arc::new (RelayState::try_from (config)?),
shutdown_rx, shutdown_rx,
Some (config_path) 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 relay_state_2 = relay_state.clone ();
let (stop_relay_tx, stop_relay_rx) = oneshot::channel (); let (stop_relay_tx, stop_relay_rx) = oneshot::channel ();