chela/src/main.rs

135 lines
3.1 KiB
Rust
Raw Normal View History

2024-04-06 02:41:10 +00:00
use std::net::SocketAddr;
2024-04-07 17:35:59 +00:00
use url::Url;
2024-04-06 02:41:10 +00:00
use axum::routing::{get, post};
use axum::Router;
use sqlx::postgres::PgPoolOptions;
use sqlx::{Pool, Postgres};
2024-04-06 13:19:28 +00:00
use sqids::Sqids;
use serde::Deserialize;
2024-04-06 02:41:10 +00:00
use info_utils::prelude::*;
pub mod get;
pub mod post;
#[derive(Clone)]
pub struct ServerState {
pub db_pool: Pool<Postgres>,
pub host: String,
2024-04-06 13:19:28 +00:00
pub sqids: Sqids,
2024-04-07 17:35:59 +00:00
pub main_page_redirect: Option<Url>,
2024-04-07 18:44:03 +00:00
pub behind_proxy: bool,
2024-04-06 02:41:10 +00:00
}
2024-04-06 13:19:28 +00:00
#[derive(Debug, Clone, sqlx::FromRow, PartialEq, Eq)]
2024-04-06 02:41:10 +00:00
pub struct UrlRow {
2024-04-06 13:19:28 +00:00
pub index: i64,
2024-04-06 02:41:10 +00:00
pub id: String,
pub url: String,
}
2024-04-06 13:19:28 +00:00
#[derive(Deserialize, Debug, Clone)]
pub struct CreateForm {
pub id: String,
pub url: url::Url,
}
2024-04-06 02:41:10 +00:00
#[tokio::main]
async fn main() -> eyre::Result<()> {
color_eyre::install()?;
let db_pool = init_db().await?;
let host = std::env::var("CHELA_HOST").unwrap_or("localhost".to_string());
2024-04-06 13:19:28 +00:00
let sqids = Sqids::builder()
.alphabet(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.chars()
.collect(),
)
.blocklist(["create".to_string()].into())
.build()?;
2024-04-07 17:35:59 +00:00
let main_page_redirect = std::env::var("CHELA_MAIN_PAGE_REDIRECT").unwrap_or_default();
2024-04-07 18:44:03 +00:00
let behind_proxy = std::env::var("CHELA_BEHIND_PROXY").is_ok();
2024-04-06 13:19:28 +00:00
let server_state = ServerState {
db_pool,
host,
sqids,
2024-04-07 17:35:59 +00:00
main_page_redirect: Url::parse(&main_page_redirect).ok(),
2024-04-07 18:44:03 +00:00
behind_proxy,
2024-04-06 13:19:28 +00:00
};
2024-04-06 16:51:08 +00:00
let address = std::env::var("CHELA_LISTEN_ADDRESS").unwrap_or("0.0.0.0".to_string());
2024-04-06 13:55:50 +00:00
let port = 3000;
2024-04-06 02:41:10 +00:00
2024-04-06 13:19:28 +00:00
let router = init_routes(server_state);
let listener = tokio::net::TcpListener::bind(format!("{address}:{port}")).await?;
log!("Listening at {}:{}", address, port);
2024-04-06 02:41:10 +00:00
axum::serve(
listener,
router.into_make_service_with_connect_info::<SocketAddr>(),
)
.await?;
Ok(())
}
async fn init_db() -> eyre::Result<Pool<Postgres>> {
let db_pool = PgPoolOptions::new()
.max_connections(15)
2024-04-07 17:35:59 +00:00
.connect(
std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set")
.as_str(),
)
2024-04-06 02:41:10 +00:00
.await?;
log!("Successfully connected to database");
2024-04-06 13:19:28 +00:00
sqlx::query("CREATE SCHEMA IF NOT EXISTS chela")
2024-04-06 02:41:10 +00:00
.execute(&db_pool)
.await?;
log!("Created schema chela");
2024-04-06 13:19:28 +00:00
sqlx::query(
2024-04-06 02:41:10 +00:00
"
CREATE TABLE IF NOT EXISTS chela.urls (
2024-04-06 13:19:28 +00:00
index BIGSERIAL PRIMARY KEY,
2024-04-06 02:41:10 +00:00
id TEXT NOT NULL UNIQUE,
url TEXT NOT NULL
)
",
)
.execute(&db_pool)
.await?;
log!("Created table chela.urls");
2024-04-06 13:19:28 +00:00
sqlx::query(
2024-04-06 02:41:10 +00:00
"
CREATE TABLE IF NOT EXISTS chela.tracking (
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
id TEXT NOT NULL,
2024-04-07 18:44:03 +00:00
ip TEXT,
2024-04-06 02:41:10 +00:00
referrer TEXT,
user_agent TEXT
)
",
)
.execute(&db_pool)
.await?;
log!("Created table chela.tracking");
Ok(db_pool)
}
2024-04-06 13:19:28 +00:00
fn init_routes(state: ServerState) -> Router {
Router::new()
.route("/", get(get::index))
.route("/:id", get(get::id))
.route("/create", get(get::create_id))
2024-04-06 02:41:10 +00:00
.route("/", post(post::create_link))
2024-04-06 13:19:28 +00:00
.layer(axum::Extension(state))
2024-04-06 02:41:10 +00:00
}