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,
16 websocket::chat_server::ChatServer,
19 use lemmy_api_crud::match_websocket_operation_crud;
20 use lemmy_db_schema::{
21 source::secret::Secret,
22 utils::{build_db_pool, get_database_url, run_migrations},
24 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
27 code_migrations::run_advanced_migrations,
29 root_span_builder::QuieterRootSpanBuilder,
34 rate_limit::RateLimitCell,
35 settings::{structs::Settings, SETTINGS},
38 use reqwest_middleware::ClientBuilder;
39 use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
40 use reqwest_tracing::TracingMiddleware;
41 use std::{env, thread, time::Duration};
42 use tracing_actix_web::TracingLogger;
44 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
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(),
55 comments_style: CommentsStyle {
56 separator: "#".to_owned(),
58 objects_style: ObjectsStyle {
59 surround_keys_with_quotes: false,
60 use_comma_as_separator: false,
64 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
68 let settings = SETTINGS.to_owned();
70 init_logging(&settings.opentelemetry_url)?;
72 // Set up the bb8 connection pool
73 let db_url = get_database_url(Some(&settings));
74 run_migrations(&db_url);
76 // Run the migrations from code
77 let pool = build_db_pool(&settings).await?;
78 run_advanced_migrations(&pool, &settings).await?;
80 // Schedules various cleanup tasks for the DB
81 thread::spawn(move || {
82 scheduled_tasks::setup(db_url).expect("Couldn't set up scheduled_tasks");
85 // Initialize the secrets
86 let secret = Secret::init(&pool)
88 .expect("Couldn't initialize secrets.");
90 // Make sure the local site is set up.
91 let site_view = SiteView::read_local(&pool)
93 .expect("local site not set up");
94 let local_site = site_view.local_site;
95 let federation_enabled = local_site.federation_enabled;
97 if federation_enabled {
98 println!("federation enabled, host is {}", &settings.hostname);
101 check_private_instance_and_federation_enabled(&local_site)?;
103 // Set up the rate limiter
104 let rate_limit_config =
105 local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit);
106 let rate_limit_cell = RateLimitCell::new(rate_limit_config).await;
109 "Starting http server at {}:{}",
110 settings.bind, settings.port
113 let reqwest_client = Client::builder()
114 .user_agent(build_user_agent(&settings))
115 .timeout(REQWEST_TIMEOUT)
118 let retry_policy = ExponentialBackoff {
120 max_retry_interval: REQWEST_TIMEOUT,
121 min_retry_interval: Duration::from_millis(100),
125 let client = ClientBuilder::new(reqwest_client.clone())
126 .with(TracingMiddleware::default())
127 .with(RetryTransientMiddleware::new_with_policy(retry_policy))
130 // Pictrs cannot use the retry middleware
131 let pictrs_client = ClientBuilder::new(reqwest_client.clone())
132 .with(TracingMiddleware::default())
135 let chat_server = ChatServer::startup(
137 |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
138 |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
142 rate_limit_cell.clone(),
146 // Create Http server with websocket support
147 let settings_bind = settings.clone();
148 HttpServer::new(move || {
149 let context = LemmyContext::create(
155 rate_limit_cell.clone(),
158 .wrap(middleware::Logger::default())
159 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
160 .app_data(Data::new(context))
161 .app_data(Data::new(rate_limit_cell.clone()))
163 .configure(|cfg| api_routes::config(cfg, rate_limit_cell))
165 if federation_enabled {
166 lemmy_apub::http::routes::config(cfg);
167 webfinger::config(cfg);
170 .configure(feeds::config)
171 .configure(|cfg| images::config(cfg, pictrs_client.clone(), rate_limit_cell))
172 .configure(nodeinfo::config)
174 .bind((settings_bind.bind, settings_bind.port))?