| 1 |
use multithreaded::{AppState, config::Config, csrf}; |
| 2 |
use sqlx::postgres::PgPoolOptions; |
| 3 |
use tokio::net::TcpListener; |
| 4 |
use tower_sessions::ExpiredDeletion; |
| 5 |
use tower_sessions::SessionManagerLayer; |
| 6 |
use tower_sessions::cookie::SameSite; |
| 7 |
use tower_sessions_sqlx_store::PostgresStore; |
| 8 |
use tracing_subscriber::EnvFilter; |
| 9 |
|
| 10 |
#[tokio::main] |
| 11 |
async fn main() { |
| 12 |
tracing_subscriber::fmt() |
| 13 |
.with_env_filter(EnvFilter::from_default_env()) |
| 14 |
.init(); |
| 15 |
|
| 16 |
dotenvy::dotenv().ok(); |
| 17 |
|
| 18 |
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set"); |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
let pool = PgPoolOptions::new() |
| 26 |
.max_connections(32) |
| 27 |
.acquire_timeout(std::time::Duration::from_secs(10)) |
| 28 |
.connect(&database_url) |
| 29 |
.await |
| 30 |
.expect("failed to connect to database"); |
| 31 |
|
| 32 |
sqlx::migrate!() |
| 33 |
.run(&pool) |
| 34 |
.await |
| 35 |
.expect("failed to run migrations"); |
| 36 |
|
| 37 |
tracing::info!("migrations applied"); |
| 38 |
|
| 39 |
|
| 40 |
if std::env::args().any(|a| a == "--seed") { |
| 41 |
multithreaded::seed::run(&pool).await; |
| 42 |
tracing::info!("seed data inserted"); |
| 43 |
return; |
| 44 |
} |
| 45 |
|
| 46 |
let config = Config::from_env(); |
| 47 |
multithreaded::error_page::init(config.mnw_base_url.clone()); |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
multithreaded::trust_store::anchors_ok(); |
| 54 |
|
| 55 |
|
| 56 |
let s3 = if let Some(ref s3_config) = config.s3 { |
| 57 |
match multithreaded::storage::S3Storage::new(s3_config).await { |
| 58 |
Ok(client) => { |
| 59 |
tracing::info!("S3 storage configured (bucket: {})", s3_config.bucket); |
| 60 |
Some(std::sync::Arc::new(client)) |
| 61 |
} |
| 62 |
Err(e) => { |
| 63 |
tracing::warn!("S3 storage unavailable: {e}"); |
| 64 |
None |
| 65 |
} |
| 66 |
} |
| 67 |
} else { |
| 68 |
tracing::info!("S3 storage not configured (image uploads disabled)"); |
| 69 |
None |
| 70 |
}; |
| 71 |
|
| 72 |
let state = AppState { |
| 73 |
db: pool.clone(), |
| 74 |
config, |
| 75 |
http: multithreaded::tls::builder() |
| 76 |
.timeout(std::time::Duration::from_secs(15)) |
| 77 |
.connect_timeout(std::time::Duration::from_secs(5)) |
| 78 |
.build() |
| 79 |
.expect("failed to build HTTP client"), |
| 80 |
link_preview: multithreaded::link_preview::LinkPreviewFetcher::Http( |
| 81 |
multithreaded::link_preview::build_preview_client(), |
| 82 |
), |
| 83 |
s3, |
| 84 |
chat: std::sync::Arc::new(multithreaded::chat::new_chat()), |
| 85 |
chat_identities: multithreaded::chat::IdentityCache::new(), |
| 86 |
}; |
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
let session_pool = PgPoolOptions::new() |
| 93 |
.max_connections(6) |
| 94 |
.acquire_timeout(std::time::Duration::from_secs(10)) |
| 95 |
.connect(&database_url) |
| 96 |
.await |
| 97 |
.expect("failed to connect session store pool"); |
| 98 |
let session_store = PostgresStore::new(session_pool); |
| 99 |
session_store |
| 100 |
.migrate() |
| 101 |
.await |
| 102 |
.expect("failed to migrate session store"); |
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
let deletion_store = session_store.clone(); |
| 109 |
let deletion_task = supervise("session-expiry-sweep", move || { |
| 110 |
deletion_store |
| 111 |
.clone() |
| 112 |
.continuously_delete_expired(tokio::time::Duration::from_hours(1)) |
| 113 |
}); |
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
let purge_task = state.s3.as_ref().map(|s3| { |
| 118 |
let db = state.db.clone(); |
| 119 |
let s3 = s3.clone(); |
| 120 |
supervise("image-purge-sweep", move || { |
| 121 |
multithreaded::maintenance::continuously_purge_removed_images( |
| 122 |
db.clone(), |
| 123 |
s3.clone(), |
| 124 |
tokio::time::Duration::from_hours(6), |
| 125 |
) |
| 126 |
}) |
| 127 |
}); |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
let chat_sweep_db = state.db.clone(); |
| 133 |
let chat_sweep_task = supervise("chat-retention-sweep", move || { |
| 134 |
multithreaded::maintenance::continuously_sweep_chat( |
| 135 |
chat_sweep_db.clone(), |
| 136 |
multithreaded::maintenance::CHAT_SWEEP_INTERVAL, |
| 137 |
) |
| 138 |
}); |
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
let chat_limiter = state.chat.clone(); |
| 143 |
let chat_rate_task = supervise("chat-rate-bucket-sweep", move || { |
| 144 |
multithreaded::maintenance::continuously_sweep_chat_rate_limits(chat_limiter.clone()) |
| 145 |
}); |
| 146 |
|
| 147 |
let session_layer = SessionManagerLayer::new(session_store) |
| 148 |
.with_name("mt_session") |
| 149 |
.with_same_site(SameSite::Lax) |
| 150 |
.with_expiry(tower_sessions::Expiry::OnInactivity(time::Duration::days( |
| 151 |
7, |
| 152 |
))) |
| 153 |
.with_secure(state.config.cookie_secure); |
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
let forum = multithreaded::routes::forum_routes(state.clone()) |
| 158 |
.layer(axum::middleware::from_fn(csrf::csrf_middleware)) |
| 159 |
.layer(session_layer); |
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
let app = forum |
| 166 |
|
| 167 |
.merge(multithreaded::routes::internal::internal_routes(state)) |
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
.route( |
| 173 |
"/static/{*path}", |
| 174 |
axum::routing::get(multithreaded::static_assets::serve), |
| 175 |
) |
| 176 |
.layer(tower_http::set_header::SetResponseHeaderLayer::overriding( |
| 177 |
axum::http::header::CONTENT_SECURITY_POLICY, |
| 178 |
axum::http::HeaderValue::from_static( |
| 179 |
"default-src 'self'; img-src 'self'; style-src 'self'; \ |
| 180 |
frame-ancestors 'none'; object-src 'none'; base-uri 'none'; \ |
| 181 |
form-action 'self'", |
| 182 |
), |
| 183 |
)) |
| 184 |
.layer(tower_http::set_header::SetResponseHeaderLayer::overriding( |
| 185 |
axum::http::header::X_CONTENT_TYPE_OPTIONS, |
| 186 |
axum::http::HeaderValue::from_static("nosniff"), |
| 187 |
)) |
| 188 |
.layer(tower_http::set_header::SetResponseHeaderLayer::overriding( |
| 189 |
axum::http::header::X_FRAME_OPTIONS, |
| 190 |
axum::http::HeaderValue::from_static("DENY"), |
| 191 |
)) |
| 192 |
.layer( |
| 193 |
tower_http::set_header::SetResponseHeaderLayer::if_not_present( |
| 194 |
axum::http::header::CACHE_CONTROL, |
| 195 |
axum::http::HeaderValue::from_static("private, no-cache"), |
| 196 |
), |
| 197 |
) |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
.layer(tower_http::timeout::TimeoutLayer::with_status_code( |
| 205 |
axum::http::StatusCode::REQUEST_TIMEOUT, |
| 206 |
std::time::Duration::from_secs(30), |
| 207 |
)); |
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
let host = std::env::var("HOST").unwrap_or_else(|_| "127.0.0.1".to_string()); |
| 217 |
let port = std::env::var("PORT").unwrap_or_else(|_| "3400".to_string()); |
| 218 |
let addr = format!("{host}:{port}"); |
| 219 |
|
| 220 |
let listener = TcpListener::bind(&addr).await.expect("failed to bind"); |
| 221 |
|
| 222 |
tracing::info!("listening on {}", listener.local_addr().unwrap()); |
| 223 |
|
| 224 |
axum::serve( |
| 225 |
listener, |
| 226 |
app.into_make_service_with_connect_info::<std::net::SocketAddr>(), |
| 227 |
) |
| 228 |
.with_graceful_shutdown(shutdown_signal()) |
| 229 |
.await |
| 230 |
.expect("server error"); |
| 231 |
|
| 232 |
deletion_task.abort(); |
| 233 |
let _ = deletion_task.await; |
| 234 |
if let Some(task) = purge_task { |
| 235 |
task.abort(); |
| 236 |
let _ = task.await; |
| 237 |
} |
| 238 |
for task in [chat_sweep_task, chat_rate_task] { |
| 239 |
task.abort(); |
| 240 |
let _ = task.await; |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
fn supervise<F, Fut>(name: &'static str, factory: F) -> tokio::task::JoinHandle<()> |
| 252 |
where |
| 253 |
F: Fn() -> Fut + Send + 'static, |
| 254 |
Fut: std::future::Future + Send + 'static, |
| 255 |
Fut::Output: Send, |
| 256 |
{ |
| 257 |
const RESTART_BACKOFF: std::time::Duration = std::time::Duration::from_secs(5); |
| 258 |
tokio::task::spawn(async move { |
| 259 |
loop { |
| 260 |
match tokio::task::spawn(factory()).await { |
| 261 |
Ok(_) => { |
| 262 |
tracing::error!( |
| 263 |
task = name, |
| 264 |
"background task returned unexpectedly; restarting" |
| 265 |
); |
| 266 |
} |
| 267 |
Err(e) if e.is_panic() => { |
| 268 |
tracing::error!(task = name, "background task panicked; restarting"); |
| 269 |
} |
| 270 |
|
| 271 |
Err(_) => return, |
| 272 |
} |
| 273 |
tokio::time::sleep(RESTART_BACKOFF).await; |
| 274 |
} |
| 275 |
}) |
| 276 |
} |
| 277 |
|
| 278 |
async fn shutdown_signal() { |
| 279 |
use tokio::signal; |
| 280 |
let ctrl_c = async { |
| 281 |
signal::ctrl_c() |
| 282 |
.await |
| 283 |
.expect("failed to install Ctrl+C handler"); |
| 284 |
}; |
| 285 |
#[cfg(unix)] |
| 286 |
let terminate = async { |
| 287 |
signal::unix::signal(signal::unix::SignalKind::terminate()) |
| 288 |
.expect("failed to install signal handler") |
| 289 |
.recv() |
| 290 |
.await; |
| 291 |
}; |
| 292 |
#[cfg(not(unix))] |
| 293 |
let terminate = std::future::pending::<()>(); |
| 294 |
tokio::select! { |
| 295 |
() = ctrl_c => {}, |
| 296 |
() = terminate => {}, |
| 297 |
} |
| 298 |
tracing::info!("Shutdown signal received"); |
| 299 |
} |
| 300 |
|