]> Untitled Git - lemmy.git/blob - src/lib.rs
Remove `actix_rt` & use standard tokio spawn (#3158)
[lemmy.git] / src / lib.rs
1 pub mod api_routes_http;
2 pub mod code_migrations;
3 pub mod root_span_builder;
4 pub mod scheduled_tasks;
5 #[cfg(feature = "console")]
6 pub mod telemetry;
7
8 use crate::{code_migrations::run_advanced_migrations, root_span_builder::QuieterRootSpanBuilder};
9 use activitypub_federation::config::{FederationConfig, FederationMiddleware};
10 use actix_cors::Cors;
11 use actix_web::{middleware, web::Data, App, HttpServer, Result};
12 use doku::json::{AutoComments, CommentsStyle, Formatting, ObjectsStyle};
13 use lemmy_api_common::{
14   context::LemmyContext,
15   lemmy_db_views::structs::SiteView,
16   request::build_user_agent,
17   utils::{
18     check_private_instance_and_federation_enabled,
19     local_site_rate_limit_to_rate_limit_config,
20   },
21 };
22 use lemmy_apub::{VerifyUrlData, FEDERATION_HTTP_FETCH_LIMIT};
23 use lemmy_db_schema::{
24   source::secret::Secret,
25   utils::{build_db_pool, get_database_url, run_migrations},
26 };
27 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
28 use lemmy_utils::{
29   error::LemmyError,
30   rate_limit::RateLimitCell,
31   settings::{structs::Settings, SETTINGS},
32 };
33 use reqwest::Client;
34 use reqwest_middleware::ClientBuilder;
35 use reqwest_tracing::TracingMiddleware;
36 use std::{env, thread, time::Duration};
37 use tracing::subscriber::set_global_default;
38 use tracing_actix_web::TracingLogger;
39 use tracing_error::ErrorLayer;
40 use tracing_log::LogTracer;
41 use tracing_subscriber::{filter::Targets, layer::SubscriberExt, Layer, Registry};
42 use url::Url;
43
44 /// Max timeout for http requests
45 pub(crate) const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
46
47 /// Placing the main function in lib.rs allows other crates to import it and embed Lemmy
48 pub async fn start_lemmy_server() -> Result<(), LemmyError> {
49   let args: Vec<String> = env::args().collect();
50   if args.get(1) == Some(&"--print-config-docs".to_string()) {
51     let fmt = Formatting {
52       auto_comments: AutoComments::none(),
53       comments_style: CommentsStyle {
54         separator: "#".to_owned(),
55       },
56       objects_style: ObjectsStyle {
57         surround_keys_with_quotes: false,
58         use_comma_as_separator: false,
59       },
60       ..Default::default()
61     };
62     println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
63     return Ok(());
64   }
65
66   let scheduled_tasks_enabled = args.get(1) != Some(&"--disable-scheduled-tasks".to_string());
67
68   let settings = SETTINGS.to_owned();
69
70   // Run the DB migrations
71   let db_url = get_database_url(Some(&settings));
72   run_migrations(&db_url);
73
74   // Set up the connection pool
75   let pool = build_db_pool(&settings).await?;
76
77   // Run the Code-required migrations
78   run_advanced_migrations(&pool, &settings).await?;
79
80   // Initialize the secrets
81   let secret = Secret::init(&pool)
82     .await
83     .expect("Couldn't initialize secrets.");
84
85   // Make sure the local site is set up.
86   let site_view = SiteView::read_local(&pool)
87     .await
88     .expect("local site not set up");
89   let local_site = site_view.local_site;
90   let federation_enabled = local_site.federation_enabled;
91
92   if federation_enabled {
93     println!("federation enabled, host is {}", &settings.hostname);
94   }
95
96   check_private_instance_and_federation_enabled(&local_site)?;
97
98   // Set up the rate limiter
99   let rate_limit_config =
100     local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit);
101   let rate_limit_cell = RateLimitCell::new(rate_limit_config).await;
102
103   println!(
104     "Starting http server at {}:{}",
105     settings.bind, settings.port
106   );
107
108   let user_agent = build_user_agent(&settings);
109   let reqwest_client = Client::builder()
110     .user_agent(user_agent.clone())
111     .timeout(REQWEST_TIMEOUT)
112     .connect_timeout(REQWEST_TIMEOUT)
113     .build()?;
114
115   let client = ClientBuilder::new(reqwest_client.clone())
116     .with(TracingMiddleware::default())
117     .build();
118
119   // Pictrs cannot use the retry middleware
120   let pictrs_client = ClientBuilder::new(reqwest_client.clone())
121     .with(TracingMiddleware::default())
122     .build();
123
124   let context = LemmyContext::create(
125     pool.clone(),
126     client.clone(),
127     secret.clone(),
128     rate_limit_cell.clone(),
129   );
130
131   if scheduled_tasks_enabled {
132     // Schedules various cleanup tasks for the DB
133     thread::spawn({
134       let context = context.clone();
135       move || {
136         scheduled_tasks::setup(db_url, user_agent, context)
137           .expect("Couldn't set up scheduled_tasks");
138       }
139     });
140   }
141
142   let settings_bind = settings.clone();
143
144   let federation_config = FederationConfig::builder()
145     .domain(settings.hostname.clone())
146     .app_data(context.clone())
147     .client(client.clone())
148     .http_fetch_limit(FEDERATION_HTTP_FETCH_LIMIT)
149     .worker_count(settings.worker_count)
150     .retry_count(settings.retry_count)
151     .debug(cfg!(debug_assertions))
152     .http_signature_compat(true)
153     .url_verifier(Box::new(VerifyUrlData(context.pool().clone())))
154     .build()
155     .await?;
156
157   // Create Http server with websocket support
158   HttpServer::new(move || {
159     let cors_config = if cfg!(debug_assertions) {
160       Cors::permissive()
161     } else {
162       let cors_origin = std::env::var("LEMMY_CORS_ORIGIN").unwrap_or("http://localhost".into());
163       Cors::default()
164         .allowed_origin(&cors_origin)
165         .allowed_origin(&settings.get_protocol_and_hostname())
166     };
167
168     App::new()
169       .wrap(middleware::Logger::new(
170         // This is the default log format save for the usage of %{r}a over %a to guarantee to record the client's (forwarded) IP and not the last peer address, since the latter is frequently just a reverse proxy
171         "%{r}a '%r' %s %b '%{Referer}i' '%{User-Agent}i' %T",
172       ))
173       .wrap(cors_config)
174       .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
175       .app_data(Data::new(context.clone()))
176       .app_data(Data::new(rate_limit_cell.clone()))
177       .wrap(FederationMiddleware::new(federation_config.clone()))
178       // The routes
179       .configure(|cfg| api_routes_http::config(cfg, rate_limit_cell))
180       .configure(|cfg| {
181         if federation_enabled {
182           lemmy_apub::http::routes::config(cfg);
183           webfinger::config(cfg);
184         }
185       })
186       .configure(feeds::config)
187       .configure(|cfg| images::config(cfg, pictrs_client.clone(), rate_limit_cell))
188       .configure(nodeinfo::config)
189   })
190   .bind((settings_bind.bind, settings_bind.port))?
191   .run()
192   .await?;
193
194   Ok(())
195 }
196
197 pub fn init_logging(opentelemetry_url: &Option<Url>) -> Result<(), LemmyError> {
198   LogTracer::init()?;
199
200   let log_description = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".into());
201
202   let targets = log_description
203     .trim()
204     .trim_matches('"')
205     .parse::<Targets>()?;
206
207   let format_layer = tracing_subscriber::fmt::layer().with_filter(targets.clone());
208
209   let subscriber = Registry::default()
210     .with(format_layer)
211     .with(ErrorLayer::default());
212
213   if let Some(_url) = opentelemetry_url {
214     #[cfg(feature = "console")]
215     telemetry::init_tracing(_url.as_ref(), subscriber, targets)?;
216     #[cfg(not(feature = "console"))]
217     tracing::error!("Feature `console` must be enabled for opentelemetry tracing");
218   } else {
219     set_global_default(subscriber)?;
220   }
221
222   Ok(())
223 }