Skip to main content

tuwunel_service/presence/
mod.rs

1mod aggregate;
2mod data;
3// Write/update pipeline lives in pipeline.rs.
4mod pipeline;
5
6use std::{collections::HashMap, net::IpAddr, sync::Arc, time::Duration};
7
8use async_trait::async_trait;
9use futures::{
10	Stream, StreamExt, TryFutureExt,
11	future::{AbortHandle, Abortable, join},
12	stream::FuturesUnordered,
13};
14use loole::{Receiver, Sender};
15use ruma::{
16	DeviceId, OwnedUserId, UInt, UserId,
17	api::federation::transactions::edu::PresenceUpdate,
18	events::presence::{PresenceEvent, PresenceEventContent},
19	presence::PresenceState,
20};
21use serde::{Deserialize, Serialize};
22use tokio::sync::RwLock;
23use tuwunel_core::{
24	Result, checked, debug, debug_warn, err, implement,
25	result::LogErr,
26	trace,
27	utils::{TryFutureExtExt, millis_since_unix_epoch},
28};
29
30use self::{aggregate::PresenceAggregator, data::Data};
31use crate::appservice::RegistrationInfo;
32
33#[derive(Default)]
34pub struct Ping<'a> {
35	pub device_id: Option<&'a DeviceId>,
36	pub client_ip: Option<IpAddr>,
37	pub new_state: Option<&'a PresenceState>,
38	pub appservice: Option<&'a RegistrationInfo>,
39}
40
41/// Represents data required to be kept in order to implement the presence
42/// specification.
43#[derive(Serialize, Deserialize, Debug, Clone)]
44pub(super) struct Presence {
45	pub(super) state: PresenceState,
46	pub(super) currently_active: bool,
47	pub(super) last_active_ts: u64,
48	pub(super) status_msg: Option<String>,
49}
50
51impl Presence {
52	pub(super) fn from_json_bytes(bytes: &[u8]) -> Result<Self> {
53		serde_json::from_slice(bytes)
54			.map_err(|_| err!(Database(error!("Invalid presence data in database"))))
55	}
56}
57
58pub struct Service {
59	timer_channel: (Sender<TimerType>, Receiver<TimerType>),
60	timeout_remote_users: bool,
61	idle_timeout: u64,
62	offline_timeout: u64,
63	db: Data,
64	services: Arc<crate::services::OnceServices>,
65	last_sync_seen: RwLock<HashMap<OwnedUserId, u64>>,
66	device_presence: PresenceAggregator,
67}
68
69type TimerType = (OwnedUserId, Duration, u64);
70type TimerFired = (OwnedUserId, u64);
71
72#[async_trait]
73impl crate::Service for Service {
74	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
75		let config = &args.server.config;
76		let idle_timeout_s = config.presence.idle_timeout_s;
77		let offline_timeout_s = config.presence.offline_timeout_s;
78
79		Ok(Arc::new(Self {
80			timer_channel: loole::unbounded(),
81			timeout_remote_users: config.presence.timeout_remote_users,
82			idle_timeout: checked!(idle_timeout_s * 1_000)?,
83			offline_timeout: checked!(offline_timeout_s * 1_000)?,
84			db: Data::new(args),
85			services: args.services.clone(),
86			last_sync_seen: RwLock::new(HashMap::new()),
87			device_presence: PresenceAggregator::new(),
88		}))
89	}
90
91	async fn worker(self: Arc<Self>) -> Result {
92		// reset dormant online/away statuses to offline, and set the server user as
93		// online
94		self.unset_all_presence().await;
95		self.device_presence.clear().await;
96		_ = self
97			.maybe_ping_presence(&self.services.globals.server_user, Ping::default())
98			.await;
99
100		let receiver = self.timer_channel.1.clone();
101
102		let mut presence_timers: FuturesUnordered<_> = FuturesUnordered::new();
103		let mut timer_handles: HashMap<OwnedUserId, (u64, AbortHandle)> = HashMap::new();
104		while !receiver.is_closed() && self.services.server.is_running() {
105			tokio::select! {
106				Some(result) = presence_timers.next() => {
107					let Ok((user_id, count)) = result else {
108						continue;
109					};
110
111					if let Some((current_count, _)) = timer_handles.get(&user_id)
112						&& *current_count != count {
113						trace!(?user_id, count, current_count, "Skipping stale presence timer");
114						continue;
115					}
116
117					timer_handles.remove(&user_id);
118					self.process_presence_timer(&user_id, count).await.log_err().ok();
119				},
120				event = receiver.recv_async() => match event {
121					Ok((user_id, timeout, count)) => {
122						debug!(
123							"Adding timer {}: {user_id} timeout:{timeout:?} count:{count}",
124							presence_timers.len()
125						);
126						if let Some((_, handle)) = timer_handles.remove(&user_id) {
127							handle.abort();
128						}
129
130						let (handle, reg) = AbortHandle::new_pair();
131						presence_timers.push(Abortable::new(
132							pipeline::presence_timer(user_id.clone(), timeout, count),
133							reg,
134						));
135						timer_handles.insert(user_id, (count, handle));
136					},
137					_ => break,
138				},
139			}
140		}
141
142		// set the server user as offline
143		let ping = Ping {
144			new_state: Some(&PresenceState::Offline),
145			..Default::default()
146		};
147
148		_ = self
149			.maybe_ping_presence(&self.services.globals.server_user, ping)
150			.await;
151
152		Ok(())
153	}
154
155	async fn interrupt(&self) {
156		let (timer_sender, _) = &self.timer_channel;
157		if !timer_sender.is_closed() {
158			timer_sender.close();
159		}
160	}
161
162	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
163}
164
165impl Service {
166	/// record that a user has just successfully completed a /sync (or
167	/// equivalent activity)
168	pub async fn note_sync(&self, user_id: &UserId, appservice: Option<&RegistrationInfo>) {
169		if appservice.is_some() || !self.services.config.push.suppress_when_active {
170			return;
171		}
172
173		let now = millis_since_unix_epoch();
174		self.last_sync_seen
175			.write()
176			.await
177			.insert(user_id.to_owned(), now);
178	}
179
180	/// Returns milliseconds since last observed sync for user (if any)
181	pub async fn last_sync_gap_ms(&self, user_id: &UserId) -> Option<u64> {
182		let now = millis_since_unix_epoch();
183		self.last_sync_seen
184			.read()
185			.await
186			.get(user_id)
187			.map(|ts| now.saturating_sub(*ts))
188	}
189
190	/// Returns the latest presence event for the given user.
191	pub async fn get_presence(&self, user_id: &UserId) -> Result<PresenceEvent> {
192		self.db
193			.get_presence(user_id)
194			.map_ok(|(_, presence)| presence)
195			.await
196	}
197
198	/// Removes the presence record for the given user from the database.
199	///
200	/// TODO: Why is this not used?
201	pub async fn remove_presence(&self, user_id: &UserId) {
202		self.db.remove_presence(user_id).await;
203	}
204
205	// Unset online/unavailable presence to offline on startup
206	async fn unset_all_presence(&self) {
207		if !self.services.server.config.presence.allow_local || self.services.db.is_read_only() {
208			return;
209		}
210
211		let _cork = self.services.db.cork();
212
213		for user_id in &self
214			.services
215			.users
216			.list_local_users()
217			.map(UserId::to_owned)
218			.collect::<Vec<_>>()
219			.await
220		{
221			let presence = self.db.get_presence(user_id).await;
222
223			let presence = match presence {
224				| Ok((_, ref presence)) => &presence.content,
225				| _ => continue,
226			};
227
228			if !matches!(
229				presence.presence,
230				PresenceState::Unavailable | PresenceState::Online | PresenceState::Busy
231			) {
232				trace!(?user_id, ?presence, "Skipping user");
233				continue;
234			}
235
236			trace!(?user_id, ?presence, "Resetting presence to offline");
237
238			_ = self
239				.set_presence(
240					user_id,
241					&PresenceState::Offline,
242					Some(false),
243					presence.last_active_ago,
244					presence.status_msg.clone(),
245				)
246				.await
247				.inspect_err(|e| {
248					debug_warn!(
249						?presence,
250						"{user_id} has invalid presence in database and failed to reset it to \
251						 offline: {e}"
252					);
253				});
254		}
255	}
256
257	/// Returns the most recent presence updates that happened after the event
258	/// with id `since`.
259	pub fn presence_since(
260		&self,
261		since: u64,
262		to: Option<u64>,
263	) -> impl Stream<Item = (&UserId, u64, &[u8])> + Send + '_ {
264		self.db.presence_since(since, to)
265	}
266
267	#[inline]
268	pub async fn from_json_bytes_to_event(
269		&self,
270		bytes: &[u8],
271		user_id: &UserId,
272	) -> Result<PresenceEvent> {
273		let presence = Presence::from_json_bytes(bytes)?;
274		let event = self.to_presence_event(presence, user_id).await;
275
276		Ok(event)
277	}
278
279	/// Creates a PresenceEvent from available data.
280	async fn to_presence_event(&self, presence: Presence, user_id: &UserId) -> PresenceEvent {
281		let now = millis_since_unix_epoch();
282		let last_active_ago = now.saturating_sub(presence.last_active_ts);
283
284		let avatar_url = self.services.profile.avatar_url(user_id).ok();
285		let displayname = self.services.profile.displayname(user_id).ok();
286		let (avatar_url, displayname) = join(avatar_url, displayname).await;
287
288		PresenceEvent {
289			sender: user_id.to_owned(),
290			content: PresenceEventContent {
291				presence: presence.state,
292				status_msg: presence.status_msg,
293				currently_active: Some(presence.currently_active),
294				last_active_ago: Some(UInt::new_saturating(last_active_ago)),
295				avatar_url,
296				displayname,
297			},
298		}
299	}
300}
301
302/// Decode stored presence for a federation update.
303///
304/// Activity age saturates at the protocol integer limit and at zero for future
305/// timestamps. Federation updates omit profile fields and require no profile reads.
306#[implement(Service)]
307pub fn from_json_bytes_to_update(
308	&self,
309	bytes: &[u8],
310	user_id: &UserId,
311) -> Result<PresenceUpdate> {
312	let presence = Presence::from_json_bytes(bytes)?;
313	let now = millis_since_unix_epoch();
314	let last_active_ago = now.saturating_sub(presence.last_active_ts);
315
316	Ok(PresenceUpdate {
317		user_id: user_id.to_owned(),
318		presence: presence.state,
319		currently_active: presence.currently_active,
320		status_msg: presence.status_msg,
321		last_active_ago: UInt::new_saturating(last_active_ago),
322	})
323}
324
325/// Returns the latest optional presence event.
326///
327/// An absent index returns none. Payload and decoding errors remain visible.
328#[implement(Service)]
329pub async fn get_presence_optional(&self, user_id: &UserId) -> Result<Option<PresenceEvent>> {
330	self.db
331		.get_presence_optional(user_id)
332		.map_ok(|presence| presence.map(|(_, presence)| presence))
333		.await
334}