Skip to main content

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::{
18    collections::{BTreeMap, HashMap},
19    fmt,
20    path::{Path, PathBuf},
21    sync::Arc,
22};
23
24use async_trait::async_trait;
25use deadpool::managed::PoolConfig;
26use matrix_sdk_base::{
27    cross_process_lock::CrossProcessLockGeneration,
28    media::{
29        MediaRequestParameters, UniqueKey,
30        store::{
31            IgnoreMediaRetentionPolicy, MediaRetentionPolicy, MediaService, MediaStore,
32            MediaStoreInner,
33        },
34    },
35    timer,
36};
37use matrix_sdk_store_encryption::StoreCipher;
38use ruma::{MilliSecondsSinceUnixEpoch, MxcUri, OwnedMxcUri, time::SystemTime};
39use rusqlite::{OptionalExtension, params_from_iter};
40use tokio::{
41    fs,
42    sync::{Mutex, OwnedMutexGuard},
43};
44use tracing::{debug, instrument};
45
46use crate::{
47    OpenStoreError, RuntimeConfig, Secret, SqliteStoreConfig,
48    connection::{
49        self, Connection as SqliteAsyncConn, Pool as SqlitePool, SqliteConnections,
50        SqliteConnectionsInner,
51    },
52    error::{Error, Result},
53    utils::{
54        EncryptableStore, SqliteAsyncConnExt, SqliteKeyValueStoreAsyncConnExt,
55        SqliteKeyValueStoreConnExt, SqliteTransactionExt, time_to_timestamp,
56    },
57};
58
59mod keys {
60    // Entries in Key-value store
61    pub const MEDIA_RETENTION_POLICY: &str = "media_retention_policy";
62    pub const LAST_MEDIA_CLEANUP_TIME: &str = "last_media_cleanup_time";
63
64    // Tables
65    pub const MEDIA: &str = "media";
66}
67
68/// The database name.
69pub const DATABASE_NAME: &str = "matrix-sdk-media.sqlite3";
70
71/// An SQLite-based media store.
72#[derive(Clone)]
73pub struct SqliteMediaStore {
74    store_cipher: Option<Arc<StoreCipher>>,
75
76    /// `Some` when active, `None` when closed.
77    connections: Arc<SqliteConnections>,
78
79    /// Retained so we can rebuild the pool on reopen.
80    db_path: PathBuf,
81
82    /// Retained so we can rebuild the pool on reopen.
83    pool_config: PoolConfig,
84
85    /// Retained so we can re-apply runtime config on reopen.
86    runtime_config: RuntimeConfig,
87
88    media_service: MediaService,
89}
90
91#[cfg(not(tarpaulin_include))]
92impl fmt::Debug for SqliteMediaStore {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.debug_struct("SqliteMediaStore").finish_non_exhaustive()
95    }
96}
97
98impl EncryptableStore for SqliteMediaStore {
99    fn get_cypher(&self) -> Option<&StoreCipher> {
100        self.store_cipher.as_deref()
101    }
102}
103
104impl SqliteMediaStore {
105    /// Open the SQLite-based media store at the given path using the given
106    /// passphrase to encrypt private data.
107    pub async fn open(
108        path: impl AsRef<Path>,
109        passphrase: Option<&str>,
110    ) -> Result<Self, OpenStoreError> {
111        Self::open_with_config(&SqliteStoreConfig::new(path).passphrase(passphrase)).await
112    }
113
114    /// Open the SQLite-based media store at the given path using the given key
115    /// to encrypt private data.
116    pub async fn open_with_key(
117        path: impl AsRef<Path>,
118        key: Option<&[u8]>,
119    ) -> Result<Self, OpenStoreError> {
120        Self::open_with_config(&SqliteStoreConfig::new(path).key(key)).await
121    }
122
123    /// Open the SQLite-based media store with the config open config.
124    #[instrument(skip(config), fields(path = ?config.path))]
125    pub async fn open_with_config(config: &SqliteStoreConfig) -> Result<Self, OpenStoreError> {
126        debug!(?config);
127
128        let _timer = timer!("open_with_config");
129
130        fs::create_dir_all(&config.path).await.map_err(OpenStoreError::CreateDir)?;
131
132        let db_path = config.path.join(DATABASE_NAME);
133        let pool_config = config.pool_config();
134        let runtime_config = config.runtime_config();
135
136        let pool = config.build_pool_of_connections(DATABASE_NAME)?;
137
138        let this =
139            Self::open_with_pool(pool, db_path, pool_config, runtime_config, config.secret.clone())
140                .await?;
141
142        // Apply runtime config on the write connection.
143        this.write().await?.apply_runtime_config(runtime_config).await?;
144
145        Ok(this)
146    }
147
148    /// Open an SQLite-based media store using the given SQLite database pool.
149    /// The given passphrase will be used to encrypt private data.
150    async fn open_with_pool(
151        pool: SqlitePool,
152        db_path: PathBuf,
153        pool_config: PoolConfig,
154        runtime_config: RuntimeConfig,
155        secret: Option<Secret>,
156    ) -> Result<Self, OpenStoreError> {
157        let conn = pool.get().await?;
158
159        let version = conn.db_version().await?;
160        run_migrations(&conn, version).await?;
161
162        conn.wal_checkpoint().await;
163
164        let store_cipher = match &secret {
165            Some(s) => Some(Arc::new(conn.get_or_create_store_cipher(s.clone()).await?)),
166            None => None,
167        };
168
169        let media_service = MediaService::new();
170        let media_retention_policy = conn.get_serialized_kv(keys::MEDIA_RETENTION_POLICY).await?;
171        let last_media_cleanup_time = conn.get_serialized_kv(keys::LAST_MEDIA_CLEANUP_TIME).await?;
172        media_service.restore(media_retention_policy, last_media_cleanup_time);
173
174        let connections = SqliteConnectionsInner {
175            pool,
176            // Use `conn` as our selected write connection.
177            write_connection: Arc::new(Mutex::new(conn)),
178        };
179
180        Ok(Self {
181            store_cipher,
182            connections: Arc::new(SqliteConnections::new(connections).await),
183            db_path,
184            pool_config,
185            runtime_config,
186            media_service,
187        })
188    }
189
190    // Acquire a connection for executing read operations.
191    #[instrument(skip_all)]
192    async fn read(&self) -> Result<SqliteAsyncConn> {
193        let pool = {
194            let guard = self.connections.lock().await;
195            let conns = guard.as_ref().ok_or(Error::StoreClosed)?;
196            conns.pool.clone()
197        };
198
199        let connection = pool.get().await?;
200
201        // Per https://www.sqlite.org/foreignkeys.html#fk_enable, foreign key
202        // support must be enabled on a per-connection basis. Execute it every
203        // time we try to get a connection, since we can't guarantee a previous
204        // connection did enable it before.
205        connection.execute_batch("PRAGMA foreign_keys = ON;").await?;
206
207        Ok(connection)
208    }
209
210    // Acquire a connection for executing write operations.
211    #[instrument(skip_all)]
212    async fn write(&self) -> Result<OwnedMutexGuard<SqliteAsyncConn>> {
213        let write_connection = {
214            let guard = self.connections.lock().await;
215            let conns = guard.as_ref().ok_or(Error::StoreClosed)?;
216            conns.write_connection.clone()
217        };
218
219        let connection = write_connection.lock_owned().await;
220
221        // Specify a busy timeout so that operations are automatically retried,
222        // in case the database was marked as locked, which can happen
223        // under very peculiar circumstances in WAL mode.
224        //
225        // The timeout value is in milliseconds.
226        //
227        // See also https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode.
228        connection.execute_batch("PRAGMA busy_timeout = 2000;").await?;
229
230        // Per https://www.sqlite.org/foreignkeys.html#fk_enable, foreign key
231        // support must be enabled on a per-connection basis. Execute it every
232        // time we try to get a connection, since we can't guarantee a previous
233        // connection did enable it before.
234        connection.execute_batch("PRAGMA foreign_keys = ON;").await?;
235
236        Ok(connection)
237    }
238
239    pub async fn vacuum(&self) -> Result<()> {
240        let write_connection = {
241            let guard = self.connections.lock().await;
242            let conns = guard.as_ref().ok_or(Error::StoreClosed)?;
243            conns.write_connection.clone()
244        };
245        write_connection.lock().await.vacuum().await
246    }
247
248    async fn get_db_size(&self) -> Result<Option<usize>> {
249        let pool = {
250            let guard = self.connections.lock().await;
251            let conns = guard.as_ref().ok_or(Error::StoreClosed)?;
252            conns.pool.clone()
253        };
254        Ok(Some(pool.get().await?.get_db_size().await?))
255    }
256
257    pub async fn close(&self) -> Result<()> {
258        connection::close_connections(&self.connections, "Media store").await;
259        Ok(())
260    }
261
262    pub async fn reopen(&self) -> Result<()> {
263        connection::reopen_connections(
264            &self.connections,
265            self.db_path.clone(),
266            self.pool_config,
267            self.runtime_config,
268        )
269        .await?;
270        Ok(())
271    }
272
273    /// Returns the pool size status, for testing purposes.
274    #[cfg(test)]
275    async fn pool_max_size(&self) -> Option<usize> {
276        let guard = self.connections.lock().await;
277        guard.as_ref().map(|conns| conns.pool.status().max_size)
278    }
279}
280
281/// Run migrations for the given version of the database.
282async fn run_migrations(conn: &SqliteAsyncConn, version: u8) -> Result<()> {
283    // Always enable foreign keys for the current connection.
284    conn.execute_batch("PRAGMA foreign_keys = ON;").await?;
285
286    if version < 1 {
287        debug!("Creating database");
288        // First turn on WAL mode, this can't be done in the transaction, it
289        // fails with the error message: "cannot change into wal mode from
290        // within a transaction".
291        conn.execute_batch("PRAGMA journal_mode = wal;").await?;
292        conn.with_immediate_transaction(|txn| {
293            txn.execute_batch(include_str!("../migrations/media_store/001_init.sql"))?;
294            txn.set_db_version(1)
295        })
296        .await?;
297    }
298
299    if version < 2 {
300        debug!("Upgrading database to version 2");
301        conn.with_immediate_transaction(|txn| {
302            txn.execute_batch(include_str!(
303                "../migrations/media_store/002_lease_locks_with_generation.sql"
304            ))?;
305            txn.set_db_version(2)
306        })
307        .await?;
308    }
309
310    Ok(())
311}
312
313#[async_trait]
314impl MediaStore for SqliteMediaStore {
315    type Error = Error;
316
317    #[instrument(skip(self))]
318    async fn try_take_leased_lock(
319        &self,
320        lease_duration_ms: u32,
321        key: &str,
322        holder: &str,
323    ) -> Result<Option<CrossProcessLockGeneration>> {
324        let key = key.to_owned();
325        let holder = holder.to_owned();
326
327        let now: u64 = MilliSecondsSinceUnixEpoch::now().get().into();
328        let expiration = now + lease_duration_ms as u64;
329
330        // Learn about the `excluded` keyword in https://sqlite.org/lang_upsert.html.
331        let generation = self
332            .write()
333            .await?
334            .with_immediate_transaction(move |txn| {
335                txn.query_one(
336                    "INSERT INTO lease_locks (key, holder, expiration)
337                    VALUES (?1, ?2, ?3)
338                    ON CONFLICT (key)
339                    DO
340                        UPDATE SET
341                            holder = excluded.holder,
342                            expiration = excluded.expiration,
343                            generation =
344                                CASE holder
345                                    WHEN excluded.holder THEN generation
346                                    ELSE generation + 1
347                                END
348                        WHERE
349                            holder = excluded.holder
350                            OR expiration < ?4
351                    RETURNING generation
352                    ",
353                    (key, holder, expiration, now),
354                    |row| row.get(0),
355                )
356                .optional()
357            })
358            .await?;
359
360        Ok(generation)
361    }
362
363    async fn add_media_content(
364        &self,
365        request: &MediaRequestParameters,
366        content: Vec<u8>,
367        ignore_policy: IgnoreMediaRetentionPolicy,
368    ) -> Result<()> {
369        let _timer = timer!("method");
370
371        self.media_service.add_media_content(self, request, content, ignore_policy).await
372    }
373
374    #[instrument(skip_all)]
375    async fn replace_media_key(
376        &self,
377        from: &MediaRequestParameters,
378        to: &MediaRequestParameters,
379    ) -> Result<(), Self::Error> {
380        let _timer = timer!("method");
381
382        let prev_uri = self.encode_key(keys::MEDIA, from.source.unique_key());
383        let prev_format = self.encode_key(keys::MEDIA, from.format.unique_key());
384
385        let new_uri = self.encode_key(keys::MEDIA, to.source.unique_key());
386        let new_format = self.encode_key(keys::MEDIA, to.format.unique_key());
387
388        let conn = self.write().await?;
389        conn.execute(
390            r#"UPDATE media SET uri = ?, format = ? WHERE uri = ? AND format = ?"#,
391            (new_uri, new_format, prev_uri, prev_format),
392        )
393        .await?;
394
395        Ok(())
396    }
397
398    #[instrument(skip_all)]
399    async fn get_media_content(&self, request: &MediaRequestParameters) -> Result<Option<Vec<u8>>> {
400        let _timer = timer!("method");
401
402        self.media_service.get_media_content(self, request).await
403    }
404
405    #[instrument(skip_all)]
406    async fn remove_media_content(&self, request: &MediaRequestParameters) -> Result<()> {
407        let _timer = timer!("method");
408
409        let uri = self.encode_key(keys::MEDIA, request.source.unique_key());
410        let format = self.encode_key(keys::MEDIA, request.format.unique_key());
411
412        let conn = self.write().await?;
413        conn.execute("DELETE FROM media WHERE uri = ? AND format = ?", (uri, format)).await?;
414
415        Ok(())
416    }
417
418    #[instrument(skip(self))]
419    async fn remove_media_content_for_uri(&self, uri: &MxcUri) -> Result<()> {
420        let _timer = timer!("method");
421
422        let uri = self.encode_key(keys::MEDIA, uri);
423
424        let conn = self.write().await?;
425        conn.execute("DELETE FROM media WHERE uri = ?", (uri,)).await?;
426
427        Ok(())
428    }
429
430    #[instrument(skip_all)]
431    async fn set_media_retention_policy(
432        &self,
433        policy: MediaRetentionPolicy,
434    ) -> Result<(), Self::Error> {
435        let _timer = timer!("method");
436
437        self.media_service.set_media_retention_policy(self, policy).await
438    }
439
440    #[instrument(skip_all)]
441    fn media_retention_policy(&self) -> MediaRetentionPolicy {
442        let _timer = timer!("method");
443
444        self.media_service.media_retention_policy()
445    }
446
447    #[instrument(skip_all)]
448    async fn set_ignore_media_retention_policy(
449        &self,
450        request: &MediaRequestParameters,
451        ignore_policy: IgnoreMediaRetentionPolicy,
452    ) -> Result<(), Self::Error> {
453        let _timer = timer!("method");
454
455        self.media_service.set_ignore_media_retention_policy(self, request, ignore_policy).await
456    }
457
458    #[instrument(skip_all)]
459    async fn clean(&self) -> Result<(), Self::Error> {
460        let _timer = timer!("method");
461
462        self.media_service.clean(self).await
463    }
464
465    async fn close(&self) -> Result<(), Self::Error> {
466        SqliteMediaStore::close(self).await
467    }
468
469    async fn reopen(&self) -> Result<(), Self::Error> {
470        SqliteMediaStore::reopen(self).await
471    }
472
473    async fn optimize(&self) -> Result<(), Self::Error> {
474        Ok(self.vacuum().await?)
475    }
476
477    async fn get_size(&self) -> Result<Option<usize>, Self::Error> {
478        self.get_db_size().await
479    }
480
481    #[instrument(skip_all)]
482    async fn media_sizes(
483        &self,
484        uris: &[OwnedMxcUri],
485    ) -> Result<BTreeMap<OwnedMxcUri, u64>, Self::Error> {
486        let _timer = timer!("method");
487
488        if uris.is_empty() {
489            return Ok(BTreeMap::new());
490        }
491
492        let mut lookup = HashMap::with_capacity(uris.len());
493        let mut keys = Vec::with_capacity(uris.len());
494        for uri in uris {
495            let key = self.encode_key(keys::MEDIA, uri.as_str());
496            lookup.insert(key.to_vec(), uri.clone());
497            keys.push(key);
498        }
499
500        let sizes = self
501            .read()
502            .await?
503            .chunk_large_query_over(keys, None, move |txn, chunk| {
504                let sql = format!(
505                    "SELECT uri, sum(length(data)) FROM media WHERE uri IN ({}) GROUP BY uri",
506                    chunk.host_parameters()
507                );
508                let mut stmt = txn.prepare(&sql)?;
509                let mut sizes = Vec::new();
510                let rows = stmt.query(params_from_iter(chunk.iter()))?;
511                for row in rows.mapped(|row| Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, u64>(1)?)))
512                {
513                    let (key, size) = row?;
514                    if let Some(uri) = lookup.get(&key) {
515                        sizes.push((uri.clone(), size));
516                    }
517                }
518                Ok(sizes)
519            })
520            .await?;
521
522        Ok(sizes.into_iter().collect())
523    }
524}
525
526#[cfg_attr(target_family = "wasm", async_trait(?Send))]
527#[cfg_attr(not(target_family = "wasm"), async_trait)]
528impl MediaStoreInner for SqliteMediaStore {
529    type Error = Error;
530
531    async fn media_retention_policy_inner(
532        &self,
533    ) -> Result<Option<MediaRetentionPolicy>, Self::Error> {
534        let conn = self.read().await?;
535        conn.get_serialized_kv(keys::MEDIA_RETENTION_POLICY).await
536    }
537
538    async fn set_media_retention_policy_inner(
539        &self,
540        policy: MediaRetentionPolicy,
541    ) -> Result<(), Self::Error> {
542        let conn = self.write().await?;
543        conn.set_serialized_kv(keys::MEDIA_RETENTION_POLICY, policy).await?;
544        Ok(())
545    }
546
547    async fn add_media_content_inner(
548        &self,
549        request: &MediaRequestParameters,
550        data: Vec<u8>,
551        last_access: SystemTime,
552        policy: MediaRetentionPolicy,
553        ignore_policy: IgnoreMediaRetentionPolicy,
554    ) -> Result<(), Self::Error> {
555        let ignore_policy = ignore_policy.is_yes();
556        let data = self.encode_value(data)?;
557
558        if !ignore_policy && policy.exceeds_max_file_size(data.len() as u64) {
559            return Ok(());
560        }
561
562        let uri = self.encode_key(keys::MEDIA, request.source.unique_key());
563        let format = self.encode_key(keys::MEDIA, request.format.unique_key());
564        let timestamp = time_to_timestamp(last_access);
565
566        let conn = self.write().await?;
567        conn.execute(
568            "INSERT OR REPLACE INTO media (uri, format, data, last_access, ignore_policy) VALUES (?, ?, ?, ?, ?)",
569            (uri, format, data, timestamp, ignore_policy),
570        )
571        .await?;
572
573        Ok(())
574    }
575
576    async fn set_ignore_media_retention_policy_inner(
577        &self,
578        request: &MediaRequestParameters,
579        ignore_policy: IgnoreMediaRetentionPolicy,
580    ) -> Result<(), Self::Error> {
581        let uri = self.encode_key(keys::MEDIA, request.source.unique_key());
582        let format = self.encode_key(keys::MEDIA, request.format.unique_key());
583        let ignore_policy = ignore_policy.is_yes();
584
585        let conn = self.write().await?;
586        conn.execute(
587            r#"UPDATE media SET ignore_policy = ? WHERE uri = ? AND format = ?"#,
588            (ignore_policy, uri, format),
589        )
590        .await?;
591
592        Ok(())
593    }
594
595    async fn get_media_content_inner(
596        &self,
597        request: &MediaRequestParameters,
598        current_time: SystemTime,
599    ) -> Result<Option<Vec<u8>>, Self::Error> {
600        let uri = self.encode_key(keys::MEDIA, request.source.unique_key());
601        let format = self.encode_key(keys::MEDIA, request.format.unique_key());
602        let timestamp = time_to_timestamp(current_time);
603
604        let data = self
605            .write()
606            .await?
607            .with_immediate_transaction(move |txn| {
608                // Update the last access. We need to do this first so the
609                // transaction is in write mode right away. See:
610                // https://sqlite.org/lang_transaction.html#read_transactions_versus_write_transactions
611                txn.execute(
612                    "UPDATE media SET last_access = ? WHERE uri = ? AND format = ?",
613                    (timestamp, &uri, &format),
614                )?;
615
616                txn.query_row::<Vec<u8>, _, _>(
617                    "SELECT data FROM media WHERE uri = ? AND format = ?",
618                    (&uri, &format),
619                    |row| row.get(0),
620                )
621                .optional()
622            })
623            .await?;
624
625        data.map(|v| self.decode_value(&v).map(Into::into)).transpose()
626    }
627
628    async fn clean_inner(
629        &self,
630        policy: MediaRetentionPolicy,
631        current_time: SystemTime,
632    ) -> Result<(), Self::Error> {
633        if !policy.has_limitations() {
634            // We can safely skip all the checks.
635            return Ok(());
636        }
637
638        let conn = self.read().await?;
639
640        let removed = conn
641            .with_immediate_transaction::<_, Self::Error, _>(move |txn| {
642                let mut removed = false;
643
644                // First, check media content that exceed the max filesize.
645                if let Some(max_file_size) = policy.computed_max_file_size() {
646                    let count = txn.execute(
647                        "DELETE FROM media WHERE ignore_policy IS FALSE AND length(data) > ?",
648                        (max_file_size,),
649                    )?;
650
651                    if count > 0 {
652                        removed = true;
653                    }
654                }
655
656                // Then, clean up expired media content.
657                if let Some(last_access_expiry) = policy.last_access_expiry {
658                    let current_timestamp = time_to_timestamp(current_time);
659                    let expiry_secs = last_access_expiry.as_secs();
660                    let count = txn.execute(
661                        "DELETE FROM media WHERE ignore_policy IS FALSE AND (? - last_access) >= ?",
662                        (current_timestamp, expiry_secs),
663                    )?;
664
665                    if count > 0 {
666                        removed = true;
667                    }
668                }
669
670                // Finally, if the cache size is too big, remove old items until
671                // it fits.
672                if let Some(max_cache_size) = policy.max_cache_size {
673                    // i64 is the integer type used by SQLite, use it here to
674                    // avoid usize overflow during the conversion of the result.
675                    let cache_size = txn
676                        .query_row(
677                            "SELECT sum(length(data)) FROM media WHERE ignore_policy IS FALSE",
678                            (),
679                            |row| {
680                                // `sum()` returns `NULL` if there are no rows.
681                                row.get::<_, Option<u64>>(0)
682                            },
683                        )?
684                        .unwrap_or_default();
685
686                    // If the cache size is overflowing or bigger than max cache
687                    // size, clean up.
688                    if cache_size > max_cache_size {
689                        // Get the sizes of the media contents ordered by last
690                        // access.
691                        let mut cached_stmt = txn.prepare_cached(
692                            "SELECT rowid, length(data) FROM media \
693                             WHERE ignore_policy IS FALSE ORDER BY last_access DESC",
694                        )?;
695                        let content_sizes = cached_stmt
696                            .query(())?
697                            .mapped(|row| Ok((row.get::<_, i64>(0)?, row.get::<_, u64>(1)?)));
698
699                        let mut accumulated_items_size = 0u64;
700                        let mut limit_reached = false;
701                        let mut rows_to_remove = Vec::new();
702
703                        for result in content_sizes {
704                            let (row_id, size) = match result {
705                                Ok(content_size) => content_size,
706                                Err(error) => {
707                                    return Err(error.into());
708                                }
709                            };
710
711                            if limit_reached {
712                                rows_to_remove.push(row_id);
713                                continue;
714                            }
715
716                            match accumulated_items_size.checked_add(size) {
717                                Some(acc) if acc > max_cache_size => {
718                                    // We can stop accumulating.
719                                    limit_reached = true;
720                                    rows_to_remove.push(row_id);
721                                }
722                                Some(acc) => accumulated_items_size = acc,
723                                None => {
724                                    // The accumulated size is overflowing but
725                                    // the setting cannot be bigger than
726                                    // usize::MAX, we can stop accumulating.
727                                    limit_reached = true;
728                                    rows_to_remove.push(row_id);
729                                }
730                            }
731                        }
732
733                        if !rows_to_remove.is_empty() {
734                            removed = true;
735                        }
736
737                        txn.chunk_large_query_over(rows_to_remove, None, |txn, row_ids| {
738                            let sql_params = row_ids.host_parameters();
739                            let query = format!("DELETE FROM media WHERE rowid IN ({sql_params})");
740                            txn.prepare(&query)?.execute(params_from_iter(row_ids))?;
741                            Ok(Vec::<()>::new())
742                        })?;
743                    }
744                }
745
746                txn.set_serialized_kv(keys::LAST_MEDIA_CLEANUP_TIME, current_time)?;
747
748                Ok(removed)
749            })
750            .await?;
751
752        // If we removed media, defragment the database and free space on the
753        // filesystem.
754        if removed {
755            conn.vacuum().await?;
756        }
757
758        Ok(())
759    }
760
761    async fn last_media_cleanup_time_inner(&self) -> Result<Option<SystemTime>, Self::Error> {
762        let conn = self.read().await?;
763        conn.get_serialized_kv(keys::LAST_MEDIA_CLEANUP_TIME).await
764    }
765}
766
767#[cfg(test)]
768mod tests {
769    use std::{
770        path::PathBuf,
771        sync::{
772            LazyLock,
773            atomic::{AtomicU32, Ordering::SeqCst},
774        },
775        time::Duration,
776    };
777
778    use matrix_sdk_base::{
779        media::{
780            MediaFormat, MediaRequestParameters, MediaThumbnailSettings,
781            store::{IgnoreMediaRetentionPolicy, MediaStore, MediaStoreError},
782        },
783        media_store_inner_integration_tests, media_store_integration_tests,
784        media_store_integration_tests_time,
785    };
786    use matrix_sdk_test::async_test;
787    use ruma::{events::room::MediaSource, media::Method, mxc_uri, uint};
788    use tempfile::{TempDir, tempdir};
789
790    use super::SqliteMediaStore;
791    use crate::{SqliteStoreConfig, utils::SqliteAsyncConnExt};
792
793    static TMP_DIR: LazyLock<TempDir> = LazyLock::new(|| tempdir().unwrap());
794    static NUM: AtomicU32 = AtomicU32::new(0);
795
796    fn new_media_store_workspace() -> PathBuf {
797        let name = NUM.fetch_add(1, SeqCst).to_string();
798        TMP_DIR.path().join(name)
799    }
800
801    async fn get_media_store() -> Result<SqliteMediaStore, MediaStoreError> {
802        let tmpdir_path = new_media_store_workspace();
803
804        tracing::info!("using media store @ {}", tmpdir_path.to_str().unwrap());
805
806        Ok(SqliteMediaStore::open(tmpdir_path.to_str().unwrap(), None).await.unwrap())
807    }
808
809    media_store_integration_tests!();
810    media_store_integration_tests_time!();
811    media_store_inner_integration_tests!();
812
813    async fn get_media_store_content_sorted_by_last_access(
814        media_store: &SqliteMediaStore,
815    ) -> Vec<Vec<u8>> {
816        let sqlite_db = media_store.read().await.expect("accessing sqlite db failed");
817        sqlite_db
818            .prepare("SELECT data FROM media ORDER BY last_access DESC", |mut stmt| {
819                stmt.query(())?.mapped(|row| row.get(0)).collect()
820            })
821            .await
822            .expect("querying media cache content by last access failed")
823    }
824
825    #[async_test]
826    async fn test_pool_size() {
827        let tmpdir_path = new_media_store_workspace();
828        let store_open_config = SqliteStoreConfig::new(tmpdir_path).pool_max_size(42);
829
830        let store = SqliteMediaStore::open_with_config(&store_open_config).await.unwrap();
831
832        assert_eq!(store.pool_max_size().await.unwrap(), 42);
833    }
834
835    #[async_test]
836    async fn test_last_access() {
837        let media_store = get_media_store().await.expect("creating media cache failed");
838        let uri = mxc_uri!("mxc://localhost/media");
839        let file_request = MediaRequestParameters {
840            source: MediaSource::Plain(uri.to_owned()),
841            format: MediaFormat::File,
842        };
843        let thumbnail_request = MediaRequestParameters {
844            source: MediaSource::Plain(uri.to_owned()),
845            format: MediaFormat::Thumbnail(MediaThumbnailSettings::with_method(
846                Method::Crop,
847                uint!(100),
848                uint!(100),
849            )),
850        };
851
852        let content: Vec<u8> = "hello world".into();
853        let thumbnail_content: Vec<u8> = "hello…".into();
854
855        // Add the media.
856        media_store
857            .add_media_content(&file_request, content.clone(), IgnoreMediaRetentionPolicy::No)
858            .await
859            .expect("adding file failed");
860
861        // Since the precision of the timestamp is in seconds, wait so the
862        // timestamps differ.
863        tokio::time::sleep(Duration::from_secs(3)).await;
864
865        media_store
866            .add_media_content(
867                &thumbnail_request,
868                thumbnail_content.clone(),
869                IgnoreMediaRetentionPolicy::No,
870            )
871            .await
872            .expect("adding thumbnail failed");
873
874        // File's last access is older than thumbnail.
875        let contents = get_media_store_content_sorted_by_last_access(&media_store).await;
876
877        assert_eq!(contents.len(), 2, "media cache contents length is wrong");
878        assert_eq!(contents[0], thumbnail_content, "thumbnail is not last access");
879        assert_eq!(contents[1], content, "file is not second-to-last access");
880
881        // Since the precision of the timestamp is in seconds, wait so the
882        // timestamps differ.
883        tokio::time::sleep(Duration::from_secs(3)).await;
884
885        // Access the file so its last access is more recent.
886        let _ = media_store
887            .get_media_content(&file_request)
888            .await
889            .expect("getting file failed")
890            .expect("file is missing");
891
892        // File's last access is more recent than thumbnail.
893        let contents = get_media_store_content_sorted_by_last_access(&media_store).await;
894
895        assert_eq!(contents.len(), 2, "media cache contents length is wrong");
896        assert_eq!(contents[0], content, "file is not last access");
897        assert_eq!(contents[1], thumbnail_content, "thumbnail is not second-to-last access");
898    }
899}
900
901#[cfg(test)]
902mod close_reopen_tests {
903    use std::sync::{
904        LazyLock,
905        atomic::{AtomicU32, Ordering::SeqCst},
906    };
907
908    use matrix_sdk_base::media::{
909        MediaFormat, MediaRequestParameters,
910        store::{IgnoreMediaRetentionPolicy, MediaStore},
911    };
912    use matrix_sdk_test::async_test;
913    use ruma::{events::room::MediaSource, mxc_uri};
914    use tempfile::{TempDir, tempdir};
915
916    use super::SqliteMediaStore;
917
918    static TMP_DIR: LazyLock<TempDir> = LazyLock::new(|| tempdir().unwrap());
919    static NUM: AtomicU32 = AtomicU32::new(0);
920
921    async fn new_store() -> SqliteMediaStore {
922        let name = NUM.fetch_add(1, SeqCst).to_string();
923        let tmpdir_path = TMP_DIR.path().join(name);
924        SqliteMediaStore::open(tmpdir_path, None).await.unwrap()
925    }
926
927    fn test_request() -> MediaRequestParameters {
928        MediaRequestParameters {
929            source: MediaSource::Plain(mxc_uri!("mxc://localhost/test_media").to_owned()),
930            format: MediaFormat::File,
931        }
932    }
933
934    #[async_test]
935    async fn test_close_completes_without_timeout() {
936        let store = new_store().await;
937
938        // Close should complete quickly without hitting any timeout.
939        let start = std::time::Instant::now();
940        store.close().await.unwrap();
941        let elapsed = start.elapsed();
942
943        assert!(
944            elapsed < std::time::Duration::from_secs(2),
945            "close() took {elapsed:?}, expected < 2s (no timeout)"
946        );
947
948        // Connections should be None after close.
949        let guard = store.connections.lock().await;
950        assert!(guard.is_none(), "connections should be None after close");
951    }
952
953    #[async_test]
954    async fn test_reopen_restores_connections() {
955        let store = new_store().await;
956
957        store.close().await.unwrap();
958
959        {
960            let guard = store.connections.lock().await;
961            assert!(guard.is_none());
962        }
963
964        store.reopen().await.unwrap();
965
966        {
967            let guard = store.connections.lock().await;
968            assert!(guard.is_some(), "connections should be Some after reopen");
969        }
970    }
971
972    #[async_test]
973    async fn test_close_is_idempotent() {
974        let store = new_store().await;
975
976        store.close().await.unwrap();
977        // Second close should be a no-op.
978        store.close().await.unwrap();
979
980        let guard = store.connections.lock().await;
981        assert!(guard.is_none());
982    }
983
984    #[async_test]
985    async fn test_reopen_is_idempotent() {
986        let store = new_store().await;
987
988        // Reopen on an active store should be a no-op.
989        store.reopen().await.unwrap();
990
991        let guard = store.connections.lock().await;
992        assert!(guard.is_some());
993    }
994
995    #[async_test]
996    async fn test_read_fails_when_closed() {
997        let store = new_store().await;
998        store.close().await.unwrap();
999
1000        let err = store.get_media_content(&test_request()).await;
1001        assert!(err.is_err(), "read should fail when closed");
1002
1003        let err_msg = err.unwrap_err().to_string();
1004        assert!(err_msg.contains("closed"), "error should mention 'closed', got: {err_msg}");
1005    }
1006
1007    #[async_test]
1008    async fn test_write_fails_when_closed() {
1009        let store = new_store().await;
1010        store.close().await.unwrap();
1011
1012        let err = store
1013            .add_media_content(&test_request(), b"data".to_vec(), IgnoreMediaRetentionPolicy::No)
1014            .await;
1015        assert!(err.is_err(), "write should fail when closed");
1016
1017        let err_msg = err.unwrap_err().to_string();
1018        assert!(err_msg.contains("closed"), "error should mention 'closed', got: {err_msg}");
1019    }
1020
1021    #[async_test]
1022    async fn test_data_persists_across_close_reopen() {
1023        let store = new_store().await;
1024
1025        // Write some media content.
1026        store
1027            .add_media_content(
1028                &test_request(),
1029                b"hello world".to_vec(),
1030                IgnoreMediaRetentionPolicy::Yes,
1031            )
1032            .await
1033            .unwrap();
1034
1035        // Verify it's there.
1036        let content = store.get_media_content(&test_request()).await.unwrap();
1037        assert_eq!(content.as_deref(), Some(b"hello world".as_slice()));
1038
1039        // Close and reopen.
1040        store.close().await.unwrap();
1041        store.reopen().await.unwrap();
1042
1043        // Content should still be there after reopen.
1044        let content = store.get_media_content(&test_request()).await.unwrap();
1045        assert_eq!(
1046            content.as_deref(),
1047            Some(b"hello world".as_slice()),
1048            "media content should persist across close/reopen"
1049        );
1050    }
1051
1052    #[async_test]
1053    async fn test_multiple_close_reopen_cycles() {
1054        let store = new_store().await;
1055
1056        for _ in 0..5 {
1057            store.close().await.unwrap();
1058            store.reopen().await.unwrap();
1059
1060            // After each cycle, the store should be fully operational.
1061            let result = store.get_media_content(&test_request()).await;
1062            assert!(result.is_ok(), "store should work after close/reopen cycle");
1063        }
1064    }
1065
1066    #[async_test]
1067    async fn test_pool_is_fully_drained_after_close() {
1068        let store = new_store().await;
1069
1070        // Do a few reads to exercise the pool.
1071        let _ = store.get_media_content(&test_request()).await;
1072        let _ = store.get_media_content(&test_request()).await;
1073
1074        store.close().await.unwrap();
1075
1076        // After close, the connections field should be None (pool and write
1077        // connection have been fully torn down).
1078        let guard = store.connections.lock().await;
1079        assert!(guard.is_none(), "all connections should be released after close");
1080    }
1081
1082    #[async_test]
1083    async fn test_operations_work_immediately_after_reopen() {
1084        let store = new_store().await;
1085
1086        store.close().await.unwrap();
1087        store.reopen().await.unwrap();
1088
1089        // Read should work immediately after reopen.
1090        let result = store.get_media_content(&test_request()).await;
1091        assert!(result.is_ok(), "read should succeed immediately after reopen");
1092
1093        // Write should work immediately after reopen.
1094        let result = store
1095            .add_media_content(
1096                &test_request(),
1097                b"after_reopen".to_vec(),
1098                IgnoreMediaRetentionPolicy::No,
1099            )
1100            .await;
1101        assert!(result.is_ok(), "write should succeed immediately after reopen");
1102    }
1103
1104    #[async_test]
1105    async fn test_close_waits_for_held_read_connection_to_drain() {
1106        let store = new_store().await;
1107
1108        // Acquire a read connection and hold it, simulating an in-flight read.
1109        let held_conn = store.read().await.unwrap();
1110
1111        // Spawn close in a background task — it will close the pool and then
1112        // poll-wait for pool.status().size == 0 in the drain loop.
1113        let store_clone = store.clone();
1114        let close_handle = tokio::spawn(async move {
1115            store_clone.close().await.unwrap();
1116        });
1117
1118        // Give close() a moment to close the pool and enter the drain loop.
1119        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1120
1121        // The close task should still be running because we hold a connection.
1122        assert!(!close_handle.is_finished(), "close should be waiting for the held connection");
1123
1124        // Release the held connection — this lets pool.status().size drop to 0.
1125        drop(held_conn);
1126
1127        // Now close should complete promptly (well within the 5s timeout).
1128        let timeout = tokio::time::timeout(std::time::Duration::from_secs(3), close_handle).await;
1129        assert!(timeout.is_ok(), "close should complete after the held connection is released");
1130        timeout.unwrap().unwrap();
1131
1132        // Verify the store is fully closed.
1133        let guard = store.connections.lock().await;
1134        assert!(guard.is_none(), "connections should be None after close");
1135    }
1136}
1137
1138#[cfg(test)]
1139mod encrypted_tests {
1140    use std::sync::{
1141        LazyLock,
1142        atomic::{AtomicU32, Ordering::SeqCst},
1143    };
1144
1145    use matrix_sdk_base::{
1146        media::store::MediaStoreError, media_store_inner_integration_tests,
1147        media_store_integration_tests, media_store_integration_tests_time,
1148    };
1149    use tempfile::{TempDir, tempdir};
1150
1151    use super::SqliteMediaStore;
1152
1153    static TMP_DIR: LazyLock<TempDir> = LazyLock::new(|| tempdir().unwrap());
1154    static NUM: AtomicU32 = AtomicU32::new(0);
1155
1156    async fn get_media_store() -> Result<SqliteMediaStore, MediaStoreError> {
1157        let name = NUM.fetch_add(1, SeqCst).to_string();
1158        let tmpdir_path = TMP_DIR.path().join(name);
1159
1160        tracing::info!("using media store @ {}", tmpdir_path.to_str().unwrap());
1161
1162        Ok(SqliteMediaStore::open(tmpdir_path.to_str().unwrap(), Some("default_test_password"))
1163            .await
1164            .unwrap())
1165    }
1166
1167    media_store_integration_tests!();
1168    media_store_integration_tests_time!();
1169    media_store_inner_integration_tests!();
1170}