qchgk_web/src/main.rs

176 lines
4.4 KiB
Rust
Raw Normal View History

2019-08-05 14:06:27 +00:00
#![feature(proc_macro_hygiene, decl_macro)]
2022-11-11 17:56:35 +00:00
extern crate serde;
2019-08-19 12:58:47 +00:00
extern crate serde_json;
2019-08-02 10:47:16 +00:00
2019-08-19 12:58:47 +00:00
#[macro_use]
extern crate rocket;
2019-08-05 14:06:27 +00:00
extern crate rocket_contrib;
2019-08-02 10:47:16 +00:00
2019-08-05 14:06:27 +00:00
use rocket::response::Redirect;
2019-08-19 12:58:47 +00:00
use rocket::{Rocket, State};
2019-08-05 14:06:27 +00:00
use rocket_contrib::serve::StaticFiles;
use rocket_contrib::templates::Template;
2019-08-02 10:47:16 +00:00
2019-08-19 12:58:47 +00:00
use rand::distributions::Uniform;
use rand::Rng;
2019-08-02 10:47:16 +00:00
use std::ops::Deref;
2023-03-28 13:36:04 +00:00
use std::sync::Arc;
2023-01-03 22:12:03 +00:00
use chgk_ledb_lib::db;
2022-11-11 17:56:35 +00:00
use chgk_ledb_lib::questions::Question;
2023-04-04 08:39:52 +00:00
use mini_moka::sync::Cache;
use std::time::Duration;
2023-01-03 22:12:03 +00:00
const DB_FILENAME: &str = "db.dat";
2022-10-03 21:07:25 +00:00
trait ErrorEmpty {
type Output;
fn err_empty(self) -> Result<Self::Output, ()>;
}
impl<T, E> ErrorEmpty for Result<T, E> {
type Output = T;
fn err_empty(self) -> Result<Self::Output, ()> {
self.map_err(|_| ())
}
}
#[derive(Clone)]
struct ArcTemplateData {
value: Arc<serde_json::Value>,
}
impl ArcTemplateData {
fn new(value: serde_json::Value) -> ArcTemplateData {
ArcTemplateData {
value: Arc::new(value),
}
}
fn render(&self, name: &'static str) -> Template {
Template::render(name, self.value.deref())
}
}
2023-04-04 08:39:52 +00:00
type TemplateCache = mini_moka::sync::Cache<usize, ArcTemplateData>;
2023-03-28 13:36:04 +00:00
type DataBaseInner = db::Reader<Question>;
type DataBase = Arc<DataBaseInner>;
struct AppState {
2023-03-28 13:36:04 +00:00
db: DataBase,
2023-01-03 22:12:03 +00:00
database_distribution: Uniform<usize>,
2019-08-19 12:58:47 +00:00
}
2023-03-28 13:36:04 +00:00
impl From<DataBaseInner> for AppState {
fn from(db: DataBaseInner) -> Self {
let last_id = db.len();
let database_distribution = rand::distributions::Uniform::new_inclusive(1usize, last_id);
let db = Arc::new(db);
2023-01-03 22:12:03 +00:00
2023-03-28 13:36:04 +00:00
Self {
db,
database_distribution,
2023-03-28 13:36:04 +00:00
}
}
2019-08-19 12:58:47 +00:00
}
2023-01-03 22:12:03 +00:00
fn random_question_id(database_distribution: &Uniform<usize>) -> usize {
2019-08-19 12:58:47 +00:00
let mut rng = rand::thread_rng();
rng.sample(database_distribution)
2019-08-02 10:47:16 +00:00
}
2023-03-28 13:36:04 +00:00
fn get_question(db: &DataBase, id: usize) -> Result<Question, ()> {
db.get(id - 1).err_empty()
2019-08-02 10:47:16 +00:00
}
fn show_question_details(
template_name: &'static str,
data: &AppState,
cache: &TemplateCache,
id: usize,
) -> Template {
if let Some(value) = cache.get(&id) {
return value.render(template_name);
}
2023-03-28 13:36:04 +00:00
match get_question(&data.db, id) {
2022-10-03 21:07:25 +00:00
Ok(question) => {
2019-08-19 12:58:47 +00:00
let mut context = serde_json::to_value(question).expect("question serialize");
if context.is_object() {
let next_id = random_question_id(&data.database_distribution);
context["next"] = serde_json::to_value(next_id).expect("question id serialize");
}
let value = ArcTemplateData::new(context);
let result = value.render(template_name);
cache.insert(id, value);
result
2022-10-03 21:07:25 +00:00
}
Err(_) => {
use std::collections::HashMap;
let context: HashMap<String, String> = HashMap::new();
2023-03-28 13:36:04 +00:00
Template::render("404", context)
2019-08-02 10:47:16 +00:00
}
}
}
2019-08-05 14:06:27 +00:00
#[get("/q/<id>")]
fn show_question(data: State<AppState>, cache: State<TemplateCache>, id: usize) -> Template {
show_question_details("question", data.inner(), cache.inner(), id)
2019-08-02 10:47:16 +00:00
}
2019-08-05 14:06:27 +00:00
#[get("/q/<id>/a")]
fn show_answer(data: State<AppState>, cache: State<TemplateCache>, id: usize) -> Template {
show_question_details("answer", data.inner(), cache.inner(), id)
2019-08-02 10:47:16 +00:00
}
2022-10-03 21:07:25 +00:00
#[get("/q/0")]
fn question0() -> Redirect {
Redirect::to("/")
}
#[get("/q/0/a")]
fn answer0() -> Redirect {
Redirect::to("/")
}
2019-08-05 14:06:27 +00:00
#[get("/")]
fn index(data: State<AppState>) -> Redirect {
2019-08-19 12:58:47 +00:00
let id = random_question_id(&data.database_distribution);
2019-08-05 14:06:27 +00:00
Redirect::temporary(format!("/q/{}", id))
2019-08-02 10:47:16 +00:00
}
2019-08-05 14:06:27 +00:00
#[catch(404)]
fn not_found(_req: &rocket::Request) -> Template {
use std::collections::HashMap;
let context: HashMap<String, String> = HashMap::new();
2023-03-28 13:36:04 +00:00
Template::render("404", context)
2019-08-05 14:06:27 +00:00
}
2019-08-02 10:47:16 +00:00
2019-08-05 14:06:27 +00:00
fn rocket() -> Rocket {
2023-03-28 13:36:04 +00:00
let state: AppState = db::Reader::new(DB_FILENAME, 2048).expect("open db").into();
let cache: TemplateCache = Cache::builder()
.time_to_idle(Duration::from_secs(15 * 60))
.max_capacity(300)
.build();
2019-08-05 14:06:27 +00:00
rocket::ignite()
.manage(state)
.manage(cache)
2019-08-05 14:06:27 +00:00
.register(catchers![not_found])
2022-10-03 21:07:25 +00:00
.mount(
"/",
routes![index, show_question, show_answer, question0, answer0],
)
2019-08-05 14:06:27 +00:00
.mount("/q", routes![index])
.mount("/q/static", StaticFiles::from("static/"))
.attach(Template::fairing())
}
fn main() {
rocket().launch();
2019-08-02 10:47:16 +00:00
}