1 use clokwerk::{Scheduler, TimeUnits as CTimeUnits};
3 dsl::{now, IntervalDsl},
8 // Import week days and WeekDay
9 use diesel::{sql_query, PgConnection, RunQueryDsl};
10 use lemmy_db_schema::{
20 source::instance::{Instance, InstanceForm},
21 utils::{functions::hot_rank, naive_now},
23 use lemmy_routes::nodeinfo::NodeInfo;
24 use lemmy_utils::{error::LemmyError, REQWEST_TIMEOUT};
25 use reqwest::blocking::Client;
26 use std::{thread, time::Duration};
27 use tracing::{error, info};
29 /// Schedules various cleanup tasks for lemmy in a background thread
30 pub fn setup(db_url: String, user_agent: String) -> Result<(), LemmyError> {
31 // Setup the connections
32 let mut scheduler = Scheduler::new();
34 let mut conn_1 = PgConnection::establish(&db_url).expect("could not establish connection");
35 let mut conn_2 = PgConnection::establish(&db_url).expect("could not establish connection");
36 let mut conn_3 = PgConnection::establish(&db_url).expect("could not establish connection");
37 let mut conn_4 = PgConnection::establish(&db_url).expect("could not establish connection");
40 active_counts(&mut conn_1);
41 update_hot_ranks(&mut conn_1, false);
42 update_banned_when_expired(&mut conn_1);
43 clear_old_activities(&mut conn_1);
45 // Update active counts every hour
46 scheduler.every(CTimeUnits::hour(1)).run(move || {
47 active_counts(&mut conn_1);
48 update_banned_when_expired(&mut conn_1);
51 // Update hot ranks every 5 minutes
52 scheduler.every(CTimeUnits::minutes(5)).run(move || {
53 update_hot_ranks(&mut conn_2, true);
56 // Clear old activities every week
57 scheduler.every(CTimeUnits::weeks(1)).run(move || {
58 clear_old_activities(&mut conn_3);
61 scheduler.every(CTimeUnits::days(1)).run(move || {
62 update_instance_software(&mut conn_4, &user_agent);
65 // Manually run the scheduler in an event loop
67 scheduler.run_pending();
68 thread::sleep(Duration::from_millis(1000));
72 /// Update the hot_rank columns for the aggregates tables
73 fn update_hot_ranks(conn: &mut PgConnection, last_week_only: bool) {
74 let mut post_update = diesel::update(post_aggregates::table).into_boxed();
75 let mut comment_update = diesel::update(comment_aggregates::table).into_boxed();
76 let mut community_update = diesel::update(community_aggregates::table).into_boxed();
78 // Only update for the last week of content
80 info!("Updating hot ranks for last week...");
81 let last_week = now - diesel::dsl::IntervalDsl::weeks(1);
83 post_update = post_update.filter(post_aggregates::published.gt(last_week));
84 comment_update = comment_update.filter(comment_aggregates::published.gt(last_week));
85 community_update = community_update.filter(community_aggregates::published.gt(last_week));
87 info!("Updating hot ranks for all history...");
92 post_aggregates::hot_rank.eq(hot_rank(post_aggregates::score, post_aggregates::published)),
93 post_aggregates::hot_rank_active.eq(hot_rank(
94 post_aggregates::score,
95 post_aggregates::newest_comment_time_necro,
102 error!("Failed to update post_aggregates hot_ranks: {}", e)
107 .set(comment_aggregates::hot_rank.eq(hot_rank(
108 comment_aggregates::score,
109 comment_aggregates::published,
115 error!("Failed to update comment_aggregates hot_ranks: {}", e)
119 match community_update
120 .set(community_aggregates::hot_rank.eq(hot_rank(
121 community_aggregates::subscribers,
122 community_aggregates::published,
130 error!("Failed to update community_aggregates hot_ranks: {}", e)
135 /// Clear old activities (this table gets very large)
136 fn clear_old_activities(conn: &mut PgConnection) {
137 info!("Clearing old activities...");
138 match diesel::delete(activity::table.filter(activity::published.lt(now - 6.months())))
145 error!("Failed to clear old activities: {}", e)
150 /// Re-calculate the site and community active counts every 12 hours
151 fn active_counts(conn: &mut PgConnection) {
152 info!("Updating active site and community aggregates ...");
154 let intervals = vec![
157 ("1 month", "month"),
158 ("6 months", "half_year"),
161 for i in &intervals {
162 let update_site_stmt = format!(
163 "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}'))",
166 match sql_query(update_site_stmt).execute(conn) {
169 error!("Failed to update site stats: {}", e)
173 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);
174 match sql_query(update_community_stmt).execute(conn) {
177 error!("Failed to update community stats: {}", e)
185 /// Set banned to false after ban expires
186 fn update_banned_when_expired(conn: &mut PgConnection) {
187 info!("Updating banned column if it expires ...");
189 match diesel::update(
191 .filter(person::banned.eq(true))
192 .filter(person::ban_expires.lt(now)),
194 .set(person::banned.eq(false))
199 error!("Failed to update person.banned when expires: {}", e)
202 match diesel::delete(community_person_ban::table.filter(community_person_ban::expires.lt(now)))
207 error!("Failed to remove community_ban expired rows: {}", e)
212 /// Updates the instance software and version
213 fn update_instance_software(conn: &mut PgConnection, user_agent: &str) {
214 info!("Updating instances software and versions...");
216 let client = match Client::builder()
217 .user_agent(user_agent)
218 .timeout(REQWEST_TIMEOUT)
221 Ok(client) => client,
223 error!("Failed to build reqwest client: {}", e);
228 let instances = match instance::table.get_results::<Instance>(conn) {
229 Ok(instances) => instances,
231 error!("Failed to get instances: {}", e);
236 for instance in instances {
237 let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
239 // Skip it if it can't connect
244 .and_then(|t| t.json::<NodeInfo>().ok());
246 if let Some(node_info) = res {
247 let software = node_info.software.as_ref();
248 let form = InstanceForm::builder()
249 .domain(instance.domain)
250 .software(software.and_then(|s| s.name.clone()))
251 .version(software.and_then(|s| s.version.clone()))
252 .updated(Some(naive_now()))
255 match diesel::update(instance::table.find(instance.id))
263 error!("Failed to update site instance software: {}", e);
273 use lemmy_routes::nodeinfo::NodeInfo;
278 async fn test_nodeinfo() {
279 let client = Client::builder().build().unwrap();
280 let lemmy_ml_nodeinfo = client
281 .get("https://lemmy.ml/nodeinfo/2.0.json")
289 assert_eq!(lemmy_ml_nodeinfo.software.unwrap().name.unwrap(), "lemmy");