Skip to main content

matrix_sdk_base/store/
traits.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16    borrow::Borrow,
17    collections::{BTreeMap, BTreeSet, HashMap},
18    fmt,
19    ops::Deref,
20    sync::Arc,
21};
22
23use as_variant::as_variant;
24use async_trait::async_trait;
25use growable_bloom_filter::GrowableBloom;
26use matrix_sdk_common::{AsyncTraitDeps, ttl::TtlValue};
27use ruma::{
28    EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedMxcUri, OwnedRoomId,
29    OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UserId,
30    api::{
31        MatrixVersion, SupportedVersions,
32        client::{
33            discovery::{
34                discover_homeserver::{self, HomeserverInfo, IdentityServerInfo, TileServerInfo},
35                get_capabilities::v3::Capabilities,
36            },
37            retention::{
38                RoomIdOrAllRooms,
39                get_retention_configuration::msc1763::{
40                    Response as RetentionConfigurationApiResponse, RetentionLimits,
41                },
42            },
43            rtc::RtcTransport,
44        },
45    },
46    events::{
47        AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, EmptyStateKey, GlobalAccountDataEvent,
48        GlobalAccountDataEventContent, GlobalAccountDataEventType, RedactContent,
49        RedactedStateEventContent, RoomAccountDataEvent, RoomAccountDataEventContent,
50        RoomAccountDataEventType, StateEventType, StaticEventContent, StaticStateEventContent,
51        presence::PresenceEvent,
52        receipt::{Receipt, ReceiptThread, ReceiptType},
53        room::retention::RoomRetentionEventContent,
54    },
55    profile::UserProfile,
56    serde::Raw,
57};
58use serde::{Deserialize, Serialize};
59use thiserror::Error;
60use tokio::sync::{Mutex, MutexGuard};
61
62use super::{
63    ChildTransactionId, DependentQueuedRequest, DependentQueuedRequestKind, QueueWedgeError,
64    QueuedRequest, QueuedRequestKind, RoomLoadSettings, StateChanges, StoreError,
65    send_queue::SentRequestKey,
66};
67use crate::{
68    MinimalRoomMemberEvent, RoomInfo, RoomMemberships,
69    deserialized_responses::{
70        DisplayName, RawAnySyncOrStrippedState, RawMemberEvent, RawSyncOrStrippedState,
71    },
72    store::StoredThreadSubscription,
73};
74
75/// An abstract state store trait that can be used to implement different stores
76/// for the SDK.
77#[cfg_attr(target_family = "wasm", async_trait(?Send))]
78#[cfg_attr(not(target_family = "wasm"), async_trait)]
79pub trait StateStore: AsyncTraitDeps {
80    /// The error type used by this state store.
81    type Error: fmt::Debug + Into<StoreError> + From<serde_json::Error>;
82
83    /// Get key-value data from the store.
84    ///
85    /// # Arguments
86    ///
87    /// * `key` - The key to fetch data for.
88    async fn get_kv_data(
89        &self,
90        key: StateStoreDataKey<'_>,
91    ) -> Result<Option<StateStoreDataValue>, Self::Error>;
92
93    /// Put key-value data into the store.
94    ///
95    /// # Arguments
96    ///
97    /// * `key` - The key to identify the data in the store.
98    ///
99    /// * `value` - The data to insert.
100    ///
101    /// Panics if the key and value variants do not match.
102    async fn set_kv_data(
103        &self,
104        key: StateStoreDataKey<'_>,
105        value: StateStoreDataValue,
106    ) -> Result<(), Self::Error>;
107
108    /// Remove key-value data from the store.
109    ///
110    /// # Arguments
111    ///
112    /// * `key` - The key to remove the data for.
113    async fn remove_kv_data(&self, key: StateStoreDataKey<'_>) -> Result<(), Self::Error>;
114
115    /// Save the set of state changes in the store.
116    async fn save_changes(&self, changes: &StateChanges) -> Result<(), Self::Error>;
117
118    /// Get the stored presence event for the given user.
119    ///
120    /// # Arguments
121    ///
122    /// - `user_id` - The id of the user for which we wish to fetch the presence
123    /// event for.
124    async fn get_presence_event(
125        &self,
126        user_id: &UserId,
127    ) -> Result<Option<Raw<PresenceEvent>>, Self::Error>;
128
129    /// Get the stored presence events for the given users.
130    ///
131    /// # Arguments
132    ///
133    /// * `user_ids` - The IDs of the users to fetch the presence events for.
134    async fn get_presence_events(
135        &self,
136        user_ids: &[OwnedUserId],
137    ) -> Result<Vec<Raw<PresenceEvent>>, Self::Error>;
138
139    /// Get a state event out of the state store.
140    ///
141    /// # Arguments
142    ///
143    /// * `room_id` - The id of the room the state event was received for.
144    ///
145    /// * `event_type` - The event type of the state event.
146    async fn get_state_event(
147        &self,
148        room_id: &RoomId,
149        event_type: StateEventType,
150        state_key: &str,
151    ) -> Result<Option<RawAnySyncOrStrippedState>, Self::Error>;
152
153    /// Get a list of state events for a given room and `StateEventType`.
154    ///
155    /// # Arguments
156    ///
157    /// * `room_id` - The id of the room to find events for.
158    ///
159    /// * `event_type` - The event type.
160    async fn get_state_events(
161        &self,
162        room_id: &RoomId,
163        event_type: StateEventType,
164    ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error>;
165
166    /// Get a list of state events for a given room, `StateEventType`, and the
167    /// given state keys.
168    ///
169    /// # Arguments
170    ///
171    /// - `room_id` - The id of the room to find events for.
172    /// - `event_type` - The event type.
173    /// - `state_keys` - The list of state keys to find.
174    async fn get_state_events_for_keys(
175        &self,
176        room_id: &RoomId,
177        event_type: StateEventType,
178        state_keys: &[&str],
179    ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error>;
180
181    /// Get the current profile for the given user in the given room.
182    ///
183    /// # Arguments
184    ///
185    /// * `room_id` - The room id the profile is used in.
186    ///
187    /// * `user_id` - The id of the user the profile belongs to.
188    async fn get_profile(
189        &self,
190        room_id: &RoomId,
191        user_id: &UserId,
192    ) -> Result<Option<MinimalRoomMemberEvent>, Self::Error>;
193
194    /// Get the current profiles for the given users in the given room.
195    ///
196    /// # Arguments
197    ///
198    /// * `room_id` - The ID of the room the profiles are used in.
199    ///
200    /// * `user_ids` - The IDs of the users the profiles belong to.
201    async fn get_profiles<'a>(
202        &self,
203        room_id: &RoomId,
204        user_ids: &'a [OwnedUserId],
205    ) -> Result<BTreeMap<&'a UserId, MinimalRoomMemberEvent>, Self::Error>;
206
207    /// Get the user ids of members for a given room with the given memberships,
208    /// for stripped and regular rooms alike.
209    async fn get_user_ids(
210        &self,
211        room_id: &RoomId,
212        memberships: RoomMemberships,
213    ) -> Result<Vec<OwnedUserId>, Self::Error>;
214
215    /// Get a set of pure `RoomInfo`s the store knows about.
216    async fn get_room_infos(
217        &self,
218        room_load_settings: &RoomLoadSettings,
219    ) -> Result<Vec<RoomInfo>, Self::Error>;
220
221    /// Get all the users that use the given display name in the given room.
222    ///
223    /// # Arguments
224    ///
225    /// - `room_id` - The id of the room for which the display name users should
226    /// be fetched for.
227    /// - `display_name` - The display name that the users use.
228    async fn get_users_with_display_name(
229        &self,
230        room_id: &RoomId,
231        display_name: &DisplayName,
232    ) -> Result<BTreeSet<OwnedUserId>, Self::Error>;
233
234    /// Get all the users that use the given display names in the given room.
235    ///
236    /// # Arguments
237    ///
238    /// * `room_id` - The ID of the room to fetch the display names for.
239    ///
240    /// * `display_names` - The display names that the users use.
241    async fn get_users_with_display_names<'a>(
242        &self,
243        room_id: &RoomId,
244        display_names: &'a [DisplayName],
245    ) -> Result<HashMap<&'a DisplayName, BTreeSet<OwnedUserId>>, Self::Error>;
246
247    /// Get an event out of the account data store.
248    ///
249    /// # Arguments
250    ///
251    /// * `event_type` - The event type of the account data event.
252    async fn get_account_data_event(
253        &self,
254        event_type: GlobalAccountDataEventType,
255    ) -> Result<Option<Raw<AnyGlobalAccountDataEvent>>, Self::Error>;
256
257    /// Get an event out of the room account data store.
258    ///
259    /// # Arguments
260    ///
261    /// - `room_id` - The id of the room for which the room account data event
262    ///   should
263    /// be fetched.
264    /// - `event_type` - The event type of the room account data event.
265    async fn get_room_account_data_event(
266        &self,
267        room_id: &RoomId,
268        event_type: RoomAccountDataEventType,
269    ) -> Result<Option<Raw<AnyRoomAccountDataEvent>>, Self::Error>;
270
271    /// Get a user's read receipt for a given room and receipt type and thread.
272    ///
273    /// # Arguments
274    ///
275    /// - `room_id` - The id of the room for which the receipt should be
276    ///   fetched.
277    ///
278    /// - `receipt_type` - The type of the receipt.
279    /// - `receipt_thread` - The thread a receipt applies to.
280    /// - `user_id` - The id of the user for whom the receipt should be fetched.
281    async fn get_user_room_receipt_event(
282        &self,
283        room_id: &RoomId,
284        receipt_type: ReceiptType,
285        receipt_thread: &ReceiptThread,
286        user_id: &UserId,
287    ) -> Result<Option<(OwnedEventId, Receipt)>, Self::Error>;
288
289    /// Get an event's read receipts for a given room, receipt type, and thread.
290    ///
291    /// # Arguments
292    ///
293    /// - `room_id` - The id of the room for which the receipts should be
294    ///   fetched.
295    ///
296    /// - `receipt_type` - The type of the receipts.
297    /// - `receipt_thread` - The thread a receipt applies to.
298    /// - `event_id` - The id of the event for which the receipts should be
299    ///   fetched.
300    async fn get_event_room_receipt_events(
301        &self,
302        room_id: &RoomId,
303        receipt_type: ReceiptType,
304        receipt_thread: &ReceiptThread,
305        event_id: &EventId,
306    ) -> Result<Vec<(OwnedUserId, Receipt)>, Self::Error>;
307
308    /// Get arbitrary data from the custom store
309    ///
310    /// # Arguments
311    ///
312    /// * `key` - The key to fetch data for
313    async fn get_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error>;
314
315    /// Put arbitrary data into the custom store, return the data previously
316    /// stored
317    ///
318    /// # Arguments
319    ///
320    /// - `key` - The key to insert data into
321    /// - `value` - The value to insert
322    async fn set_custom_value(
323        &self,
324        key: &[u8],
325        value: Vec<u8>,
326    ) -> Result<Option<Vec<u8>>, Self::Error>;
327
328    /// Put arbitrary data into the custom store, do not attempt to read any
329    /// previous data
330    ///
331    /// Optimization option for set_custom_values for stores that would perform
332    /// better withouts the extra read and the caller not needing that data
333    /// returned. Otherwise this just wraps around `set_custom_data` and
334    /// discards the result.
335    ///
336    /// # Arguments
337    ///
338    /// - `key` - The key to insert data into
339    /// - `value` - The value to insert
340    async fn set_custom_value_no_read(
341        &self,
342        key: &[u8],
343        value: Vec<u8>,
344    ) -> Result<(), Self::Error> {
345        self.set_custom_value(key, value).await.map(|_| ())
346    }
347
348    /// Remove arbitrary data from the custom store and return it if existed
349    ///
350    /// # Arguments
351    ///
352    /// * `key` - The key to remove data from
353    async fn remove_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error>;
354
355    /// Remove a room and all elements associated from the state store.
356    ///
357    /// # Arguments
358    ///
359    /// * `room_id` - The `RoomId` of the room to delete.
360    async fn remove_room(&self, room_id: &RoomId) -> Result<(), Self::Error>;
361
362    /// Save a request to be sent by a send queue later (e.g. sending an event).
363    ///
364    /// # Arguments
365    ///
366    /// - `room_id` - The `RoomId` of the send queue's room.
367    /// - `transaction_id` - The unique key identifying the event to be sent
368    ///   (and its transaction). Note: this is expected to be randomly generated
369    ///   and thus unique.
370    /// - `content` - Serializable event content to be sent.
371    async fn save_send_queue_request(
372        &self,
373        room_id: &RoomId,
374        transaction_id: OwnedTransactionId,
375        created_at: MilliSecondsSinceUnixEpoch,
376        request: QueuedRequestKind,
377        priority: usize,
378    ) -> Result<(), Self::Error>;
379
380    /// Updates a send queue request with the given content, and resets its
381    /// error status.
382    ///
383    /// # Arguments
384    ///
385    /// - `room_id` - The `RoomId` of the send queue's room.
386    /// - `transaction_id` - The unique key identifying the request to be sent
387    ///   (and its transaction).
388    /// - `content` - Serializable event content to replace the original one.
389    ///
390    /// Returns true if a request has been updated, or false otherwise.
391    async fn update_send_queue_request(
392        &self,
393        room_id: &RoomId,
394        transaction_id: &TransactionId,
395        content: QueuedRequestKind,
396    ) -> Result<bool, Self::Error>;
397
398    /// Remove a request previously inserted with
399    /// [`Self::save_send_queue_request`] from the database, based on its
400    /// transaction id.
401    ///
402    /// Returns true if something has been removed, or false otherwise.
403    async fn remove_send_queue_request(
404        &self,
405        room_id: &RoomId,
406        transaction_id: &TransactionId,
407    ) -> Result<bool, Self::Error>;
408
409    /// Loads all the send queue requests for the given room.
410    ///
411    /// The resulting vector of queued requests should be ordered from higher
412    /// priority to lower priority, and respect the insertion order when
413    /// priorities are equal.
414    async fn load_send_queue_requests(
415        &self,
416        room_id: &RoomId,
417    ) -> Result<Vec<QueuedRequest>, Self::Error>;
418
419    /// Updates the send queue error status (wedge) for a given send queue
420    /// request.
421    async fn update_send_queue_request_status(
422        &self,
423        room_id: &RoomId,
424        transaction_id: &TransactionId,
425        error: Option<QueueWedgeError>,
426    ) -> Result<(), Self::Error>;
427
428    /// Loads all the rooms which have any pending requests in their send queue.
429    async fn load_rooms_with_unsent_requests(&self) -> Result<Vec<OwnedRoomId>, Self::Error>;
430
431    /// Add a new entry to the list of dependent send queue requests for a
432    /// parent request.
433    async fn save_dependent_queued_request(
434        &self,
435        room_id: &RoomId,
436        parent_txn_id: &TransactionId,
437        own_txn_id: ChildTransactionId,
438        created_at: MilliSecondsSinceUnixEpoch,
439        content: DependentQueuedRequestKind,
440    ) -> Result<(), Self::Error>;
441
442    /// Mark a set of dependent send queue requests as ready, using a key
443    /// identifying the homeserver's response.
444    ///
445    /// ⚠ Beware! There's no verification applied that the parent key type is
446    /// compatible with the dependent event type. The invalid state may be
447    /// lazily filtered out in `load_dependent_queued_requests`.
448    ///
449    /// Returns the number of updated requests.
450    async fn mark_dependent_queued_requests_as_ready(
451        &self,
452        room_id: &RoomId,
453        parent_txn_id: &TransactionId,
454        sent_parent_key: SentRequestKey,
455    ) -> Result<usize, Self::Error>;
456
457    /// Update a dependent send queue request with the new content.
458    ///
459    /// Returns true if the request was found and could be updated.
460    async fn update_dependent_queued_request(
461        &self,
462        room_id: &RoomId,
463        own_transaction_id: &ChildTransactionId,
464        new_content: DependentQueuedRequestKind,
465    ) -> Result<bool, Self::Error>;
466
467    /// Remove a specific dependent send queue request by id.
468    ///
469    /// Returns true if the dependent send queue request has been indeed
470    /// removed.
471    async fn remove_dependent_queued_request(
472        &self,
473        room: &RoomId,
474        own_txn_id: &ChildTransactionId,
475    ) -> Result<bool, Self::Error>;
476
477    /// List all the dependent send queue requests.
478    ///
479    /// This returns absolutely all the dependent send queue requests, whether
480    /// they have a parent event id or not. As a contract for implementors, they
481    /// must be returned in insertion order.
482    async fn load_dependent_queued_requests(
483        &self,
484        room: &RoomId,
485    ) -> Result<Vec<DependentQueuedRequest>, Self::Error>;
486
487    /// Inserts or updates multiple thread subscriptions.
488    ///
489    /// If the new thread subscription hasn't set a bumpstamp, and there was a
490    /// previous subscription in the database with a bumpstamp, the existing
491    /// bumpstamp is kept.
492    ///
493    /// If the new thread subscription has a bumpstamp that's lower than or
494    /// equal to a previous one, the existing subscription is kept, i.e. this
495    /// method must have no effect.
496    async fn upsert_thread_subscriptions(
497        &self,
498        updates: Vec<(&RoomId, &EventId, StoredThreadSubscription)>,
499    ) -> Result<(), Self::Error>;
500
501    /// Remove a previous thread subscription for a given room and thread.
502    ///
503    /// Note: removing an unknown thread subscription is a no-op.
504    async fn remove_thread_subscription(
505        &self,
506        room: &RoomId,
507        thread_id: &EventId,
508    ) -> Result<(), Self::Error>;
509
510    /// Loads the current thread subscription for a given room and thread.
511    ///
512    /// Returns `None` if there was no entry for the given room/thread pair.
513    async fn load_thread_subscription(
514        &self,
515        room: &RoomId,
516        thread_id: &EventId,
517    ) -> Result<Option<StoredThreadSubscription>, Self::Error>;
518
519    /// Get a user's global profile from the store.
520    ///
521    /// Global profiles are persisted as part of [`StateStore::save_changes`],
522    /// from the [`StateChanges::global_profiles`] field, following the MSC4262
523    /// update pattern: fields with an explicit `null` value are removed, while
524    /// fields not present are left unchanged.
525    ///
526    /// Returns `None` if there was no stored global profile for the given user.
527    async fn get_global_profile(
528        &self,
529        user_id: &UserId,
530    ) -> Result<Option<UserProfile>, Self::Error>;
531
532    /// Get the global profiles for the given users from the store.
533    ///
534    /// See [`StateStore::get_global_profile`] for more details. Users without a
535    /// stored global profile are absent from the returned map.
536    async fn get_global_profiles<'a>(
537        &self,
538        user_ids: &'a [OwnedUserId],
539    ) -> Result<BTreeMap<&'a UserId, UserProfile>, Self::Error>;
540
541    /// Get which of the given users' global profiles can be fetched directly,
542    /// rather than waiting for them to come via /sync.
543    ///
544    /// These are the users without a stored global profile, and whose profile
545    /// isn't marked as unavailable, see
546    /// [`StateChanges::unavailable_global_profiles`].
547    async fn get_missing_global_profiles<'a>(
548        &self,
549        user_ids: &'a [OwnedUserId],
550    ) -> Result<Vec<&'a UserId>, Self::Error>;
551
552    /// Close the store, releasing all held resources (database connections,
553    /// file descriptors, file locks).
554    ///
555    /// In-flight operations complete before this method returns. After it
556    /// returns, operations will fail until [`Self::reopen()`] is called.
557    async fn close(&self) -> Result<(), Self::Error>;
558
559    /// Reopen the store after a [`Self::close()`], re-acquiring database
560    /// connections.
561    async fn reopen(&self) -> Result<(), Self::Error>;
562
563    /// Perform database optimizations if any are available, i.e. vacuuming in
564    /// SQLite.
565    ///
566    /// /// **Warning:** this was added to check if SQLite fragmentation was the
567    /// source of performance issues, **DO NOT use in production**.
568    #[doc(hidden)]
569    async fn optimize(&self) -> Result<(), Self::Error>;
570
571    /// Returns the size of the store in bytes, if known.
572    async fn get_size(&self) -> Result<Option<usize>, Self::Error>;
573}
574
575#[cfg_attr(target_family = "wasm", async_trait(?Send))]
576#[cfg_attr(not(target_family = "wasm"), async_trait)]
577impl<T: StateStore> StateStore for &T {
578    type Error = T::Error;
579
580    async fn get_kv_data(
581        &self,
582        key: StateStoreDataKey<'_>,
583    ) -> Result<Option<StateStoreDataValue>, Self::Error> {
584        (*self).get_kv_data(key).await
585    }
586
587    async fn set_kv_data(
588        &self,
589        key: StateStoreDataKey<'_>,
590        value: StateStoreDataValue,
591    ) -> Result<(), Self::Error> {
592        (*self).set_kv_data(key, value).await
593    }
594
595    async fn remove_kv_data(&self, key: StateStoreDataKey<'_>) -> Result<(), Self::Error> {
596        (*self).remove_kv_data(key).await
597    }
598
599    async fn save_changes(&self, changes: &StateChanges) -> Result<(), Self::Error> {
600        (*self).save_changes(changes).await
601    }
602
603    async fn get_presence_event(
604        &self,
605        user_id: &UserId,
606    ) -> Result<Option<Raw<PresenceEvent>>, Self::Error> {
607        (*self).get_presence_event(user_id).await
608    }
609
610    async fn get_presence_events(
611        &self,
612        user_ids: &[OwnedUserId],
613    ) -> Result<Vec<Raw<PresenceEvent>>, Self::Error> {
614        (*self).get_presence_events(user_ids).await
615    }
616
617    async fn get_state_event(
618        &self,
619        room_id: &RoomId,
620        event_type: StateEventType,
621        state_key: &str,
622    ) -> Result<Option<RawAnySyncOrStrippedState>, Self::Error> {
623        (*self).get_state_event(room_id, event_type, state_key).await
624    }
625
626    async fn get_state_events(
627        &self,
628        room_id: &RoomId,
629        event_type: StateEventType,
630    ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error> {
631        (*self).get_state_events(room_id, event_type).await
632    }
633
634    async fn get_state_events_for_keys(
635        &self,
636        room_id: &RoomId,
637        event_type: StateEventType,
638        state_keys: &[&str],
639    ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error> {
640        (*self).get_state_events_for_keys(room_id, event_type, state_keys).await
641    }
642
643    async fn get_profile(
644        &self,
645        room_id: &RoomId,
646        user_id: &UserId,
647    ) -> Result<Option<MinimalRoomMemberEvent>, Self::Error> {
648        (*self).get_profile(room_id, user_id).await
649    }
650
651    async fn get_profiles<'a>(
652        &self,
653        room_id: &RoomId,
654        user_ids: &'a [OwnedUserId],
655    ) -> Result<BTreeMap<&'a UserId, MinimalRoomMemberEvent>, Self::Error> {
656        (*self).get_profiles(room_id, user_ids).await
657    }
658
659    async fn get_user_ids(
660        &self,
661        room_id: &RoomId,
662        memberships: RoomMemberships,
663    ) -> Result<Vec<OwnedUserId>, Self::Error> {
664        (*self).get_user_ids(room_id, memberships).await
665    }
666
667    async fn get_room_infos(
668        &self,
669        room_load_settings: &RoomLoadSettings,
670    ) -> Result<Vec<RoomInfo>, Self::Error> {
671        (*self).get_room_infos(room_load_settings).await
672    }
673
674    async fn get_users_with_display_name(
675        &self,
676        room_id: &RoomId,
677        display_name: &DisplayName,
678    ) -> Result<BTreeSet<OwnedUserId>, Self::Error> {
679        (*self).get_users_with_display_name(room_id, display_name).await
680    }
681
682    async fn get_users_with_display_names<'a>(
683        &self,
684        room_id: &RoomId,
685        display_names: &'a [DisplayName],
686    ) -> Result<HashMap<&'a DisplayName, BTreeSet<OwnedUserId>>, Self::Error> {
687        (*self).get_users_with_display_names(room_id, display_names).await
688    }
689
690    async fn get_account_data_event(
691        &self,
692        event_type: GlobalAccountDataEventType,
693    ) -> Result<Option<Raw<AnyGlobalAccountDataEvent>>, Self::Error> {
694        (*self).get_account_data_event(event_type).await
695    }
696
697    async fn get_room_account_data_event(
698        &self,
699        room_id: &RoomId,
700        event_type: RoomAccountDataEventType,
701    ) -> Result<Option<Raw<AnyRoomAccountDataEvent>>, Self::Error> {
702        (*self).get_room_account_data_event(room_id, event_type).await
703    }
704
705    async fn get_user_room_receipt_event(
706        &self,
707        room_id: &RoomId,
708        receipt_type: ReceiptType,
709        receipt_thread: &ReceiptThread,
710        user_id: &UserId,
711    ) -> Result<Option<(OwnedEventId, Receipt)>, Self::Error> {
712        (*self).get_user_room_receipt_event(room_id, receipt_type, receipt_thread, user_id).await
713    }
714
715    async fn get_event_room_receipt_events(
716        &self,
717        room_id: &RoomId,
718        receipt_type: ReceiptType,
719        receipt_thread: &ReceiptThread,
720        event_id: &EventId,
721    ) -> Result<Vec<(OwnedUserId, Receipt)>, Self::Error> {
722        (*self).get_event_room_receipt_events(room_id, receipt_type, receipt_thread, event_id).await
723    }
724
725    async fn get_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
726        (*self).get_custom_value(key).await
727    }
728
729    async fn set_custom_value(
730        &self,
731        key: &[u8],
732        value: Vec<u8>,
733    ) -> Result<Option<Vec<u8>>, Self::Error> {
734        (*self).set_custom_value(key, value).await
735    }
736
737    async fn remove_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
738        (*self).remove_custom_value(key).await
739    }
740
741    async fn remove_room(&self, room_id: &RoomId) -> Result<(), Self::Error> {
742        (*self).remove_room(room_id).await
743    }
744
745    async fn save_send_queue_request(
746        &self,
747        room_id: &RoomId,
748        transaction_id: OwnedTransactionId,
749        created_at: MilliSecondsSinceUnixEpoch,
750        request: QueuedRequestKind,
751        priority: usize,
752    ) -> Result<(), Self::Error> {
753        (*self)
754            .save_send_queue_request(room_id, transaction_id, created_at, request, priority)
755            .await
756    }
757
758    async fn update_send_queue_request(
759        &self,
760        room_id: &RoomId,
761        transaction_id: &TransactionId,
762        content: QueuedRequestKind,
763    ) -> Result<bool, Self::Error> {
764        (*self).update_send_queue_request(room_id, transaction_id, content).await
765    }
766
767    async fn remove_send_queue_request(
768        &self,
769        room_id: &RoomId,
770        transaction_id: &TransactionId,
771    ) -> Result<bool, Self::Error> {
772        (*self).remove_send_queue_request(room_id, transaction_id).await
773    }
774
775    async fn load_send_queue_requests(
776        &self,
777        room_id: &RoomId,
778    ) -> Result<Vec<QueuedRequest>, Self::Error> {
779        (*self).load_send_queue_requests(room_id).await
780    }
781
782    async fn update_send_queue_request_status(
783        &self,
784        room_id: &RoomId,
785        transaction_id: &TransactionId,
786        error: Option<QueueWedgeError>,
787    ) -> Result<(), Self::Error> {
788        (*self).update_send_queue_request_status(room_id, transaction_id, error).await
789    }
790
791    async fn load_rooms_with_unsent_requests(&self) -> Result<Vec<OwnedRoomId>, Self::Error> {
792        (*self).load_rooms_with_unsent_requests().await
793    }
794
795    async fn save_dependent_queued_request(
796        &self,
797        room_id: &RoomId,
798        parent_txn_id: &TransactionId,
799        own_txn_id: ChildTransactionId,
800        created_at: MilliSecondsSinceUnixEpoch,
801        content: DependentQueuedRequestKind,
802    ) -> Result<(), Self::Error> {
803        (*self)
804            .save_dependent_queued_request(room_id, parent_txn_id, own_txn_id, created_at, content)
805            .await
806    }
807
808    async fn mark_dependent_queued_requests_as_ready(
809        &self,
810        room_id: &RoomId,
811        parent_txn_id: &TransactionId,
812        sent_parent_key: SentRequestKey,
813    ) -> Result<usize, Self::Error> {
814        (*self)
815            .mark_dependent_queued_requests_as_ready(room_id, parent_txn_id, sent_parent_key)
816            .await
817    }
818
819    async fn update_dependent_queued_request(
820        &self,
821        room_id: &RoomId,
822        own_transaction_id: &ChildTransactionId,
823        new_content: DependentQueuedRequestKind,
824    ) -> Result<bool, Self::Error> {
825        (*self).update_dependent_queued_request(room_id, own_transaction_id, new_content).await
826    }
827
828    async fn remove_dependent_queued_request(
829        &self,
830        room: &RoomId,
831        own_txn_id: &ChildTransactionId,
832    ) -> Result<bool, Self::Error> {
833        (*self).remove_dependent_queued_request(room, own_txn_id).await
834    }
835
836    async fn load_dependent_queued_requests(
837        &self,
838        room: &RoomId,
839    ) -> Result<Vec<DependentQueuedRequest>, Self::Error> {
840        (*self).load_dependent_queued_requests(room).await
841    }
842
843    async fn upsert_thread_subscriptions(
844        &self,
845        updates: Vec<(&RoomId, &EventId, StoredThreadSubscription)>,
846    ) -> Result<(), Self::Error> {
847        (*self).upsert_thread_subscriptions(updates).await
848    }
849
850    async fn remove_thread_subscription(
851        &self,
852        room: &RoomId,
853        thread_id: &EventId,
854    ) -> Result<(), Self::Error> {
855        (*self).remove_thread_subscription(room, thread_id).await
856    }
857
858    async fn load_thread_subscription(
859        &self,
860        room: &RoomId,
861        thread_id: &EventId,
862    ) -> Result<Option<StoredThreadSubscription>, Self::Error> {
863        (*self).load_thread_subscription(room, thread_id).await
864    }
865
866    async fn get_global_profile(
867        &self,
868        user_id: &UserId,
869    ) -> Result<Option<UserProfile>, Self::Error> {
870        (*self).get_global_profile(user_id).await
871    }
872
873    async fn get_global_profiles<'a>(
874        &self,
875        user_ids: &'a [OwnedUserId],
876    ) -> Result<BTreeMap<&'a UserId, UserProfile>, Self::Error> {
877        (*self).get_global_profiles(user_ids).await
878    }
879
880    async fn get_missing_global_profiles<'a>(
881        &self,
882        user_ids: &'a [OwnedUserId],
883    ) -> Result<Vec<&'a UserId>, Self::Error> {
884        (*self).get_missing_global_profiles(user_ids).await
885    }
886
887    async fn close(&self) -> Result<(), Self::Error> {
888        (*self).close().await
889    }
890
891    async fn reopen(&self) -> Result<(), Self::Error> {
892        (*self).reopen().await
893    }
894
895    async fn optimize(&self) -> Result<(), Self::Error> {
896        (*self).optimize().await
897    }
898
899    async fn get_size(&self) -> Result<Option<usize>, Self::Error> {
900        (*self).get_size().await
901    }
902}
903
904#[cfg_attr(target_family = "wasm", async_trait(?Send))]
905#[cfg_attr(not(target_family = "wasm"), async_trait)]
906impl<T: StateStore + ?Sized> StateStore for Arc<T> {
907    type Error = T::Error;
908
909    async fn get_kv_data(
910        &self,
911        key: StateStoreDataKey<'_>,
912    ) -> Result<Option<StateStoreDataValue>, Self::Error> {
913        self.deref().get_kv_data(key).await
914    }
915
916    async fn set_kv_data(
917        &self,
918        key: StateStoreDataKey<'_>,
919        value: StateStoreDataValue,
920    ) -> Result<(), Self::Error> {
921        self.deref().set_kv_data(key, value).await
922    }
923
924    async fn remove_kv_data(&self, key: StateStoreDataKey<'_>) -> Result<(), Self::Error> {
925        self.deref().remove_kv_data(key).await
926    }
927
928    async fn save_changes(&self, changes: &StateChanges) -> Result<(), Self::Error> {
929        self.deref().save_changes(changes).await
930    }
931
932    async fn get_presence_event(
933        &self,
934        user_id: &UserId,
935    ) -> Result<Option<Raw<PresenceEvent>>, Self::Error> {
936        self.deref().get_presence_event(user_id).await
937    }
938
939    async fn get_presence_events(
940        &self,
941        user_ids: &[OwnedUserId],
942    ) -> Result<Vec<Raw<PresenceEvent>>, Self::Error> {
943        self.deref().get_presence_events(user_ids).await
944    }
945
946    async fn get_state_event(
947        &self,
948        room_id: &RoomId,
949        event_type: StateEventType,
950        state_key: &str,
951    ) -> Result<Option<RawAnySyncOrStrippedState>, Self::Error> {
952        self.deref().get_state_event(room_id, event_type, state_key).await
953    }
954
955    async fn get_state_events(
956        &self,
957        room_id: &RoomId,
958        event_type: StateEventType,
959    ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error> {
960        self.deref().get_state_events(room_id, event_type).await
961    }
962
963    async fn get_state_events_for_keys(
964        &self,
965        room_id: &RoomId,
966        event_type: StateEventType,
967        state_keys: &[&str],
968    ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error> {
969        self.deref().get_state_events_for_keys(room_id, event_type, state_keys).await
970    }
971
972    async fn get_profile(
973        &self,
974        room_id: &RoomId,
975        user_id: &UserId,
976    ) -> Result<Option<MinimalRoomMemberEvent>, Self::Error> {
977        self.deref().get_profile(room_id, user_id).await
978    }
979
980    async fn get_profiles<'a>(
981        &self,
982        room_id: &RoomId,
983        user_ids: &'a [OwnedUserId],
984    ) -> Result<BTreeMap<&'a UserId, MinimalRoomMemberEvent>, Self::Error> {
985        self.deref().get_profiles(room_id, user_ids).await
986    }
987
988    async fn get_user_ids(
989        &self,
990        room_id: &RoomId,
991        memberships: RoomMemberships,
992    ) -> Result<Vec<OwnedUserId>, Self::Error> {
993        self.deref().get_user_ids(room_id, memberships).await
994    }
995
996    async fn get_room_infos(
997        &self,
998        room_load_settings: &RoomLoadSettings,
999    ) -> Result<Vec<RoomInfo>, Self::Error> {
1000        self.deref().get_room_infos(room_load_settings).await
1001    }
1002
1003    async fn get_users_with_display_name(
1004        &self,
1005        room_id: &RoomId,
1006        display_name: &DisplayName,
1007    ) -> Result<BTreeSet<OwnedUserId>, Self::Error> {
1008        self.deref().get_users_with_display_name(room_id, display_name).await
1009    }
1010
1011    async fn get_users_with_display_names<'a>(
1012        &self,
1013        room_id: &RoomId,
1014        display_names: &'a [DisplayName],
1015    ) -> Result<HashMap<&'a DisplayName, BTreeSet<OwnedUserId>>, Self::Error> {
1016        self.deref().get_users_with_display_names(room_id, display_names).await
1017    }
1018
1019    async fn get_account_data_event(
1020        &self,
1021        event_type: GlobalAccountDataEventType,
1022    ) -> Result<Option<Raw<AnyGlobalAccountDataEvent>>, Self::Error> {
1023        self.deref().get_account_data_event(event_type).await
1024    }
1025
1026    async fn get_room_account_data_event(
1027        &self,
1028        room_id: &RoomId,
1029        event_type: RoomAccountDataEventType,
1030    ) -> Result<Option<Raw<AnyRoomAccountDataEvent>>, Self::Error> {
1031        self.deref().get_room_account_data_event(room_id, event_type).await
1032    }
1033
1034    async fn get_user_room_receipt_event(
1035        &self,
1036        room_id: &RoomId,
1037        receipt_type: ReceiptType,
1038        receipt_thread: &ReceiptThread,
1039        user_id: &UserId,
1040    ) -> Result<Option<(OwnedEventId, Receipt)>, Self::Error> {
1041        self.deref()
1042            .get_user_room_receipt_event(room_id, receipt_type, receipt_thread, user_id)
1043            .await
1044    }
1045
1046    async fn get_event_room_receipt_events(
1047        &self,
1048        room_id: &RoomId,
1049        receipt_type: ReceiptType,
1050        receipt_thread: &ReceiptThread,
1051        event_id: &EventId,
1052    ) -> Result<Vec<(OwnedUserId, Receipt)>, Self::Error> {
1053        self.deref()
1054            .get_event_room_receipt_events(room_id, receipt_type, receipt_thread, event_id)
1055            .await
1056    }
1057
1058    async fn get_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
1059        self.deref().get_custom_value(key).await
1060    }
1061
1062    async fn set_custom_value(
1063        &self,
1064        key: &[u8],
1065        value: Vec<u8>,
1066    ) -> Result<Option<Vec<u8>>, Self::Error> {
1067        self.deref().set_custom_value(key, value).await
1068    }
1069
1070    async fn remove_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
1071        self.deref().remove_custom_value(key).await
1072    }
1073
1074    async fn remove_room(&self, room_id: &RoomId) -> Result<(), Self::Error> {
1075        self.deref().remove_room(room_id).await
1076    }
1077
1078    async fn save_send_queue_request(
1079        &self,
1080        room_id: &RoomId,
1081        transaction_id: OwnedTransactionId,
1082        created_at: MilliSecondsSinceUnixEpoch,
1083        request: QueuedRequestKind,
1084        priority: usize,
1085    ) -> Result<(), Self::Error> {
1086        self.deref()
1087            .save_send_queue_request(room_id, transaction_id, created_at, request, priority)
1088            .await
1089    }
1090
1091    async fn update_send_queue_request(
1092        &self,
1093        room_id: &RoomId,
1094        transaction_id: &TransactionId,
1095        content: QueuedRequestKind,
1096    ) -> Result<bool, Self::Error> {
1097        self.deref().update_send_queue_request(room_id, transaction_id, content).await
1098    }
1099
1100    async fn remove_send_queue_request(
1101        &self,
1102        room_id: &RoomId,
1103        transaction_id: &TransactionId,
1104    ) -> Result<bool, Self::Error> {
1105        self.deref().remove_send_queue_request(room_id, transaction_id).await
1106    }
1107
1108    async fn load_send_queue_requests(
1109        &self,
1110        room_id: &RoomId,
1111    ) -> Result<Vec<QueuedRequest>, Self::Error> {
1112        self.deref().load_send_queue_requests(room_id).await
1113    }
1114
1115    async fn update_send_queue_request_status(
1116        &self,
1117        room_id: &RoomId,
1118        transaction_id: &TransactionId,
1119        error: Option<QueueWedgeError>,
1120    ) -> Result<(), Self::Error> {
1121        self.deref().update_send_queue_request_status(room_id, transaction_id, error).await
1122    }
1123
1124    async fn load_rooms_with_unsent_requests(&self) -> Result<Vec<OwnedRoomId>, Self::Error> {
1125        self.deref().load_rooms_with_unsent_requests().await
1126    }
1127
1128    async fn save_dependent_queued_request(
1129        &self,
1130        room_id: &RoomId,
1131        parent_txn_id: &TransactionId,
1132        own_txn_id: ChildTransactionId,
1133        created_at: MilliSecondsSinceUnixEpoch,
1134        content: DependentQueuedRequestKind,
1135    ) -> Result<(), Self::Error> {
1136        self.deref()
1137            .save_dependent_queued_request(room_id, parent_txn_id, own_txn_id, created_at, content)
1138            .await
1139    }
1140
1141    async fn mark_dependent_queued_requests_as_ready(
1142        &self,
1143        room_id: &RoomId,
1144        parent_txn_id: &TransactionId,
1145        sent_parent_key: SentRequestKey,
1146    ) -> Result<usize, Self::Error> {
1147        self.deref()
1148            .mark_dependent_queued_requests_as_ready(room_id, parent_txn_id, sent_parent_key)
1149            .await
1150    }
1151
1152    async fn update_dependent_queued_request(
1153        &self,
1154        room_id: &RoomId,
1155        own_transaction_id: &ChildTransactionId,
1156        new_content: DependentQueuedRequestKind,
1157    ) -> Result<bool, Self::Error> {
1158        self.deref().update_dependent_queued_request(room_id, own_transaction_id, new_content).await
1159    }
1160
1161    async fn remove_dependent_queued_request(
1162        &self,
1163        room: &RoomId,
1164        own_txn_id: &ChildTransactionId,
1165    ) -> Result<bool, Self::Error> {
1166        self.deref().remove_dependent_queued_request(room, own_txn_id).await
1167    }
1168
1169    async fn load_dependent_queued_requests(
1170        &self,
1171        room: &RoomId,
1172    ) -> Result<Vec<DependentQueuedRequest>, Self::Error> {
1173        self.deref().load_dependent_queued_requests(room).await
1174    }
1175
1176    async fn upsert_thread_subscriptions(
1177        &self,
1178        updates: Vec<(&RoomId, &EventId, StoredThreadSubscription)>,
1179    ) -> Result<(), Self::Error> {
1180        self.deref().upsert_thread_subscriptions(updates).await
1181    }
1182
1183    async fn remove_thread_subscription(
1184        &self,
1185        room: &RoomId,
1186        thread_id: &EventId,
1187    ) -> Result<(), Self::Error> {
1188        self.deref().remove_thread_subscription(room, thread_id).await
1189    }
1190
1191    async fn load_thread_subscription(
1192        &self,
1193        room: &RoomId,
1194        thread_id: &EventId,
1195    ) -> Result<Option<StoredThreadSubscription>, Self::Error> {
1196        self.deref().load_thread_subscription(room, thread_id).await
1197    }
1198
1199    async fn get_global_profile(
1200        &self,
1201        user_id: &UserId,
1202    ) -> Result<Option<UserProfile>, Self::Error> {
1203        self.deref().get_global_profile(user_id).await
1204    }
1205
1206    async fn get_global_profiles<'a>(
1207        &self,
1208        user_ids: &'a [OwnedUserId],
1209    ) -> Result<BTreeMap<&'a UserId, UserProfile>, Self::Error> {
1210        self.deref().get_global_profiles(user_ids).await
1211    }
1212
1213    async fn get_missing_global_profiles<'a>(
1214        &self,
1215        user_ids: &'a [OwnedUserId],
1216    ) -> Result<Vec<&'a UserId>, Self::Error> {
1217        self.deref().get_missing_global_profiles(user_ids).await
1218    }
1219
1220    async fn close(&self) -> Result<(), Self::Error> {
1221        self.deref().close().await
1222    }
1223
1224    async fn reopen(&self) -> Result<(), Self::Error> {
1225        self.deref().reopen().await
1226    }
1227
1228    async fn optimize(&self) -> Result<(), Self::Error> {
1229        self.deref().optimize().await
1230    }
1231
1232    async fn get_size(&self) -> Result<Option<usize>, Self::Error> {
1233        self.deref().get_size().await
1234    }
1235}
1236
1237#[repr(transparent)]
1238struct EraseStateStoreError<T>(T);
1239
1240#[cfg(not(tarpaulin_include))]
1241impl<T: fmt::Debug> fmt::Debug for EraseStateStoreError<T> {
1242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1243        self.0.fmt(f)
1244    }
1245}
1246
1247#[cfg_attr(target_family = "wasm", async_trait(?Send))]
1248#[cfg_attr(not(target_family = "wasm"), async_trait)]
1249impl<T: StateStore> StateStore for EraseStateStoreError<T> {
1250    type Error = StoreError;
1251
1252    async fn get_kv_data(
1253        &self,
1254        key: StateStoreDataKey<'_>,
1255    ) -> Result<Option<StateStoreDataValue>, Self::Error> {
1256        self.0.get_kv_data(key).await.map_err(Into::into)
1257    }
1258
1259    async fn set_kv_data(
1260        &self,
1261        key: StateStoreDataKey<'_>,
1262        value: StateStoreDataValue,
1263    ) -> Result<(), Self::Error> {
1264        self.0.set_kv_data(key, value).await.map_err(Into::into)
1265    }
1266
1267    async fn remove_kv_data(&self, key: StateStoreDataKey<'_>) -> Result<(), Self::Error> {
1268        self.0.remove_kv_data(key).await.map_err(Into::into)
1269    }
1270
1271    async fn save_changes(&self, changes: &StateChanges) -> Result<(), Self::Error> {
1272        self.0.save_changes(changes).await.map_err(Into::into)
1273    }
1274
1275    async fn get_presence_event(
1276        &self,
1277        user_id: &UserId,
1278    ) -> Result<Option<Raw<PresenceEvent>>, Self::Error> {
1279        self.0.get_presence_event(user_id).await.map_err(Into::into)
1280    }
1281
1282    async fn get_presence_events(
1283        &self,
1284        user_ids: &[OwnedUserId],
1285    ) -> Result<Vec<Raw<PresenceEvent>>, Self::Error> {
1286        self.0.get_presence_events(user_ids).await.map_err(Into::into)
1287    }
1288
1289    async fn get_state_event(
1290        &self,
1291        room_id: &RoomId,
1292        event_type: StateEventType,
1293        state_key: &str,
1294    ) -> Result<Option<RawAnySyncOrStrippedState>, Self::Error> {
1295        self.0.get_state_event(room_id, event_type, state_key).await.map_err(Into::into)
1296    }
1297
1298    async fn get_state_events(
1299        &self,
1300        room_id: &RoomId,
1301        event_type: StateEventType,
1302    ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error> {
1303        self.0.get_state_events(room_id, event_type).await.map_err(Into::into)
1304    }
1305
1306    async fn get_state_events_for_keys(
1307        &self,
1308        room_id: &RoomId,
1309        event_type: StateEventType,
1310        state_keys: &[&str],
1311    ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error> {
1312        self.0.get_state_events_for_keys(room_id, event_type, state_keys).await.map_err(Into::into)
1313    }
1314
1315    async fn get_profile(
1316        &self,
1317        room_id: &RoomId,
1318        user_id: &UserId,
1319    ) -> Result<Option<MinimalRoomMemberEvent>, Self::Error> {
1320        self.0.get_profile(room_id, user_id).await.map_err(Into::into)
1321    }
1322
1323    async fn get_profiles<'a>(
1324        &self,
1325        room_id: &RoomId,
1326        user_ids: &'a [OwnedUserId],
1327    ) -> Result<BTreeMap<&'a UserId, MinimalRoomMemberEvent>, Self::Error> {
1328        self.0.get_profiles(room_id, user_ids).await.map_err(Into::into)
1329    }
1330
1331    async fn get_user_ids(
1332        &self,
1333        room_id: &RoomId,
1334        memberships: RoomMemberships,
1335    ) -> Result<Vec<OwnedUserId>, Self::Error> {
1336        self.0.get_user_ids(room_id, memberships).await.map_err(Into::into)
1337    }
1338
1339    async fn get_room_infos(
1340        &self,
1341        room_load_settings: &RoomLoadSettings,
1342    ) -> Result<Vec<RoomInfo>, Self::Error> {
1343        self.0.get_room_infos(room_load_settings).await.map_err(Into::into)
1344    }
1345
1346    async fn get_users_with_display_name(
1347        &self,
1348        room_id: &RoomId,
1349        display_name: &DisplayName,
1350    ) -> Result<BTreeSet<OwnedUserId>, Self::Error> {
1351        self.0.get_users_with_display_name(room_id, display_name).await.map_err(Into::into)
1352    }
1353
1354    async fn get_users_with_display_names<'a>(
1355        &self,
1356        room_id: &RoomId,
1357        display_names: &'a [DisplayName],
1358    ) -> Result<HashMap<&'a DisplayName, BTreeSet<OwnedUserId>>, Self::Error> {
1359        self.0.get_users_with_display_names(room_id, display_names).await.map_err(Into::into)
1360    }
1361
1362    async fn get_account_data_event(
1363        &self,
1364        event_type: GlobalAccountDataEventType,
1365    ) -> Result<Option<Raw<AnyGlobalAccountDataEvent>>, Self::Error> {
1366        self.0.get_account_data_event(event_type).await.map_err(Into::into)
1367    }
1368
1369    async fn get_room_account_data_event(
1370        &self,
1371        room_id: &RoomId,
1372        event_type: RoomAccountDataEventType,
1373    ) -> Result<Option<Raw<AnyRoomAccountDataEvent>>, Self::Error> {
1374        self.0.get_room_account_data_event(room_id, event_type).await.map_err(Into::into)
1375    }
1376
1377    async fn get_user_room_receipt_event(
1378        &self,
1379        room_id: &RoomId,
1380        receipt_type: ReceiptType,
1381        receipt_thread: &ReceiptThread,
1382        user_id: &UserId,
1383    ) -> Result<Option<(OwnedEventId, Receipt)>, Self::Error> {
1384        self.0
1385            .get_user_room_receipt_event(room_id, receipt_type, receipt_thread, user_id)
1386            .await
1387            .map_err(Into::into)
1388    }
1389
1390    async fn get_event_room_receipt_events(
1391        &self,
1392        room_id: &RoomId,
1393        receipt_type: ReceiptType,
1394        receipt_thread: &ReceiptThread,
1395        event_id: &EventId,
1396    ) -> Result<Vec<(OwnedUserId, Receipt)>, Self::Error> {
1397        self.0
1398            .get_event_room_receipt_events(room_id, receipt_type, receipt_thread, event_id)
1399            .await
1400            .map_err(Into::into)
1401    }
1402
1403    async fn get_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
1404        self.0.get_custom_value(key).await.map_err(Into::into)
1405    }
1406
1407    async fn set_custom_value(
1408        &self,
1409        key: &[u8],
1410        value: Vec<u8>,
1411    ) -> Result<Option<Vec<u8>>, Self::Error> {
1412        self.0.set_custom_value(key, value).await.map_err(Into::into)
1413    }
1414
1415    async fn remove_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
1416        self.0.remove_custom_value(key).await.map_err(Into::into)
1417    }
1418
1419    async fn remove_room(&self, room_id: &RoomId) -> Result<(), Self::Error> {
1420        self.0.remove_room(room_id).await.map_err(Into::into)
1421    }
1422
1423    async fn save_send_queue_request(
1424        &self,
1425        room_id: &RoomId,
1426        transaction_id: OwnedTransactionId,
1427        created_at: MilliSecondsSinceUnixEpoch,
1428        content: QueuedRequestKind,
1429        priority: usize,
1430    ) -> Result<(), Self::Error> {
1431        self.0
1432            .save_send_queue_request(room_id, transaction_id, created_at, content, priority)
1433            .await
1434            .map_err(Into::into)
1435    }
1436
1437    async fn update_send_queue_request(
1438        &self,
1439        room_id: &RoomId,
1440        transaction_id: &TransactionId,
1441        content: QueuedRequestKind,
1442    ) -> Result<bool, Self::Error> {
1443        self.0.update_send_queue_request(room_id, transaction_id, content).await.map_err(Into::into)
1444    }
1445
1446    async fn remove_send_queue_request(
1447        &self,
1448        room_id: &RoomId,
1449        transaction_id: &TransactionId,
1450    ) -> Result<bool, Self::Error> {
1451        self.0.remove_send_queue_request(room_id, transaction_id).await.map_err(Into::into)
1452    }
1453
1454    async fn load_send_queue_requests(
1455        &self,
1456        room_id: &RoomId,
1457    ) -> Result<Vec<QueuedRequest>, Self::Error> {
1458        self.0.load_send_queue_requests(room_id).await.map_err(Into::into)
1459    }
1460
1461    async fn update_send_queue_request_status(
1462        &self,
1463        room_id: &RoomId,
1464        transaction_id: &TransactionId,
1465        error: Option<QueueWedgeError>,
1466    ) -> Result<(), Self::Error> {
1467        self.0
1468            .update_send_queue_request_status(room_id, transaction_id, error)
1469            .await
1470            .map_err(Into::into)
1471    }
1472
1473    async fn load_rooms_with_unsent_requests(&self) -> Result<Vec<OwnedRoomId>, Self::Error> {
1474        self.0.load_rooms_with_unsent_requests().await.map_err(Into::into)
1475    }
1476
1477    async fn save_dependent_queued_request(
1478        &self,
1479        room_id: &RoomId,
1480        parent_txn_id: &TransactionId,
1481        own_txn_id: ChildTransactionId,
1482        created_at: MilliSecondsSinceUnixEpoch,
1483        content: DependentQueuedRequestKind,
1484    ) -> Result<(), Self::Error> {
1485        self.0
1486            .save_dependent_queued_request(room_id, parent_txn_id, own_txn_id, created_at, content)
1487            .await
1488            .map_err(Into::into)
1489    }
1490
1491    async fn mark_dependent_queued_requests_as_ready(
1492        &self,
1493        room_id: &RoomId,
1494        parent_txn_id: &TransactionId,
1495        sent_parent_key: SentRequestKey,
1496    ) -> Result<usize, Self::Error> {
1497        self.0
1498            .mark_dependent_queued_requests_as_ready(room_id, parent_txn_id, sent_parent_key)
1499            .await
1500            .map_err(Into::into)
1501    }
1502
1503    async fn remove_dependent_queued_request(
1504        &self,
1505        room_id: &RoomId,
1506        own_txn_id: &ChildTransactionId,
1507    ) -> Result<bool, Self::Error> {
1508        self.0.remove_dependent_queued_request(room_id, own_txn_id).await.map_err(Into::into)
1509    }
1510
1511    async fn load_dependent_queued_requests(
1512        &self,
1513        room_id: &RoomId,
1514    ) -> Result<Vec<DependentQueuedRequest>, Self::Error> {
1515        self.0.load_dependent_queued_requests(room_id).await.map_err(Into::into)
1516    }
1517
1518    async fn update_dependent_queued_request(
1519        &self,
1520        room_id: &RoomId,
1521        own_transaction_id: &ChildTransactionId,
1522        new_content: DependentQueuedRequestKind,
1523    ) -> Result<bool, Self::Error> {
1524        self.0
1525            .update_dependent_queued_request(room_id, own_transaction_id, new_content)
1526            .await
1527            .map_err(Into::into)
1528    }
1529
1530    async fn upsert_thread_subscriptions(
1531        &self,
1532        updates: Vec<(&RoomId, &EventId, StoredThreadSubscription)>,
1533    ) -> Result<(), Self::Error> {
1534        self.0.upsert_thread_subscriptions(updates).await.map_err(Into::into)
1535    }
1536
1537    async fn load_thread_subscription(
1538        &self,
1539        room: &RoomId,
1540        thread_id: &EventId,
1541    ) -> Result<Option<StoredThreadSubscription>, Self::Error> {
1542        self.0.load_thread_subscription(room, thread_id).await.map_err(Into::into)
1543    }
1544
1545    async fn remove_thread_subscription(
1546        &self,
1547        room: &RoomId,
1548        thread_id: &EventId,
1549    ) -> Result<(), Self::Error> {
1550        self.0.remove_thread_subscription(room, thread_id).await.map_err(Into::into)
1551    }
1552
1553    async fn get_global_profile(
1554        &self,
1555        user_id: &UserId,
1556    ) -> Result<Option<UserProfile>, Self::Error> {
1557        self.0.get_global_profile(user_id).await.map_err(Into::into)
1558    }
1559
1560    async fn get_global_profiles<'a>(
1561        &self,
1562        user_ids: &'a [OwnedUserId],
1563    ) -> Result<BTreeMap<&'a UserId, UserProfile>, Self::Error> {
1564        self.0.get_global_profiles(user_ids).await.map_err(Into::into)
1565    }
1566
1567    async fn get_missing_global_profiles<'a>(
1568        &self,
1569        user_ids: &'a [OwnedUserId],
1570    ) -> Result<Vec<&'a UserId>, Self::Error> {
1571        self.0.get_missing_global_profiles(user_ids).await.map_err(Into::into)
1572    }
1573
1574    async fn close(&self) -> Result<(), Self::Error> {
1575        self.0.close().await.map_err(Into::into)
1576    }
1577
1578    async fn reopen(&self) -> Result<(), Self::Error> {
1579        self.0.reopen().await.map_err(Into::into)
1580    }
1581
1582    async fn optimize(&self) -> Result<(), Self::Error> {
1583        self.0.optimize().await.map_err(Into::into)
1584    }
1585
1586    async fn get_size(&self) -> Result<Option<usize>, Self::Error> {
1587        self.0.get_size().await.map_err(Into::into)
1588    }
1589}
1590
1591/// A wrapper around a [`StateStore`] that supports synchronizing calls to
1592/// [`StateStore::save_changes`].
1593#[derive(Debug, Clone)]
1594pub struct SaveLockedStateStore<T = Arc<DynStateStore>> {
1595    store: T,
1596    lock: Arc<Mutex<()>>,
1597}
1598
1599/// An error type that represents a scenario where a [`MutexGuard`] provided to
1600/// a function does not reference the underlying [`Mutex`] in the enclosing
1601/// [`SaveLockedStateStore`].
1602#[derive(Debug, Error)]
1603#[error("a mutex guard was provided, but it does not reference the correct mutex")]
1604pub struct IncorrectMutexGuardError;
1605
1606impl From<IncorrectMutexGuardError> for StoreError {
1607    fn from(value: IncorrectMutexGuardError) -> Self {
1608        Self::backend(value)
1609    }
1610}
1611
1612impl<T> SaveLockedStateStore<T> {
1613    /// Creates a new [`SaveLockedStateStore`] with the provided store.
1614    pub fn new(store: T) -> Self {
1615        Self { store, lock: Arc::new(Mutex::new(())) }
1616    }
1617
1618    /// Returns a reference to the underlying [`Mutex`] used to synchronize
1619    /// calls to [`StateStore::save_changes`].
1620    pub fn lock(&self) -> &Mutex<()> {
1621        self.lock.as_ref()
1622    }
1623}
1624
1625impl<T: StateStore> SaveLockedStateStore<T> {
1626    /// Provides a means of calling [`StateStore::save_changes`] when the caller
1627    /// has already acquired the underlying [`Mutex`]. Returns an error if the
1628    /// [`MutexGuard`] provided does not reference the underlying [`Mutex`].
1629    pub async fn save_changes_with_guard(
1630        &self,
1631        guard: &MutexGuard<'_, ()>,
1632        changes: &StateChanges,
1633    ) -> Result<(), StoreError> {
1634        if !std::ptr::eq(MutexGuard::mutex(guard), self.lock()) {
1635            Err(IncorrectMutexGuardError.into())
1636        } else {
1637            self.store.save_changes(changes).await.map_err(Into::into)
1638        }
1639    }
1640
1641    /// Provides a means of calling [`StateStore::remove_room`] when the caller
1642    /// has already acquired the underlying [`Mutex`]. Returns an error if the
1643    /// [`MutexGuard`] provided does not reference the underlying [`Mutex`].
1644    pub async fn remove_room_with_guard(
1645        &self,
1646        guard: &MutexGuard<'_, ()>,
1647        room_id: &RoomId,
1648    ) -> Result<(), StoreError> {
1649        if !std::ptr::eq(MutexGuard::mutex(guard), self.lock()) {
1650            Err(IncorrectMutexGuardError.into())
1651        } else {
1652            self.store.remove_room(room_id).await.map_err(Into::into)
1653        }
1654    }
1655}
1656
1657#[cfg_attr(target_family = "wasm", async_trait(?Send))]
1658#[cfg_attr(not(target_family = "wasm"), async_trait)]
1659impl<T: StateStore> StateStore for SaveLockedStateStore<T> {
1660    type Error = T::Error;
1661
1662    async fn get_kv_data(
1663        &self,
1664        key: StateStoreDataKey<'_>,
1665    ) -> Result<Option<StateStoreDataValue>, Self::Error> {
1666        self.store.get_kv_data(key).await
1667    }
1668
1669    async fn set_kv_data(
1670        &self,
1671        key: StateStoreDataKey<'_>,
1672        value: StateStoreDataValue,
1673    ) -> Result<(), Self::Error> {
1674        self.store.set_kv_data(key, value).await
1675    }
1676
1677    async fn remove_kv_data(&self, key: StateStoreDataKey<'_>) -> Result<(), Self::Error> {
1678        self.store.remove_kv_data(key).await
1679    }
1680
1681    async fn save_changes(&self, changes: &StateChanges) -> Result<(), Self::Error> {
1682        let _guard = self.lock.lock().await;
1683        self.store.save_changes(changes).await
1684    }
1685
1686    async fn get_presence_event(
1687        &self,
1688        user_id: &UserId,
1689    ) -> Result<Option<Raw<PresenceEvent>>, Self::Error> {
1690        self.store.get_presence_event(user_id).await
1691    }
1692
1693    async fn get_presence_events(
1694        &self,
1695        user_ids: &[OwnedUserId],
1696    ) -> Result<Vec<Raw<PresenceEvent>>, Self::Error> {
1697        self.store.get_presence_events(user_ids).await
1698    }
1699
1700    async fn get_state_event(
1701        &self,
1702        room_id: &RoomId,
1703        event_type: StateEventType,
1704        state_key: &str,
1705    ) -> Result<Option<RawAnySyncOrStrippedState>, Self::Error> {
1706        self.store.get_state_event(room_id, event_type, state_key).await
1707    }
1708
1709    async fn get_state_events(
1710        &self,
1711        room_id: &RoomId,
1712        event_type: StateEventType,
1713    ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error> {
1714        self.store.get_state_events(room_id, event_type).await
1715    }
1716
1717    async fn get_state_events_for_keys(
1718        &self,
1719        room_id: &RoomId,
1720        event_type: StateEventType,
1721        state_keys: &[&str],
1722    ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error> {
1723        self.store.get_state_events_for_keys(room_id, event_type, state_keys).await
1724    }
1725
1726    async fn get_profile(
1727        &self,
1728        room_id: &RoomId,
1729        user_id: &UserId,
1730    ) -> Result<Option<MinimalRoomMemberEvent>, Self::Error> {
1731        self.store.get_profile(room_id, user_id).await
1732    }
1733
1734    async fn get_profiles<'a>(
1735        &self,
1736        room_id: &RoomId,
1737        user_ids: &'a [OwnedUserId],
1738    ) -> Result<BTreeMap<&'a UserId, MinimalRoomMemberEvent>, Self::Error> {
1739        self.store.get_profiles(room_id, user_ids).await
1740    }
1741
1742    async fn get_user_ids(
1743        &self,
1744        room_id: &RoomId,
1745        memberships: RoomMemberships,
1746    ) -> Result<Vec<OwnedUserId>, Self::Error> {
1747        self.store.get_user_ids(room_id, memberships).await
1748    }
1749
1750    async fn get_room_infos(
1751        &self,
1752        room_load_settings: &RoomLoadSettings,
1753    ) -> Result<Vec<RoomInfo>, Self::Error> {
1754        self.store.get_room_infos(room_load_settings).await
1755    }
1756
1757    async fn get_users_with_display_name(
1758        &self,
1759        room_id: &RoomId,
1760        display_name: &DisplayName,
1761    ) -> Result<BTreeSet<OwnedUserId>, Self::Error> {
1762        self.store.get_users_with_display_name(room_id, display_name).await
1763    }
1764
1765    async fn get_users_with_display_names<'a>(
1766        &self,
1767        room_id: &RoomId,
1768        display_names: &'a [DisplayName],
1769    ) -> Result<HashMap<&'a DisplayName, BTreeSet<OwnedUserId>>, Self::Error> {
1770        self.store.get_users_with_display_names(room_id, display_names).await
1771    }
1772
1773    async fn get_account_data_event(
1774        &self,
1775        event_type: GlobalAccountDataEventType,
1776    ) -> Result<Option<Raw<AnyGlobalAccountDataEvent>>, Self::Error> {
1777        self.store.get_account_data_event(event_type).await
1778    }
1779
1780    async fn get_room_account_data_event(
1781        &self,
1782        room_id: &RoomId,
1783        event_type: RoomAccountDataEventType,
1784    ) -> Result<Option<Raw<AnyRoomAccountDataEvent>>, Self::Error> {
1785        self.store.get_room_account_data_event(room_id, event_type).await
1786    }
1787
1788    async fn get_user_room_receipt_event(
1789        &self,
1790        room_id: &RoomId,
1791        receipt_type: ReceiptType,
1792        receipt_thread: &ReceiptThread,
1793        user_id: &UserId,
1794    ) -> Result<Option<(OwnedEventId, Receipt)>, Self::Error> {
1795        self.store.get_user_room_receipt_event(room_id, receipt_type, receipt_thread, user_id).await
1796    }
1797
1798    async fn get_event_room_receipt_events(
1799        &self,
1800        room_id: &RoomId,
1801        receipt_type: ReceiptType,
1802        receipt_thread: &ReceiptThread,
1803        event_id: &EventId,
1804    ) -> Result<Vec<(OwnedUserId, Receipt)>, Self::Error> {
1805        self.store
1806            .get_event_room_receipt_events(room_id, receipt_type, receipt_thread, event_id)
1807            .await
1808    }
1809
1810    async fn get_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
1811        self.store.get_custom_value(key).await
1812    }
1813
1814    async fn set_custom_value(
1815        &self,
1816        key: &[u8],
1817        value: Vec<u8>,
1818    ) -> Result<Option<Vec<u8>>, Self::Error> {
1819        self.store.set_custom_value(key, value).await
1820    }
1821
1822    async fn remove_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
1823        self.store.remove_custom_value(key).await
1824    }
1825
1826    async fn remove_room(&self, room_id: &RoomId) -> Result<(), Self::Error> {
1827        let _guard = self.lock.lock().await;
1828        self.store.remove_room(room_id).await
1829    }
1830
1831    async fn save_send_queue_request(
1832        &self,
1833        room_id: &RoomId,
1834        transaction_id: OwnedTransactionId,
1835        created_at: MilliSecondsSinceUnixEpoch,
1836        request: QueuedRequestKind,
1837        priority: usize,
1838    ) -> Result<(), Self::Error> {
1839        self.store
1840            .save_send_queue_request(room_id, transaction_id, created_at, request, priority)
1841            .await
1842    }
1843
1844    async fn update_send_queue_request(
1845        &self,
1846        room_id: &RoomId,
1847        transaction_id: &TransactionId,
1848        content: QueuedRequestKind,
1849    ) -> Result<bool, Self::Error> {
1850        self.store.update_send_queue_request(room_id, transaction_id, content).await
1851    }
1852
1853    async fn remove_send_queue_request(
1854        &self,
1855        room_id: &RoomId,
1856        transaction_id: &TransactionId,
1857    ) -> Result<bool, Self::Error> {
1858        self.store.remove_send_queue_request(room_id, transaction_id).await
1859    }
1860
1861    async fn load_send_queue_requests(
1862        &self,
1863        room_id: &RoomId,
1864    ) -> Result<Vec<QueuedRequest>, Self::Error> {
1865        self.store.load_send_queue_requests(room_id).await
1866    }
1867
1868    async fn update_send_queue_request_status(
1869        &self,
1870        room_id: &RoomId,
1871        transaction_id: &TransactionId,
1872        error: Option<QueueWedgeError>,
1873    ) -> Result<(), Self::Error> {
1874        self.store.update_send_queue_request_status(room_id, transaction_id, error).await
1875    }
1876
1877    async fn load_rooms_with_unsent_requests(&self) -> Result<Vec<OwnedRoomId>, Self::Error> {
1878        self.store.load_rooms_with_unsent_requests().await
1879    }
1880
1881    async fn save_dependent_queued_request(
1882        &self,
1883        room_id: &RoomId,
1884        parent_txn_id: &TransactionId,
1885        own_txn_id: ChildTransactionId,
1886        created_at: MilliSecondsSinceUnixEpoch,
1887        content: DependentQueuedRequestKind,
1888    ) -> Result<(), Self::Error> {
1889        self.store
1890            .save_dependent_queued_request(room_id, parent_txn_id, own_txn_id, created_at, content)
1891            .await
1892    }
1893
1894    async fn mark_dependent_queued_requests_as_ready(
1895        &self,
1896        room_id: &RoomId,
1897        parent_txn_id: &TransactionId,
1898        sent_parent_key: SentRequestKey,
1899    ) -> Result<usize, Self::Error> {
1900        self.store
1901            .mark_dependent_queued_requests_as_ready(room_id, parent_txn_id, sent_parent_key)
1902            .await
1903    }
1904
1905    async fn update_dependent_queued_request(
1906        &self,
1907        room_id: &RoomId,
1908        own_transaction_id: &ChildTransactionId,
1909        new_content: DependentQueuedRequestKind,
1910    ) -> Result<bool, Self::Error> {
1911        self.store.update_dependent_queued_request(room_id, own_transaction_id, new_content).await
1912    }
1913
1914    async fn remove_dependent_queued_request(
1915        &self,
1916        room: &RoomId,
1917        own_txn_id: &ChildTransactionId,
1918    ) -> Result<bool, Self::Error> {
1919        self.store.remove_dependent_queued_request(room, own_txn_id).await
1920    }
1921
1922    async fn load_dependent_queued_requests(
1923        &self,
1924        room: &RoomId,
1925    ) -> Result<Vec<DependentQueuedRequest>, Self::Error> {
1926        self.store.load_dependent_queued_requests(room).await
1927    }
1928
1929    async fn upsert_thread_subscriptions(
1930        &self,
1931        updates: Vec<(&RoomId, &EventId, StoredThreadSubscription)>,
1932    ) -> Result<(), Self::Error> {
1933        self.store.upsert_thread_subscriptions(updates).await
1934    }
1935
1936    async fn load_thread_subscription(
1937        &self,
1938        room: &RoomId,
1939        thread_id: &EventId,
1940    ) -> Result<Option<StoredThreadSubscription>, Self::Error> {
1941        self.store.load_thread_subscription(room, thread_id).await
1942    }
1943
1944    async fn remove_thread_subscription(
1945        &self,
1946        room: &RoomId,
1947        thread_id: &EventId,
1948    ) -> Result<(), Self::Error> {
1949        self.store.remove_thread_subscription(room, thread_id).await
1950    }
1951
1952    async fn get_global_profile(
1953        &self,
1954        user_id: &UserId,
1955    ) -> Result<Option<UserProfile>, Self::Error> {
1956        self.store.get_global_profile(user_id).await
1957    }
1958
1959    async fn get_global_profiles<'a>(
1960        &self,
1961        user_ids: &'a [OwnedUserId],
1962    ) -> Result<BTreeMap<&'a UserId, UserProfile>, Self::Error> {
1963        self.store.get_global_profiles(user_ids).await
1964    }
1965
1966    async fn get_missing_global_profiles<'a>(
1967        &self,
1968        user_ids: &'a [OwnedUserId],
1969    ) -> Result<Vec<&'a UserId>, Self::Error> {
1970        self.store.get_missing_global_profiles(user_ids).await
1971    }
1972
1973    async fn close(&self) -> Result<(), Self::Error> {
1974        self.store.close().await
1975    }
1976
1977    async fn reopen(&self) -> Result<(), Self::Error> {
1978        self.store.reopen().await
1979    }
1980
1981    async fn optimize(&self) -> Result<(), Self::Error> {
1982        self.store.optimize().await
1983    }
1984
1985    async fn get_size(&self) -> Result<Option<usize>, Self::Error> {
1986        self.store.get_size().await
1987    }
1988}
1989
1990/// Convenience functionality for state stores.
1991#[cfg_attr(target_family = "wasm", async_trait(?Send))]
1992#[cfg_attr(not(target_family = "wasm"), async_trait)]
1993pub trait StateStoreExt: StateStore {
1994    /// Get a specific state event of statically-known type.
1995    ///
1996    /// # Arguments
1997    ///
1998    /// * `room_id` - The id of the room the state event was received for.
1999    async fn get_state_event_static<C>(
2000        &self,
2001        room_id: &RoomId,
2002    ) -> Result<Option<RawSyncOrStrippedState<C>>, Self::Error>
2003    where
2004        C: StaticEventContent<IsPrefix = ruma::events::False>
2005            + StaticStateEventContent<StateKey = EmptyStateKey>
2006            + RedactContent,
2007        C::Redacted: RedactedStateEventContent,
2008    {
2009        Ok(self.get_state_event(room_id, C::TYPE.into(), "").await?.map(|raw| raw.cast()))
2010    }
2011
2012    /// Get a specific state event of statically-known type.
2013    ///
2014    /// # Arguments
2015    ///
2016    /// * `room_id` - The id of the room the state event was received for.
2017    async fn get_state_event_static_for_key<C, K>(
2018        &self,
2019        room_id: &RoomId,
2020        state_key: &K,
2021    ) -> Result<Option<RawSyncOrStrippedState<C>>, Self::Error>
2022    where
2023        C: StaticEventContent<IsPrefix = ruma::events::False>
2024            + StaticStateEventContent
2025            + RedactContent,
2026        C::StateKey: Borrow<K>,
2027        C::Redacted: RedactedStateEventContent,
2028        K: AsRef<str> + ?Sized + Sync,
2029    {
2030        Ok(self
2031            .get_state_event(room_id, C::TYPE.into(), state_key.as_ref())
2032            .await?
2033            .map(|raw| raw.cast()))
2034    }
2035
2036    /// Get a list of state events of a statically-known type for a given room.
2037    ///
2038    /// # Arguments
2039    ///
2040    /// * `room_id` - The id of the room to find events for.
2041    async fn get_state_events_static<C>(
2042        &self,
2043        room_id: &RoomId,
2044    ) -> Result<Vec<RawSyncOrStrippedState<C>>, Self::Error>
2045    where
2046        C: StaticEventContent<IsPrefix = ruma::events::False>
2047            + StaticStateEventContent
2048            + RedactContent,
2049        C::Redacted: RedactedStateEventContent,
2050    {
2051        // FIXME: Could be more efficient, if we had streaming store accessor
2052        // functions
2053        Ok(self
2054            .get_state_events(room_id, C::TYPE.into())
2055            .await?
2056            .into_iter()
2057            .map(|raw| raw.cast())
2058            .collect())
2059    }
2060
2061    /// Get a list of state events of a statically-known type for a given room
2062    /// and given state keys.
2063    ///
2064    /// # Arguments
2065    ///
2066    /// - `room_id` - The id of the room to find events for.
2067    /// - `state_keys` - The list of state keys to find.
2068    async fn get_state_events_for_keys_static<'a, C, K, I>(
2069        &self,
2070        room_id: &RoomId,
2071        state_keys: I,
2072    ) -> Result<Vec<RawSyncOrStrippedState<C>>, Self::Error>
2073    where
2074        C: StaticEventContent<IsPrefix = ruma::events::False>
2075            + StaticStateEventContent
2076            + RedactContent,
2077        C::StateKey: Borrow<K>,
2078        C::Redacted: RedactedStateEventContent,
2079        K: AsRef<str> + Sized + Sync + 'a,
2080        I: IntoIterator<Item = &'a K> + Send,
2081        I::IntoIter: Send,
2082    {
2083        Ok(self
2084            .get_state_events_for_keys(
2085                room_id,
2086                C::TYPE.into(),
2087                &state_keys.into_iter().map(|k| k.as_ref()).collect::<Vec<_>>(),
2088            )
2089            .await?
2090            .into_iter()
2091            .map(|raw| raw.cast())
2092            .collect())
2093    }
2094
2095    /// Get an event of a statically-known type from the account data store.
2096    async fn get_account_data_event_static<C>(
2097        &self,
2098    ) -> Result<Option<Raw<GlobalAccountDataEvent<C>>>, Self::Error>
2099    where
2100        C: StaticEventContent<IsPrefix = ruma::events::False> + GlobalAccountDataEventContent,
2101    {
2102        Ok(self.get_account_data_event(C::TYPE.into()).await?.map(Raw::cast_unchecked))
2103    }
2104
2105    /// Get an event of a statically-known type from the room account data
2106    /// store.
2107    ///
2108    /// # Arguments
2109    ///
2110    /// - `room_id` - The id of the room for which the room account data event
2111    ///   should be fetched.
2112    async fn get_room_account_data_event_static<C>(
2113        &self,
2114        room_id: &RoomId,
2115    ) -> Result<Option<Raw<RoomAccountDataEvent<C>>>, Self::Error>
2116    where
2117        C: StaticEventContent<IsPrefix = ruma::events::False> + RoomAccountDataEventContent,
2118    {
2119        Ok(self
2120            .get_room_account_data_event(room_id, C::TYPE.into())
2121            .await?
2122            .map(Raw::cast_unchecked))
2123    }
2124
2125    /// Get the `MemberEvent` for the given state key in the given room id.
2126    ///
2127    /// # Arguments
2128    ///
2129    /// * `room_id` - The room id the member event belongs to.
2130    ///
2131    /// * `state_key` - The user id that the member event defines the state for.
2132    async fn get_member_event(
2133        &self,
2134        room_id: &RoomId,
2135        state_key: &UserId,
2136    ) -> Result<Option<RawMemberEvent>, Self::Error> {
2137        self.get_state_event_static_for_key(room_id, state_key).await
2138    }
2139}
2140
2141#[cfg_attr(target_family = "wasm", async_trait(?Send))]
2142#[cfg_attr(not(target_family = "wasm"), async_trait)]
2143impl<T: StateStore + ?Sized> StateStoreExt for T {}
2144
2145/// A type-erased [`StateStore`].
2146pub type DynStateStore = dyn StateStore<Error = StoreError>;
2147
2148/// A type that can be type-erased into `Arc<dyn StateStore>`.
2149///
2150/// This trait is not meant to be implemented directly outside
2151/// `matrix-sdk-crypto`, but it is automatically implemented for everything that
2152/// implements `StateStore`.
2153pub trait IntoStateStore {
2154    #[doc(hidden)]
2155    fn into_state_store(self) -> Arc<DynStateStore>;
2156}
2157
2158impl<T> IntoStateStore for T
2159where
2160    T: StateStore + Sized + 'static,
2161{
2162    fn into_state_store(self) -> Arc<DynStateStore> {
2163        Arc::new(EraseStateStoreError(self))
2164    }
2165}
2166
2167/// Serialisable representation of get_supported_versions::Response.
2168#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2169pub struct SupportedVersionsResponse {
2170    /// Versions supported by the remote server.
2171    pub versions: Vec<String>,
2172
2173    /// List of unstable features and their enablement status.
2174    pub unstable_features: BTreeMap<String, bool>,
2175}
2176
2177impl SupportedVersionsResponse {
2178    /// Extracts known Matrix versions and features from the un-typed lists of
2179    /// strings.
2180    ///
2181    /// Note: Matrix versions and features that Ruma cannot parse, or does not
2182    /// know about, are discarded.
2183    pub fn supported_versions(&self) -> SupportedVersions {
2184        let mut supported_versions =
2185            SupportedVersions::from_parts(&self.versions, &self.unstable_features);
2186
2187        // We need at least one supported version to be able to make requests,
2188        // so we default to Matrix 1.0.
2189        if supported_versions.versions.is_empty() {
2190            supported_versions.versions.insert(MatrixVersion::V1_0);
2191        }
2192
2193        supported_versions
2194    }
2195}
2196
2197#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2198/// A serialisable representation of discover_homeserver::Response.
2199pub struct WellKnownResponse {
2200    /// Information about the homeserver to connect to.
2201    pub homeserver: HomeserverInfo,
2202
2203    /// Information about the identity server to connect to.
2204    pub identity_server: Option<IdentityServerInfo>,
2205
2206    /// Information about the tile server to use to display location data.
2207    pub tile_server: Option<TileServerInfo>,
2208
2209    /// A list of the available MatrixRTC foci, ordered by priority.
2210    pub rtc_foci: Vec<RtcTransport>,
2211}
2212
2213impl From<discover_homeserver::Response> for WellKnownResponse {
2214    fn from(response: discover_homeserver::Response) -> Self {
2215        Self {
2216            homeserver: response.homeserver,
2217            identity_server: response.identity_server,
2218            tile_server: response.tile_server,
2219            rtc_foci: response.rtc_foci,
2220        }
2221    }
2222}
2223
2224/// A serialisable representation of the
2225/// `get_retention_configuration::msc1763::Response`.
2226///
2227/// See [MSC1763](https://github.com/matrix-org/matrix-spec-proposals/pull/1763)
2228/// for more info.
2229#[derive(Debug, Clone, Serialize, Deserialize)]
2230pub struct RetentionConfigurationResponse {
2231    /// Map between a room ID (or all rooms) and their respective retention
2232    /// policy.
2233    pub policies: BTreeMap<RoomIdOrAllRooms, RoomRetentionEventContent>,
2234
2235    /// Limits to apply to policies defined by `m.room.retention` state events.
2236    pub limits: RetentionLimits,
2237}
2238
2239impl From<RetentionConfigurationApiResponse> for RetentionConfigurationResponse {
2240    fn from(response: RetentionConfigurationApiResponse) -> Self {
2241        Self { policies: response.policies, limits: response.limits }
2242    }
2243}
2244
2245impl From<RetentionConfigurationResponse> for RetentionConfigurationApiResponse {
2246    fn from(response: RetentionConfigurationResponse) -> Self {
2247        Self::new(response.policies, response.limits)
2248    }
2249}
2250
2251/// A value for key-value data that should be persisted into the store.
2252#[derive(Debug, Clone)]
2253pub enum StateStoreDataValue {
2254    /// The sync token.
2255    SyncToken(String),
2256
2257    /// The supported versions of the server.
2258    SupportedVersions(TtlValue<SupportedVersionsResponse>),
2259
2260    /// The well-known information of the server.
2261    WellKnown(TtlValue<Option<WellKnownResponse>>),
2262
2263    /// A filter with the given ID.
2264    Filter(String),
2265
2266    /// The user avatar url
2267    UserAvatarUrl(OwnedMxcUri),
2268
2269    /// A list of recently visited room identifiers for the current user
2270    RecentlyVisitedRooms(Vec<OwnedRoomId>),
2271
2272    /// Persistent data for
2273    /// `matrix_sdk_ui::unable_to_decrypt_hook::UtdHookManager`.
2274    UtdHookManagerData(GrowableBloom),
2275
2276    /// A unit value telling us that the client uploaded duplicate one-time
2277    /// keys.
2278    OneTimeKeyAlreadyUploaded,
2279
2280    /// A composer draft for the room. To learn more, see [`ComposerDraft`].
2281    ///
2282    /// [`ComposerDraft`]: Self::ComposerDraft
2283    ComposerDraft(ComposerDraft),
2284
2285    /// A list of knock request ids marked as seen in a room.
2286    SeenKnockRequests(BTreeMap<OwnedEventId, OwnedUserId>),
2287
2288    /// A list of tokens to continue thread subscriptions catchup.
2289    ///
2290    /// See documentation of [`ThreadSubscriptionCatchupToken`] for more
2291    /// details.
2292    ThreadSubscriptionsCatchupTokens(Vec<ThreadSubscriptionCatchupToken>),
2293
2294    /// The capabilities the homeserver supports or disables.
2295    HomeserverCapabilities(TtlValue<Capabilities>),
2296
2297    /// The message retention configuration of the homeserver
2298    /// ([MSC1763](https://github.com/matrix-org/matrix-spec-proposals/pull/1763)).
2299    RetentionConfiguration(TtlValue<RetentionConfigurationResponse>),
2300}
2301
2302/// Tokens to use when catching up on thread subscriptions.
2303///
2304/// These tokens are created when the client receives some thread subscriptions
2305/// from sync, but the sync indicates that there are more thread subscriptions
2306/// available on the server. In this case, it's expected that the client will
2307/// call the [MSC4308] companion endpoint to catch up (back-paginate) on
2308/// previous thread subscriptions.
2309///
2310/// [MSC4308]: https://github.com/matrix-org/matrix-spec-proposals/pull/4308
2311#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2312pub struct ThreadSubscriptionCatchupToken {
2313    /// The token to use as the lower bound when fetching new threads
2314    /// subscriptions.
2315    ///
2316    /// In sliding sync, this is the `prev_batch` value of a sliding sync
2317    /// response.
2318    pub from: String,
2319
2320    /// The token to use as the upper bound when fetching new threads
2321    /// subscriptions.
2322    ///
2323    /// In sliding sync, it must be set to the `pos` value of the sliding sync
2324    /// _request_, which response received a `prev_batch` token.
2325    pub to: Option<String>,
2326}
2327
2328/// Current draft of the composer for the room.
2329#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2330pub struct ComposerDraft {
2331    /// The draft content in plain text.
2332    pub plain_text: String,
2333    /// If the message is formatted in HTML, the HTML representation of the
2334    /// message.
2335    pub html_text: Option<String>,
2336    /// The type of draft.
2337    pub draft_type: ComposerDraftType,
2338    /// Attachments associated with this draft.
2339    #[serde(default)]
2340    pub attachments: Vec<DraftAttachment>,
2341}
2342
2343/// An attachment stored with a composer draft.
2344#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2345pub struct DraftAttachment {
2346    /// The filename of the attachment.
2347    pub filename: String,
2348    /// The attachment content with type-specific data.
2349    pub content: DraftAttachmentContent,
2350}
2351
2352/// The content of a draft attachment with type-specific data.
2353#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2354#[serde(tag = "type")]
2355pub enum DraftAttachmentContent {
2356    /// Image attachment.
2357    Image {
2358        /// The image file data.
2359        #[serde(with = "serde_bytes")]
2360        data: Vec<u8>,
2361        /// MIME type.
2362        mimetype: Option<String>,
2363        /// File size in bytes.
2364        size: Option<u64>,
2365        /// Width in pixels.
2366        width: Option<u64>,
2367        /// Height in pixels.
2368        height: Option<u64>,
2369        /// BlurHash string.
2370        blurhash: Option<String>,
2371        /// Optional thumbnail.
2372        thumbnail: Option<DraftThumbnail>,
2373    },
2374    /// Video attachment.
2375    Video {
2376        /// The video file data.
2377        #[serde(with = "serde_bytes")]
2378        data: Vec<u8>,
2379        /// MIME type.
2380        mimetype: Option<String>,
2381        /// File size in bytes.
2382        size: Option<u64>,
2383        /// Width in pixels.
2384        width: Option<u64>,
2385        /// Height in pixels.
2386        height: Option<u64>,
2387        /// Duration.
2388        duration: Option<std::time::Duration>,
2389        /// BlurHash string.
2390        blurhash: Option<String>,
2391        /// Optional thumbnail.
2392        thumbnail: Option<DraftThumbnail>,
2393    },
2394    /// Audio attachment.
2395    Audio {
2396        /// The audio file data.
2397        #[serde(with = "serde_bytes")]
2398        data: Vec<u8>,
2399        /// MIME type.
2400        mimetype: Option<String>,
2401        /// File size in bytes.
2402        size: Option<u64>,
2403        /// Duration.
2404        duration: Option<std::time::Duration>,
2405    },
2406    /// Generic file attachment.
2407    File {
2408        /// The file data.
2409        #[serde(with = "serde_bytes")]
2410        data: Vec<u8>,
2411        /// MIME type.
2412        mimetype: Option<String>,
2413        /// File size in bytes.
2414        size: Option<u64>,
2415    },
2416}
2417
2418/// Thumbnail data for a draft attachment.
2419#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2420pub struct DraftThumbnail {
2421    /// The filename of the thumbnail.
2422    pub filename: String,
2423    /// The thumbnail image data.
2424    #[serde(with = "serde_bytes")]
2425    pub data: Vec<u8>,
2426    /// MIME type of the thumbnail.
2427    pub mimetype: Option<String>,
2428    /// Width in pixels.
2429    pub width: Option<u64>,
2430    /// Height in pixels.
2431    pub height: Option<u64>,
2432    /// File size in bytes.
2433    pub size: Option<u64>,
2434}
2435
2436/// The type of draft of the composer.
2437#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2438pub enum ComposerDraftType {
2439    /// The draft is a new message.
2440    NewMessage,
2441    /// The draft is a reply to an event.
2442    Reply {
2443        /// The ID of the event being replied to.
2444        event_id: OwnedEventId,
2445    },
2446    /// The draft is an edit of an event.
2447    Edit {
2448        /// The ID of the event being edited.
2449        event_id: OwnedEventId,
2450    },
2451}
2452
2453impl StateStoreDataValue {
2454    /// Get this value if it is a sync token.
2455    pub fn into_sync_token(self) -> Option<String> {
2456        as_variant!(self, Self::SyncToken)
2457    }
2458
2459    /// Get this value if it is a filter.
2460    pub fn into_filter(self) -> Option<String> {
2461        as_variant!(self, Self::Filter)
2462    }
2463
2464    /// Get this value if it is a user avatar url.
2465    pub fn into_user_avatar_url(self) -> Option<OwnedMxcUri> {
2466        as_variant!(self, Self::UserAvatarUrl)
2467    }
2468
2469    /// Get this value if it is a list of recently visited rooms.
2470    pub fn into_recently_visited_rooms(self) -> Option<Vec<OwnedRoomId>> {
2471        as_variant!(self, Self::RecentlyVisitedRooms)
2472    }
2473
2474    /// Get this value if it is the data for the `UtdHookManager`.
2475    pub fn into_utd_hook_manager_data(self) -> Option<GrowableBloom> {
2476        as_variant!(self, Self::UtdHookManagerData)
2477    }
2478
2479    /// Get this value if it is a composer draft.
2480    pub fn into_composer_draft(self) -> Option<ComposerDraft> {
2481        as_variant!(self, Self::ComposerDraft)
2482    }
2483
2484    /// Get this value if it is the supported versions metadata.
2485    pub fn into_supported_versions(self) -> Option<TtlValue<SupportedVersionsResponse>> {
2486        as_variant!(self, Self::SupportedVersions)
2487    }
2488
2489    /// Get this value if it is the well-known metadata.
2490    pub fn into_well_known(self) -> Option<TtlValue<Option<WellKnownResponse>>> {
2491        as_variant!(self, Self::WellKnown)
2492    }
2493
2494    /// Get this value if it is the data for the ignored join requests.
2495    pub fn into_seen_knock_requests(self) -> Option<BTreeMap<OwnedEventId, OwnedUserId>> {
2496        as_variant!(self, Self::SeenKnockRequests)
2497    }
2498
2499    /// Get this value if it is the data for the thread subscriptions catchup
2500    /// tokens.
2501    pub fn into_thread_subscriptions_catchup_tokens(
2502        self,
2503    ) -> Option<Vec<ThreadSubscriptionCatchupToken>> {
2504        as_variant!(self, Self::ThreadSubscriptionsCatchupTokens)
2505    }
2506
2507    /// Get this value if it is the data for the capabilities the homeserver
2508    /// supports or disables.
2509    pub fn into_homeserver_capabilities(self) -> Option<TtlValue<Capabilities>> {
2510        as_variant!(self, Self::HomeserverCapabilities)
2511    }
2512
2513    /// Get this value if it is the homeserver's message retention
2514    /// configuration.
2515    pub fn into_retention_configuration(self) -> Option<TtlValue<RetentionConfigurationResponse>> {
2516        as_variant!(self, Self::RetentionConfiguration)
2517    }
2518}
2519
2520/// A key for key-value data.
2521#[derive(Debug, Clone, Copy)]
2522pub enum StateStoreDataKey<'a> {
2523    /// The sync token.
2524    SyncToken,
2525
2526    /// The supported versions of the server,
2527    SupportedVersions,
2528
2529    /// The well-known information of the server,
2530    WellKnown,
2531
2532    /// A filter with the given name.
2533    Filter(&'a str),
2534
2535    /// Avatar URL
2536    UserAvatarUrl(&'a UserId),
2537
2538    /// Recently visited room identifiers
2539    RecentlyVisitedRooms(&'a UserId),
2540
2541    /// Persistent data for
2542    /// `matrix_sdk_ui::unable_to_decrypt_hook::UtdHookManager`.
2543    UtdHookManagerData,
2544
2545    /// Data remembering if the client already reported that it has uploaded
2546    /// duplicate one-time keys.
2547    OneTimeKeyAlreadyUploaded,
2548
2549    /// A composer draft for the room. To learn more, see [`ComposerDraft`].
2550    ///
2551    /// [`ComposerDraft`]: Self::ComposerDraft
2552    ComposerDraft(&'a RoomId, Option<&'a EventId>),
2553
2554    /// A list of knock request ids marked as seen in a room.
2555    SeenKnockRequests(&'a RoomId),
2556
2557    /// A list of thread subscriptions catchup tokens.
2558    ThreadSubscriptionsCatchupTokens,
2559
2560    /// A list of capabilities that the homeserver supports.
2561    HomeserverCapabilities,
2562
2563    /// The message retention configuration of the homeserver.
2564    RetentionConfiguration,
2565}
2566
2567impl StateStoreDataKey<'_> {
2568    /// Key to use for the [`SyncToken`][Self::SyncToken] variant.
2569    pub const SYNC_TOKEN: &'static str = "sync_token";
2570
2571    /// Key to use for the [`SupportedVersions`][Self::SupportedVersions]
2572    /// variant.
2573    // Note: this is the old name, kept for backwards compatibility.
2574    pub const SUPPORTED_VERSIONS: &'static str = "server_capabilities";
2575
2576    /// Key to use for the [`WellKnown`][Self::WellKnown] variant.
2577    pub const WELL_KNOWN: &'static str = "well_known";
2578
2579    /// Key prefix to use for the [`Filter`][Self::Filter] variant.
2580    pub const FILTER: &'static str = "filter";
2581
2582    /// Key prefix to use for the [`UserAvatarUrl`][Self::UserAvatarUrl]
2583    /// variant.
2584    pub const USER_AVATAR_URL: &'static str = "user_avatar_url";
2585
2586    /// Key prefix to use for the
2587    /// [`RecentlyVisitedRooms`][Self::RecentlyVisitedRooms] variant.
2588    pub const RECENTLY_VISITED_ROOMS: &'static str = "recently_visited_rooms";
2589
2590    /// Key to use for the [`UtdHookManagerData`][Self::UtdHookManagerData]
2591    /// variant.
2592    pub const UTD_HOOK_MANAGER_DATA: &'static str = "utd_hook_manager_data";
2593
2594    /// Key to use for the flag remembering that we already reported that we
2595    /// uploaded duplicate one-time keys.
2596    pub const ONE_TIME_KEY_ALREADY_UPLOADED: &'static str = "one_time_key_already_uploaded";
2597
2598    /// Key prefix to use for the [`ComposerDraft`][Self::ComposerDraft]
2599    /// variant.
2600    pub const COMPOSER_DRAFT: &'static str = "composer_draft";
2601
2602    /// Key prefix to use for the [`SeenKnockRequests`][Self::SeenKnockRequests]
2603    /// variant.
2604    pub const SEEN_KNOCK_REQUESTS: &'static str = "seen_knock_requests";
2605
2606    /// Key prefix to use for the
2607    /// [`ThreadSubscriptionsCatchupTokens`][Self::ThreadSubscriptionsCatchupTokens]
2608    /// variant.
2609    pub const THREAD_SUBSCRIPTIONS_CATCHUP_TOKENS: &'static str =
2610        "thread_subscriptions_catchup_tokens";
2611
2612    /// Key prefix to use for the homeserver's [`Capabilities`].
2613    pub const HOMESERVER_CAPABILITIES: &'static str = "homeserver_capabilities";
2614
2615    /// Key to use for the
2616    /// [`RetentionConfiguration`][Self::RetentionConfiguration] variant.
2617    pub const RETENTION_CONFIGURATION: &'static str = "retention_configuration";
2618}
2619
2620/// Compare two thread subscription changes bump stamps, given a fixed room and
2621/// thread root event id pair.
2622///
2623/// May update the newer one to keep the previous one if needed, under some
2624/// conditions.
2625///
2626/// Returns true if the new subscription should be stored, or false if the new
2627/// subscription should be ignored.
2628pub fn compare_thread_subscription_bump_stamps(
2629    previous: Option<u64>,
2630    new: &mut Option<u64>,
2631) -> bool {
2632    match (previous, &new) {
2633        // If the previous subscription had a bump stamp, and the new one
2634        // doesn't, keep the previous one; it should be updated soon via sync
2635        // anyways.
2636        (Some(prev_bump), None) => {
2637            *new = Some(prev_bump);
2638        }
2639
2640        // If the previous bump stamp is newer than the new one, don't store the value at all.
2641        (Some(prev_bump), Some(new_bump)) if *new_bump <= prev_bump => {
2642            return false;
2643        }
2644
2645        // In all other cases, keep the new bumpstamp.
2646        _ => {}
2647    }
2648
2649    true
2650}
2651
2652#[cfg(test)]
2653mod tests {
2654    mod save_locked_state_store {
2655        use std::time::Duration;
2656
2657        use assert_matches::assert_matches;
2658        use futures_util::future::{self, Either};
2659        #[cfg(all(target_family = "wasm", target_os = "unknown"))]
2660        use gloo_timers::future::sleep;
2661        use matrix_sdk_common::executor::spawn;
2662        use matrix_sdk_test::async_test;
2663        use ruma::room_id;
2664        use tokio::sync::Mutex;
2665        #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
2666        use tokio::time::sleep;
2667
2668        use crate::{
2669            StateChanges, StateStore,
2670            store::{IntoStateStore, MemoryStore, Result, SaveLockedStateStore},
2671        };
2672
2673        async fn get_store() -> Result<impl StateStore> {
2674            Ok(SaveLockedStateStore::new(MemoryStore::new()))
2675        }
2676
2677        statestore_integration_tests!();
2678
2679        #[async_test]
2680        async fn test_save_changes_only_accepts_guard_for_underlying_mutex() {
2681            let state_store = SaveLockedStateStore::new(MemoryStore::new());
2682            let state_changes = StateChanges::default();
2683            state_store
2684                .save_changes_with_guard(&state_store.lock().lock().await, &state_changes)
2685                .await
2686                .expect("state store accepts guard for underlying mutex");
2687
2688            let mutex = Mutex::new(());
2689            state_store
2690                .save_changes_with_guard(&mutex.lock().await, &state_changes)
2691                .await
2692                .expect_err("state store does not accept guard for unknown mutex");
2693        }
2694
2695        #[async_test]
2696        async fn test_remove_room_only_accepts_guard_for_underlying_mutex() {
2697            let state_store = SaveLockedStateStore::new(MemoryStore::new());
2698            let room_id = room_id!("!room");
2699            state_store
2700                .remove_room_with_guard(&state_store.lock().lock().await, room_id)
2701                .await
2702                .expect("state store accepts guard for underlying mutex");
2703
2704            let mutex = Mutex::new(());
2705            state_store
2706                .remove_room_with_guard(&mutex.lock().await, room_id)
2707                .await
2708                .expect_err("state store does not accept guard for unknown mutex");
2709        }
2710
2711        #[derive(Debug)]
2712        struct Elapsed;
2713
2714        async fn timeout<F: Future + Unpin>(
2715            duration: Duration,
2716            f: F,
2717        ) -> Result<F::Output, Elapsed> {
2718            #[cfg(all(target_family = "wasm", target_os = "unknown"))]
2719            {
2720                match future::select(sleep(duration), f).await {
2721                    Either::Left(_) => return Err(Elapsed),
2722                    Either::Right((output, _)) => Ok(output),
2723                }
2724            }
2725            #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
2726            {
2727                tokio::time::timeout(duration, f).await.map_err(|_| Elapsed)
2728            }
2729        }
2730
2731        #[async_test]
2732        async fn test_state_store_waits_to_acquire_lock_before_saving_changes() {
2733            let state_store = SaveLockedStateStore::new(MemoryStore::new().into_state_store());
2734
2735            // Acquire lock and hold it for 5 seconds
2736            let lock_task = spawn({
2737                let state_store = state_store.clone();
2738                async move {
2739                    let lock = state_store.lock();
2740                    let _guard = lock.lock().await;
2741                    sleep(Duration::from_secs(5)).await;
2742                }
2743            });
2744
2745            // Try to save changes to the state store while the lock is held by
2746            // another task
2747            let save_task =
2748                spawn(async move { state_store.save_changes(&StateChanges::default()).await });
2749
2750            // Ensure that the second task does not progress until the first
2751            // task has completed and therefore release the save lock
2752            assert_matches!(future::select(lock_task, save_task).await, Either::Left((_, save_task)) => {
2753                timeout(Duration::from_millis(100), save_task)
2754                    .await
2755                    .expect("task completes before timeout")
2756                    .expect("task completes successfully")
2757                    .expect("task saves changes");
2758            });
2759        }
2760
2761        #[async_test]
2762        async fn test_state_store_waits_to_acquire_lock_before_removing_room() {
2763            let state_store = SaveLockedStateStore::new(MemoryStore::new().into_state_store());
2764
2765            // Acquire lock and hold it for 5 seconds
2766            let lock_task = spawn({
2767                let state_store = state_store.clone();
2768                async move {
2769                    let lock = state_store.lock();
2770                    let _guard = lock.lock().await;
2771                    sleep(Duration::from_secs(5)).await;
2772                }
2773            });
2774
2775            // Try to remove room from the state store while the lock is held by
2776            // another task
2777            let remove_task =
2778                spawn(async move { state_store.remove_room(room_id!("!room")).await });
2779
2780            // Ensure that the second task does not progress until the first
2781            // task has completed and therefore release the save lock
2782            assert_matches!(future::select(lock_task, remove_task).await, Either::Left((_, remove_task)) => {
2783                timeout(Duration::from_millis(100), remove_task)
2784                    .await
2785                    .expect("task completes before timeout")
2786                    .expect("task completes successfully")
2787                    .expect("task saves changes");
2788            });
2789        }
2790    }
2791}