Skip to main content

tuwunel_service/sync/
mod.rs

1mod watch;
2
3#[cfg(test)]
4mod tests;
5
6use std::{
7	collections::{BTreeMap, btree_map::Entry},
8	mem::replace,
9	sync::Arc,
10};
11
12use futures::Stream;
13use ruma::{
14	DeviceId, OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId,
15	api::client::sync::sync_events::v5::{
16		ConnId as ConnectionId, ListId, Request, request,
17		request::{AccountData, E2EE, Profiles, Receipts, ToDevice, Typing},
18	},
19	profile::ProfileFieldName,
20};
21use serde::{Deserialize, Serialize};
22use tokio::sync::Mutex as TokioMutex;
23use tuwunel_core::{
24	Result, at, debug, err, implement, is_equal_to,
25	smallvec::SmallVec,
26	utils::{OptionExt, stream::TryIgnore},
27};
28use tuwunel_database::{Cbor, Deserialized, Map, serialize_val};
29
30use crate::rooms::short::ShortStateHash;
31
32pub struct Service {
33	services: Arc<crate::services::OnceServices>,
34	connections: Connections,
35	db: Data,
36}
37
38struct Data {
39	userdeviceconnid_conn: Arc<Map>,
40	todeviceid_events: Arc<Map>,
41	userroomid_joined: Arc<Map>,
42	userroomid_invitestate: Arc<Map>,
43	userroomid_leftstate: Arc<Map>,
44	userroomid_knockedstate: Arc<Map>,
45	userroomid_notificationcount: Arc<Map>,
46	userroomid_highlightcount: Arc<Map>,
47	pduid_pdu: Arc<Map>,
48	keychangeid_userid: Arc<Map>,
49	profilechangeid_userid: Arc<Map>,
50	roomuserdataid_accountdata: Arc<Map>,
51	roomusertype_roomuserdataid: Arc<Map>,
52	readreceiptid_readreceipt: Arc<Map>,
53	userid_lastonetimekeyupdate: Arc<Map>,
54	roomuserid_lastnotificationread: Arc<Map>,
55}
56
57/// What a sliding sync connection carries from one request to the next.
58///
59/// It is stored after every response, so a client resuming from a position
60/// finds the lists, extension settings and per-room progress it left there.
61#[derive(Debug, Default, Deserialize, Serialize)]
62pub struct Connection {
63	pub globalsince: u64,
64	pub next_batch: u64,
65	pub lists: Lists,
66	pub extensions: request::Extensions,
67	pub subscriptions: Subscriptions,
68	pub rooms: Rooms,
69
70	/// Position of the response that last carried the syncing user's whole
71	/// profile in the MSC4262 profiles extension.
72	///
73	/// Zero until a response has carried it, and again whenever the extension is
74	/// switched off, so switching it back on sends the whole profile anew.
75	#[serde(default)]
76	pub own_profile_since: u64,
77
78	/// Whether the connection asked for a profile field it did not have before.
79	///
80	/// It rides the whole profile above, so the rooms replay their slice of the
81	/// change log until the client advances past the response carrying the
82	/// widened field set, and it is forgotten with everything else the extension
83	/// owes when the extension goes off.
84	#[serde(default)]
85	pub profiles_fields_widened: bool,
86}
87
88/// Delivery progress for one room on a Sliding Sync connection.
89///
90/// The cursor advances with complete ranges; configuration tracks room payloads.
91#[derive(Clone, Debug, Default, Deserialize, Serialize)]
92pub struct Room {
93	/// Position the room's content was last delivered up to.
94	pub roomsince: u64,
95
96	/// Hash of the room configuration last delivered.
97	#[serde(default)]
98	pub config_hash: u64,
99
100	/// Fingerprints of the required-state selectors last delivered for this room.
101	#[serde(default)]
102	pub required_state: RequiredState,
103
104	/// Snapshot the delivered required state was read against.
105	///
106	/// Zero when unknown, as for a room recorded by an older build or delivered
107	/// without resolving every key its required state named: its deltas compare
108	/// against the cursor and resend outliers until a delivery records one.
109	#[serde(default)]
110	pub shortstatehash: ShortStateHash,
111
112	/// Fingerprints of the requested state keys whose events the last delivery
113	/// found due but could not read.
114	///
115	/// The snapshot does not vouch for these keys, so the next delivery that
116	/// compares state sends their events whatever the snapshot holds.
117	#[serde(default, skip_serializing_if = "UnreadState::is_empty")]
118	pub unread_state: UnreadState,
119
120	/// The room's delivery progress before the last request advanced it, kept in
121	/// memory for a retry of that request's position.
122	#[serde(skip)]
123	pub checkpoint: Option<Checkpoint>,
124}
125
126/// A room's delivery progress as a request resuming from `pos` found it.
127///
128/// A retry of that position restores it, so the retry repeats the delta a lost
129/// response carried instead of resending the room's whole state. A restart
130/// forgets it, and a retry then rewinds the room to that position and forgets
131/// its delivered configuration.
132#[derive(Clone, Debug)]
133pub struct Checkpoint {
134	/// The position the request resumed from.
135	pos: u64,
136
137	/// The room's cursor before the request advanced it.
138	roomsince: u64,
139
140	/// The delivered configuration the request replaced, boxed since most hold none.
141	config: Option<Box<DeliveredConfig>>,
142}
143
144/// Fingerprints of delivered required-state selectors.
145///
146/// The inline capacity covers common room-list and open-room selections.
147pub type RequiredState = SmallVec<[u64; 18]>;
148
149/// A room configuration's hash and its required-state coverage.
150///
151/// The merged request configuration yields one per room. A delivered payload
152/// records it with the snapshot its coverage was read against.
153pub type RoomConfig = (u64, RequiredState);
154
155/// Fingerprints of requested state keys whose due events a delivery could not read.
156///
157/// Only a read fault leaves any; two fit inline at the size of an empty `Vec`.
158pub type UnreadState = SmallVec<[u64; 2]>;
159
160/// A delivered room configuration's hash, its required-state coverage, the
161/// snapshot that coverage was read against, and the keys whose events the
162/// delivery could not read.
163///
164/// All four advance together only after a room payload is assembled.
165pub type DeliveredConfig = (u64, RequiredState, ShortStateHash, UnreadState);
166
167type Connections = TokioMutex<BTreeMap<ConnectionKey, ConnectionVal>>;
168pub type ConnectionVal = Arc<TokioMutex<Connection>>;
169pub type ConnectionKey = (OwnedUserId, Option<OwnedDeviceId>, Option<ConnectionId>);
170
171pub type Subscriptions = BTreeMap<OwnedRoomId, request::ListConfig>;
172pub type Lists = BTreeMap<ListId, request::List>;
173pub type Rooms = BTreeMap<OwnedRoomId, Room>;
174
175/// A completed room range, with the configuration its payload delivered, if any.
176///
177/// Without a configuration, completing the range advances only the room's cursor.
178pub type RoomUpdate<'a> = (&'a RoomId, Option<DeliveredConfig>);
179
180impl crate::Service for Service {
181	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
182		Ok(Arc::new(Self {
183			db: Data {
184				userdeviceconnid_conn: args.db["userdeviceconnid_conn"].clone(),
185				todeviceid_events: args.db["todeviceid_events"].clone(),
186				userroomid_joined: args.db["userroomid_joined"].clone(),
187				userroomid_invitestate: args.db["userroomid_invitestate"].clone(),
188				userroomid_leftstate: args.db["userroomid_leftstate"].clone(),
189				userroomid_knockedstate: args.db["userroomid_knockedstate"].clone(),
190				userroomid_notificationcount: args.db["userroomid_notificationcount"].clone(),
191				userroomid_highlightcount: args.db["userroomid_highlightcount"].clone(),
192				pduid_pdu: args.db["pduid_pdu"].clone(),
193				keychangeid_userid: args.db["keychangeid_userid"].clone(),
194				profilechangeid_userid: args.db["profilechangeid_userid"].clone(),
195				roomuserdataid_accountdata: args.db["roomuserdataid_accountdata"].clone(),
196				roomusertype_roomuserdataid: args.db["roomusertype_roomuserdataid"].clone(),
197				readreceiptid_readreceipt: args.db["readreceiptid_readreceipt"].clone(),
198				userid_lastonetimekeyupdate: args.db["userid_lastonetimekeyupdate"].clone(),
199				roomuserid_lastnotificationread: args.db["roomuserid_lastnotificationread"]
200					.clone(),
201			},
202			services: args.services.clone(),
203			connections: Default::default(),
204		}))
205	}
206
207	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
208}
209
210/// Drops the loaded connections that match every filter given, returning how
211/// many were dropped.
212///
213/// A filter left out matches any value, so giving none drops every loaded
214/// connection. A dropped connection is deleted from the cache and from
215/// storage; one only in storage is kept.
216#[implement(Service)]
217#[tracing::instrument(level = "debug", skip(self))]
218pub async fn clear_connections(
219	&self,
220	user_id: Option<&UserId>,
221	device_id: Option<&DeviceId>,
222	conn_id: Option<&ConnectionId>,
223) -> usize {
224	self.connections
225		.lock()
226		.await
227		.extract_if(.., |key, _| connection_matches(key, user_id, device_id, conn_id))
228		.inspect(|(key, _)| self.db.userdeviceconnid_conn.del(key))
229		.count()
230}
231
232fn connection_matches(
233	(conn_user_id, conn_device_id, conn_conn_id): &ConnectionKey,
234	user_id: Option<&UserId>,
235	device_id: Option<&DeviceId>,
236	conn_id: Option<&ConnectionId>,
237) -> bool {
238	user_id.is_none_or(is_equal_to!(conn_user_id))
239		&& device_id.is_none_or(|device_id| conn_device_id.as_deref() == Some(device_id))
240		&& conn_id.is_none_or(|conn_id| conn_conn_id.as_ref() == Some(conn_id))
241}
242
243#[implement(Service)]
244#[tracing::instrument(level = "debug", skip(self))]
245pub async fn drop_connection(&self, key: &ConnectionKey) {
246	let mut cache = self.connections.lock().await;
247
248	self.db.userdeviceconnid_conn.del(key);
249	cache.remove(key);
250}
251
252/// Returns the connection for a key, from the cache or else from storage.
253///
254/// An uncached connection for a removed device is returned fresh and left
255/// uncached, and a device that cannot be read fails the load. Otherwise the
256/// stored state, or a default when none is stored, is cached.
257#[implement(Service)]
258#[tracing::instrument(level = "debug", skip(self))]
259pub async fn load_or_init_connection(&self, key: &ConnectionKey) -> Result<ConnectionVal> {
260	let mut cache = self.connections.lock().await;
261
262	if let Some(conn) = cache.get(key) {
263		return Ok(conn.clone());
264	}
265
266	// Left uncached, a removed device's connection can never be stored.
267	if self.device_removed(key).await? {
268		return Ok(ConnectionVal::default());
269	}
270
271	let conn: ConnectionVal = self
272		.db
273		.userdeviceconnid_conn
274		.qry(key)
275		.await
276		.deserialized()
277		.map(|Cbor(conn)| conn)
278		.map(TokioMutex::new)
279		.map(Arc::new)
280		.unwrap_or_default();
281
282	cache.insert(key.clone(), conn.clone());
283
284	Ok(conn)
285}
286
287#[implement(Service)]
288async fn device_removed(&self, (user_id, device_id, _): &ConnectionKey) -> Result<bool> {
289	let exists = device_id
290		.as_deref()
291		.map_async(|device_id| {
292			self.services
293				.users
294				.try_device_exists(user_id, device_id)
295		})
296		.await;
297
298	confirmed_removed(exists)
299}
300
301/// Reads a device lookup as a removal only when it found no device.
302///
303/// No device to look up removes nothing, and a failed lookup stays an error.
304fn confirmed_removed(exists: Option<Result<bool>>) -> Result<bool> {
305	exists.transpose().map(is_equal_to!(Some(false)))
306}
307
308#[implement(Service)]
309#[tracing::instrument(level = "debug", skip(self))]
310pub async fn load_connection(&self, key: &ConnectionKey) -> Result<ConnectionVal> {
311	let mut cache = self.connections.lock().await;
312
313	match cache.entry(key.clone()) {
314		| Entry::Occupied(val) => Ok(val.get().clone()),
315		| Entry::Vacant(val) => self
316			.db
317			.userdeviceconnid_conn
318			.qry(key)
319			.await
320			.deserialized::<Cbor<_>>()
321			.map(at!(0))
322			.map(TokioMutex::new)
323			.map(Arc::new)
324			.map(|conn| val.insert(conn).clone()),
325	}
326}
327
328/// Stores a connection's state while the cache still holds that connection.
329///
330/// A connection dropped, or replaced by a newer load, while a request held it
331/// is not stored again. The check and the write hold the one server-wide cache
332/// lock, so no drop falls between them and every store briefly waits on it.
333#[implement(Service)]
334#[tracing::instrument(level = "debug", skip(self, loaded, conn))]
335pub async fn store_connection(
336	&self,
337	key: &ConnectionKey,
338	loaded: &ConnectionVal,
339	conn: &Connection,
340) -> Result {
341	// Encoded before the lock, so the wait on it stays short.
342	let state = serialize_val(Cbor(conn))?;
343	let cache = self.connections.lock().await;
344	let cached = cache
345		.get(key)
346		.is_some_and(|current| Arc::ptr_eq(current, loaded));
347
348	if !cached {
349		debug!(?key, "Not persisting a dropped connection");
350		return Ok(());
351	}
352
353	self.db.userdeviceconnid_conn.put_raw(key, state);
354
355	debug!(
356		since = %conn.globalsince,
357		next_batch = %conn.next_batch,
358		"Persisted connection state"
359	);
360
361	Ok(())
362}
363
364#[implement(Service)]
365#[tracing::instrument(level = "debug", skip(self))]
366pub async fn get_loaded_connection(&self, key: &ConnectionKey) -> Result<ConnectionVal> {
367	self.connections
368		.lock()
369		.await
370		.get(key)
371		.cloned()
372		.ok_or_else(|| err!(Request(NotFound("Connection not found."))))
373}
374
375#[implement(Service)]
376#[tracing::instrument(level = "trace", skip(self))]
377pub async fn list_loaded_connections(&self) -> Vec<ConnectionKey> {
378	self.connections
379		.lock()
380		.await
381		.keys()
382		.cloned()
383		.collect()
384}
385
386#[implement(Service)]
387#[tracing::instrument(level = "trace", skip(self))]
388pub fn list_stored_connections(&self) -> impl Stream<Item = ConnectionKey> {
389	self.db.userdeviceconnid_conn.keys().ignore_err()
390}
391
392#[implement(Service)]
393#[tracing::instrument(level = "trace", skip(self))]
394pub async fn is_connection_loaded(&self, key: &ConnectionKey) -> bool {
395	self.connections.lock().await.contains_key(key)
396}
397
398#[implement(Service)]
399#[tracing::instrument(level = "trace", skip(self))]
400pub async fn is_connection_stored(&self, key: &ConnectionKey) -> bool {
401	self.db.userdeviceconnid_conn.contains(key).await
402}
403
404#[inline]
405pub fn into_connection_key<U, D, C>(
406	user_id: U,
407	device_id: Option<D>,
408	conn_id: Option<C>,
409) -> ConnectionKey
410where
411	U: Into<OwnedUserId>,
412	D: Into<OwnedDeviceId>,
413	C: Into<ConnectionId>,
414{
415	(user_id.into(), device_id.map(Into::into), conn_id.map(Into::into))
416}
417
418/// Rewind each room past a retried position to where that position left it.
419///
420/// A room checkpointed at the retried position is restored as the client last
421/// saw it. Any other room past the position rewinds to it and forgets its
422/// delivered configuration.
423#[implement(Connection)]
424#[tracing::instrument(level = "debug", skip(self))]
425pub fn update_rooms_prologue(&mut self, retry_since: Option<u64>) {
426	let Some(retry_since) = retry_since else {
427		return;
428	};
429
430	self.rooms
431		.values_mut()
432		.filter(|room| room.roomsince > retry_since)
433		.for_each(|room| room.rewind(retry_since));
434}
435
436#[implement(Room)]
437fn rewind(&mut self, since: u64) {
438	let (roomsince, config) = self.take_checkpoint(since).map_or_else(
439		|| (since, Some(DeliveredConfig::default())),
440		|Checkpoint { roomsince, config, .. }| (roomsince, config.map(|config| *config)),
441	);
442
443	self.roomsince = roomsince;
444	if let Some(config) = config {
445		self.replace_config(config);
446	}
447}
448
449#[implement(Room)]
450fn take_checkpoint(&mut self, pos: u64) -> Option<Checkpoint> {
451	self.checkpoint
452		.take()
453		.filter(|checkpoint| checkpoint.pos == pos)
454}
455
456#[implement(Room)]
457fn replace_config(
458	&mut self,
459	(config_hash, required_state, shortstatehash, unread_state): DeliveredConfig,
460) -> DeliveredConfig {
461	(
462		replace(&mut self.config_hash, config_hash),
463		replace(&mut self.required_state, required_state),
464		replace(&mut self.shortstatehash, shortstatehash),
465		replace(&mut self.unread_state, unread_state),
466	)
467}
468
469/// Advance the per-room cursor for each complete bounded room range.
470///
471/// `roomsince` is the lower bound of every content query for its room. A failed
472/// room keeps its cursor and retries the same range after a later wake. An
473/// advanced room is checkpointed at `since`, the position the request resumed from.
474#[implement(Connection)]
475#[tracing::instrument(level = "debug", skip_all)]
476pub fn update_rooms_epilogue<'a, Complete>(&mut self, since: u64, complete: Complete)
477where
478	Complete: Iterator<Item = RoomUpdate<'a>> + Send + 'a,
479{
480	let next_batch = self.next_batch;
481
482	complete.for_each(|(room_id, config)| {
483		self.rooms
484			.entry(room_id.into())
485			.or_default()
486			.advance(since, next_batch, config);
487	});
488}
489
490/// Advance the room for a request that resumed from `since`.
491///
492/// A checkpoint taken at `since` is kept; one from another position gives way to
493/// the room as this request found it. The checkpoint keeps the first configuration
494/// replaced at `since` that the delivery changed, so a retry restores what the
495/// client last saw.
496#[implement(Room)]
497fn advance(&mut self, since: u64, next_batch: u64, config: Option<DeliveredConfig>) {
498	let found = self.take_checkpoint(since).unwrap_or(Checkpoint {
499		pos: since,
500		roomsince: self.roomsince,
501		config: None,
502	});
503
504	// An unchanged configuration needs no copy; the room still holds it.
505	let replaced = config
506		.map(|config| self.replace_config(config))
507		.filter(|(config_hash, required_state, shortstatehash, unread_state)| {
508			(*config_hash, required_state, *shortstatehash, unread_state) != self.delivered()
509		});
510
511	let checkpoint = Checkpoint {
512		config: found.config.or_else(|| replaced.map(Box::new)),
513		..found
514	};
515
516	self.roomsince = next_batch;
517	self.checkpoint = Some(checkpoint);
518}
519
520#[implement(Room)]
521#[inline]
522fn delivered(&self) -> (u64, &RequiredState, ShortStateHash, &UnreadState) {
523	(self.config_hash, &self.required_state, self.shortstatehash, &self.unread_state)
524}
525
526/// Records that this pass carried the syncing user's whole profile.
527///
528/// Called once the pass has assembled its extensions, so a pass that failed
529/// leaves the profile owed to the next one.
530#[implement(Connection)]
531#[tracing::instrument(level = "debug", skip_all)]
532pub fn update_profiles_epilogue(&mut self) {
533	if self.own_profile_owed() {
534		self.own_profile_since = self.next_batch;
535	}
536}
537
538/// Whether a base is owed for a profile field the connection did not have
539/// before.
540///
541/// MSC4262 asks for the widened fields of every user in the room subset, which
542/// the room passes deliver by replaying their whole slice of the change log.
543#[implement(Connection)]
544#[inline]
545#[must_use]
546pub fn profiles_fields_owed(&self) -> bool {
547	self.profiles_fields_widened && self.own_profile_owed()
548}
549
550/// Whether the syncing user's whole profile is owed to the profiles extension.
551///
552/// It is owed while the extension is on and the client has not acknowledged a
553/// response carrying it: the connection is new, the extension was switched on
554/// after the connection began, or the client is replaying from before the
555/// response that carried it.
556#[implement(Connection)]
557#[inline]
558#[must_use]
559pub fn own_profile_owed(&self) -> bool {
560	self.extensions.profiles.enabled.unwrap_or(false)
561		&& (self.own_profile_since == 0 || self.own_profile_since > self.globalsince)
562}
563
564/// Merges the request's lists, subscriptions and extension settings into the
565/// connection.
566///
567/// Returns whether a caught-up connection needs a pass because a list or
568/// subscription changed or the request enabled the e2ee extension.
569/// MSC4543 requires the e2ee section in the response to the enabling request.
570#[implement(Connection)]
571#[tracing::instrument(level = "debug", skip_all)]
572pub fn update_cache(&mut self, request: &Request) -> bool {
573	let e2ee_enabled = self.extensions.e2ee.enabled == Some(true);
574	let lists_changed = Self::update_cache_lists(request, self);
575	let subscriptions_changed = Self::update_cache_subscriptions(request, self);
576
577	let fields_widened = Self::update_cache_extensions(request, self);
578
579	self.update_cache_profiles_owed(fields_widened);
580
581	lists_changed
582		|| subscriptions_changed
583		|| (!e2ee_enabled && self.extensions.e2ee.enabled == Some(true))
584}
585
586#[implement(Connection)]
587fn update_cache_lists(request: &Request, cached: &mut Self) -> bool {
588	request
589		.lists
590		.iter()
591		.fold(false, |changed, (list_id, request_list)| {
592			let list_changed = match cached.lists.get_mut(list_id) {
593				| Some(cached_list) => Self::update_cache_list(request_list, cached_list),
594				| None => {
595					cached
596						.lists
597						.insert(list_id.clone(), request_list.clone());
598
599					true
600				},
601			};
602
603			changed | list_changed
604		})
605}
606
607#[implement(Connection)]
608fn update_cache_list(request: &request::List, cached: &mut request::List) -> bool {
609	let ranges_changed = request.ranges != cached.ranges;
610	let timeline_limit_changed =
611		request.room_details.timeline_limit != cached.room_details.timeline_limit;
612
613	let required_state_changed = !request.room_details.required_state.is_empty()
614		&& request.room_details.required_state != cached.room_details.required_state;
615
616	let filters_changed = request.filters.as_ref().is_some_and(|request| {
617		cached
618			.filters
619			.as_ref()
620			.is_none_or(|cached| !list_filters_are_equal(request, cached))
621	});
622
623	let changed =
624		ranges_changed || timeline_limit_changed || required_state_changed || filters_changed;
625
626	if ranges_changed {
627		cached.ranges.clone_from(&request.ranges);
628	}
629
630	cached.room_details.timeline_limit = request.room_details.timeline_limit;
631
632	if required_state_changed {
633		cached
634			.room_details
635			.required_state
636			.clone_from(&request.room_details.required_state);
637	}
638
639	if filters_changed {
640		cached.filters.clone_from(&request.filters);
641	}
642
643	changed
644}
645
646#[implement(Connection)]
647fn update_cache_subscriptions(request: &Request, cached: &mut Self) -> bool {
648	let changed = !subscriptions_are_equal(&request.room_subscriptions, &cached.subscriptions);
649
650	if changed {
651		cached
652			.subscriptions
653			.clone_from(&request.room_subscriptions);
654	}
655
656	changed
657}
658
659fn subscriptions_are_equal(request: &Subscriptions, cached: &Subscriptions) -> bool {
660	request.len() == cached.len()
661		&& request
662			.iter()
663			.zip(cached)
664			.all(|(request, cached)| {
665				request.0 == cached.0 && list_config_is_equal(request.1, cached.1)
666			})
667}
668
669fn list_config_is_equal(request: &request::ListConfig, cached: &request::ListConfig) -> bool {
670	request.timeline_limit == cached.timeline_limit
671		&& request.required_state == cached.required_state
672}
673
674fn list_filters_are_equal(request: &request::ListFilters, cached: &request::ListFilters) -> bool {
675	request.is_dm == cached.is_dm
676		&& request.is_encrypted == cached.is_encrypted
677		&& request.is_invite == cached.is_invite
678		&& request.room_types == cached.room_types
679		&& request.not_room_types == cached.not_room_types
680		&& request.tags == cached.tags
681		&& request.not_tags == cached.not_tags
682		&& request.spaces == cached.spaces
683}
684
685/// Merges the request's extension settings into the connection.
686///
687/// Returns whether the MSC4262 field filter named a field the connection did
688/// not have, which the profiles extension owes a base for.
689#[implement(Connection)]
690fn update_cache_extensions(request: &Request, cached: &mut Self) -> bool {
691	let request = &request.extensions;
692	let cached = &mut cached.extensions;
693
694	Self::update_cache_account_data(&request.account_data, &mut cached.account_data);
695	Self::update_cache_receipts(&request.receipts, &mut cached.receipts);
696	Self::update_cache_typing(&request.typing, &mut cached.typing);
697	Self::update_cache_to_device(&request.to_device, &mut cached.to_device);
698	Self::update_cache_e2ee(&request.e2ee, &mut cached.e2ee);
699
700	Self::update_cache_profiles(&request.profiles, &mut cached.profiles)
701}
702
703#[implement(Connection)]
704fn update_cache_account_data(request: &AccountData, cached: &mut AccountData) {
705	some_or_sticky(request.enabled.as_ref(), &mut cached.enabled);
706	some_or_sticky(request.lists.as_ref(), &mut cached.lists);
707	some_or_sticky(request.rooms.as_ref(), &mut cached.rooms);
708}
709
710#[implement(Connection)]
711fn update_cache_receipts(request: &Receipts, cached: &mut Receipts) {
712	some_or_sticky(request.enabled.as_ref(), &mut cached.enabled);
713	some_or_sticky(request.rooms.as_ref(), &mut cached.rooms);
714	some_or_sticky(request.lists.as_ref(), &mut cached.lists);
715}
716
717#[implement(Connection)]
718fn update_cache_typing(request: &Typing, cached: &mut Typing) {
719	some_or_sticky(request.enabled.as_ref(), &mut cached.enabled);
720	some_or_sticky(request.rooms.as_ref(), &mut cached.rooms);
721	some_or_sticky(request.lists.as_ref(), &mut cached.lists);
722}
723
724#[implement(Connection)]
725fn update_cache_to_device(request: &ToDevice, cached: &mut ToDevice) {
726	some_or_sticky(request.enabled.as_ref(), &mut cached.enabled);
727	cached.since.clone_from(&request.since);
728	cached.limit = request.limit;
729}
730
731/// Merges the profiles extension settings into the connection.
732///
733/// Returns whether the request widened the field filter, which is read before
734/// the merge overwrites the filter it compares against.
735#[implement(Connection)]
736fn update_cache_profiles(request: &Profiles, cached: &mut Profiles) -> bool {
737	some_or_sticky(request.enabled.as_ref(), &mut cached.enabled);
738	some_or_sticky(request.rooms.as_ref(), &mut cached.rooms);
739	some_or_sticky(request.lists.as_ref(), &mut cached.lists);
740
741	let Some(fields) = request.fields.as_ref() else {
742		return false;
743	};
744
745	if let Some(cached) = cached.fields.as_mut() {
746		normalize_profile_fields(cached);
747	}
748
749	let widened = fields_widened(Some(fields), cached.fields.as_deref());
750
751	retain_profile_fields(&mut cached.fields, fields);
752
753	widened
754}
755
756fn retain_profile_fields(
757	cached: &mut Option<Vec<ProfileFieldName>>,
758	fields: &[ProfileFieldName],
759) {
760	let retained = cached.get_or_insert_default();
761
762	fields.clone_into(retained);
763	normalize_profile_fields(retained);
764}
765
766fn normalize_profile_fields(fields: &mut Vec<ProfileFieldName>) {
767	fields.sort_unstable();
768	fields.dedup();
769}
770
771/// Whether the request names a profile field the connection did not ask for.
772///
773/// An absent cached filter already covers every field, and an absent request
774/// keeps the cached one, so neither widens anything.
775fn fields_widened(
776	request: Option<&[ProfileFieldName]>,
777	cached: Option<&[ProfileFieldName]>,
778) -> bool {
779	request
780		.zip(cached)
781		.is_some_and(|(request, cached)| {
782			request
783				.iter()
784				.any(|name| cached.binary_search(name).is_err())
785		})
786}
787
788#[implement(Connection)]
789fn update_cache_e2ee(request: &E2EE, cached: &mut E2EE) {
790	some_or_sticky(request.enabled.as_ref(), &mut cached.enabled);
791}
792
793#[implement(Connection)]
794fn update_cache_profiles_owed(&mut self, fields_widened: bool) {
795	if fields_widened || !self.extensions.profiles.enabled.unwrap_or(false) {
796		self.own_profile_since = 0;
797	}
798
799	self.profiles_fields_widened =
800		fields_widened || (self.profiles_fields_widened && self.own_profile_owed());
801}
802
803fn some_or_sticky<T: Clone>(target: Option<&T>, cached: &mut Option<T>) {
804	if let Some(target) = target {
805		cached.replace(target.clone());
806	}
807}