2 extern crate diesel_migrations;
5 use actix_web::{web::Data, *};
7 r2d2::{ConnectionManager, Pool},
10 use doku::json::{AutoComments, Formatting};
11 use lemmy_api::match_websocket_operation;
12 use lemmy_api_common::{
13 request::build_user_agent,
14 utils::{blocking, check_private_instance_and_federation_enabled},
16 use lemmy_api_crud::match_websocket_operation_crud;
17 use lemmy_db_schema::{source::secret::Secret, utils::get_database_url_from_env};
18 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
21 code_migrations::run_advanced_migrations,
23 root_span_builder::QuieterRootSpanBuilder,
28 rate_limit::{rate_limiter::RateLimiter, RateLimit},
29 settings::structs::Settings,
31 use lemmy_websocket::{chat_server::ChatServer, LemmyContext};
32 use parking_lot::Mutex;
34 use reqwest_middleware::ClientBuilder;
35 use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
36 use reqwest_tracing::TracingMiddleware;
37 use std::{env, sync::Arc, thread, time::Duration};
38 use tracing_actix_web::TracingLogger;
42 /// Max timeout for http requests
43 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
46 async fn main() -> Result<(), LemmyError> {
47 let args: Vec<String> = env::args().collect();
48 if args.len() == 2 && args[1] == "--print-config-docs" {
49 let fmt = Formatting {
50 auto_comments: AutoComments::none(),
53 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
57 let settings = Settings::init().expect("Couldn't initialize settings.");
59 init_logging(settings.opentelemetry_url.as_deref())?;
61 // Set up the r2d2 connection pool
62 let db_url = match get_database_url_from_env() {
64 Err(_) => settings.get_database_url(),
66 let manager = ConnectionManager::<PgConnection>::new(&db_url);
67 let pool = Pool::builder()
68 .max_size(settings.database.pool_size)
70 .unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
72 // Run the migrations from code
73 let protocol_and_hostname = settings.get_protocol_and_hostname();
74 blocking(&pool, move |conn| {
75 embedded_migrations::run(conn)?;
76 run_advanced_migrations(conn, &protocol_and_hostname)?;
77 Ok(()) as Result<(), LemmyError>
81 // Schedules various cleanup tasks for the DB
82 let pool2 = pool.clone();
83 thread::spawn(move || {
84 scheduled_tasks::setup(pool2).expect("Couldn't set up scheduled_tasks");
87 // Set up the rate limiter
88 let rate_limiter = RateLimit {
89 rate_limiter: Arc::new(Mutex::new(RateLimiter::default())),
90 rate_limit_config: settings.rate_limit.to_owned().unwrap_or_default(),
93 // Initialize the secrets
94 let conn = pool.get()?;
95 let secret = Secret::init(&conn).expect("Couldn't initialize secrets.");
98 "Starting http server at {}:{}",
99 settings.bind, settings.port
102 let reqwest_client = Client::builder()
103 .user_agent(build_user_agent(&settings))
104 .timeout(REQWEST_TIMEOUT)
107 let retry_policy = ExponentialBackoff {
109 max_retry_interval: REQWEST_TIMEOUT,
110 min_retry_interval: Duration::from_millis(100),
114 let client = ClientBuilder::new(reqwest_client.clone())
115 .with(TracingMiddleware)
116 .with(RetryTransientMiddleware::new_with_policy(retry_policy))
119 // Pictrs cannot use the retry middleware
120 let pictrs_client = ClientBuilder::new(reqwest_client.clone())
121 .with(TracingMiddleware)
124 check_private_instance_and_federation_enabled(&pool, &settings).await?;
126 let chat_server = ChatServer::startup(
128 rate_limiter.clone(),
129 |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
130 |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
137 // Create Http server with websocket support
138 let settings_bind = settings.clone();
139 HttpServer::new(move || {
140 let context = LemmyContext::create(
142 chat_server.to_owned(),
147 let rate_limiter = rate_limiter.clone();
149 .wrap(actix_web::middleware::Logger::default())
150 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
151 .app_data(Data::new(context))
152 .app_data(Data::new(rate_limiter.clone()))
154 .configure(|cfg| api_routes::config(cfg, &rate_limiter))
155 .configure(|cfg| lemmy_apub::http::routes::config(cfg, &settings))
156 .configure(feeds::config)
157 .configure(|cfg| images::config(cfg, pictrs_client.clone(), &rate_limiter))
158 .configure(nodeinfo::config)
159 .configure(|cfg| webfinger::config(cfg, &settings))
161 .bind((settings_bind.bind, settings_bind.port))?