matrix_sdk_sqlite/
media_store.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//! An SQLite-based backend for the [`MediaStore`].
16
17use std::{fmt, path::Path, sync::Arc};
18
19use async_trait::async_trait;
20use matrix_sdk_base::{
21    cross_process_lock::CrossProcessLockGeneration,
22    media::{
23        store::{
24            IgnoreMediaRetentionPolicy, MediaRetentionPolicy, MediaService, MediaStore,
25            MediaStoreInner,
26        },
27        MediaRequestParameters, UniqueKey,
28    },
29    timer,
30};
31use matrix_sdk_store_encryption::StoreCipher;
32use ruma::{time::SystemTime, MilliSecondsSinceUnixEpoch, MxcUri};
33use rusqlite::{params_from_iter, OptionalExtension};
34use tokio::{
35    fs,
36    sync::{Mutex, OwnedMutexGuard},
37};
38use tracing::{debug, instrument, trace};
39
40use crate::{
41    connection::{Connection as SqliteAsyncConn, Pool as SqlitePool},
42    error::{Error, Result},
43    utils::{
44        repeat_vars, time_to_timestamp, EncryptableStore, SqliteAsyncConnExt,
45        SqliteKeyValueStoreAsyncConnExt, SqliteKeyValueStoreConnExt, SqliteTransactionExt,
46    },
47    OpenStoreError, Secret, SqliteStoreConfig,
48};
49
50mod keys {
51    // Entries in Key-value store
52    pub const MEDIA_RETENTION_POLICY: &str = "media_retention_policy";
53    pub const LAST_MEDIA_CLEANUP_TIME: &str = "last_media_cleanup_time";
54
55    // Tables
56    pub const MEDIA: &str = "media";
57}
58
59/// The database name.
60const DATABASE_NAME: &str = "matrix-sdk-media.sqlite3";
61
62/// Identifier of the latest database version.
63///
64/// This is used to figure whether the SQLite database requires a migration.
65/// Every new SQL migration should imply a bump of this number, and changes in
66/// the [`run_migrations`] function.
67const DATABASE_VERSION: u8 = 2;
68
69/// An SQLite-based media store.
70#[derive(Clone)]
71pub struct SqliteMediaStore {
72    store_cipher: Option<Arc<StoreCipher>>,
73
74    /// The pool of connections.
75    pool: SqlitePool,
76
77    /// We make the difference between connections for read operations, and for
78    /// write operations. We keep a single connection apart from write
79    /// operations. All other connections are used for read operations. The
80    /// lock is used to ensure there is one owner at a time.
81    write_connection: Arc<Mutex<SqliteAsyncConn>>,
82
83    media_service: MediaService,
84}
85
86#[cfg(not(tarpaulin_include))]
87impl fmt::Debug for SqliteMediaStore {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.debug_struct("SqliteMediaStore").finish_non_exhaustive()
90    }
91}
92
93impl EncryptableStore for SqliteMediaStore {
94    fn get_cypher(&self) -> Option<&StoreCipher> {
95        self.store_cipher.as_deref()
96    }
97}
98
99impl SqliteMediaStore {
100    /// Open the SQLite-based media store at the given path using the
101    /// given passphrase to encrypt private data.
102    pub async fn open(
103        path: impl AsRef<Path>,
104        passphrase: Option<&str>,
105    ) -> Result<Self, OpenStoreError> {
106        Self::open_with_config(SqliteStoreConfig::new(path).passphrase(passphrase)).await
107    }
108
109    /// Open the SQLite-based media store at the given path using the given
110    /// key to encrypt private data.
111    pub async fn open_with_key(
112        path: impl AsRef<Path>,
113        key: Option<&[u8; 32]>,
114    ) -> Result<Self, OpenStoreError> {
115        Self::open_with_config(SqliteStoreConfig::new(path).key(key)).await
116    }
117
118    /// Open the SQLite-based media store with the config open config.
119    #[instrument(skip(config), fields(path = ?config.path))]
120    pub async fn open_with_config(config: SqliteStoreConfig) -> Result<Self, OpenStoreError> {
121        debug!(?config);
122
123        let _timer = timer!("open_with_config");
124
125        fs::create_dir_all(&config.path).await.map_err(OpenStoreError::CreateDir)?;
126
127        let pool = config.build_pool_of_connections(DATABASE_NAME)?;
128
129        let this = Self::open_with_pool(pool, config.secret).await?;
130        this.write().await?.apply_runtime_config(config.runtime_config).await?;
131
132        Ok(this)
133    }
134
135    /// Open an SQLite-based media store using the given SQLite database
136    /// pool. The given passphrase will be used to encrypt private data.
137    async fn open_with_pool(
138        pool: SqlitePool,
139        secret: Option<Secret>,
140    ) -> Result<Self, OpenStoreError> {
141        let conn = pool.get().await?;
142
143        let version = conn.db_version().await?;
144        run_migrations(&conn, version).await?;
145
146        let store_cipher = match secret {
147            Some(s) => Some(Arc::new(conn.get_or_create_store_cipher(s).await?)),
148            None => None,
149        };
150
151        let media_service = MediaService::new();
152        let media_retention_policy = conn.get_serialized_kv(keys::MEDIA_RETENTION_POLICY).await?;
153        let last_media_cleanup_time = conn.get_serialized_kv(keys::LAST_MEDIA_CLEANUP_TIME).await?;
154        media_service.restore(media_retention_policy, last_media_cleanup_time);
155
156        Ok(Self {
157            store_cipher,
158            pool,
159            // Use `conn` as our selected write connections.
160            write_connection: Arc::new(Mutex::new(conn)),
161            media_service,
162        })
163    }
164
165    // Acquire a connection for executing read operations.
166    #[instrument(skip_all)]
167    async fn read(&self) -> Result<SqliteAsyncConn> {
168        trace!("Taking a `read` connection");
169        let _timer = timer!("connection");
170
171        let connection = self.pool.get().await?;
172
173        // Per https://www.sqlite.org/foreignkeys.html#fk_enable, foreign key
174        // support must be enabled on a per-connection basis. Execute it every
175        // time we try to get a connection, since we can't guarantee a previous
176        // connection did enable it before.
177        connection.execute_batch("PRAGMA foreign_keys = ON;").await?;
178
179        Ok(connection)
180    }
181
182    // Acquire a connection for executing write operations.
183    #[instrument(skip_all)]
184    async fn write(&self) -> Result<OwnedMutexGuard<SqliteAsyncConn>> {
185        trace!("Taking a `write` connection");
186        let _timer = timer!("connection");
187
188        let connection = self.write_connection.clone().lock_owned().await;
189
190        // Per https://www.sqlite.org/foreignkeys.html#fk_enable, foreign key
191        // support must be enabled on a per-connection basis. Execute it every
192        // time we try to get a connection, since we can't guarantee a previous
193        // connection did enable it before.
194        connection.execute_batch("PRAGMA foreign_keys = ON;").await?;
195
196        Ok(connection)
197    }
198}
199
200/// Run migrations for the given version of the database.
201async fn run_migrations(conn: &SqliteAsyncConn, version: u8) -> Result<()> {
202    if version == 0 {
203        debug!("Creating database");
204    } else if version < DATABASE_VERSION {
205        debug!(version, new_version = DATABASE_VERSION, "Upgrading database");
206    } else {
207        return Ok(());
208    }
209
210    // Always enable foreign keys for the current connection.
211    conn.execute_batch("PRAGMA foreign_keys = ON;").await?;
212
213    if version < 1 {
214        // First turn on WAL mode, this can't be done in the transaction, it fails with
215        // the error message: "cannot change into wal mode from within a transaction".
216        conn.execute_batch("PRAGMA journal_mode = wal;").await?;
217        conn.with_transaction(|txn| {
218            txn.execute_batch(include_str!("../migrations/media_store/001_init.sql"))?;
219            txn.set_db_version(1)
220        })
221        .await?;
222    }
223
224    if version < 2 {
225        conn.with_transaction(|txn| {
226            txn.execute_batch(include_str!(
227                "../migrations/media_store/002_lease_locks_with_generation.sql"
228            ))?;
229            txn.set_db_version(2)
230        })
231        .await?;
232    }
233
234    Ok(())
235}
236
237#[async_trait]
238impl MediaStore for SqliteMediaStore {
239    type Error = Error;
240
241    #[instrument(skip(self))]
242    async fn try_take_leased_lock(
243        &self,
244        lease_duration_ms: u32,
245        key: &str,
246        holder: &str,
247    ) -> Result<Option<CrossProcessLockGeneration>> {
248        let _timer = timer!("method");
249
250        let key = key.to_owned();
251        let holder = holder.to_owned();
252
253        let now: u64 = MilliSecondsSinceUnixEpoch::now().get().into();
254        let expiration = now + lease_duration_ms as u64;
255
256        // Learn about the `excluded` keyword in https://sqlite.org/lang_upsert.html.
257        let generation = self
258            .write()
259            .await?
260            .with_transaction(move |txn| {
261                txn.query_row(
262                    "INSERT INTO lease_locks (key, holder, expiration)
263                    VALUES (?1, ?2, ?3)
264                    ON CONFLICT (key)
265                    DO
266                        UPDATE SET
267                            holder = excluded.holder,
268                            expiration = excluded.expiration,
269                            generation =
270                                CASE holder
271                                    WHEN excluded.holder THEN generation
272                                    ELSE generation + 1
273                                END
274                        WHERE
275                            holder = excluded.holder
276                            OR expiration < ?4
277                    RETURNING generation
278                    ",
279                    (key, holder, expiration, now),
280                    |row| row.get(0),
281                )
282                .optional()
283            })
284            .await?;
285
286        Ok(generation)
287    }
288
289    async fn add_media_content(
290        &self,
291        request: &MediaRequestParameters,
292        content: Vec<u8>,
293        ignore_policy: IgnoreMediaRetentionPolicy,
294    ) -> Result<()> {
295        let _timer = timer!("method");
296
297        self.media_service.add_media_content(self, request, content, ignore_policy).await
298    }
299
300    #[instrument(skip_all)]
301    async fn replace_media_key(
302        &self,
303        from: &MediaRequestParameters,
304        to: &MediaRequestParameters,
305    ) -> Result<(), Self::Error> {
306        let _timer = timer!("method");
307
308        let prev_uri = self.encode_key(keys::MEDIA, from.source.unique_key());
309        let prev_format = self.encode_key(keys::MEDIA, from.format.unique_key());
310
311        let new_uri = self.encode_key(keys::MEDIA, to.source.unique_key());
312        let new_format = self.encode_key(keys::MEDIA, to.format.unique_key());
313
314        let conn = self.write().await?;
315        conn.execute(
316            r#"UPDATE media SET uri = ?, format = ? WHERE uri = ? AND format = ?"#,
317            (new_uri, new_format, prev_uri, prev_format),
318        )
319        .await?;
320
321        Ok(())
322    }
323
324    #[instrument(skip_all)]
325    async fn get_media_content(&self, request: &MediaRequestParameters) -> Result<Option<Vec<u8>>> {
326        let _timer = timer!("method");
327
328        self.media_service.get_media_content(self, request).await
329    }
330
331    #[instrument(skip_all)]
332    async fn remove_media_content(&self, request: &MediaRequestParameters) -> Result<()> {
333        let _timer = timer!("method");
334
335        let uri = self.encode_key(keys::MEDIA, request.source.unique_key());
336        let format = self.encode_key(keys::MEDIA, request.format.unique_key());
337
338        let conn = self.write().await?;
339        conn.execute("DELETE FROM media WHERE uri = ? AND format = ?", (uri, format)).await?;
340
341        Ok(())
342    }
343
344    #[instrument(skip(self))]
345    async fn get_media_content_for_uri(
346        &self,
347        uri: &MxcUri,
348    ) -> Result<Option<Vec<u8>>, Self::Error> {
349        let _timer = timer!("method");
350
351        self.media_service.get_media_content_for_uri(self, uri).await
352    }
353
354    #[instrument(skip(self))]
355    async fn remove_media_content_for_uri(&self, uri: &MxcUri) -> Result<()> {
356        let _timer = timer!("method");
357
358        let uri = self.encode_key(keys::MEDIA, uri);
359
360        let conn = self.write().await?;
361        conn.execute("DELETE FROM media WHERE uri = ?", (uri,)).await?;
362
363        Ok(())
364    }
365
366    #[instrument(skip_all)]
367    async fn set_media_retention_policy(
368        &self,
369        policy: MediaRetentionPolicy,
370    ) -> Result<(), Self::Error> {
371        let _timer = timer!("method");
372
373        self.media_service.set_media_retention_policy(self, policy).await
374    }
375
376    #[instrument(skip_all)]
377    fn media_retention_policy(&self) -> MediaRetentionPolicy {
378        let _timer = timer!("method");
379
380        self.media_service.media_retention_policy()
381    }
382
383    #[instrument(skip_all)]
384    async fn set_ignore_media_retention_policy(
385        &self,
386        request: &MediaRequestParameters,
387        ignore_policy: IgnoreMediaRetentionPolicy,
388    ) -> Result<(), Self::Error> {
389        let _timer = timer!("method");
390
391        self.media_service.set_ignore_media_retention_policy(self, request, ignore_policy).await
392    }
393
394    #[instrument(skip_all)]
395    async fn clean(&self) -> Result<(), Self::Error> {
396        let _timer = timer!("method");
397
398        self.media_service.clean(self).await
399    }
400}
401
402#[cfg_attr(target_family = "wasm", async_trait(?Send))]
403#[cfg_attr(not(target_family = "wasm"), async_trait)]
404impl MediaStoreInner for SqliteMediaStore {
405    type Error = Error;
406
407    async fn media_retention_policy_inner(
408        &self,
409    ) -> Result<Option<MediaRetentionPolicy>, Self::Error> {
410        let conn = self.read().await?;
411        conn.get_serialized_kv(keys::MEDIA_RETENTION_POLICY).await
412    }
413
414    async fn set_media_retention_policy_inner(
415        &self,
416        policy: MediaRetentionPolicy,
417    ) -> Result<(), Self::Error> {
418        let conn = self.write().await?;
419        conn.set_serialized_kv(keys::MEDIA_RETENTION_POLICY, policy).await?;
420        Ok(())
421    }
422
423    async fn add_media_content_inner(
424        &self,
425        request: &MediaRequestParameters,
426        data: Vec<u8>,
427        last_access: SystemTime,
428        policy: MediaRetentionPolicy,
429        ignore_policy: IgnoreMediaRetentionPolicy,
430    ) -> Result<(), Self::Error> {
431        let ignore_policy = ignore_policy.is_yes();
432        let data = self.encode_value(data)?;
433
434        if !ignore_policy && policy.exceeds_max_file_size(data.len() as u64) {
435            return Ok(());
436        }
437
438        let uri = self.encode_key(keys::MEDIA, request.source.unique_key());
439        let format = self.encode_key(keys::MEDIA, request.format.unique_key());
440        let timestamp = time_to_timestamp(last_access);
441
442        let conn = self.write().await?;
443        conn.execute(
444            "INSERT OR REPLACE INTO media (uri, format, data, last_access, ignore_policy) VALUES (?, ?, ?, ?, ?)",
445            (uri, format, data, timestamp, ignore_policy),
446        )
447        .await?;
448
449        Ok(())
450    }
451
452    async fn set_ignore_media_retention_policy_inner(
453        &self,
454        request: &MediaRequestParameters,
455        ignore_policy: IgnoreMediaRetentionPolicy,
456    ) -> Result<(), Self::Error> {
457        let uri = self.encode_key(keys::MEDIA, request.source.unique_key());
458        let format = self.encode_key(keys::MEDIA, request.format.unique_key());
459        let ignore_policy = ignore_policy.is_yes();
460
461        let conn = self.write().await?;
462        conn.execute(
463            r#"UPDATE media SET ignore_policy = ? WHERE uri = ? AND format = ?"#,
464            (ignore_policy, uri, format),
465        )
466        .await?;
467
468        Ok(())
469    }
470
471    async fn get_media_content_inner(
472        &self,
473        request: &MediaRequestParameters,
474        current_time: SystemTime,
475    ) -> Result<Option<Vec<u8>>, Self::Error> {
476        let uri = self.encode_key(keys::MEDIA, request.source.unique_key());
477        let format = self.encode_key(keys::MEDIA, request.format.unique_key());
478        let timestamp = time_to_timestamp(current_time);
479
480        let conn = self.write().await?;
481        let data = conn
482            .with_transaction::<_, rusqlite::Error, _>(move |txn| {
483                // Update the last access.
484                // We need to do this first so the transaction is in write mode right away.
485                // See: https://sqlite.org/lang_transaction.html#read_transactions_versus_write_transactions
486                txn.execute(
487                    "UPDATE media SET last_access = ? WHERE uri = ? AND format = ?",
488                    (timestamp, &uri, &format),
489                )?;
490
491                txn.query_row::<Vec<u8>, _, _>(
492                    "SELECT data FROM media WHERE uri = ? AND format = ?",
493                    (&uri, &format),
494                    |row| row.get(0),
495                )
496                .optional()
497            })
498            .await?;
499
500        data.map(|v| self.decode_value(&v).map(Into::into)).transpose()
501    }
502
503    async fn get_media_content_for_uri_inner(
504        &self,
505        uri: &MxcUri,
506        current_time: SystemTime,
507    ) -> Result<Option<Vec<u8>>, Self::Error> {
508        let uri = self.encode_key(keys::MEDIA, uri);
509        let timestamp = time_to_timestamp(current_time);
510
511        let conn = self.write().await?;
512        let data = conn
513            .with_transaction::<_, rusqlite::Error, _>(move |txn| {
514                // Update the last access.
515                // We need to do this first so the transaction is in write mode right away.
516                // See: https://sqlite.org/lang_transaction.html#read_transactions_versus_write_transactions
517                txn.execute("UPDATE media SET last_access = ? WHERE uri = ?", (timestamp, &uri))?;
518
519                txn.query_row::<Vec<u8>, _, _>(
520                    "SELECT data FROM media WHERE uri = ?",
521                    (&uri,),
522                    |row| row.get(0),
523                )
524                .optional()
525            })
526            .await?;
527
528        data.map(|v| self.decode_value(&v).map(Into::into)).transpose()
529    }
530
531    async fn clean_inner(
532        &self,
533        policy: MediaRetentionPolicy,
534        current_time: SystemTime,
535    ) -> Result<(), Self::Error> {
536        if !policy.has_limitations() {
537            // We can safely skip all the checks.
538            return Ok(());
539        }
540
541        let conn = self.write().await?;
542        let removed = conn
543            .with_transaction::<_, Error, _>(move |txn| {
544                let mut removed = false;
545
546                // First, check media content that exceed the max filesize.
547                if let Some(max_file_size) = policy.computed_max_file_size() {
548                    let count = txn.execute(
549                        "DELETE FROM media WHERE ignore_policy IS FALSE AND length(data) > ?",
550                        (max_file_size,),
551                    )?;
552
553                    if count > 0 {
554                        removed = true;
555                    }
556                }
557
558                // Then, clean up expired media content.
559                if let Some(last_access_expiry) = policy.last_access_expiry {
560                    let current_timestamp = time_to_timestamp(current_time);
561                    let expiry_secs = last_access_expiry.as_secs();
562                    let count = txn.execute(
563                        "DELETE FROM media WHERE ignore_policy IS FALSE AND (? - last_access) >= ?",
564                        (current_timestamp, expiry_secs),
565                    )?;
566
567                    if count > 0 {
568                        removed = true;
569                    }
570                }
571
572                // Finally, if the cache size is too big, remove old items until it fits.
573                if let Some(max_cache_size) = policy.max_cache_size {
574                    // i64 is the integer type used by SQLite, use it here to avoid usize overflow
575                    // during the conversion of the result.
576                    let cache_size = txn
577                        .query_row(
578                            "SELECT sum(length(data)) FROM media WHERE ignore_policy IS FALSE",
579                            (),
580                            |row| {
581                                // `sum()` returns `NULL` if there are no rows.
582                                row.get::<_, Option<u64>>(0)
583                            },
584                        )?
585                        .unwrap_or_default();
586
587                    // If the cache size is overflowing or bigger than max cache size, clean up.
588                    if cache_size > max_cache_size {
589                        // Get the sizes of the media contents ordered by last access.
590                        let mut cached_stmt = txn.prepare_cached(
591                            "SELECT rowid, length(data) FROM media \
592                             WHERE ignore_policy IS FALSE ORDER BY last_access DESC",
593                        )?;
594                        let content_sizes = cached_stmt
595                            .query(())?
596                            .mapped(|row| Ok((row.get::<_, i64>(0)?, row.get::<_, u64>(1)?)));
597
598                        let mut accumulated_items_size = 0u64;
599                        let mut limit_reached = false;
600                        let mut rows_to_remove = Vec::new();
601
602                        for result in content_sizes {
603                            let (row_id, size) = match result {
604                                Ok(content_size) => content_size,
605                                Err(error) => {
606                                    return Err(error.into());
607                                }
608                            };
609
610                            if limit_reached {
611                                rows_to_remove.push(row_id);
612                                continue;
613                            }
614
615                            match accumulated_items_size.checked_add(size) {
616                                Some(acc) if acc > max_cache_size => {
617                                    // We can stop accumulating.
618                                    limit_reached = true;
619                                    rows_to_remove.push(row_id);
620                                }
621                                Some(acc) => accumulated_items_size = acc,
622                                None => {
623                                    // The accumulated size is overflowing but the setting cannot be
624                                    // bigger than usize::MAX, we can stop accumulating.
625                                    limit_reached = true;
626                                    rows_to_remove.push(row_id);
627                                }
628                            }
629                        }
630
631                        if !rows_to_remove.is_empty() {
632                            removed = true;
633                        }
634
635                        txn.chunk_large_query_over(rows_to_remove, None, |txn, row_ids| {
636                            let sql_params = repeat_vars(row_ids.len());
637                            let query = format!("DELETE FROM media WHERE rowid IN ({sql_params})");
638                            txn.prepare(&query)?.execute(params_from_iter(row_ids))?;
639                            Ok(Vec::<()>::new())
640                        })?;
641                    }
642                }
643
644                txn.set_serialized_kv(keys::LAST_MEDIA_CLEANUP_TIME, current_time)?;
645
646                Ok(removed)
647            })
648            .await?;
649
650        // If we removed media, defragment the database and free space on the
651        // filesystem.
652        if removed {
653            conn.vacuum().await?;
654        }
655
656        Ok(())
657    }
658
659    async fn last_media_cleanup_time_inner(&self) -> Result<Option<SystemTime>, Self::Error> {
660        let conn = self.read().await?;
661        conn.get_serialized_kv(keys::LAST_MEDIA_CLEANUP_TIME).await
662    }
663}
664
665#[cfg(test)]
666mod tests {
667    use std::{
668        path::PathBuf,
669        sync::atomic::{AtomicU32, Ordering::SeqCst},
670        time::Duration,
671    };
672
673    use matrix_sdk_base::{
674        media::{
675            store::{IgnoreMediaRetentionPolicy, MediaStore, MediaStoreError},
676            MediaFormat, MediaRequestParameters, MediaThumbnailSettings,
677        },
678        media_store_inner_integration_tests, media_store_integration_tests,
679        media_store_integration_tests_time,
680    };
681    use matrix_sdk_test::async_test;
682    use once_cell::sync::Lazy;
683    use ruma::{events::room::MediaSource, media::Method, mxc_uri, uint};
684    use tempfile::{tempdir, TempDir};
685
686    use super::SqliteMediaStore;
687    use crate::{utils::SqliteAsyncConnExt, SqliteStoreConfig};
688
689    static TMP_DIR: Lazy<TempDir> = Lazy::new(|| tempdir().unwrap());
690    static NUM: AtomicU32 = AtomicU32::new(0);
691
692    fn new_media_store_workspace() -> PathBuf {
693        let name = NUM.fetch_add(1, SeqCst).to_string();
694        TMP_DIR.path().join(name)
695    }
696
697    async fn get_media_store() -> Result<SqliteMediaStore, MediaStoreError> {
698        let tmpdir_path = new_media_store_workspace();
699
700        tracing::info!("using media store @ {}", tmpdir_path.to_str().unwrap());
701
702        Ok(SqliteMediaStore::open(tmpdir_path.to_str().unwrap(), None).await.unwrap())
703    }
704
705    media_store_integration_tests!();
706    media_store_integration_tests_time!();
707    media_store_inner_integration_tests!();
708
709    async fn get_media_store_content_sorted_by_last_access(
710        media_store: &SqliteMediaStore,
711    ) -> Vec<Vec<u8>> {
712        let sqlite_db = media_store.read().await.expect("accessing sqlite db failed");
713        sqlite_db
714            .prepare("SELECT data FROM media ORDER BY last_access DESC", |mut stmt| {
715                stmt.query(())?.mapped(|row| row.get(0)).collect()
716            })
717            .await
718            .expect("querying media cache content by last access failed")
719    }
720
721    #[async_test]
722    async fn test_pool_size() {
723        let tmpdir_path = new_media_store_workspace();
724        let store_open_config = SqliteStoreConfig::new(tmpdir_path).pool_max_size(42);
725
726        let store = SqliteMediaStore::open_with_config(store_open_config).await.unwrap();
727
728        assert_eq!(store.pool.status().max_size, 42);
729    }
730
731    #[async_test]
732    async fn test_last_access() {
733        let media_store = get_media_store().await.expect("creating media cache failed");
734        let uri = mxc_uri!("mxc://localhost/media");
735        let file_request = MediaRequestParameters {
736            source: MediaSource::Plain(uri.to_owned()),
737            format: MediaFormat::File,
738        };
739        let thumbnail_request = MediaRequestParameters {
740            source: MediaSource::Plain(uri.to_owned()),
741            format: MediaFormat::Thumbnail(MediaThumbnailSettings::with_method(
742                Method::Crop,
743                uint!(100),
744                uint!(100),
745            )),
746        };
747
748        let content: Vec<u8> = "hello world".into();
749        let thumbnail_content: Vec<u8> = "hello…".into();
750
751        // Add the media.
752        media_store
753            .add_media_content(&file_request, content.clone(), IgnoreMediaRetentionPolicy::No)
754            .await
755            .expect("adding file failed");
756
757        // Since the precision of the timestamp is in seconds, wait so the timestamps
758        // differ.
759        tokio::time::sleep(Duration::from_secs(3)).await;
760
761        media_store
762            .add_media_content(
763                &thumbnail_request,
764                thumbnail_content.clone(),
765                IgnoreMediaRetentionPolicy::No,
766            )
767            .await
768            .expect("adding thumbnail failed");
769
770        // File's last access is older than thumbnail.
771        let contents = get_media_store_content_sorted_by_last_access(&media_store).await;
772
773        assert_eq!(contents.len(), 2, "media cache contents length is wrong");
774        assert_eq!(contents[0], thumbnail_content, "thumbnail is not last access");
775        assert_eq!(contents[1], content, "file is not second-to-last access");
776
777        // Since the precision of the timestamp is in seconds, wait so the timestamps
778        // differ.
779        tokio::time::sleep(Duration::from_secs(3)).await;
780
781        // Access the file so its last access is more recent.
782        let _ = media_store
783            .get_media_content(&file_request)
784            .await
785            .expect("getting file failed")
786            .expect("file is missing");
787
788        // File's last access is more recent than thumbnail.
789        let contents = get_media_store_content_sorted_by_last_access(&media_store).await;
790
791        assert_eq!(contents.len(), 2, "media cache contents length is wrong");
792        assert_eq!(contents[0], content, "file is not last access");
793        assert_eq!(contents[1], thumbnail_content, "thumbnail is not second-to-last access");
794    }
795}
796
797#[cfg(test)]
798mod encrypted_tests {
799    use std::sync::atomic::{AtomicU32, Ordering::SeqCst};
800
801    use matrix_sdk_base::{
802        media::store::MediaStoreError, media_store_inner_integration_tests,
803        media_store_integration_tests, media_store_integration_tests_time,
804    };
805    use once_cell::sync::Lazy;
806    use tempfile::{tempdir, TempDir};
807
808    use super::SqliteMediaStore;
809
810    static TMP_DIR: Lazy<TempDir> = Lazy::new(|| tempdir().unwrap());
811    static NUM: AtomicU32 = AtomicU32::new(0);
812
813    async fn get_media_store() -> Result<SqliteMediaStore, MediaStoreError> {
814        let name = NUM.fetch_add(1, SeqCst).to_string();
815        let tmpdir_path = TMP_DIR.path().join(name);
816
817        tracing::info!("using media store @ {}", tmpdir_path.to_str().unwrap());
818
819        Ok(SqliteMediaStore::open(tmpdir_path.to_str().unwrap(), Some("default_test_password"))
820            .await
821            .unwrap())
822    }
823
824    media_store_integration_tests!();
825    media_store_integration_tests_time!();
826    media_store_inner_integration_tests!();
827}