ptth_server v2.1.0 will allow custom servers with a user-supplied request handler

main
_ 2021-05-09 19:29:15 +00:00
parent 08009de043
commit 6c826b0cc5
4 changed files with 254 additions and 138 deletions

2
Cargo.lock generated
View File

@ -1575,7 +1575,7 @@ dependencies = [
[[package]] [[package]]
name = "ptth_server" name = "ptth_server"
version = "2.0.0" version = "2.1.0"
dependencies = [ dependencies = [
"aho-corasick", "aho-corasick",
"always_equal", "always_equal",

View File

@ -1,7 +1,7 @@
[package] [package]
name = "ptth_server" name = "ptth_server"
version = "2.0.0" version = "2.1.0"
authors = ["Trish"] authors = ["Trish"]
edition = "2018" edition = "2018"
license = "AGPL-3.0" license = "AGPL-3.0"

View File

@ -0,0 +1,49 @@
#[tokio::main]
async fn main () -> anyhow::Result <()> {
use std::{
fs,
sync::Arc,
};
use ptth_core::{
graceful_shutdown,
http_serde::{
RequestParts,
Response,
},
};
use ptth_server::{
Builder,
State,
};
let api_key = fs::read_to_string ("config/ptth_server_custom_key.txt")?
.trim_end ()
.to_string ();
let state = Builder::new (
"ptth_server_custom".to_string (),
"http://127.0.0.1:4000/7ZSFUKGV".to_string ()
)
.api_key (api_key)
.build ()?;
let state = Arc::new (state);
let mut spawn_handler = || {
|req: RequestParts| async move {
let mut resp = Response::default ();
resp.body_bytes (req.uri.as_bytes ().to_vec ());
Ok (resp)
}
};
State::run (
&state,
graceful_shutdown::init (),
&mut spawn_handler,
).await?;
Ok (())
}

View File

@ -72,7 +72,7 @@ pub mod load_toml;
use errors::ServerError; use errors::ServerError;
struct State { pub struct State {
file_server: file_server::FileServer, file_server: file_server::FileServer,
config: Config, config: Config,
client: Client, client: Client,
@ -145,15 +145,15 @@ async fn handle_one_req (
Ok::<(), ServerError> (()) Ok::<(), ServerError> (())
} }
async fn handle_requests <F, F2, H> ( async fn handle_requests <F, H, SH> (
state: &Arc <State>, state: &Arc <State>,
req_resp: reqwest::Response, req_resp: reqwest::Response,
mut spawn_handler: H, spawn_handler: &mut SH,
) -> Result <(), ServerError> ) -> Result <(), ServerError>
where where
F: Send + Future <Output = anyhow::Result <http_serde::Response>>, F: Send + Future <Output = anyhow::Result <http_serde::Response>>,
F2: Send + 'static + FnOnce (http_serde::RequestParts) -> F, H: Send + 'static + FnOnce (http_serde::RequestParts) -> F,
H: Send + FnMut () -> F2 SH: Send + FnMut () -> H
{ {
//println! ("Step 1"); //println! ("Step 1");
@ -253,7 +253,46 @@ pub struct Config {
pub throttle_upload: bool, pub throttle_upload: bool,
} }
/// Runs a PTTH file server pub struct Builder {
config_file: ConfigFile,
hidden_path: Option <PathBuf>,
asset_root: Option <PathBuf>,
}
impl Builder {
pub fn new (
name: String,
relay_url: String,
) -> Self {
let config_file = ConfigFile {
name,
api_key: ptth_core::gen_key (),
relay_url,
file_server_root: None,
throttle_upload: false,
};
Self {
config_file,
hidden_path: None,
asset_root: None,
}
}
pub fn build (self) -> Result <State, ServerError>
{
State::new (
self.config_file,
self.hidden_path,
self.asset_root
)
}
pub fn api_key (mut self, key: String) -> Self {
self.config_file.api_key = key;
self
}
}
pub async fn run_server ( pub async fn run_server (
config_file: ConfigFile, config_file: ConfigFile,
@ -263,10 +302,39 @@ pub async fn run_server (
) )
-> Result <(), ServerError> -> Result <(), ServerError>
{ {
use std::{ let state = Arc::new (State::new (
convert::TryInto, config_file,
hidden_path,
asset_root,
)?);
let state_2 = Arc::clone (&state);
let mut spawn_handler = || {
let state = Arc::clone (&state_2);
|req: http_serde::RequestParts| async move {
Ok (state.file_server.serve_all (req.method, &req.uri, &req.headers).await?)
}
}; };
State::run (
&state,
shutdown_oneshot,
&mut spawn_handler,
).await
}
impl State {
pub fn new (
config_file: ConfigFile,
hidden_path: Option <PathBuf>,
asset_root: Option <PathBuf>
)
-> Result <Self, ServerError>
{
use std::convert::TryInto;
use arc_swap::ArcSwap; use arc_swap::ArcSwap;
let asset_root = asset_root.unwrap_or_else (PathBuf::new); let asset_root = asset_root.unwrap_or_else (PathBuf::new);
@ -289,7 +357,7 @@ pub async fn run_server (
file_server::metrics::Interval::monitor (interval_writer).await; file_server::metrics::Interval::monitor (interval_writer).await;
}); });
let state = Arc::new (State { let state = State {
file_server: file_server::FileServer::new ( file_server: file_server::FileServer::new (
config_file.file_server_root, config_file.file_server_root,
&asset_root, &asset_root,
@ -302,15 +370,21 @@ pub async fn run_server (
throttle_upload: config_file.throttle_upload, throttle_upload: config_file.throttle_upload,
}, },
client, client,
}); };
run_server_loop (state, shutdown_oneshot).await Ok (state)
} }
async fn run_server_loop ( pub async fn run <F, H, SH> (
state: Arc <State>, state: &Arc <Self>,
shutdown_oneshot: oneshot::Receiver <()>, shutdown_oneshot: oneshot::Receiver <()>,
) -> Result <(), ServerError> { spawn_handler: &mut SH,
) -> Result <(), ServerError>
where
F: Send + Future <Output = anyhow::Result <http_serde::Response>>,
H: Send + 'static + FnOnce (http_serde::RequestParts) -> F,
SH: Send + FnMut () -> H
{
use http::status::StatusCode; use http::status::StatusCode;
let mut backoff_delay = 0; let mut backoff_delay = 0;
@ -384,14 +458,6 @@ async fn run_server_loop (
// Unpack the requests, spawn them into new tasks, then loop back // Unpack the requests, spawn them into new tasks, then loop back
// around. // around.
let spawn_handler = || {
let state = Arc::clone (&state);
|req: http_serde::RequestParts| async move {
Ok (state.file_server.serve_all (req.method, &req.uri, &req.headers).await?)
}
};
if handle_requests ( if handle_requests (
&state, &state,
req_resp, req_resp,
@ -411,6 +477,7 @@ async fn run_server_loop (
Ok (()) Ok (())
} }
}
#[cfg (test)] #[cfg (test)]
mod tests { mod tests {