2 extern crate diesel_migrations;
4 use actix_web::{middleware, web::Data, App, HttpServer, Result};
5 use diesel_migrations::EmbeddedMigrations;
6 use doku::json::{AutoComments, CommentsStyle, Formatting, ObjectsStyle};
7 use lemmy_api_common::{
9 lemmy_db_views::structs::SiteView,
10 request::build_user_agent,
12 check_private_instance_and_federation_enabled,
13 local_site_rate_limit_to_rate_limit_config,
15 websocket::chat_server::ChatServer,
17 use lemmy_db_schema::{
18 source::secret::Secret,
19 utils::{build_db_pool, get_database_url, run_migrations},
21 use lemmy_routes::{feeds, images, nodeinfo, webfinger};
24 code_migrations::run_advanced_migrations,
26 root_span_builder::QuieterRootSpanBuilder,
31 rate_limit::RateLimitCell,
32 settings::{structs::Settings, SETTINGS},
35 use reqwest_middleware::ClientBuilder;
36 use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
37 use reqwest_tracing::TracingMiddleware;
38 use std::{env, sync::Arc, thread, time::Duration};
39 use tracing_actix_web::TracingLogger;
41 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
43 /// Max timeout for http requests
44 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
47 async fn main() -> Result<(), LemmyError> {
48 let args: Vec<String> = env::args().collect();
49 if args.len() == 2 && args[1] == "--print-config-docs" {
50 let fmt = Formatting {
51 auto_comments: AutoComments::none(),
52 comments_style: CommentsStyle {
53 separator: "#".to_owned(),
55 objects_style: ObjectsStyle {
56 surround_keys_with_quotes: false,
57 use_comma_as_separator: false,
61 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
65 let settings = SETTINGS.to_owned();
67 init_logging(&settings.opentelemetry_url)?;
69 // Set up the bb8 connection pool
70 let db_url = get_database_url(Some(&settings));
71 run_migrations(&db_url);
73 // Run the migrations from code
74 let pool = build_db_pool(&settings).await?;
75 run_advanced_migrations(&pool, &settings).await?;
77 // Schedules various cleanup tasks for the DB
78 thread::spawn(move || {
79 scheduled_tasks::setup(db_url).expect("Couldn't set up scheduled_tasks");
82 // Initialize the secrets
83 let secret = Secret::init(&pool)
85 .expect("Couldn't initialize secrets.");
87 // Make sure the local site is set up.
88 let site_view = SiteView::read_local(&pool)
90 .expect("local site not set up");
91 let local_site = site_view.local_site;
92 let federation_enabled = local_site.federation_enabled;
94 if federation_enabled {
95 println!("federation enabled, host is {}", &settings.hostname);
98 check_private_instance_and_federation_enabled(&local_site)?;
100 // Set up the rate limiter
101 let rate_limit_config =
102 local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit);
103 let rate_limit_cell = RateLimitCell::new(rate_limit_config).await;
106 "Starting http server at {}:{}",
107 settings.bind, settings.port
110 let reqwest_client = Client::builder()
111 .user_agent(build_user_agent(&settings))
112 .timeout(REQWEST_TIMEOUT)
115 let retry_policy = ExponentialBackoff {
117 max_retry_interval: REQWEST_TIMEOUT,
118 min_retry_interval: Duration::from_millis(100),
122 let client = ClientBuilder::new(reqwest_client.clone())
123 .with(TracingMiddleware::default())
124 .with(RetryTransientMiddleware::new_with_policy(retry_policy))
127 // Pictrs cannot use the retry middleware
128 let pictrs_client = ClientBuilder::new(reqwest_client.clone())
129 .with(TracingMiddleware::default())
132 let chat_server = Arc::new(ChatServer::startup());
134 // Create Http server with websocket support
135 let settings_bind = settings.clone();
136 HttpServer::new(move || {
137 let context = LemmyContext::create(
143 rate_limit_cell.clone(),
146 .wrap(middleware::Logger::default())
147 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
148 .app_data(Data::new(context))
149 .app_data(Data::new(rate_limit_cell.clone()))
151 .configure(|cfg| api_routes_http::config(cfg, rate_limit_cell))
153 if federation_enabled {
154 lemmy_apub::http::routes::config(cfg);
155 webfinger::config(cfg);
158 .configure(feeds::config)
159 .configure(|cfg| images::config(cfg, pictrs_client.clone(), rate_limit_cell))
160 .configure(nodeinfo::config)
162 .bind((settings_bind.bind, settings_bind.port))?