matrix_sdk_store_file_event_cache/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use async_trait::async_trait;
use base64ct::{Base64UrlUnpadded, Encoding};
use core::fmt::Debug;
use matrix_sdk_base::{
    event_cache::{
        store::{EventCacheStore, EventCacheStoreError, DEFAULT_CHUNK_CAPACITY},
        Event, Gap,
    },
    linked_chunk::{LinkedChunk, Update},
    media::{MediaRequestParameters, UniqueKey},
    ruma::{MxcUri, RoomId},
    StateStore,
};
use matrix_sdk_store_encryption::StoreCipher;
use serde::{Deserialize, Serialize};
use std::{fs, path::PathBuf, time::Duration};
use tracing::instrument;

#[cfg(feature = "queued")]
mod queued;

#[cfg(feature = "queued")]
pub use queued::QueuedEventCacheStore;

pub struct FileEventCacheStore<T> {
    cache_dir: PathBuf,
    store_cipher: StoreCipher,
    inner: T,
}

impl<T> Debug for FileEventCacheStore<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FileEventCacheStore")
            .field("cache_dir", &self.cache_dir)
            .finish()
    }
}

impl<T> FileEventCacheStore<T> {
    pub fn with_store_cipher(
        cache_dir: PathBuf,
        store_cipher: StoreCipher,
        inner: T,
    ) -> FileEventCacheStore<T> {
        FileEventCacheStore {
            cache_dir,
            store_cipher,
            inner,
        }
    }

    fn encode_value(&self, value: Vec<u8>) -> Result<Vec<u8>, EventCacheStoreError> {
        let encoded = self
            .store_cipher
            .encrypt_value_data(value)
            .map_err(EventCacheStoreError::backend)?;
        rmp_serde::to_vec_named(&encoded).map_err(EventCacheStoreError::backend)
    }

    fn decode_value(&self, value: &[u8]) -> Result<Vec<u8>, EventCacheStoreError> {
        let encrypted = rmp_serde::from_slice(value).map_err(EventCacheStoreError::backend)?;
        self.store_cipher
            .decrypt_value_data(encrypted)
            .map_err(EventCacheStoreError::backend)
    }

    fn encode_key(&self, key: impl AsRef<[u8]>) -> String {
        Base64UrlUnpadded::encode_string(&self.store_cipher.hash_key("ext_media", key.as_ref()))
    }
}

#[derive(Serialize, Deserialize)]
struct LeaveLockInfo {
    holder: String,
    expiration: Duration,
}

#[async_trait]
impl<T> EventCacheStore for FileEventCacheStore<T>
where
    T: EventCacheStore,
{
    type Error = EventCacheStoreError;

    async fn try_take_leased_lock(
        &self,
        lease_duration_ms: u32,
        key: &str,
        holder: &str,
    ) -> Result<bool, Self::Error> {
        self.inner
            .try_take_leased_lock(lease_duration_ms, key, holder)
            .await
            .map_err(|e| e.into())
    }

    async fn handle_linked_chunk_updates(
        &self,
        room_id: &RoomId,
        updates: Vec<Update<Event, Gap>>,
    ) -> Result<(), Self::Error> {
        self.inner
            .handle_linked_chunk_updates(room_id, updates)
            .await
            .map_err(|e| e.into())
    }

    async fn reload_linked_chunk(
        &self,
        room_id: &RoomId,
    ) -> Result<Option<LinkedChunk<DEFAULT_CHUNK_CAPACITY, Event, Gap>>, Self::Error> {
        self.inner
            .reload_linked_chunk(room_id)
            .await
            .map_err(|e| e.into())
    }

    #[instrument(skip_all)]
    async fn add_media_content(
        &self,
        request: &MediaRequestParameters,
        content: Vec<u8>,
    ) -> Result<(), Self::Error> {
        let base_filename = self.encode_key(request.source.unique_key());
        let data = self
            .encode_value(content)
            .map_err(|e| EventCacheStoreError::Backend(Box::new(e)))?;
        fs::write(self.cache_dir.join(base_filename), data)
            .map_err(|e| EventCacheStoreError::Backend(Box::new(e)))?;
        Ok(())
    }

    #[instrument(skip_all)]
    async fn get_media_content(
        &self,
        request: &MediaRequestParameters,
    ) -> Result<Option<Vec<u8>>, Self::Error> {
        let base_filename = self.encode_key(request.source.unique_key());
        fs::read(self.cache_dir.join(base_filename))
            .ok()
            .map(|data| self.decode_value(&data))
            .transpose()
    }

    async fn get_media_content_for_uri(
        &self,
        uri: &MxcUri,
    ) -> Result<Option<Vec<u8>>, Self::Error> {
        let base_filename = self.encode_key(uri);
        fs::read(self.cache_dir.join(base_filename))
            .ok()
            .map(|data| self.decode_value(&data))
            .transpose()
    }

    #[instrument(skip_all)]
    async fn remove_media_content(
        &self,
        request: &MediaRequestParameters,
    ) -> Result<(), Self::Error> {
        let base_filename = self.encode_key(request.source.unique_key());
        fs::remove_file(self.cache_dir.join(base_filename))
            .map_err(|e| EventCacheStoreError::Backend(Box::new(e)))?;
        Ok(())
    }

    #[instrument(skip_all)]
    async fn remove_media_content_for_uri(&self, uri: &MxcUri) -> Result<(), Self::Error> {
        let base_filename = self.encode_key(uri);
        fs::remove_file(self.cache_dir.join(base_filename))
            .map_err(|e| EventCacheStoreError::Backend(Box::new(e)))?;
        Ok(())
    }

    #[instrument(skip_all)]
    async fn replace_media_key(
        &self,
        from: &MediaRequestParameters,
        to: &MediaRequestParameters,
    ) -> Result<(), Self::Error> {
        let from_filename = self.encode_key(from.source.unique_key());
        let to_filename = self.encode_key(to.source.unique_key());
        fs::rename(from_filename, to_filename)
            .map_err(|e| EventCacheStoreError::Backend(Box::new(e)))?;
        Ok(())
    }
}

#[cfg(feature = "queued")]
pub async fn wrap_with_file_cache_and_limits<T, S>(
    state_store: &S,
    event_cache_store: T,
    cache_path: PathBuf,
    passphrase: &str,
    queue_size: usize,
) -> Result<QueuedEventCacheStore<FileEventCacheStore<T>>, EventCacheStoreError>
where
    S: StateStore + Sync + Send,
    T: EventCacheStore + Sync + Send,
{
    let cached =
        wrap_with_file_cache_inner(state_store, event_cache_store, cache_path, passphrase).await?;
    Ok(QueuedEventCacheStore::new(cached, queue_size))
}

pub async fn wrap_with_file_cache<T, S>(
    state_store: &S,
    event_cache_store: T,
    cache_path: PathBuf,
    passphrase: &str,
) -> Result<FileEventCacheStore<T>, EventCacheStoreError>
where
    S: StateStore + Sync + Send,
    T: EventCacheStore + Sync + Send,
{
    wrap_with_file_cache_inner(state_store, event_cache_store, cache_path, passphrase).await
}

async fn wrap_with_file_cache_inner<T, S>(
    state_store: &S,
    event_cache_store: T,
    cache_path: PathBuf,
    passphrase: &str,
) -> Result<FileEventCacheStore<T>, EventCacheStoreError>
where
    S: StateStore + Sync + Send,
    T: EventCacheStore + Sync + Send,
{
    let cipher = if let Some(enc_key) = state_store
        .get_custom_value(b"ext_media_key")
        .await
        .map_err(|e| EventCacheStoreError::backend(e.into()))?
    {
        StoreCipher::import(passphrase, &enc_key)?
    } else {
        let cipher = StoreCipher::new()?;
        let key = cipher.export(passphrase)?;
        state_store
            .set_custom_value_no_read(b"ext_media_key", key)
            .await
            .map_err(|e| EventCacheStoreError::backend(e.into()))?;
        cipher
    };

    fs::create_dir_all(cache_path.as_path())
        .map_err(|e| EventCacheStoreError::Backend(Box::new(e)))?;

    Ok(FileEventCacheStore::with_store_cipher(
        cache_path,
        cipher,
        event_cache_store,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Result;
    use matrix_sdk_base::{
        media::MediaFormat,
        ruma::{events::room::MediaSource, OwnedMxcUri},
    };
    use matrix_sdk_sqlite::{SqliteEventCacheStore, SqliteStateStore};
    use matrix_sdk_test::async_test;
    use uuid::Uuid;

    fn fake_mr(id: &str) -> MediaRequestParameters {
        MediaRequestParameters {
            source: MediaSource::Plain(OwnedMxcUri::from(id)),
            format: MediaFormat::File,
        }
    }

    #[async_test]
    async fn test_it_works() -> Result<()> {
        let cache_dir = tempfile::tempdir()?;
        let cipher = StoreCipher::new()?;
        let cache = SqliteEventCacheStore::open(cache_dir.path(), None).await?;
        let fmc = FileEventCacheStore::with_store_cipher(cache_dir.into_path(), cipher, cache);
        let some_content = "this is some content";
        fmc.add_media_content(&fake_mr("my_id"), some_content.into())
            .await?;
        assert_eq!(
            fmc.get_media_content(&fake_mr("my_id")).await?,
            Some(some_content.into())
        );

        Ok(())
    }

    #[async_test]
    async fn test_it_works_after_restart() -> Result<()> {
        let cache_dir = tempfile::tempdir()?;
        let passphrase = "this is a secret passphrase";
        let some_content = "this is some content";
        let my_item_id = "my_id";
        let enc_key = {
            // first media cache
            let cipher = StoreCipher::new()?;
            let export = cipher.export(passphrase)?;
            let cache = SqliteEventCacheStore::open(cache_dir.path(), Some(passphrase)).await?;
            let fmc = FileEventCacheStore::with_store_cipher(
                cache_dir.path().to_path_buf(),
                cipher,
                cache,
            );
            fmc.add_media_content(&fake_mr(my_item_id), some_content.into())
                .await?;
            assert_eq!(
                fmc.get_media_content(&fake_mr(my_item_id)).await?,
                Some(some_content.into())
            );
            export
        };

        // second media cache
        let cipher = StoreCipher::import(passphrase, &enc_key)?;
        let cache = SqliteEventCacheStore::open(cache_dir.path(), Some(passphrase)).await?;
        let fmc =
            FileEventCacheStore::with_store_cipher(cache_dir.path().to_path_buf(), cipher, cache);
        assert_eq!(
            fmc.get_media_content(&fake_mr(my_item_id)).await?,
            Some(some_content.into())
        );

        Ok(())
    }

    #[async_test]
    async fn test_with_sqlite_store() -> Result<()> {
        let db_path = tempfile::tempdir()?;
        let cache_dir = tempfile::tempdir()?;
        let passphrase = Uuid::new_v4().to_string();
        let some_content = "this is some content";
        let my_item_id = "my_id";
        {
            // as a block means we are closing things up
            let db = SqliteStateStore::open(db_path.path(), Some(&passphrase)).await?;
            let cache = SqliteEventCacheStore::open(cache_dir.path(), Some(&passphrase)).await?;
            let outer =
                wrap_with_file_cache(&db, cache, cache_dir.path().to_path_buf(), &passphrase)
                    .await?;
            // first media cache
            outer
                .add_media_content(&fake_mr(my_item_id), some_content.into())
                .await?;
            assert_eq!(
                outer.get_media_content(&fake_mr(my_item_id)).await?,
                Some(some_content.into())
            );
        };

        // second media cache
        let db = SqliteStateStore::open(db_path, Some(&passphrase)).await?;

        let cache = SqliteEventCacheStore::open(cache_dir.path(), Some(&passphrase)).await?;
        let outer =
            wrap_with_file_cache(&db, cache, cache_dir.path().to_path_buf(), &passphrase).await?;
        // first media cache
        outer
            .add_media_content(&fake_mr(my_item_id), some_content.into())
            .await?;
        assert_eq!(
            outer.get_media_content(&fake_mr(my_item_id)).await?,
            Some(some_content.into())
        );

        Ok(())
    }
}