2 extern crate diesel_migrations;
5 use actix_web::{web::Data, *};
7 r2d2::{ConnectionManager, Pool},
10 use doku::json::{AutoComments, Formatting};
11 use lemmy_api::match_websocket_operation;
12 use lemmy_api_common::{
13 request::build_user_agent,
14 utils::{blocking, check_private_instance_and_federation_enabled},
16 use lemmy_api_crud::match_websocket_operation_crud;
17 use lemmy_db_schema::{source::secret::Secret, utils::get_database_url_from_env};
18 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
21 code_migrations::run_advanced_migrations,
23 root_span_builder::QuieterRootSpanBuilder,
28 rate_limit::{rate_limiter::RateLimiter, RateLimit},
29 settings::{structs::Settings, SETTINGS},
31 use lemmy_websocket::{chat_server::ChatServer, LemmyContext};
33 use reqwest_middleware::ClientBuilder;
34 use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
35 use reqwest_tracing::TracingMiddleware;
42 use tracing_actix_web::TracingLogger;
46 /// Max timeout for http requests
47 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
50 async fn main() -> Result<(), LemmyError> {
51 let args: Vec<String> = env::args().collect();
52 if args.len() == 2 && args[1] == "--print-config-docs" {
53 let fmt = Formatting {
54 auto_comments: AutoComments::none(),
57 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
61 let settings = SETTINGS.to_owned();
63 init_logging(&settings.opentelemetry_url)?;
65 // Set up the r2d2 connection pool
66 let db_url = match get_database_url_from_env() {
68 Err(_) => settings.get_database_url(),
70 let manager = ConnectionManager::<PgConnection>::new(&db_url);
71 let pool = Pool::builder()
72 .max_size(settings.database.pool_size)
74 .unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
76 // Run the migrations from code
77 let protocol_and_hostname = settings.get_protocol_and_hostname();
78 blocking(&pool, move |conn| {
79 embedded_migrations::run(conn)?;
80 run_advanced_migrations(conn, &protocol_and_hostname)?;
81 Ok(()) as Result<(), LemmyError>
85 // Schedules various cleanup tasks for the DB
86 let pool2 = pool.clone();
87 thread::spawn(move || {
88 scheduled_tasks::setup(pool2).expect("Couldn't set up scheduled_tasks");
91 // Set up the rate limiter
92 let rate_limiter = RateLimit {
93 rate_limiter: Arc::new(Mutex::new(RateLimiter::default())),
94 rate_limit_config: settings.rate_limit.to_owned().unwrap_or_default(),
97 // Initialize the secrets
98 let conn = pool.get()?;
99 let secret = Secret::init(&conn).expect("Couldn't initialize secrets.");
102 "Starting http server at {}:{}",
103 settings.bind, settings.port
106 let reqwest_client = Client::builder()
107 .user_agent(build_user_agent(&settings))
108 .timeout(REQWEST_TIMEOUT)
111 let retry_policy = ExponentialBackoff {
113 max_retry_interval: REQWEST_TIMEOUT,
114 min_retry_interval: Duration::from_millis(100),
118 let client = ClientBuilder::new(reqwest_client.clone())
119 .with(TracingMiddleware)
120 .with(RetryTransientMiddleware::new_with_policy(retry_policy))
123 // Pictrs cannot use the retry middleware
124 let pictrs_client = ClientBuilder::new(reqwest_client.clone())
125 .with(TracingMiddleware)
128 check_private_instance_and_federation_enabled(&pool, &settings).await?;
130 let chat_server = ChatServer::startup(
132 rate_limiter.clone(),
133 |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
134 |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
141 // Create Http server with websocket support
142 let settings_bind = settings.clone();
143 HttpServer::new(move || {
144 let context = LemmyContext::create(
146 chat_server.to_owned(),
151 let rate_limiter = rate_limiter.clone();
153 .wrap(actix_web::middleware::Logger::default())
154 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
155 .app_data(Data::new(context))
156 .app_data(Data::new(rate_limiter.clone()))
158 .configure(|cfg| api_routes::config(cfg, &rate_limiter))
159 .configure(|cfg| lemmy_apub::http::routes::config(cfg, &settings))
160 .configure(feeds::config)
161 .configure(|cfg| images::config(cfg, pictrs_client.clone(), &rate_limiter))
162 .configure(nodeinfo::config)
163 .configure(|cfg| webfinger::config(cfg, &settings))
165 .bind((settings_bind.bind, settings_bind.port))?