Skip to main content

tuwunel_service/rooms/typing/
mod.rs

1use 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	// Unix epoch millisecond timestamp when each typing indicator expires.
38	users: BTreeMap<OwnedUserId, u64>,
39	// Global stream position of the last change to this room. The count permit must
40	// retire only after releasing the typing state lock.
41	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	/// Sets a user as typing until the timeout timestamp is reached or
59	/// roomtyping_remove is called.
60	#[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		// update clients
74		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		// update appservices
94		let appservice_send = self.appservice_send(room_id);
95
96		// update federation
97		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	/// Removes a user from typing before the timeout is reached.
110	#[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		// update clients
123		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		// update appservices
143		let appservice_send = self.appservice_send(room_id);
144
145		// update federation
146		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	/// Returns a future that resolves on the next typing update in this room.
159	///
160	/// The receiver subscribes before this returns, so the update is seen however
161	/// late the future is first polled. A lagged receiver has lost the messages it
162	/// would have matched, so it asks the room instead. Callers pass a retired
163	/// count as `since` and run `wait_pending` after registering, so an update at
164	/// or below it needs no wake.
165	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		// Not an `async fn`, which would defer the subscribe to the first poll.
173		// The block owns `room_id`: `any` rejects an async closure owning it.
174		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	/// Returns whether a receiver that lagged should wake for this room.
186	///
187	/// It should for an update past `since`, and for a typist past their timeout,
188	/// whom only a pass removes. This reads and leaves the removal to that pass: a
189	/// sibling's wake can drop the watcher at any await, and expiry removes typists
190	/// before it tells federation, so a drop there would lose the stop for good.
191	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	/// Makes sure that typing events with old timestamps get removed.
205	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		// update clients
239		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		// update appservices
259		let appservice_send = self.appservice_send(room_id);
260
261		// update federation
262		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() // erase region
270			.await
271			.map(|_| ())
272	}
273
274	/// Returns the count of the last typing update in this room.
275	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	/// Returns the typing content with all typing users in the room.
288	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	/// Sends a typing EDU to all appservices interested in the room.
300	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	/// Returns a new typing EDU.
317	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	/// Returns one coherent typing update token and visible user snapshot.
336	///
337	/// The predicate checks the token under the same lock and can skip cloning
338	/// stale users. Selected user IDs are captured before ignored users are
339	/// filtered after releasing the lock.
340	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}