Skip to main content

tuwunel_service/migrations/
upgrade_legacy_mediaid_user.rs

1use std::sync::Arc;
2
3use tuwunel_core::{
4	Result, info,
5	result::NotFound,
6	utils::{TryReadyExt, stream::TryBroadbandExt},
7	warn,
8};
9use tuwunel_database::{Map, SEP};
10
11use super::tally::{Outcome, Tally};
12use crate::{
13	Services,
14	integrity::mediaid_user::{Legacy, classify_legacy, legacy},
15};
16
17pub(super) async fn upgrade_legacy_mediaid_user(services: &Services) -> Result {
18	let db = &services.db;
19	let cork = db.cork_and_sync();
20	let mediaid_user = &db["mediaid_user"];
21
22	warn!("Upgrading legacy mediaid_user keys to composite (mxc, user_id) layout");
23
24	// A legacy key has no separator, so each converts to a key no other one does,
25	// and the repairs cannot interfere.
26	let tally = legacy(services)
27		.broad_and_then(async |finding| repair(mediaid_user, &finding).await)
28		.ready_try_fold(Tally::default(), |tally, outcome| Ok(tally.record(outcome)))
29		.await?;
30
31	drop(cork);
32	info!(
33		upgraded = %tally.repaired,
34		removed_invalid = %tally.removed,
35		stale = %tally.stale,
36		"Upgraded legacy mediaid_user keys"
37	);
38
39	mediaid_user.sort()
40}
41
42/// Upgrades or removes the row a finding names, as it stands now.
43///
44/// The row is read again and classified as the check does, so the uploader comes
45/// from the current value. A row removed since the scan, or no longer legacy, is
46/// counted stale.
47#[tracing::instrument(level = "debug", skip_all)]
48async fn repair(mediaid_user: &Arc<Map>, finding: &Legacy) -> Result<Outcome> {
49	let (Legacy::Upgradable { key, .. } | Legacy::Unowned { key, .. }) = finding;
50	let current = mediaid_user.get(key).await.optional()?;
51	let outcome = match current
52		.as_deref()
53		.and_then(|value| classify_legacy(key, value))
54	{
55		| None => Outcome::Stale,
56		| Some(Legacy::Unowned { key, value }) => {
57			warn!(?key, ?value, "Legacy entry has unparsable user_id, removing");
58
59			mediaid_user.remove(&key);
60
61			Outcome::Removed
62		},
63		| Some(Legacy::Upgradable { key, user_id }) => {
64			let upgraded_key = [key.as_slice(), &[SEP], user_id.as_bytes()].concat();
65
66			mediaid_user.insert(&upgraded_key, user_id.as_str());
67			mediaid_user.remove(&key);
68
69			Outcome::Repaired
70		},
71	};
72
73	Ok(outcome)
74}