Skip to main content

matrix_sdk_base/event_cache/store/
traits.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
15use std::{fmt, sync::Arc};
16
17use async_trait::async_trait;
18use matrix_sdk_common::{
19    AsyncTraitDeps,
20    cross_process_lock::CrossProcessLockGeneration,
21    linked_chunk::{
22        ChunkIdentifier, ChunkIdentifierGenerator, ChunkMetadata, LinkedChunkId, Position,
23        RawChunk, Update,
24    },
25};
26use ruma::{EventId, OwnedEventId, RoomId, events::relation::RelationType};
27
28use super::{
29    super::{Event, Gap, thread::ThreadInfo},
30    EventCacheStoreError,
31};
32
33/// A default capacity for linked chunks, when manipulating in conjunction with
34/// an `EventCacheStore` implementation.
35// TODO: move back?
36pub const DEFAULT_CHUNK_CAPACITY: usize = 128;
37
38/// An abstract trait that can be used to implement different store backends
39/// for the event cache of the SDK.
40#[cfg_attr(target_family = "wasm", async_trait(?Send))]
41#[cfg_attr(not(target_family = "wasm"), async_trait)]
42pub trait EventCacheStore: AsyncTraitDeps {
43    /// The error type used by this event cache store.
44    type Error: fmt::Debug + Into<EventCacheStoreError>;
45
46    /// Try to take a lock using the given store.
47    async fn try_take_leased_lock(
48        &self,
49        lease_duration_ms: u32,
50        key: &str,
51        holder: &str,
52    ) -> Result<Option<CrossProcessLockGeneration>, Self::Error>;
53
54    /// An [`Update`] reflects an operation that has happened inside a linked
55    /// chunk. The linked chunk is used by the event cache to store the events
56    /// in-memory. This method aims at forwarding this update inside this store.
57    async fn handle_linked_chunk_updates(
58        &self,
59        linked_chunk_id: LinkedChunkId<'_>,
60        updates: Vec<Update<Event, Gap>>,
61    ) -> Result<(), Self::Error>;
62
63    /// Return all the raw components of a linked chunk, so the caller may
64    /// reconstruct the linked chunk later.
65    #[doc(hidden)]
66    async fn load_all_chunks(
67        &self,
68        linked_chunk_id: LinkedChunkId<'_>,
69    ) -> Result<Vec<RawChunk<Event, Gap>>, Self::Error>;
70
71    /// Load all of the chunks' metadata for the given [`LinkedChunkId`].
72    ///
73    /// Chunks are unordered, and there's no guarantee that the chunks would
74    /// form a valid linked chunk after reconstruction.
75    async fn load_all_chunks_metadata(
76        &self,
77        linked_chunk_id: LinkedChunkId<'_>,
78    ) -> Result<Vec<ChunkMetadata>, Self::Error>;
79
80    /// Load the last chunk of the `LinkedChunk` holding all events of the room
81    /// identified by `room_id`.
82    ///
83    /// This is used to iteratively load events for the `EventCache`.
84    async fn load_last_chunk(
85        &self,
86        linked_chunk_id: LinkedChunkId<'_>,
87    ) -> Result<(Option<RawChunk<Event, Gap>>, ChunkIdentifierGenerator), Self::Error>;
88
89    /// Load the chunk before the chunk identified by `before_chunk_identifier`
90    /// of the `LinkedChunk` holding all events of the room identified by
91    /// `room_id`
92    ///
93    /// This is used to iteratively load events for the `EventCache`.
94    async fn load_previous_chunk(
95        &self,
96        linked_chunk_id: LinkedChunkId<'_>,
97        before_chunk_identifier: ChunkIdentifier,
98    ) -> Result<Option<RawChunk<Event, Gap>>, Self::Error>;
99
100    /// Load the [`ThreadInfo`] associated to `room_id` and `thread_id`.
101    ///
102    /// If the `ThreadInfo` does not exist, this method **must create** it.
103    /// Consequently, this method is also a way to remember a thread.
104    ///
105    /// It does nothing regarding events or linked chunks.
106    /// This is important if one wants to list all threads, or remove specific
107    /// events or linked chunks.
108    async fn load_thread_info(
109        &self,
110        room_id: &RoomId,
111        thread_id: &EventId,
112    ) -> Result<ThreadInfo, Self::Error>;
113
114    /// Update the [`ThreadInfo`] associated to `room_id` and `thread_id`.
115    ///
116    /// If it does not exist, this method **must fail**! Normally, the
117    /// `ThreadInfo` must be created automatically with
118    /// [`Self::load_thread_info`], so it must always exist.
119    async fn update_thread_info(
120        &self,
121        room_id: &RoomId,
122        thread_id: &EventId,
123        thread_info: &ThreadInfo,
124    ) -> Result<(), Self::Error>;
125
126    /// Clear persisted events for all the rooms if `room_id` is `None`, or a
127    /// single room otherwise.
128    ///
129    /// This will empty and remove all the linked chunks stored previously,
130    /// using the above [`Self::handle_linked_chunk_updates`] methods. It
131    /// *also* deletes all the events' content.
132    ///
133    /// ⚠ This is meant only for super specific use cases, where there shouldn't
134    /// be any live in-memory linked chunks. In general, prefer using
135    /// `EventCache::clear_all_rooms()` from the common SDK crate.
136    async fn clear_all_events(&self, room_id: Option<&RoomId>) -> Result<(), Self::Error>;
137
138    /// Given a set of event IDs, return the duplicated events along with their
139    /// position if there are any.
140    async fn filter_duplicated_events(
141        &self,
142        linked_chunk_id: LinkedChunkId<'_>,
143        events: Vec<OwnedEventId>,
144    ) -> Result<Vec<(OwnedEventId, Position)>, Self::Error>;
145
146    /// Find an event by its ID in a room.
147    ///
148    /// This method must return events saved either in any linked chunks, *or*
149    /// events saved "out-of-band" with the [`Self::save_event`] method.
150    async fn find_event(
151        &self,
152        room_id: &RoomId,
153        event_id: &EventId,
154    ) -> Result<Option<Event>, Self::Error>;
155
156    /// Find all the events (alongside their position in the room's linked
157    /// chunk, if available) that relate to a given event.
158    ///
159    /// The only events which don't have a position are those which have been
160    /// saved out-of-band using [`Self::save_event`].
161    ///
162    /// Note: it doesn't process relations recursively: for instance, if
163    /// requesting only thread events, it will NOT return the aggregated
164    /// events affecting the returned events. It is the responsibility of
165    /// the caller to do so, if needed.
166    ///
167    /// An additional filter can be provided to only retrieve related events for
168    /// a certain relationship.
169    ///
170    /// This method must return events saved either in any linked chunks, *or*
171    /// events saved "out-of-band" with the [`Self::save_event`] method.
172    async fn find_event_relations(
173        &self,
174        room_id: &RoomId,
175        event_id: &EventId,
176        filter: Option<&[RelationType]>,
177    ) -> Result<Vec<(Event, Option<Position>)>, Self::Error>;
178
179    /// Get all events in this room.
180    ///
181    /// This method must return events saved either in any linked chunks, *or*
182    /// events saved "out-of-band" with the [`Self::save_event`] method.
183    async fn get_room_events(
184        &self,
185        room_id: &RoomId,
186        event_type: Option<&str>,
187        session_id: Option<&str>,
188    ) -> Result<Vec<Event>, Self::Error>;
189
190    /// Save an event, that might or might not be part of an existing linked
191    /// chunk.
192    ///
193    /// If the event has no event id, it will not be saved, and the function
194    /// must return an Ok result early.
195    ///
196    /// If the event was already stored with the same id, it must be replaced,
197    /// without causing an error.
198    async fn save_event(&self, room_id: &RoomId, event: Event) -> Result<(), Self::Error>;
199
200    /// Close the store, releasing all held resources (database connections,
201    /// file descriptors, file locks).
202    ///
203    /// In-flight operations complete before this method returns. After it
204    /// returns, operations will fail until [`Self::reopen()`] is called.
205    async fn close(&self) -> Result<(), Self::Error>;
206
207    /// Reopen the store after a [`Self::close()`], re-acquiring database
208    /// connections.
209    async fn reopen(&self) -> Result<(), Self::Error>;
210
211    /// Perform database optimizations if any are available, i.e. vacuuming in
212    /// SQLite.
213    ///
214    /// **Warning:** this was added to check if SQLite fragmentation was the
215    /// source of performance issues, **DO NOT use in production**.
216    #[doc(hidden)]
217    async fn optimize(&self) -> Result<(), Self::Error>;
218
219    /// Returns the size of the store in bytes, if known.
220    async fn get_size(&self) -> Result<Option<usize>, Self::Error>;
221}
222
223#[repr(transparent)]
224struct EraseEventCacheStoreError<T>(T);
225
226#[cfg(not(tarpaulin_include))]
227impl<T: fmt::Debug> fmt::Debug for EraseEventCacheStoreError<T> {
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        self.0.fmt(f)
230    }
231}
232
233#[cfg_attr(target_family = "wasm", async_trait(?Send))]
234#[cfg_attr(not(target_family = "wasm"), async_trait)]
235impl<T: EventCacheStore> EventCacheStore for EraseEventCacheStoreError<T> {
236    type Error = EventCacheStoreError;
237
238    async fn try_take_leased_lock(
239        &self,
240        lease_duration_ms: u32,
241        key: &str,
242        holder: &str,
243    ) -> Result<Option<CrossProcessLockGeneration>, Self::Error> {
244        self.0.try_take_leased_lock(lease_duration_ms, key, holder).await.map_err(Into::into)
245    }
246
247    async fn handle_linked_chunk_updates(
248        &self,
249        linked_chunk_id: LinkedChunkId<'_>,
250        updates: Vec<Update<Event, Gap>>,
251    ) -> Result<(), Self::Error> {
252        self.0.handle_linked_chunk_updates(linked_chunk_id, updates).await.map_err(Into::into)
253    }
254
255    async fn load_all_chunks(
256        &self,
257        linked_chunk_id: LinkedChunkId<'_>,
258    ) -> Result<Vec<RawChunk<Event, Gap>>, Self::Error> {
259        self.0.load_all_chunks(linked_chunk_id).await.map_err(Into::into)
260    }
261
262    async fn load_all_chunks_metadata(
263        &self,
264        linked_chunk_id: LinkedChunkId<'_>,
265    ) -> Result<Vec<ChunkMetadata>, Self::Error> {
266        self.0.load_all_chunks_metadata(linked_chunk_id).await.map_err(Into::into)
267    }
268
269    async fn load_last_chunk(
270        &self,
271        linked_chunk_id: LinkedChunkId<'_>,
272    ) -> Result<(Option<RawChunk<Event, Gap>>, ChunkIdentifierGenerator), Self::Error> {
273        self.0.load_last_chunk(linked_chunk_id).await.map_err(Into::into)
274    }
275
276    async fn load_previous_chunk(
277        &self,
278        linked_chunk_id: LinkedChunkId<'_>,
279        before_chunk_identifier: ChunkIdentifier,
280    ) -> Result<Option<RawChunk<Event, Gap>>, Self::Error> {
281        self.0
282            .load_previous_chunk(linked_chunk_id, before_chunk_identifier)
283            .await
284            .map_err(Into::into)
285    }
286
287    async fn load_thread_info(
288        &self,
289        room_id: &RoomId,
290        thread_id: &EventId,
291    ) -> Result<ThreadInfo, Self::Error> {
292        self.0.load_thread_info(room_id, thread_id).await.map_err(Into::into)
293    }
294
295    async fn update_thread_info(
296        &self,
297        room_id: &RoomId,
298        thread_id: &EventId,
299        thread_info: &ThreadInfo,
300    ) -> Result<(), Self::Error> {
301        self.0.update_thread_info(room_id, thread_id, thread_info).await.map_err(Into::into)
302    }
303
304    async fn clear_all_events(&self, room_id: Option<&RoomId>) -> Result<(), Self::Error> {
305        self.0.clear_all_events(room_id).await.map_err(Into::into)
306    }
307
308    async fn filter_duplicated_events(
309        &self,
310        linked_chunk_id: LinkedChunkId<'_>,
311        events: Vec<OwnedEventId>,
312    ) -> Result<Vec<(OwnedEventId, Position)>, Self::Error> {
313        self.0.filter_duplicated_events(linked_chunk_id, events).await.map_err(Into::into)
314    }
315
316    async fn find_event(
317        &self,
318        room_id: &RoomId,
319        event_id: &EventId,
320    ) -> Result<Option<Event>, Self::Error> {
321        self.0.find_event(room_id, event_id).await.map_err(Into::into)
322    }
323
324    async fn find_event_relations(
325        &self,
326        room_id: &RoomId,
327        event_id: &EventId,
328        filter: Option<&[RelationType]>,
329    ) -> Result<Vec<(Event, Option<Position>)>, Self::Error> {
330        self.0.find_event_relations(room_id, event_id, filter).await.map_err(Into::into)
331    }
332
333    async fn get_room_events(
334        &self,
335        room_id: &RoomId,
336        event_type: Option<&str>,
337        session_id: Option<&str>,
338    ) -> Result<Vec<Event>, Self::Error> {
339        self.0.get_room_events(room_id, event_type, session_id).await.map_err(Into::into)
340    }
341
342    async fn save_event(&self, room_id: &RoomId, event: Event) -> Result<(), Self::Error> {
343        self.0.save_event(room_id, event).await.map_err(Into::into)
344    }
345
346    async fn close(&self) -> Result<(), Self::Error> {
347        self.0.close().await.map_err(Into::into)
348    }
349
350    async fn reopen(&self) -> Result<(), Self::Error> {
351        self.0.reopen().await.map_err(Into::into)
352    }
353
354    async fn optimize(&self) -> Result<(), Self::Error> {
355        self.0.optimize().await.map_err(Into::into)?;
356        Ok(())
357    }
358
359    async fn get_size(&self) -> Result<Option<usize>, Self::Error> {
360        Ok(self.0.get_size().await.map_err(Into::into)?)
361    }
362}
363
364/// A type-erased [`EventCacheStore`].
365pub type DynEventCacheStore = dyn EventCacheStore<Error = EventCacheStoreError>;
366
367/// A type that can be type-erased into `Arc<dyn EventCacheStore>`.
368///
369/// This trait is not meant to be implemented directly outside
370/// `matrix-sdk-base`, but it is automatically implemented for everything that
371/// implements `EventCacheStore`.
372pub trait IntoEventCacheStore {
373    #[doc(hidden)]
374    fn into_event_cache_store(self) -> Arc<DynEventCacheStore>;
375}
376
377impl IntoEventCacheStore for Arc<DynEventCacheStore> {
378    fn into_event_cache_store(self) -> Arc<DynEventCacheStore> {
379        self
380    }
381}
382
383impl<T> IntoEventCacheStore for T
384where
385    T: EventCacheStore + Sized + 'static,
386{
387    fn into_event_cache_store(self) -> Arc<DynEventCacheStore> {
388        Arc::new(EraseEventCacheStoreError(self))
389    }
390}
391
392// Turns a given `Arc<T>` into `Arc<DynEventCacheStore>` by attaching the
393// `EventCacheStore` impl vtable of `EraseEventCacheStoreError<T>`.
394impl<T> IntoEventCacheStore for Arc<T>
395where
396    T: EventCacheStore + 'static,
397{
398    fn into_event_cache_store(self) -> Arc<DynEventCacheStore> {
399        let ptr: *const T = Arc::into_raw(self);
400        let ptr_erased = ptr as *const EraseEventCacheStoreError<T>;
401        // SAFETY: EraseEventCacheStoreError is repr(transparent) so T and
402        //         EraseEventCacheStoreError<T> have the same layout and ABI
403        unsafe { Arc::from_raw(ptr_erased) }
404    }
405}