]> Untitled Git - lemmy.git/blob - src/scheduled_tasks.rs
5b1ae419bc11f0918878fd08b368761011da0069
[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 conn = pool.get()?;
15   active_counts(&conn);
16   update_banned_when_expired(&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(&conn, true);
21   scheduler.every(1.hour()).run(move || {
22     active_counts(&conn);
23     update_banned_when_expired(&conn);
24     reindex_aggregates_tables(&conn, true);
25   });
26
27   let conn = pool.get()?;
28   clear_old_activities(&conn);
29   scheduler.every(1.weeks()).run(move || {
30     clear_old_activities(&conn);
31   });
32
33   // Manually run the scheduler in an event loop
34   loop {
35     scheduler.run_pending();
36     thread::sleep(Duration::from_millis(1000));
37   }
38 }
39
40 /// Reindex the aggregates tables every one hour
41 /// This is necessary because hot_rank is actually a mutable function:
42 /// https://dba.stackexchange.com/questions/284052/how-to-create-an-index-based-on-a-time-based-function-in-postgres?noredirect=1#comment555727_284052
43 fn reindex_aggregates_tables(conn: &PgConnection, concurrently: bool) {
44   for table_name in &[
45     "post_aggregates",
46     "comment_aggregates",
47     "community_aggregates",
48   ] {
49     reindex_table(conn, table_name, concurrently);
50   }
51 }
52
53 fn reindex_table(conn: &PgConnection, table_name: &str, concurrently: bool) {
54   let concurrently_str = if concurrently { "concurrently" } else { "" };
55   info!("Reindexing table {} {} ...", concurrently_str, table_name);
56   let query = format!("reindex table {} {}", concurrently_str, table_name);
57   sql_query(query).execute(conn).expect("reindex table");
58   info!("Done.");
59 }
60
61 /// Clear old activities (this table gets very large)
62 fn clear_old_activities(conn: &PgConnection) {
63   info!("Clearing old activities...");
64   Activity::delete_olds(conn).expect("clear old activities");
65   info!("Done.");
66 }
67
68 /// Re-calculate the site and community active counts every 12 hours
69 fn active_counts(conn: &PgConnection) {
70   info!("Updating active site and community aggregates ...");
71
72   let intervals = vec![
73     ("1 day", "day"),
74     ("1 week", "week"),
75     ("1 month", "month"),
76     ("6 months", "half_year"),
77   ];
78
79   for i in &intervals {
80     let update_site_stmt = format!(
81       "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}'))",
82       i.1, i.0
83     );
84     sql_query(update_site_stmt)
85       .execute(conn)
86       .expect("update site stats");
87
88     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);
89     sql_query(update_community_stmt)
90       .execute(conn)
91       .expect("update community stats");
92   }
93
94   info!("Done.");
95 }
96
97 /// Set banned to false after ban expires
98 fn update_banned_when_expired(conn: &PgConnection) {
99   info!("Updating banned column if it expires ...");
100   let update_ban_expires_stmt =
101     "update person set banned = false where banned = true and ban_expires < now()";
102   sql_query(update_ban_expires_stmt)
103     .execute(conn)
104     .expect("update banned when expires");
105 }