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