]> Untitled Git - lemmy.git/blob - src/scheduled_tasks.rs
Split activity table into sent and received parts (fixes #3103) (#3583)
[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, true);
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, false);
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, last_week_only: bool) {
119   let process_start_time = if last_week_only {
120     info!("Updating hot ranks for last week...");
121     naive_now() - chrono::Duration::days(7)
122   } else {
123     info!("Updating hot ranks for all history...");
124     NaiveDateTime::from_timestamp_opt(0, 0).expect("0 timestamp creation")
125   };
126
127   process_hot_ranks_in_batches(
128     conn,
129     "post_aggregates",
130     "SET hot_rank = hot_rank(a.score, a.published),
131          hot_rank_active = hot_rank(a.score, a.newest_comment_time_necro)",
132     process_start_time,
133   );
134
135   process_hot_ranks_in_batches(
136     conn,
137     "comment_aggregates",
138     "SET hot_rank = hot_rank(a.score, a.published)",
139     process_start_time,
140   );
141
142   process_hot_ranks_in_batches(
143     conn,
144     "community_aggregates",
145     "SET hot_rank = hot_rank(a.subscribers, a.published)",
146     process_start_time,
147   );
148
149   info!("Finished hot ranks update!");
150 }
151
152 #[derive(QueryableByName)]
153 struct HotRanksUpdateResult {
154   #[diesel(sql_type = Timestamp)]
155   published: NaiveDateTime,
156 }
157
158 /// Runs the hot rank update query in batches until all rows after `process_start_time` have been
159 /// processed.
160 /// In `set_clause`, "a" will refer to the current aggregates table.
161 /// Locked rows are skipped in order to prevent deadlocks (they will likely get updated on the next
162 /// run)
163 fn process_hot_ranks_in_batches(
164   conn: &mut PgConnection,
165   table_name: &str,
166   set_clause: &str,
167   process_start_time: NaiveDateTime,
168 ) {
169   let update_batch_size = 1000; // Bigger batches than this tend to cause seq scans
170   let mut previous_batch_result = Some(process_start_time);
171   while let Some(previous_batch_last_published) = previous_batch_result {
172     // Raw `sql_query` is used as a performance optimization - Diesel does not support doing this
173     // in a single query (neither as a CTE, nor using a subquery)
174     let result = sql_query(format!(
175       r#"WITH batch AS (SELECT a.id
176                FROM {aggregates_table} a
177                WHERE a.published > $1
178                ORDER BY a.published
179                LIMIT $2
180                FOR UPDATE SKIP LOCKED)
181          UPDATE {aggregates_table} a {set_clause}
182              FROM batch WHERE a.id = batch.id RETURNING a.published;
183     "#,
184       aggregates_table = table_name,
185       set_clause = set_clause
186     ))
187     .bind::<Timestamp, _>(previous_batch_last_published)
188     .bind::<Integer, _>(update_batch_size)
189     .get_results::<HotRanksUpdateResult>(conn);
190
191     match result {
192       Ok(updated_rows) => previous_batch_result = updated_rows.last().map(|row| row.published),
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 {}",
201     table_name
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 }