]> Untitled Git - lemmy.git/blob - src/lib.rs
Update apub library to 0.4.4 (#3258)
[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 federation_config = FederationConfig::builder()
143     .domain(settings.hostname.clone())
144     .app_data(context.clone())
145     .client(client.clone())
146     .http_fetch_limit(FEDERATION_HTTP_FETCH_LIMIT)
147     .worker_count(local_site.federation_worker_count as usize)
148     .debug(cfg!(debug_assertions))
149     .http_signature_compat(true)
150     .url_verifier(Box::new(VerifyUrlData(context.pool().clone())))
151     .build()
152     .await
153     .expect("configure federation");
154
155   // Create Http server with websocket support
156   let settings_bind = settings.clone();
157   HttpServer::new(move || {
158     let context = context.clone();
159
160     let cors_config = if cfg!(debug_assertions) {
161       Cors::permissive()
162     } else {
163       let cors_origin = std::env::var("LEMMY_CORS_ORIGIN").unwrap_or("http://localhost".into());
164       Cors::default()
165         .allowed_origin(&cors_origin)
166         .allowed_origin(&settings.get_protocol_and_hostname())
167     };
168
169     App::new()
170       .wrap(middleware::Logger::new(
171         // 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
172         "%{r}a '%r' %s %b '%{Referer}i' '%{User-Agent}i' %T",
173       ))
174       .wrap(cors_config)
175       .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
176       .app_data(Data::new(context))
177       .app_data(Data::new(rate_limit_cell.clone()))
178       .wrap(FederationMiddleware::new(federation_config.clone()))
179       // The routes
180       .configure(|cfg| api_routes_http::config(cfg, rate_limit_cell))
181       .configure(|cfg| {
182         if federation_enabled {
183           lemmy_apub::http::routes::config(cfg);
184           webfinger::config(cfg);
185         }
186       })
187       .configure(feeds::config)
188       .configure(|cfg| images::config(cfg, pictrs_client.clone(), rate_limit_cell))
189       .configure(nodeinfo::config)
190   })
191   .bind((settings_bind.bind, settings_bind.port))?
192   .run()
193   .await?;
194
195   Ok(())
196 }
197
198 pub fn init_logging(opentelemetry_url: &Option<Url>) -> Result<(), LemmyError> {
199   LogTracer::init()?;
200
201   let log_description = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".into());
202
203   let targets = log_description
204     .trim()
205     .trim_matches('"')
206     .parse::<Targets>()?;
207
208   let format_layer = tracing_subscriber::fmt::layer().with_filter(targets.clone());
209
210   let subscriber = Registry::default()
211     .with(format_layer)
212     .with(ErrorLayer::default());
213
214   if let Some(_url) = opentelemetry_url {
215     #[cfg(feature = "console")]
216     telemetry::init_tracing(_url.as_ref(), subscriber, targets)?;
217     #[cfg(not(feature = "console"))]
218     tracing::error!("Feature `console` must be enabled for opentelemetry tracing");
219   } else {
220     set_global_default(subscriber)?;
221   }
222
223   Ok(())
224 }