matrix_sdk_base/event_cache/store/
mod.rs

1// Copyright 2024 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
15//! The event cache stores holds events when the cache was
16//! activated to save bandwidth at the cost of increased storage space usage.
17//!
18//! Implementing the `EventCacheStore` trait, you can plug any storage backend
19//! into the event cache for the actual storage. By default this brings an
20//! in-memory store.
21
22use 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, CrossProcessLockError, CrossProcessLockGeneration, CrossProcessLockGuard,
32    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/// The high-level public type to represent an `EventCacheStore` lock.
46#[derive(Clone)]
47pub struct EventCacheStoreLock {
48    /// The inner cross process lock that is used to lock the `EventCacheStore`.
49    cross_process_lock: Arc<CrossProcessLock<LockableEventCacheStore>>,
50
51    /// The store itself.
52    ///
53    /// That's the only place where the store exists.
54    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    /// Create a new lock around the [`EventCacheStore`].
66    ///
67    /// The `holder` argument represents the holder inside the
68    /// [`CrossProcessLock::new`].
69    pub fn new<S>(store: S, holder: String) -> Self
70    where
71        S: IntoEventCacheStore,
72    {
73        let store = store.into_event_cache_store();
74
75        Self {
76            cross_process_lock: Arc::new(CrossProcessLock::new(
77                LockableEventCacheStore(store.clone()),
78                "default".to_owned(),
79                holder,
80            )),
81            store,
82        }
83    }
84
85    /// Acquire a spin lock (see [`CrossProcessLock::spin_lock`]).
86    pub async fn lock(&self) -> Result<EventCacheStoreLockState, CrossProcessLockError> {
87        let lock_state =
88            self.cross_process_lock.spin_lock(None).await??.map(|cross_process_lock_guard| {
89                EventCacheStoreLockGuard { cross_process_lock_guard, store: self.store.clone() }
90            });
91
92        Ok(lock_state)
93    }
94}
95
96/// The equivalent of [`CrossProcessLockState`] but for the [`EventCacheStore`].
97///
98/// [`CrossProcessLockState`]: matrix_sdk_common::cross_process_lock::CrossProcessLockState
99pub type EventCacheStoreLockState = MappedCrossProcessLockState<EventCacheStoreLockGuard>;
100
101/// An RAII implementation of a “scoped lock” of an [`EventCacheStoreLock`].
102/// When this structure is dropped (falls out of scope), the lock will be
103/// unlocked.
104#[derive(Clone)]
105pub struct EventCacheStoreLockGuard {
106    /// The cross process lock guard.
107    #[allow(unused)]
108    cross_process_lock_guard: CrossProcessLockGuard,
109
110    /// A reference to the store.
111    store: Arc<DynEventCacheStore>,
112}
113
114impl EventCacheStoreLockGuard {
115    /// Forward to [`CrossProcessLockGuard::clear_dirty`].
116    ///
117    /// This is an associated method to avoid colliding with the [`Deref`]
118    /// implementation.
119    pub fn clear_dirty(this: &Self) {
120        this.cross_process_lock_guard.clear_dirty();
121    }
122
123    /// Force to [`CrossProcessLockGuard::is_dirty`].
124    pub fn is_dirty(this: &Self) -> bool {
125        this.cross_process_lock_guard.is_dirty()
126    }
127}
128
129#[cfg(not(tarpaulin_include))]
130impl fmt::Debug for EventCacheStoreLockGuard {
131    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
132        formatter.debug_struct("EventCacheStoreLockGuard").finish_non_exhaustive()
133    }
134}
135
136impl Deref for EventCacheStoreLockGuard {
137    type Target = DynEventCacheStore;
138
139    fn deref(&self) -> &Self::Target {
140        self.store.as_ref()
141    }
142}
143
144/// Event cache store specific error type.
145#[derive(Debug, thiserror::Error)]
146pub enum EventCacheStoreError {
147    /// An error happened in the underlying database backend.
148    #[error(transparent)]
149    Backend(Box<dyn std::error::Error + Send + Sync>),
150
151    /// The store is locked with a passphrase and an incorrect passphrase
152    /// was given.
153    #[error("The event cache store failed to be unlocked")]
154    Locked,
155
156    /// An unencrypted store was tried to be unlocked with a passphrase.
157    #[error("The event cache store is not encrypted but tried to be opened with a passphrase")]
158    Unencrypted,
159
160    /// The store failed to encrypt or decrypt some data.
161    #[error("Error encrypting or decrypting data from the event cache store: {0}")]
162    Encryption(#[from] StoreEncryptionError),
163
164    /// The store failed to encode or decode some data.
165    #[error("Error encoding or decoding data from the event cache store: {0}")]
166    Codec(#[from] Utf8Error),
167
168    /// The store failed to serialize or deserialize some data.
169    #[error("Error serializing or deserializing data from the event cache store: {0}")]
170    Serialization(#[from] serde_json::Error),
171
172    /// The database format has changed in a backwards incompatible way.
173    #[error(
174        "The database format of the event cache store changed in an incompatible way, \
175         current version: {0}, latest version: {1}"
176    )]
177    UnsupportedDatabaseVersion(usize, usize),
178
179    /// The store contains invalid data.
180    #[error("The store contains invalid data: {details}")]
181    InvalidData {
182        /// Details why the data contained in the store was invalid.
183        details: String,
184    },
185}
186
187impl EventCacheStoreError {
188    /// Create a new [`Backend`][Self::Backend] error.
189    ///
190    /// Shorthand for `EventCacheStoreError::Backend(Box::new(error))`.
191    #[inline]
192    pub fn backend<E>(error: E) -> Self
193    where
194        E: std::error::Error + Send + Sync + 'static,
195    {
196        Self::Backend(Box::new(error))
197    }
198}
199
200impl From<EventCacheStoreError> for CrossProcessLockError {
201    fn from(value: EventCacheStoreError) -> Self {
202        Self::TryLock(Box::new(value))
203    }
204}
205
206/// An `EventCacheStore` specific result type.
207pub type Result<T, E = EventCacheStoreError> = std::result::Result<T, E>;
208
209/// A type that wraps the [`EventCacheStore`] but implements [`TryLock`] to
210/// make it usable inside the cross process lock.
211#[derive(Clone, Debug)]
212struct LockableEventCacheStore(Arc<DynEventCacheStore>);
213
214impl TryLock for LockableEventCacheStore {
215    type LockError = EventCacheStoreError;
216
217    async fn try_lock(
218        &self,
219        lease_duration_ms: u32,
220        key: &str,
221        holder: &str,
222    ) -> std::result::Result<Option<CrossProcessLockGeneration>, Self::LockError> {
223        self.0.try_take_leased_lock(lease_duration_ms, key, holder).await
224    }
225}
226
227/// Helper to extract the relation information from an event.
228///
229/// If the event isn't in relation to another event, then this will return
230/// `None`. Otherwise, returns both the event id this event relates to, and the
231/// kind of relation as a string (e.g. `m.replace`).
232pub fn extract_event_relation(event: &Raw<AnySyncTimelineEvent>) -> Option<(OwnedEventId, String)> {
233    #[derive(serde::Deserialize)]
234    struct RelatesTo {
235        event_id: OwnedEventId,
236        rel_type: String,
237    }
238
239    #[derive(serde::Deserialize)]
240    struct EventContent {
241        #[serde(rename = "m.relates_to")]
242        rel: Option<RelatesTo>,
243    }
244
245    match event.get_field::<EventContent>("content") {
246        Ok(event_content) => {
247            event_content.and_then(|c| c.rel).map(|rel| (rel.event_id, rel.rel_type))
248        }
249        Err(err) => {
250            trace!("when extracting relation data from an event: {err}");
251            None
252        }
253    }
254}