Skip to main content

tuwunel_service/rooms/state_accessor/
checked.rs

1//! Check-only reads of room state.
2//!
3//! The live readers rebuild a room's state through typed decoders, an unchecked
4//! slice and a cache of rebuilt chains, so a damaged row there panics, fails, or
5//! hides behind a warm cache. Integrity checks resolve state through here
6//! instead, from storage alone, where a damaged row is `Mapped::Damaged`.
7
8use std::{collections::BTreeSet, str::from_utf8};
9
10use futures::{TryFutureExt, TryStreamExt, stream::unfold};
11use ruma::{EventId, OwnedEventId, RoomId, events::StateEventType};
12use tuwunel_core::{Err, Result, implement, result::NotFound, utils::u64_from_bytes};
13
14use super::Service;
15use crate::{
16	integrity::short_ids::state::{apply, layer, visit},
17	rooms::{
18		short::ShortStateHash,
19		state_compressor::{CompressedState, compress_state_event, parse_compressed_state_event},
20		timeline::Mapped,
21	},
22};
23
24/// Finds the event one tuple holds in a room's current state, as
25/// `room_state_get_id` does, from storage alone.
26///
27/// Every outcome is the one that function gives, except that damage it would
28/// panic or fail on, or whose leading bytes a release build would accept, is
29/// `Mapped::Damaged`, and a failed read keeps its own error where that function
30/// wraps it. The state is rebuilt before the tuple's short id is read, so a
31/// damaged state is reported even for a tuple without one.
32#[implement(Service)]
33#[tracing::instrument(level = "debug", skip(self))]
34pub(crate) async fn room_state_get_id_checked(
35	&self,
36	room_id: &RoomId,
37	event_type: &StateEventType,
38	state_key: &str,
39) -> Result<Mapped<OwnedEventId>> {
40	match self.room_state_checked(room_id).await? {
41		| Mapped::Damaged => Ok(Mapped::Damaged),
42		| Mapped::Event(state) =>
43			self.state_get_id_checked(&state, event_type, state_key)
44				.await,
45	}
46}
47
48/// Rebuilds a room's current state as `room_state_get_id` does, from storage
49/// alone.
50///
51/// A room with no current state fails as there. The state pointer and each diff
52/// on its chain are decoded untrusted, so one that does not decode, a diff the
53/// chain names but storage lacks, or a chain that loops is `Mapped::Damaged`,
54/// where the live reader panics, fails, never returns, or in a release build
55/// reads the leading bytes of a value longer than it expects. A failed read
56/// keeps its own error, which the live reader wraps for a diff. The cache of
57/// rebuilt chains is not read, so a warm one cannot hide damage.
58#[implement(Service)]
59#[tracing::instrument(level = "debug", skip(self))]
60pub(crate) async fn room_state_checked(
61	&self,
62	room_id: &RoomId,
63) -> Result<Mapped<CompressedState>> {
64	let shortstatehash = self.services.db["roomid_shortstatehash"]
65		.get(room_id)
66		.map_ok(|value| u64_from_bytes(&value).ok())
67		.await?;
68
69	let Some(shortstatehash) = shortstatehash else {
70		return Ok(Mapped::Damaged);
71	};
72
73	self.full_state_checked(shortstatehash).await
74}
75
76/// Rebuilds one state from its diff chain as `load_shortstatehash_info` does.
77///
78/// Each diff adds its entries to its parent's state and then takes its removed
79/// ones away, while a root's added entries are the whole state.
80#[implement(Service)]
81#[tracing::instrument(level = "debug", skip(self))]
82async fn full_state_checked(
83	&self,
84	shortstatehash: ShortStateHash,
85) -> Result<Mapped<CompressedState>> {
86	let db = &self.services.db;
87	let chain = unfold((Some(shortstatehash), BTreeSet::new()), async |(next, visited)| {
88		let next = next?;
89		let diff = match visited.contains(&next) {
90			| true => Ok(None),
91			| false => layer(db, next).await,
92		};
93
94		let parent = diff
95			.as_ref()
96			.ok()
97			.and_then(Option::as_ref)
98			.and_then(|diff| diff.parent);
99
100		Some((diff, (parent, visit(visited, next))))
101	})
102	.try_collect::<Vec<_>>()
103	.await?;
104
105	let state = chain
106		.into_iter()
107		.rev()
108		.try_fold(CompressedState::new(), |state, diff| diff.map(|diff| apply(state, diff)));
109
110	Ok(state.map_or(Mapped::Damaged, Mapped::Event))
111}
112
113/// Finds the event one tuple holds in a rebuilt state, as `state_get_id` does,
114/// from storage alone.
115///
116/// A tuple without a short id, or one the state does not hold, fails as there. A
117/// short id that does not decode, or a short event id with no event id behind it
118/// or a damaged one, is `Mapped::Damaged`, where the live reader fails, panics or
119/// decodes a prefix. A failed read keeps its own error, which the live reader
120/// wraps for the event id.
121#[implement(Service)]
122#[tracing::instrument(level = "debug", skip(self, state))]
123pub(crate) async fn state_get_id_checked(
124	&self,
125	state: &CompressedState,
126	event_type: &StateEventType,
127	state_key: &str,
128) -> Result<Mapped<OwnedEventId>> {
129	let shortstatekey = self.services.db["statekey_shortstatekey"]
130		.qry(&(event_type, state_key))
131		.map_ok(|value| u64_from_bytes(&value).ok())
132		.await?;
133
134	let Some(shortstatekey) = shortstatekey else {
135		return Ok(Mapped::Damaged);
136	};
137
138	let start = compress_state_event(shortstatekey, 0);
139	let end = compress_state_event(shortstatekey, u64::MAX);
140	let Some(&entry) = state.range(start..=end).next() else {
141		return Err!(Request(NotFound("Not found in room state")));
142	};
143
144	let (_, shorteventid) = parse_compressed_state_event(entry);
145	let event_id = self.services.db["shorteventid_eventid"]
146		.get(&shorteventid.to_be_bytes())
147		.map_ok(|value| event_id(&value))
148		.await
149		.present()?
150		.flatten();
151
152	Ok(event_id.map_or(Mapped::Damaged, Mapped::Event))
153}
154
155fn event_id(value: &[u8]) -> Option<OwnedEventId> {
156	from_utf8(value)
157		.ok()
158		.and_then(|id| EventId::parse(id).ok())
159}