Files
sorsfonalak/services/forum/src/main.rs
T

67 lines
2.4 KiB
Rust
Raw Normal View History

//! Sorsfonalak forum: pseudonymous members, topics, threads, posts,
//! reactions, read marks, followed threads and moderation (docs/kozosseg.md).
//!
//! A service of its own, so it can be scaled apart from the backend. It shares
//! the database and the login: a session of the backend (`sf_session` cookie
//! or `Authorization: Bearer`) is valid here too.
//!
//! Configuration: `DATABASE_URL`, `PUBLIC_BASE_URL` (the site, for e-mail
//! links; default `http://localhost:3001`); `BIND_ADDR` (default `0.0.0.0:8083`),
//! `LOG_FORMAT`, `RUST_LOG`, `LOG_DIR`. Database migrations run at startup.
//!
//! `forum healthcheck` performs a local health check (for Docker).
mod auth;
mod error;
2026-11-26 11:41:45 +00:00
mod live;
mod mail;
mod rank;
mod routes;
#[cfg(test)]
mod tests;
mod text;
use std::sync::Arc;
use anyhow::Context;
use sqlx::PgPool;
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8083";
pub struct AppState {
pub db: PgPool,
/// Seconds a member waits between two posts (0 in the tests).
pub flood_secs: i32,
2026-11-26 11:41:45 +00:00
/// The site's address, for the links in e-mails (`PUBLIC_BASE_URL`); also
/// the only origin allowed to open a live connection.
pub base_url: String,
2026-11-26 11:41:45 +00:00
/// The live events of this instance (`live::listen` fills it).
pub hub: live::Hub,
}
impl AppState {
pub fn new(db: PgPool, base_url: String) -> Self {
2026-11-26 11:41:45 +00:00
Self { db, flood_secs: 5, base_url: base_url.trim_end_matches('/').to_string(), hub: live::Hub::default() }
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let addr = service_kit::bind_addr(DEFAULT_BIND_ADDR)?;
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
return service_kit::healthcheck(addr);
}
let _log = service_kit::init_logging("forum");
let url = std::env::var("DATABASE_URL").context("DATABASE_URL is not set")?;
let pool = db::connect(&url).await.context("connecting to the database")?;
db::migrate(&pool).await.context("running database migrations")?;
let base_url = std::env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| "http://localhost:3001".into());
2026-11-26 11:41:45 +00:00
let state = Arc::new(AppState::new(pool, base_url));
tokio::spawn(live::listen(state.db.clone(), state.hub.clone()));
let app = routes::router(state);
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
tracing::info!(%addr, "listening");
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
Ok(())
}