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

112 lines
4.0 KiB
Rust
Raw Normal View History

//! Sorsfonalak backend: users, login, charts, synastries, analyses, credits
//! and public sharing. Charts are calculated by the horoscope-api service.
//!
//! Configuration: see [`config::Config`]; plus `BIND_ADDR` (default
//! `0.0.0.0:8081`), `LOG_FORMAT` and `RUST_LOG`.
//! Database migrations run at startup.
//!
//! `backend healthcheck` performs a local health check (for Docker).
mod auth;
mod birth_changes;
mod config;
mod credits;
mod error;
mod invoices;
mod models;
2026-11-20 19:40:03 +00:00
mod oidc;
mod packages;
mod persons;
mod photo;
mod routes;
mod storage;
2026-11-20 06:41:21 +00:00
mod stripe;
#[cfg(test)]
mod tests;
mod views;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context;
use horoscope_client::HoroscopeClient;
use sqlx::PgPool;
use crate::auth::LoginLimiter;
use crate::config::Config;
2026-11-20 19:40:03 +00:00
use crate::oidc::IdTokenVerifier;
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8081";
pub struct AppState {
pub db: PgPool,
pub config: Config,
pub horoscope: HoroscopeClient,
2026-11-20 19:40:03 +00:00
pub google: IdTokenVerifier,
pub apple: IdTokenVerifier,
pub login_limiter: LoginLimiter,
/// The public sign calculator, per visitor address.
pub calculator_limiter: LoginLimiter,
/// The public place search (typing makes several calls), per visitor address.
pub places_limiter: LoginLimiter,
/// Share visits already counted (link and visitor address, for half an hour):
/// a reload is not a new visit, without storing anything in the browser.
pub share_visits: LoginLimiter,
pub models: models::Catalog,
2026-11-20 06:41:21 +00:00
pub stripe: stripe::Client,
/// Uploaded photos; `None` when no object storage is configured.
pub storage: Option<storage::Storage>,
}
impl AppState {
pub fn new(db: PgPool, config: Config) -> Self {
Self {
horoscope: HoroscopeClient::new(&config.horoscope_api_url),
2026-11-20 19:40:03 +00:00
google: IdTokenVerifier::google(config.google_client_ids.clone(), config.google_jwks_url.clone()),
apple: IdTokenVerifier::apple(config.apple_client_ids.clone(), config.apple_jwks_url.clone()),
login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)),
calculator_limiter: LoginLimiter::new(30, Duration::from_secs(60 * 60)),
places_limiter: LoginLimiter::new(300, Duration::from_secs(60 * 60)),
share_visits: LoginLimiter::new(1, Duration::from_secs(30 * 60)),
models: models::Catalog::new(&config.openrouter_models_url),
2026-11-20 06:41:21 +00:00
stripe: stripe::Client::default(),
storage: config.storage.clone().map(storage::Storage::new),
db,
config,
}
}
}
#[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("backend");
let config = Config::from_env()?;
let pool = db::connect(&config.database_url).await.context("connecting to the database")?;
db::migrate(&pool).await.context("running database migrations")?;
tracing::info!(
google_login = !config.google_client_ids.is_empty(),
2026-11-20 19:40:03 +00:00
apple_login = !config.apple_client_ids.is_empty(),
horoscope_api = %config.horoscope_api_url,
"database ready"
);
if std::env::args().nth(1).as_deref() == Some("recalculate") {
return routes::recalculate(&AppState::new(pool, config)).await;
}
let state = AppState::new(pool, config);
if state.config.storage_create_bucket
&& let Some(storage) = &state.storage
&& let Err(e) = storage.ensure_bucket().await
{
tracing::warn!(error = %e, "creating the object storage bucket failed");
}
let app = routes::router(Arc::new(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(())
}