]> Untitled Git - lemmy.git/blob - src/scheduled_tasks.rs
a4d0926817f190e0f3d4beb16fa8d2e797323c6c
[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::{
17     captcha_answer,
18     comment,
19     community_person_ban,
20     instance,
21     person,
22     post,
23     received_activity,
24     sent_activity,
25   },
26   source::instance::{Instance, InstanceForm},
27   utils::{naive_now, DELETED_REPLACEMENT_TEXT},
28 };
29 use lemmy_routes::nodeinfo::NodeInfo;
30 use lemmy_utils::{
31   error::{LemmyError, LemmyResult},
32   REQWEST_TIMEOUT,
33 };
34 use reqwest::blocking::Client;
35 use std::{thread, time::Duration};
36 use tracing::{error, info, warn};
37
38 /// Schedules various cleanup tasks for lemmy in a background thread
39 pub fn setup(
40   db_url: String,
41   user_agent: String,
42   context_1: LemmyContext,
43 ) -> Result<(), LemmyError> {
44   // Setup the connections
45   let mut scheduler = Scheduler::new();
46
47   startup_jobs(&db_url);
48
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);
55   });
56
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);
62   });
63
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);
69   });
70
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);
76   });
77
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);
82   });
83
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);
89   });
90
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}"))
96       .ok();
97   });
98
99   // Manually run the scheduler in an event loop
100   loop {
101     scheduler.run_pending();
102     thread::sleep(Duration::from_millis(1000));
103   }
104 }
105
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);
114 }
115
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...");
120
121   process_hot_ranks_in_batches(
122     conn,
123     "post_aggregates",
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)",
127   );
128
129   process_hot_ranks_in_batches(
130     conn,
131     "comment_aggregates",
132     "a.hot_rank != 0",
133     "SET hot_rank = hot_rank(a.score, a.published)",
134   );
135
136   process_hot_ranks_in_batches(
137     conn,
138     "community_aggregates",
139     "a.hot_rank != 0",
140     "SET hot_rank = hot_rank(a.subscribers, a.published)",
141   );
142
143   info!("Finished hot ranks update!");
144 }
145
146 #[derive(QueryableByName)]
147 struct HotRanksUpdateResult {
148   #[diesel(sql_type = Timestamp)]
149   published: NaiveDateTime,
150 }
151
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
155 /// run)
156 fn process_hot_ranks_in_batches(
157   conn: &mut PgConnection,
158   table_name: &str,
159   where_clause: &str,
160   set_clause: &str,
161 ) {
162   let process_start_time = NaiveDateTime::from_timestamp_opt(0, 0).expect("0 timestamp creation");
163
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})
174                ORDER BY a.published
175                LIMIT $2
176                FOR UPDATE SKIP LOCKED)
177          UPDATE {aggregates_table} a {set_clause}
178              FROM batch WHERE a.id = batch.id RETURNING a.published;
179     "#,
180       aggregates_table = table_name,
181       set_clause = set_clause,
182       where_clause = where_clause
183     ))
184     .bind::<Timestamp, _>(previous_batch_last_published)
185     .bind::<Integer, _>(update_batch_size)
186     .get_results::<HotRanksUpdateResult>(conn);
187
188     match result {
189       Ok(updated_rows) => {
190         processed_rows_count += updated_rows.len();
191         previous_batch_result = updated_rows.last().map(|row| row.published);
192       }
193       Err(e) => {
194         error!("Failed to update {} hot_ranks: {}", table_name, e);
195         break;
196       }
197     }
198   }
199   info!(
200     "Finished process_hot_ranks_in_batches execution for {} (processed {} rows)",
201     table_name, processed_rows_count
202   );
203 }
204
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))),
208   )
209   .execute(conn)
210   {
211     Ok(_) => {
212       info!("Done.");
213     }
214     Err(e) => {
215       error!("Failed to clear old captcha answers: {}", e)
216     }
217   }
218 }
219
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())))
224     .execute(conn)
225     .map_err(|e| error!("Failed to clear old sent activities: {}", e))
226     .ok();
227
228   diesel::delete(
229     received_activity::table.filter(received_activity::published.lt(now - 3.months())),
230   )
231   .execute(conn)
232   .map_err(|e| error!("Failed to clear old received activities: {}", e))
233   .ok();
234 }
235
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(
240     post::table
241       .filter(post::deleted.eq(true))
242       .filter(post::updated.lt(now.nullable() - 1.months()))
243       .filter(post::body.ne(DELETED_REPLACEMENT_TEXT)),
244   )
245   .set((
246     post::body.eq(DELETED_REPLACEMENT_TEXT),
247     post::name.eq(DELETED_REPLACEMENT_TEXT),
248   ))
249   .execute(conn)
250   {
251     Ok(_) => {
252       info!("Done.");
253     }
254     Err(e) => {
255       error!("Failed to overwrite deleted posts: {}", e)
256     }
257   }
258
259   info!("Overwriting deleted comments...");
260   match diesel::update(
261     comment::table
262       .filter(comment::deleted.eq(true))
263       .filter(comment::updated.lt(now.nullable() - 1.months()))
264       .filter(comment::content.ne(DELETED_REPLACEMENT_TEXT)),
265   )
266   .set(comment::content.eq(DELETED_REPLACEMENT_TEXT))
267   .execute(conn)
268   {
269     Ok(_) => {
270       info!("Done.");
271     }
272     Err(e) => {
273       error!("Failed to overwrite deleted comments: {}", e)
274     }
275   }
276 }
277
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 ...");
281
282   let intervals = vec![
283     ("1 day", "day"),
284     ("1 week", "week"),
285     ("1 month", "month"),
286     ("6 months", "half_year"),
287   ];
288
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",
292       i.1, i.0
293     );
294     match sql_query(update_site_stmt).execute(conn) {
295       Ok(_) => {}
296       Err(e) => {
297         error!("Failed to update site stats: {}", e)
298       }
299     }
300
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) {
303       Ok(_) => {}
304       Err(e) => {
305         error!("Failed to update community stats: {}", e)
306       }
307     }
308   }
309
310   info!("Done.");
311 }
312
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 ...");
316
317   match diesel::update(
318     person::table
319       .filter(person::banned.eq(true))
320       .filter(person::ban_expires.lt(now)),
321   )
322   .set(person::banned.eq(false))
323   .execute(conn)
324   {
325     Ok(_) => {}
326     Err(e) => {
327       error!("Failed to update person.banned when expires: {}", e)
328     }
329   }
330   match diesel::delete(community_person_ban::table.filter(community_person_ban::expires.lt(now)))
331     .execute(conn)
332   {
333     Ok(_) => {}
334     Err(e) => {
335       error!("Failed to remove community_ban expired rows: {}", e)
336     }
337   }
338 }
339
340 /// Updates the instance software and version
341 ///
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...");
346
347   let client = Client::builder()
348     .user_agent(user_agent)
349     .timeout(REQWEST_TIMEOUT)
350     .build()?;
351
352   let instances = instance::table.get_results::<Instance>(conn)?;
353
354   for instance in instances {
355     let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
356
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()))
364       .build();
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
368         Some(default_form)
369       }
370       Ok(res) => match res.json::<NodeInfo>() {
371         Ok(node_info) => {
372           // Instance sent valid nodeinfo, write it to db
373           Some(
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())
379               .build(),
380           )
381         }
382         Err(_) => {
383           // No valid nodeinfo but valid HTTP response, consider instance alive
384           Some(default_form)
385         }
386       },
387       Err(_) => {
388         // dead instance, do nothing
389         None
390       }
391     };
392     if let Some(form) = form {
393       diesel::update(instance::table.find(instance.id))
394         .set(form)
395         .execute(conn)?;
396     }
397   }
398   info!("Finished updating instances software and versions...");
399   Ok(())
400 }
401
402 #[cfg(test)]
403 mod tests {
404   use lemmy_routes::nodeinfo::NodeInfo;
405   use reqwest::Client;
406
407   #[tokio::test]
408   #[ignore]
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")
413       .send()
414       .await
415       .unwrap()
416       .json::<NodeInfo>()
417       .await
418       .unwrap();
419
420     assert_eq!(lemmy_ml_nodeinfo.software.unwrap().name.unwrap(), "lemmy");
421   }
422 }