Skip to main content

tuwunel_service/rooms/state_accessor/
state.rs

1use std::{ops::Deref, sync::Arc};
2
3use futures::{FutureExt, Stream, StreamExt, TryFutureExt, future::try_join, pin_mut};
4use ruma::{
5	OwnedEventId, UserId,
6	events::{
7		StateEventType, TimelineEventType,
8		room::member::{MembershipState, RoomMemberEventContent},
9	},
10};
11use serde::Deserialize;
12use tuwunel_core::{
13	Result, at, err, implement,
14	matrix::{Event, Pdu, StateKey},
15	pair_of,
16	utils::{
17		result::FlatOk,
18		stream::{BroadbandExt, IterStream, ReadyExt, TryIgnore},
19	},
20};
21
22use crate::rooms::{
23	short::{ShortEventId, ShortStateHash, ShortStateKey},
24	state_compressor::{CompressedState, compress_state_event, parse_compressed_state_event},
25};
26
27/// The user was a joined member at this state (potentially in the past)
28#[implement(super::Service)]
29#[inline]
30pub async fn user_was_joined(&self, shortstatehash: ShortStateHash, user_id: &UserId) -> bool {
31	self.user_membership(shortstatehash, user_id)
32		.await == MembershipState::Join
33}
34
35/// The user was an invited or joined room member at this state (potentially
36/// in the past)
37#[implement(super::Service)]
38#[inline]
39pub async fn user_was_invited(&self, shortstatehash: ShortStateHash, user_id: &UserId) -> bool {
40	let s = self
41		.user_membership(shortstatehash, user_id)
42		.await;
43	s == MembershipState::Join || s == MembershipState::Invite
44}
45
46/// Get membership for given user in state
47#[implement(super::Service)]
48pub async fn user_membership(
49	&self,
50	shortstatehash: ShortStateHash,
51	user_id: &UserId,
52) -> MembershipState {
53	self.state_get_content(shortstatehash, &StateEventType::RoomMember, user_id.as_str())
54		.await
55		.map_or(MembershipState::Leave, |c: RoomMemberEventContent| c.membership)
56}
57
58/// MSC4115: the user's room membership "just after" the given PDU landed.
59///
60/// `pdu_shortstatehash` returns state-before-the-event, so a member event
61/// targeting `user_id` overrides that lookup with its own content.
62#[implement(super::Service)]
63pub async fn user_membership_at_pdu(&self, user_id: &UserId, pdu: &Pdu) -> MembershipState {
64	if pdu.kind() == &TimelineEventType::RoomMember
65		&& pdu.state_key() == Some(user_id.as_str())
66		&& let Ok(content) = pdu.get_content::<RoomMemberEventContent>()
67	{
68		return content.membership;
69	}
70
71	let Ok(shortstatehash) = self
72		.services
73		.state
74		.pdu_shortstatehash(pdu.event_id())
75		.await
76	else {
77		return MembershipState::Leave;
78	};
79
80	self.user_membership(shortstatehash, user_id)
81		.await
82}
83
84/// Returns a single PDU from `room_id` with key (`event_type`,`state_key`).
85#[implement(super::Service)]
86pub async fn state_get_content<T>(
87	&self,
88	shortstatehash: ShortStateHash,
89	event_type: &StateEventType,
90	state_key: &str,
91) -> Result<T>
92where
93	T: for<'de> Deserialize<'de> + Send,
94{
95	self.state_get(shortstatehash, event_type, state_key)
96		.await
97		.and_then(|event| event.get_content())
98}
99
100#[implement(super::Service)]
101pub async fn state_contains(
102	&self,
103	shortstatehash: ShortStateHash,
104	event_type: &StateEventType,
105	state_key: &str,
106) -> bool {
107	let Ok(shortstatekey) = self
108		.services
109		.short
110		.get_shortstatekey(event_type, state_key)
111		.await
112	else {
113		return false;
114	};
115
116	self.state_contains_shortstatekey(shortstatehash, shortstatekey)
117		.await
118}
119
120#[implement(super::Service)]
121pub async fn state_contains_type(
122	&self,
123	shortstatehash: ShortStateHash,
124	event_type: &StateEventType,
125) -> bool {
126	let state_keys = self.state_keys(shortstatehash, event_type);
127
128	pin_mut!(state_keys);
129	state_keys.next().await.is_some()
130}
131
132#[implement(super::Service)]
133pub async fn state_contains_shortstatekey(
134	&self,
135	shortstatehash: ShortStateHash,
136	shortstatekey: ShortStateKey,
137) -> bool {
138	let start = compress_state_event(shortstatekey, 0);
139	let end = compress_state_event(shortstatekey, u64::MAX);
140
141	self.load_full_state(shortstatehash)
142		.map_ok(|full_state| full_state.range(start..=end).next().copied())
143		.await
144		.flat_ok()
145		.is_some()
146}
147
148/// Returns a single PDU from `room_id` with key (`event_type`,
149/// `state_key`).
150#[implement(super::Service)]
151pub async fn state_get(
152	&self,
153	shortstatehash: ShortStateHash,
154	event_type: &StateEventType,
155	state_key: &str,
156) -> Result<Pdu> {
157	let event_id: OwnedEventId = self
158		.state_get_id(shortstatehash, event_type, state_key)
159		.await?;
160
161	self.services.timeline.get_pdu(&event_id).await
162}
163
164/// Returns a single EventId from `room_id` with key (`event_type`,
165/// `state_key`).
166#[implement(super::Service)]
167pub async fn state_get_id(
168	&self,
169	shortstatehash: ShortStateHash,
170	event_type: &StateEventType,
171	state_key: &str,
172) -> Result<OwnedEventId> {
173	let shorteventid = self
174		.state_get_shortid(shortstatehash, event_type, state_key)
175		.await?;
176
177	self.services
178		.short
179		.get_eventid_from_short(shorteventid)
180		.await
181}
182
183/// Returns a single EventId from `room_id` with key (`event_type`,
184/// `state_key`).
185#[implement(super::Service)]
186pub async fn state_get_shortid(
187	&self,
188	shortstatehash: ShortStateHash,
189	event_type: &StateEventType,
190	state_key: &str,
191) -> Result<ShortEventId> {
192	let shortstatekey = self
193		.services
194		.short
195		.get_shortstatekey(event_type, state_key)
196		.await?;
197
198	let start = compress_state_event(shortstatekey, 0);
199	let end = compress_state_event(shortstatekey, u64::MAX);
200	self.load_full_state(shortstatehash)
201		.map_ok(|full_state| {
202			full_state
203				.range(start..=end)
204				.next()
205				.copied()
206				.map(parse_compressed_state_event)
207				.map(at!(1))
208				.ok_or(err!(Request(NotFound("Not found in room state"))))
209		})
210		.await?
211}
212
213/// Iterates the events for an event_type in the state.
214#[implement(super::Service)]
215pub fn state_type_pdus<'a>(
216	&'a self,
217	shortstatehash: ShortStateHash,
218	event_type: &'a StateEventType,
219) -> impl Stream<Item = impl Event> + Send + 'a {
220	self.state_keys_with_ids(shortstatehash, event_type)
221		.map(at!(1))
222		.broad_filter_map(async |event_id: OwnedEventId| {
223			self.services
224				.timeline
225				.get_pdu(&event_id)
226				.await
227				.ok()
228		})
229}
230
231/// Iterates the state_keys for an event_type in the state; current state
232/// event_id included.
233#[implement(super::Service)]
234pub fn state_keys_with_ids<'a>(
235	&'a self,
236	shortstatehash: ShortStateHash,
237	event_type: &'a StateEventType,
238) -> impl Stream<Item = (StateKey, OwnedEventId)> + Send + 'a {
239	self.state_keys_with_shortids(shortstatehash, event_type)
240		.unzip()
241		.map(|(state_keys, shorteventids): (Vec<_>, Vec<_>)| {
242			self.services
243				.short
244				.multi_get_eventid_from_short(shorteventids.into_iter().stream())
245				.zip(state_keys.into_iter().stream())
246				.ready_filter_map(|(eid, sk)| eid.map(move |eid| (sk, eid)).ok())
247		})
248		.flatten_stream()
249}
250
251/// Iterates the state_keys for an event_type in the state; current state
252/// event_id included.
253#[implement(super::Service)]
254pub fn state_keys_with_shortids<'a>(
255	&'a self,
256	shortstatehash: ShortStateHash,
257	event_type: &'a StateEventType,
258) -> impl Stream<Item = (StateKey, ShortEventId)> + Send + 'a {
259	self.state_full_shortids(shortstatehash)
260		.ignore_err()
261		.unzip()
262		.map(move |(shortstatekeys, shorteventids): (Vec<_>, Vec<_>)| {
263			self.services
264				.short
265				.multi_get_statekey_from_short(shortstatekeys.into_iter().stream())
266				.zip(shorteventids.into_iter().stream())
267				.ready_filter_map(|(res, id)| res.map(|res| (res, id)).ok())
268				.ready_filter_map(move |((event_type_, state_key), event_id)| {
269					event_type_
270						.eq(event_type)
271						.then_some((state_key, event_id))
272				})
273		})
274		.flatten_stream()
275}
276
277/// Iterates the state_keys for an event_type in the state
278#[implement(super::Service)]
279pub fn state_keys<'a>(
280	&'a self,
281	shortstatehash: ShortStateHash,
282	event_type: &'a StateEventType,
283) -> impl Stream<Item = StateKey> + Send + 'a {
284	let short_ids = self
285		.state_full_shortids(shortstatehash)
286		.ignore_err()
287		.map(at!(0));
288
289	self.services
290		.short
291		.multi_get_statekey_from_short(short_ids)
292		.ready_filter_map(Result::ok)
293		.ready_filter_map(move |(event_type_, state_key)| {
294			event_type_.eq(event_type).then_some(state_key)
295		})
296}
297
298/// Returns the state events removed between the interval (present in .0 but
299/// not in .1)
300#[implement(super::Service)]
301#[inline]
302pub fn state_removed(
303	&self,
304	shortstatehash: pair_of!(ShortStateHash),
305) -> impl Stream<Item = (ShortStateKey, ShortEventId)> + Send + '_ {
306	self.state_added((shortstatehash.1, shortstatehash.0))
307}
308
309/// Returns the state events added between the interval (present in .1 but
310/// not in .0)
311#[implement(super::Service)]
312pub fn state_added(
313	&self,
314	shortstatehash: pair_of!(ShortStateHash),
315) -> impl Stream<Item = (ShortStateKey, ShortEventId)> + Send + '_ {
316	let a = self.load_full_state(shortstatehash.0);
317	let b = self.load_full_state(shortstatehash.1);
318	try_join(a, b)
319		.map_ok(|(a, b)| b.difference(&a).copied().collect::<Vec<_>>())
320		.map_ok(IterStream::try_stream)
321		.try_flatten_stream()
322		.ignore_err()
323		.map(parse_compressed_state_event)
324}
325
326#[implement(super::Service)]
327pub fn state_full(
328	&self,
329	shortstatehash: ShortStateHash,
330) -> impl Stream<Item = ((StateEventType, StateKey), impl Event)> + Send + '_ {
331	self.state_full_pdus(shortstatehash)
332		.ready_filter_map(|pdu| {
333			Some(((pdu.kind().to_cow_str().into(), pdu.state_key()?.into()), pdu))
334		})
335}
336
337#[implement(super::Service)]
338pub fn state_full_pdus(
339	&self,
340	shortstatehash: ShortStateHash,
341) -> impl Stream<Item = impl Event> + Send + '_ {
342	let short_ids = self
343		.state_full_shortids(shortstatehash)
344		.ignore_err()
345		.map(at!(1));
346
347	self.services
348		.short
349		.multi_get_eventid_from_short(short_ids)
350		.ready_filter_map(Result::ok)
351		.broad_filter_map(async |event_id: OwnedEventId| {
352			self.services
353				.timeline
354				.get_pdu(&event_id)
355				.await
356				.ok()
357		})
358}
359
360/// Builds a StateMap by iterating over all keys that start
361/// with state_hash, this gives the full state for the given state_hash.
362#[implement(super::Service)]
363pub fn state_full_ids(
364	&self,
365	shortstatehash: ShortStateHash,
366) -> impl Stream<Item = (ShortStateKey, OwnedEventId)> + Send + '_ {
367	self.state_full_shortids(shortstatehash)
368		.ignore_err()
369		.unzip()
370		.map(|(shortstatekeys, shorteventids): (Vec<_>, Vec<_>)| {
371			self.services
372				.short
373				.multi_get_eventid_from_short(shorteventids.into_iter().stream())
374				.zip(shortstatekeys.into_iter().stream())
375				.ready_filter_map(|(eid, ssk)| eid.ok().map(|eid| (ssk, eid)))
376		})
377		.flatten_stream()
378}
379
380#[implement(super::Service)]
381pub fn state_full_shortids(
382	&self,
383	shortstatehash: ShortStateHash,
384) -> impl Stream<Item = Result<(ShortStateKey, ShortEventId)>> + Send + '_ {
385	self.load_full_state(shortstatehash)
386		.map_ok(|full_state| {
387			full_state
388				.deref()
389				.iter()
390				.copied()
391				.map(parse_compressed_state_event)
392				.collect()
393		})
394		.map_ok(Vec::into_iter)
395		.map_ok(IterStream::try_stream)
396		.try_flatten_stream()
397}
398
399#[implement(super::Service)]
400#[tracing::instrument(name = "load", level = "debug", skip(self))]
401async fn load_full_state(&self, shortstatehash: ShortStateHash) -> Result<Arc<CompressedState>> {
402	self.services
403		.state_compressor
404		.load_shortstatehash_info(shortstatehash)
405		.map_err(|e| err!(Database("Missing state IDs: {e}")))
406		.map_ok(|vec| {
407			vec.last()
408				.expect("at least one layer")
409				.full_state
410				.clone()
411		})
412		.await
413}