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::{blocking, check_private_instance_and_federation_enabled};
13 use lemmy_api_crud::match_websocket_operation_crud;
14 use lemmy_apub_lib::activity_queue::create_activity_queue;
15 use lemmy_db_schema::{get_database_url_from_env, source::secret::Secret};
16 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
19 code_migrations::run_advanced_migrations,
21 root_span_builder::QuieterRootSpanBuilder,
25 rate_limit::{rate_limiter::RateLimiter, RateLimit},
26 request::build_user_agent,
27 settings::structs::Settings,
31 use lemmy_websocket::{chat_server::ChatServer, LemmyContext};
32 use parking_lot::Mutex;
34 use reqwest_middleware::ClientBuilder;
35 use reqwest_tracing::TracingMiddleware;
36 use std::{env, sync::Arc, thread};
37 use tracing_actix_web::TracingLogger;
42 async fn main() -> Result<(), LemmyError> {
43 let args: Vec<String> = env::args().collect();
44 if args.len() == 2 && args[1] == "--print-config-docs" {
45 let fmt = Formatting {
46 auto_comments: AutoComments::none(),
49 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
53 let settings = Settings::init().expect("Couldn't initialize settings.");
55 init_tracing(settings.opentelemetry_url.as_deref())?;
57 // Set up the r2d2 connection pool
58 let db_url = match get_database_url_from_env() {
60 Err(_) => settings.get_database_url(),
62 let manager = ConnectionManager::<PgConnection>::new(&db_url);
63 let pool = Pool::builder()
64 .max_size(settings.database.pool_size)
66 .unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
68 // Run the migrations from code
69 let protocol_and_hostname = settings.get_protocol_and_hostname();
70 blocking(&pool, move |conn| {
71 embedded_migrations::run(conn)?;
72 run_advanced_migrations(conn, &protocol_and_hostname)?;
73 Ok(()) as Result<(), LemmyError>
77 // Schedules various cleanup tasks for the DB
78 let pool2 = pool.clone();
79 thread::spawn(move || {
80 scheduled_tasks::setup(pool2).expect("Couldn't set up scheduled_tasks");
83 // Set up the rate limiter
84 let rate_limiter = RateLimit {
85 rate_limiter: Arc::new(Mutex::new(RateLimiter::default())),
86 rate_limit_config: settings.rate_limit.to_owned().unwrap_or_default(),
89 // Initialize the secrets
90 let conn = pool.get()?;
91 let secret = Secret::init(&conn).expect("Couldn't initialize secrets.");
94 "Starting http server at {}:{}",
95 settings.bind, settings.port
98 let client = Client::builder()
99 .user_agent(build_user_agent(&settings))
100 .timeout(REQWEST_TIMEOUT)
103 let client = ClientBuilder::new(client).with(TracingMiddleware).build();
105 let queue_manager = create_activity_queue(client.clone(), settings.federation.worker_count);
107 let activity_queue = queue_manager.queue_handle().clone();
109 check_private_instance_and_federation_enabled(&pool, &settings).await?;
111 let chat_server = ChatServer::startup(
113 rate_limiter.clone(),
114 |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
115 |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
117 activity_queue.clone(),
123 // Create Http server with websocket support
124 let settings_bind = settings.clone();
125 HttpServer::new(move || {
126 let context = LemmyContext::create(
128 chat_server.to_owned(),
130 activity_queue.to_owned(),
134 let rate_limiter = rate_limiter.clone();
136 .wrap(actix_web::middleware::Logger::default())
137 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
138 .app_data(Data::new(context))
139 .app_data(Data::new(rate_limiter.clone()))
141 .configure(|cfg| api_routes::config(cfg, &rate_limiter))
142 .configure(|cfg| lemmy_apub::http::routes::config(cfg, &settings))
143 .configure(feeds::config)
144 .configure(|cfg| images::config(cfg, client.clone(), &rate_limiter))
145 .configure(nodeinfo::config)
146 .configure(|cfg| webfinger::config(cfg, &settings))
148 .bind((settings_bind.bind, settings_bind.port))?