]> Untitled Git - lemmy.git/blob - src/main.rs
07be683e9c574b71e40b53d16c53485d1b12c8f6
[lemmy.git] / src / main.rs
1 #[macro_use]
2 extern crate diesel_migrations;
3
4 use actix::prelude::*;
5 use actix_web::{web::Data, *};
6 use diesel::{
7   r2d2::{ConnectionManager, Pool},
8   PgConnection,
9 };
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},
15 };
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};
19 use lemmy_server::{
20   api_routes,
21   code_migrations::run_advanced_migrations,
22   init_logging,
23   root_span_builder::QuieterRootSpanBuilder,
24   scheduled_tasks,
25 };
26 use lemmy_utils::{
27   error::LemmyError,
28   rate_limit::{rate_limiter::RateLimiter, RateLimit},
29   settings::{structs::Settings, SETTINGS},
30 };
31 use lemmy_websocket::{chat_server::ChatServer, LemmyContext};
32 use reqwest::Client;
33 use reqwest_middleware::ClientBuilder;
34 use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
35 use reqwest_tracing::TracingMiddleware;
36 use std::{
37   env,
38   sync::{Arc, Mutex},
39   thread,
40   time::Duration,
41 };
42 use tracing_actix_web::TracingLogger;
43
44 embed_migrations!();
45
46 /// Max timeout for http requests
47 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
48
49 #[actix_web::main]
50 async fn main() -> Result<(), LemmyError> {
51   let args: Vec<String> = env::args().collect();
52   if args.len() == 2 && args[1] == "--print-config-docs" {
53     let fmt = Formatting {
54       auto_comments: AutoComments::none(),
55       ..Default::default()
56     };
57     println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
58     return Ok(());
59   }
60
61   let settings = SETTINGS.to_owned();
62
63   init_logging(&settings.opentelemetry_url)?;
64
65   // Set up the r2d2 connection pool
66   let db_url = match get_database_url_from_env() {
67     Ok(url) => url,
68     Err(_) => settings.get_database_url(),
69   };
70   let manager = ConnectionManager::<PgConnection>::new(&db_url);
71   let pool = Pool::builder()
72     .max_size(settings.database.pool_size)
73     .min_idle(Some(1))
74     .build(manager)
75     .unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
76
77   // Run the migrations from code
78   let protocol_and_hostname = settings.get_protocol_and_hostname();
79   blocking(&pool, move |conn| {
80     embedded_migrations::run(conn)?;
81     run_advanced_migrations(conn, &protocol_and_hostname)?;
82     Ok(()) as Result<(), LemmyError>
83   })
84   .await??;
85
86   // Schedules various cleanup tasks for the DB
87   let pool2 = pool.clone();
88   thread::spawn(move || {
89     scheduled_tasks::setup(pool2).expect("Couldn't set up scheduled_tasks");
90   });
91
92   // Set up the rate limiter
93   let rate_limiter = RateLimit {
94     rate_limiter: Arc::new(Mutex::new(RateLimiter::default())),
95     rate_limit_config: settings.rate_limit.to_owned().unwrap_or_default(),
96   };
97
98   // Initialize the secrets
99   let conn = pool.get()?;
100   let secret = Secret::init(&conn).expect("Couldn't initialize secrets.");
101
102   println!(
103     "Starting http server at {}:{}",
104     settings.bind, settings.port
105   );
106
107   let reqwest_client = Client::builder()
108     .user_agent(build_user_agent(&settings))
109     .timeout(REQWEST_TIMEOUT)
110     .build()?;
111
112   let retry_policy = ExponentialBackoff {
113     max_n_retries: 3,
114     max_retry_interval: REQWEST_TIMEOUT,
115     min_retry_interval: Duration::from_millis(100),
116     backoff_exponent: 2,
117   };
118
119   let client = ClientBuilder::new(reqwest_client.clone())
120     .with(TracingMiddleware)
121     .with(RetryTransientMiddleware::new_with_policy(retry_policy))
122     .build();
123
124   // Pictrs cannot use the retry middleware
125   let pictrs_client = ClientBuilder::new(reqwest_client.clone())
126     .with(TracingMiddleware)
127     .build();
128
129   check_private_instance_and_federation_enabled(&pool, &settings).await?;
130
131   let chat_server = ChatServer::startup(
132     pool.clone(),
133     rate_limiter.clone(),
134     |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
135     |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
136     client.clone(),
137     settings.clone(),
138     secret.clone(),
139   )
140   .start();
141
142   // Create Http server with websocket support
143   let settings_bind = settings.clone();
144   HttpServer::new(move || {
145     let context = LemmyContext::create(
146       pool.clone(),
147       chat_server.to_owned(),
148       client.clone(),
149       settings.to_owned(),
150       secret.to_owned(),
151     );
152     let rate_limiter = rate_limiter.clone();
153     App::new()
154       .wrap(actix_web::middleware::Logger::default())
155       .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
156       .app_data(Data::new(context))
157       .app_data(Data::new(rate_limiter.clone()))
158       // The routes
159       .configure(|cfg| api_routes::config(cfg, &rate_limiter))
160       .configure(|cfg| lemmy_apub::http::routes::config(cfg, &settings))
161       .configure(feeds::config)
162       .configure(|cfg| images::config(cfg, pictrs_client.clone(), &rate_limiter))
163       .configure(nodeinfo::config)
164       .configure(|cfg| webfinger::config(cfg, &settings))
165   })
166   .bind((settings_bind.bind, settings_bind.port))?
167   .run()
168   .await?;
169
170   Ok(())
171 }