1 use clokwerk::{Scheduler, TimeUnits};
2 // Import week days and WeekDay
3 use diesel::{sql_query, PgConnection, RunQueryDsl};
4 use diesel::{Connection, ExpressionMethods, QueryDsl};
6 source::instance::{Instance, InstanceForm},
9 use lemmy_routes::nodeinfo::NodeInfo;
10 use lemmy_utils::{error::LemmyError, REQWEST_TIMEOUT};
11 use reqwest::blocking::Client;
12 use std::{thread, time::Duration};
15 /// Schedules various cleanup tasks for lemmy in a background thread
16 pub fn setup(db_url: String, user_agent: String) -> Result<(), LemmyError> {
17 // Setup the connections
18 let mut scheduler = Scheduler::new();
20 let mut conn = PgConnection::establish(&db_url).expect("could not establish connection");
22 let mut conn_2 = PgConnection::establish(&db_url).expect("could not establish connection");
24 active_counts(&mut conn);
25 update_banned_when_expired(&mut conn);
27 // On startup, reindex the tables non-concurrently
28 // TODO remove this for now, since it slows down startup a lot on lemmy.ml
29 reindex_aggregates_tables(&mut conn, true);
30 scheduler.every(1.hour()).run(move || {
31 let conn = &mut PgConnection::establish(&db_url)
32 .unwrap_or_else(|_| panic!("Error connecting to {db_url}"));
34 update_banned_when_expired(conn);
35 reindex_aggregates_tables(conn, true);
36 drop_ccnew_indexes(conn);
39 clear_old_activities(&mut conn);
40 scheduler.every(1.weeks()).run(move || {
41 clear_old_activities(&mut conn);
44 update_instance_software(&mut conn_2, &user_agent);
45 scheduler.every(1.days()).run(move || {
46 update_instance_software(&mut conn_2, &user_agent);
49 // Manually run the scheduler in an event loop
51 scheduler.run_pending();
52 thread::sleep(Duration::from_millis(1000));
56 /// Reindex the aggregates tables every one hour
57 /// This is necessary because hot_rank is actually a mutable function:
58 /// https://dba.stackexchange.com/questions/284052/how-to-create-an-index-based-on-a-time-based-function-in-postgres?noredirect=1#comment555727_284052
59 fn reindex_aggregates_tables(conn: &mut PgConnection, concurrently: bool) {
63 "community_aggregates",
65 reindex_table(conn, table_name, concurrently);
69 fn reindex_table(conn: &mut PgConnection, table_name: &str, concurrently: bool) {
70 let concurrently_str = if concurrently { "concurrently" } else { "" };
71 info!("Reindexing table {} {} ...", concurrently_str, table_name);
72 let query = format!("reindex table {concurrently_str} {table_name}");
73 sql_query(query).execute(conn).expect("reindex table");
77 /// Clear old activities (this table gets very large)
78 fn clear_old_activities(conn: &mut PgConnection) {
79 use diesel::dsl::{now, IntervalDsl};
80 use lemmy_db_schema::schema::activity::dsl::{activity, published};
81 info!("Clearing old activities...");
82 diesel::delete(activity.filter(published.lt(now - 6.months())))
84 .expect("clear old activities");
88 /// Re-calculate the site and community active counts every 12 hours
89 fn active_counts(conn: &mut PgConnection) {
90 info!("Updating active site and community aggregates ...");
96 ("6 months", "half_year"),
100 let update_site_stmt = format!(
101 "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}'))",
104 sql_query(update_site_stmt)
106 .expect("update site stats");
108 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);
109 sql_query(update_community_stmt)
111 .expect("update community stats");
117 /// Set banned to false after ban expires
118 fn update_banned_when_expired(conn: &mut PgConnection) {
119 info!("Updating banned column if it expires ...");
120 let update_ban_expires_stmt =
121 "update person set banned = false where banned = true and ban_expires < now()";
122 sql_query(update_ban_expires_stmt)
124 .expect("update banned when expires");
127 /// Drops the phantom CCNEW indexes created by postgres
128 /// https://github.com/LemmyNet/lemmy/issues/2431
129 fn drop_ccnew_indexes(conn: &mut PgConnection) {
130 info!("Dropping phantom ccnew indexes...");
131 let drop_stmt = "select drop_ccnew_indexes()";
134 .expect("drop ccnew indexes");
137 /// Updates the instance software and version
138 fn update_instance_software(conn: &mut PgConnection, user_agent: &str) {
139 use lemmy_db_schema::schema::instance;
140 info!("Updating instances software and versions...");
142 let client = Client::builder()
143 .user_agent(user_agent)
144 .timeout(REQWEST_TIMEOUT)
146 .expect("couldnt build reqwest client");
148 let instances = instance::table
149 .get_results::<Instance>(conn)
150 .expect("no instances found");
152 for instance in instances {
153 let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
155 // Skip it if it can't connect
160 .and_then(|t| t.json::<NodeInfo>().ok());
162 if let Some(node_info) = res {
163 let software = node_info.software.as_ref();
164 let form = InstanceForm::builder()
165 .domain(instance.domain)
166 .software(software.and_then(|s| s.name.clone()))
167 .version(software.and_then(|s| s.version.clone()))
168 .updated(Some(naive_now()))
171 diesel::update(instance::table.find(instance.id))
174 .expect("update site instance software");
182 use lemmy_routes::nodeinfo::NodeInfo;
186 async fn test_nodeinfo() {
187 let client = Client::builder().build().unwrap();
188 let lemmy_ml_nodeinfo = client
189 .get("https://lemmy.ml/nodeinfo/2.0.json")
197 assert_eq!(lemmy_ml_nodeinfo.software.unwrap().name.unwrap(), "lemmy");