Skip to main content

tuwunel_service/integrity/
referencedevents.rs

1use std::{fmt, str::from_utf8};
2
3use futures::Stream;
4use tuwunel_core::{
5	Result,
6	smallstr::SmallString,
7	utils::{BoolExt, TryReadyExt},
8};
9use tuwunel_database::{KeyBuf, SEP};
10
11use super::{Check, Report, ScanExt, tally};
12use crate::Services;
13
14/// Inline budget for one of the ids a key joins.
15///
16/// A hashed event id fits, while a room id on a long server name spills to the
17/// heap, which a finding can afford.
18type Id = SmallString<[u8; 48]>;
19
20pub(super) static CHECK: Check = Check {
21	name: "referenced-events",
22	about: "Every referencedevents key separates its room and event ids",
23	quiescent: false,
24	walk: |services, limit| tally(scan(services), limit),
25};
26
27/// A `referencedevents` key with no separator between its room and event ids.
28///
29/// Such a key reads as an unknown room, so the event's reference is lost until the
30/// key is rewritten. Only a key naming where the event id begins can be.
31pub enum Finding {
32	/// The key joins the two ids, and the event id's sigil shows where to split it.
33	Unseparated {
34		/// The stored key.
35		key: KeyBuf,
36
37		/// The part of the key before the event id.
38		room_id: Id,
39
40		/// The event id ending the key.
41		event_id: Id,
42	},
43
44	/// The key has no sigil to split at, or is not text.
45	Unparsable {
46		/// The stored key.
47		key: KeyBuf,
48	},
49}
50
51/// Streams each `referencedevents` key missing its separator.
52///
53/// The defect is visible in the key alone, so any later row is unaffected by a
54/// repair of this one.
55#[tracing::instrument(level = "trace", skip_all)]
56pub fn scan(services: &Services) -> impl Stream<Item = Result<Finding>> + Send + '_ {
57	services.db["referencedevents"]
58		.raw_scan()
59		.scanned(&services.server)
60		.ready_try_filter_map(|(key, _)| Ok(key.contains(&SEP).or(|| finding(key))))
61}
62
63impl Report for Finding {
64	fn kind(&self) -> &'static str {
65		match self {
66			| Self::Unseparated { .. } => "missing-separator",
67			| Self::Unparsable { .. } => "unparsable-key",
68		}
69	}
70}
71
72impl fmt::Display for Finding {
73	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74		match self {
75			| Self::Unseparated { room_id, event_id, .. } => {
76				write!(f, "no separator between {room_id} and {event_id}")
77			},
78			| Self::Unparsable { key } => write!(f, "key cannot be split: {key:?}"),
79		}
80	}
81}
82
83fn finding(key: &[u8]) -> Finding {
84	let parts = from_utf8(key)
85		.ok()
86		.and_then(|key| key.find('$').map(|at| key.split_at(at)));
87
88	match parts {
89		| None => Finding::Unparsable { key: KeyBuf::from_slice(key) },
90		| Some((room_id, event_id)) => Finding::Unseparated {
91			key: KeyBuf::from_slice(key),
92			room_id: room_id.into(),
93			event_id: event_id.into(),
94		},
95	}
96}