2 extern crate diesel_migrations;
4 use crate::diesel_migrations::MigrationHarness;
6 use actix_web::{web::Data, *};
8 r2d2::{ConnectionManager, Pool},
11 use diesel_migrations::EmbeddedMigrations;
12 use doku::json::{AutoComments, Formatting};
13 use lemmy_api::match_websocket_operation;
14 use lemmy_api_common::{
15 lemmy_db_views::structs::SiteView,
16 request::build_user_agent,
19 check_private_instance_and_federation_enabled,
20 local_site_rate_limit_to_rate_limit_config,
23 use lemmy_api_crud::match_websocket_operation_crud;
24 use lemmy_db_schema::{source::secret::Secret, utils::get_database_url_from_env};
25 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
28 code_migrations::run_advanced_migrations,
30 root_span_builder::QuieterRootSpanBuilder,
35 rate_limit::{rate_limiter::RateLimiter, RateLimit},
36 settings::{structs::Settings, SETTINGS},
38 use lemmy_websocket::{chat_server::ChatServer, LemmyContext};
40 use reqwest_middleware::ClientBuilder;
41 use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
42 use reqwest_tracing::TracingMiddleware;
49 use tracing_actix_web::TracingLogger;
51 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
53 /// Max timeout for http requests
54 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
57 async fn main() -> Result<(), LemmyError> {
58 let args: Vec<String> = env::args().collect();
59 if args.len() == 2 && args[1] == "--print-config-docs" {
60 let fmt = Formatting {
61 auto_comments: AutoComments::none(),
64 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
68 let settings = SETTINGS.to_owned();
70 init_logging(&settings.opentelemetry_url)?;
72 // Set up the r2d2 connection pool
73 let db_url = match get_database_url_from_env() {
75 Err(_) => settings.get_database_url(),
77 let manager = ConnectionManager::<PgConnection>::new(&db_url);
78 let pool = Pool::builder()
79 .max_size(settings.database.pool_size)
83 // Run the migrations from code
84 let settings_cloned = settings.to_owned();
85 blocking(&pool, move |conn| {
87 .run_pending_migrations(MIGRATIONS)
88 .map_err(|_| LemmyError::from_message("Couldn't run migrations"))?;
89 run_advanced_migrations(conn, &settings_cloned)?;
90 Ok(()) as Result<(), LemmyError>
94 // Schedules various cleanup tasks for the DB
95 let pool2 = pool.clone();
96 thread::spawn(move || {
97 scheduled_tasks::setup(pool2).expect("Couldn't set up scheduled_tasks");
100 // Initialize the secrets
101 let conn = &mut pool.get()?;
102 let secret = Secret::init(conn).expect("Couldn't initialize secrets.");
104 // Make sure the local site is set up.
105 let site_view = SiteView::read_local(conn).expect("local site not set up");
106 let local_site = site_view.local_site;
107 let federation_enabled = local_site.federation_enabled;
109 if federation_enabled {
110 println!("federation enabled, host is {}", &settings.hostname);
113 check_private_instance_and_federation_enabled(&local_site)?;
115 // Set up the rate limiter
116 let rate_limit_config =
117 local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit);
119 // TODO this isn't live-updating
120 // https://github.com/LemmyNet/lemmy/issues/2508
121 let rate_limiter = RateLimit {
122 rate_limiter: Arc::new(Mutex::new(RateLimiter::default())),
127 "Starting http server at {}:{}",
128 settings.bind, settings.port
131 let reqwest_client = Client::builder()
132 .user_agent(build_user_agent(&settings))
133 .timeout(REQWEST_TIMEOUT)
136 let retry_policy = ExponentialBackoff {
138 max_retry_interval: REQWEST_TIMEOUT,
139 min_retry_interval: Duration::from_millis(100),
143 let client = ClientBuilder::new(reqwest_client.clone())
144 .with(TracingMiddleware::default())
145 .with(RetryTransientMiddleware::new_with_policy(retry_policy))
148 // Pictrs cannot use the retry middleware
149 let pictrs_client = ClientBuilder::new(reqwest_client.clone())
150 .with(TracingMiddleware::default())
153 let chat_server = ChatServer::startup(
155 rate_limiter.clone(),
156 |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
157 |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
164 // Create Http server with websocket support
165 let settings_bind = settings.clone();
166 HttpServer::new(move || {
167 let context = LemmyContext::create(
169 chat_server.to_owned(),
174 let rate_limiter = rate_limiter.clone();
176 .wrap(actix_web::middleware::Logger::default())
177 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
178 .app_data(Data::new(context))
179 .app_data(Data::new(rate_limiter.clone()))
181 .configure(|cfg| api_routes::config(cfg, &rate_limiter))
183 if federation_enabled {
184 lemmy_apub::http::routes::config(cfg);
185 webfinger::config(cfg);
188 .configure(feeds::config)
189 .configure(|cfg| images::config(cfg, pictrs_client.clone(), &rate_limiter))
190 .configure(nodeinfo::config)
192 .bind((settings_bind.bind, settings_bind.port))?