tuwunel_service/rooms/spaces/
mod.rs1mod cache;
2mod federation;
3mod local;
4mod pagination_token;
5#[cfg(test)]
6mod tests;
7
8use std::{fmt::Debug, sync::Arc};
9
10use async_trait::async_trait;
11use futures::{FutureExt, Stream, StreamExt, TryFutureExt};
12use ruma::{
13 OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, ServerName, UserId,
14 api::{
15 client::space::SpaceHierarchyRoomsChunk,
16 federation::space::SpaceHierarchyParentSummary as ParentSummary,
17 },
18 events::{
19 StateEventType,
20 space::child::{HierarchySpaceChildEvent as ChildEvent, SpaceChildEventContent},
21 },
22 room::{JoinRuleSummary, RestrictedSummary},
23 serde::Raw,
24};
25use tuwunel_core::{
26 Err, Result, implement,
27 utils::{
28 future::{BoolExt, TryExtExt},
29 stream::{BroadbandExt, IterStream, ReadyExt, TryReadyExt},
30 },
31};
32use tuwunel_database::Map;
33use tuwunel_matrix::Event;
34
35use self::cache::Cached;
36pub use self::pagination_token::PaginationToken;
37
38pub struct Service {
39 services: Arc<crate::services::OnceServices>,
40 db: Db,
41}
42
43struct Db {
44 roomid_spacehierarchy: Arc<Map>,
45}
46
47#[expect(clippy::large_enum_variant)]
48#[derive(Clone, Debug)]
49pub enum Accessibility {
50 Accessible(ParentSummary),
51 Inaccessible,
52}
53
54#[derive(Debug)]
57pub enum Identifier<'a> {
58 UserId(&'a UserId),
59 ServerName(&'a ServerName),
60}
61
62#[async_trait]
63impl crate::Service for Service {
64 fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
65 Ok(Arc::new(Self {
66 services: args.services.clone(),
67 db: Db {
68 roomid_spacehierarchy: args.db["roomid_spacehierarchy"].clone(),
69 },
70 }))
71 }
72
73 async fn clear_cache(&self) { self.db.roomid_spacehierarchy.clear().await; }
74
75 fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
76}
77
78#[implement(Service)]
81#[tracing::instrument(
82 name = "summary",
83 level = "debug",
84 ret(level = "trace")
85 skip_all,
86 fields(
87 ?room_id,
88 ?sender,
89 via = via.len(),
90 )
91)]
92pub async fn get_summary_and_children(
93 &self,
94 room_id: &RoomId,
95 sender: &Identifier<'_>,
96 via: &[OwnedServerName],
97) -> Result<Accessibility> {
98 debug_assert!(
99 matches!(sender, Identifier::UserId(_)) || via.is_empty(),
100 "The federation handler must not produce federation requests.",
101 );
102
103 self.get_summary_and_children_local(room_id, sender)
104 .or_else(async |e| match e {
105 | _ if !e.is_not_found() => Err(e),
106
107 | _ if via.is_empty() =>
108 Err!(Request(NotFound("Space room not found locally; not querying federation"))),
109
110 | _ =>
111 self.get_summary_and_children_federation(room_id, sender, via)
112 .boxed() .await,
114 })
115 .await
116}
117
118#[implement(Service)]
120pub fn get_space_children<'a>(
121 &'a self,
122 room_id: &'a RoomId,
123) -> impl Stream<Item = OwnedRoomId> + Send + 'a {
124 self.services
125 .state_accessor
126 .room_state_keys(room_id, &StateEventType::SpaceChild)
127 .ready_and_then(|state_key| OwnedRoomId::parse(state_key.as_str()).map_err(Into::into))
128 .ready_filter_map(Result::ok)
129}
130
131#[implement(Service)]
133fn get_space_child_events<'a>(
134 &'a self,
135 room_id: &'a RoomId,
136) -> impl Stream<Item = impl Event> + Send + 'a {
137 self.services
138 .state_accessor
139 .room_state_keys_with_ids(room_id, &StateEventType::SpaceChild)
140 .ready_filter_map(Result::ok)
141 .broad_filter_map(async |(state_key, event_id): (_, OwnedEventId)| {
142 self.services
143 .timeline
144 .get_pdu(&event_id)
145 .map_ok(move |pdu| (state_key, pdu))
146 .ok()
147 .await
148 })
149 .ready_filter_map(|(state_key, pdu)| {
150 let Ok(content) = pdu.get_content::<SpaceChildEventContent>() else {
151 return None;
152 };
153
154 if content.via.is_empty() {
155 return None;
156 }
157
158 if RoomId::parse(&state_key).is_err() {
159 return None;
160 }
161
162 Some(pdu)
163 })
164}
165
166#[implement(Service)]
168#[tracing::instrument(
169 level = "debug",
170 ret,
171 skip_all,
172 fields(
173 %current_room,
174 ?join_rule,
175 ?sender,
176 ),
177)]
178async fn is_accessible_child(
179 &self,
180 current_room: &RoomId,
181 join_rule: &JoinRuleSummary,
182 sender: &Identifier<'_>,
183) -> bool {
184 if let Identifier::ServerName(server_name) = sender {
185 if self
187 .services
188 .event_handler
189 .acl_check(server_name, current_room)
190 .await
191 .is_err()
192 {
193 return false;
194 }
195 }
196
197 if let Identifier::UserId(user_id) = sender {
198 let is_joined = self
199 .services
200 .state_cache
201 .is_joined(user_id, current_room);
202
203 let is_invited = self
204 .services
205 .state_cache
206 .is_invited(user_id, current_room);
207
208 if is_joined.or(is_invited).await {
209 return true;
210 }
211 }
212
213 match join_rule {
214 | JoinRuleSummary::Public
215 | JoinRuleSummary::Knock
216 | JoinRuleSummary::KnockRestricted(_) => true,
217
218 | JoinRuleSummary::Restricted(RestrictedSummary { allowed_room_ids })
219 if allowed_room_ids.is_empty() =>
220 true,
221
222 | JoinRuleSummary::Restricted(RestrictedSummary { allowed_room_ids }) =>
223 allowed_room_ids
224 .iter()
225 .stream()
226 .any(async |room| match sender {
227 | Identifier::UserId(user) =>
228 self.services
229 .state_cache
230 .is_joined(user, room)
231 .await,
232
233 | Identifier::ServerName(server) =>
234 self.services
235 .state_cache
236 .server_in_room(server, room)
237 .await,
238 })
239 .await,
240
241 | _ => false, }
243}
244
245pub fn get_parent_children_via(
248 parent: &ParentSummary,
249 suggested_only: bool,
250) -> impl DoubleEndedIterator<Item = (OwnedRoomId, impl Iterator<Item = OwnedServerName>)> + '_ {
251 parent
252 .children_state
253 .iter()
254 .map(Raw::deserialize)
255 .filter_map(Result::ok)
256 .filter_map(move |ChildEvent { state_key, content, .. }: _| {
257 (content.suggested || !suggested_only).then_some((state_key, content.via.into_iter()))
258 })
259}
260
261#[inline]
264#[must_use]
265pub fn summary_to_chunk(
266 ParentSummary { children_state, summary }: ParentSummary,
267) -> SpaceHierarchyRoomsChunk {
268 SpaceHierarchyRoomsChunk { children_state, summary }
269}
270
271#[inline]
272#[must_use]
273pub fn is_summary_serializable(summary: &ParentSummary) -> bool {
274 !matches!(summary.summary.join_rule, JoinRuleSummary::_Custom(_))
277}