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_apub_lib::activity_queue::create_activity_queue;
18 use lemmy_db_schema::{source::secret::Secret, utils::get_database_url_from_env};
19 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
22 code_migrations::run_advanced_migrations,
24 root_span_builder::QuieterRootSpanBuilder,
28 rate_limit::{rate_limiter::RateLimiter, RateLimit},
29 settings::structs::Settings,
33 use lemmy_websocket::{chat_server::ChatServer, LemmyContext};
34 use parking_lot::Mutex;
36 use reqwest_middleware::ClientBuilder;
37 use reqwest_tracing::TracingMiddleware;
38 use std::{env, sync::Arc, thread};
39 use tracing_actix_web::TracingLogger;
44 async fn main() -> Result<(), LemmyError> {
45 let args: Vec<String> = env::args().collect();
46 if args.len() == 2 && args[1] == "--print-config-docs" {
47 let fmt = Formatting {
48 auto_comments: AutoComments::none(),
51 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
55 let settings = Settings::init().expect("Couldn't initialize settings.");
57 init_logging(settings.opentelemetry_url.as_deref())?;
59 // Set up the r2d2 connection pool
60 let db_url = match get_database_url_from_env() {
62 Err(_) => settings.get_database_url(),
64 let manager = ConnectionManager::<PgConnection>::new(&db_url);
65 let pool = Pool::builder()
66 .max_size(settings.database.pool_size)
68 .unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
70 // Run the migrations from code
71 let protocol_and_hostname = settings.get_protocol_and_hostname();
72 blocking(&pool, move |conn| {
73 embedded_migrations::run(conn)?;
74 run_advanced_migrations(conn, &protocol_and_hostname)?;
75 Ok(()) as Result<(), LemmyError>
79 // Schedules various cleanup tasks for the DB
80 let pool2 = pool.clone();
81 thread::spawn(move || {
82 scheduled_tasks::setup(pool2).expect("Couldn't set up scheduled_tasks");
85 // Set up the rate limiter
86 let rate_limiter = RateLimit {
87 rate_limiter: Arc::new(Mutex::new(RateLimiter::default())),
88 rate_limit_config: settings.rate_limit.to_owned().unwrap_or_default(),
91 // Initialize the secrets
92 let conn = pool.get()?;
93 let secret = Secret::init(&conn).expect("Couldn't initialize secrets.");
96 "Starting http server at {}:{}",
97 settings.bind, settings.port
100 let client = Client::builder()
101 .user_agent(build_user_agent(&settings))
102 .timeout(REQWEST_TIMEOUT)
105 let client = ClientBuilder::new(client).with(TracingMiddleware).build();
107 let queue_manager = create_activity_queue(client.clone(), settings.federation.worker_count);
109 let activity_queue = queue_manager.queue_handle().clone();
111 check_private_instance_and_federation_enabled(&pool, &settings).await?;
113 let chat_server = ChatServer::startup(
115 rate_limiter.clone(),
116 |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
117 |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
119 activity_queue.clone(),
125 // Create Http server with websocket support
126 let settings_bind = settings.clone();
127 HttpServer::new(move || {
128 let context = LemmyContext::create(
130 chat_server.to_owned(),
132 activity_queue.to_owned(),
136 let rate_limiter = rate_limiter.clone();
138 .wrap(actix_web::middleware::Logger::default())
139 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
140 .app_data(Data::new(context))
141 .app_data(Data::new(rate_limiter.clone()))
143 .configure(|cfg| api_routes::config(cfg, &rate_limiter))
144 .configure(|cfg| lemmy_apub::http::routes::config(cfg, &settings))
145 .configure(feeds::config)
146 .configure(|cfg| images::config(cfg, client.clone(), &rate_limiter))
147 .configure(nodeinfo::config)
148 .configure(|cfg| webfinger::config(cfg, &settings))
150 .bind((settings_bind.bind, settings_bind.port))?