Async scheduler (#3949)

* fix: switch to async scheduler

* fix: pass context to scheduled tasks

* Merge remote-tracking branch 'upstream/main' into async-scheduler

* retrigger ci

* retrigger ci
This commit is contained in:
Alex Roman 2023-09-11 10:12:16 +01:00 committed by GitHub
parent 375d9a2a3c
commit 6735a98d35
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 302 additions and 257 deletions

View file

@ -54,7 +54,7 @@ use lemmy_utils::{
use reqwest::Client; use reqwest::Client;
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware}; use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use reqwest_tracing::TracingMiddleware; use reqwest_tracing::TracingMiddleware;
use std::{env, ops::Deref, thread, time::Duration}; use std::{env, ops::Deref, time::Duration};
use tokio::signal::unix::SignalKind; use tokio::signal::unix::SignalKind;
use tracing::subscriber::set_global_default; use tracing::subscriber::set_global_default;
use tracing_actix_web::TracingLogger; use tracing_actix_web::TracingLogger;
@ -181,13 +181,7 @@ pub async fn start_lemmy_server(args: CmdArgs) -> Result<(), LemmyError> {
if scheduled_tasks_enabled { if scheduled_tasks_enabled {
// Schedules various cleanup tasks for the DB // Schedules various cleanup tasks for the DB
thread::spawn({ let _scheduled_tasks = tokio::task::spawn(scheduled_tasks::setup(context.clone()));
let context = context.clone();
move || {
scheduled_tasks::setup(db_url, user_agent, context)
.expect("Couldn't set up scheduled_tasks");
}
});
} }
#[cfg(feature = "prometheus-metrics")] #[cfg(feature = "prometheus-metrics")]

View file

@ -1,16 +1,15 @@
use chrono::{DateTime, TimeZone, Utc}; use chrono::{DateTime, TimeZone, Utc};
use clokwerk::{Scheduler, TimeUnits as CTimeUnits}; use clokwerk::{AsyncScheduler, TimeUnits as CTimeUnits};
use diesel::{ use diesel::{
dsl::IntervalDsl, dsl::IntervalDsl,
sql_query,
sql_types::{Integer, Timestamptz}, sql_types::{Integer, Timestamptz},
Connection,
ExpressionMethods, ExpressionMethods,
NullableExpressionMethods, NullableExpressionMethods,
QueryDsl, QueryDsl,
QueryableByName, QueryableByName,
}; };
// Import week days and WeekDay use diesel_async::{AsyncPgConnection, RunQueryDsl};
use diesel::{sql_query, PgConnection, RunQueryDsl};
use lemmy_api_common::context::LemmyContext; use lemmy_api_common::context::LemmyContext;
use lemmy_db_schema::{ use lemmy_db_schema::{
schema::{ schema::{
@ -24,153 +23,144 @@ use lemmy_db_schema::{
sent_activity, sent_activity,
}, },
source::instance::{Instance, InstanceForm}, source::instance::{Instance, InstanceForm},
utils::{naive_now, now, DELETED_REPLACEMENT_TEXT}, utils::{get_conn, naive_now, now, DbPool, DELETED_REPLACEMENT_TEXT},
}; };
use lemmy_routes::nodeinfo::NodeInfo; use lemmy_routes::nodeinfo::NodeInfo;
use lemmy_utils::{ use lemmy_utils::error::{LemmyError, LemmyResult};
error::{LemmyError, LemmyResult}, use reqwest_middleware::ClientWithMiddleware;
REQWEST_TIMEOUT, use std::time::Duration;
};
use reqwest::blocking::Client;
use std::{thread, time::Duration};
use tracing::{error, info, warn}; use tracing::{error, info, warn};
/// Schedules various cleanup tasks for lemmy in a background thread /// Schedules various cleanup tasks for lemmy in a background thread
pub fn setup( pub async fn setup(context: LemmyContext) -> Result<(), LemmyError> {
db_url: String,
user_agent: String,
context_1: LemmyContext,
) -> Result<(), LemmyError> {
// Setup the connections // Setup the connections
let mut scheduler = Scheduler::new(); let mut scheduler = AsyncScheduler::new();
startup_jobs(&mut context.pool()).await;
startup_jobs(&db_url);
let context_1 = context.clone();
// Update active counts every hour // Update active counts every hour
let url = db_url.clone();
scheduler.every(CTimeUnits::hour(1)).run(move || { scheduler.every(CTimeUnits::hour(1)).run(move || {
PgConnection::establish(&url) let context = context_1.clone();
.map(|mut conn| {
active_counts(&mut conn); async move {
update_banned_when_expired(&mut conn); active_counts(&mut context.pool()).await;
}) update_banned_when_expired(&mut context.pool()).await;
.map_err(|e| { }
error!("Failed to establish db connection for active counts update: {e}");
})
.ok();
}); });
let context_1 = context.clone();
// Update hot ranks every 15 minutes // Update hot ranks every 15 minutes
let url = db_url.clone();
scheduler.every(CTimeUnits::minutes(15)).run(move || {
PgConnection::establish(&url)
.map(|mut conn| {
update_hot_ranks(&mut conn);
})
.map_err(|e| {
error!("Failed to establish db connection for hot ranks update: {e}");
})
.ok();
});
// Delete any captcha answers older than ten minutes, every ten minutes
let url = db_url.clone();
scheduler.every(CTimeUnits::minutes(10)).run(move || { scheduler.every(CTimeUnits::minutes(10)).run(move || {
PgConnection::establish(&url) let context = context_1.clone();
.map(|mut conn| {
delete_expired_captcha_answers(&mut conn); async move {
}) update_hot_ranks(&mut context.pool()).await;
.map_err(|e| { }
error!("Failed to establish db connection for captcha cleanup: {e}");
})
.ok();
}); });
let context_1 = context.clone();
// Delete any captcha answers older than ten minutes, every ten minutes
scheduler.every(CTimeUnits::minutes(10)).run(move || {
let context = context_1.clone();
async move {
delete_expired_captcha_answers(&mut context.pool()).await;
}
});
let context_1 = context.clone();
// Clear old activities every week // Clear old activities every week
let url = db_url.clone();
scheduler.every(CTimeUnits::weeks(1)).run(move || { scheduler.every(CTimeUnits::weeks(1)).run(move || {
PgConnection::establish(&url) let context = context_1.clone();
.map(|mut conn| {
clear_old_activities(&mut conn); async move {
}) clear_old_activities(&mut context.pool()).await;
.map_err(|e| { }
error!("Failed to establish db connection for activity cleanup: {e}");
})
.ok();
}); });
let context_1 = context.clone();
// Remove old rate limit buckets after 1 to 2 hours of inactivity // Remove old rate limit buckets after 1 to 2 hours of inactivity
scheduler.every(CTimeUnits::hour(1)).run(move || { scheduler.every(CTimeUnits::hour(1)).run(move || {
let context = context_1.clone();
async move {
let hour = Duration::from_secs(3600); let hour = Duration::from_secs(3600);
context_1.settings_updated_channel().remove_older_than(hour); context.settings_updated_channel().remove_older_than(hour);
}
}); });
let context_1 = context.clone();
// Overwrite deleted & removed posts and comments every day // Overwrite deleted & removed posts and comments every day
let url = db_url.clone();
scheduler.every(CTimeUnits::days(1)).run(move || { scheduler.every(CTimeUnits::days(1)).run(move || {
PgConnection::establish(&db_url) let context = context_1.clone();
.map(|mut conn| {
overwrite_deleted_posts_and_comments(&mut conn); async move {
}) overwrite_deleted_posts_and_comments(&mut context.pool()).await;
.map_err(|e| { }
error!("Failed to establish db connection for deleted content cleanup: {e}");
})
.ok();
}); });
let context_1 = context.clone();
// Update the Instance Software // Update the Instance Software
scheduler.every(CTimeUnits::days(1)).run(move || { scheduler.every(CTimeUnits::days(1)).run(move || {
PgConnection::establish(&url) let context = context_1.clone();
.map(|mut conn| {
update_instance_software(&mut conn, &user_agent) async move {
update_instance_software(&mut context.pool(), context.client())
.await
.map_err(|e| warn!("Failed to update instance software: {e}")) .map_err(|e| warn!("Failed to update instance software: {e}"))
.ok(); .ok();
}) }
.map_err(|e| {
error!("Failed to establish db connection for instance software update: {e}");
})
.ok();
}); });
// Manually run the scheduler in an event loop // Manually run the scheduler in an event loop
loop { loop {
scheduler.run_pending(); scheduler.run_pending().await;
thread::sleep(Duration::from_millis(1000)); tokio::time::sleep(Duration::from_millis(1000)).await;
} }
} }
/// Run these on server startup /// Run these on server startup
fn startup_jobs(db_url: &str) { async fn startup_jobs(pool: &mut DbPool<'_>) {
let mut conn = PgConnection::establish(db_url).expect("could not establish connection"); active_counts(pool).await;
active_counts(&mut conn); update_hot_ranks(pool).await;
update_hot_ranks(&mut conn); update_banned_when_expired(pool).await;
update_banned_when_expired(&mut conn); clear_old_activities(pool).await;
clear_old_activities(&mut conn); overwrite_deleted_posts_and_comments(pool).await;
overwrite_deleted_posts_and_comments(&mut conn);
} }
/// Update the hot_rank columns for the aggregates tables /// Update the hot_rank columns for the aggregates tables
/// Runs in batches until all necessary rows are updated once /// Runs in batches until all necessary rows are updated once
fn update_hot_ranks(conn: &mut PgConnection) { async fn update_hot_ranks(pool: &mut DbPool<'_>) {
info!("Updating hot ranks for all history..."); info!("Updating hot ranks for all history...");
process_post_aggregates_ranks_in_batches(conn); let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
process_post_aggregates_ranks_in_batches(&mut conn).await;
process_ranks_in_batches( process_ranks_in_batches(
conn, &mut conn,
"comment_aggregates", "comment_aggregates",
"a.hot_rank != 0", "a.hot_rank != 0",
"SET hot_rank = hot_rank(a.score, a.published)", "SET hot_rank = hot_rank(a.score, a.published)",
); )
.await;
process_ranks_in_batches( process_ranks_in_batches(
conn, &mut conn,
"community_aggregates", "community_aggregates",
"a.hot_rank != 0", "a.hot_rank != 0",
"SET hot_rank = hot_rank(a.subscribers, a.published)", "SET hot_rank = hot_rank(a.subscribers, a.published)",
); )
.await;
info!("Finished hot ranks update!"); info!("Finished hot ranks update!");
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
#[derive(QueryableByName)] #[derive(QueryableByName)]
@ -183,8 +173,8 @@ struct HotRanksUpdateResult {
/// In `where_clause` and `set_clause`, "a" will refer to the current aggregates table. /// In `where_clause` and `set_clause`, "a" will refer to the current aggregates table.
/// Locked rows are skipped in order to prevent deadlocks (they will likely get updated on the next /// Locked rows are skipped in order to prevent deadlocks (they will likely get updated on the next
/// run) /// run)
fn process_ranks_in_batches( async fn process_ranks_in_batches(
conn: &mut PgConnection, conn: &mut AsyncPgConnection,
table_name: &str, table_name: &str,
where_clause: &str, where_clause: &str,
set_clause: &str, set_clause: &str,
@ -216,7 +206,8 @@ fn process_ranks_in_batches(
)) ))
.bind::<Timestamptz, _>(previous_batch_last_published) .bind::<Timestamptz, _>(previous_batch_last_published)
.bind::<Integer, _>(update_batch_size) .bind::<Integer, _>(update_batch_size)
.get_results::<HotRanksUpdateResult>(conn); .get_results::<HotRanksUpdateResult>(conn)
.await;
match result { match result {
Ok(updated_rows) => { Ok(updated_rows) => {
@ -237,7 +228,7 @@ fn process_ranks_in_batches(
/// Post aggregates is a special case, since it needs to join to the community_aggregates /// Post aggregates is a special case, since it needs to join to the community_aggregates
/// table, to get the active monthly user counts. /// table, to get the active monthly user counts.
fn process_post_aggregates_ranks_in_batches(conn: &mut PgConnection) { async fn process_post_aggregates_ranks_in_batches(conn: &mut AsyncPgConnection) {
let process_start_time: DateTime<Utc> = Utc let process_start_time: DateTime<Utc> = Utc
.timestamp_opt(0, 0) .timestamp_opt(0, 0)
.single() .single()
@ -265,7 +256,8 @@ fn process_post_aggregates_ranks_in_batches(conn: &mut PgConnection) {
) )
.bind::<Timestamptz, _>(previous_batch_last_published) .bind::<Timestamptz, _>(previous_batch_last_published)
.bind::<Integer, _>(update_batch_size) .bind::<Integer, _>(update_batch_size)
.get_results::<HotRanksUpdateResult>(conn); .get_results::<HotRanksUpdateResult>(conn)
.await;
match result { match result {
Ok(updated_rows) => { Ok(updated_rows) => {
@ -284,38 +276,64 @@ fn process_post_aggregates_ranks_in_batches(conn: &mut PgConnection) {
); );
} }
fn delete_expired_captcha_answers(conn: &mut PgConnection) { async fn delete_expired_captcha_answers(pool: &mut DbPool<'_>) {
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
diesel::delete( diesel::delete(
captcha_answer::table.filter(captcha_answer::published.lt(now() - IntervalDsl::minutes(10))), captcha_answer::table
.filter(captcha_answer::published.lt(now() - IntervalDsl::minutes(10))),
) )
.execute(conn) .execute(&mut conn)
.await
.map(|_| { .map(|_| {
info!("Done."); info!("Done.");
}) })
.map_err(|e| error!("Failed to clear old captcha answers: {e}")) .map_err(|e| error!("Failed to clear old captcha answers: {e}"))
.ok(); .ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// Clear old activities (this table gets very large) /// Clear old activities (this table gets very large)
fn clear_old_activities(conn: &mut PgConnection) { async fn clear_old_activities(pool: &mut DbPool<'_>) {
info!("Clearing old activities..."); info!("Clearing old activities...");
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
diesel::delete(sent_activity::table.filter(sent_activity::published.lt(now() - 3.months()))) diesel::delete(sent_activity::table.filter(sent_activity::published.lt(now() - 3.months())))
.execute(conn) .execute(&mut conn)
.await
.map_err(|e| error!("Failed to clear old sent activities: {e}")) .map_err(|e| error!("Failed to clear old sent activities: {e}"))
.ok(); .ok();
diesel::delete( diesel::delete(
received_activity::table.filter(received_activity::published.lt(now() - 3.months())), received_activity::table.filter(received_activity::published.lt(now() - 3.months())),
) )
.execute(conn) .execute(&mut conn)
.await
.map(|_| info!("Done.")) .map(|_| info!("Done."))
.map_err(|e| error!("Failed to clear old received activities: {e}")) .map_err(|e| error!("Failed to clear old received activities: {e}"))
.ok(); .ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// overwrite posts and comments 30d after deletion /// overwrite posts and comments 30d after deletion
fn overwrite_deleted_posts_and_comments(conn: &mut PgConnection) { async fn overwrite_deleted_posts_and_comments(pool: &mut DbPool<'_>) {
info!("Overwriting deleted posts..."); info!("Overwriting deleted posts...");
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
diesel::update( diesel::update(
post::table post::table
.filter(post::deleted.eq(true)) .filter(post::deleted.eq(true))
@ -326,7 +344,8 @@ fn overwrite_deleted_posts_and_comments(conn: &mut PgConnection) {
post::body.eq(DELETED_REPLACEMENT_TEXT), post::body.eq(DELETED_REPLACEMENT_TEXT),
post::name.eq(DELETED_REPLACEMENT_TEXT), post::name.eq(DELETED_REPLACEMENT_TEXT),
)) ))
.execute(conn) .execute(&mut conn)
.await
.map(|_| { .map(|_| {
info!("Done."); info!("Done.");
}) })
@ -341,18 +360,28 @@ fn overwrite_deleted_posts_and_comments(conn: &mut PgConnection) {
.filter(comment::content.ne(DELETED_REPLACEMENT_TEXT)), .filter(comment::content.ne(DELETED_REPLACEMENT_TEXT)),
) )
.set(comment::content.eq(DELETED_REPLACEMENT_TEXT)) .set(comment::content.eq(DELETED_REPLACEMENT_TEXT))
.execute(conn) .execute(&mut conn)
.await
.map(|_| { .map(|_| {
info!("Done."); info!("Done.");
}) })
.map_err(|e| error!("Failed to overwrite deleted comments: {e}")) .map_err(|e| error!("Failed to overwrite deleted comments: {e}"))
.ok(); .ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// Re-calculate the site and community active counts every 12 hours /// Re-calculate the site and community active counts every 12 hours
fn active_counts(conn: &mut PgConnection) { async fn active_counts(pool: &mut DbPool<'_>) {
info!("Updating active site and community aggregates ..."); info!("Updating active site and community aggregates ...");
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
let intervals = vec![ let intervals = vec![
("1 day", "day"), ("1 day", "day"),
("1 week", "week"), ("1 week", "week"),
@ -366,56 +395,72 @@ fn active_counts(conn: &mut PgConnection) {
i.1, i.0 i.1, i.0
); );
sql_query(update_site_stmt) sql_query(update_site_stmt)
.execute(conn) .execute(&mut conn)
.await
.map_err(|e| error!("Failed to update site stats: {e}")) .map_err(|e| error!("Failed to update site stats: {e}"))
.ok(); .ok();
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); 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);
sql_query(update_community_stmt) sql_query(update_community_stmt)
.execute(conn) .execute(&mut conn)
.await
.map_err(|e| error!("Failed to update community stats: {e}")) .map_err(|e| error!("Failed to update community stats: {e}"))
.ok(); .ok();
} }
info!("Done."); info!("Done.");
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// Set banned to false after ban expires /// Set banned to false after ban expires
fn update_banned_when_expired(conn: &mut PgConnection) { async fn update_banned_when_expired(pool: &mut DbPool<'_>) {
info!("Updating banned column if it expires ..."); info!("Updating banned column if it expires ...");
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
diesel::update( diesel::update(
person::table person::table
.filter(person::banned.eq(true)) .filter(person::banned.eq(true))
.filter(person::ban_expires.lt(now().nullable())), .filter(person::ban_expires.lt(now().nullable())),
) )
.set(person::banned.eq(false)) .set(person::banned.eq(false))
.execute(conn) .execute(&mut conn)
.await
.map_err(|e| error!("Failed to update person.banned when expires: {e}")) .map_err(|e| error!("Failed to update person.banned when expires: {e}"))
.ok(); .ok();
diesel::delete( diesel::delete(
community_person_ban::table.filter(community_person_ban::expires.lt(now().nullable())), community_person_ban::table.filter(community_person_ban::expires.lt(now().nullable())),
) )
.execute(conn) .execute(&mut conn)
.await
.map_err(|e| error!("Failed to remove community_ban expired rows: {e}")) .map_err(|e| error!("Failed to remove community_ban expired rows: {e}"))
.ok(); .ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// Updates the instance software and version /// Updates the instance software and version
/// ///
/// TODO: this should be async
/// TODO: if instance has been dead for a long time, it should be checked less frequently /// TODO: if instance has been dead for a long time, it should be checked less frequently
fn update_instance_software(conn: &mut PgConnection, user_agent: &str) -> LemmyResult<()> { async fn update_instance_software(
pool: &mut DbPool<'_>,
client: &ClientWithMiddleware,
) -> LemmyResult<()> {
info!("Updating instances software and versions..."); info!("Updating instances software and versions...");
let conn = get_conn(pool).await;
let client = Client::builder() match conn {
.user_agent(user_agent) Ok(mut conn) => {
.timeout(REQWEST_TIMEOUT) let instances = instance::table.get_results::<Instance>(&mut conn).await?;
.connect_timeout(REQWEST_TIMEOUT)
.build()?;
let instances = instance::table.get_results::<Instance>(conn)?;
for instance in instances { for instance in instances {
let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain); let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
@ -428,12 +473,12 @@ fn update_instance_software(conn: &mut PgConnection, user_agent: &str) -> LemmyR
.domain(instance.domain.clone()) .domain(instance.domain.clone())
.updated(Some(naive_now())) .updated(Some(naive_now()))
.build(); .build();
let form = match client.get(&node_info_url).send() { let form = match client.get(&node_info_url).send().await {
Ok(res) if res.status().is_client_error() => { Ok(res) if res.status().is_client_error() => {
// Instance doesnt have nodeinfo but sent a response, consider it alive // Instance doesnt have nodeinfo but sent a response, consider it alive
Some(default_form) Some(default_form)
} }
Ok(res) => match res.json::<NodeInfo>() { Ok(res) => match res.json::<NodeInfo>().await {
Ok(node_info) => { Ok(node_info) => {
// Instance sent valid nodeinfo, write it to db // Instance sent valid nodeinfo, write it to db
let software = node_info.software.as_ref(); let software = node_info.software.as_ref();
@ -459,10 +504,16 @@ fn update_instance_software(conn: &mut PgConnection, user_agent: &str) -> LemmyR
if let Some(form) = form { if let Some(form) = form {
diesel::update(instance::table.find(instance.id)) diesel::update(instance::table.find(instance.id))
.set(form) .set(form)
.execute(conn)?; .execute(&mut conn)
.await?;
} }
} }
info!("Finished updating instances software and versions..."); info!("Finished updating instances software and versions...");
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
Ok(()) Ok(())
} }