Compare commits

...

6 commits

Author SHA1 Message Date
996924582a
use macros 2019-12-21 23:34:03 -05:00
320e41c6f2
graceful bad-config handling 2019-12-21 15:56:59 -05:00
e11e514c12
use custom error 2019-12-21 15:43:04 -05:00
be505480c5
rustfmt 2019-12-21 14:21:20 -05:00
64aec75659
refactor config reading 2019-12-21 14:16:47 -05:00
c195efd1b4
clippy 2019-12-21 14:08:04 -05:00
2 changed files with 196 additions and 145 deletions

2
rustfmt.toml Normal file
View file

@ -0,0 +1,2 @@
tab_spaces = 2
use_field_init_shorthand = true

View file

@ -1,197 +1,246 @@
use actix_web::{ use actix_web::{
get, get,
http::header, http::header,
web::{Data, Query}, web::{Data, Query},
App, HttpResponse, HttpServer, Responder, App, HttpResponse, HttpServer, Responder,
}; };
use handlebars::Handlebars; use handlebars::Handlebars;
use hotwatch::{Event, Hotwatch}; use hotwatch::{Event, Hotwatch};
use serde::Deserialize; use serde::Deserialize;
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
use std::error::Error;
use std::fmt;
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io::{Error, Write}; use std::io::Write;
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use std::time::Duration; use std::time::Duration;
static DEFAULT_CONFIG: &[u8] = include_bytes!("../bunbun.default.toml"); static DEFAULT_CONFIG: &[u8] = include_bytes!("../bunbun.default.toml");
static CONFIG_FILE: &str = "bunbun.toml"; static CONFIG_FILE: &str = "bunbun.toml";
#[derive(Debug)]
enum BunBunError {
IoError(std::io::Error),
ParseError(serde_yaml::Error),
WatchError(hotwatch::Error),
}
impl fmt::Display for BunBunError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
BunBunError::IoError(e) => e.fmt(f),
BunBunError::ParseError(e) => e.fmt(f),
BunBunError::WatchError(e) => e.fmt(f),
}
}
}
impl Error for BunBunError {}
macro_rules! from_error {
($from:ty, $to:ident) => {
impl From<$from> for BunBunError {
fn from(e: $from) -> Self {
BunBunError::$to(e)
}
}
};
}
from_error!(std::io::Error, IoError);
from_error!(serde_yaml::Error, ParseError);
from_error!(hotwatch::Error, WatchError);
#[get("/ls")] #[get("/ls")]
fn list(data: Data<Arc<RwLock<State>>>) -> impl Responder { fn list(data: Data<Arc<RwLock<State>>>) -> impl Responder {
let data = data.read().unwrap(); let data = data.read().unwrap();
HttpResponse::Ok().body(data.renderer.render("list", &data.routes).unwrap()) HttpResponse::Ok().body(data.renderer.render("list", &data.routes).unwrap())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
struct SearchQuery { struct SearchQuery {
to: String, to: String,
} }
#[get("/hop")] #[get("/hop")]
fn hop(data: Data<Arc<RwLock<State>>>, query: Query<SearchQuery>) -> impl Responder { fn hop(data: Data<Arc<RwLock<State>>>, query: Query<SearchQuery>) -> impl Responder {
let data = data.read().unwrap(); let data = data.read().unwrap();
let mut raw_args = query.to.split_ascii_whitespace(); let mut raw_args = query.to.split_ascii_whitespace();
let command = raw_args.next(); let command = raw_args.next();
if command.is_none() { if command.is_none() {
return HttpResponse::NotFound().body("not found"); return HttpResponse::NotFound().body("not found");
}
// Reform args into url-safe string (probably want to go thru an actual parser)
let mut args = String::new();
if let Some(first_arg) = raw_args.next() {
args.push_str(first_arg);
for arg in raw_args {
args.push_str("+");
args.push_str(arg);
} }
}
// Reform args into url-safe string (probably want to go thru an actual parser) let mut template_args = HashMap::new();
let mut args = String::new(); template_args.insert("query", args);
if let Some(first_arg) = raw_args.next() {
args.push_str(first_arg);
for arg in raw_args {
args.push_str("+");
args.push_str(arg);
}
}
let mut template_args = HashMap::new(); match data.routes.get(command.unwrap()) {
template_args.insert("query", args); Some(template) => HttpResponse::Found()
.header(
match data.routes.get(command.unwrap()) { header::LOCATION,
Some(template) => HttpResponse::Found() data
.header( .renderer
header::LOCATION, .render_template(template, &template_args)
data.renderer .unwrap(),
.render_template(template, &template_args) )
.unwrap(), .finish(),
) None => match &data.default_route {
.finish(), Some(route) => {
None => match &data.default_route { template_args.insert(
Some(route) => { "query",
template_args.insert( format!(
"query", "{}+{}",
format!( command.unwrap(),
"{}+{}", template_args.get("query").unwrap()
command.unwrap(), ),
template_args.get("query").unwrap() );
), HttpResponse::Found()
); .header(
HttpResponse::Found() header::LOCATION,
.header( data
header::LOCATION, .renderer
data.renderer .render_template(data.routes.get(route).unwrap(), &template_args)
.render_template(data.routes.get(route).unwrap(), &template_args) .unwrap(),
.unwrap(), )
) .finish()
.finish() }
} None => HttpResponse::NotFound().body("not found"),
None => HttpResponse::NotFound().body("not found"), },
}, }
}
} }
#[get("/")] #[get("/")]
fn index(data: Data<Arc<RwLock<State>>>) -> impl Responder { fn index(data: Data<Arc<RwLock<State>>>) -> impl Responder {
let data = data.read().unwrap(); let data = data.read().unwrap();
let mut template_args = HashMap::new(); let mut template_args = HashMap::new();
template_args.insert("hostname", &data.public_address); template_args.insert("hostname", &data.public_address);
HttpResponse::Ok().body(data.renderer.render("index", &template_args).unwrap()) HttpResponse::Ok().body(data.renderer.render("index", &template_args).unwrap())
} }
#[get("/bunbunsearch.xml")] #[get("/bunbunsearch.xml")]
fn opensearch(data: Data<Arc<RwLock<State>>>) -> impl Responder { fn opensearch(data: Data<Arc<RwLock<State>>>) -> impl Responder {
let data = data.read().unwrap(); let data = data.read().unwrap();
let mut template_args = HashMap::new(); let mut template_args = HashMap::new();
template_args.insert("hostname", &data.public_address); template_args.insert("hostname", &data.public_address);
HttpResponse::Ok() HttpResponse::Ok()
.header( .header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
"application/opensearchdescription+xml", "application/opensearchdescription+xml",
) )
.body(data.renderer.render("opensearch", &template_args).unwrap()) .body(data.renderer.render("opensearch", &template_args).unwrap())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
struct Config { struct Config {
bind_address: String, bind_address: String,
public_address: String, public_address: String,
default_route: Option<String>, default_route: Option<String>,
routes: BTreeMap<String, String>, routes: BTreeMap<String, String>,
} }
struct State { struct State {
public_address: String, public_address: String,
default_route: Option<String>, default_route: Option<String>,
routes: BTreeMap<String, String>, routes: BTreeMap<String, String>,
renderer: Handlebars, renderer: Handlebars,
} }
fn main() -> Result<(), Error> { fn main() -> Result<(), BunBunError> {
let config_file = match File::open(CONFIG_FILE) { let conf = read_config(CONFIG_FILE)?;
Ok(file) => file, let renderer = compile_templates();
Err(_) => { let state = Arc::from(RwLock::new(State {
eprintln!("Unable to find a {} file. Creating default!", CONFIG_FILE); public_address: conf.public_address,
let mut fd = OpenOptions::new() default_route: conf.default_route,
.write(true) routes: conf.routes,
.create_new(true) renderer,
.open(CONFIG_FILE) }));
.expect("Unable to write to directory!"); let state_ref = state.clone();
fd.write_all(DEFAULT_CONFIG)?;
File::open(CONFIG_FILE)? let mut watch = Hotwatch::new_with_custom_delay(Duration::from_millis(500))?;
watch.watch(CONFIG_FILE, move |e: Event| {
if let Event::Write(_) = e {
let mut state = state.write().unwrap();
match read_config(CONFIG_FILE) {
Ok(conf) => {
state.public_address = conf.public_address;
state.default_route = conf.default_route;
state.routes = conf.routes;
} }
}; Err(e) => eprintln!("Config is malformed: {}", e),
}
}
})?;
let renderer = compile_templates(); HttpServer::new(move || {
let conf: Config = serde_yaml::from_reader(config_file).unwrap(); App::new()
let state = Arc::from(RwLock::new(State { .data(state_ref.clone())
public_address: conf.public_address, .service(hop)
default_route: conf.default_route, .service(list)
routes: conf.routes, .service(index)
renderer: renderer, .service(opensearch)
})); })
let state_ref = state.clone(); .bind(&conf.bind_address)?
.run()?;
let mut watch = Ok(())
Hotwatch::new_with_custom_delay(Duration::from_millis(500)).expect("Failed to init watch"); }
watch fn read_config(config_file_path: &str) -> Result<Config, BunBunError> {
.watch(CONFIG_FILE, move |e: Event| { let config_file = match File::open(config_file_path) {
if let Event::Write(_) = e { Ok(file) => file,
let config_file = File::open(CONFIG_FILE).unwrap(); Err(_) => {
let conf: Config = serde_yaml::from_reader(config_file).unwrap(); eprintln!(
let state = state.clone(); "Unable to find a {} file. Creating default!",
let mut state = state.write().unwrap(); config_file_path
state.public_address = conf.public_address; );
state.default_route = conf.default_route; let mut fd = OpenOptions::new()
state.routes = conf.routes; .write(true)
} .create_new(true)
}) .open(config_file_path)
.expect("failed to watch"); .expect("Unable to write to directory!");
fd.write_all(DEFAULT_CONFIG)?;
HttpServer::new(move || { File::open(config_file_path)?
App::new() }
.data(state_ref.clone()) };
.service(hop) Ok(serde_yaml::from_reader(config_file)?)
.service(list)
.service(index)
.service(opensearch)
})
.bind(&conf.bind_address)?
.run()
} }
fn compile_templates() -> Handlebars { fn compile_templates() -> Handlebars {
let mut handlebars = Handlebars::new(); let mut handlebars = Handlebars::new();
handlebars
.register_template_string( macro_rules! register_template {
"index", ( $( $template:expr ),* ) => {
String::from_utf8_lossy(include_bytes!("templates/index.hbs")), $(
) handlebars
.unwrap(); .register_template_string(
handlebars $template,
.register_template_string( String::from_utf8_lossy(
"opensearch", include_bytes!(concat!("templates/", $template, ".hbs")))
String::from_utf8_lossy(include_bytes!("templates/bunbunsearch.xml")), )
) .unwrap();
.unwrap(); )*
handlebars };
.register_template_string( }
"list",
String::from_utf8_lossy(include_bytes!("templates/list.hbs")), register_template!("index", "list");
)
.unwrap(); handlebars
handlebars .register_template_string(
"opensearch",
String::from_utf8_lossy(include_bytes!(concat!("templates/", "bunbunsearch.xml"))),
)
.unwrap();
handlebars
} }