forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

main.rs85 lines, 3.4 KiBHistoryRawDownload
1use anyhow::Context;
2use hezarfen_backend::config::Config;
3use hezarfen_backend::rate_limit::UserRateLimiter;
4use hezarfen_backend::state::AppState;
5use hezarfen_backend::{build_router, database};
6
7#[tokio::main]
8async fn main() -> anyhow::Result<()> {
9 dotenvy::dotenv().ok();
10 let telemetry_cfg = hezarfen_backend::config::telemetry_from_env()?;
11 // Held until after graceful shutdown: dropping the guard flushes whatever
12 // the exporters still have buffered.
13 let (_telemetry, metrics) = hezarfen_backend::telemetry::init(&telemetry_cfg)?;
14 match telemetry_cfg.otlp_endpoint.as_deref() {
15 Some(endpoint) => {
16 tracing::info!("exporting OpenTelemetry traces/metrics/logs to {endpoint}")
17 }
18 None => tracing::info!(
19 "OpenTelemetry export is off (set OTEL_EXPORTER_OTLP_ENDPOINT to turn it on)"
20 ),
21 }
22
23 let cfg = Config::from_env();
24 // Hash the login decoy now, so the first unknown-username login is not the
25 // one request that pays for it (see `PasswordHash::prewarm_decoy`).
26 hezarfen_backend::domain::user::PasswordHash::prewarm_decoy();
27 // Connects to the control database, migrates it and seeds the builder —
28 // all of it idempotent and unconditional on every boot. Every registered
29 // school is brought to the school-schema head here too (see
30 // `Tenants::sweep_school_schemas`); school pools themselves come up
31 // lazily, one connection each, on first use.
32 let tenants = database::init(&cfg).await?;
33 tokio::fs::create_dir_all(&cfg.files_path)
34 .await
35 .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?;
36 let ai = hezarfen_backend::ai::start_bridge(&cfg).await?;
37 let app = build_router(AppState {
38 db: tenants.control().clone(),
39 tenants,
40 files_path: cfg.files_path.clone().into(),
41 cookie_secure: cfg.cookie_secure,
42 rate_limit: cfg.rate_limit.clone(),
43 chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute),
44 rag_limit: UserRateLimiter::per_user_minute(cfg.rag_per_minute),
45 exam_presence: Default::default(),
46 board_hub: Default::default(),
47 ai,
48 metrics,
49 });
50
51 let addr = format!("{}:{}", cfg.host, cfg.port);
52 let listener = tokio::net::TcpListener::bind(addr.as_str()).await?;
53 tracing::info!("hezarfen_backend listening on http://{addr}");
54 // `with_connect_info` records each connection's peer address, which the
55 // rate limiter uses as its per-client key (unless TRUST_PROXY is set).
56 axum::serve(
57 listener,
58 app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
59 )
60 .with_graceful_shutdown(shutdown_signal())
61 .await?;
62 tracing::info!("shutting down");
63 Ok(())
64}
65
66/// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process
67/// gets no default signal handling, so without this a `podman stop` waits out
68/// its grace period and SIGKILLs us — dropping in-flight requests mid-write.
69async fn shutdown_signal() {
70 let ctrl_c = async {
71 tokio::signal::ctrl_c()
72 .await
73 .expect("failed to install SIGINT handler");
74 };
75 let terminate = async {
76 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
77 .expect("failed to install SIGTERM handler")
78 .recv()
79 .await;
80 };
81 tokio::select! {
82 _ = ctrl_c => {},
83 _ = terminate => {},
84 }
85}