Skip to main content

tuwunel_service/rooms/state_cache/
mod.rs

1//! Persistent indexes derived from room membership state.
2//!
3//! The service maintains paired user-to-room and room-to-user membership rows,
4//! aggregate counts, participating-server indexes, and cached stripped state.
5//! Read helpers expose point queries and cursor-backed streams over those
6//! derived indexes.
7
8#[cfg(test)]
9mod tests;
10mod update;
11mod via;
12
13use std::{
14	collections::HashMap,
15	convert::identity,
16	sync::{Arc, RwLock},
17};
18
19use futures::{
20	Stream, StreamExt, TryStreamExt,
21	future::{join5, ready},
22	pin_mut,
23	stream::{empty, select},
24};
25use ruma::{
26	OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, ServerName, UserId,
27	events::{AnyStrippedStateEvent, AnySyncStateEvent, room::member::MembershipState},
28	serde::Raw,
29};
30use serde::de::DeserializeOwned;
31use tuwunel_core::{
32	Err, Result, at, debug_warn, err, implement, trace,
33	utils::{
34		self, BoolExt,
35		result::NotFound,
36		stream::{BroadbandExt, IterStream, ReadyExt, TryIgnore},
37	},
38	warn,
39};
40use tuwunel_database::{
41	Deserialized, Ignore, IgnoreAll, Interfix, Map, SEP, deserialize_from_slice,
42};
43use tuwunel_matrix::{Event, Pdu, event::Owned};
44use update::EMPTY_INVITE_STATE;
45/// Input types for applying membership-cache transitions.
46///
47/// The update descriptor owns event data while borrowing the affected user and
48/// room identifiers. Optional stripped state accompanies invite and knock
49/// transitions.
50pub use update::{MembershipUpdate, StrippedRoomState};
51
52use crate::appservice::RegistrationInfo;
53
54/// Persistent room-membership cache and derived-index service.
55///
56/// Paired indexes answer membership queries in either direction, while room
57/// aggregates track counts and participating servers. A process-local cache
58/// memoizes appservice membership decisions.
59pub struct Service {
60	appservice_in_room_cache: AppServiceInRoomCache,
61	services: Arc<crate::services::OnceServices>,
62	db: Data,
63}
64
65struct Data {
66	roomid_knockedcount: Arc<Map>,
67	roomid_invitedcount: Arc<Map>,
68	roomid_inviteviaservers: Arc<Map>,
69	roomid_joinedcount: Arc<Map>,
70	roomserverids: Arc<Map>,
71	roomuserid_invitecount: Arc<Map>,
72	roomuserid_joinedcount: Arc<Map>,
73	roomuserid_leftcount: Arc<Map>,
74	roomuserid_knockedcount: Arc<Map>,
75	roomuseroncejoinedids: Arc<Map>,
76	serverroomids: Arc<Map>,
77	userroomid_invitestate: Arc<Map>,
78	userroomid_joinedcount: Arc<Map>,
79	userroomid_leftstate: Arc<Map>,
80	userroomid_knockedstate: Arc<Map>,
81}
82
83type AppServiceInRoomCache = RwLock<HashMap<OwnedRoomId, HashMap<String, bool>>>;
84type StrippedState = Vec<Raw<AnyStrippedStateEvent>>;
85type StrippedStateEventItem = (OwnedRoomId, StrippedState);
86type SyncStateEventItem = (OwnedRoomId, Vec<Raw<AnySyncStateEvent>>);
87
88// CBOR tag 10 enclosing null, reserved for forgotten membership by this codec.
89const FORGOTTEN_STATE: &[u8] = b"\xCA\xF6";
90
91impl crate::Service for Service {
92	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
93		Ok(Arc::new(Self {
94			appservice_in_room_cache: RwLock::new(HashMap::new()),
95			services: args.services.clone(),
96			db: Data {
97				roomid_knockedcount: args.db["roomid_knockedcount"].clone(),
98				roomid_invitedcount: args.db["roomid_invitedcount"].clone(),
99				roomid_inviteviaservers: args.db["roomid_inviteviaservers"].clone(),
100				roomid_joinedcount: args.db["roomid_joinedcount"].clone(),
101				roomserverids: args.db["roomserverids"].clone(),
102				roomuserid_invitecount: args.db["roomuserid_invitecount"].clone(),
103				roomuserid_joinedcount: args.db["roomuserid_joined"].clone(),
104				roomuserid_leftcount: args.db["roomuserid_leftcount"].clone(),
105				roomuserid_knockedcount: args.db["roomuserid_knockedcount"].clone(),
106				roomuseroncejoinedids: args.db["roomuseroncejoinedids"].clone(),
107				serverroomids: args.db["serverroomids"].clone(),
108				userroomid_invitestate: args.db["userroomid_invitestate"].clone(),
109				userroomid_joinedcount: args.db["userroomid_joined"].clone(),
110				userroomid_leftstate: args.db["userroomid_leftstate"].clone(),
111				userroomid_knockedstate: args.db["userroomid_knockedstate"].clone(),
112			},
113		}))
114	}
115
116	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
117}
118
119/// Tests whether an appservice participates in a room.
120///
121/// A registration participates when its sender or a namespace-matching user is
122/// joined. Results are memoized by room and registration identifier. Membership
123/// rebuilds and explicit clears remove cached entries, but do not fence an
124/// in-flight lookup from republishing an older result. Deleting a room's
125/// membership indexes does not invalidate this cache.
126///
127/// A caller that may run alongside a re-registration must hold the appservice
128/// registry's read guard across the call, since the re-registration's clear
129/// relies on it; one holding a copied registration and no guard takes
130/// `appservice_in_room_uncached` instead.
131#[implement(Service)]
132#[tracing::instrument(level = "trace", skip_all)]
133pub async fn appservice_in_room(&self, room_id: &RoomId, appservice: &RegistrationInfo) -> bool {
134	let cached = self
135		.appservice_in_room_cache
136		.read()
137		.expect("locked")
138		.get(room_id)
139		.and_then(|map| map.get(&appservice.registration.id))
140		.copied();
141
142	if let Some(cached) = cached {
143		return cached;
144	}
145
146	let in_room = self
147		.appservice_in_room_uncached(room_id, appservice)
148		.await;
149
150	self.appservice_in_room_cache
151		.write()
152		.expect("locked")
153		.entry(room_id.into())
154		.or_default()
155		.insert(appservice.registration.id.clone(), in_room);
156
157	in_room
158}
159
160/// Tests whether an appservice participates in a room, bypassing the memo.
161///
162/// A registration participates when its sender or a namespace-matching user is
163/// joined, read from current membership. The memo is neither read nor filled,
164/// so the answer cannot be stale and the call needs no registry guard.
165#[implement(Service)]
166#[tracing::instrument(level = "trace", skip_all)]
167pub async fn appservice_in_room_uncached(
168	&self,
169	room_id: &RoomId,
170	appservice: &RegistrationInfo,
171) -> bool {
172	self.is_joined(&appservice.sender, room_id).await
173		|| self
174			.room_members(room_id)
175			.ready_any(|user_id| appservice.is_user_match(user_id))
176			.await
177}
178
179/// Returns the appservice membership cache's room count and capacity.
180///
181/// The first value counts room-level map entries rather than individual
182/// registrations. The second reports the backing map's current allocation
183/// capacity.
184#[implement(Service)]
185pub fn get_appservice_in_room_cache_usage(&self) -> (usize, usize) {
186	let cache = self
187		.appservice_in_room_cache
188		.read()
189		.expect("locked");
190
191	(cache.len(), cache.capacity())
192}
193
194/// Clears every memoized appservice membership decision.
195///
196/// Persistent membership indexes are not changed. Later lookups that miss the
197/// memo recompute and cache their answers from current joined membership, but
198/// a lookup already in flight can republish an older result after the clear.
199#[implement(Service)]
200#[tracing::instrument(level = "debug", skip_all)]
201pub fn clear_appservice_in_room_cache(&self) {
202	self.appservice_in_room_cache
203		.write()
204		.expect("locked")
205		.clear();
206}
207
208/// Clears the memoized membership decisions of one appservice.
209///
210/// Its cached answers may not hold once its registration's namespaces change;
211/// every other registration keeps its own. A lookup already in flight can
212/// republish an older result after the clear.
213#[implement(Service)]
214#[tracing::instrument(level = "debug", skip(self))]
215pub fn clear_appservice_in_room_cache_for(&self, appservice_id: &str) {
216	self.appservice_in_room_cache
217		.write()
218		.expect("locked")
219		.retain(|_, appservices| {
220			appservices.remove(appservice_id);
221			!appservices.is_empty()
222		});
223}
224
225/// Returns a stream of the remote servers participating in this room.
226///
227/// Our own server is filtered out, so the result is the federation fan-out
228/// set for the room. Items borrow the database cursor and are invalid after the
229/// next poll; consume or own each item before advancing. Storage errors are
230/// skipped as in [`Self::room_servers`].
231#[implement(Service)]
232#[tracing::instrument(skip(self), level = "trace")]
233pub fn remote_room_servers<'a>(
234	&'a self,
235	room_id: &'a RoomId,
236) -> impl Stream<Item = &ServerName> + Send + 'a {
237	self.room_servers(room_id)
238		.ready_filter(|server| !self.services.globals.server_is_ours(server))
239}
240
241/// Streams all servers recorded as participating in a room.
242///
243/// Storage and key-decoding failures are skipped. Each server name borrows the
244/// cursor and must be consumed or owned before the stream advances.
245#[implement(Service)]
246#[tracing::instrument(skip(self), level = "debug")]
247pub fn room_servers<'a>(
248	&'a self,
249	room_id: &'a RoomId,
250) -> impl Stream<Item = &ServerName> + Send + 'a {
251	let prefix = (room_id, Interfix);
252	self.db
253		.roomserverids
254		.keys_prefix(&prefix)
255		.ignore_err()
256		.map(|(_, server): (Ignore, &ServerName)| server)
257}
258
259/// Tests whether a server is recorded as participating in a room.
260///
261/// The reverse server-to-room index supplies the answer. Missing rows and
262/// storage failures both return `false`.
263#[implement(Service)]
264#[tracing::instrument(skip(self), level = "trace")]
265pub async fn server_in_room<'a>(&'a self, server: &'a ServerName, room_id: &'a RoomId) -> bool {
266	self.server_in_room_result(server, room_id)
267		.await
268		.unwrap_or(false)
269}
270
271/// Tests whether a server is recorded as participating in a room.
272///
273/// Missing rows return `false`; storage failures are preserved for callers
274/// whose authority decision depends on the result.
275#[implement(Service)]
276#[tracing::instrument(skip(self), level = "trace")]
277pub async fn server_in_room_result<'a>(
278	&'a self,
279	server: &'a ServerName,
280	room_id: &'a RoomId,
281) -> Result<bool> {
282	let key = (server, room_id);
283
284	match self.db.serverroomids.qry(&key).await {
285		| Ok(_) => Ok(true),
286		| Err(error) if error.is_not_found() => Ok(false),
287		| Err(error) => Err(error),
288	}
289}
290
291/// Streams all rooms recorded for a participating server.
292///
293/// Storage and key-decoding failures are skipped. Each room identifier borrows
294/// the cursor and must be consumed or owned before the stream advances.
295#[implement(Service)]
296#[tracing::instrument(skip(self), level = "debug")]
297pub fn server_rooms<'a>(
298	&'a self,
299	server: &'a ServerName,
300) -> impl Stream<Item = &RoomId> + Send + 'a {
301	let prefix = (server, Interfix);
302	self.db
303		.serverroomids
304		.keys_prefix(&prefix)
305		.ignore_err()
306		.map(|(_, room_id): (Ignore, &RoomId)| room_id)
307}
308
309/// Streams each server participating in at least one known room.
310///
311/// Adjacent duplicate prefixes are collapsed, yielding server names in
312/// ascending key order. Storage and decoding failures are skipped, and each
313/// item borrows the cursor until its next poll.
314#[implement(Service)]
315#[tracing::instrument(skip(self), level = "debug")]
316pub fn servers(&self) -> impl Stream<Item = &ServerName> + Send + '_ {
317	self.db
318		.serverroomids
319		.keys()
320		.ignore_err()
321		.ready_scan(
322			None,
323			|last: &mut Option<OwnedServerName>, (server, _): (&ServerName, Ignore)| {
324				let fresh = last.as_deref() != Some(server);
325
326				if fresh {
327					*last = Some(server.to_owned());
328				}
329
330				Some(fresh.then_some(server))
331			},
332		)
333		.ready_filter_map(identity)
334}
335
336/// Tests whether a server participates in any known room.
337///
338/// The check stops at the first reverse-index row. Errors skipped by
339/// [`Self::server_rooms`] are indistinguishable from absence.
340#[implement(Service)]
341#[tracing::instrument(skip(self), level = "trace")]
342pub async fn server_shares_room(&self, server: &ServerName) -> bool {
343	self.server_rooms(server)
344		.ready_any(|_| true)
345		.await
346}
347
348/// Tests whether a server shares a joined room with a user.
349///
350/// The check searches rooms recorded for the server for any current user
351/// join. Index errors are treated as absent rows by the underlying helpers.
352#[implement(Service)]
353#[tracing::instrument(skip(self), level = "trace")]
354pub async fn server_sees_user(&self, server: &ServerName, user_id: &UserId) -> bool {
355	self.server_rooms(server)
356		.map(ToOwned::to_owned)
357		.broad_any(async |room_id| self.is_joined(user_id, &room_id).await)
358		.await
359}
360
361/// Tests whether two users share a currently joined room.
362///
363/// The check consumes only the first intersection result. Storage or decoding
364/// failures skipped by the joined-room streams can produce `false`.
365#[implement(Service)]
366#[tracing::instrument(skip(self), level = "trace")]
367pub async fn user_sees_user(&self, user_a: &UserId, user_b: &UserId) -> bool {
368	let get_shared_rooms = self.get_shared_rooms(user_a, user_b);
369
370	pin_mut!(get_shared_rooms);
371	get_shared_rooms.next().await.is_some()
372}
373
374/// Streams rooms in which both users are currently joined.
375///
376/// The two key-ordered joined-room streams are intersected without
377/// materializing either set. Items borrow their source database cursor and are
378/// invalid after the next poll; consume or own each item before advancing. Read
379/// failures are skipped by the source streams.
380#[implement(Service)]
381#[tracing::instrument(skip(self), level = "debug")]
382pub fn get_shared_rooms<'a>(
383	&'a self,
384	user_a: &'a UserId,
385	user_b: &'a UserId,
386) -> impl Stream<Item = &RoomId> + Send + 'a {
387	let a = self.rooms_joined(user_a);
388	let b = self.rooms_joined(user_b);
389
390	utils::set::intersection_sorted_stream2(a, b)
391}
392
393/// Streams all users currently indexed as joined to a room.
394///
395/// Storage and key-decoding failures are skipped. Each user identifier borrows
396/// the cursor and must be consumed or owned before the stream advances.
397#[implement(Service)]
398#[tracing::instrument(skip(self), level = "debug")]
399pub fn room_members<'a>(
400	&'a self,
401	room_id: &'a RoomId,
402) -> impl Stream<Item = &UserId> + Send + 'a {
403	self.room_members_checked(room_id).ignore_err()
404}
405
406/// Streams joined users within the room's exact encoded prefix.
407///
408/// Storage and user-key decoding failures are surfaced as error items rather
409/// than dropped. User IDs borrow the cursor and must be consumed or owned
410/// before advancing it.
411#[implement(Service)]
412#[tracing::instrument(skip(self), level = "debug")]
413pub fn room_members_checked<'a>(
414	&'a self,
415	room_id: &'a RoomId,
416) -> impl Stream<Item = Result<&'a UserId>> + Send + 'a {
417	let prefix = (room_id, Interfix);
418
419	self.db
420		.roomuserid_joinedcount
421		.keys_prefix(&prefix)
422		.map_ok(|(_, user_id): (Ignore, &UserId)| user_id)
423}
424
425/// Returns the stored number of users currently joined to a room.
426///
427/// The aggregate is rebuilt from membership indexes by
428/// [`Self::update_joined_count`]. Missing or malformed count rows return an
429/// error.
430#[implement(Service)]
431#[tracing::instrument(skip(self), level = "trace")]
432pub async fn room_joined_count(&self, room_id: &RoomId) -> Result<u64> {
433	self.db
434		.roomid_joinedcount
435		.get(room_id)
436		.await
437		.deserialized()
438}
439
440/// Returns the stored number of users currently invited to a room.
441///
442/// The aggregate is rebuilt from membership indexes by
443/// [`Self::update_joined_count`]. Missing or malformed count rows return an
444/// error.
445#[implement(Service)]
446#[tracing::instrument(skip(self), level = "trace")]
447pub async fn room_invited_count(&self, room_id: &RoomId) -> Result<u64> {
448	self.db
449		.roomid_invitedcount
450		.get(room_id)
451		.await
452		.deserialized()
453}
454
455/// Returns the stored number of users currently knocking on a room.
456///
457/// The aggregate is rebuilt from membership indexes by
458/// [`Self::update_joined_count`]. Missing or malformed count rows return an
459/// error.
460#[implement(Service)]
461#[tracing::instrument(skip(self), level = "trace")]
462pub async fn room_knocked_count(&self, room_id: &RoomId) -> Result<u64> {
463	self.db
464		.roomid_knockedcount
465		.get(room_id)
466		.await
467		.deserialized()
468}
469
470/// Streams active local users currently joined to a room.
471///
472/// Local joined users are filtered through the user service, excluding guests
473/// and deactivated accounts. The stream otherwise inherits
474/// [`Self::room_members`]'s cursor lifetime and error policy.
475#[implement(Service)]
476#[tracing::instrument(skip(self), level = "debug")]
477pub fn active_local_users_in_room<'a>(
478	&'a self,
479	room_id: &'a RoomId,
480) -> impl Stream<Item = &UserId> + Send + 'a {
481	self.local_users_in_room(room_id)
482		.filter(|user| self.services.users.is_active(user))
483}
484
485/// Streams all local users currently joined to a room.
486///
487/// Guest and deactivated accounts remain included. The stream otherwise
488/// inherits [`Self::room_members`]'s cursor lifetime and error policy.
489#[implement(Service)]
490#[tracing::instrument(skip(self), level = "debug")]
491pub fn local_users_in_room<'a>(
492	&'a self,
493	room_id: &'a RoomId,
494) -> impl Stream<Item = &UserId> + Send + 'a {
495	self.room_members(room_id)
496		.ready_filter(|user| self.services.globals.user_is_local(user))
497}
498
499/// Streams local users currently invited to a room.
500///
501/// Remote invitees are filtered out by server name. The stream otherwise
502/// inherits [`Self::room_members_invited`]'s cursor lifetime and error policy.
503#[implement(Service)]
504#[tracing::instrument(skip(self), level = "debug")]
505pub fn local_users_invited_to_room<'a>(
506	&'a self,
507	room_id: &'a RoomId,
508) -> impl Stream<Item = &UserId> + Send + 'a {
509	self.room_members_invited(room_id)
510		.ready_filter(|user| self.services.globals.user_is_local(user))
511}
512
513/// Tests whether local memberships permit pruning a room.
514///
515/// Joins, invites, and knocks always protect the room. When required,
516/// departures protect it until forgotten; read failures propagate.
517/// Callers must hold the room state lock through this check and deletion.
518#[implement(Service)]
519#[tracing::instrument(skip(self), level = "debug")]
520pub async fn can_prune_room(&self, room_id: &RoomId, require_forgotten: bool) -> Result<bool> {
521	let prefix = (room_id, Interfix);
522	let occupied = [
523		&self.db.roomuserid_joinedcount,
524		&self.db.roomuserid_invitecount,
525		&self.db.roomuserid_knockedcount,
526	]
527	.into_iter()
528	.stream()
529	.flat_map(|map| map.keys_prefix(&prefix))
530	.try_any(|(_, user): (Ignore, &UserId)| ready(self.services.globals.user_is_local(user)))
531	.await?;
532
533	if occupied || !require_forgotten {
534		return Ok(!occupied);
535	}
536
537	self.db
538		.roomuserid_leftcount
539		.keys_prefix(&prefix)
540		.try_filter(|(_, user): &(Ignore, &UserId)| {
541			ready(self.services.globals.user_is_local(user))
542		})
543		.and_then(async |(_, user)| self.is_forgotten(user, room_id).await)
544		.try_all(ready)
545		.await
546}
547
548/// Streams user identifiers from the once-joined index under a room prefix.
549///
550/// Once-joined rows are currently written with user-first keys, while this
551/// accessor probes a room-first prefix, so the stored layout can yield no
552/// matches. Yielded user identifiers borrow the database cursor and are invalid
553/// after the next poll; consume or own each item before advancing. Storage and
554/// decoding failures are skipped.
555#[implement(Service)]
556#[tracing::instrument(skip(self), level = "debug")]
557pub fn room_useroncejoined<'a>(
558	&'a self,
559	room_id: &'a RoomId,
560) -> impl Stream<Item = &UserId> + Send + 'a {
561	let prefix = (room_id, Interfix);
562	self.db
563		.roomuseroncejoinedids
564		.keys_prefix(&prefix)
565		.ignore_err()
566		.map(|(_, user_id): (Ignore, &UserId)| user_id)
567}
568
569/// Streams all users currently indexed as invited to a room.
570///
571/// Storage and key-decoding failures are skipped. Each user identifier borrows
572/// the cursor and must be consumed or owned before the stream advances.
573#[implement(Service)]
574#[tracing::instrument(skip(self), level = "debug")]
575pub fn room_members_invited<'a>(
576	&'a self,
577	room_id: &'a RoomId,
578) -> impl Stream<Item = &UserId> + Send + 'a {
579	let prefix = (room_id, Interfix);
580	self.db
581		.roomuserid_invitecount
582		.keys_prefix(&prefix)
583		.ignore_err()
584		.map(|(_, user_id): (Ignore, &UserId)| user_id)
585}
586
587/// Streams all users currently indexed as knocking on a room.
588///
589/// Storage and key-decoding failures are skipped. Each user identifier borrows
590/// the cursor and must be consumed or owned before the stream advances.
591#[implement(Service)]
592#[tracing::instrument(skip(self), level = "debug")]
593pub fn room_members_knocked<'a>(
594	&'a self,
595	room_id: &'a RoomId,
596) -> impl Stream<Item = &UserId> + Send + 'a {
597	let prefix = (room_id, Interfix);
598	self.db
599		.roomuserid_knockedcount
600		.keys_prefix(&prefix)
601		.ignore_err()
602		.map(|(_, user_id): (Ignore, &UserId)| user_id)
603}
604
605/// Returns the stream position last recorded for a user's current invite.
606///
607/// Each invite event or forced replay rewrites it. Missing rows and malformed
608/// counts return an error; the optional event ID tail is ignored.
609#[implement(Service)]
610#[tracing::instrument(skip(self), level = "trace")]
611pub async fn get_invite_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<u64> {
612	let key = (room_id, user_id);
613	self.db
614		.roomuserid_invitecount
615		.qry(&key)
616		.await
617		.deserialized()
618		.map(|(count, _): (u64, IgnoreAll)| count)
619}
620
621/// Returns the event ID recorded for a user's current invite.
622///
623/// Legacy rows have no ID. Missing rows and malformed values return an error.
624#[implement(Service)]
625#[tracing::instrument(skip(self), level = "trace")]
626pub async fn get_invite_event(
627	&self,
628	room_id: &RoomId,
629	user_id: &UserId,
630) -> Result<Option<OwnedEventId>> {
631	let key = (room_id, user_id);
632	let value = self.db.roomuserid_invitecount.qry(&key).await?;
633	let tail = value
634		.get(size_of::<u64>()..)
635		.ok_or_else(|| err!(Database("Invalid invite count prefix")))?;
636
637	// The generic codec checks framing and full consumption only in debug.
638	if let Some((&separator, event_id)) = tail.split_first()
639		&& (separator != SEP || event_id.contains(&SEP))
640	{
641		return Err!(Database("Invalid invite event tail framing"));
642	}
643
644	value
645		.deserialized()
646		.map(|(_, event_id): (u64, Option<OwnedEventId>)| event_id)
647}
648
649/// Returns the stream position last recorded for a user's current knock.
650///
651/// Each knock event for the user rewrites it, as does a forced state replay,
652/// so it neither counts knocks nor marks the first. Missing or malformed index
653/// rows return an error.
654#[implement(Service)]
655#[tracing::instrument(skip(self), level = "trace")]
656pub async fn get_knock_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<u64> {
657	let key = (room_id, user_id);
658	self.db
659		.roomuserid_knockedcount
660		.qry(&key)
661		.await
662		.deserialized()
663}
664
665/// Returns the stream position of a retained leave or ban.
666///
667/// Forgotten rooms return a missing-row error even though their departure
668/// position survives for incremental sync. Storage and decoding failures are
669/// propagated.
670#[implement(Service)]
671#[tracing::instrument(skip(self), level = "trace")]
672pub async fn get_left_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<u64> {
673	let count = self.get_departure_count(room_id, user_id).await?;
674
675	if self.is_forgotten(user_id, room_id).await? {
676		return Err!(Request(NotFound("Room has been forgotten")));
677	}
678
679	Ok(count)
680}
681
682/// Returns the stream position of a current departure, including forgotten rooms.
683///
684/// Incremental sync uses this position to deliver pending departures.
685/// Forgotten departures retain their original position across state replay;
686/// missing or malformed count rows return an error.
687#[implement(Service)]
688#[tracing::instrument(skip(self), level = "trace")]
689pub async fn get_departure_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<u64> {
690	let key = (room_id, user_id);
691
692	self.db
693		.roomuserid_leftcount
694		.qry(&key)
695		.await
696		.deserialized()
697}
698
699/// Tests whether a user's departure carries the forgotten marker.
700///
701/// Only the complete canonical marker matches; legacy state values do not.
702/// Missing rows return false and storage failures propagate.
703#[implement(Service)]
704#[tracing::instrument(skip(self), level = "trace")]
705pub async fn is_forgotten(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
706	let key = (user_id, room_id);
707
708	self.db
709		.userroomid_leftstate
710		.qry(&key)
711		.await
712		.optional()
713		.map(|state| state.is_some_and(|state| state.as_ref().eq(FORGOTTEN_STATE)))
714}
715
716/// Returns the stream position last recorded for a user's current join.
717///
718/// Every join and every forced state replay records it, except an appended
719/// profile change over a position no later than the join it replaces, which
720/// keeps that position. Federation ingest replays each accepted member event
721/// before appending it, so a remote user's accepted profile change still moves
722/// their position. A join recorded before positions were stored holds an empty value
723/// that reads as zero, and the next join rewrites it, as it does a malformed
724/// row. Missing or malformed rows return an error.
725#[implement(Service)]
726#[tracing::instrument(skip(self), level = "trace")]
727pub async fn get_joined_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<u64> {
728	let key = (room_id, user_id);
729
730	self.db
731		.roomuserid_joinedcount
732		.qry(&key)
733		.await
734		.and_then(|value| {
735			value
736				.is_empty()
737				.map_or_else(|| value.deserialized(), || Ok(0))
738		})
739}
740
741/// Streams every cached membership category for a user.
742///
743/// Join, leave, invite, and knock indexes are combined without a global
744/// ordering guarantee. Yielded room identifiers borrow their source database
745/// cursor and are invalid after the next poll; consume or own each item before
746/// advancing. Source-stream errors are skipped.
747#[implement(Service)]
748#[inline]
749pub fn all_user_memberships<'a>(
750	&'a self,
751	user_id: &'a UserId,
752) -> impl Stream<Item = (MembershipState, &RoomId)> + Send + 'a {
753	self.user_memberships(user_id, None)
754}
755
756/// Streams selected cached membership categories for a user.
757///
758/// A missing mask selects join, leave, invite, and knock; an empty mask selects
759/// none. Category streams are interleaved without a global ordering guarantee,
760/// and their storage errors are skipped. Yielded room identifiers borrow their
761/// source database cursor and are invalid after the next poll; consume or own
762/// each item before advancing.
763#[implement(Service)]
764#[tracing::instrument(skip(self), level = "debug")]
765pub fn user_memberships<'a>(
766	&'a self,
767	user_id: &'a UserId,
768	mask: Option<&[MembershipState]>,
769) -> impl Stream<Item = (MembershipState, &RoomId)> + Send + 'a {
770	let joined = mask
771		.is_none_or(|mask| mask.contains(&MembershipState::Join))
772		.then(|| {
773			self.rooms_joined(user_id)
774				.map(|room_id| (MembershipState::Join, room_id))
775				.left_stream()
776		})
777		.unwrap_or_else(|| empty().right_stream());
778
779	let invited = mask
780		.is_none_or(|mask| mask.contains(&MembershipState::Invite))
781		.then(|| {
782			self.rooms_invited(user_id)
783				.map(|room_id| (MembershipState::Invite, room_id))
784				.left_stream()
785		})
786		.unwrap_or_else(|| empty().right_stream());
787
788	let knocked = mask
789		.is_none_or(|mask| mask.contains(&MembershipState::Knock))
790		.then(|| {
791			self.rooms_knocked(user_id)
792				.map(|room_id| (MembershipState::Knock, room_id))
793				.left_stream()
794		})
795		.unwrap_or_else(|| empty().right_stream());
796
797	let left = mask
798		.is_none_or(|mask| mask.contains(&MembershipState::Leave))
799		.then(|| {
800			self.rooms_left(user_id)
801				.map(|room_id| (MembershipState::Leave, room_id))
802				.left_stream()
803		})
804		.unwrap_or_else(|| empty().right_stream());
805
806	select(select(joined, left), select(invited, knocked))
807}
808
809/// Streams rooms in which a user is currently indexed as joined.
810///
811/// Only the user's exact encoded prefix is scanned. Storage and
812/// decoding failures are skipped, and each room identifier borrows the cursor
813/// until its next poll.
814#[implement(Service)]
815#[tracing::instrument(skip(self), level = "debug")]
816pub fn rooms_joined<'a>(
817	&'a self,
818	user_id: &'a UserId,
819) -> impl Stream<Item = &RoomId> + Send + 'a {
820	let prefix = (user_id, Interfix);
821	self.db
822		.userroomid_joinedcount
823		.keys_prefix(&prefix)
824		.ignore_err()
825		.map(|(_, room_id): (Ignore, &RoomId)| room_id)
826}
827
828/// Streams joined rooms within the user's exact encoded prefix.
829///
830/// Storage and room-key decoding failures are surfaced as error items rather
831/// than dropped. Room IDs borrow the cursor and must be consumed or owned
832/// before advancing it.
833#[implement(Service)]
834#[tracing::instrument(skip(self), level = "trace")]
835pub fn rooms_joined_checked<'a>(
836	&'a self,
837	user_id: &'a UserId,
838) -> impl Stream<Item = Result<&'a RoomId>> + Send + 'a {
839	let prefix = (user_id, Interfix);
840
841	self.db
842		.userroomid_joinedcount
843		.keys_prefix(&prefix)
844		.map_ok(|(_, room_id): (Ignore, &RoomId)| room_id)
845}
846
847/// Streams rooms in which a user is currently indexed as invited.
848///
849/// Only the user's exact encoded prefix is scanned. Storage and
850/// decoding failures are skipped, and each room identifier borrows the cursor
851/// until its next poll.
852#[implement(Service)]
853#[tracing::instrument(skip(self), level = "debug")]
854pub fn rooms_invited<'a>(
855	&'a self,
856	user_id: &'a UserId,
857) -> impl Stream<Item = &RoomId> + Send + 'a {
858	let prefix = (user_id, Interfix);
859	self.db
860		.userroomid_invitestate
861		.keys_prefix(&prefix)
862		.ignore_err()
863		.map(|(_, room_id): (Ignore, &RoomId)| room_id)
864}
865
866/// Streams rooms in which a user is currently indexed as knocking.
867///
868/// Only the user's exact encoded prefix is scanned. Storage and
869/// decoding failures are skipped, and each room identifier borrows the cursor
870/// until its next poll.
871#[implement(Service)]
872#[tracing::instrument(skip(self), level = "debug")]
873pub fn rooms_knocked<'a>(
874	&'a self,
875	user_id: &'a UserId,
876) -> impl Stream<Item = &RoomId> + Send + 'a {
877	let prefix = (user_id, Interfix);
878	self.db
879		.userroomid_knockedstate
880		.keys_prefix(&prefix)
881		.ignore_err()
882		.map(|(_, room_id): (Ignore, &RoomId)| room_id)
883}
884
885/// Streams rooms for which a user's leave state is retained.
886///
887/// Forgotten rooms are filtered by their marker value. Storage and
888/// decoding failures are skipped, and each room identifier borrows the cursor
889/// until its next poll.
890#[implement(Service)]
891#[tracing::instrument(skip(self), level = "debug")]
892pub fn rooms_left<'a>(&'a self, user_id: &'a UserId) -> impl Stream<Item = &RoomId> + Send + 'a {
893	self.retained_left_rows(user_id).map(at!(0))
894}
895
896#[implement(Service)]
897fn retained_left_rows<'a>(
898	&'a self,
899	user_id: &'a UserId,
900) -> impl Stream<Item = (&RoomId, &[u8])> + Send + 'a {
901	let prefix = (user_id, Interfix);
902
903	self.db
904		.userroomid_leftstate
905		.stream_prefix_raw(&prefix)
906		.ignore_err()
907		.ready_filter(|(_, state)| *state != FORGOTTEN_STATE)
908		.map(|(key, state)| {
909			deserialize_from_slice(key).map(|(_, room_id): (Ignore, &RoomId)| (room_id, state))
910		})
911		.ignore_err()
912}
913
914/// Streams rooms with departure evidence, including forgotten rooms.
915///
916/// Incremental sync checks each room's departure position before emitting it.
917/// Identifiers borrow the cursor until its next poll; storage and key-decoding
918/// failures are skipped.
919#[implement(Service)]
920#[tracing::instrument(skip(self), level = "debug")]
921pub fn rooms_departed<'a>(
922	&'a self,
923	user_id: &'a UserId,
924) -> impl Stream<Item = &RoomId> + Send + 'a {
925	let prefix = (user_id, Interfix);
926	self.db
927		.userroomid_leftstate
928		.keys_prefix(&prefix)
929		.ignore_err()
930		.map(|(_, room_id): (Ignore, &RoomId)| room_id)
931}
932
933/// Streams stored stripped state for a user's current invitations.
934///
935/// Each item owns its room identifier and decoded state vector. Storage,
936/// key-decoding, and state-deserialization failures are skipped.
937#[implement(Service)]
938#[tracing::instrument(skip(self), level = "debug")]
939pub fn rooms_invited_state<'a>(
940	&'a self,
941	user_id: &'a UserId,
942) -> impl Stream<Item = StrippedStateEventItem> + Send + 'a {
943	type KeyVal<'a> = (Key<'a>, Raw<Vec<AnyStrippedStateEvent>>);
944	type Key<'a> = (&'a UserId, &'a RoomId);
945
946	let prefix = (user_id, Interfix);
947	self.db
948		.userroomid_invitestate
949		.stream_prefix(&prefix)
950		.ignore_err()
951		.map(|((_, room_id), state): KeyVal<'_>| (room_id.to_owned(), state))
952		.map(|(room_id, state)| Ok((room_id, state.deserialize_as_unchecked()?)))
953		.ignore_err()
954}
955
956/// Streams stored stripped state for a user's current knocks.
957///
958/// Each item owns its room identifier and decoded state vector, read as
959/// [`Self::knock_state`] reads it. Storage, key-decoding, and
960/// state-deserialization failures are skipped.
961#[implement(Service)]
962#[tracing::instrument(skip(self), level = "trace")]
963pub fn rooms_knocked_state<'a>(
964	&'a self,
965	user_id: &'a UserId,
966) -> impl Stream<Item = StrippedStateEventItem> + Send + 'a {
967	type KeyVal<'a> = (Key<'a>, Raw<Vec<AnyStrippedStateEvent>>);
968	type Key<'a> = (&'a UserId, &'a RoomId);
969
970	let prefix = (user_id, Interfix);
971	self.db
972		.userroomid_knockedstate
973		.stream_prefix(&prefix)
974		.ignore_err()
975		.map(|((_, room_id), state): KeyVal<'_>| (room_id.to_owned(), state))
976		.map(|(room_id, state)| Ok((room_id, state.deserialize_as_unchecked()?)))
977		.ignore_err()
978		.map(move |(room_id, state)| (room_id, without_superseded_membership(state, user_id)))
979}
980
981/// Streams stored state for rooms a user has left but not forgotten.
982///
983/// Both native state arrays and compatible single-event rows are accepted.
984/// Storage and key-decoding failures are skipped, while unusable state values
985/// yield an empty event vector for their room.
986#[implement(Service)]
987#[tracing::instrument(skip(self), level = "debug")]
988pub fn rooms_left_state<'a>(
989	&'a self,
990	user_id: &'a UserId,
991) -> impl Stream<Item = SyncStateEventItem> + Send + 'a {
992	self.retained_left_rows(user_id)
993		.map(|(room_id, state)| {
994			deserialize_from_slice(state)
995				.map(|state: Raw<Vec<AnySyncStateEvent>>| (room_id.to_owned(), state))
996		})
997		.ignore_err()
998		.map(|(room_id, state)| {
999			let state = state_events(&room_id, &state);
1000
1001			(room_id, state)
1002		})
1003}
1004
1005/// Returns the stripped state stored for a user's current invitation.
1006///
1007/// The value is decoded as an array of stripped state events. Missing rows,
1008/// storage failures, and malformed state return an error.
1009#[implement(Service)]
1010#[tracing::instrument(skip(self), level = "trace")]
1011pub async fn invite_state(
1012	&self,
1013	user_id: &UserId,
1014	room_id: &RoomId,
1015) -> Result<Vec<Raw<AnyStrippedStateEvent>>> {
1016	let key = (user_id, room_id);
1017	self.db
1018		.userroomid_invitestate
1019		.qry(&key)
1020		.await
1021		.deserialized()
1022		.and_then(|val: Raw<Vec<AnyStrippedStateEvent>>| {
1023			val.deserialize_as_unchecked().map_err(Into::into)
1024		})
1025}
1026
1027/// Whether the user's stored invite carries any stripped state.
1028///
1029/// The row is probed raw rather than decoded through [`Self::invite_state`], so
1030/// no stripped state is materialized to answer it. A failed read is an error
1031/// rather than an absent row.
1032#[implement(Service)]
1033#[tracing::instrument(skip(self), level = "trace")]
1034pub async fn has_invite_state(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
1035	let key = (user_id, room_id);
1036
1037	self.db
1038		.userroomid_invitestate
1039		.qry(&key)
1040		.await
1041		.optional()
1042		.map(|state| state.is_some_and(|state| state.len() > EMPTY_INVITE_STATE.len()))
1043}
1044
1045/// Returns the stripped state stored for a user's current knock.
1046///
1047/// The value is decoded as an array of stripped state events, keeping only the
1048/// last of the user's own member events, which is the knock. Missing rows,
1049/// storage failures, and malformed state return an error.
1050#[implement(Service)]
1051#[tracing::instrument(skip(self), level = "trace")]
1052pub async fn knock_state(
1053	&self,
1054	user_id: &UserId,
1055	room_id: &RoomId,
1056) -> Result<Vec<Raw<AnyStrippedStateEvent>>> {
1057	let key = (user_id, room_id);
1058
1059	self.db
1060		.userroomid_knockedstate
1061		.qry(&key)
1062		.await
1063		.deserialized()
1064		.and_then(|val: Raw<Vec<AnyStrippedStateEvent>>| {
1065			val.deserialize_as_unchecked().map_err(Into::into)
1066		})
1067		.map(|state| without_superseded_membership(state, user_id))
1068}
1069
1070/// Drops all but the last of the user's member events from a knock summary.
1071///
1072/// A summary stored by an earlier version can carry the user's superseded
1073/// membership ahead of the knock, and a client reads the first one it finds.
1074fn without_superseded_membership(state: StrippedState, user_id: &UserId) -> StrippedState {
1075	let own_member = |event: &Raw<AnyStrippedStateEvent>| {
1076		let field = |key| event.get_field::<&str>(key).ok().flatten();
1077
1078		field("type") == Some("m.room.member") && field("state_key") == Some(user_id.as_str())
1079	};
1080
1081	let last = state.iter().rposition(own_member);
1082
1083	state
1084		.into_iter()
1085		.enumerate()
1086		.filter(|(i, event)| Some(*i) == last || !own_member(event))
1087		.map(at!(1))
1088		.collect()
1089}
1090
1091/// Returns the cached state for a room a user has left.
1092///
1093/// Native state arrays and compatible single-event rows are normalized into
1094/// one vector. Forgotten, missing or unreadable rows return an error. An
1095/// unusable stored JSON shape is logged and becomes an empty vector.
1096#[implement(Service)]
1097#[tracing::instrument(skip(self), level = "trace")]
1098pub async fn left_state(
1099	&self,
1100	user_id: &UserId,
1101	room_id: &RoomId,
1102) -> Result<Vec<Raw<AnyStrippedStateEvent>>> {
1103	let key = (user_id, room_id);
1104	self.db
1105		.userroomid_leftstate
1106		.qry(&key)
1107		.await
1108		.and_then(|state| {
1109			if state.as_ref().eq(FORGOTTEN_STATE) {
1110				return Err!(Request(NotFound("Room has been forgotten")));
1111			}
1112
1113			Ok(state)
1114		})
1115		.deserialized()
1116		.map(|state: Raw<Vec<AnyStrippedStateEvent>>| state_events(room_id, &state))
1117}
1118
1119/// Infers a user's cached membership state for one room.
1120///
1121/// Current indexes take precedence in join, leave, knock, then invite order.
1122/// When none exists, a once-joined marker is reported as `Ban`; no marker
1123/// returns `None`. Read failures from the boolean probes are treated as
1124/// absence.
1125#[implement(Service)]
1126#[tracing::instrument(skip(self), level = "trace")]
1127pub async fn user_membership(
1128	&self,
1129	user_id: &UserId,
1130	room_id: &RoomId,
1131) -> Option<MembershipState> {
1132	let states = join5(
1133		self.is_joined(user_id, room_id),
1134		self.is_left(user_id, room_id),
1135		self.is_knocked(user_id, room_id),
1136		self.is_invited(user_id, room_id),
1137		self.once_joined(user_id, room_id),
1138	)
1139	.await;
1140
1141	match states {
1142		| (true, ..) => Some(MembershipState::Join),
1143		| (_, true, ..) => Some(MembershipState::Leave),
1144		| (_, _, true, ..) => Some(MembershipState::Knock),
1145		| (_, _, _, true, ..) => Some(MembershipState::Invite),
1146		| (false, false, false, false, true) => Some(MembershipState::Ban),
1147		| _ => None,
1148	}
1149}
1150
1151/// Tests whether a user has ever been marked as joined to a room.
1152///
1153/// The durable marker survives later membership transitions and explicit
1154/// forget operations. Missing rows and storage failures both return `false`.
1155#[implement(Service)]
1156#[tracing::instrument(skip(self), level = "debug")]
1157pub async fn once_joined(&self, user_id: &UserId, room_id: &RoomId) -> bool {
1158	let key = (user_id, room_id);
1159	self.db.roomuseroncejoinedids.contains(&key).await
1160}
1161
1162/// Tests whether a user is currently joined to any of the given rooms.
1163///
1164/// The rooms are probed concurrently and the first joined room decides the
1165/// answer; an empty set of rooms answers `false`. A probe that fails counts
1166/// as not joined, as it does for [`Self::is_joined`].
1167#[implement(Service)]
1168#[tracing::instrument(skip(self, room_ids), level = "trace")]
1169pub async fn is_joined_any<'a, Rooms>(&self, user_id: &UserId, room_ids: Rooms) -> bool
1170where
1171	Rooms: IntoIterator<Item = &'a RoomId> + Send,
1172	Rooms::IntoIter: Send,
1173{
1174	room_ids
1175		.into_iter()
1176		.stream()
1177		.broad_any(|room_id| self.is_joined(user_id, room_id))
1178		.await
1179}
1180
1181/// Tests whether a user is currently indexed as joined to a room.
1182///
1183/// The user-to-room join index supplies the answer. Missing rows and storage
1184/// failures both return `false`.
1185#[implement(Service)]
1186#[tracing::instrument(skip(self), level = "trace")]
1187pub async fn is_joined<'a>(&'a self, user_id: &'a UserId, room_id: &'a RoomId) -> bool {
1188	let key = (user_id, room_id);
1189
1190	self.db
1191		.userroomid_joinedcount
1192		.contains(&key)
1193		.await
1194}
1195
1196/// Tests whether a user is indexed as joined to a room, returning a failed read
1197/// as an error.
1198///
1199/// Only a missing row returns `false`.
1200#[implement(Service)]
1201#[tracing::instrument(skip(self), level = "trace")]
1202pub async fn try_is_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
1203	let key = (user_id, room_id);
1204
1205	self.db
1206		.userroomid_joinedcount
1207		.try_contains(&key)
1208		.await
1209}
1210
1211/// Tests whether a user is currently indexed as knocking on a room.
1212///
1213/// The stored knock-state row supplies the answer. Missing rows and storage
1214/// failures both return `false`.
1215#[implement(Service)]
1216#[tracing::instrument(skip(self), level = "trace")]
1217pub async fn is_knocked<'a>(&'a self, user_id: &'a UserId, room_id: &'a RoomId) -> bool {
1218	let key = (user_id, room_id);
1219	self.db
1220		.userroomid_knockedstate
1221		.contains(&key)
1222		.await
1223}
1224
1225/// Tests whether a user is currently indexed as invited to a room.
1226///
1227/// The stored invite-state row supplies the answer. Missing rows and storage
1228/// failures both return `false`.
1229#[implement(Service)]
1230#[tracing::instrument(skip(self), level = "trace")]
1231pub async fn is_invited(&self, user_id: &UserId, room_id: &RoomId) -> bool {
1232	let key = (user_id, room_id);
1233
1234	self.db
1235		.userroomid_invitestate
1236		.contains(&key)
1237		.await
1238}
1239
1240/// Tests whether a user is indexed as invited to a room, returning a failed read
1241/// as an error.
1242///
1243/// Only a missing row returns `false`.
1244#[implement(Service)]
1245#[tracing::instrument(skip(self), level = "trace")]
1246pub async fn try_is_invited(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
1247	let key = (user_id, room_id);
1248
1249	self.db
1250		.userroomid_invitestate
1251		.try_contains(&key)
1252		.await
1253}
1254
1255/// Tests whether a user's leave state is currently retained for a room.
1256///
1257/// Explicitly forgotten rooms carry a marker and return `false`. Missing rows and
1258/// storage failures are otherwise indistinguishable.
1259#[implement(Service)]
1260#[tracing::instrument(skip(self), level = "trace")]
1261pub async fn is_left(&self, user_id: &UserId, room_id: &RoomId) -> bool {
1262	let key = (user_id, room_id);
1263
1264	self.db
1265		.userroomid_leftstate
1266		.qry(&key)
1267		.await
1268		.is_ok_and(|state| state.as_ref().ne(FORGOTTEN_STATE))
1269}
1270
1271/// Deletes a room's aggregate and paired membership indexes.
1272///
1273/// Aggregate rows and every paired index row found during enumeration are
1274/// deleted in one database transaction. Local users' leave rows survive unless
1275/// `force` is true, while remote leave rows are always removed. Once-joined
1276/// markers and appservice membership-cache entries are untouched. Storage
1277/// errors encountered during enumeration are skipped and can leave index rows
1278/// behind.
1279#[implement(Service)]
1280#[tracing::instrument(skip(self), level = "trace")]
1281pub async fn delete_room_join_counts(&self, room_id: &RoomId, force: bool) -> Result {
1282	let prefix = (room_id, Interfix);
1283	let mut txn = self.services.db.txn();
1284
1285	txn.del_raw(&self.db.roomid_knockedcount, room_id);
1286
1287	txn.del_raw(&self.db.roomid_invitedcount, room_id);
1288
1289	txn.del_raw(&self.db.roomid_inviteviaservers, room_id);
1290
1291	txn.del_raw(&self.db.roomid_joinedcount, room_id);
1292
1293	self.db
1294		.roomserverids
1295		.keys_prefix(&prefix)
1296		.ignore_err()
1297		.ready_for_each(|key: (&RoomId, &ServerName)| {
1298			trace!("Removing key: {key:?}");
1299			txn.del(&self.db.roomserverids, key);
1300
1301			let reverse_key = (key.1, key.0);
1302
1303			trace!("Removing reverse key: {reverse_key:?}");
1304			txn.del(&self.db.serverroomids, reverse_key);
1305		})
1306		.await;
1307
1308	self.db
1309		.roomuserid_invitecount
1310		.keys_prefix(&prefix)
1311		.ignore_err()
1312		.ready_for_each(|key: (&RoomId, &UserId)| {
1313			trace!("Removing key: {key:?}");
1314			txn.del(&self.db.roomuserid_invitecount, key);
1315
1316			let reverse_key = (key.1, key.0);
1317
1318			trace!("Removing reverse key: {reverse_key:?}");
1319			txn.del(&self.db.userroomid_invitestate, reverse_key);
1320		})
1321		.await;
1322
1323	self.db
1324		.roomuserid_joinedcount
1325		.keys_prefix(&prefix)
1326		.ignore_err()
1327		.ready_for_each(|key: (&RoomId, &UserId)| {
1328			trace!("Removing key: {key:?}");
1329			txn.del(&self.db.roomuserid_joinedcount, key);
1330
1331			let reverse_key = (key.1, key.0);
1332
1333			trace!("Removing reverse key: {reverse_key:?}");
1334			txn.del(&self.db.userroomid_joinedcount, reverse_key);
1335		})
1336		.await;
1337
1338	self.db
1339		.roomuserid_knockedcount
1340		.keys_prefix(&prefix)
1341		.ignore_err()
1342		.ready_for_each(|key: (&RoomId, &UserId)| {
1343			trace!("Removing key: {key:?}");
1344			txn.del(&self.db.roomuserid_knockedcount, key);
1345
1346			let reverse_key = (key.1, key.0);
1347
1348			trace!("Removing reverse key: {reverse_key:?}");
1349			txn.del(&self.db.userroomid_knockedstate, reverse_key);
1350		})
1351		.await;
1352
1353	self.db
1354		.roomuserid_leftcount
1355		.keys_prefix(&prefix)
1356		.ignore_err()
1357		.ready_filter(|(_, user_id): &(&RoomId, &UserId)| {
1358			force || !self.services.globals.user_is_local(user_id)
1359		})
1360		.ready_for_each(|key: (&RoomId, &UserId)| {
1361			trace!("Removing key: {key:?}");
1362			txn.del(&self.db.roomuserid_leftcount, key);
1363
1364			let reverse_key = (key.1, key.0);
1365
1366			trace!("Removing reverse key: {reverse_key:?}");
1367			txn.del(&self.db.userroomid_leftstate, reverse_key);
1368		})
1369		.await;
1370
1371	txn.execute();
1372
1373	Ok(())
1374}
1375
1376/// Normalizes either supported cached leave-state representation.
1377///
1378/// Imported databases can contain one leave event where this service writes an
1379/// array of state events. Both shapes are read without rewriting the row, and
1380/// malformed values are logged before producing an empty vector.
1381fn state_events<T, U>(room_id: &RoomId, state: &Raw<T>) -> Vec<U>
1382where
1383	U: DeserializeOwned + From<Owned<Pdu>>,
1384{
1385	match state.json().get().trim_start().as_bytes().first() {
1386		| Some(b'[') => state
1387			.deserialize_as_unchecked()
1388			.inspect_err(
1389				|e| debug_warn!(%room_id, error = %e, "Unusable cached membership state"),
1390			)
1391			.unwrap_or_default(),
1392
1393		// A foreign row holds the leave event alone; lift it into the array shape.
1394		| Some(b'{') => state
1395			.deserialize_as_unchecked()
1396			.map(|event: Pdu| [event.into_format()].into())
1397			.inspect_err(|e| debug_warn!(%room_id, error = %e, "Unusable cached leave event"))
1398			.unwrap_or_default(),
1399
1400		| _ => Vec::new(),
1401	}
1402}