Skip to main content

tuwunel_service/sync/
watch.rs

1use futures::{
2	FutureExt, Stream, StreamExt, future::BoxFuture, pin_mut, stream::FuturesUnordered,
3};
4use ruma::{DeviceId, RoomId, UserId};
5use tuwunel_core::{implement, trace};
6use tuwunel_database::{Interfix, Separator, serialize_key};
7
8/// Register all sync watchers for the given user, device, and rooms eagerly,
9/// then return a future that resolves when any watcher fires.
10///
11/// The outer `await` completes once registration is done. Callers must drive
12/// it before sampling state, so a write between the registration window and
13/// the long-poll await cannot be missed; that race had `MustSyncUntil` calls
14/// hang for the full timeout when fast-path federation invites landed during
15/// the gap.
16///
17/// Two-phase by design: outer await registers, inner future awaits a hit.
18#[implement(super::Service)]
19#[tracing::instrument(skip(self, rooms), level = "debug")]
20#[expect(clippy::async_yields_async)]
21pub async fn watch<'a, Rooms>(
22	&'a self,
23	user_id: &'a UserId,
24	device_id: Option<&'a DeviceId>,
25	rooms: Rooms,
26) -> impl Future<Output = ()> + Send + 'a
27where
28	Rooms: Stream<Item = &'a RoomId> + Send + 'a,
29{
30	let userid_prefix =
31		serialize_key((user_id, Interfix)).expect("failed to serialize watch prefix");
32
33	// Boxed for a heterogeneous fan of watchers.
34	let mut futures: FuturesUnordered<BoxFuture<'a, ()>> = [
35		self.db
36			.userroomid_joined
37			.watch_raw_prefix(&userid_prefix)
38			.boxed(),
39		self.db
40			.userroomid_invitestate
41			.watch_raw_prefix(&userid_prefix)
42			.boxed(),
43		self.db
44			.userroomid_leftstate
45			.watch_raw_prefix(&userid_prefix)
46			.boxed(),
47		self.db
48			.userroomid_knockedstate
49			.watch_raw_prefix(&userid_prefix)
50			.boxed(),
51		self.db
52			.userroomid_notificationcount
53			.watch_raw_prefix(&userid_prefix)
54			.boxed(),
55		self.db
56			.userroomid_highlightcount
57			.watch_raw_prefix(&userid_prefix)
58			.boxed(),
59		self.db
60			.roomusertype_roomuserdataid
61			.watch_prefix((Separator, user_id, Interfix))
62			.boxed(),
63		// More key changes (used when user is not joined to any rooms)
64		self.db
65			.keychangeid_userid
66			.watch_raw_prefix(&userid_prefix)
67			.boxed(),
68		// Profile changes (used when user is not joined to any rooms)
69		self.db
70			.profilechangeid_userid
71			.watch_raw_prefix(&userid_prefix)
72			.boxed(),
73		// One time keys
74		self.db
75			.userid_lastonetimekeyupdate
76			.watch_raw_prefix(user_id)
77			.boxed(),
78		// User account data
79		self.db
80			.roomuserdataid_accountdata
81			.watch_prefix((Option::<&RoomId>::None, user_id, Interfix))
82			.boxed(),
83	]
84	.into_iter()
85	.collect();
86
87	if let Some(device_id) = device_id {
88		// Return when *any* user changed their key
89		// TODO: only send for user they share a room with
90		futures.push(
91			self.db
92				.todeviceid_events
93				.watch_prefix((user_id, device_id, Interfix))
94				.boxed(),
95		);
96	}
97
98	// Every count up to this point is covered by the pass after this call.
99	let typing_since = self.services.globals.current_count();
100
101	// Drive the rooms stream during phase 1 so per-room watchers register
102	// before this fn returns. Stream items are not retained across cursor
103	// advances; the rocksdb slice contract forbids stashing them.
104	pin_mut!(rooms);
105	while let Some(room_id) = rooms.next().await {
106		let Ok(short_roomid) = self.services.short.get_shortroomid(room_id).await else {
107			continue;
108		};
109
110		// Notification clearance
111		futures.push(
112			self.db
113				.roomuserid_lastnotificationread
114				.watch_prefix((room_id, user_id))
115				.boxed(),
116		);
117		// Key changes
118		futures.push(
119			self.db
120				.keychangeid_userid
121				.watch_prefix((room_id, Interfix))
122				.boxed(),
123		);
124		futures.push(
125			self.db
126				.profilechangeid_userid
127				.watch_prefix((room_id, Interfix))
128				.boxed(),
129		);
130		// Room account data
131		futures.push(
132			self.db
133				.roomusertype_roomuserdataid
134				.watch_prefix((room_id, user_id))
135				.boxed(),
136		);
137		// PDUs
138		futures.push(
139			self.db
140				.pduid_pdu
141				.watch_prefix(short_roomid)
142				.boxed(),
143		);
144		// EDUs
145		futures.push(
146			self.db
147				.readreceiptid_readreceipt
148				.watch_prefix((room_id, Interfix))
149				.boxed(),
150		);
151
152		futures.push(
153			self.services
154				.typing
155				.wait_for_update(room_id.to_owned(), typing_since)
156				.boxed(),
157		);
158	}
159
160	// Server shutdown
161	futures.push(self.services.server.until_shutdown().boxed());
162
163	async move {
164		if !self.services.server.is_running() {
165			return;
166		}
167
168		trace!(futures = futures.len(), "watch started");
169		futures.next().await;
170		trace!(futures = futures.len(), "watch finished");
171	}
172}