]> Untitled Git - lemmy.git/blob - src/main.rs
Adding admin purging of DB items and pictures. #904 #1331 (#1809)
[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,
30 };
31 use lemmy_websocket::{chat_server::ChatServer, LemmyContext};
32 use parking_lot::Mutex;
33 use reqwest::Client;
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;
39
40 embed_migrations!();
41
42 /// Max timeout for http requests
43 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
44
45 #[actix_web::main]
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(),
51       ..Default::default()
52     };
53     println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
54     return Ok(());
55   }
56
57   let settings = Settings::init().expect("Couldn't initialize settings.");
58
59   init_logging(settings.opentelemetry_url.as_deref())?;
60
61   // Set up the r2d2 connection pool
62   let db_url = match get_database_url_from_env() {
63     Ok(url) => url,
64     Err(_) => settings.get_database_url(),
65   };
66   let manager = ConnectionManager::<PgConnection>::new(&db_url);
67   let pool = Pool::builder()
68     .max_size(settings.database.pool_size)
69     .build(manager)
70     .unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
71
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>
78   })
79   .await??;
80
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");
85   });
86
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(),
91   };
92
93   // Initialize the secrets
94   let conn = pool.get()?;
95   let secret = Secret::init(&conn).expect("Couldn't initialize secrets.");
96
97   println!(
98     "Starting http server at {}:{}",
99     settings.bind, settings.port
100   );
101
102   let reqwest_client = Client::builder()
103     .user_agent(build_user_agent(&settings))
104     .timeout(REQWEST_TIMEOUT)
105     .build()?;
106
107   let retry_policy = ExponentialBackoff {
108     max_n_retries: 3,
109     max_retry_interval: REQWEST_TIMEOUT,
110     min_retry_interval: Duration::from_millis(100),
111     backoff_exponent: 2,
112   };
113
114   let client = ClientBuilder::new(reqwest_client.clone())
115     .with(TracingMiddleware)
116     .with(RetryTransientMiddleware::new_with_policy(retry_policy))
117     .build();
118
119   // Pictrs cannot use the retry middleware
120   let pictrs_client = ClientBuilder::new(reqwest_client.clone())
121     .with(TracingMiddleware)
122     .build();
123
124   check_private_instance_and_federation_enabled(&pool, &settings).await?;
125
126   let chat_server = ChatServer::startup(
127     pool.clone(),
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)),
131     client.clone(),
132     settings.clone(),
133     secret.clone(),
134   )
135   .start();
136
137   // Create Http server with websocket support
138   let settings_bind = settings.clone();
139   HttpServer::new(move || {
140     let context = LemmyContext::create(
141       pool.clone(),
142       chat_server.to_owned(),
143       client.clone(),
144       settings.to_owned(),
145       secret.to_owned(),
146     );
147     let rate_limiter = rate_limiter.clone();
148     App::new()
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()))
153       // The routes
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))
160   })
161   .bind((settings_bind.bind, settings_bind.port))?
162   .run()
163   .await?;
164
165   Ok(())
166 }