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_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,
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};
26 match_websocket_operation,
27 match_websocket_operation_apub,
28 match_websocket_operation_crud,
30 code_migrations::run_advanced_migrations,
32 root_span_builder::QuieterRootSpanBuilder,
37 rate_limit::RateLimitCell,
38 settings::{structs::Settings, SETTINGS},
41 use reqwest_middleware::ClientBuilder;
42 use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
43 use reqwest_tracing::TracingMiddleware;
44 use std::{env, thread, time::Duration};
45 use tracing_actix_web::TracingLogger;
47 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
49 /// Max timeout for http requests
50 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
53 async fn main() -> Result<(), LemmyError> {
54 let args: Vec<String> = env::args().collect();
55 if args.len() == 2 && args[1] == "--print-config-docs" {
56 let fmt = Formatting {
57 auto_comments: AutoComments::none(),
58 comments_style: CommentsStyle {
59 separator: "#".to_owned(),
61 objects_style: ObjectsStyle {
62 surround_keys_with_quotes: false,
63 use_comma_as_separator: false,
67 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
71 let settings = SETTINGS.to_owned();
73 init_logging(&settings.opentelemetry_url)?;
75 // Set up the bb8 connection pool
76 let db_url = get_database_url(Some(&settings));
77 run_migrations(&db_url);
79 // Run the migrations from code
80 let pool = build_db_pool(&settings).await?;
81 run_advanced_migrations(&pool, &settings).await?;
83 // Schedules various cleanup tasks for the DB
84 thread::spawn(move || {
85 scheduled_tasks::setup(db_url).expect("Couldn't set up scheduled_tasks");
88 // Initialize the secrets
89 let secret = Secret::init(&pool)
91 .expect("Couldn't initialize secrets.");
93 // Make sure the local site is set up.
94 let site_view = SiteView::read_local(&pool)
96 .expect("local site not set up");
97 let local_site = site_view.local_site;
98 let federation_enabled = local_site.federation_enabled;
100 if federation_enabled {
101 println!("federation enabled, host is {}", &settings.hostname);
104 check_private_instance_and_federation_enabled(&local_site)?;
106 // Set up the rate limiter
107 let rate_limit_config =
108 local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit);
109 let rate_limit_cell = RateLimitCell::new(rate_limit_config).await;
112 "Starting http server at {}:{}",
113 settings.bind, settings.port
116 let reqwest_client = Client::builder()
117 .user_agent(build_user_agent(&settings))
118 .timeout(REQWEST_TIMEOUT)
121 let retry_policy = ExponentialBackoff {
123 max_retry_interval: REQWEST_TIMEOUT,
124 min_retry_interval: Duration::from_millis(100),
128 let client = ClientBuilder::new(reqwest_client.clone())
129 .with(TracingMiddleware::default())
130 .with(RetryTransientMiddleware::new_with_policy(retry_policy))
133 // Pictrs cannot use the retry middleware
134 let pictrs_client = ClientBuilder::new(reqwest_client.clone())
135 .with(TracingMiddleware::default())
138 let chat_server = ChatServer::startup(
140 |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
141 |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
142 |c, i, o, d| Box::pin(match_websocket_operation_apub(c, i, o, d)),
146 rate_limit_cell.clone(),
150 // Create Http server with websocket support
151 let settings_bind = settings.clone();
152 HttpServer::new(move || {
153 let context = LemmyContext::create(
159 rate_limit_cell.clone(),
162 .wrap(middleware::Logger::default())
163 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
164 .app_data(Data::new(context))
165 .app_data(Data::new(rate_limit_cell.clone()))
167 .configure(|cfg| api_routes::config(cfg, rate_limit_cell))
169 if federation_enabled {
170 lemmy_apub::http::routes::config(cfg);
171 webfinger::config(cfg);
174 .configure(feeds::config)
175 .configure(|cfg| images::config(cfg, pictrs_client.clone(), rate_limit_cell))
176 .configure(nodeinfo::config)
178 .bind((settings_bind.bind, settings_bind.port))?