mirror of
https://github.com/LemmyNet/lemmy.git
synced 2024-11-25 07:36:01 +00:00
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:
parent
375d9a2a3c
commit
6735a98d35
10
src/lib.rs
10
src/lib.rs
|
@ -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")]
|
||||||
|
|
|
@ -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 hour = Duration::from_secs(3600);
|
let context = context_1.clone();
|
||||||
context_1.settings_updated_channel().remove_older_than(hour);
|
|
||||||
|
async move {
|
||||||
|
let hour = Duration::from_secs(3600);
|
||||||
|
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 {
|
||||||
.map_err(|e| warn!("Failed to update instance software: {e}"))
|
update_instance_software(&mut context.pool(), context.client())
|
||||||
.ok();
|
.await
|
||||||
})
|
.map_err(|e| warn!("Failed to update instance software: {e}"))
|
||||||
.map_err(|e| {
|
.ok();
|
||||||
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;
|
||||||
|
|
||||||
process_ranks_in_batches(
|
match conn {
|
||||||
conn,
|
Ok(mut conn) => {
|
||||||
"comment_aggregates",
|
process_post_aggregates_ranks_in_batches(&mut conn).await;
|
||||||
"a.hot_rank != 0",
|
|
||||||
"SET hot_rank = hot_rank(a.score, a.published)",
|
|
||||||
);
|
|
||||||
|
|
||||||
process_ranks_in_batches(
|
process_ranks_in_batches(
|
||||||
conn,
|
&mut conn,
|
||||||
"community_aggregates",
|
"comment_aggregates",
|
||||||
"a.hot_rank != 0",
|
"a.hot_rank != 0",
|
||||||
"SET hot_rank = hot_rank(a.subscribers, a.published)",
|
"SET hot_rank = hot_rank(a.score, a.published)",
|
||||||
);
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
info!("Finished hot ranks update!");
|
process_ranks_in_batches(
|
||||||
|
&mut conn,
|
||||||
|
"community_aggregates",
|
||||||
|
"a.hot_rank != 0",
|
||||||
|
"SET hot_rank = hot_rank(a.subscribers, a.published)",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
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,185 +276,244 @@ 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<'_>) {
|
||||||
diesel::delete(
|
let conn = get_conn(pool).await;
|
||||||
captcha_answer::table.filter(captcha_answer::published.lt(now() - IntervalDsl::minutes(10))),
|
|
||||||
)
|
match conn {
|
||||||
.execute(conn)
|
Ok(mut conn) => {
|
||||||
.map(|_| {
|
diesel::delete(
|
||||||
info!("Done.");
|
captcha_answer::table
|
||||||
})
|
.filter(captcha_answer::published.lt(now() - IntervalDsl::minutes(10))),
|
||||||
.map_err(|e| error!("Failed to clear old captcha answers: {e}"))
|
)
|
||||||
.ok();
|
.execute(&mut conn)
|
||||||
|
.await
|
||||||
|
.map(|_| {
|
||||||
|
info!("Done.");
|
||||||
|
})
|
||||||
|
.map_err(|e| error!("Failed to clear old captcha answers: {e}"))
|
||||||
|
.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...");
|
||||||
diesel::delete(sent_activity::table.filter(sent_activity::published.lt(now() - 3.months())))
|
let conn = get_conn(pool).await;
|
||||||
.execute(conn)
|
|
||||||
.map_err(|e| error!("Failed to clear old sent activities: {e}"))
|
|
||||||
.ok();
|
|
||||||
|
|
||||||
diesel::delete(
|
match conn {
|
||||||
received_activity::table.filter(received_activity::published.lt(now() - 3.months())),
|
Ok(mut conn) => {
|
||||||
)
|
diesel::delete(sent_activity::table.filter(sent_activity::published.lt(now() - 3.months())))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.map(|_| info!("Done."))
|
.await
|
||||||
.map_err(|e| error!("Failed to clear old received activities: {e}"))
|
.map_err(|e| error!("Failed to clear old sent activities: {e}"))
|
||||||
.ok();
|
.ok();
|
||||||
|
|
||||||
|
diesel::delete(
|
||||||
|
received_activity::table.filter(received_activity::published.lt(now() - 3.months())),
|
||||||
|
)
|
||||||
|
.execute(&mut conn)
|
||||||
|
.await
|
||||||
|
.map(|_| info!("Done."))
|
||||||
|
.map_err(|e| error!("Failed to clear old received activities: {e}"))
|
||||||
|
.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...");
|
||||||
diesel::update(
|
let conn = get_conn(pool).await;
|
||||||
post::table
|
|
||||||
.filter(post::deleted.eq(true))
|
|
||||||
.filter(post::updated.lt(now().nullable() - 1.months()))
|
|
||||||
.filter(post::body.ne(DELETED_REPLACEMENT_TEXT)),
|
|
||||||
)
|
|
||||||
.set((
|
|
||||||
post::body.eq(DELETED_REPLACEMENT_TEXT),
|
|
||||||
post::name.eq(DELETED_REPLACEMENT_TEXT),
|
|
||||||
))
|
|
||||||
.execute(conn)
|
|
||||||
.map(|_| {
|
|
||||||
info!("Done.");
|
|
||||||
})
|
|
||||||
.map_err(|e| error!("Failed to overwrite deleted posts: {e}"))
|
|
||||||
.ok();
|
|
||||||
|
|
||||||
info!("Overwriting deleted comments...");
|
match conn {
|
||||||
diesel::update(
|
Ok(mut conn) => {
|
||||||
comment::table
|
diesel::update(
|
||||||
.filter(comment::deleted.eq(true))
|
post::table
|
||||||
.filter(comment::updated.lt(now().nullable() - 1.months()))
|
.filter(post::deleted.eq(true))
|
||||||
.filter(comment::content.ne(DELETED_REPLACEMENT_TEXT)),
|
.filter(post::updated.lt(now().nullable() - 1.months()))
|
||||||
)
|
.filter(post::body.ne(DELETED_REPLACEMENT_TEXT)),
|
||||||
.set(comment::content.eq(DELETED_REPLACEMENT_TEXT))
|
)
|
||||||
.execute(conn)
|
.set((
|
||||||
.map(|_| {
|
post::body.eq(DELETED_REPLACEMENT_TEXT),
|
||||||
info!("Done.");
|
post::name.eq(DELETED_REPLACEMENT_TEXT),
|
||||||
})
|
))
|
||||||
.map_err(|e| error!("Failed to overwrite deleted comments: {e}"))
|
.execute(&mut conn)
|
||||||
.ok();
|
.await
|
||||||
|
.map(|_| {
|
||||||
|
info!("Done.");
|
||||||
|
})
|
||||||
|
.map_err(|e| error!("Failed to overwrite deleted posts: {e}"))
|
||||||
|
.ok();
|
||||||
|
|
||||||
|
info!("Overwriting deleted comments...");
|
||||||
|
diesel::update(
|
||||||
|
comment::table
|
||||||
|
.filter(comment::deleted.eq(true))
|
||||||
|
.filter(comment::updated.lt(now().nullable() - 1.months()))
|
||||||
|
.filter(comment::content.ne(DELETED_REPLACEMENT_TEXT)),
|
||||||
|
)
|
||||||
|
.set(comment::content.eq(DELETED_REPLACEMENT_TEXT))
|
||||||
|
.execute(&mut conn)
|
||||||
|
.await
|
||||||
|
.map(|_| {
|
||||||
|
info!("Done.");
|
||||||
|
})
|
||||||
|
.map_err(|e| error!("Failed to overwrite deleted comments: {e}"))
|
||||||
|
.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 intervals = vec![
|
let conn = get_conn(pool).await;
|
||||||
("1 day", "day"),
|
|
||||||
("1 week", "week"),
|
|
||||||
("1 month", "month"),
|
|
||||||
("6 months", "half_year"),
|
|
||||||
];
|
|
||||||
|
|
||||||
for i in &intervals {
|
match conn {
|
||||||
let update_site_stmt = format!(
|
Ok(mut conn) => {
|
||||||
|
let intervals = vec![
|
||||||
|
("1 day", "day"),
|
||||||
|
("1 week", "week"),
|
||||||
|
("1 month", "month"),
|
||||||
|
("6 months", "half_year"),
|
||||||
|
];
|
||||||
|
|
||||||
|
for i in &intervals {
|
||||||
|
let update_site_stmt = format!(
|
||||||
"update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}')) where site_id = 1",
|
"update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}')) where site_id = 1",
|
||||||
i.1, i.0
|
i.1, i.0
|
||||||
);
|
);
|
||||||
sql_query(update_site_stmt)
|
sql_query(update_site_stmt)
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.map_err(|e| error!("Failed to update site stats: {e}"))
|
.await
|
||||||
.ok();
|
.map_err(|e| error!("Failed to update site stats: {e}"))
|
||||||
|
.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)
|
||||||
.map_err(|e| error!("Failed to update community stats: {e}"))
|
.await
|
||||||
.ok();
|
.map_err(|e| error!("Failed to update community stats: {e}"))
|
||||||
|
.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
info!("Done.");
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
error!("Failed to get connection from pool: {e}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("Done.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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;
|
||||||
|
|
||||||
diesel::update(
|
match conn {
|
||||||
person::table
|
Ok(mut conn) => {
|
||||||
.filter(person::banned.eq(true))
|
diesel::update(
|
||||||
.filter(person::ban_expires.lt(now().nullable())),
|
person::table
|
||||||
)
|
.filter(person::banned.eq(true))
|
||||||
.set(person::banned.eq(false))
|
.filter(person::ban_expires.lt(now().nullable())),
|
||||||
.execute(conn)
|
)
|
||||||
.map_err(|e| error!("Failed to update person.banned when expires: {e}"))
|
.set(person::banned.eq(false))
|
||||||
.ok();
|
.execute(&mut conn)
|
||||||
|
.await
|
||||||
|
.map_err(|e| error!("Failed to update person.banned when expires: {e}"))
|
||||||
|
.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)
|
||||||
.map_err(|e| error!("Failed to remove community_ban expired rows: {e}"))
|
.await
|
||||||
.ok();
|
.map_err(|e| error!("Failed to remove community_ban expired rows: {e}"))
|
||||||
|
.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 {
|
||||||
|
let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
|
||||||
|
|
||||||
for instance in instances {
|
// The `updated` column is used to check if instances are alive. If it is more than three days
|
||||||
let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
|
// in the past, no outgoing activities will be sent to that instance. However not every
|
||||||
|
// Fediverse instance has a valid Nodeinfo endpoint (its not required for Activitypub). That's
|
||||||
// The `updated` column is used to check if instances are alive. If it is more than three days
|
// why we always need to mark instances as updated if they are alive.
|
||||||
// in the past, no outgoing activities will be sent to that instance. However not every
|
let default_form = InstanceForm::builder()
|
||||||
// Fediverse instance has a valid Nodeinfo endpoint (its not required for Activitypub). That's
|
.domain(instance.domain.clone())
|
||||||
// why we always need to mark instances as updated if they are alive.
|
.updated(Some(naive_now()))
|
||||||
let default_form = InstanceForm::builder()
|
.build();
|
||||||
.domain(instance.domain.clone())
|
let form = match client.get(&node_info_url).send().await {
|
||||||
.updated(Some(naive_now()))
|
Ok(res) if res.status().is_client_error() => {
|
||||||
.build();
|
// Instance doesnt have nodeinfo but sent a response, consider it alive
|
||||||
let form = match client.get(&node_info_url).send() {
|
Some(default_form)
|
||||||
Ok(res) if res.status().is_client_error() => {
|
}
|
||||||
// Instance doesnt have nodeinfo but sent a response, consider it alive
|
Ok(res) => match res.json::<NodeInfo>().await {
|
||||||
Some(default_form)
|
Ok(node_info) => {
|
||||||
}
|
// Instance sent valid nodeinfo, write it to db
|
||||||
Ok(res) => match res.json::<NodeInfo>() {
|
let software = node_info.software.as_ref();
|
||||||
Ok(node_info) => {
|
Some(
|
||||||
// Instance sent valid nodeinfo, write it to db
|
InstanceForm::builder()
|
||||||
let software = node_info.software.as_ref();
|
.domain(instance.domain)
|
||||||
Some(
|
.updated(Some(naive_now()))
|
||||||
InstanceForm::builder()
|
.software(software.and_then(|s| s.name.clone()))
|
||||||
.domain(instance.domain)
|
.version(software.and_then(|s| s.version.clone()))
|
||||||
.updated(Some(naive_now()))
|
.build(),
|
||||||
.software(software.and_then(|s| s.name.clone()))
|
)
|
||||||
.version(software.and_then(|s| s.version.clone()))
|
}
|
||||||
.build(),
|
Err(_) => {
|
||||||
)
|
// No valid nodeinfo but valid HTTP response, consider instance alive
|
||||||
|
Some(default_form)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(_) => {
|
||||||
|
// dead instance, do nothing
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(form) = form {
|
||||||
|
diesel::update(instance::table.find(instance.id))
|
||||||
|
.set(form)
|
||||||
|
.execute(&mut conn)
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
Err(_) => {
|
|
||||||
// No valid nodeinfo but valid HTTP response, consider instance alive
|
|
||||||
Some(default_form)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(_) => {
|
|
||||||
// dead instance, do nothing
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
};
|
info!("Finished updating instances software and versions...");
|
||||||
if let Some(form) = form {
|
}
|
||||||
diesel::update(instance::table.find(instance.id))
|
Err(e) => {
|
||||||
.set(form)
|
error!("Failed to get connection from pool: {e}");
|
||||||
.execute(conn)?;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
info!("Finished updating instances software and versions...");
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue