]> Untitled Git - lemmy.git/blob - src/main.rs
Rework websocket (#2598)
[lemmy.git] / src / main.rs
1 #[macro_use]
2 extern crate diesel_migrations;
3
4 use actix_web::{middleware, web::Data, App, HttpServer, Result};
5 use diesel_migrations::EmbeddedMigrations;
6 use doku::json::{AutoComments, CommentsStyle, Formatting, ObjectsStyle};
7 use lemmy_api_common::{
8   context::LemmyContext,
9   lemmy_db_views::structs::SiteView,
10   request::build_user_agent,
11   utils::{
12     check_private_instance_and_federation_enabled,
13     local_site_rate_limit_to_rate_limit_config,
14   },
15   websocket::chat_server::ChatServer,
16 };
17 use lemmy_db_schema::{
18   source::secret::Secret,
19   utils::{build_db_pool, get_database_url, run_migrations},
20 };
21 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
22 use lemmy_server::{
23   api_routes_http,
24   code_migrations::run_advanced_migrations,
25   init_logging,
26   root_span_builder::QuieterRootSpanBuilder,
27   scheduled_tasks,
28 };
29 use lemmy_utils::{
30   error::LemmyError,
31   rate_limit::RateLimitCell,
32   settings::{structs::Settings, SETTINGS},
33 };
34 use reqwest::Client;
35 use reqwest_middleware::ClientBuilder;
36 use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
37 use reqwest_tracing::TracingMiddleware;
38 use std::{env, sync::Arc, thread, time::Duration};
39 use tracing_actix_web::TracingLogger;
40
41 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
42
43 /// Max timeout for http requests
44 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
45
46 #[actix_web::main]
47 async fn main() -> Result<(), LemmyError> {
48   let args: Vec<String> = env::args().collect();
49   if args.len() == 2 && args[1] == "--print-config-docs" {
50     let fmt = Formatting {
51       auto_comments: AutoComments::none(),
52       comments_style: CommentsStyle {
53         separator: "#".to_owned(),
54       },
55       objects_style: ObjectsStyle {
56         surround_keys_with_quotes: false,
57         use_comma_as_separator: false,
58       },
59       ..Default::default()
60     };
61     println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
62     return Ok(());
63   }
64
65   let settings = SETTINGS.to_owned();
66
67   init_logging(&settings.opentelemetry_url)?;
68
69   // Set up the bb8 connection pool
70   let db_url = get_database_url(Some(&settings));
71   run_migrations(&db_url);
72
73   // Run the migrations from code
74   let pool = build_db_pool(&settings).await?;
75   run_advanced_migrations(&pool, &settings).await?;
76
77   // Schedules various cleanup tasks for the DB
78   thread::spawn(move || {
79     scheduled_tasks::setup(db_url).expect("Couldn't set up scheduled_tasks");
80   });
81
82   // Initialize the secrets
83   let secret = Secret::init(&pool)
84     .await
85     .expect("Couldn't initialize secrets.");
86
87   // Make sure the local site is set up.
88   let site_view = SiteView::read_local(&pool)
89     .await
90     .expect("local site not set up");
91   let local_site = site_view.local_site;
92   let federation_enabled = local_site.federation_enabled;
93
94   if federation_enabled {
95     println!("federation enabled, host is {}", &settings.hostname);
96   }
97
98   check_private_instance_and_federation_enabled(&local_site)?;
99
100   // Set up the rate limiter
101   let rate_limit_config =
102     local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit);
103   let rate_limit_cell = RateLimitCell::new(rate_limit_config).await;
104
105   println!(
106     "Starting http server at {}:{}",
107     settings.bind, settings.port
108   );
109
110   let reqwest_client = Client::builder()
111     .user_agent(build_user_agent(&settings))
112     .timeout(REQWEST_TIMEOUT)
113     .build()?;
114
115   let retry_policy = ExponentialBackoff {
116     max_n_retries: 3,
117     max_retry_interval: REQWEST_TIMEOUT,
118     min_retry_interval: Duration::from_millis(100),
119     backoff_exponent: 2,
120   };
121
122   let client = ClientBuilder::new(reqwest_client.clone())
123     .with(TracingMiddleware::default())
124     .with(RetryTransientMiddleware::new_with_policy(retry_policy))
125     .build();
126
127   // Pictrs cannot use the retry middleware
128   let pictrs_client = ClientBuilder::new(reqwest_client.clone())
129     .with(TracingMiddleware::default())
130     .build();
131
132   let chat_server = Arc::new(ChatServer::startup());
133
134   // Create Http server with websocket support
135   let settings_bind = settings.clone();
136   HttpServer::new(move || {
137     let context = LemmyContext::create(
138       pool.clone(),
139       chat_server.clone(),
140       client.clone(),
141       settings.clone(),
142       secret.clone(),
143       rate_limit_cell.clone(),
144     );
145     App::new()
146       .wrap(middleware::Logger::default())
147       .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
148       .app_data(Data::new(context))
149       .app_data(Data::new(rate_limit_cell.clone()))
150       // The routes
151       .configure(|cfg| api_routes_http::config(cfg, rate_limit_cell))
152       .configure(|cfg| {
153         if federation_enabled {
154           lemmy_apub::http::routes::config(cfg);
155           webfinger::config(cfg);
156         }
157       })
158       .configure(feeds::config)
159       .configure(|cfg| images::config(cfg, pictrs_client.clone(), rate_limit_cell))
160       .configure(nodeinfo::config)
161   })
162   .bind((settings_bind.bind, settings_bind.port))?
163   .run()
164   .await?;
165
166   Ok(())
167 }