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