polish prns.cc code

This commit is contained in:
sam 2023-07-28 02:21:33 +02:00
parent 6754296a48
commit 74ac9396c9
No known key found for this signature in database
GPG key ID: B4EF20DDE721CAA1
7 changed files with 82 additions and 149 deletions

60
Cargo.lock generated
View file

@ -194,6 +194,17 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "colored"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2674ec482fbc38012cf31e6c42ba0177b431a0cb6f15fe40efa5aab1bda516f6"
dependencies = [
"is-terminal",
"lazy_static",
"windows-sys 0.48.0",
]
[[package]] [[package]]
name = "cookie" name = "cookie"
version = "0.17.0" version = "0.17.0"
@ -801,12 +812,9 @@ dependencies = [
[[package]] [[package]]
name = "log" name = "log"
version = "0.4.17" version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "loom" name = "loom"
@ -936,6 +944,15 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "num_threads"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.17.1" version = "1.17.1"
@ -1074,13 +1091,13 @@ name = "prns"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"dotenvy", "dotenvy",
"log",
"pronouns", "pronouns",
"rocket", "rocket",
"simple_logger",
"sqlx", "sqlx",
"time", "time",
"tokio", "tokio",
"tracing",
"tracing-subscriber",
] ]
[[package]] [[package]]
@ -1512,6 +1529,18 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "simple_logger"
version = "4.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2230cd5c29b815c9b699fb610b49a5ed65588f3509d9f0108be3a885da629333"
dependencies = [
"colored",
"log",
"time",
"windows-sys 0.42.0",
]
[[package]] [[package]]
name = "slab" name = "slab"
version = "0.4.8" version = "0.4.8"
@ -1766,6 +1795,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59e399c068f43a5d116fedaf73b203fa4f9c519f17e2b34f63221d3792f81446" checksum = "59e399c068f43a5d116fedaf73b203fa4f9c519f17e2b34f63221d3792f81446"
dependencies = [ dependencies = [
"itoa", "itoa",
"libc",
"num_threads",
"serde", "serde",
"time-core", "time-core",
"time-macros", "time-macros",
@ -2231,6 +2262,21 @@ dependencies = [
"windows-targets 0.48.1", "windows-targets 0.48.1",
] ]
[[package]]
name = "windows-sys"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
dependencies = [
"windows_aarch64_gnullvm 0.42.2",
"windows_aarch64_msvc 0.42.2",
"windows_i686_gnu 0.42.2",
"windows_i686_msvc 0.42.2",
"windows_x86_64_gnu 0.42.2",
"windows_x86_64_gnullvm 0.42.2",
"windows_x86_64_msvc 0.42.2",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.45.0" version = "0.45.0"

View file

@ -1,6 +1,5 @@
[workspace] [workspace]
members = [ members = [
"pronouns", "pronouns",
"exporter",
"prns", "prns",
] ]

View file

@ -1,14 +0,0 @@
[package]
name = "exporter"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.6.12"
dotenvy = "0.15.7"
serde = { version = "1.0.159", features = ["derive"] }
serde_json = "1.0.95"
sqlx = { version = "0.6.3", features= ["runtime-tokio-rustls", "postgres", "json"]}
tokio = { version = "1.27.0", features = ["full"] }
tracing = "0.1.37"
tracing-subscriber = "0.3.16"

View file

@ -1,90 +0,0 @@
use std::env;
use std::net::SocketAddr;
use std::sync::Arc;
use axum::{
extract::{Path, State},
http::StatusCode,
routing::get,
Json, Router,
};
use sqlx::{postgres::PgPoolOptions, Pool, Postgres};
use tracing::{error, info};
use tracing_subscriber;
use user::ExportUser;
use crate::user::DBUser;
pub mod user;
struct AppState {
pool: Pool<Postgres>,
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
info!("Loading .env");
dotenvy::dotenv().unwrap();
info!("Connecting to database");
let db_dsn = env::var("DATABASE_URL").expect("DATABASE_URL is not set or invalid!");
let pool = PgPoolOptions::new()
.max_connections(10)
.connect(db_dsn.as_str())
.await
.expect("Could not connect do database!");
info!("Initializing exporter server");
let shared_state = Arc::new(AppState { pool });
let app = Router::new()
.route("/start/:id", get(handler))
.with_state(shared_state);
let port = match env::var("EXPORTER_PORT") {
Ok(val) => val
.parse::<u16>()
.expect("EXPORTER_PORT is not a valid integer!"),
Err(_) => {
error!("EXPORTER_PORT is not set, falling back to port 8081");
8081
}
};
info!(port, "Starting server");
let addr = SocketAddr::from(([127, 0, 0, 1], port));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handler(
State(state): State<Arc<AppState>>,
Path(user_id): Path<String>,
) -> Result<(StatusCode, Json<ExportUser>), (StatusCode, String)> {
info!(user_id = user_id, "Received thing :)");
let user = match sqlx::query_as!(
DBUser,
"SELECT id, username, display_name FROM users WHERE id = $1",
user_id
)
.fetch_one(&state.pool)
.await
{
Ok(val) => val,
Err(why) => return Err((StatusCode::INTERNAL_SERVER_ERROR, format!("{}", why))),
};
info!(id = user.id, username = user.username, "Got user!");
Ok((StatusCode::ACCEPTED, Json(user.to_export())))
}

View file

@ -1,24 +0,0 @@
use serde::Serialize;
pub struct DBUser {
pub id: String,
pub username: String,
pub display_name: Option<String>,
}
impl DBUser {
pub fn to_export(self) -> ExportUser {
ExportUser {
id: self.id,
username: self.username,
display_name: self.display_name,
}
}
}
#[derive(Serialize, Debug)]
pub struct ExportUser {
pub id: String,
pub username: String,
pub display_name: Option<String>,
}

View file

@ -11,6 +11,6 @@ time = { version = "0.3.23", features = ["formatting", "serde"] }
sqlx = { version = "0.6.3", features = ["runtime-tokio-rustls", "postgres", "json"]} sqlx = { version = "0.6.3", features = ["runtime-tokio-rustls", "postgres", "json"]}
rocket = "0.5.0-rc.3" rocket = "0.5.0-rc.3"
tokio = { version = "1.27.0", features = ["full"] } tokio = { version = "1.27.0", features = ["full"] }
tracing = "0.1.37"
tracing-subscriber = "0.3.16"
dotenvy = "0.15.7" dotenvy = "0.15.7"
simple_logger = "4.2.0"
log = "0.4.19"

View file

@ -1,9 +1,8 @@
use pronouns::models::{member::Member, user::User}; use pronouns::models::{member::Member, user::User};
use rocket::{response::Redirect, State}; use rocket::{response::Redirect, Config, State};
use simple_logger;
use sqlx::{postgres::PgPoolOptions, Pool, Postgres}; use sqlx::{postgres::PgPoolOptions, Pool, Postgres};
use std::env; use std::{env, path::PathBuf};
use tracing::info;
use tracing_subscriber;
#[macro_use] #[macro_use]
extern crate rocket; extern crate rocket;
@ -12,8 +11,10 @@ struct AppState {
base_url: String, base_url: String,
} }
#[get("/<sid>")] #[get("/<path..>")]
async fn redirect(state: &State<AppState>, sid: &str) -> Redirect { async fn redirect(state: &State<AppState>, path: PathBuf) -> Redirect {
let sid = path.to_str().unwrap_or("");
match sid.len() { match sid.len() {
5 => sqlx::query_as!( 5 => sqlx::query_as!(
User, User,
@ -23,7 +24,7 @@ async fn redirect(state: &State<AppState>, sid: &str) -> Redirect {
.fetch_one(&state.pool) .fetch_one(&state.pool)
.await .await
.map_or_else( .map_or_else(
|_| Redirect::temporary(format!("{}", state.base_url)), |_| Redirect::temporary(state.base_url.clone()),
|u| Redirect::temporary(format!("{}/@{}", state.base_url, u.username)), |u| Redirect::temporary(format!("{}/@{}", state.base_url, u.username)),
), ),
6 => { 6 => {
@ -35,7 +36,7 @@ async fn redirect(state: &State<AppState>, sid: &str) -> Redirect {
.fetch_one(&state.pool) .fetch_one(&state.pool)
.await .await
{ {
Err(_) => return Redirect::temporary(format!("{}", state.base_url)), Err(_) => return Redirect::temporary(state.base_url.clone()),
Ok(val) => val, Ok(val) => val,
}; };
@ -47,7 +48,7 @@ async fn redirect(state: &State<AppState>, sid: &str) -> Redirect {
.fetch_one(&state.pool) .fetch_one(&state.pool)
.await .await
.map_or_else( .map_or_else(
|_| Redirect::temporary(format!("{}", state.base_url)), |_| Redirect::temporary(state.base_url.clone()),
|u| { |u| {
Redirect::temporary(format!( Redirect::temporary(format!(
"{}/@{}/{}", "{}/@{}/{}",
@ -56,13 +57,13 @@ async fn redirect(state: &State<AppState>, sid: &str) -> Redirect {
}, },
) )
} }
_ => Redirect::temporary(format!("{}", state.base_url)), _ => Redirect::temporary(state.base_url.clone()),
} }
} }
#[launch] #[launch]
async fn rocket() -> _ { async fn rocket() -> _ {
tracing_subscriber::fmt::init(); simple_logger::SimpleLogger::new().env().init().unwrap();
info!("Loading .env"); info!("Loading .env");
@ -72,6 +73,15 @@ async fn rocket() -> _ {
let db_dsn = env::var("DATABASE_URL").expect("DATABASE_URL is not set or invalid!"); let db_dsn = env::var("DATABASE_URL").expect("DATABASE_URL is not set or invalid!");
let base_url = env::var("BASE_URL").expect("BASE_URL is not set or invalid!"); let base_url = env::var("BASE_URL").expect("BASE_URL is not set or invalid!");
let port = match env::var("PRNS_PORT") {
Ok(val) => val
.parse::<u16>()
.expect("PRNS_PORT is not a valid integer!"),
Err(_) => {
error!("PRNS_PORT is not set, falling back to port 8087");
8087
}
};
let pool = PgPoolOptions::new() let pool = PgPoolOptions::new()
.max_connections(10) .max_connections(10)
@ -81,7 +91,13 @@ async fn rocket() -> _ {
info!("Initializing prns.cc server"); info!("Initializing prns.cc server");
let config = Config {
port,
..Config::default()
};
rocket::build() rocket::build()
.configure(config)
.manage(AppState { pool, base_url }) .manage(AppState { pool, base_url })
.mount("/", routes![redirect]) .mount("/", routes![redirect])
} }