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::{
16 schema::{activity, captcha_answer, comment, community_person_ban, instance, person, post},
17 source::instance::{Instance, InstanceForm},
18 utils::{naive_now, DELETED_REPLACEMENT_TEXT},
20 use lemmy_routes::nodeinfo::NodeInfo;
22 error::{LemmyError, LemmyResult},
25 use reqwest::blocking::Client;
26 use std::{thread, time::Duration};
27 use tracing::{error, info, warn};
29 /// Schedules various cleanup tasks for lemmy in a background thread
33 context_1: LemmyContext,
34 ) -> Result<(), LemmyError> {
35 // Setup the connections
36 let mut scheduler = Scheduler::new();
38 startup_jobs(&db_url);
40 // Update active counts every hour
41 let url = db_url.clone();
42 scheduler.every(CTimeUnits::hour(1)).run(move || {
43 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
44 active_counts(&mut conn);
45 update_banned_when_expired(&mut conn);
48 // Update hot ranks every 15 minutes
49 let url = db_url.clone();
50 scheduler.every(CTimeUnits::minutes(15)).run(move || {
51 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
52 update_hot_ranks(&mut conn, true);
55 // Delete any captcha answers older than ten minutes, every ten minutes
56 let url = db_url.clone();
57 scheduler.every(CTimeUnits::minutes(10)).run(move || {
58 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
59 delete_expired_captcha_answers(&mut conn);
62 // Clear old activities every week
63 let url = db_url.clone();
64 scheduler.every(CTimeUnits::weeks(1)).run(move || {
65 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
66 clear_old_activities(&mut conn);
69 // Remove old rate limit buckets after 1 to 2 hours of inactivity
70 scheduler.every(CTimeUnits::hour(1)).run(move || {
71 let hour = Duration::from_secs(3600);
72 context_1.settings_updated_channel().remove_older_than(hour);
75 // Overwrite deleted & removed posts and comments every day
76 let url = db_url.clone();
77 scheduler.every(CTimeUnits::days(1)).run(move || {
78 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
79 overwrite_deleted_posts_and_comments(&mut conn);
82 // Update the Instance Software
83 scheduler.every(CTimeUnits::days(1)).run(move || {
84 let mut conn = PgConnection::establish(&db_url).expect("could not establish connection");
85 update_instance_software(&mut conn, &user_agent)
86 .map_err(|e| warn!("Failed to update instance software: {e}"))
90 // Manually run the scheduler in an event loop
92 scheduler.run_pending();
93 thread::sleep(Duration::from_millis(1000));
97 /// Run these on server startup
98 fn startup_jobs(db_url: &str) {
99 let mut conn = PgConnection::establish(db_url).expect("could not establish connection");
100 active_counts(&mut conn);
101 update_hot_ranks(&mut conn, false);
102 update_banned_when_expired(&mut conn);
103 clear_old_activities(&mut conn);
104 overwrite_deleted_posts_and_comments(&mut conn);
107 /// Update the hot_rank columns for the aggregates tables
108 /// Runs in batches until all necessary rows are updated once
109 fn update_hot_ranks(conn: &mut PgConnection, last_week_only: bool) {
110 let process_start_time = if last_week_only {
111 info!("Updating hot ranks for last week...");
112 naive_now() - chrono::Duration::days(7)
114 info!("Updating hot ranks for all history...");
115 NaiveDateTime::from_timestamp_opt(0, 0).expect("0 timestamp creation")
118 process_hot_ranks_in_batches(
121 "SET hot_rank = hot_rank(a.score, a.published),
122 hot_rank_active = hot_rank(a.score, a.newest_comment_time_necro)",
126 process_hot_ranks_in_batches(
128 "comment_aggregates",
129 "SET hot_rank = hot_rank(a.score, a.published)",
133 process_hot_ranks_in_batches(
135 "community_aggregates",
136 "SET hot_rank = hot_rank(a.subscribers, a.published)",
140 info!("Finished hot ranks update!");
143 #[derive(QueryableByName)]
144 struct HotRanksUpdateResult {
145 #[diesel(sql_type = Timestamp)]
146 published: NaiveDateTime,
149 /// Runs the hot rank update query in batches until all rows after `process_start_time` have been
151 /// In `set_clause`, "a" will refer to the current aggregates table.
152 /// Locked rows are skipped in order to prevent deadlocks (they will likely get updated on the next
154 fn process_hot_ranks_in_batches(
155 conn: &mut PgConnection,
158 process_start_time: NaiveDateTime,
160 let update_batch_size = 1000; // Bigger batches than this tend to cause seq scans
161 let mut previous_batch_result = Some(process_start_time);
162 while let Some(previous_batch_last_published) = previous_batch_result {
163 // Raw `sql_query` is used as a performance optimization - Diesel does not support doing this
164 // in a single query (neither as a CTE, nor using a subquery)
165 let result = sql_query(format!(
166 r#"WITH batch AS (SELECT a.id
167 FROM {aggregates_table} a
168 WHERE a.published > $1
171 FOR UPDATE SKIP LOCKED)
172 UPDATE {aggregates_table} a {set_clause}
173 FROM batch WHERE a.id = batch.id RETURNING a.published;
175 aggregates_table = table_name,
176 set_clause = set_clause
178 .bind::<Timestamp, _>(previous_batch_last_published)
179 .bind::<Integer, _>(update_batch_size)
180 .get_results::<HotRanksUpdateResult>(conn);
183 Ok(updated_rows) => previous_batch_result = updated_rows.last().map(|row| row.published),
185 error!("Failed to update {} hot_ranks: {}", table_name, e);
191 "Finished process_hot_ranks_in_batches execution for {}",
196 fn delete_expired_captcha_answers(conn: &mut PgConnection) {
197 match diesel::delete(
198 captcha_answer::table.filter(captcha_answer::published.lt(now - IntervalDsl::minutes(10))),
206 error!("Failed to clear old captcha answers: {}", e)
211 /// Clear old activities (this table gets very large)
212 fn clear_old_activities(conn: &mut PgConnection) {
213 info!("Clearing old activities...");
214 match diesel::delete(activity::table.filter(activity::published.lt(now - 6.months())))
221 error!("Failed to clear old activities: {}", e)
226 /// overwrite posts and comments 30d after deletion
227 fn overwrite_deleted_posts_and_comments(conn: &mut PgConnection) {
228 info!("Overwriting deleted posts...");
229 match diesel::update(
231 .filter(post::deleted.eq(true))
232 .filter(post::updated.lt(now.nullable() - 1.months()))
233 .filter(post::body.ne(DELETED_REPLACEMENT_TEXT)),
236 post::body.eq(DELETED_REPLACEMENT_TEXT),
237 post::name.eq(DELETED_REPLACEMENT_TEXT),
245 error!("Failed to overwrite deleted posts: {}", e)
249 info!("Overwriting deleted comments...");
250 match diesel::update(
252 .filter(comment::deleted.eq(true))
253 .filter(comment::updated.lt(now.nullable() - 1.months()))
254 .filter(comment::content.ne(DELETED_REPLACEMENT_TEXT)),
256 .set(comment::content.eq(DELETED_REPLACEMENT_TEXT))
263 error!("Failed to overwrite deleted comments: {}", e)
268 /// Re-calculate the site and community active counts every 12 hours
269 fn active_counts(conn: &mut PgConnection) {
270 info!("Updating active site and community aggregates ...");
272 let intervals = vec![
275 ("1 month", "month"),
276 ("6 months", "half_year"),
279 for i in &intervals {
280 let update_site_stmt = format!(
281 "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}')) where site_id = 1",
284 match sql_query(update_site_stmt).execute(conn) {
287 error!("Failed to update site stats: {}", e)
291 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);
292 match sql_query(update_community_stmt).execute(conn) {
295 error!("Failed to update community stats: {}", e)
303 /// Set banned to false after ban expires
304 fn update_banned_when_expired(conn: &mut PgConnection) {
305 info!("Updating banned column if it expires ...");
307 match diesel::update(
309 .filter(person::banned.eq(true))
310 .filter(person::ban_expires.lt(now)),
312 .set(person::banned.eq(false))
317 error!("Failed to update person.banned when expires: {}", e)
320 match diesel::delete(community_person_ban::table.filter(community_person_ban::expires.lt(now)))
325 error!("Failed to remove community_ban expired rows: {}", e)
330 /// Updates the instance software and version
332 /// TODO: this should be async
333 /// TODO: if instance has been dead for a long time, it should be checked less frequently
334 fn update_instance_software(conn: &mut PgConnection, user_agent: &str) -> LemmyResult<()> {
335 info!("Updating instances software and versions...");
337 let client = Client::builder()
338 .user_agent(user_agent)
339 .timeout(REQWEST_TIMEOUT)
342 let instances = instance::table.get_results::<Instance>(conn)?;
344 for instance in instances {
345 let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
347 // The `updated` column is used to check if instances are alive. If it is more than three days
348 // in the past, no outgoing activities will be sent to that instance. However not every
349 // Fediverse instance has a valid Nodeinfo endpoint (its not required for Activitypub). That's
350 // why we always need to mark instances as updated if they are alive.
351 let default_form = InstanceForm::builder()
352 .domain(instance.domain.clone())
353 .updated(Some(naive_now()))
355 let form = match client.get(&node_info_url).send() {
356 Ok(res) if res.status().is_client_error() => {
357 // Instance doesnt have nodeinfo but sent a response, consider it alive
360 Ok(res) => match res.json::<NodeInfo>() {
362 // Instance sent valid nodeinfo, write it to db
364 InstanceForm::builder()
365 .domain(instance.domain)
366 .updated(Some(naive_now()))
367 .software(node_info.software.and_then(|s| s.name))
368 .version(node_info.version.clone())
373 // No valid nodeinfo but valid HTTP response, consider instance alive
378 // dead instance, do nothing
382 if let Some(form) = form {
383 diesel::update(instance::table.find(instance.id))
388 info!("Finished updating instances software and versions...");
394 use lemmy_routes::nodeinfo::NodeInfo;
399 async fn test_nodeinfo() {
400 let client = Client::builder().build().unwrap();
401 let lemmy_ml_nodeinfo = client
402 .get("https://lemmy.ml/nodeinfo/2.0.json")
410 assert_eq!(lemmy_ml_nodeinfo.software.unwrap().name.unwrap(), "lemmy");