quickpeep/quickpeep/src/main.rs

92 lines
2.6 KiB
Rust

use crate::config::WebConfig;
use crate::web::seed_collector::{seed_collection_root, seed_collection_root_post};
use anyhow::{bail, Context};
use axum::extract::Extension;
use axum::http::StatusCode;
use axum::routing::{get, get_service, post};
use axum::Router;
use env_logger::Env;
use sqlx::sqlite::SqlitePoolOptions;
use std::path::PathBuf;
use tower_http::services::ServeDir;
mod config;
mod web;
mod webutil;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
env_logger::Builder::from_env(
Env::default().default_filter_or("info,quickpeep=debug,sqlx=warn"),
)
.init();
let config_path =
PathBuf::from(std::env::var("QP_WEB_CONFIG").unwrap_or_else(|_| "qp_web.ron".to_owned()));
if !config_path.exists() {
bail!(
"Config path {:?} doesn't exist. QP_WEB_CONFIG env var overrides.",
config_path
);
}
let file_bytes = std::fs::read(&config_path).context("Failed to read web config file")?;
let web_config: WebConfig =
ron::de::from_bytes(&file_bytes).context("Failed to parse web config")?;
let pool = SqlitePoolOptions::new()
.min_connections(1)
.after_connect(|conn| {
Box::pin(async move {
// Use the WAL because it just makes more sense :)
sqlx::query("PRAGMA journal_mode = WAL")
.execute(&mut *conn)
.await?;
// Enable foreign keys because we like them!
sqlx::query("PRAGMA foreign_keys = ON")
.execute(&mut *conn)
.await?;
Ok(())
})
})
.connect(
&web_config
.sqlite_db_path
.to_str()
.context("SQLite DB path should be UTF-8")?,
)
.await?;
sqlx::migrate!().run(&pool).await?;
let app = Router::new()
.route("/seeds/", get(seed_collection_root))
.route("/seeds/", post(seed_collection_root_post))
.layer(Extension(web_config))
.layer(Extension(pool))
.nest(
"/static",
get_service(ServeDir::new("./quickpeep_static/dist")).handle_error(
|error: std::io::Error| async move {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
)
},
),
);
// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:9001".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
Ok(())
}