]> Untitled Git - lemmy.git/blob - src/scheduled_tasks.rs
Adding instance software and version. Fixes #2222 (#2733)
[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_db_schema::{
6   source::instance::{Instance, InstanceForm},
7   utils::naive_now,
8 };
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};
13 use tracing::info;
14
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();
19
20   let mut conn = PgConnection::establish(&db_url).expect("could not establish connection");
21
22   let mut conn_2 = PgConnection::establish(&db_url).expect("could not establish connection");
23
24   active_counts(&mut conn);
25   update_banned_when_expired(&mut conn);
26
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}"));
33     active_counts(conn);
34     update_banned_when_expired(conn);
35     reindex_aggregates_tables(conn, true);
36     drop_ccnew_indexes(conn);
37   });
38
39   clear_old_activities(&mut conn);
40   scheduler.every(1.weeks()).run(move || {
41     clear_old_activities(&mut conn);
42   });
43
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);
47   });
48
49   // Manually run the scheduler in an event loop
50   loop {
51     scheduler.run_pending();
52     thread::sleep(Duration::from_millis(1000));
53   }
54 }
55
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) {
60   for table_name in &[
61     "post_aggregates",
62     "comment_aggregates",
63     "community_aggregates",
64   ] {
65     reindex_table(conn, table_name, concurrently);
66   }
67 }
68
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");
74   info!("Done.");
75 }
76
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())))
83     .execute(conn)
84     .expect("clear old activities");
85   info!("Done.");
86 }
87
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 ...");
91
92   let intervals = vec![
93     ("1 day", "day"),
94     ("1 week", "week"),
95     ("1 month", "month"),
96     ("6 months", "half_year"),
97   ];
98
99   for i in &intervals {
100     let update_site_stmt = format!(
101       "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}'))",
102       i.1, i.0
103     );
104     sql_query(update_site_stmt)
105       .execute(conn)
106       .expect("update site stats");
107
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)
110       .execute(conn)
111       .expect("update community stats");
112   }
113
114   info!("Done.");
115 }
116
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)
123     .execute(conn)
124     .expect("update banned when expires");
125 }
126
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()";
132   sql_query(drop_stmt)
133     .execute(conn)
134     .expect("drop ccnew indexes");
135 }
136
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...");
141
142   let client = Client::builder()
143     .user_agent(user_agent)
144     .timeout(REQWEST_TIMEOUT)
145     .build()
146     .expect("couldnt build reqwest client");
147
148   let instances = instance::table
149     .get_results::<Instance>(conn)
150     .expect("no instances found");
151
152   for instance in instances {
153     let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
154
155     // Skip it if it can't connect
156     let res = client
157       .get(&node_info_url)
158       .send()
159       .ok()
160       .and_then(|t| t.json::<NodeInfo>().ok());
161
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()))
169         .build();
170
171       diesel::update(instance::table.find(instance.id))
172         .set(form)
173         .execute(conn)
174         .expect("update site instance software");
175     }
176   }
177   info!("Done.");
178 }
179
180 #[cfg(test)]
181 mod tests {
182   use lemmy_routes::nodeinfo::NodeInfo;
183   use reqwest::Client;
184
185   #[tokio::test]
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")
190       .send()
191       .await
192       .unwrap()
193       .json::<NodeInfo>()
194       .await
195       .unwrap();
196
197     assert_eq!(lemmy_ml_nodeinfo.software.unwrap().name.unwrap(), "lemmy");
198   }
199 }