]> Untitled Git - lemmy.git/blob - src/main.rs
Add tracing (#1942)
[lemmy.git] / src / main.rs
1 #[macro_use]
2 extern crate diesel_migrations;
3
4 use actix::prelude::*;
5 use actix_web::{web::Data, *};
6 use diesel::{
7   r2d2::{ConnectionManager, Pool},
8   PgConnection,
9 };
10 use doku::json::{AutoComments, Formatting};
11 use lemmy_api::match_websocket_operation;
12 use lemmy_api_common::blocking;
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};
17 use lemmy_server::{
18   api_routes,
19   code_migrations::run_advanced_migrations,
20   init_tracing,
21   scheduled_tasks,
22 };
23 use lemmy_utils::{
24   rate_limit::{rate_limiter::RateLimiter, RateLimit},
25   request::build_user_agent,
26   settings::structs::Settings,
27   LemmyError,
28 };
29 use lemmy_websocket::{chat_server::ChatServer, LemmyContext};
30 use reqwest::Client;
31 use std::{env, sync::Arc, thread};
32 use tokio::sync::Mutex;
33 use tracing_actix_web::TracingLogger;
34
35 embed_migrations!();
36
37 #[actix_web::main]
38 async fn main() -> Result<(), LemmyError> {
39   let args: Vec<String> = env::args().collect();
40   if args.len() == 2 && args[1] == "--print-config-docs" {
41     let fmt = Formatting {
42       auto_comments: AutoComments::none(),
43       ..Default::default()
44     };
45     println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
46     return Ok(());
47   }
48
49   init_tracing()?;
50
51   let settings = Settings::init().expect("Couldn't initialize settings.");
52
53   // Set up the r2d2 connection pool
54   let db_url = match get_database_url_from_env() {
55     Ok(url) => url,
56     Err(_) => settings.get_database_url(),
57   };
58   let manager = ConnectionManager::<PgConnection>::new(&db_url);
59   let pool = Pool::builder()
60     .max_size(settings.database.pool_size)
61     .build(manager)
62     .unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
63
64   // Run the migrations from code
65   let protocol_and_hostname = settings.get_protocol_and_hostname();
66   blocking(&pool, move |conn| {
67     embedded_migrations::run(conn)?;
68     run_advanced_migrations(conn, &protocol_and_hostname)?;
69     Ok(()) as Result<(), LemmyError>
70   })
71   .await??;
72
73   let pool2 = pool.clone();
74   thread::spawn(move || {
75     scheduled_tasks::setup(pool2).expect("Couldn't set up scheduled_tasks");
76   });
77
78   // Set up the rate limiter
79   let rate_limiter = RateLimit {
80     rate_limiter: Arc::new(Mutex::new(RateLimiter::default())),
81     rate_limit_config: settings.rate_limit.to_owned().unwrap_or_default(),
82   };
83
84   // Initialize the secrets
85   let conn = pool.get()?;
86   let secret = Secret::init(&conn).expect("Couldn't initialize secrets.");
87
88   println!(
89     "Starting http server at {}:{}",
90     settings.bind, settings.port
91   );
92
93   let client = Client::builder()
94     .user_agent(build_user_agent(&settings))
95     .build()?;
96
97   let activity_queue = create_activity_queue();
98
99   let chat_server = ChatServer::startup(
100     pool.clone(),
101     rate_limiter.clone(),
102     |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
103     |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
104     client.clone(),
105     activity_queue.clone(),
106     settings.clone(),
107     secret.clone(),
108   )
109   .start();
110
111   // Create Http server with websocket support
112   let settings_bind = settings.clone();
113   HttpServer::new(move || {
114     let context = LemmyContext::create(
115       pool.clone(),
116       chat_server.to_owned(),
117       client.clone(),
118       activity_queue.to_owned(),
119       settings.to_owned(),
120       secret.to_owned(),
121     );
122     let rate_limiter = rate_limiter.clone();
123     App::new()
124       .wrap(TracingLogger::default())
125       .app_data(Data::new(context))
126       // The routes
127       .configure(|cfg| api_routes::config(cfg, &rate_limiter))
128       .configure(|cfg| lemmy_apub::http::routes::config(cfg, &settings))
129       .configure(feeds::config)
130       .configure(|cfg| images::config(cfg, &rate_limiter))
131       .configure(nodeinfo::config)
132       .configure(|cfg| webfinger::config(cfg, &settings))
133   })
134   .bind((settings_bind.bind, settings_bind.port))?
135   .run()
136   .await?;
137
138   Ok(())
139 }