]> Untitled Git - lemmy.git/blob - src/scheduled_tasks.rs
Diesel 2.0.0 upgrade (#2452)
[lemmy.git] / src / scheduled_tasks.rs
1 // Scheduler, and trait for .seconds(), .minutes(), etc.
2 use clokwerk::{Scheduler, TimeUnits};
3 // Import week days and WeekDay
4 use diesel::{sql_query, PgConnection, RunQueryDsl};
5 use lemmy_db_schema::{source::activity::Activity, utils::DbPool};
6 use lemmy_utils::error::LemmyError;
7 use std::{thread, time::Duration};
8 use tracing::info;
9
10 /// Schedules various cleanup tasks for lemmy in a background thread
11 pub fn setup(pool: DbPool) -> Result<(), LemmyError> {
12   let mut scheduler = Scheduler::new();
13
14   let mut conn = pool.get()?;
15   active_counts(&mut conn);
16   update_banned_when_expired(&mut conn);
17
18   // On startup, reindex the tables non-concurrently
19   // TODO remove this for now, since it slows down startup a lot on lemmy.ml
20   reindex_aggregates_tables(&mut conn, true);
21   scheduler.every(1.hour()).run(move || {
22     active_counts(&mut conn);
23     update_banned_when_expired(&mut conn);
24     reindex_aggregates_tables(&mut conn, true);
25     drop_ccnew_indexes(&mut conn);
26   });
27
28   let mut conn = pool.get()?;
29   clear_old_activities(&mut conn);
30   scheduler.every(1.weeks()).run(move || {
31     clear_old_activities(&mut conn);
32   });
33
34   // Manually run the scheduler in an event loop
35   loop {
36     scheduler.run_pending();
37     thread::sleep(Duration::from_millis(1000));
38   }
39 }
40
41 /// Reindex the aggregates tables every one hour
42 /// This is necessary because hot_rank is actually a mutable function:
43 /// https://dba.stackexchange.com/questions/284052/how-to-create-an-index-based-on-a-time-based-function-in-postgres?noredirect=1#comment555727_284052
44 fn reindex_aggregates_tables(conn: &mut PgConnection, concurrently: bool) {
45   for table_name in &[
46     "post_aggregates",
47     "comment_aggregates",
48     "community_aggregates",
49   ] {
50     reindex_table(conn, table_name, concurrently);
51   }
52 }
53
54 fn reindex_table(conn: &mut PgConnection, table_name: &str, concurrently: bool) {
55   let concurrently_str = if concurrently { "concurrently" } else { "" };
56   info!("Reindexing table {} {} ...", concurrently_str, table_name);
57   let query = format!("reindex table {} {}", concurrently_str, table_name);
58   sql_query(query).execute(conn).expect("reindex table");
59   info!("Done.");
60 }
61
62 /// Clear old activities (this table gets very large)
63 fn clear_old_activities(conn: &mut PgConnection) {
64   info!("Clearing old activities...");
65   Activity::delete_olds(conn).expect("clear old activities");
66   info!("Done.");
67 }
68
69 /// Re-calculate the site and community active counts every 12 hours
70 fn active_counts(conn: &mut PgConnection) {
71   info!("Updating active site and community aggregates ...");
72
73   let intervals = vec![
74     ("1 day", "day"),
75     ("1 week", "week"),
76     ("1 month", "month"),
77     ("6 months", "half_year"),
78   ];
79
80   for i in &intervals {
81     let update_site_stmt = format!(
82       "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}'))",
83       i.1, i.0
84     );
85     sql_query(update_site_stmt)
86       .execute(conn)
87       .expect("update site stats");
88
89     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);
90     sql_query(update_community_stmt)
91       .execute(conn)
92       .expect("update community stats");
93   }
94
95   info!("Done.");
96 }
97
98 /// Set banned to false after ban expires
99 fn update_banned_when_expired(conn: &mut PgConnection) {
100   info!("Updating banned column if it expires ...");
101   let update_ban_expires_stmt =
102     "update person set banned = false where banned = true and ban_expires < now()";
103   sql_query(update_ban_expires_stmt)
104     .execute(conn)
105     .expect("update banned when expires");
106 }
107
108 /// Drops the phantom CCNEW indexes created by postgres
109 /// https://github.com/LemmyNet/lemmy/issues/2431
110 fn drop_ccnew_indexes(conn: &mut PgConnection) {
111   info!("Dropping phantom ccnew indexes...");
112   let drop_stmt = "select drop_ccnew_indexes()";
113   sql_query(drop_stmt)
114     .execute(conn)
115     .expect("drop ccnew indexes");
116 }