2 extern crate diesel_migrations;
5 use actix_web::{web::Data, *};
6 use diesel_migrations::EmbeddedMigrations;
7 use doku::json::{AutoComments, Formatting};
8 use lemmy_api::match_websocket_operation;
9 use lemmy_api_common::{
10 lemmy_db_views::structs::SiteView,
11 request::build_user_agent,
13 check_private_instance_and_federation_enabled,
14 local_site_rate_limit_to_rate_limit_config,
17 use lemmy_api_crud::match_websocket_operation_crud;
18 use lemmy_db_schema::{
19 source::secret::Secret,
20 utils::{build_db_pool, get_database_url, run_migrations},
22 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
25 code_migrations::run_advanced_migrations,
27 root_span_builder::QuieterRootSpanBuilder,
32 rate_limit::{rate_limiter::RateLimiter, RateLimit},
33 settings::{structs::Settings, SETTINGS},
35 use lemmy_websocket::{chat_server::ChatServer, LemmyContext};
37 use reqwest_middleware::ClientBuilder;
38 use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
39 use reqwest_tracing::TracingMiddleware;
46 use tracing_actix_web::TracingLogger;
48 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
50 /// Max timeout for http requests
51 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
54 async fn main() -> Result<(), LemmyError> {
55 let args: Vec<String> = env::args().collect();
56 if args.len() == 2 && args[1] == "--print-config-docs" {
57 let fmt = Formatting {
58 auto_comments: AutoComments::none(),
61 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
65 let settings = SETTINGS.to_owned();
67 init_logging(&settings.opentelemetry_url)?;
69 // Set up the bb8 connection pool
70 let db_url = get_database_url(Some(&settings));
71 run_migrations(&db_url);
73 // Run the migrations from code
74 let pool = build_db_pool(&settings).await?;
75 run_advanced_migrations(&pool, &settings).await?;
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");
82 // Initialize the secrets
83 let secret = Secret::init(&pool)
85 .expect("Couldn't initialize secrets.");
87 // Make sure the local site is set up.
88 let site_view = SiteView::read_local(&pool)
90 .expect("local site not set up");
91 let local_site = site_view.local_site;
92 let federation_enabled = local_site.federation_enabled;
94 if federation_enabled {
95 println!("federation enabled, host is {}", &settings.hostname);
98 check_private_instance_and_federation_enabled(&local_site)?;
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);
104 // TODO this isn't live-updating
105 // https://github.com/LemmyNet/lemmy/issues/2508
106 let rate_limiter = RateLimit {
107 rate_limiter: Arc::new(Mutex::new(RateLimiter::default())),
112 "Starting http server at {}:{}",
113 settings.bind, settings.port
116 let reqwest_client = Client::builder()
117 .user_agent(build_user_agent(&settings))
118 .timeout(REQWEST_TIMEOUT)
121 let retry_policy = ExponentialBackoff {
123 max_retry_interval: REQWEST_TIMEOUT,
124 min_retry_interval: Duration::from_millis(100),
128 let client = ClientBuilder::new(reqwest_client.clone())
129 .with(TracingMiddleware::default())
130 .with(RetryTransientMiddleware::new_with_policy(retry_policy))
133 // Pictrs cannot use the retry middleware
134 let pictrs_client = ClientBuilder::new(reqwest_client.clone())
135 .with(TracingMiddleware::default())
138 let chat_server = ChatServer::startup(
140 rate_limiter.clone(),
141 |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
142 |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
149 // Create Http server with websocket support
150 let settings_bind = settings.clone();
151 HttpServer::new(move || {
152 let context = LemmyContext::create(
154 chat_server.to_owned(),
159 let rate_limiter = rate_limiter.clone();
161 .wrap(actix_web::middleware::Logger::default())
162 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
163 .app_data(Data::new(context))
164 .app_data(Data::new(rate_limiter.clone()))
166 .configure(|cfg| api_routes::config(cfg, &rate_limiter))
168 if federation_enabled {
169 lemmy_apub::http::routes::config(cfg);
170 webfinger::config(cfg);
173 .configure(feeds::config)
174 .configure(|cfg| images::config(cfg, pictrs_client.clone(), &rate_limiter))
175 .configure(nodeinfo::config)
177 .bind((settings_bind.bind, settings_bind.port))?