matrix_sdk_base/media/store/
mod.rs

1// Copyright 2025 Kévin Commaille
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 media store holds downloaded media when the cache was
16//! activated to save bandwidth at the cost of increased storage space usage.
17//!
18//! Implementing the `MediaStore` trait, you can plug any storage backend
19//! into the media store for the actual storage. By default this brings an
20//! in-memory store.
21
22mod media_retention_policy;
23mod media_service;
24mod memory_store;
25mod traits;
26#[cfg(any(test, feature = "testing"))]
27#[macro_use]
28pub mod integration_tests;
29
30#[cfg(not(tarpaulin_include))]
31use std::fmt;
32use std::{ops::Deref, sync::Arc};
33
34use matrix_sdk_common::cross_process_lock::{
35    CrossProcessLock, CrossProcessLockError, CrossProcessLockGeneration, CrossProcessLockGuard,
36    CrossProcessLockKind, TryLock,
37};
38use matrix_sdk_store_encryption::Error as StoreEncryptionError;
39pub use traits::{DynMediaStore, IntoMediaStore, MediaStore, MediaStoreInner};
40
41#[cfg(any(test, feature = "testing"))]
42pub use self::integration_tests::{MediaStoreInnerIntegrationTests, MediaStoreIntegrationTests};
43pub use self::{
44    media_retention_policy::MediaRetentionPolicy,
45    media_service::{IgnoreMediaRetentionPolicy, MediaService},
46    memory_store::MemoryMediaStore,
47};
48
49/// Media store specific error type.
50#[derive(Debug, thiserror::Error)]
51pub enum MediaStoreError {
52    /// An error happened in the underlying database backend.
53    #[error(transparent)]
54    Backend(Box<dyn std::error::Error + Send + Sync>),
55
56    /// The store failed to encrypt or decrypt some data.
57    #[error("Error encrypting or decrypting data from the media store: {0}")]
58    Encryption(#[from] StoreEncryptionError),
59
60    /// The store contains invalid data.
61    #[error("The store contains invalid data: {details}")]
62    InvalidData {
63        /// Details why the data contained in the store was invalid.
64        details: String,
65    },
66
67    /// The store failed to serialize or deserialize some data.
68    #[error("Error serializing or deserializing data from the media store: {0}")]
69    Serialization(#[from] serde_json::Error),
70}
71
72impl MediaStoreError {
73    /// Create a new [`Backend`][Self::Backend] error.
74    ///
75    /// Shorthand for `MediaStoreError::Backend(Box::new(error))`.
76    #[inline]
77    pub fn backend<E>(error: E) -> Self
78    where
79        E: std::error::Error + Send + Sync + 'static,
80    {
81        Self::Backend(Box::new(error))
82    }
83}
84
85impl From<MediaStoreError> for CrossProcessLockError {
86    fn from(value: MediaStoreError) -> Self {
87        Self::TryLock(Box::new(value))
88    }
89}
90
91/// An `MediaStore` specific result type.
92pub type Result<T, E = MediaStoreError> = std::result::Result<T, E>;
93
94/// The high-level public type to represent an `MediaStore` lock.
95#[derive(Clone)]
96pub struct MediaStoreLock {
97    /// The inner cross process lock that is used to lock the `MediaStore`.
98    cross_process_lock: Arc<CrossProcessLock<LockableMediaStore>>,
99
100    /// The store itself.
101    ///
102    /// That's the only place where the store exists.
103    store: Arc<DynMediaStore>,
104}
105
106#[cfg(not(tarpaulin_include))]
107impl fmt::Debug for MediaStoreLock {
108    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
109        formatter.debug_struct("MediaStoreLock").finish_non_exhaustive()
110    }
111}
112
113impl MediaStoreLock {
114    /// Create a new lock around the [`MediaStore`].
115    ///
116    /// The `holder` argument represents the holder inside the
117    /// [`CrossProcessLock::new`].
118    pub fn new<S>(store: S, holder: String) -> Self
119    where
120        S: IntoMediaStore,
121    {
122        let store = store.into_media_store();
123
124        Self {
125            cross_process_lock: Arc::new(CrossProcessLock::new(
126                LockableMediaStore(store.clone()),
127                "default".to_owned(),
128                holder,
129            )),
130            store,
131        }
132    }
133
134    /// Acquire a spin lock (see [`CrossProcessLock::spin_lock`]).
135    pub async fn lock(&self) -> Result<MediaStoreLockGuard<'_>, CrossProcessLockError> {
136        let cross_process_lock_guard = match self.cross_process_lock.spin_lock(None).await?? {
137            // The lock is clean: no other hold acquired it, all good!
138            CrossProcessLockKind::Clean(guard) => guard,
139
140            // The lock is dirty: another holder acquired it since the last time we acquired it.
141            // It's not a problem in the case of the `MediaStore` because this API is “stateless” at
142            // the time of writing (2025-11-11). There is nothing that can be out-of-sync: all the
143            // state is in the database, nothing in memory.
144            CrossProcessLockKind::Dirty(guard) => {
145                self.cross_process_lock.clear_dirty();
146
147                guard
148            }
149        };
150
151        Ok(MediaStoreLockGuard { cross_process_lock_guard, store: self.store.deref() })
152    }
153}
154
155/// An RAII implementation of a “scoped lock” of an [`MediaStoreLock`].
156/// When this structure is dropped (falls out of scope), the lock will be
157/// unlocked.
158pub struct MediaStoreLockGuard<'a> {
159    /// The cross process lock guard.
160    #[allow(unused)]
161    cross_process_lock_guard: CrossProcessLockGuard,
162
163    /// A reference to the store.
164    store: &'a DynMediaStore,
165}
166
167#[cfg(not(tarpaulin_include))]
168impl fmt::Debug for MediaStoreLockGuard<'_> {
169    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
170        formatter.debug_struct("MediaStoreLockGuard").finish_non_exhaustive()
171    }
172}
173
174impl Deref for MediaStoreLockGuard<'_> {
175    type Target = DynMediaStore;
176
177    fn deref(&self) -> &Self::Target {
178        self.store
179    }
180}
181
182/// A type that wraps the [`MediaStore`] but implements [`TryLock`] to
183/// make it usable inside the cross process lock.
184#[derive(Clone, Debug)]
185struct LockableMediaStore(Arc<DynMediaStore>);
186
187impl TryLock for LockableMediaStore {
188    type LockError = MediaStoreError;
189
190    async fn try_lock(
191        &self,
192        lease_duration_ms: u32,
193        key: &str,
194        holder: &str,
195    ) -> std::result::Result<Option<CrossProcessLockGeneration>, Self::LockError> {
196        self.0.try_take_leased_lock(lease_duration_ms, key, holder).await
197    }
198}