tuwunel_service/rooms/typing/
mod.rs1use std::{collections::BTreeMap, sync::Arc};
2
3use futures::{FutureExt, StreamExt, TryStreamExt, future::try_join, stream::unfold};
4use ruma::{
5 OwnedRoomId, OwnedUserId, RoomId, UserId,
6 api::{
7 appservice::event::push_events::v1::EphemeralData,
8 federation::transactions::edu::{Edu, TypingContent},
9 },
10 events::{
11 EphemeralRoomEvent, GlobalAccountDataEventType, ignored_user_list::IgnoredUserListEvent,
12 typing::TypingEventContent,
13 },
14};
15use tokio::sync::{
16 RwLock,
17 broadcast::{self, error::RecvError},
18};
19use tuwunel_core::{
20 Result, Server,
21 debug::INFO_SPAN_LEVEL,
22 debug_info, trace,
23 utils::{BoolExt, IterStream, millis_since_unix_epoch},
24};
25
26use crate::sending::EduBuf;
27
28pub struct Service {
29 server: Arc<Server>,
30 services: Arc<crate::services::OnceServices>,
31 typing: RwLock<BTreeMap<OwnedRoomId, RoomTyping>>,
32 pub typing_update_sender: broadcast::Sender<OwnedRoomId>,
33}
34
35#[derive(Default)]
36struct RoomTyping {
37 users: BTreeMap<OwnedUserId, u64>,
39 update: u64,
42}
43
44impl crate::Service for Service {
45 fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
46 Ok(Arc::new(Self {
47 server: args.server.clone(),
48 services: args.services.clone(),
49 typing: RwLock::new(BTreeMap::new()),
50 typing_update_sender: broadcast::channel(100).0,
51 }))
52 }
53
54 fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
55}
56
57impl Service {
58 #[tracing::instrument(
61 name = "typing_start"
62 level = INFO_SPAN_LEVEL,
63 skip_all,
64 fields(
65 %room_id,
66 %user_id,
67 %timeout,
68 )
69 )]
70 pub async fn typing_add(&self, user_id: &UserId, room_id: &RoomId, timeout: u64) -> Result {
71 debug_info!("typing started {user_id:?} in {room_id:?} timeout:{timeout:?}");
72
73 let mut typing = self.typing.write().await;
75 let room = typing.entry(room_id.to_owned()).or_default();
76 room.users.insert(user_id.to_owned(), timeout);
77
78 let count = self.services.globals.next_count();
79
80 room.update = *count;
81
82 drop(typing);
83 drop(count);
84
85 if self
86 .typing_update_sender
87 .send(room_id.to_owned())
88 .is_err()
89 {
90 trace!("receiver found what it was looking for and is no longer interested");
91 }
92
93 let appservice_send = self.appservice_send(room_id);
95
96 let federation_send = self
98 .services
99 .globals
100 .user_is_local(user_id)
101 .then_async(|| self.federation_send(room_id, user_id, true))
102 .map(Option::transpose);
103
104 try_join(appservice_send, federation_send)
105 .await
106 .map(|_| ())
107 }
108
109 #[tracing::instrument(
111 name = "typing_stop"
112 level = INFO_SPAN_LEVEL,
113 skip_all,
114 fields(
115 %room_id,
116 %user_id,
117 )
118 )]
119 pub async fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result {
120 debug_info!("typing stopped {user_id:?} in {room_id:?}");
121
122 let mut typing = self.typing.write().await;
124 let room = typing.entry(room_id.to_owned()).or_default();
125 room.users.remove(user_id);
126
127 let count = self.services.globals.next_count();
128
129 room.update = *count;
130
131 drop(typing);
132 drop(count);
133
134 if self
135 .typing_update_sender
136 .send(room_id.to_owned())
137 .is_err()
138 {
139 trace!("receiver found what it was looking for and is no longer interested");
140 }
141
142 let appservice_send = self.appservice_send(room_id);
144
145 let federation_send = self
147 .services
148 .globals
149 .user_is_local(user_id)
150 .then_async(|| self.federation_send(room_id, user_id, false))
151 .map(Option::transpose);
152
153 try_join(appservice_send, federation_send)
154 .await
155 .map(|_| ())
156 }
157
158 pub fn wait_for_update(
166 &self,
167 room_id: OwnedRoomId,
168 since: u64,
169 ) -> impl Future<Output = ()> + Send + '_ {
170 let receiver = self.typing_update_sender.subscribe();
171
172 async move {
175 unfold(receiver, async |mut receiver| Some((receiver.recv().await, receiver)))
176 .any(async |update| match update {
177 | Ok(next) => next == room_id,
178 | Err(RecvError::Lagged(_)) => self.lag_wakes(&room_id, since).await,
179 | Err(RecvError::Closed) => true,
180 })
181 .await;
182 }
183 }
184
185 async fn lag_wakes(&self, room_id: &RoomId, since: u64) -> bool {
192 let now = millis_since_unix_epoch();
193
194 self.typing
195 .read()
196 .map(|typing| {
197 typing
198 .get(room_id)
199 .is_some_and(|room| room.update > since || room.has_expired(now))
200 })
201 .await
202 }
203
204 async fn typings_maintain(&self, room_id: &RoomId) -> Result {
206 let current_timestamp = millis_since_unix_epoch();
207 let typing = self.typing.read().await;
208 let has_expired = typing
209 .get(room_id)
210 .is_some_and(|room| room.has_expired(current_timestamp));
211
212 drop(typing);
213
214 if !has_expired {
215 return Ok(());
216 }
217
218 let current_timestamp = millis_since_unix_epoch();
219 let mut removable = Vec::new();
220 let mut typing = self.typing.write().await;
221 let Some(room) = typing.get_mut(room_id) else {
222 return Ok(());
223 };
224
225 room.users.retain(|user, timeout| {
226 let expired = *timeout < current_timestamp;
227 if expired {
228 removable.push(user.clone());
229 }
230
231 expired.is_false()
232 });
233
234 if removable.is_empty() {
235 return Ok(());
236 }
237
238 let count = self.services.globals.next_count();
240
241 room.update = *count;
242
243 drop(typing);
244 drop(count);
245
246 for user in &removable {
247 debug_info!("typing timeout {user:?} in {room_id:?}");
248 }
249
250 if self
251 .typing_update_sender
252 .send(room_id.to_owned())
253 .is_err()
254 {
255 trace!("receiver found what it was looking for and is no longer interested");
256 }
257
258 let appservice_send = self.appservice_send(room_id);
260
261 let federation_sends = removable
263 .iter()
264 .filter(|user_id| self.services.globals.user_is_local(user_id))
265 .try_stream()
266 .try_for_each(|user_id| self.federation_send(room_id, user_id, false));
267
268 try_join(appservice_send, federation_sends)
269 .boxed() .await
271 .map(|_| ())
272 }
273
274 pub async fn last_typing_update(&self, room_id: &RoomId) -> Result<u64> {
276 self.typings_maintain(room_id).await?;
277
278 self.typing
279 .read()
280 .await
281 .get(room_id)
282 .map(|room| room.update)
283 .map(Ok)
284 .unwrap_or(Ok(0))
285 }
286
287 async fn typings_content(&self, room_id: &RoomId) -> TypingEventContent {
289 let typing = self.typing.read().await;
290 let user_ids = typing
291 .get(room_id)
292 .into_iter()
293 .flat_map(|room| room.users.keys().cloned())
294 .collect();
295
296 TypingEventContent { user_ids }
297 }
298
299 async fn appservice_send(&self, room_id: &RoomId) -> Result {
301 let content = self.typings_content(room_id).await;
302
303 self.services
304 .sending
305 .send_edu_room_appservices(room_id, |buf| {
306 let edu = EphemeralData::Typing(EphemeralRoomEvent {
307 room_id: room_id.to_owned(),
308 content: content.clone(),
309 });
310
311 Ok(serde_json::to_writer(buf, &edu)?)
312 })
313 .await
314 }
315
316 pub async fn typing_users_for_user(
318 &self,
319 room_id: &RoomId,
320 sender_user: &UserId,
321 ) -> Result<Vec<OwnedUserId>> {
322 let typing = self.typing.read().await;
323 let user_ids = typing
324 .get(room_id)
325 .into_iter()
326 .flat_map(|room| room.users.keys().cloned())
327 .collect();
328 drop(typing);
329
330 Ok(self
331 .filter_typing_users(user_ids, sender_user)
332 .await)
333 }
334
335 pub async fn typing_snapshot_for_user<Select>(
341 &self,
342 room_id: &RoomId,
343 sender_user: &UserId,
344 select: Select,
345 ) -> Result<Option<(u64, Vec<OwnedUserId>)>>
346 where
347 Select: FnOnce(u64) -> bool + Send,
348 {
349 self.typings_maintain(room_id).await?;
350
351 let typing = self.typing.read().await;
352 let room = typing.get(room_id);
353 let update = room.map_or(0, |room| room.update);
354
355 if !select(update) {
356 return Ok(None);
357 }
358
359 let user_ids = room
360 .into_iter()
361 .flat_map(|room| room.users.keys().cloned())
362 .collect();
363
364 drop(typing);
365
366 let user_ids = self
367 .filter_typing_users(user_ids, sender_user)
368 .await;
369
370 Ok(Some((update, user_ids)))
371 }
372
373 async fn filter_typing_users(
374 &self,
375 user_ids: Vec<OwnedUserId>,
376 sender_user: &UserId,
377 ) -> Vec<OwnedUserId> {
378 if user_ids.is_empty() {
379 return user_ids;
380 }
381
382 let ignored: Option<IgnoredUserListEvent> = self
383 .services
384 .account_data
385 .get_global(sender_user, GlobalAccountDataEventType::IgnoredUserList)
386 .await
387 .ok();
388
389 user_ids
390 .into_iter()
391 .filter(|user_id| {
392 ignored.as_ref().is_none_or(|ignored| {
393 !ignored
394 .content
395 .ignored_users
396 .contains_key::<UserId>(user_id.as_ref())
397 })
398 })
399 .collect()
400 }
401
402 async fn federation_send(&self, room_id: &RoomId, user_id: &UserId, typing: bool) -> Result {
403 debug_assert!(
404 self.services.globals.user_is_local(user_id),
405 "tried to broadcast typing status of remote user",
406 );
407
408 if !self.server.config.typing.allow_outgoing {
409 return Ok(());
410 }
411
412 let content = TypingContent::new(room_id.to_owned(), user_id.to_owned(), typing);
413 let edu = Edu::Typing(content);
414
415 let mut buf = EduBuf::new();
416 serde_json::to_writer(&mut buf, &edu).expect("Serialized Edu::Typing");
417
418 self.services
419 .sending
420 .send_edu_room(room_id, buf)
421 .await?;
422
423 Ok(())
424 }
425}
426
427impl RoomTyping {
428 fn has_expired(&self, now: u64) -> bool { self.users.values().any(|timeout| *timeout < now) }
429}