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, 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;
21 use lemmy_utils::{error::LemmyError, REQWEST_TIMEOUT};
22 use reqwest::blocking::Client;
23 use std::{thread, time::Duration};
24 use tracing::{error, info};
26 /// Schedules various cleanup tasks for lemmy in a background thread
30 context_1: LemmyContext,
31 ) -> Result<(), LemmyError> {
32 // Setup the connections
33 let mut scheduler = Scheduler::new();
35 startup_jobs(&db_url);
37 // Update active counts every hour
38 let url = db_url.clone();
39 scheduler.every(CTimeUnits::hour(1)).run(move || {
40 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
41 active_counts(&mut conn);
42 update_banned_when_expired(&mut conn);
45 // Update hot ranks every 15 minutes
46 let url = db_url.clone();
47 scheduler.every(CTimeUnits::minutes(15)).run(move || {
48 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
49 update_hot_ranks(&mut conn, true);
52 // Clear old activities every week
53 let url = db_url.clone();
54 scheduler.every(CTimeUnits::weeks(1)).run(move || {
55 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
56 clear_old_activities(&mut conn);
59 // Remove old rate limit buckets after 1 to 2 hours of inactivity
60 scheduler.every(CTimeUnits::hour(1)).run(move || {
61 let hour = Duration::from_secs(3600);
62 context_1.settings_updated_channel().remove_older_than(hour);
65 // Overwrite deleted & removed posts and comments every day
66 let url = db_url.clone();
67 scheduler.every(CTimeUnits::days(1)).run(move || {
68 let mut conn = PgConnection::establish(&url).expect("could not establish connection");
69 overwrite_deleted_posts_and_comments(&mut conn);
72 // Update the Instance Software
73 scheduler.every(CTimeUnits::days(1)).run(move || {
74 let mut conn = PgConnection::establish(&db_url).expect("could not establish connection");
75 update_instance_software(&mut conn, &user_agent);
78 // Manually run the scheduler in an event loop
80 scheduler.run_pending();
81 thread::sleep(Duration::from_millis(1000));
85 /// Run these on server startup
86 fn startup_jobs(db_url: &str) {
87 let mut conn = PgConnection::establish(db_url).expect("could not establish connection");
88 active_counts(&mut conn);
89 update_hot_ranks(&mut conn, false);
90 update_banned_when_expired(&mut conn);
91 clear_old_activities(&mut conn);
92 overwrite_deleted_posts_and_comments(&mut conn);
95 /// Update the hot_rank columns for the aggregates tables
96 /// Runs in batches until all necessary rows are updated once
97 fn update_hot_ranks(conn: &mut PgConnection, last_week_only: bool) {
98 let process_start_time = if last_week_only {
99 info!("Updating hot ranks for last week...");
100 naive_now() - chrono::Duration::days(7)
102 info!("Updating hot ranks for all history...");
103 NaiveDateTime::from_timestamp_opt(0, 0).expect("0 timestamp creation")
106 process_hot_ranks_in_batches(
109 "SET hot_rank = hot_rank(a.score, a.published),
110 hot_rank_active = hot_rank(a.score, a.newest_comment_time_necro)",
114 process_hot_ranks_in_batches(
116 "comment_aggregates",
117 "SET hot_rank = hot_rank(a.score, a.published)",
121 process_hot_ranks_in_batches(
123 "community_aggregates",
124 "SET hot_rank = hot_rank(a.subscribers, a.published)",
128 info!("Finished hot ranks update!");
131 #[derive(QueryableByName)]
132 struct HotRanksUpdateResult {
133 #[diesel(sql_type = Timestamp)]
134 published: NaiveDateTime,
137 /// Runs the hot rank update query in batches until all rows after `process_start_time` have been
139 /// In `set_clause`, "a" will refer to the current aggregates table.
140 /// Locked rows are skipped in order to prevent deadlocks (they will likely get updated on the next
142 fn process_hot_ranks_in_batches(
143 conn: &mut PgConnection,
146 process_start_time: NaiveDateTime,
148 let update_batch_size = 1000; // Bigger batches than this tend to cause seq scans
149 let mut previous_batch_result = Some(process_start_time);
150 while let Some(previous_batch_last_published) = previous_batch_result {
151 // Raw `sql_query` is used as a performance optimization - Diesel does not support doing this
152 // in a single query (neither as a CTE, nor using a subquery)
153 let result = sql_query(format!(
154 r#"WITH batch AS (SELECT a.id
155 FROM {aggregates_table} a
156 WHERE a.published > $1
159 FOR UPDATE SKIP LOCKED)
160 UPDATE {aggregates_table} a {set_clause}
161 FROM batch WHERE a.id = batch.id RETURNING a.published;
163 aggregates_table = table_name,
164 set_clause = set_clause
166 .bind::<Timestamp, _>(previous_batch_last_published)
167 .bind::<Integer, _>(update_batch_size)
168 .get_results::<HotRanksUpdateResult>(conn);
171 Ok(updated_rows) => previous_batch_result = updated_rows.last().map(|row| row.published),
173 error!("Failed to update {} hot_ranks: {}", table_name, e);
179 "Finished process_hot_ranks_in_batches execution for {}",
184 /// Clear old activities (this table gets very large)
185 fn clear_old_activities(conn: &mut PgConnection) {
186 info!("Clearing old activities...");
187 match diesel::delete(activity::table.filter(activity::published.lt(now - 6.months())))
194 error!("Failed to clear old activities: {}", e)
199 /// overwrite posts and comments 30d after deletion
200 fn overwrite_deleted_posts_and_comments(conn: &mut PgConnection) {
201 info!("Overwriting deleted posts...");
202 match diesel::update(
204 .filter(post::deleted.eq(true))
205 .filter(post::updated.lt(now.nullable() - 1.months()))
206 .filter(post::body.ne(DELETED_REPLACEMENT_TEXT)),
209 post::body.eq(DELETED_REPLACEMENT_TEXT),
210 post::name.eq(DELETED_REPLACEMENT_TEXT),
218 error!("Failed to overwrite deleted posts: {}", e)
222 info!("Overwriting deleted comments...");
223 match diesel::update(
225 .filter(comment::deleted.eq(true))
226 .filter(comment::updated.lt(now.nullable() - 1.months()))
227 .filter(comment::content.ne(DELETED_REPLACEMENT_TEXT)),
229 .set(comment::content.eq(DELETED_REPLACEMENT_TEXT))
236 error!("Failed to overwrite deleted comments: {}", e)
241 /// Re-calculate the site and community active counts every 12 hours
242 fn active_counts(conn: &mut PgConnection) {
243 info!("Updating active site and community aggregates ...");
245 let intervals = vec![
248 ("1 month", "month"),
249 ("6 months", "half_year"),
252 for i in &intervals {
253 let update_site_stmt = format!(
254 "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}'))",
257 match sql_query(update_site_stmt).execute(conn) {
260 error!("Failed to update site stats: {}", e)
264 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);
265 match sql_query(update_community_stmt).execute(conn) {
268 error!("Failed to update community stats: {}", e)
276 /// Set banned to false after ban expires
277 fn update_banned_when_expired(conn: &mut PgConnection) {
278 info!("Updating banned column if it expires ...");
280 match diesel::update(
282 .filter(person::banned.eq(true))
283 .filter(person::ban_expires.lt(now)),
285 .set(person::banned.eq(false))
290 error!("Failed to update person.banned when expires: {}", e)
293 match diesel::delete(community_person_ban::table.filter(community_person_ban::expires.lt(now)))
298 error!("Failed to remove community_ban expired rows: {}", e)
303 /// Updates the instance software and version
304 fn update_instance_software(conn: &mut PgConnection, user_agent: &str) {
305 info!("Updating instances software and versions...");
307 let client = match Client::builder()
308 .user_agent(user_agent)
309 .timeout(REQWEST_TIMEOUT)
312 Ok(client) => client,
314 error!("Failed to build reqwest client: {}", e);
319 let instances = match instance::table.get_results::<Instance>(conn) {
320 Ok(instances) => instances,
322 error!("Failed to get instances: {}", e);
327 for instance in instances {
328 let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
330 // Skip it if it can't connect
335 .and_then(|t| t.json::<NodeInfo>().ok());
337 if let Some(node_info) = res {
338 let software = node_info.software.as_ref();
339 let form = InstanceForm::builder()
340 .domain(instance.domain)
341 .software(software.and_then(|s| s.name.clone()))
342 .version(software.and_then(|s| s.version.clone()))
343 .updated(Some(naive_now()))
346 match diesel::update(instance::table.find(instance.id))
354 error!("Failed to update site instance software: {}", e);
364 use lemmy_routes::nodeinfo::NodeInfo;
369 async fn test_nodeinfo() {
370 let client = Client::builder().build().unwrap();
371 let lemmy_ml_nodeinfo = client
372 .get("https://lemmy.ml/nodeinfo/2.0.json")
380 assert_eq!(lemmy_ml_nodeinfo.software.unwrap().name.unwrap(), "lemmy");