Skip to main content

tuwunel_service/sending/sender/select/
presence.rs

1use std::{
2	collections::BTreeMap,
3	convert::identity,
4	sync::atomic::{AtomicU64, AtomicUsize, Ordering},
5};
6
7use futures::StreamExt;
8use ruma::{
9	OwnedUserId, ServerName, UserId,
10	api::federation::transactions::edu::{Edu, PresenceContent, PresenceUpdate},
11};
12use tuwunel_core::{
13	implement,
14	utils::{ReadyExt, result::LogErr, stream::TryReadyExt},
15};
16
17use super::edu_buf;
18use crate::sending::{EDU_LIMIT, EduBuf, Service};
19
20/// The latest presence state per user gathered for one EDU.
21type Updates = BTreeMap<OwnedUserId, PresenceUpdate>;
22
23const USER_LIMIT: usize = 256;
24
25/// Select one presence EDU for the users a server may see.
26///
27/// The window's local presence transitions collapse into one `Edu::Presence`
28/// carrying the latest state per user. A budget trip drops it, and presence
29/// self-heals on the next transition.
30#[implement(Service)]
31#[tracing::instrument(
32	name = "presence",
33	level = "trace",
34	skip(self, server_name, max_edu_count, events_len)
35)]
36pub(super) async fn select_edus_presence(
37	&self,
38	server_name: &ServerName,
39	since: (u64, u64),
40	max_edu_count: &AtomicU64,
41	events_len: &AtomicUsize,
42) -> Option<EduBuf> {
43	// Sequential mapping parks the cursor while the item's borrows cross the awaits.
44	let updates = self
45		.services
46		.presence
47		.presence_since(since.0, Some(since.1))
48		.inspect(|(_, count, _)| {
49			debug_assert!(*count <= since.1, "exceeded upper-bound");
50			max_edu_count.fetch_max(*count, Ordering::Relaxed);
51		})
52		.ready_filter(|(user_id, ..)| self.services.globals.user_is_local(user_id))
53		.filter_map(|(user_id, _, presence_bytes)| {
54			self.presence_update(server_name, user_id, presence_bytes)
55		})
56		.map(Ok)
57		.ready_try_fold(Updates::new(), |mut updates, (user_id, update)| {
58			updates.insert(user_id, update);
59
60			// The distinct-user limit ends the scan with the map as the error.
61			if updates.len() >= USER_LIMIT {
62				Err(updates)
63			} else {
64				Ok(updates)
65			}
66		})
67		.await
68		.unwrap_or_else(identity);
69
70	if updates.is_empty() {
71		return None;
72	}
73
74	// A budget trip drops presence, which self-heals on the next transition.
75	if events_len.fetch_add(1, Ordering::Relaxed) >= EDU_LIMIT {
76		return None;
77	}
78
79	Some(edu_buf(&Edu::Presence(PresenceContent {
80		push: updates.into_values().collect(),
81	})))
82}
83
84/// The presence update to ship for one transition, if the server may see it.
85#[implement(Service)]
86async fn presence_update(
87	&self,
88	server_name: &ServerName,
89	user_id: &UserId,
90	presence_bytes: &[u8],
91) -> Option<(OwnedUserId, PresenceUpdate)> {
92	if !self
93		.services
94		.state_cache
95		.server_sees_user(server_name, user_id)
96		.await
97	{
98		return None;
99	}
100
101	let update = self
102		.services
103		.presence
104		.from_json_bytes_to_update(presence_bytes, user_id)
105		.log_err()
106		.ok()?;
107
108	Some((user_id.to_owned(), update))
109}