Merge pull request 'migrate/rocket/0.5' (#3) from migrate/rocket/0.5 into master
All checks were successful
continuous-integration/drone/push Build is passing

Reviewed-on: #3
This commit is contained in:
Dmitry Belyaev 2023-08-18 08:07:13 +00:00
commit f86a3a9050
4 changed files with 1226 additions and 757 deletions

View File

@ -1,9 +1,10 @@
kind: pipeline kind: pipeline
type: docker
name: default name: default
steps: steps:
- name: build - name: build
image: rustlang/rust:nightly-alpine image: rust:1-alpine
commands: commands:
- apk add --no-cache musl-dev - apk add --no-cache musl-dev
- cargo fetch - cargo fetch

1902
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -11,19 +11,14 @@ readme = "README.md"
[dependencies] [dependencies]
rand="0.8" rand="0.8"
serde="1.0" rocket = { version = "=0.5.0-rc.3", features = ["json"] }
serde_json="1.0" rocket_dyn_templates = { version = "=0.1.0-rc.3", features = ["tera"] }
rocket="0.4" chgk_ledb_lib = {git = "https://gitea.b4tman.ru/b4tman/chgk_ledb.git", rev="699478f85e", package="chgk_ledb_lib", features=["async"]}
chgk_ledb_lib = {git = "https://gitea.b4tman.ru/b4tman/chgk_ledb.git", rev="27260695f7", package="chgk_ledb_lib"}
mini-moka = "0.10.0" mini-moka = "0.10.0"
[dependencies.rocket_contrib]
version = "0.4"
default-features = false
features = ["serve", "tera_templates"]
[profile.release] [profile.release]
opt-level = 3 opt-level = 3
debug = false debug = false
lto = true lto = true
strip = true strip = true

View File

@ -1,16 +1,11 @@
#![feature(proc_macro_hygiene, decl_macro)]
extern crate serde;
extern crate serde_json;
#[macro_use] #[macro_use]
extern crate rocket; extern crate rocket;
extern crate rocket_contrib;
use rocket::fs::FileServer;
use rocket::response::Redirect; use rocket::response::Redirect;
use rocket::{Rocket, State}; use rocket::State;
use rocket_contrib::serve::StaticFiles; use rocket_dyn_templates::tera;
use rocket_contrib::templates::Template; use rocket_dyn_templates::Template;
use rand::distributions::Uniform; use rand::distributions::Uniform;
use rand::Rng; use rand::Rng;
@ -18,7 +13,7 @@ use rand::Rng;
use std::ops::Deref; use std::ops::Deref;
use std::sync::Arc; use std::sync::Arc;
use chgk_ledb_lib::db; use chgk_ledb_lib::async_db;
use chgk_ledb_lib::questions::Question; use chgk_ledb_lib::questions::Question;
use mini_moka::sync::Cache; use mini_moka::sync::Cache;
@ -40,11 +35,11 @@ impl<T, E> ErrorEmpty for Result<T, E> {
#[derive(Clone)] #[derive(Clone)]
struct ArcTemplateData { struct ArcTemplateData {
value: Arc<serde_json::Value>, value: Arc<tera::Value>,
} }
impl ArcTemplateData { impl ArcTemplateData {
fn new(value: serde_json::Value) -> ArcTemplateData { fn new(value: tera::Value) -> ArcTemplateData {
ArcTemplateData { ArcTemplateData {
value: Arc::new(value), value: Arc::new(value),
} }
@ -56,7 +51,7 @@ impl ArcTemplateData {
type TemplateCache = mini_moka::sync::Cache<usize, ArcTemplateData>; type TemplateCache = mini_moka::sync::Cache<usize, ArcTemplateData>;
type DataBaseInner = db::Reader<Question>; type DataBaseInner = async_db::Reader<Question>;
type DataBase = Arc<DataBaseInner>; type DataBase = Arc<DataBaseInner>;
struct AppState { struct AppState {
db: DataBase, db: DataBase,
@ -81,11 +76,11 @@ fn random_question_id(database_distribution: &Uniform<usize>) -> usize {
rng.sample(database_distribution) rng.sample(database_distribution)
} }
fn get_question(db: &DataBase, id: usize) -> Result<Question, ()> { async fn get_question(db: &DataBase, id: usize) -> Result<Question, ()> {
db.get(id - 1).err_empty() db.get(id - 1).await.err_empty()
} }
fn show_question_details( async fn show_question_details(
template_name: &'static str, template_name: &'static str,
data: &AppState, data: &AppState,
cache: &TemplateCache, cache: &TemplateCache,
@ -95,12 +90,12 @@ fn show_question_details(
return value.render(template_name); return value.render(template_name);
} }
match get_question(&data.db, id) { match get_question(&data.db, id).await {
Ok(question) => { Ok(question) => {
let mut context = serde_json::to_value(question).expect("question serialize"); let mut context = tera::to_value(question).expect("question serialize");
if context.is_object() { if context.is_object() {
let next_id = random_question_id(&data.database_distribution); let next_id = random_question_id(&data.database_distribution);
context["next"] = serde_json::to_value(next_id).expect("question id serialize"); context["next"] = tera::to_value(next_id).expect("question id serialize");
} }
let value = ArcTemplateData::new(context); let value = ArcTemplateData::new(context);
@ -118,13 +113,17 @@ fn show_question_details(
} }
#[get("/q/<id>")] #[get("/q/<id>")]
fn show_question(data: State<AppState>, cache: State<TemplateCache>, id: usize) -> Template { async fn show_question(
show_question_details("question", data.inner(), cache.inner(), id) data: &State<AppState>,
cache: &State<TemplateCache>,
id: usize,
) -> Template {
show_question_details("question", data.inner(), cache.inner(), id).await
} }
#[get("/q/<id>/a")] #[get("/q/<id>/a")]
fn show_answer(data: State<AppState>, cache: State<TemplateCache>, id: usize) -> Template { async fn show_answer(data: &State<AppState>, cache: &State<TemplateCache>, id: usize) -> Template {
show_question_details("answer", data.inner(), cache.inner(), id) show_question_details("answer", data.inner(), cache.inner(), id).await
} }
#[get("/q/0")] #[get("/q/0")]
@ -138,7 +137,7 @@ fn answer0() -> Redirect {
} }
#[get("/")] #[get("/")]
fn index(data: State<AppState>) -> Redirect { fn index(data: &State<AppState>) -> Redirect {
let id = random_question_id(&data.database_distribution); let id = random_question_id(&data.database_distribution);
Redirect::temporary(format!("/q/{}", id)) Redirect::temporary(format!("/q/{}", id))
} }
@ -150,26 +149,26 @@ fn not_found(_req: &rocket::Request) -> Template {
Template::render("404", context) Template::render("404", context)
} }
fn rocket() -> Rocket { #[launch]
let state: AppState = db::Reader::new(DB_FILENAME, 2048).expect("open db").into(); async fn rocket() -> _ {
let state: AppState = async_db::Reader::new(DB_FILENAME)
.await
.expect("open db")
.into();
let cache: TemplateCache = Cache::builder() let cache: TemplateCache = Cache::builder()
.time_to_idle(Duration::from_secs(15 * 60)) .time_to_idle(Duration::from_secs(15 * 60))
.max_capacity(300) .max_capacity(300)
.build(); .build();
rocket::ignite() rocket::build()
.manage(state) .manage(state)
.manage(cache) .manage(cache)
.register(catchers![not_found]) .register("/", catchers![not_found])
.mount( .mount(
"/", "/",
routes![index, show_question, show_answer, question0, answer0], routes![index, show_question, show_answer, question0, answer0],
) )
.mount("/q", routes![index]) .mount("/q", routes![index])
.mount("/q/static", StaticFiles::from("static/")) .mount("/q/static", FileServer::from("static/"))
.attach(Template::fairing()) .attach(Template::fairing())
} }
fn main() {
rocket().launch();
}