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};
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();
14 let mut conn = PgConnection::establish(&db_url).expect("could not establish connection");
16 active_counts(&mut conn);
17 update_banned_when_expired(&mut conn);
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}"));
26 update_banned_when_expired(conn);
27 reindex_aggregates_tables(conn, true);
28 drop_ccnew_indexes(conn);
31 clear_old_activities(&mut conn);
32 scheduler.every(1.weeks()).run(move || {
33 clear_old_activities(&mut conn);
36 // Manually run the scheduler in an event loop
38 scheduler.run_pending();
39 thread::sleep(Duration::from_millis(1000));
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) {
50 "community_aggregates",
52 reindex_table(conn, table_name, concurrently);
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");
64 /// Clear old activities (this table gets very large)
65 fn clear_old_activities(conn: &mut PgConnection) {
66 use diesel::dsl::{now, IntervalDsl};
67 use lemmy_db_schema::schema::activity::dsl::{activity, published};
68 info!("Clearing old activities...");
69 diesel::delete(activity.filter(published.lt(now - 6.months())))
71 .expect("clear old activities");
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 ...");
83 ("6 months", "half_year"),
87 let update_site_stmt = format!(
88 "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}'))",
91 sql_query(update_site_stmt)
93 .expect("update site stats");
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)
98 .expect("update community stats");
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)
111 .expect("update banned when expires");
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()";
121 .expect("drop ccnew indexes");