Skip to main content

tuwunel_service/integrity/
threadrootid_latestcount.rs

1//! The thread pointers in `threadrootid_latestcount`.
2//!
3//! A pointer holds the count of the one `threadactivityid_rootid` row that lists
4//! its thread, so a room's thread list reads activity rows newest first and skips
5//! any row a pointer has moved past.
6
7use std::{fmt, sync::Arc};
8
9use futures::Stream;
10use tuwunel_core::{
11	Result,
12	result::NotFound,
13	utils::{TryReadyExt, stream::TryBroadbandExt},
14};
15use tuwunel_database::{KeyBuf, Map};
16use tuwunel_matrix::{PduCount, RawPduId};
17
18use super::{Check, Report, ScanExt, tally};
19use crate::{Services, rooms::threads::activity_key};
20
21type Pointer = (RawPduId, PduCount);
22
23pub(super) static CHECK: Check = Check {
24	name: "thread-activity",
25	about: "Every thread pointer has the activity row it points at, naming its root",
26	quiescent: true,
27	walk: |services, limit| tally(scan(services), limit),
28};
29
30/// A thread pointer without the activity row it points at.
31///
32/// Its thread is then missing from its room's thread list. The rebuild of the
33/// thread activity index writes every pointer afresh beside its row.
34pub enum Finding {
35	/// No activity row sits at the pointer's count.
36	Dangling {
37		/// The thread root.
38		root_id: RawPduId,
39
40		/// The count the pointer holds.
41		count: PduCount,
42	},
43
44	/// The activity row at the pointer's count names another root.
45	Misdirected {
46		/// The thread root.
47		root_id: RawPduId,
48
49		/// The count the pointer holds.
50		count: PduCount,
51
52		/// The root the activity row names.
53		named: KeyBuf,
54	},
55
56	/// The pointer's key is not a PDU id, or its value not a count.
57	Unparsable {
58		/// The stored key.
59		key: KeyBuf,
60	},
61}
62
63/// Streams each pointer whose activity row is absent or names another root.
64///
65/// Only the pointer is checked. Activity rows behind it are dead and are reaped
66/// as the list is read, and a pointer need not name the newest reply, since a
67/// redaction moves it only when the thread empties.
68#[tracing::instrument(level = "trace", skip_all)]
69pub fn scan(services: &Services) -> impl Stream<Item = Result<Finding>> + Send + '_ {
70	let activity = &services.db["threadactivityid_rootid"];
71
72	services.db["threadrootid_latestcount"]
73		.raw_scan()
74		.scanned(&services.server)
75		.ready_and_then(|(key, value)| {
76			Ok(pointer(key, value).ok_or_else(|| KeyBuf::from_slice(key)))
77		})
78		.broad_and_then(async |pointer| match pointer {
79			| Ok(pointer) => verify(activity, pointer).await,
80			| Err(key) => Ok(Some(Finding::Unparsable { key })),
81		})
82		.ready_try_filter_map(Ok)
83}
84
85impl Report for Finding {
86	fn kind(&self) -> &'static str {
87		match self {
88			| Self::Dangling { .. } => "dangling-pointer",
89			| Self::Misdirected { .. } => "misdirected-pointer",
90			| Self::Unparsable { .. } => "unparsable-pointer",
91		}
92	}
93}
94
95impl fmt::Display for Finding {
96	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97		match self {
98			| Self::Dangling { root_id, count } => {
99				write!(f, "pointer of thread root {root_id:?} at {count:?} has no activity row")
100			},
101			| Self::Misdirected { root_id, count, named } => write!(
102				f,
103				"activity row at {count:?} for thread root {root_id:?} names {}",
104				named.escape_ascii()
105			),
106			| Self::Unparsable { key } => {
107				write!(f, "thread pointer cannot be read: {}", key.escape_ascii())
108			},
109		}
110	}
111}
112
113fn pointer(key: &[u8], value: &[u8]) -> Option<Pointer> {
114	let root_id = RawPduId::try_from_bytes(key)?;
115	let count = value.try_into().map(u64::from_be_bytes).ok()?;
116
117	Some((root_id, PduCount::from_unsigned(count)))
118}
119
120#[tracing::instrument(level = "debug", skip_all)]
121async fn verify(activity: &Arc<Map>, (root_id, count): Pointer) -> Result<Option<Finding>> {
122	let named = activity
123		.get(&activity_key(root_id, count))
124		.await
125		.optional()?
126		.map(|named| {
127			named
128				.ne(root_id.as_bytes())
129				.then(|| KeyBuf::from_slice(&named))
130		});
131
132	let finding = match named {
133		| None => Some(Finding::Dangling { root_id, count }),
134		| Some(Some(named)) => Some(Finding::Misdirected { root_id, count, named }),
135		| Some(None) => None,
136	};
137
138	Ok(finding)
139}