matrix_sdk_base/event_cache/store/
mod.rs1use std::{fmt, ops::Deref, str::Utf8Error, sync::Arc};
23
24#[cfg(any(test, feature = "testing"))]
25#[macro_use]
26pub mod integration_tests;
27mod memory_store;
28mod traits;
29
30use matrix_sdk_common::cross_process_lock::{
31 CrossProcessLock, CrossProcessLockConfig, CrossProcessLockError, CrossProcessLockGeneration,
32 CrossProcessLockGuard, MappedCrossProcessLockState, TryLock,
33};
34pub use matrix_sdk_store_encryption::Error as StoreEncryptionError;
35use ruma::{OwnedEventId, events::AnySyncTimelineEvent, serde::Raw};
36use tracing::trace;
37
38#[cfg(any(test, feature = "testing"))]
39pub use self::integration_tests::EventCacheStoreIntegrationTests;
40pub use self::{
41 memory_store::MemoryStore,
42 traits::{DEFAULT_CHUNK_CAPACITY, DynEventCacheStore, EventCacheStore, IntoEventCacheStore},
43};
44
45#[derive(Clone)]
47pub struct EventCacheStoreLock {
48 cross_process_lock: Arc<CrossProcessLock<LockableEventCacheStore>>,
50
51 store: Arc<DynEventCacheStore>,
55}
56
57#[cfg(not(tarpaulin_include))]
58impl fmt::Debug for EventCacheStoreLock {
59 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
60 formatter.debug_struct("EventCacheStoreLock").finish_non_exhaustive()
61 }
62}
63
64impl EventCacheStoreLock {
65 pub fn new<S>(store: S, cross_process_lock_config: CrossProcessLockConfig) -> Self
70 where
71 S: IntoEventCacheStore,
72 {
73 let store = store.into_event_cache_store();
74
75 let cross_process_lock = Arc::new(CrossProcessLock::new(
76 LockableEventCacheStore(store.clone()),
77 "default".to_owned(),
78 cross_process_lock_config,
79 ));
80 Self { cross_process_lock, store }
81 }
82
83 pub async fn lock(&self) -> Result<EventCacheStoreLockState, CrossProcessLockError> {
85 Ok(self.cross_process_lock.spin_lock(None).await??.map(|cross_process_lock_guard| {
86 EventCacheStoreLockGuard { cross_process_lock_guard, store: self.store.clone() }
87 }))
88 }
89}
90
91pub type EventCacheStoreLockState = MappedCrossProcessLockState<EventCacheStoreLockGuard>;
95
96#[derive(Clone)]
100pub struct EventCacheStoreLockGuard {
101 #[allow(unused)]
103 cross_process_lock_guard: CrossProcessLockGuard,
104
105 store: Arc<DynEventCacheStore>,
107}
108
109impl EventCacheStoreLockGuard {
110 pub fn clear_dirty(this: &Self) {
115 this.cross_process_lock_guard.clear_dirty();
116 }
117
118 pub fn is_dirty(this: &Self) -> bool {
120 this.cross_process_lock_guard.is_dirty()
121 }
122}
123
124#[cfg(not(tarpaulin_include))]
125impl fmt::Debug for EventCacheStoreLockGuard {
126 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
127 formatter.debug_struct("EventCacheStoreLockGuard").finish_non_exhaustive()
128 }
129}
130
131impl Deref for EventCacheStoreLockGuard {
132 type Target = DynEventCacheStore;
133
134 fn deref(&self) -> &Self::Target {
135 self.store.as_ref()
136 }
137}
138
139#[derive(Debug, thiserror::Error)]
141pub enum EventCacheStoreError {
142 #[error(transparent)]
144 Backend(Box<dyn std::error::Error + Send + Sync>),
145
146 #[error("The event cache store failed to be unlocked")]
149 Locked,
150
151 #[error("The event cache store is not encrypted but tried to be opened with a passphrase")]
153 Unencrypted,
154
155 #[error("Error encrypting or decrypting data from the event cache store: {0}")]
157 Encryption(#[from] StoreEncryptionError),
158
159 #[error("Error encoding or decoding data from the event cache store: {0}")]
161 Codec(#[from] Utf8Error),
162
163 #[error("Error serializing or deserializing data from the event cache store: {0}")]
165 Serialization(#[from] serde_json::Error),
166
167 #[error(
169 "The database format of the event cache store changed in an incompatible way, \
170 current version: {0}, latest version: {1}"
171 )]
172 UnsupportedDatabaseVersion(usize, usize),
173
174 #[error("The store contains invalid data: {details}")]
176 InvalidData {
177 details: String,
179 },
180}
181
182impl EventCacheStoreError {
183 #[inline]
187 pub fn backend<E>(error: E) -> Self
188 where
189 E: std::error::Error + Send + Sync + 'static,
190 {
191 Self::Backend(Box::new(error))
192 }
193}
194
195impl From<EventCacheStoreError> for CrossProcessLockError {
196 fn from(value: EventCacheStoreError) -> Self {
197 Self::TryLock(Box::new(value))
198 }
199}
200
201pub type Result<T, E = EventCacheStoreError> = std::result::Result<T, E>;
203
204#[derive(Clone, Debug)]
207struct LockableEventCacheStore(Arc<DynEventCacheStore>);
208
209impl TryLock for LockableEventCacheStore {
210 type LockError = EventCacheStoreError;
211
212 async fn try_lock(
213 &self,
214 lease_duration_ms: u32,
215 key: &str,
216 holder: &str,
217 ) -> std::result::Result<Option<CrossProcessLockGeneration>, Self::LockError> {
218 self.0.try_take_leased_lock(lease_duration_ms, key, holder).await
219 }
220}
221
222pub fn extract_event_relation(event: &Raw<AnySyncTimelineEvent>) -> Option<(OwnedEventId, String)> {
228 #[derive(serde::Deserialize)]
229 struct RelatesTo {
230 event_id: OwnedEventId,
231 rel_type: String,
232 }
233
234 #[derive(serde::Deserialize)]
235 struct EventContent {
236 #[serde(rename = "m.relates_to")]
237 rel: Option<RelatesTo>,
238 }
239
240 match event.get_field::<EventContent>("content") {
241 Ok(event_content) => {
242 event_content.and_then(|c| c.rel).map(|rel| (rel.event_id, rel.rel_type))
243 }
244 Err(err) => {
245 trace!("when extracting relation data from an event: {err}");
246 None
247 }
248 }
249}