1 use chrono::NaiveDateTime;
2 use clokwerk::{Scheduler, TimeUnits as CTimeUnits};
4 dsl::{now, IntervalDsl},
5 sql_types::{Integer, Timestamp},
8 NullableExpressionMethods,
12 // Import week days and WeekDay
13 use diesel::{sql_query, PgConnection, RunQueryDsl};
14 use lemmy_api_common::context::LemmyContext;
15 use lemmy_db_schema::{
26 source::instance::{Instance, InstanceForm},
27 utils::{naive_now, DELETED_REPLACEMENT_TEXT},
29 use lemmy_routes::nodeinfo::NodeInfo;
31 error::{LemmyError, LemmyResult},
34 use reqwest::blocking::Client;
35 use std::{thread, time::Duration};
36 use tracing::{error, info, warn};
38 /// Schedules various cleanup tasks for lemmy in a background thread
42 context_1: LemmyContext,
43 ) -> Result<(), LemmyError> {
44 // Setup the connections
45 let mut scheduler = Scheduler::new();
47 startup_jobs(&db_url);
49 // Update active counts every hour
50 let url = db_url.clone();
51 scheduler.every(CTimeUnits::hour(1)).run(move || {
52 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
53 active_counts(&mut conn);
54 update_banned_when_expired(&mut conn);
57 // Update hot ranks every 15 minutes
58 let url = db_url.clone();
59 scheduler.every(CTimeUnits::minutes(15)).run(move || {
60 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
61 update_hot_ranks(&mut conn);
64 // Delete any captcha answers older than ten minutes, every ten minutes
65 let url = db_url.clone();
66 scheduler.every(CTimeUnits::minutes(10)).run(move || {
67 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
68 delete_expired_captcha_answers(&mut conn);
71 // Clear old activities every week
72 let url = db_url.clone();
73 scheduler.every(CTimeUnits::weeks(1)).run(move || {
74 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
75 clear_old_activities(&mut conn);
78 // Remove old rate limit buckets after 1 to 2 hours of inactivity
79 scheduler.every(CTimeUnits::hour(1)).run(move || {
80 let hour = Duration::from_secs(3600);
81 context_1.settings_updated_channel().remove_older_than(hour);
84 // Overwrite deleted & removed posts and comments every day
85 let url = db_url.clone();
86 scheduler.every(CTimeUnits::days(1)).run(move || {
87 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
88 overwrite_deleted_posts_and_comments(&mut conn);
91 // Update the Instance Software
92 scheduler.every(CTimeUnits::days(1)).run(move || {
93 let mut conn = PgConnection::establish(&db_url).expect("could not establish connection");
94 update_instance_software(&mut conn, &user_agent)
95 .map_err(|e| warn!("Failed to update instance software: {e}"))
99 // Manually run the scheduler in an event loop
101 scheduler.run_pending();
102 thread::sleep(Duration::from_millis(1000));
106 /// Run these on server startup
107 fn startup_jobs(db_url: &str) {
108 let mut conn = PgConnection::establish(db_url).expect("could not establish connection");
109 active_counts(&mut conn);
110 update_hot_ranks(&mut conn);
111 update_banned_when_expired(&mut conn);
112 clear_old_activities(&mut conn);
113 overwrite_deleted_posts_and_comments(&mut conn);
116 /// Update the hot_rank columns for the aggregates tables
117 /// Runs in batches until all necessary rows are updated once
118 fn update_hot_ranks(conn: &mut PgConnection) {
119 info!("Updating hot ranks for all history...");
121 process_hot_ranks_in_batches(
124 "a.hot_rank != 0 OR a.hot_rank_active != 0",
125 "SET hot_rank = hot_rank(a.score, a.published),
126 hot_rank_active = hot_rank(a.score, a.newest_comment_time_necro)",
129 process_hot_ranks_in_batches(
131 "comment_aggregates",
133 "SET hot_rank = hot_rank(a.score, a.published)",
136 process_hot_ranks_in_batches(
138 "community_aggregates",
140 "SET hot_rank = hot_rank(a.subscribers, a.published)",
143 info!("Finished hot ranks update!");
146 #[derive(QueryableByName)]
147 struct HotRanksUpdateResult {
148 #[diesel(sql_type = Timestamp)]
149 published: NaiveDateTime,
152 /// Runs the hot rank update query in batches until all rows have been processed.
153 /// In `where_clause` and `set_clause`, "a" will refer to the current aggregates table.
154 /// Locked rows are skipped in order to prevent deadlocks (they will likely get updated on the next
156 fn process_hot_ranks_in_batches(
157 conn: &mut PgConnection,
162 let process_start_time = NaiveDateTime::from_timestamp_opt(0, 0).expect("0 timestamp creation");
164 let update_batch_size = 1000; // Bigger batches than this tend to cause seq scans
165 let mut processed_rows_count = 0;
166 let mut previous_batch_result = Some(process_start_time);
167 while let Some(previous_batch_last_published) = previous_batch_result {
168 // Raw `sql_query` is used as a performance optimization - Diesel does not support doing this
169 // in a single query (neither as a CTE, nor using a subquery)
170 let result = sql_query(format!(
171 r#"WITH batch AS (SELECT a.id
172 FROM {aggregates_table} a
173 WHERE a.published > $1 AND ({where_clause})
176 FOR UPDATE SKIP LOCKED)
177 UPDATE {aggregates_table} a {set_clause}
178 FROM batch WHERE a.id = batch.id RETURNING a.published;
180 aggregates_table = table_name,
181 set_clause = set_clause,
182 where_clause = where_clause
184 .bind::<Timestamp, _>(previous_batch_last_published)
185 .bind::<Integer, _>(update_batch_size)
186 .get_results::<HotRanksUpdateResult>(conn);
189 Ok(updated_rows) => {
190 processed_rows_count += updated_rows.len();
191 previous_batch_result = updated_rows.last().map(|row| row.published);
194 error!("Failed to update {} hot_ranks: {}", table_name, e);
200 "Finished process_hot_ranks_in_batches execution for {} (processed {} rows)",
201 table_name, processed_rows_count
205 fn delete_expired_captcha_answers(conn: &mut PgConnection) {
206 match diesel::delete(
207 captcha_answer::table.filter(captcha_answer::published.lt(now - IntervalDsl::minutes(10))),
215 error!("Failed to clear old captcha answers: {}", e)
220 /// Clear old activities (this table gets very large)
221 fn clear_old_activities(conn: &mut PgConnection) {
222 info!("Clearing old activities...");
223 diesel::delete(sent_activity::table.filter(sent_activity::published.lt(now - 3.months())))
225 .map_err(|e| error!("Failed to clear old sent activities: {}", e))
229 received_activity::table.filter(received_activity::published.lt(now - 3.months())),
232 .map_err(|e| error!("Failed to clear old received activities: {}", e))
236 /// overwrite posts and comments 30d after deletion
237 fn overwrite_deleted_posts_and_comments(conn: &mut PgConnection) {
238 info!("Overwriting deleted posts...");
239 match diesel::update(
241 .filter(post::deleted.eq(true))
242 .filter(post::updated.lt(now.nullable() - 1.months()))
243 .filter(post::body.ne(DELETED_REPLACEMENT_TEXT)),
246 post::body.eq(DELETED_REPLACEMENT_TEXT),
247 post::name.eq(DELETED_REPLACEMENT_TEXT),
255 error!("Failed to overwrite deleted posts: {}", e)
259 info!("Overwriting deleted comments...");
260 match diesel::update(
262 .filter(comment::deleted.eq(true))
263 .filter(comment::updated.lt(now.nullable() - 1.months()))
264 .filter(comment::content.ne(DELETED_REPLACEMENT_TEXT)),
266 .set(comment::content.eq(DELETED_REPLACEMENT_TEXT))
273 error!("Failed to overwrite deleted comments: {}", e)
278 /// Re-calculate the site and community active counts every 12 hours
279 fn active_counts(conn: &mut PgConnection) {
280 info!("Updating active site and community aggregates ...");
282 let intervals = vec![
285 ("1 month", "month"),
286 ("6 months", "half_year"),
289 for i in &intervals {
290 let update_site_stmt = format!(
291 "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}')) where site_id = 1",
294 match sql_query(update_site_stmt).execute(conn) {
297 error!("Failed to update site stats: {}", e)
301 let update_community_stmt = format!("update community_aggregates ca set users_active_{} = mv.count_ from community_aggregates_activity('{}') mv where ca.community_id = mv.community_id_", i.1, i.0);
302 match sql_query(update_community_stmt).execute(conn) {
305 error!("Failed to update community stats: {}", e)
313 /// Set banned to false after ban expires
314 fn update_banned_when_expired(conn: &mut PgConnection) {
315 info!("Updating banned column if it expires ...");
317 match diesel::update(
319 .filter(person::banned.eq(true))
320 .filter(person::ban_expires.lt(now)),
322 .set(person::banned.eq(false))
327 error!("Failed to update person.banned when expires: {}", e)
330 match diesel::delete(community_person_ban::table.filter(community_person_ban::expires.lt(now)))
335 error!("Failed to remove community_ban expired rows: {}", e)
340 /// Updates the instance software and version
342 /// TODO: this should be async
343 /// TODO: if instance has been dead for a long time, it should be checked less frequently
344 fn update_instance_software(conn: &mut PgConnection, user_agent: &str) -> LemmyResult<()> {
345 info!("Updating instances software and versions...");
347 let client = Client::builder()
348 .user_agent(user_agent)
349 .timeout(REQWEST_TIMEOUT)
352 let instances = instance::table.get_results::<Instance>(conn)?;
354 for instance in instances {
355 let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
357 // The `updated` column is used to check if instances are alive. If it is more than three days
358 // in the past, no outgoing activities will be sent to that instance. However not every
359 // Fediverse instance has a valid Nodeinfo endpoint (its not required for Activitypub). That's
360 // why we always need to mark instances as updated if they are alive.
361 let default_form = InstanceForm::builder()
362 .domain(instance.domain.clone())
363 .updated(Some(naive_now()))
365 let form = match client.get(&node_info_url).send() {
366 Ok(res) if res.status().is_client_error() => {
367 // Instance doesnt have nodeinfo but sent a response, consider it alive
370 Ok(res) => match res.json::<NodeInfo>() {
372 // Instance sent valid nodeinfo, write it to db
374 InstanceForm::builder()
375 .domain(instance.domain)
376 .updated(Some(naive_now()))
377 .software(node_info.software.and_then(|s| s.name))
378 .version(node_info.version.clone())
383 // No valid nodeinfo but valid HTTP response, consider instance alive
388 // dead instance, do nothing
392 if let Some(form) = form {
393 diesel::update(instance::table.find(instance.id))
398 info!("Finished updating instances software and versions...");
404 use lemmy_routes::nodeinfo::NodeInfo;
409 async fn test_nodeinfo() {
410 let client = Client::builder().build().unwrap();
411 let lemmy_ml_nodeinfo = client
412 .get("https://lemmy.ml/nodeinfo/2.0.json")
420 assert_eq!(lemmy_ml_nodeinfo.software.unwrap().name.unwrap(), "lemmy");