1use 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#[cfg_attr(target_family = "wasm", async_trait(?Send))]
78#[cfg_attr(not(target_family = "wasm"), async_trait)]
79pub trait StateStore: AsyncTraitDeps {
80 type Error: fmt::Debug + Into<StoreError> + From<serde_json::Error>;
82
83 async fn get_kv_data(
89 &self,
90 key: StateStoreDataKey<'_>,
91 ) -> Result<Option<StateStoreDataValue>, Self::Error>;
92
93 async fn set_kv_data(
103 &self,
104 key: StateStoreDataKey<'_>,
105 value: StateStoreDataValue,
106 ) -> Result<(), Self::Error>;
107
108 async fn remove_kv_data(&self, key: StateStoreDataKey<'_>) -> Result<(), Self::Error>;
114
115 async fn save_changes(&self, changes: &StateChanges) -> Result<(), Self::Error>;
117
118 async fn get_presence_event(
125 &self,
126 user_id: &UserId,
127 ) -> Result<Option<Raw<PresenceEvent>>, Self::Error>;
128
129 async fn get_presence_events(
135 &self,
136 user_ids: &[OwnedUserId],
137 ) -> Result<Vec<Raw<PresenceEvent>>, Self::Error>;
138
139 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 async fn get_state_events(
161 &self,
162 room_id: &RoomId,
163 event_type: StateEventType,
164 ) -> Result<Vec<RawAnySyncOrStrippedState>, Self::Error>;
165
166 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 async fn get_profile(
189 &self,
190 room_id: &RoomId,
191 user_id: &UserId,
192 ) -> Result<Option<MinimalRoomMemberEvent>, Self::Error>;
193
194 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 async fn get_user_ids(
210 &self,
211 room_id: &RoomId,
212 memberships: RoomMemberships,
213 ) -> Result<Vec<OwnedUserId>, Self::Error>;
214
215 async fn get_room_infos(
217 &self,
218 room_load_settings: &RoomLoadSettings,
219 ) -> Result<Vec<RoomInfo>, Self::Error>;
220
221 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 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 async fn get_account_data_event(
253 &self,
254 event_type: GlobalAccountDataEventType,
255 ) -> Result<Option<Raw<AnyGlobalAccountDataEvent>>, Self::Error>;
256
257 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 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 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 async fn get_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error>;
314
315 async fn set_custom_value(
323 &self,
324 key: &[u8],
325 value: Vec<u8>,
326 ) -> Result<Option<Vec<u8>>, Self::Error>;
327
328 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 async fn remove_custom_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error>;
354
355 async fn remove_room(&self, room_id: &RoomId) -> Result<(), Self::Error>;
361
362 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 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 async fn remove_send_queue_request(
404 &self,
405 room_id: &RoomId,
406 transaction_id: &TransactionId,
407 ) -> Result<bool, Self::Error>;
408
409 async fn load_send_queue_requests(
415 &self,
416 room_id: &RoomId,
417 ) -> Result<Vec<QueuedRequest>, Self::Error>;
418
419 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 async fn load_rooms_with_unsent_requests(&self) -> Result<Vec<OwnedRoomId>, Self::Error>;
430
431 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 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 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 async fn remove_dependent_queued_request(
472 &self,
473 room: &RoomId,
474 own_txn_id: &ChildTransactionId,
475 ) -> Result<bool, Self::Error>;
476
477 async fn load_dependent_queued_requests(
483 &self,
484 room: &RoomId,
485 ) -> Result<Vec<DependentQueuedRequest>, Self::Error>;
486
487 async fn upsert_thread_subscriptions(
497 &self,
498 updates: Vec<(&RoomId, &EventId, StoredThreadSubscription)>,
499 ) -> Result<(), Self::Error>;
500
501 async fn remove_thread_subscription(
505 &self,
506 room: &RoomId,
507 thread_id: &EventId,
508 ) -> Result<(), Self::Error>;
509
510 async fn load_thread_subscription(
514 &self,
515 room: &RoomId,
516 thread_id: &EventId,
517 ) -> Result<Option<StoredThreadSubscription>, Self::Error>;
518
519 async fn get_global_profile(
528 &self,
529 user_id: &UserId,
530 ) -> Result<Option<UserProfile>, Self::Error>;
531
532 async fn get_global_profiles<'a>(
537 &self,
538 user_ids: &'a [OwnedUserId],
539 ) -> Result<BTreeMap<&'a UserId, UserProfile>, Self::Error>;
540
541 async fn get_missing_global_profiles<'a>(
548 &self,
549 user_ids: &'a [OwnedUserId],
550 ) -> Result<Vec<&'a UserId>, Self::Error>;
551
552 async fn close(&self) -> Result<(), Self::Error>;
558
559 async fn reopen(&self) -> Result<(), Self::Error>;
562
563 #[doc(hidden)]
569 async fn optimize(&self) -> Result<(), Self::Error>;
570
571 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#[derive(Debug, Clone)]
1594pub struct SaveLockedStateStore<T = Arc<DynStateStore>> {
1595 store: T,
1596 lock: Arc<Mutex<()>>,
1597}
1598
1599#[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 pub fn new(store: T) -> Self {
1615 Self { store, lock: Arc::new(Mutex::new(())) }
1616 }
1617
1618 pub fn lock(&self) -> &Mutex<()> {
1621 self.lock.as_ref()
1622 }
1623}
1624
1625impl<T: StateStore> SaveLockedStateStore<T> {
1626 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 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#[cfg_attr(target_family = "wasm", async_trait(?Send))]
1992#[cfg_attr(not(target_family = "wasm"), async_trait)]
1993pub trait StateStoreExt: StateStore {
1994 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 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 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 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 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 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 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 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
2145pub type DynStateStore = dyn StateStore<Error = StoreError>;
2147
2148pub 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2169pub struct SupportedVersionsResponse {
2170 pub versions: Vec<String>,
2172
2173 pub unstable_features: BTreeMap<String, bool>,
2175}
2176
2177impl SupportedVersionsResponse {
2178 pub fn supported_versions(&self) -> SupportedVersions {
2184 let mut supported_versions =
2185 SupportedVersions::from_parts(&self.versions, &self.unstable_features);
2186
2187 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)]
2198pub struct WellKnownResponse {
2200 pub homeserver: HomeserverInfo,
2202
2203 pub identity_server: Option<IdentityServerInfo>,
2205
2206 pub tile_server: Option<TileServerInfo>,
2208
2209 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#[derive(Debug, Clone, Serialize, Deserialize)]
2230pub struct RetentionConfigurationResponse {
2231 pub policies: BTreeMap<RoomIdOrAllRooms, RoomRetentionEventContent>,
2234
2235 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#[derive(Debug, Clone)]
2253pub enum StateStoreDataValue {
2254 SyncToken(String),
2256
2257 SupportedVersions(TtlValue<SupportedVersionsResponse>),
2259
2260 WellKnown(TtlValue<Option<WellKnownResponse>>),
2262
2263 Filter(String),
2265
2266 UserAvatarUrl(OwnedMxcUri),
2268
2269 RecentlyVisitedRooms(Vec<OwnedRoomId>),
2271
2272 UtdHookManagerData(GrowableBloom),
2275
2276 OneTimeKeyAlreadyUploaded,
2279
2280 ComposerDraft(ComposerDraft),
2284
2285 SeenKnockRequests(BTreeMap<OwnedEventId, OwnedUserId>),
2287
2288 ThreadSubscriptionsCatchupTokens(Vec<ThreadSubscriptionCatchupToken>),
2293
2294 HomeserverCapabilities(TtlValue<Capabilities>),
2296
2297 RetentionConfiguration(TtlValue<RetentionConfigurationResponse>),
2300}
2301
2302#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2312pub struct ThreadSubscriptionCatchupToken {
2313 pub from: String,
2319
2320 pub to: Option<String>,
2326}
2327
2328#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2330pub struct ComposerDraft {
2331 pub plain_text: String,
2333 pub html_text: Option<String>,
2336 pub draft_type: ComposerDraftType,
2338 #[serde(default)]
2340 pub attachments: Vec<DraftAttachment>,
2341}
2342
2343#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2345pub struct DraftAttachment {
2346 pub filename: String,
2348 pub content: DraftAttachmentContent,
2350}
2351
2352#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2354#[serde(tag = "type")]
2355pub enum DraftAttachmentContent {
2356 Image {
2358 #[serde(with = "serde_bytes")]
2360 data: Vec<u8>,
2361 mimetype: Option<String>,
2363 size: Option<u64>,
2365 width: Option<u64>,
2367 height: Option<u64>,
2369 blurhash: Option<String>,
2371 thumbnail: Option<DraftThumbnail>,
2373 },
2374 Video {
2376 #[serde(with = "serde_bytes")]
2378 data: Vec<u8>,
2379 mimetype: Option<String>,
2381 size: Option<u64>,
2383 width: Option<u64>,
2385 height: Option<u64>,
2387 duration: Option<std::time::Duration>,
2389 blurhash: Option<String>,
2391 thumbnail: Option<DraftThumbnail>,
2393 },
2394 Audio {
2396 #[serde(with = "serde_bytes")]
2398 data: Vec<u8>,
2399 mimetype: Option<String>,
2401 size: Option<u64>,
2403 duration: Option<std::time::Duration>,
2405 },
2406 File {
2408 #[serde(with = "serde_bytes")]
2410 data: Vec<u8>,
2411 mimetype: Option<String>,
2413 size: Option<u64>,
2415 },
2416}
2417
2418#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2420pub struct DraftThumbnail {
2421 pub filename: String,
2423 #[serde(with = "serde_bytes")]
2425 pub data: Vec<u8>,
2426 pub mimetype: Option<String>,
2428 pub width: Option<u64>,
2430 pub height: Option<u64>,
2432 pub size: Option<u64>,
2434}
2435
2436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2438pub enum ComposerDraftType {
2439 NewMessage,
2441 Reply {
2443 event_id: OwnedEventId,
2445 },
2446 Edit {
2448 event_id: OwnedEventId,
2450 },
2451}
2452
2453impl StateStoreDataValue {
2454 pub fn into_sync_token(self) -> Option<String> {
2456 as_variant!(self, Self::SyncToken)
2457 }
2458
2459 pub fn into_filter(self) -> Option<String> {
2461 as_variant!(self, Self::Filter)
2462 }
2463
2464 pub fn into_user_avatar_url(self) -> Option<OwnedMxcUri> {
2466 as_variant!(self, Self::UserAvatarUrl)
2467 }
2468
2469 pub fn into_recently_visited_rooms(self) -> Option<Vec<OwnedRoomId>> {
2471 as_variant!(self, Self::RecentlyVisitedRooms)
2472 }
2473
2474 pub fn into_utd_hook_manager_data(self) -> Option<GrowableBloom> {
2476 as_variant!(self, Self::UtdHookManagerData)
2477 }
2478
2479 pub fn into_composer_draft(self) -> Option<ComposerDraft> {
2481 as_variant!(self, Self::ComposerDraft)
2482 }
2483
2484 pub fn into_supported_versions(self) -> Option<TtlValue<SupportedVersionsResponse>> {
2486 as_variant!(self, Self::SupportedVersions)
2487 }
2488
2489 pub fn into_well_known(self) -> Option<TtlValue<Option<WellKnownResponse>>> {
2491 as_variant!(self, Self::WellKnown)
2492 }
2493
2494 pub fn into_seen_knock_requests(self) -> Option<BTreeMap<OwnedEventId, OwnedUserId>> {
2496 as_variant!(self, Self::SeenKnockRequests)
2497 }
2498
2499 pub fn into_thread_subscriptions_catchup_tokens(
2502 self,
2503 ) -> Option<Vec<ThreadSubscriptionCatchupToken>> {
2504 as_variant!(self, Self::ThreadSubscriptionsCatchupTokens)
2505 }
2506
2507 pub fn into_homeserver_capabilities(self) -> Option<TtlValue<Capabilities>> {
2510 as_variant!(self, Self::HomeserverCapabilities)
2511 }
2512
2513 pub fn into_retention_configuration(self) -> Option<TtlValue<RetentionConfigurationResponse>> {
2516 as_variant!(self, Self::RetentionConfiguration)
2517 }
2518}
2519
2520#[derive(Debug, Clone, Copy)]
2522pub enum StateStoreDataKey<'a> {
2523 SyncToken,
2525
2526 SupportedVersions,
2528
2529 WellKnown,
2531
2532 Filter(&'a str),
2534
2535 UserAvatarUrl(&'a UserId),
2537
2538 RecentlyVisitedRooms(&'a UserId),
2540
2541 UtdHookManagerData,
2544
2545 OneTimeKeyAlreadyUploaded,
2548
2549 ComposerDraft(&'a RoomId, Option<&'a EventId>),
2553
2554 SeenKnockRequests(&'a RoomId),
2556
2557 ThreadSubscriptionsCatchupTokens,
2559
2560 HomeserverCapabilities,
2562
2563 RetentionConfiguration,
2565}
2566
2567impl StateStoreDataKey<'_> {
2568 pub const SYNC_TOKEN: &'static str = "sync_token";
2570
2571 pub const SUPPORTED_VERSIONS: &'static str = "server_capabilities";
2575
2576 pub const WELL_KNOWN: &'static str = "well_known";
2578
2579 pub const FILTER: &'static str = "filter";
2581
2582 pub const USER_AVATAR_URL: &'static str = "user_avatar_url";
2585
2586 pub const RECENTLY_VISITED_ROOMS: &'static str = "recently_visited_rooms";
2589
2590 pub const UTD_HOOK_MANAGER_DATA: &'static str = "utd_hook_manager_data";
2593
2594 pub const ONE_TIME_KEY_ALREADY_UPLOADED: &'static str = "one_time_key_already_uploaded";
2597
2598 pub const COMPOSER_DRAFT: &'static str = "composer_draft";
2601
2602 pub const SEEN_KNOCK_REQUESTS: &'static str = "seen_knock_requests";
2605
2606 pub const THREAD_SUBSCRIPTIONS_CATCHUP_TOKENS: &'static str =
2610 "thread_subscriptions_catchup_tokens";
2611
2612 pub const HOMESERVER_CAPABILITIES: &'static str = "homeserver_capabilities";
2614
2615 pub const RETENTION_CONFIGURATION: &'static str = "retention_configuration";
2618}
2619
2620pub fn compare_thread_subscription_bump_stamps(
2629 previous: Option<u64>,
2630 new: &mut Option<u64>,
2631) -> bool {
2632 match (previous, &new) {
2633 (Some(prev_bump), None) => {
2637 *new = Some(prev_bump);
2638 }
2639
2640 (Some(prev_bump), Some(new_bump)) if *new_bump <= prev_bump => {
2642 return false;
2643 }
2644
2645 _ => {}
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 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 let save_task =
2748 spawn(async move { state_store.save_changes(&StateChanges::default()).await });
2749
2750 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 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 let remove_task =
2778 spawn(async move { state_store.remove_room(room_id!("!room")).await });
2779
2780 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}