-
-
Notifications
You must be signed in to change notification settings - Fork 883
/
scheduled_tasks.rs
657 lines (593 loc) · 20.2 KB
/
scheduled_tasks.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use activitypub_federation::config::Data;
use chrono::{DateTime, TimeZone, Utc};
use clokwerk::{AsyncScheduler, TimeUnits as CTimeUnits};
use diesel::{
dsl::{exists, not, IntervalDsl},
sql_query,
sql_types::{Integer, Timestamptz},
BoolExpressionMethods,
ExpressionMethods,
NullableExpressionMethods,
QueryDsl,
QueryableByName,
};
use diesel_async::{AsyncPgConnection, RunQueryDsl};
use lemmy_api_common::{
context::LemmyContext,
send_activity::{ActivityChannel, SendActivityData},
};
use lemmy_api_crud::post::create::send_webmention;
use lemmy_db_schema::{
schema::{
captcha_answer,
comment,
community,
community_actions,
federation_blocklist,
instance,
person,
post,
received_activity,
sent_activity,
},
source::{
community::Community,
instance::{Instance, InstanceForm},
local_user::LocalUser,
post::{Post, PostUpdateForm},
},
traits::Crud,
utils::{find_action, functions::coalesce, get_conn, now, DbPool, DELETED_REPLACEMENT_TEXT},
};
use lemmy_routes::nodeinfo::{NodeInfo, NodeInfoWellKnown};
use lemmy_utils::error::LemmyResult;
use reqwest_middleware::ClientWithMiddleware;
use std::time::Duration;
use tracing::{error, info, warn};
/// Schedules various cleanup tasks for lemmy in a background thread
pub async fn setup(context: Data<LemmyContext>) -> LemmyResult<()> {
// Setup the connections
let mut scheduler = AsyncScheduler::new();
startup_jobs(&mut context.pool()).await;
let context_1 = context.clone();
// Update active counts expired bans and unpublished posts every hour
scheduler.every(CTimeUnits::hour(1)).run(move || {
let context = context_1.clone();
async move {
active_counts(&mut context.pool()).await;
update_banned_when_expired(&mut context.pool()).await;
delete_instance_block_when_expired(&mut context.pool()).await;
}
});
let context_1 = context.reset_request_count();
// Every 10 minutes update hot ranks, delete expired captchas and publish scheduled posts
scheduler.every(CTimeUnits::minutes(10)).run(move || {
let context = context_1.reset_request_count();
async move {
update_hot_ranks(&mut context.pool()).await;
delete_expired_captcha_answers(&mut context.pool()).await;
publish_scheduled_posts(&context).await;
}
});
let context_1 = context.clone();
// Clear old activities every week
scheduler.every(CTimeUnits::weeks(1)).run(move || {
let context = context_1.clone();
async move {
clear_old_activities(&mut context.pool()).await;
}
});
let context_1 = context.clone();
// Daily tasks:
// - Overwrite deleted & removed posts and comments every day
// - Delete old denied users
// - Update instance software
scheduler.every(CTimeUnits::days(1)).run(move || {
let context = context_1.clone();
async move {
overwrite_deleted_posts_and_comments(&mut context.pool()).await;
delete_old_denied_users(&mut context.pool()).await;
update_instance_software(&mut context.pool(), context.client())
.await
.inspect_err(|e| warn!("Failed to update instance software: {e}"))
.ok();
}
});
// Manually run the scheduler in an event loop
loop {
scheduler.run_pending().await;
tokio::time::sleep(Duration::from_millis(1000)).await;
}
}
/// Run these on server startup
async fn startup_jobs(pool: &mut DbPool<'_>) {
active_counts(pool).await;
update_hot_ranks(pool).await;
update_banned_when_expired(pool).await;
delete_instance_block_when_expired(pool).await;
clear_old_activities(pool).await;
overwrite_deleted_posts_and_comments(pool).await;
delete_old_denied_users(pool).await;
}
/// Update the hot_rank columns for the aggregates tables
/// Runs in batches until all necessary rows are updated once
async fn update_hot_ranks(pool: &mut DbPool<'_>) {
info!("Updating hot ranks for all history...");
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
process_post_aggregates_ranks_in_batches(&mut conn).await;
process_ranks_in_batches(
&mut conn,
"comment",
"a.hot_rank != 0",
"SET hot_rank = r.hot_rank(a.score, a.published)",
)
.await;
process_ranks_in_batches(
&mut conn,
"community",
"a.hot_rank != 0",
"SET hot_rank = r.hot_rank(a.subscribers, a.published)",
)
.await;
info!("Finished hot ranks update!");
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
}
#[derive(QueryableByName)]
struct HotRanksUpdateResult {
#[diesel(sql_type = Timestamptz)]
published: DateTime<Utc>,
}
/// Runs the hot rank update query in batches until all rows have been processed.
/// 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
/// run)
async fn process_ranks_in_batches(
conn: &mut AsyncPgConnection,
table_name: &str,
where_clause: &str,
set_clause: &str,
) {
let process_start_time: DateTime<Utc> = Utc.timestamp_opt(0, 0).single().unwrap_or_default();
let update_batch_size = 1000; // Bigger batches than this tend to cause seq scans
let mut processed_rows_count = 0;
let mut previous_batch_result = Some(process_start_time);
while let Some(previous_batch_last_published) = previous_batch_result {
// Raw `sql_query` is used as a performance optimization - Diesel does not support doing this
// in a single query (neither as a CTE, nor using a subquery)
let result = sql_query(format!(
r#"WITH batch AS (SELECT a.{id_column}
FROM {aggregates_table} a
WHERE a.published > $1 AND ({where_clause})
ORDER BY a.published
LIMIT $2
FOR UPDATE SKIP LOCKED)
UPDATE {aggregates_table} a {set_clause}
FROM batch WHERE a.{id_column} = batch.{id_column} RETURNING a.published;
"#,
id_column = format!("{table_name}_id"),
aggregates_table = format!("{table_name}_aggregates"),
set_clause = set_clause,
where_clause = where_clause
))
.bind::<Timestamptz, _>(previous_batch_last_published)
.bind::<Integer, _>(update_batch_size)
.get_results::<HotRanksUpdateResult>(conn)
.await;
match result {
Ok(updated_rows) => {
processed_rows_count += updated_rows.len();
previous_batch_result = updated_rows.last().map(|row| row.published);
}
Err(e) => {
error!("Failed to update {} hot_ranks: {}", table_name, e);
break;
}
}
}
info!(
"Finished process_hot_ranks_in_batches execution for {} (processed {} rows)",
table_name, processed_rows_count
);
}
/// Post aggregates is a special case, since it needs to join to the community_aggregates
/// table, to get the active monthly user counts.
async fn process_post_aggregates_ranks_in_batches(conn: &mut AsyncPgConnection) {
let process_start_time: DateTime<Utc> = Utc.timestamp_opt(0, 0).single().unwrap_or_default();
let update_batch_size = 1000; // Bigger batches than this tend to cause seq scans
let mut processed_rows_count = 0;
let mut previous_batch_result = Some(process_start_time);
while let Some(previous_batch_last_published) = previous_batch_result {
let result = sql_query(
r#"WITH batch AS (SELECT pa.post_id
FROM post_aggregates pa
WHERE pa.published > $1
AND (pa.hot_rank != 0 OR pa.hot_rank_active != 0)
ORDER BY pa.published
LIMIT $2
FOR UPDATE SKIP LOCKED)
UPDATE post_aggregates pa
SET hot_rank = r.hot_rank(pa.score, pa.published),
hot_rank_active = r.hot_rank(pa.score, pa.newest_comment_time_necro),
scaled_rank = r.scaled_rank(pa.score, pa.published, ca.users_active_month)
FROM batch, community_aggregates ca
WHERE pa.post_id = batch.post_id and pa.community_id = ca.community_id RETURNING pa.published;
"#,
)
.bind::<Timestamptz, _>(previous_batch_last_published)
.bind::<Integer, _>(update_batch_size)
.get_results::<HotRanksUpdateResult>(conn)
.await;
match result {
Ok(updated_rows) => {
processed_rows_count += updated_rows.len();
previous_batch_result = updated_rows.last().map(|row| row.published);
}
Err(e) => {
error!("Failed to update {} hot_ranks: {}", "post_aggregates", e);
break;
}
}
}
info!(
"Finished process_hot_ranks_in_batches execution for {} (processed {} rows)",
"post_aggregates", processed_rows_count
);
}
async fn delete_expired_captcha_answers(pool: &mut DbPool<'_>) {
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
diesel::delete(
captcha_answer::table
.filter(captcha_answer::published.lt(now() - IntervalDsl::minutes(10))),
)
.execute(&mut conn)
.await
.map(|_| {
info!("Done.");
})
.inspect_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)
async fn clear_old_activities(pool: &mut DbPool<'_>) {
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() - IntervalDsl::days(7))),
)
.execute(&mut conn)
.await
.inspect_err(|e| error!("Failed to clear old sent activities: {e}"))
.ok();
diesel::delete(
received_activity::table
.filter(received_activity::published.lt(now() - IntervalDsl::days(7))),
)
.execute(&mut conn)
.await
.map(|_| info!("Done."))
.inspect_err(|e| error!("Failed to clear old received activities: {e}"))
.ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
}
async fn delete_old_denied_users(pool: &mut DbPool<'_>) {
LocalUser::delete_old_denied_local_users(pool)
.await
.map(|_| {
info!("Done.");
})
.inspect_err(|e| error!("Failed to deleted old denied users: {e}"))
.ok();
}
/// overwrite posts and comments 30d after deletion
async fn overwrite_deleted_posts_and_comments(pool: &mut DbPool<'_>) {
info!("Overwriting deleted posts...");
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
diesel::update(
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(&mut conn)
.await
.map(|_| {
info!("Done.");
})
.inspect_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.");
})
.inspect_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
async fn active_counts(pool: &mut DbPool<'_>) {
info!("Updating active site and community aggregates ...");
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
let intervals = vec![
("1 day", "day"),
("1 week", "week"),
("1 month", "month"),
("6 months", "half_year"),
];
for (full_form, abbr) in &intervals {
let update_site_stmt = format!(
"update site_aggregates set users_active_{} = (select * from r.site_aggregates_activity('{}')) where site_id = 1",
abbr, full_form
);
sql_query(update_site_stmt)
.execute(&mut conn)
.await
.inspect_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 r.community_aggregates_activity('{}') mv where ca.community_id = mv.community_id_", abbr, full_form);
sql_query(update_community_stmt)
.execute(&mut conn)
.await
.inspect_err(|e| error!("Failed to update community stats: {e}"))
.ok();
}
info!("Done.");
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
}
/// Set banned to false after ban expires
async fn update_banned_when_expired(pool: &mut DbPool<'_>) {
info!("Updating banned column if it expires ...");
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
diesel::update(
person::table
.filter(person::banned.eq(true))
.filter(person::ban_expires.lt(now().nullable())),
)
.set(person::banned.eq(false))
.execute(&mut conn)
.await
.inspect_err(|e| error!("Failed to update person.banned when expires: {e}"))
.ok();
diesel::delete(
community_actions::table.filter(community_actions::ban_expires.lt(now().nullable())),
)
.execute(&mut conn)
.await
.inspect_err(|e| error!("Failed to remove community_ban expired rows: {e}"))
.ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
}
/// Set banned to false after ban expires
async fn delete_instance_block_when_expired(pool: &mut DbPool<'_>) {
info!("Delete instance blocks when expired ...");
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
diesel::delete(
federation_blocklist::table.filter(federation_blocklist::expires.lt(now().nullable())),
)
.execute(&mut conn)
.await
.inspect_err(|e| error!("Failed to remove federation_blocklist expired rows: {e}"))
.ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
}
/// Find all unpublished posts with scheduled date in the future, and publish them.
async fn publish_scheduled_posts(context: &Data<LemmyContext>) {
let pool = &mut context.pool();
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
let scheduled_posts: Vec<_> = post::table
.inner_join(community::table)
.inner_join(person::table)
// find all posts which have scheduled_publish_time that is in the past
.filter(post::scheduled_publish_time.is_not_null())
.filter(coalesce(post::scheduled_publish_time, now()).lt(now()))
// make sure the post, person and community are still around
.filter(not(post::deleted.or(post::removed)))
.filter(not(person::banned.or(person::deleted)))
.filter(not(community::removed.or(community::deleted)))
// ensure that user isnt banned from community
.filter(not(exists(find_action(
community_actions::received_ban,
(person::id, community::id),
))))
.select((post::all_columns, community::all_columns))
.get_results::<(Post, Community)>(&mut conn)
.await
.inspect_err(|e| error!("Failed to read unpublished posts: {e}"))
.ok()
.unwrap_or_default();
for (post, community) in scheduled_posts {
// mark post as published in db
let form = PostUpdateForm {
scheduled_publish_time: Some(None),
..Default::default()
};
Post::update(&mut context.pool(), post.id, &form)
.await
.inspect_err(|e| error!("Failed update scheduled post: {e}"))
.ok();
// send out post via federation and webmention
let send_activity = SendActivityData::CreatePost(post.clone());
ActivityChannel::submit_activity(send_activity, context)
.inspect_err(|e| error!("Failed federate scheduled post: {e}"))
.ok();
send_webmention(post, community);
}
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
}
/// Updates the instance software and version.
///
/// Does so using the /.well-known/nodeinfo protocol described here:
/// https://github.com/jhass/nodeinfo/blob/main/PROTOCOL.md
///
/// TODO: if instance has been dead for a long time, it should be checked less frequently
async fn update_instance_software(
pool: &mut DbPool<'_>,
client: &ClientWithMiddleware,
) -> LemmyResult<()> {
info!("Updating instances software and versions...");
let conn = get_conn(pool).await;
match conn {
Ok(mut conn) => {
let instances = instance::table.get_results::<Instance>(&mut conn).await?;
for instance in instances {
if let Some(form) = build_update_instance_form(&instance.domain, client).await {
Instance::update(pool, instance.id, form).await?;
}
}
info!("Finished updating instances software and versions...");
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
Ok(())
}
/// This builds an instance update form, for a given domain.
/// If the instance sends a response, but doesn't have a well-known or nodeinfo,
/// Then return a default form with only the updated field.
async fn build_update_instance_form(
domain: &str,
client: &ClientWithMiddleware,
) -> Option<InstanceForm> {
// The `updated` column is used to check if instances are alive. If it is more than three
// days 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 why we always need to mark instances as updated if they are
// alive.
let mut instance_form = InstanceForm {
updated: Some(Utc::now()),
..InstanceForm::new(domain.to_string())
};
// First, fetch their /.well-known/nodeinfo, then extract the correct nodeinfo link from it
let well_known_url = format!("https://{}/.well-known/nodeinfo", domain);
let Ok(res) = client.get(&well_known_url).send().await else {
// This is the only kind of error that means the instance is dead
return None;
};
// In this block, returning `None` is ignored, and only means not writing nodeinfo to db
async {
if res.status().is_client_error() {
return None;
}
let node_info_url = res
.json::<NodeInfoWellKnown>()
.await
.ok()?
.links
.into_iter()
.find(|links| {
links
.rel
.as_str()
.starts_with("http://nodeinfo.diaspora.software/ns/schema/2.")
})?
.href;
let software = client
.get(node_info_url)
.send()
.await
.ok()?
.json::<NodeInfo>()
.await
.ok()?
.software?;
instance_form.software = software.name;
instance_form.version = software.version;
Some(())
}
.await;
Some(instance_form)
}
#[cfg(test)]
mod tests {
use crate::scheduled_tasks::build_update_instance_form;
use lemmy_api_common::request::client_builder;
use lemmy_utils::{
error::{LemmyErrorType, LemmyResult},
settings::structs::Settings,
};
use pretty_assertions::assert_eq;
use reqwest_middleware::ClientBuilder;
use serial_test::serial;
#[tokio::test]
#[serial]
async fn test_nodeinfo_lemmy_ml() -> LemmyResult<()> {
let client = ClientBuilder::new(client_builder(&Settings::default()).build()?).build();
let form = build_update_instance_form("lemmy.ml", &client)
.await
.ok_or(LemmyErrorType::NotFound)?;
assert_eq!(form.software.ok_or(LemmyErrorType::NotFound)?, "lemmy");
Ok(())
}
#[tokio::test]
#[serial]
async fn test_nodeinfo_mastodon_social() -> LemmyResult<()> {
let client = ClientBuilder::new(client_builder(&Settings::default()).build()?).build();
let form = build_update_instance_form("mastodon.social", &client)
.await
.ok_or(LemmyErrorType::NotFound)?;
assert_eq!(form.software.ok_or(LemmyErrorType::NotFound)?, "mastodon");
Ok(())
}
}