2 extern crate diesel_migrations;
5 use actix_web::{web::Data, *};
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::{rate_limiter::RateLimiter, RateLimit},
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;
46 use tracing_actix_web::TracingLogger;
48 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
50 /// Max timeout for http requests
51 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
54 async fn main() -> Result<(), LemmyError> {
55 let args: Vec<String> = env::args().collect();
56 if args.len() == 2 && args[1] == "--print-config-docs" {
57 let fmt = Formatting {
58 auto_comments: AutoComments::none(),
59 comments_style: CommentsStyle {
60 separator: "#".to_owned(),
62 objects_style: ObjectsStyle {
63 surround_keys_with_quotes: false,
64 use_comma_as_separator: false,
68 println!("{}", doku::to_json_fmt_val(&fmt, &Settings::default()));
72 let settings = SETTINGS.to_owned();
74 init_logging(&settings.opentelemetry_url)?;
76 // Set up the bb8 connection pool
77 let db_url = get_database_url(Some(&settings));
78 run_migrations(&db_url);
80 // Run the migrations from code
81 let pool = build_db_pool(&settings).await?;
82 run_advanced_migrations(&pool, &settings).await?;
84 // Schedules various cleanup tasks for the DB
85 thread::spawn(move || {
86 scheduled_tasks::setup(db_url).expect("Couldn't set up scheduled_tasks");
89 // Initialize the secrets
90 let secret = Secret::init(&pool)
92 .expect("Couldn't initialize secrets.");
94 // Make sure the local site is set up.
95 let site_view = SiteView::read_local(&pool)
97 .expect("local site not set up");
98 let local_site = site_view.local_site;
99 let federation_enabled = local_site.federation_enabled;
101 if federation_enabled {
102 println!("federation enabled, host is {}", &settings.hostname);
105 check_private_instance_and_federation_enabled(&local_site)?;
107 // Set up the rate limiter
108 let rate_limit_config =
109 local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit);
111 // TODO this isn't live-updating
112 // https://github.com/LemmyNet/lemmy/issues/2508
113 let rate_limiter = RateLimit {
114 rate_limiter: Arc::new(Mutex::new(RateLimiter::default())),
119 "Starting http server at {}:{}",
120 settings.bind, settings.port
123 let reqwest_client = Client::builder()
124 .user_agent(build_user_agent(&settings))
125 .timeout(REQWEST_TIMEOUT)
128 let retry_policy = ExponentialBackoff {
130 max_retry_interval: REQWEST_TIMEOUT,
131 min_retry_interval: Duration::from_millis(100),
135 let client = ClientBuilder::new(reqwest_client.clone())
136 .with(TracingMiddleware::default())
137 .with(RetryTransientMiddleware::new_with_policy(retry_policy))
140 // Pictrs cannot use the retry middleware
141 let pictrs_client = ClientBuilder::new(reqwest_client.clone())
142 .with(TracingMiddleware::default())
145 let chat_server = ChatServer::startup(
147 rate_limiter.clone(),
148 |c, i, o, d| Box::pin(match_websocket_operation(c, i, o, d)),
149 |c, i, o, d| Box::pin(match_websocket_operation_crud(c, i, o, d)),
156 // Create Http server with websocket support
157 let settings_bind = settings.clone();
158 HttpServer::new(move || {
159 let context = LemmyContext::create(
161 chat_server.to_owned(),
166 let rate_limiter = rate_limiter.clone();
168 .wrap(actix_web::middleware::Logger::default())
169 .wrap(TracingLogger::<QuieterRootSpanBuilder>::new())
170 .app_data(Data::new(context))
171 .app_data(Data::new(rate_limiter.clone()))
173 .configure(|cfg| api_routes::config(cfg, &rate_limiter))
175 if federation_enabled {
176 lemmy_apub::http::routes::config(cfg);
177 webfinger::config(cfg);
180 .configure(feeds::config)
181 .configure(|cfg| images::config(cfg, pictrs_client.clone(), &rate_limiter))
182 .configure(nodeinfo::config)
184 .bind((settings_bind.bind, settings_bind.port))?