]> Untitled Git - lemmy.git/blob - src/scheduled_tasks.rs
f20e61e12821d155ed0bdb6e02ffbc1a893ed1dd
[lemmy.git] / src / scheduled_tasks.rs
1 use chrono::NaiveDateTime;
2 use clokwerk::{Scheduler, TimeUnits as CTimeUnits};
3 use diesel::{
4   dsl::{now, IntervalDsl},
5   sql_types::{Integer, Timestamp},
6   Connection,
7   ExpressionMethods,
8   NullableExpressionMethods,
9   QueryDsl,
10   QueryableByName,
11 };
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},
19 };
20 use lemmy_routes::nodeinfo::NodeInfo;
21 use lemmy_utils::{
22   error::{LemmyError, LemmyResult},
23   REQWEST_TIMEOUT,
24 };
25 use reqwest::blocking::Client;
26 use std::{thread, time::Duration};
27 use tracing::{error, info, warn};
28
29 /// Schedules various cleanup tasks for lemmy in a background thread
30 pub fn setup(
31   db_url: String,
32   user_agent: String,
33   context_1: LemmyContext,
34 ) -> Result<(), LemmyError> {
35   // Setup the connections
36   let mut scheduler = Scheduler::new();
37
38   startup_jobs(&db_url);
39
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);
46   });
47
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);
53   });
54
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);
60   });
61
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);
67   });
68
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);
73   });
74
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);
80   });
81
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}"))
87       .ok();
88   });
89
90   // Manually run the scheduler in an event loop
91   loop {
92     scheduler.run_pending();
93     thread::sleep(Duration::from_millis(1000));
94   }
95 }
96
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);
105 }
106
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)
113   } else {
114     info!("Updating hot ranks for all history...");
115     NaiveDateTime::from_timestamp_opt(0, 0).expect("0 timestamp creation")
116   };
117
118   process_hot_ranks_in_batches(
119     conn,
120     "post_aggregates",
121     "SET hot_rank = hot_rank(a.score, a.published),
122          hot_rank_active = hot_rank(a.score, a.newest_comment_time_necro)",
123     process_start_time,
124   );
125
126   process_hot_ranks_in_batches(
127     conn,
128     "comment_aggregates",
129     "SET hot_rank = hot_rank(a.score, a.published)",
130     process_start_time,
131   );
132
133   process_hot_ranks_in_batches(
134     conn,
135     "community_aggregates",
136     "SET hot_rank = hot_rank(a.subscribers, a.published)",
137     process_start_time,
138   );
139
140   info!("Finished hot ranks update!");
141 }
142
143 #[derive(QueryableByName)]
144 struct HotRanksUpdateResult {
145   #[diesel(sql_type = Timestamp)]
146   published: NaiveDateTime,
147 }
148
149 /// Runs the hot rank update query in batches until all rows after `process_start_time` have been
150 /// processed.
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
153 /// run)
154 fn process_hot_ranks_in_batches(
155   conn: &mut PgConnection,
156   table_name: &str,
157   set_clause: &str,
158   process_start_time: NaiveDateTime,
159 ) {
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
169                ORDER BY a.published
170                LIMIT $2
171                FOR UPDATE SKIP LOCKED)
172          UPDATE {aggregates_table} a {set_clause}
173              FROM batch WHERE a.id = batch.id RETURNING a.published;
174     "#,
175       aggregates_table = table_name,
176       set_clause = set_clause
177     ))
178     .bind::<Timestamp, _>(previous_batch_last_published)
179     .bind::<Integer, _>(update_batch_size)
180     .get_results::<HotRanksUpdateResult>(conn);
181
182     match result {
183       Ok(updated_rows) => previous_batch_result = updated_rows.last().map(|row| row.published),
184       Err(e) => {
185         error!("Failed to update {} hot_ranks: {}", table_name, e);
186         break;
187       }
188     }
189   }
190   info!(
191     "Finished process_hot_ranks_in_batches execution for {}",
192     table_name
193   );
194 }
195
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))),
199   )
200   .execute(conn)
201   {
202     Ok(_) => {
203       info!("Done.");
204     }
205     Err(e) => {
206       error!("Failed to clear old captcha answers: {}", e)
207     }
208   }
209 }
210
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())))
215     .execute(conn)
216   {
217     Ok(_) => {
218       info!("Done.");
219     }
220     Err(e) => {
221       error!("Failed to clear old activities: {}", e)
222     }
223   }
224 }
225
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(
230     post::table
231       .filter(post::deleted.eq(true))
232       .filter(post::updated.lt(now.nullable() - 1.months()))
233       .filter(post::body.ne(DELETED_REPLACEMENT_TEXT)),
234   )
235   .set((
236     post::body.eq(DELETED_REPLACEMENT_TEXT),
237     post::name.eq(DELETED_REPLACEMENT_TEXT),
238   ))
239   .execute(conn)
240   {
241     Ok(_) => {
242       info!("Done.");
243     }
244     Err(e) => {
245       error!("Failed to overwrite deleted posts: {}", e)
246     }
247   }
248
249   info!("Overwriting deleted comments...");
250   match diesel::update(
251     comment::table
252       .filter(comment::deleted.eq(true))
253       .filter(comment::updated.lt(now.nullable() - 1.months()))
254       .filter(comment::content.ne(DELETED_REPLACEMENT_TEXT)),
255   )
256   .set(comment::content.eq(DELETED_REPLACEMENT_TEXT))
257   .execute(conn)
258   {
259     Ok(_) => {
260       info!("Done.");
261     }
262     Err(e) => {
263       error!("Failed to overwrite deleted comments: {}", e)
264     }
265   }
266 }
267
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 ...");
271
272   let intervals = vec![
273     ("1 day", "day"),
274     ("1 week", "week"),
275     ("1 month", "month"),
276     ("6 months", "half_year"),
277   ];
278
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",
282       i.1, i.0
283     );
284     match sql_query(update_site_stmt).execute(conn) {
285       Ok(_) => {}
286       Err(e) => {
287         error!("Failed to update site stats: {}", e)
288       }
289     }
290
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) {
293       Ok(_) => {}
294       Err(e) => {
295         error!("Failed to update community stats: {}", e)
296       }
297     }
298   }
299
300   info!("Done.");
301 }
302
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 ...");
306
307   match diesel::update(
308     person::table
309       .filter(person::banned.eq(true))
310       .filter(person::ban_expires.lt(now)),
311   )
312   .set(person::banned.eq(false))
313   .execute(conn)
314   {
315     Ok(_) => {}
316     Err(e) => {
317       error!("Failed to update person.banned when expires: {}", e)
318     }
319   }
320   match diesel::delete(community_person_ban::table.filter(community_person_ban::expires.lt(now)))
321     .execute(conn)
322   {
323     Ok(_) => {}
324     Err(e) => {
325       error!("Failed to remove community_ban expired rows: {}", e)
326     }
327   }
328 }
329
330 /// Updates the instance software and version
331 ///
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...");
336
337   let client = Client::builder()
338     .user_agent(user_agent)
339     .timeout(REQWEST_TIMEOUT)
340     .build()?;
341
342   let instances = instance::table.get_results::<Instance>(conn)?;
343
344   for instance in instances {
345     let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
346
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()))
354       .build();
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
358         Some(default_form)
359       }
360       Ok(res) => match res.json::<NodeInfo>() {
361         Ok(node_info) => {
362           // Instance sent valid nodeinfo, write it to db
363           Some(
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())
369               .build(),
370           )
371         }
372         Err(_) => {
373           // No valid nodeinfo but valid HTTP response, consider instance alive
374           Some(default_form)
375         }
376       },
377       Err(_) => {
378         // dead instance, do nothing
379         None
380       }
381     };
382     if let Some(form) = form {
383       diesel::update(instance::table.find(instance.id))
384         .set(form)
385         .execute(conn)?;
386     }
387   }
388   info!("Finished updating instances software and versions...");
389   Ok(())
390 }
391
392 #[cfg(test)]
393 mod tests {
394   use lemmy_routes::nodeinfo::NodeInfo;
395   use reqwest::Client;
396
397   #[tokio::test]
398   #[ignore]
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")
403       .send()
404       .await
405       .unwrap()
406       .json::<NodeInfo>()
407       .await
408       .unwrap();
409
410     assert_eq!(lemmy_ml_nodeinfo.software.unwrap().name.unwrap(), "lemmy");
411   }
412 }