Skip to main content

tuwunel_service/migrations/injectivity/seen/rooms/
publication.rs

1use futures::{TryStreamExt, future::ready};
2use tuwunel_core::{
3	Err, Result, err,
4	utils::{IterStream, TryReadyExt, stream::TryWidebandExt},
5};
6use tuwunel_database::{Database, Txn};
7
8use self::Operation::{Publish, Restore};
9use crate::{
10	Services,
11	integrity::short_ids::rooms::{
12		Action, Row, lookup,
13		rows::{COLUMNS, decode, rewrite},
14	},
15};
16
17pub(super) type Writes = Vec<Write>;
18
19type Changes = [Option<Write>; 2];
20
21pub(super) enum Applied {
22	Done,
23	Restored,
24}
25
26#[derive(Clone, Copy)]
27enum Operation {
28	Publish,
29	Restore,
30}
31
32pub(super) struct Write {
33	column: usize,
34	key: Box<[u8]>,
35	before: Option<Box<[u8]>>,
36	after: Option<Box<[u8]>>,
37}
38
39/// The writes one candidate's action needs, decided before any of them.
40///
41/// A purge removes every owned row. A move rewrites each row for the winner, and
42/// is refused, as `None`, when a row will not rewrite or a source or destination
43/// no longer holds what the move expects.
44#[tracing::instrument(level = "trace", skip_all)]
45pub(super) async fn plan<I>(
46	services: &Services,
47	rows: I,
48	from: u64,
49	action: Action,
50) -> Result<Option<Writes>>
51where
52	I: IntoIterator<Item = Row> + Send,
53	I::IntoIter: Send,
54{
55	services.server.check_running()?;
56	match action {
57		| Action::Purge => Ok(Some(rows.into_iter().map(removal).collect())),
58		| Action::Move(to) => preflight(&services.db, rows, from, to).await,
59	}
60}
61
62/// Publishes a candidate's planned writes and verifies them.
63///
64/// A move that fails verification is restored to its exact preimage, while a
65/// purge that fails is an error.
66#[tracing::instrument(level = "trace", skip_all)]
67pub(super) async fn apply(db: &Database, writes: &[Write], action: Action) -> Result<Applied> {
68	if commit(db, writes, Publish).await? {
69		return Ok(Applied::Done);
70	}
71
72	// Restoring after a durable delete is a no-op or overwrites a later writer's row.
73	if matches!(action, Action::Purge) {
74		return Err!("room deletion verification failed");
75	}
76
77	if !commit(db, writes, Restore).await? {
78		return Err!("room restoration verification failed");
79	}
80
81	Ok(Applied::Restored)
82}
83
84#[tracing::instrument(level = "trace", skip_all)]
85async fn preflight<I>(db: &Database, rows: I, from: u64, to: u64) -> Result<Option<Writes>>
86where
87	I: IntoIterator<Item = Row> + Send,
88	I::IntoIter: Send,
89{
90	// A refused row surfaces as Err(None), which stops the fold without an error.
91	rows.try_stream()
92		.wide_and_then(|row| prepared(db, row, from, to))
93		.map_err(Some)
94		.ready_try_fold(Writes::new(), |writes, changes| {
95			changes
96				.map(|changes| appended(writes, changes))
97				.ok_or(None)
98		})
99		.await
100		.map(Some)
101		.or_else(|error| error.map_or(Ok(None), Err))
102}
103
104async fn prepared(db: &Database, row: Row, from: u64, to: u64) -> Result<Option<Changes>> {
105	let Some((key, value)) = decode(row.column, &row.key, &row.value)
106		.and_then(|decoded| rewrite(decoded, row.column, &row.key, &row.value, from, to))
107	else {
108		return Ok(None);
109	};
110
111	let moved = key != row.key;
112	let before = lookup(db, COLUMNS[row.column], &key, |previous| match previous {
113		| None => moved.then_some(None),
114		| Some(previous) if moved => previous
115			.eq(&*value)
116			.then(|| Some(Box::from(previous))),
117		| Some(previous) => previous.eq(&*row.value).then_some(None),
118	})
119	.await?;
120
121	Ok(before.map(|before| changes(row, key, value, before)))
122}
123
124fn changes(row: Row, key: Box<[u8]>, value: Box<[u8]>, before: Option<Box<[u8]>>) -> Changes {
125	let source = removal(row);
126
127	if source.key == key {
128		return [Some(Write { after: Some(value), ..source }), None];
129	}
130
131	let destination = Write {
132		column: source.column,
133		key,
134		before,
135		after: Some(value),
136	};
137
138	[Some(source), Some(destination)]
139}
140
141fn removal(row: Row) -> Write {
142	Write {
143		column: row.column,
144		key: row.key,
145		before: Some(row.value),
146		after: None,
147	}
148}
149
150fn appended(mut writes: Writes, changes: Changes) -> Writes {
151	writes.extend(changes.into_iter().flatten());
152
153	writes
154}
155
156async fn commit(db: &Database, writes: &[Write], operation: Operation) -> Result<bool> {
157	publication(db, writes, operation)
158		.try_execute()
159		.map_err(|error| err!("{error}"))?;
160
161	verified(db, writes, operation).await
162}
163
164fn publication(db: &Database, writes: &[Write], operation: Operation) -> Txn {
165	writes
166		.iter()
167		.map(|write| (&db[COLUMNS[write.column]], &write.key, expected(write, operation)))
168		.fold(db.txn(), |mut txn, (map, key, value)| {
169			match value {
170				| None => txn.del_raw(map, key),
171				| Some(value) => txn.insert_raw(map, key, value),
172			}
173
174			txn
175		})
176}
177
178#[tracing::instrument(level = "trace", skip_all)]
179async fn verified(db: &Database, writes: &[Write], operation: Operation) -> Result<bool> {
180	writes
181		.iter()
182		.try_stream()
183		.wide_and_then(|write| {
184			lookup(db, COLUMNS[write.column], &write.key, move |value| {
185				value == expected(write, operation)
186			})
187		})
188		.try_all(ready)
189		.await
190}
191
192fn expected(write: &Write, operation: Operation) -> Option<&[u8]> {
193	match operation {
194		| Publish => write.after.as_deref(),
195		| Restore => write.before.as_deref(),
196	}
197}