Skip to main content

tuwunel_service/migrations/
moderation.rs

1use futures::TryStreamExt;
2use tuwunel_core::{
3	Result, debug_warn, err,
4	utils::{IterStream, TryReadyExt},
5	warn,
6};
7use tuwunel_database::{Json, Map};
8
9use super::tally::{Outcome, Tally};
10use crate::{
11	Services,
12	integrity::moderation::{Entry, Source, entries, sources},
13};
14
15/// Copies foreign suspension and lock columns into tuwunel's own.
16///
17/// Runs every boot and is non-destructive: the source columns are read, never
18/// removed, so a database also opened by its origin server keeps working. A
19/// source column the database lacks copies nothing.
20#[tracing::instrument(level = "debug", skip_all)]
21pub(super) async fn migrate(services: &Services) -> Result {
22	sources(services)
23		.stream()
24		.try_for_each(async |source| copy(services, &source).await)
25		.await
26}
27
28/// Copies every active entry of one foreign column into its target.
29///
30/// Each entry is written whatever the target holds, so the copy reads nothing
31/// but the foreign column; the moderation check verifies the result apart. An
32/// entry that does not decode is skipped, and logged with the totals.
33#[tracing::instrument(level = "debug", skip_all)]
34pub(super) async fn copy(services: &Services, source: &Source) -> Result {
35	let db = &services.db;
36	let target = &db[source.target];
37	let cork = db.cork_and_sync();
38
39	let tally = entries(services, source)
40		.ready_try_fold(Tally::default(), |tally, entry| Ok(tally.record(write(target, entry))))
41		.await?;
42
43	drop(cork);
44
45	if tally.skipped > 0 {
46		warn!(
47			copied = %tally.repaired,
48			skipped = %tally.skipped,
49			source = %source.name,
50			"Imported moderation entries; some skipped"
51		);
52	}
53
54	Ok(())
55}
56
57fn write(target: &Map, entry: Entry) -> Outcome {
58	match entry {
59		| Entry::Active { key, moderation } => {
60			target.raw_put(&key, Json(moderation));
61
62			Outcome::Repaired
63		},
64		| Entry::Unparsable { error, .. } => {
65			let error = err!(Database("moderation entry is not JSON: {error}"));
66
67			debug_warn!(%error, "skipping unreadable moderation entry");
68
69			Outcome::Skipped
70		},
71	}
72}