Compare commits

..

No commits in common. "165875b31ca89815c350faa5724c01805678caee" and "ea586013c9394a7e3ec5c4056fb723453a20e35a" have entirely different histories.

5 changed files with 67 additions and 106 deletions

10
.vscode/settings.json vendored
View file

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

11
Cargo.lock generated
View file

@ -363,8 +363,6 @@ dependencies = [
"actix-web 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)", "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)", "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)", "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 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)", "serde_yaml 0.8.11 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
@ -780,14 +778,6 @@ dependencies = [
"winreg 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "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]] [[package]]
name = "itoa" name = "itoa"
version = "0.4.4" version = "0.4.4"
@ -1904,7 +1894,6 @@ dependencies = [
"checksum inotify-sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e74a1aa87c59aeff6ef2cc2fa62d41bc43f54952f55652656b18a02fd5e356c0" "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 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 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 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 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" "checksum language-tags 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a91d884b6667cd606bb5a69aa0c99ba811a115fc68915e7056ec08a46e93199a"

View file

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

View file

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

View file

@ -6,24 +6,19 @@ use actix_web::{
}; };
use handlebars::Handlebars; use handlebars::Handlebars;
use hotwatch::{Event, Hotwatch}; use hotwatch::{Event, Hotwatch};
use itertools::Itertools;
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
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::fmt;
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io::Write; use std::io::Write;
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use std::time::Duration; 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 DEFAULT_CONFIG: &[u8] = include_bytes!("../bunbun.default.toml");
static CONFIG_FILE: &str = "bunbun.toml"; static CONFIG_FILE: &str = "bunbun.toml";
#[derive(Debug)] #[derive(Debug)]
#[allow(clippy::enum_variant_names)]
enum BunBunError { enum BunBunError {
IoError(std::io::Error), IoError(std::io::Error),
ParseError(serde_yaml::Error), ParseError(serde_yaml::Error),
@ -40,8 +35,8 @@ impl fmt::Display for BunBunError {
} }
} }
/// Generates a from implementation from the specified type to the provided impl Error for BunBunError {}
/// bunbun error.
macro_rules! from_error { macro_rules! from_error {
($from:ty, $to:ident) => { ($from:ty, $to:ident) => {
impl From<$from> for BunBunError { impl From<$from> for BunBunError {
@ -68,65 +63,60 @@ struct SearchQuery {
} }
#[get("/hop")] #[get("/hop")]
fn hop( fn hop(data: Data<Arc<RwLock<State>>>, query: Query<SearchQuery>) -> impl Responder {
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 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(); 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( template_args.insert(
"query", "query",
utf8_percent_encode(&args, FRAGMENT_ENCODE_SET).to_string(), format!(
"{}+{}",
command.unwrap(),
template_args.get("query").unwrap()
),
); );
HttpResponse::Found() HttpResponse::Found()
.header( .header(
header::LOCATION, header::LOCATION,
data data
.renderer .renderer
.render_template(&path, &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"),
}
}
/// 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()),
} }
} }
@ -135,8 +125,7 @@ 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() HttpResponse::Ok().body(data.renderer.render("index", &template_args).unwrap())
.body(data.renderer.render("index", &template_args).unwrap())
} }
#[get("/bunbunsearch.xml")] #[get("/bunbunsearch.xml")]
@ -152,8 +141,14 @@ fn opensearch(data: Data<Arc<RwLock<State>>>) -> impl Responder {
.body(data.renderer.render("opensearch", &template_args).unwrap()) .body(data.renderer.render("opensearch", &template_args).unwrap())
} }
/// Dynamic variables that either need to be present at runtime, or can be #[derive(Deserialize)]
/// changed during runtime. struct Config {
bind_address: String,
public_address: String,
default_route: Option<String>,
routes: BTreeMap<String, String>,
}
struct State { struct State {
public_address: String, public_address: String,
default_route: Option<String>, default_route: Option<String>,
@ -202,16 +197,6 @@ fn main() -> Result<(), BunBunError> {
Ok(()) 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> { fn read_config(config_file_path: &str) -> Result<Config, BunBunError> {
let config_file = match File::open(config_file_path) { let config_file = match File::open(config_file_path) {
Ok(file) => file, Ok(file) => file,
@ -232,13 +217,11 @@ fn read_config(config_file_path: &str) -> Result<Config, BunBunError> {
Ok(serde_yaml::from_reader(config_file)?) 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 { fn compile_templates() -> Handlebars {
let mut handlebars = Handlebars::new(); let mut handlebars = Handlebars::new();
macro_rules! register_template { macro_rules! register_template {
[ $( $template:expr ),* ] => { ( $( $template:expr ),* ) => {
$( $(
handlebars handlebars
.register_template_string( .register_template_string(
@ -250,6 +233,8 @@ fn compile_templates() -> Handlebars {
)* )*
}; };
} }
register_template!["index", "list", "opensearch"];
register_template!("index", "list", "opensearch");
handlebars handlebars
} }