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	let state_keys_with_short_ids = self
240		.state_keys_with_shortids(shortstatehash, event_type)
241		.unzip()
242		.map(|(ssks, sids): (Vec<StateKey>, Vec<u64>)| (ssks, sids))
243		.shared();
244
245	let state_keys = state_keys_with_short_ids
246		.clone()
247		.map(at!(0))
248		.map(Vec::into_iter)
249		.map(IterStream::stream)
250		.flatten_stream();
251
252	let shorteventids = state_keys_with_short_ids
253		.map(at!(1))
254		.map(Vec::into_iter)
255		.map(IterStream::stream)
256		.flatten_stream();
257
258	self.services
259		.short
260		.multi_get_eventid_from_short(shorteventids)
261		.zip(state_keys)
262		.ready_filter_map(|(eid, sk)| eid.map(move |eid| (sk, eid)).ok())
263}
264
265/// Iterates the state_keys for an event_type in the state; current state
266/// event_id included.
267#[implement(super::Service)]
268pub fn state_keys_with_shortids<'a>(
269	&'a self,
270	shortstatehash: ShortStateHash,
271	event_type: &'a StateEventType,
272) -> impl Stream<Item = (StateKey, ShortEventId)> + Send + 'a {
273	let short_ids = self
274		.state_full_shortids(shortstatehash)
275		.ignore_err()
276		.unzip()
277		.map(|(ssks, sids): (Vec<u64>, Vec<u64>)| (ssks, sids))
278		.shared();
279
280	let shortstatekeys = short_ids
281		.clone()
282		.map(at!(0))
283		.map(Vec::into_iter)
284		.map(IterStream::stream)
285		.flatten_stream();
286
287	let shorteventids = short_ids
288		.map(at!(1))
289		.map(Vec::into_iter)
290		.map(IterStream::stream)
291		.flatten_stream();
292
293	self.services
294		.short
295		.multi_get_statekey_from_short(shortstatekeys)
296		.zip(shorteventids)
297		.ready_filter_map(|(res, id)| res.map(|res| (res, id)).ok())
298		.ready_filter_map(move |((event_type_, state_key), event_id)| {
299			event_type_
300				.eq(event_type)
301				.then_some((state_key, event_id))
302		})
303}
304
305/// Iterates the state_keys for an event_type in the state
306#[implement(super::Service)]
307pub fn state_keys<'a>(
308	&'a self,
309	shortstatehash: ShortStateHash,
310	event_type: &'a StateEventType,
311) -> impl Stream<Item = StateKey> + Send + 'a {
312	let short_ids = self
313		.state_full_shortids(shortstatehash)
314		.ignore_err()
315		.map(at!(0));
316
317	self.services
318		.short
319		.multi_get_statekey_from_short(short_ids)
320		.ready_filter_map(Result::ok)
321		.ready_filter_map(move |(event_type_, state_key)| {
322			event_type_.eq(event_type).then_some(state_key)
323		})
324}
325
326/// Returns the state events removed between the interval (present in .0 but
327/// not in .1)
328#[implement(super::Service)]
329#[inline]
330pub fn state_removed(
331	&self,
332	shortstatehash: pair_of!(ShortStateHash),
333) -> impl Stream<Item = (ShortStateKey, ShortEventId)> + Send + '_ {
334	self.state_added((shortstatehash.1, shortstatehash.0))
335}
336
337/// Returns the state events added between the interval (present in .1 but
338/// not in .0)
339#[implement(super::Service)]
340pub fn state_added(
341	&self,
342	shortstatehash: pair_of!(ShortStateHash),
343) -> impl Stream<Item = (ShortStateKey, ShortEventId)> + Send + '_ {
344	let a = self.load_full_state(shortstatehash.0);
345	let b = self.load_full_state(shortstatehash.1);
346	try_join(a, b)
347		.map_ok(|(a, b)| b.difference(&a).copied().collect::<Vec<_>>())
348		.map_ok(IterStream::try_stream)
349		.try_flatten_stream()
350		.ignore_err()
351		.map(parse_compressed_state_event)
352}
353
354#[implement(super::Service)]
355pub fn state_full(
356	&self,
357	shortstatehash: ShortStateHash,
358) -> impl Stream<Item = ((StateEventType, StateKey), impl Event)> + Send + '_ {
359	self.state_full_pdus(shortstatehash)
360		.ready_filter_map(|pdu| {
361			Some(((pdu.kind().to_cow_str().into(), pdu.state_key()?.into()), pdu))
362		})
363}
364
365#[implement(super::Service)]
366pub fn state_full_pdus(
367	&self,
368	shortstatehash: ShortStateHash,
369) -> impl Stream<Item = impl Event> + Send + '_ {
370	let short_ids = self
371		.state_full_shortids(shortstatehash)
372		.ignore_err()
373		.map(at!(1));
374
375	self.services
376		.short
377		.multi_get_eventid_from_short(short_ids)
378		.ready_filter_map(Result::ok)
379		.broad_filter_map(async |event_id: OwnedEventId| {
380			self.services
381				.timeline
382				.get_pdu(&event_id)
383				.await
384				.ok()
385		})
386}
387
388/// Builds a StateMap by iterating over all keys that start
389/// with state_hash, this gives the full state for the given state_hash.
390#[implement(super::Service)]
391pub fn state_full_ids(
392	&self,
393	shortstatehash: ShortStateHash,
394) -> impl Stream<Item = (ShortStateKey, OwnedEventId)> + Send + '_ {
395	let shortids = self
396		.state_full_shortids(shortstatehash)
397		.ignore_err()
398		.unzip()
399		.shared();
400
401	let shortstatekeys = shortids
402		.clone()
403		.map(at!(0))
404		.map(Vec::into_iter)
405		.map(IterStream::stream)
406		.flatten_stream();
407
408	let shorteventids = shortids
409		.map(at!(1))
410		.map(Vec::into_iter)
411		.map(IterStream::stream)
412		.flatten_stream();
413
414	self.services
415		.short
416		.multi_get_eventid_from_short(shorteventids)
417		.zip(shortstatekeys)
418		.ready_filter_map(|(event_id, shortstatekey)| Some((shortstatekey, event_id.ok()?)))
419}
420
421#[implement(super::Service)]
422pub fn state_full_shortids(
423	&self,
424	shortstatehash: ShortStateHash,
425) -> impl Stream<Item = Result<(ShortStateKey, ShortEventId)>> + Send + '_ {
426	self.load_full_state(shortstatehash)
427		.map_ok(|full_state| {
428			full_state
429				.deref()
430				.iter()
431				.copied()
432				.map(parse_compressed_state_event)
433				.collect()
434		})
435		.map_ok(Vec::into_iter)
436		.map_ok(IterStream::try_stream)
437		.try_flatten_stream()
438}
439
440#[implement(super::Service)]
441#[tracing::instrument(name = "load", level = "debug", skip(self))]
442async fn load_full_state(&self, shortstatehash: ShortStateHash) -> Result<Arc<CompressedState>> {
443	self.services
444		.state_compressor
445		.load_shortstatehash_info(shortstatehash)
446		.map_err(|e| err!(Database("Missing state IDs: {e}")))
447		.map_ok(|vec| {
448			vec.last()
449				.expect("at least one layer")
450				.full_state
451				.clone()
452		})
453		.await
454}