2 extern crate diesel_migrations;
5 use actix_web::{middleware, web::Data, App, HttpServer, Result};
6 use diesel_migrations::EmbeddedMigrations;
7 use doku::json::{AutoComments, CommentsStyle, Formatting, ObjectsStyle};
8 use lemmy_api::match_websocket_operation;
9 use lemmy_api_common::{
10 lemmy_db_views::structs::SiteView,
11 request::build_user_agent,
13 check_private_instance_and_federation_enabled,
14 local_site_rate_limit_to_rate_limit_config,
17 use lemmy_api_crud::match_websocket_operation_crud;
18 use lemmy_db_schema::{
19 source::secret::Secret,
20 utils::{build_db_pool, get_database_url, run_migrations},
22 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
25 code_migrations::run_advanced_migrations,
27 root_span_builder::QuieterRootSpanBuilder,
32 rate_limit::RateLimitCell,
33 settings::{structs::Settings, SETTINGS},
35 use lemmy_websocket::{chat_server::ChatServer, LemmyContext};
37 use reqwest_middleware::ClientBuilder;
38 use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
39 use reqwest_tracing::TracingMiddleware;
40 use std::{env, thread, time::Duration};
41 use tracing_actix_web::TracingLogger;
43 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
45 /// Max timeout for http requests
46 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
49 async fn main() -> Result<(), LemmyError> {
50 let args: Vec<String> = env::args().collect();
51 if args.len() == 2 && args[1] == "--print-config-docs" {
52 let fmt = Formatting {
53 auto_comments: AutoComments::none(),
54 comments_style: CommentsStyle {
55 separator: "#".to_owned(),
57 objects_style: ObjectsStyle {
58 surround_keys_with_quotes: false,
59 use_comma_as_separator: false,
63 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
67 let settings = SETTINGS.to_owned();
69 init_logging(&settings.opentelemetry_url)?;
71 // Set up the bb8 connection pool
72 let db_url = get_database_url(Some(&settings));
73 run_migrations(&db_url);
75 // Run the migrations from code
76 let pool = build_db_pool(&settings).await?;
77 run_advanced_migrations(&pool, &settings).await?;
79 // Schedules various cleanup tasks for the DB
80 thread::spawn(move || {
81 scheduled_tasks::setup(db_url).expect("Couldn't set up scheduled_tasks");
84 // Initialize the secrets
85 let secret = Secret::init(&pool)
87 .expect("Couldn't initialize secrets.");
89 // Make sure the local site is set up.
90 let site_view = SiteView::read_local(&pool)
92 .expect("local site not set up");
93 let local_site = site_view.local_site;
94 let federation_enabled = local_site.federation_enabled;
96 if federation_enabled {
97 println!("federation enabled, host is {}", &settings.hostname);
100 check_private_instance_and_federation_enabled(&local_site)?;
102 // Set up the rate limiter
103 let rate_limit_config =
104 local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit);
105 let rate_limit_cell = RateLimitCell::new(rate_limit_config).await;
108 "Starting http server at {}:{}",
109 settings.bind, settings.port
112 let reqwest_client = Client::builder()
113 .user_agent(build_user_agent(&settings))
114 .timeout(REQWEST_TIMEOUT)
117 let retry_policy = ExponentialBackoff {
119 max_retry_interval: REQWEST_TIMEOUT,
120 min_retry_interval: Duration::from_millis(100),
124 let client = ClientBuilder::new(reqwest_client.clone())
125 .with(TracingMiddleware::default())
126 .with(RetryTransientMiddleware::new_with_policy(retry_policy))
129 // Pictrs cannot use the retry middleware
130 let pictrs_client = ClientBuilder::new(reqwest_client.clone())
131 .with(TracingMiddleware::default())
134 let chat_server = ChatServer::startup(
136 |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
137 |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
141 rate_limit_cell.clone(),
145 // Create Http server with websocket support
146 let settings_bind = settings.clone();
147 HttpServer::new(move || {
148 let context = LemmyContext::create(
154 rate_limit_cell.clone(),
157 .wrap(middleware::Logger::default())
158 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
159 .app_data(Data::new(context))
160 .app_data(Data::new(rate_limit_cell.clone()))
162 .configure(|cfg| api_routes::config(cfg, rate_limit_cell))
164 if federation_enabled {
165 lemmy_apub::http::routes::config(cfg);
166 webfinger::config(cfg);
169 .configure(feeds::config)
170 .configure(|cfg| images::config(cfg, pictrs_client.clone(), rate_limit_cell))
171 .configure(nodeinfo::config)
173 .bind((settings_bind.bind, settings_bind.port))?