Compare commits

...

3 commits

Author SHA1 Message Date
165875b31c
proper url decoding, better hop resolution 2019-12-22 22:10:21 -05:00
23e4039b31
add spellcheck ignore 2019-12-22 22:09:46 -05:00
ffe2457380
remove unused error trait 2019-12-22 20:05:01 -05:00
5 changed files with 104 additions and 65 deletions

10
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,10 @@
{
"cSpell.words": [
"Hotwatch",
"actix",
"bunbun",
"bunbunsearch",
"itertools",
"opensearchdescription"
]
}

11
Cargo.lock generated
View file

@ -363,6 +363,8 @@ dependencies = [
"actix-web 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)",
"handlebars 2.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
"hotwatch 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
"itertools 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)",
"percent-encoding 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_yaml 0.8.11 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -778,6 +780,14 @@ dependencies = [
"winreg 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "itertools"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "itoa"
version = "0.4.4"
@ -1894,6 +1904,7 @@ dependencies = [
"checksum inotify-sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e74a1aa87c59aeff6ef2cc2fa62d41bc43f54952f55652656b18a02fd5e356c0"
"checksum iovec 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e"
"checksum ipconfig 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "aa79fa216fbe60834a9c0737d7fcd30425b32d1c58854663e24d4c4b328ed83f"
"checksum itertools 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f56a2d0bc861f9165be4eb3442afd3c236d8a98afd426f65d92324ae1091a484"
"checksum itoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "501266b7edd0174f8530248f87f99c88fbe60ca4ef3dd486835b8d8d53136f7f"
"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"
"checksum language-tags 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a91d884b6667cd606bb5a69aa0c99ba811a115fc68915e7056ec08a46e93199a"

View file

@ -13,7 +13,9 @@ actix-web = "1.0"
serde = "1.0"
serde_yaml = "0.8"
handlebars = "2.0"
hotwatch = "0.4.3"
hotwatch = "0.4"
percent-encoding = "2.1"
itertools = "0.8"
[profile.release]
lto = true

View file

@ -1,2 +1,3 @@
tab_spaces = 2
use_field_init_shorthand = true
max_width = 80

View file

@ -6,19 +6,24 @@ use actix_web::{
};
use handlebars::Handlebars;
use hotwatch::{Event, Hotwatch};
use itertools::Itertools;
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
use serde::Deserialize;
use std::collections::{BTreeMap, HashMap};
use std::error::Error;
use std::fmt;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::sync::{Arc, RwLock};
use std::time::Duration;
/// https://url.spec.whatwg.org/#fragment-percent-encode-set
static FRAGMENT_ENCODE_SET: &AsciiSet =
&CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
static DEFAULT_CONFIG: &[u8] = include_bytes!("../bunbun.default.toml");
static CONFIG_FILE: &str = "bunbun.toml";
#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
enum BunBunError {
IoError(std::io::Error),
ParseError(serde_yaml::Error),
@ -35,8 +40,8 @@ impl fmt::Display for BunBunError {
}
}
impl Error for BunBunError {}
/// Generates a from implementation from the specified type to the provided
/// bunbun error.
macro_rules! from_error {
($from:ty, $to:ident) => {
impl From<$from> for BunBunError {
@ -63,60 +68,65 @@ struct SearchQuery {
}
#[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 mut raw_args = query.to.split_ascii_whitespace();
let command = raw_args.next();
if command.is_none() {
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);
}
}
match resolve_hop(&query.to, &data.routes, &data.default_route) {
(Some(path), args) => {
let mut template_args = HashMap::new();
template_args.insert("query", args);
match data.routes.get(command.unwrap()) {
Some(template) => HttpResponse::Found()
.header(
header::LOCATION,
data
.renderer
.render_template(template, &template_args)
.unwrap(),
)
.finish(),
None => match &data.default_route {
Some(route) => {
template_args.insert(
"query",
format!(
"{}+{}",
command.unwrap(),
template_args.get("query").unwrap()
),
utf8_percent_encode(&args, FRAGMENT_ENCODE_SET).to_string(),
);
HttpResponse::Found()
.header(
header::LOCATION,
data
.renderer
.render_template(data.routes.get(route).unwrap(), &template_args)
.render_template(&path, &template_args)
.unwrap(),
)
.finish()
}
None => HttpResponse::NotFound().body("not found"),
(None, _) => HttpResponse::NotFound().body("not found"),
}
}
/// Attempts to resolve the provided string into its route and its arguments.
/// If a default route was provided, then this will consider that route before
/// failing to resolve a route.
///
/// The first element in the tuple describes the route, while the second element
/// returns the remaining arguments. If none remain, an empty string is given.
fn resolve_hop(
query: &str,
routes: &BTreeMap<String, String>,
default_route: &Option<String>,
) -> (Option<String>, String) {
let mut split_args = query.split_ascii_whitespace().peekable();
let command = match split_args.peek() {
Some(command) => command,
None => return (None, String::new()),
};
match (routes.get(*command), default_route) {
// Found a route
(Some(resolved), _) => (
Some(resolved.clone()),
match split_args.next() {
// Discard the first result, we found the route using the first arg
Some(_) => split_args.join(" "),
None => String::new(),
},
),
// Unable to find route, but had a default route
(None, Some(route)) => (routes.get(route).cloned(), split_args.join(" ")),
// No default route and no match
(None, None) => (None, String::new()),
}
}
@ -125,7 +135,8 @@ fn index(data: Data<Arc<RwLock<State>>>) -> impl Responder {
let data = data.read().unwrap();
let mut template_args = HashMap::new();
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")]
@ -141,14 +152,8 @@ fn opensearch(data: Data<Arc<RwLock<State>>>) -> impl Responder {
.body(data.renderer.render("opensearch", &template_args).unwrap())
}
#[derive(Deserialize)]
struct Config {
bind_address: String,
public_address: String,
default_route: Option<String>,
routes: BTreeMap<String, String>,
}
/// Dynamic variables that either need to be present at runtime, or can be
/// changed during runtime.
struct State {
public_address: String,
default_route: Option<String>,
@ -197,6 +202,16 @@ fn main() -> Result<(), BunBunError> {
Ok(())
}
#[derive(Deserialize)]
struct Config {
bind_address: String,
public_address: String,
default_route: Option<String>,
routes: BTreeMap<String, String>,
}
/// Attempts to read the config file. If it doesn't exist, generate one a
/// default config file before attempting to parse it.
fn read_config(config_file_path: &str) -> Result<Config, BunBunError> {
let config_file = match File::open(config_file_path) {
Ok(file) => file,
@ -217,11 +232,13 @@ fn read_config(config_file_path: &str) -> Result<Config, BunBunError> {
Ok(serde_yaml::from_reader(config_file)?)
}
/// Returns an instance with all pre-generated templates included into the
/// binary. This allows for users to have a portable binary without needed the
/// templates at runtime.
fn compile_templates() -> Handlebars {
let mut handlebars = Handlebars::new();
macro_rules! register_template {
( $( $template:expr ),* ) => {
[ $( $template:expr ),* ] => {
$(
handlebars
.register_template_string(
@ -233,8 +250,6 @@ fn compile_templates() -> Handlebars {
)*
};
}
register_template!("index", "list", "opensearch");
register_template!["index", "list", "opensearch"];
handlebars
}