1use std::{
18 collections::HashMap,
19 fmt,
20 iter::once,
21 ops::{Deref, Not},
22 path::{Path, PathBuf},
23 sync::Arc,
24};
25
26use async_trait::async_trait;
27use deadpool::managed::PoolConfig;
28use matrix_sdk_base::{
29 cross_process_lock::CrossProcessLockGeneration,
30 deserialized_responses::TimelineEvent,
31 event_cache::{
32 Event, Gap,
33 store::{EventCacheStore, extract_event_relation},
34 thread::ThreadInfo,
35 },
36 linked_chunk::{
37 ChunkContent, ChunkIdentifier, ChunkIdentifierGenerator, ChunkMetadata, LinkedChunkId,
38 Position, RawChunk, Update,
39 },
40 timer,
41};
42use matrix_sdk_store_encryption::StoreCipher;
43use ruma::{
44 EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, events::relation::RelationType,
45};
46use rusqlite::{OptionalExtension, ToSql, Transaction, params, params_from_iter};
47use tokio::{
48 fs,
49 sync::{Mutex, OwnedMutexGuard},
50};
51use tracing::{debug, error, instrument, trace};
52
53use crate::{
54 OpenStoreError, RuntimeConfig, Secret, SqliteStoreConfig,
55 connection::{
56 self, Connection as SqliteAsyncConn, Pool as SqlitePool, SqliteConnections,
57 SqliteConnectionsInner,
58 },
59 error::{Error, Result},
60 utils::{
61 EncryptableStore, Key, SqliteAsyncConnExt, SqliteKeyValueStoreAsyncConnExt,
62 SqliteKeyValueStoreConnExt, SqliteTransactionExt, host_parameters,
63 },
64};
65
66mod keys {
67 pub const LINKED_CHUNKS: &str = "linked_chunks";
69 pub const EVENTS: &str = "events";
70}
71
72pub const DATABASE_NAME: &str = "matrix-sdk-event-cache.sqlite3";
74
75const CHUNK_TYPE_EVENT_TYPE_STRING: &str = "E";
78const CHUNK_TYPE_GAP_TYPE_STRING: &str = "G";
81
82struct Encryption {
87 cipher: Option<StoreCipher>,
88}
89
90impl Encryption {
91 fn encode_event(&self, event: &TimelineEvent) -> Result<EncodedEvent> {
92 let serialized = serde_json::to_vec(event)?;
93
94 let raw_event = event.raw();
96 let (relates_to, rel_type) = extract_event_relation(raw_event).unzip();
97
98 let state_key = raw_event
102 .get_field::<String>("state_key")
103 .ok()
104 .flatten()
105 .map(|state_key| self.encode_key(keys::EVENTS, state_key));
106
107 let content = self.encode_value(serialized)?;
109
110 Ok(EncodedEvent {
111 content,
112 rel_type,
113 state_key,
114 relates_to: relates_to
115 .map(|relates_to| self.encode_event_id(keys::EVENTS, &relates_to)),
116 })
117 }
118
119 fn decode_event(&self, raw_encoded_event: &[u8]) -> Result<Event> {
120 Ok(serde_json::from_slice(&self.decode_value(raw_encoded_event)?)?)
121 }
122
123 fn encode_event_id(&self, table_name: &str, event_id: &EventId) -> Key {
126 self.encode_key(table_name, event_id)
127 }
128
129 fn encode_room_id(&self, table_name: &str, room_id: &RoomId) -> Key {
131 self.encode_key(table_name, room_id)
132 }
133
134 fn encode_linked_chunk(&self, table_name: &str, linked_chunk_id: &LinkedChunkId<'_>) -> Key {
136 self.encode_key(table_name, linked_chunk_id.storage_key())
137 }
138
139 fn encode_thread_id(&self, thread_id: &EventId) -> Result<Vec<u8>> {
141 self.encode_value(String::from(thread_id.as_str()))
142 }
143
144 #[cfg(test)]
146 fn decode_thread_id(&self, encoded_thread_id: &[u8]) -> Result<OwnedEventId> {
147 let as_slice = self.decode_value(encoded_thread_id)?;
148 let as_str = str::from_utf8(as_slice.as_ref())?;
149
150 Ok(EventId::parse(as_str)?)
151 }
152
153 fn encode_thread_info(&self, thread_info: &ThreadInfo) -> Result<Vec<u8>> {
155 self.encode_value(serde_json::to_vec(thread_info)?)
156 }
157
158 fn decode_thread_info(&self, encoded_thread_info: &[u8]) -> Result<ThreadInfo> {
160 Ok(serde_json::from_slice(&self.decode_value(encoded_thread_info)?)?)
161 }
162}
163
164impl EncryptableStore for Encryption {
165 fn get_cypher(&self) -> Option<&StoreCipher> {
166 self.cipher.as_ref()
167 }
168}
169
170#[derive(Clone)]
172pub struct SqliteEventCacheStore {
173 encryption: Arc<Encryption>,
175
176 connections: Arc<SqliteConnections>,
178
179 db_path: PathBuf,
181
182 pool_config: PoolConfig,
184
185 runtime_config: RuntimeConfig,
187}
188
189#[cfg(not(tarpaulin_include))]
190impl fmt::Debug for SqliteEventCacheStore {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 f.debug_struct("SqliteEventCacheStore").finish_non_exhaustive()
193 }
194}
195
196impl SqliteEventCacheStore {
197 pub async fn open(
200 path: impl AsRef<Path>,
201 passphrase: Option<&str>,
202 ) -> Result<Self, OpenStoreError> {
203 Self::open_with_config(&SqliteStoreConfig::new(path).passphrase(passphrase)).await
204 }
205
206 pub async fn open_with_key(
209 path: impl AsRef<Path>,
210 key: Option<&[u8]>,
211 ) -> Result<Self, OpenStoreError> {
212 Self::open_with_config(&SqliteStoreConfig::new(path).key(key)).await
213 }
214
215 #[instrument(skip(config), fields(path = ?config.path))]
217 pub async fn open_with_config(config: &SqliteStoreConfig) -> Result<Self, OpenStoreError> {
218 debug!(?config);
219
220 let _timer = timer!("open_with_config");
221
222 fs::create_dir_all(&config.path).await.map_err(OpenStoreError::CreateDir)?;
223
224 let db_path = config.path.join(DATABASE_NAME);
225 let pool_config = config.pool_config();
226 let runtime_config = config.runtime_config();
227
228 let pool = config.build_pool_of_connections(DATABASE_NAME)?;
229
230 let this =
231 Self::open_with_pool(pool, db_path, pool_config, runtime_config, config.secret.clone())
232 .await?;
233
234 this.write().await?.apply_runtime_config(runtime_config).await?;
236
237 Ok(this)
238 }
239
240 async fn open_with_pool(
243 pool: SqlitePool,
244 db_path: PathBuf,
245 pool_config: PoolConfig,
246 runtime_config: RuntimeConfig,
247 secret: Option<Secret>,
248 ) -> Result<Self, OpenStoreError> {
249 let conn = pool.get().await?;
250
251 let version = conn.db_version().await?;
252
253 run_migrations(&conn, version).await?;
254
255 conn.wal_checkpoint().await;
256
257 let cipher = match secret {
258 Some(s) => Some(conn.get_or_create_store_cipher(s).await?),
259 None => None,
260 };
261
262 let connections = SqliteConnectionsInner {
263 pool,
264 write_connection: Arc::new(Mutex::new(conn)),
266 };
267
268 Ok(Self {
269 encryption: Arc::new(Encryption { cipher }),
270 connections: Arc::new(SqliteConnections::new(connections).await),
271 db_path,
272 pool_config,
273 runtime_config,
274 })
275 }
276
277 #[instrument(skip_all)]
279 async fn read(&self) -> Result<SqliteAsyncConn> {
280 let pool = {
281 let guard = self.connections.lock().await;
282 let conns = guard.as_ref().ok_or(Error::StoreClosed)?;
283 conns.pool.clone()
284 };
285
286 let connection = pool.get().await?;
287
288 connection.execute_batch("PRAGMA foreign_keys = ON;").await?;
293
294 Ok(connection)
295 }
296
297 #[instrument(skip_all)]
299 async fn write(&self) -> Result<OwnedMutexGuard<SqliteAsyncConn>> {
300 let write_connection = {
301 let guard = self.connections.lock().await;
302 let conns = guard.as_ref().ok_or(Error::StoreClosed)?;
303 conns.write_connection.clone()
304 };
305
306 let connection = write_connection.lock_owned().await;
307
308 connection.execute_batch("PRAGMA busy_timeout = 2000;").await?;
316
317 connection.execute_batch("PRAGMA foreign_keys = ON;").await?;
322
323 Ok(connection)
324 }
325
326 fn map_row_to_chunk(
327 row: &rusqlite::Row<'_>,
328 ) -> Result<(u64, Option<u64>, Option<u64>, String), rusqlite::Error> {
329 Ok((
330 row.get::<_, u64>(0)?,
331 row.get::<_, Option<u64>>(1)?,
332 row.get::<_, Option<u64>>(2)?,
333 row.get::<_, String>(3)?,
334 ))
335 }
336
337 pub async fn vacuum(&self) -> Result<()> {
338 let write_connection = {
339 let guard = self.connections.lock().await;
340 let conns = guard.as_ref().ok_or(Error::StoreClosed)?;
341 conns.write_connection.clone()
342 };
343 write_connection.lock().await.vacuum().await
344 }
345
346 async fn get_db_size(&self) -> Result<Option<usize>> {
347 let pool = {
348 let guard = self.connections.lock().await;
349 let conns = guard.as_ref().ok_or(Error::StoreClosed)?;
350 conns.pool.clone()
351 };
352 Ok(Some(pool.get().await?.get_db_size().await?))
353 }
354
355 pub async fn close(&self) -> Result<()> {
356 connection::close_connections(&self.connections, "Event cache store").await;
357 Ok(())
358 }
359
360 pub async fn reopen(&self) -> Result<()> {
361 connection::reopen_connections(
362 &self.connections,
363 self.db_path.clone(),
364 self.pool_config,
365 self.runtime_config,
366 )
367 .await?;
368 Ok(())
369 }
370
371 #[cfg(test)]
373 async fn pool_max_size(&self) -> Option<usize> {
374 let guard = self.connections.lock().await;
375 guard.as_ref().map(|conns| conns.pool.status().max_size)
376 }
377}
378
379struct EncodedEvent {
380 content: Vec<u8>,
381 rel_type: Option<String>,
382 relates_to: Option<Key>,
383 state_key: Option<Key>,
386}
387
388trait TransactionExtForLinkedChunks {
389 fn rebuild_chunk(
390 &self,
391 encryption: &Encryption,
392 linked_chunk_id: &Key,
393 previous: Option<u64>,
394 index: u64,
395 next: Option<u64>,
396 chunk_type: &str,
397 ) -> Result<RawChunk<Event, Gap>>;
398
399 fn load_gap_content(
400 &self,
401 encryption: &Encryption,
402 linked_chunk_id: &Key,
403 chunk_id: ChunkIdentifier,
404 ) -> Result<Gap>;
405
406 fn load_events_content(
407 &self,
408 encryption: &Encryption,
409 linked_chunk_id: &Key,
410 chunk_id: ChunkIdentifier,
411 ) -> Result<Vec<Event>>;
412}
413
414impl TransactionExtForLinkedChunks for Transaction<'_> {
415 fn rebuild_chunk(
416 &self,
417 encryption: &Encryption,
418 linked_chunk_id: &Key,
419 previous: Option<u64>,
420 id: u64,
421 next: Option<u64>,
422 chunk_type: &str,
423 ) -> Result<RawChunk<Event, Gap>> {
424 let previous = previous.map(ChunkIdentifier::new);
425 let next = next.map(ChunkIdentifier::new);
426 let id = ChunkIdentifier::new(id);
427
428 match chunk_type {
429 CHUNK_TYPE_GAP_TYPE_STRING => {
430 let gap = self.load_gap_content(encryption, linked_chunk_id, id)?;
432 Ok(RawChunk { content: ChunkContent::Gap(gap), previous, identifier: id, next })
433 }
434
435 CHUNK_TYPE_EVENT_TYPE_STRING => {
436 let events = self.load_events_content(encryption, linked_chunk_id, id)?;
438 Ok(RawChunk {
439 content: ChunkContent::Items(events),
440 previous,
441 identifier: id,
442 next,
443 })
444 }
445
446 other => {
447 Err(Error::InvalidData {
449 details: format!("a linked chunk has an unknown type {other}"),
450 })
451 }
452 }
453 }
454
455 fn load_gap_content(
456 &self,
457 encryption: &Encryption,
458 linked_chunk_id: &Key,
459 chunk_id: ChunkIdentifier,
460 ) -> Result<Gap> {
461 let encoded_prev_token: Vec<u8> = self.query_one(
464 "SELECT prev_token FROM gap_chunks WHERE chunk_id = ? AND linked_chunk_id = ?",
465 (chunk_id.index(), &linked_chunk_id),
466 |row| row.get(0),
467 )?;
468 let prev_token_bytes = encryption.decode_value(&encoded_prev_token)?;
469 let prev_token = String::from_utf8(prev_token_bytes.into_owned())?;
470 Ok(Gap { token: prev_token })
471 }
472
473 fn load_events_content(
474 &self,
475 encryption: &Encryption,
476 linked_chunk_id: &Key,
477 chunk_id: ChunkIdentifier,
478 ) -> Result<Vec<Event>> {
479 let mut events = Vec::new();
481
482 for event_data in self
483 .prepare(
484 "SELECT events.content \
485 FROM event_chunks ec, events \
486 WHERE events.event_id = ec.event_id AND ec.chunk_id = ? AND ec.linked_chunk_id = ? \
487 ORDER BY ec.position ASC",
488 )?
489 .query_map((chunk_id.index(), &linked_chunk_id), |row| row.get::<_, Vec<u8>>(0))?
490 {
491 events.push(encryption.decode_event(&event_data?)?);
492 }
493
494 Ok(events)
495 }
496}
497
498async fn run_migrations(conn: &SqliteAsyncConn, version: u8) -> Result<()> {
500 conn.execute_batch("PRAGMA foreign_keys = ON;").await?;
502
503 if version < 1 {
504 debug!("Creating database");
505 conn.execute_batch("PRAGMA journal_mode = wal;").await?;
509 conn.with_immediate_transaction(|txn| {
510 txn.execute_batch(include_str!("../migrations/event_cache_store/001_init.sql"))?;
511 txn.set_db_version(1)
512 })
513 .await?;
514 }
515
516 if version < 2 {
517 debug!("Upgrading database to version 2");
518 conn.with_immediate_transaction(|txn| {
519 txn.execute_batch(include_str!("../migrations/event_cache_store/002_lease_locks.sql"))?;
520 txn.set_db_version(2)
521 })
522 .await?;
523 }
524
525 if version < 3 {
526 debug!("Upgrading database to version 3");
527 conn.with_immediate_transaction(|txn| {
528 txn.execute_batch(include_str!("../migrations/event_cache_store/003_events.sql"))?;
529 txn.set_db_version(3)
530 })
531 .await?;
532 }
533
534 if version < 4 {
535 debug!("Upgrading database to version 4");
536 conn.with_immediate_transaction(|txn| {
537 txn.execute_batch(include_str!(
538 "../migrations/event_cache_store/004_ignore_policy.sql"
539 ))?;
540 txn.set_db_version(4)
541 })
542 .await?;
543 }
544
545 if version < 5 {
546 debug!("Upgrading database to version 5");
547 conn.with_immediate_transaction(|txn| {
548 txn.execute_batch(include_str!(
549 "../migrations/event_cache_store/005_events_index_on_event_id.sql"
550 ))?;
551 txn.set_db_version(5)
552 })
553 .await?;
554 }
555
556 if version < 6 {
557 debug!("Upgrading database to version 6");
558 conn.with_immediate_transaction(|txn| {
559 txn.execute_batch(include_str!("../migrations/event_cache_store/006_events.sql"))?;
560 txn.set_db_version(6)
561 })
562 .await?;
563 }
564
565 if version < 7 {
566 debug!("Upgrading database to version 7");
567 conn.with_immediate_transaction(|txn| {
568 txn.execute_batch(include_str!(
569 "../migrations/event_cache_store/007_event_chunks.sql"
570 ))?;
571 txn.set_db_version(7)
572 })
573 .await?;
574 }
575
576 if version < 8 {
577 debug!("Upgrading database to version 8");
578 conn.with_immediate_transaction(|txn| {
579 txn.execute_batch(include_str!(
580 "../migrations/event_cache_store/008_linked_chunk_id.sql"
581 ))?;
582 txn.set_db_version(8)
583 })
584 .await?;
585 }
586
587 if version < 9 {
588 debug!("Upgrading database to version 9");
589 conn.with_immediate_transaction(|txn| {
590 txn.execute_batch(include_str!(
591 "../migrations/event_cache_store/009_related_event_index.sql"
592 ))?;
593 txn.set_db_version(9)
594 })
595 .await?;
596 }
597
598 if version < 10 {
599 debug!("Upgrading database to version 10");
600 conn.with_immediate_transaction(|txn| {
601 txn.execute_batch(include_str!("../migrations/event_cache_store/010_drop_media.sql"))?;
602 txn.set_db_version(10)
603 })
604 .await?;
605
606 if version >= 1 {
607 conn.vacuum().await?;
610 }
611 }
612
613 if version < 11 {
614 debug!("Upgrading database to version 11");
615 conn.with_immediate_transaction(|txn| {
616 txn.execute_batch(include_str!(
617 "../migrations/event_cache_store/011_empty_event_cache.sql"
618 ))?;
619 txn.set_db_version(11)
620 })
621 .await?;
622 }
623
624 if version < 12 {
625 debug!("Upgrading database to version 12");
626 conn.with_immediate_transaction(|txn| {
627 txn.execute_batch(include_str!(
628 "../migrations/event_cache_store/012_store_event_type.sql"
629 ))?;
630 txn.set_db_version(12)
631 })
632 .await?;
633 }
634
635 if version < 13 {
636 debug!("Upgrading database to version 13");
637 conn.with_immediate_transaction(|txn| {
638 txn.execute_batch(include_str!(
639 "../migrations/event_cache_store/013_lease_locks_with_generation.sql"
640 ))?;
641 txn.set_db_version(13)
642 })
643 .await?;
644 }
645
646 if version < 14 {
647 debug!("Upgrading database to version 14");
648 conn.with_immediate_transaction(|txn| {
649 txn.execute_batch(include_str!(
650 "../migrations/event_cache_store/014_event_chunks_event_id_index.sql"
651 ))?;
652 txn.set_db_version(14)
653 })
654 .await?;
655 }
656
657 if version < 15 {
658 debug!("Upgrading database to version 15");
659 conn.with_immediate_transaction(|txn| {
660 txn.execute_batch(include_str!(
661 "../migrations/event_cache_store/015_event_ids_are_encoded.sql"
662 ))?;
663 txn.set_db_version(15)
664 })
665 .await?;
666 }
667
668 if version < 16 {
669 debug!("Upgrading database to version 16");
670 conn.with_immediate_transaction(|txn| {
671 txn.execute_batch(include_str!("../migrations/event_cache_store/016_threads.sql"))?;
672 txn.set_db_version(16)
673 })
674 .await?;
675 }
676
677 if version < 17 {
678 debug!("Upgrading database to version 17");
679 conn.with_immediate_transaction(|txn| {
680 txn.execute_batch(include_str!(
681 "../migrations/event_cache_store/017_threads_with_thread_infos.sql"
682 ))?;
683 txn.set_db_version(17)
684 })
685 .await?;
686 }
687
688 if version < 18 {
689 debug!("Upgrading database to version 18");
690 conn.with_immediate_transaction(|txn| {
691 txn.execute_batch(include_str!("../migrations/event_cache_store/018_event_chunks_unique_linked_chunk_id_event_id.sql"))?;
692 txn.set_db_version(18)
693 })
694 .await?;
695 }
696
697 if version < 19 {
698 debug!("Upgrading database to version 19");
699 conn.with_immediate_transaction(|txn| {
700 txn.execute_batch(include_str!(
701 "../migrations/event_cache_store/019_events_timestamp.sql"
702 ))?;
703 txn.set_db_version(19)
704 })
705 .await?;
706 }
707
708 if version < 20 {
709 debug!("Upgrading database to version 20");
710 conn.with_immediate_transaction(|txn| {
711 txn.execute_batch(include_str!(
712 "../migrations/event_cache_store/020_events_state_key.sql"
713 ))?;
714 txn.set_db_version(20)
715 })
716 .await?;
717 }
718
719 if version < 21 {
720 debug!("Upgrading database to version 21");
721 conn.with_immediate_transaction(|txn| {
722 txn.execute_batch(include_str!(
723 "../migrations/event_cache_store/021_events_room_session_index.sql"
724 ))?;
725 txn.set_db_version(21)
726 })
727 .await?;
728 }
729
730 Ok(())
731}
732
733#[async_trait]
734impl EventCacheStore for SqliteEventCacheStore {
735 type Error = Error;
736
737 #[instrument(skip(self))]
738 async fn try_take_leased_lock(
739 &self,
740 lease_duration_ms: u32,
741 key: &str,
742 holder: &str,
743 ) -> Result<Option<CrossProcessLockGeneration>> {
744 let key = key.to_owned();
745 let holder = holder.to_owned();
746
747 let now: u64 = MilliSecondsSinceUnixEpoch::now().get().into();
748 let expiration = now + lease_duration_ms as u64;
749
750 let generation = self
752 .write()
753 .await?
754 .with_immediate_transaction(move |txn| {
755 txn.query_one(
756 "INSERT INTO lease_locks (key, holder, expiration) \
757 VALUES (?1, ?2, ?3) \
758 ON CONFLICT (key) \
759 DO \
760 UPDATE SET \
761 holder = excluded.holder, \
762 expiration = excluded.expiration, \
763 generation = \
764 CASE holder \
765 WHEN excluded.holder THEN generation \
766 ELSE generation + 1 \
767 END \
768 WHERE \
769 holder = excluded.holder \
770 OR expiration < ?4 \
771 RETURNING generation",
772 (key, holder, expiration, now),
773 |row| row.get(0),
774 )
775 .optional()
776 })
777 .await?;
778
779 Ok(generation)
780 }
781
782 #[instrument(skip(self, updates))]
783 async fn handle_linked_chunk_updates(
784 &self,
785 linked_chunk_id: LinkedChunkId<'_>,
786 updates: Vec<Update<Event, Gap>>,
787 ) -> Result<(), Self::Error> {
788 let _timer = timer!("method");
789
790 let hashed_linked_chunk_id =
791 self.encryption.encode_linked_chunk(keys::LINKED_CHUNKS, &linked_chunk_id);
792 let hashed_room_id =
793 self.encryption.encode_room_id(keys::EVENTS, linked_chunk_id.room_id());
794 let encryption = self.encryption.clone();
795
796 self.write().await?.with_immediate_transaction::<_, Self::Error, _>(move |txn| {
799 for update in updates {
800 match update {
801 Update::NewItemsChunk { previous, new, next } => {
802 let previous = previous.as_ref().map(ChunkIdentifier::index);
803 let new = new.index();
804 let next = next.as_ref().map(ChunkIdentifier::index);
805
806 trace!("new events chunk (prev={previous:?}, i={new}, next={next:?})");
807
808 insert_chunk(
809 txn,
810 &hashed_linked_chunk_id,
811 previous,
812 new,
813 next,
814 CHUNK_TYPE_EVENT_TYPE_STRING,
815 )?;
816 }
817
818 Update::NewGapChunk { previous, new, next, gap } => {
819 let hashed_prev_token = encryption.encode_value(gap.token)?;
820
821 let previous = previous.as_ref().map(ChunkIdentifier::index);
822 let new = new.index();
823 let next = next.as_ref().map(ChunkIdentifier::index);
824
825 trace!("new gap chunk (prev={previous:?}, i={new}, next={next:?})");
826
827 insert_chunk(
829 txn,
830 &hashed_linked_chunk_id,
831 previous,
832 new,
833 next,
834 CHUNK_TYPE_GAP_TYPE_STRING,
835 )?;
836
837 txn.execute(
839 r#"
840 INSERT INTO gap_chunks(chunk_id, linked_chunk_id, prev_token)
841 VALUES (?, ?, ?)
842 "#,
843 (new, &hashed_linked_chunk_id, hashed_prev_token),
844 )?;
845 }
846
847 Update::RemoveChunk(chunk_identifier) => {
848 let chunk_id = chunk_identifier.index();
849
850 trace!("removing chunk @ {chunk_id}");
851
852 let (previous, next): (Option<usize>, Option<usize>) = txn.query_one(
854 "SELECT previous, next FROM linked_chunks WHERE id = ? AND linked_chunk_id = ?",
855 (chunk_id, &hashed_linked_chunk_id),
856 |row| Ok((row.get(0)?, row.get(1)?))
857 )?;
858
859 if let Some(previous) = previous {
861 txn.execute("UPDATE linked_chunks SET next = ? WHERE id = ? AND linked_chunk_id = ?", (next, previous, &hashed_linked_chunk_id))?;
862 }
863
864 if let Some(next) = next {
866 txn.execute("UPDATE linked_chunks SET previous = ? WHERE id = ? AND linked_chunk_id = ?", (previous, next, &hashed_linked_chunk_id))?;
867 }
868
869 txn.execute("DELETE FROM linked_chunks WHERE id = ? AND linked_chunk_id = ?", (chunk_id, &hashed_linked_chunk_id))?;
872 }
873
874 Update::PushItems { at, items } => {
875 if items.is_empty() {
876 continue;
878 }
879
880 let chunk_id = at.chunk_identifier().index();
881
882 trace!("pushing {} items @ {chunk_id}", items.len());
883
884 let mut chunk_statement = txn.prepare(
885 "INSERT INTO event_chunks(chunk_id, linked_chunk_id, event_id, position) VALUES (?, ?, ?, ?)"
886 )?;
887
888 let mut content_statement = txn.prepare(
895 "INSERT OR REPLACE INTO events(room_id, event_id, event_type, session_id, content, relates_to, rel_type, timestamp, state_key) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
896 )?;
897
898 let invalid_event = |event: TimelineEvent| {
899 let Some(event_id) = event.event_id() else {
900 error!("Trying to push an event with no ID");
901 return None;
902 };
903
904 let Some(event_type) = event.kind.event_type() else {
905 error!(%event_id, "Trying to save an event with no event type");
906 return None;
907 };
908
909 Some((event_id.to_owned(), event_type, event))
910 };
911
912 for (i, (event_id, event_type, event)) in items.into_iter().filter_map(invalid_event).enumerate() {
913 let hashed_event_id = encryption.encode_event_id(
914 keys::EVENTS,
920 &event_id,
921 );
922
923 {
925 let index = at.index() + i;
926
927 chunk_statement.execute((chunk_id, &hashed_linked_chunk_id, &hashed_event_id, index))?;
928 }
929
930 {
932 let hashed_session_id = event.kind.session_id().map(|s| encryption.encode_key(keys::EVENTS, s));
933 let hashed_event_type = encryption.encode_key(keys::EVENTS, event_type);
934 let timestamp = event.timestamp.map(|ts| u64::from(ts.get()));
935 let encoded_event = encryption.encode_event(&event)?;
936
937 content_statement.execute((
938 &hashed_room_id,
939 &hashed_event_id,
940 hashed_event_type,
941 hashed_session_id,
942 encoded_event.content,
943 encoded_event.relates_to,
944 encoded_event.rel_type,
945 timestamp,
946 encoded_event.state_key,
947 ))?;
948 }
949 }
950 }
951
952 Update::ReplaceItem { at, item: event } => {
953 let chunk_id = at.chunk_identifier().index();
954 let index = at.index();
955
956 trace!("replacing item @ {chunk_id}:{index}");
957
958 let Some(event_id) = event.event_id().map(|event_id| event_id.to_owned()) else {
960 error!("Trying to replace an event with a new one that has no ID");
961 continue;
962 };
963
964 let Some(event_type) = event.kind.event_type() else {
965 error!(%event_id, "Trying to save an event with no event type");
966 continue;
967 };
968
969 let hashed_event_id = encryption.encode_event_id(keys::EVENTS, &event_id);
970
971 {
979 let hashed_session_id = event.kind.session_id().map(|s| encryption.encode_key(keys::EVENTS, s));
980 let hashed_event_type = encryption.encode_key(keys::EVENTS, event_type);
981 let encoded_event = encryption.encode_event(&event)?;
982
983 let timestamp = event.timestamp.map(|ts| u64::from(ts.get()));
984 txn.execute(
985 "INSERT OR REPLACE INTO events(room_id, event_id, event_type, session_id, content, relates_to, rel_type, timestamp, state_key) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
986 (
987 &hashed_room_id,
988 &hashed_event_id,
989 hashed_event_type,
990 hashed_session_id,
991 encoded_event.content,
992 encoded_event.relates_to,
993 encoded_event.rel_type,
994 timestamp,
995 encoded_event.state_key,
996 ),
997 )?;
998 }
999
1000 {
1002 txn.execute(
1004 r#"UPDATE event_chunks SET event_id = ? WHERE linked_chunk_id = ? AND chunk_id = ? AND position = ?"#,
1005 (&hashed_event_id, &hashed_linked_chunk_id, chunk_id, index)
1006 )?;
1007 }
1008 }
1009
1010 Update::RemoveItem { at } => {
1011 let chunk_id = at.chunk_identifier().index();
1012 let index = at.index();
1013
1014 trace!("removing item @ {chunk_id}:{index}");
1015
1016 txn.execute("DELETE FROM event_chunks WHERE linked_chunk_id = ? AND chunk_id = ? AND position = ?", (&hashed_linked_chunk_id, chunk_id, index))?;
1018
1019 txn.execute(
1120 r#"
1121 UPDATE event_chunks
1122 SET position = -(position - 1)
1123 WHERE linked_chunk_id = ? AND chunk_id = ? AND position > ?
1124 "#,
1125 (&hashed_linked_chunk_id, chunk_id, index)
1126 )?;
1127 txn.execute(
1128 r#"
1129 UPDATE event_chunks
1130 SET position = -position
1131 WHERE position < 0 AND linked_chunk_id = ? AND chunk_id = ?
1132 "#,
1133 (&hashed_linked_chunk_id, chunk_id)
1134 )?;
1135
1136 }
1139
1140 Update::DetachLastItems { at } => {
1141 let chunk_id = at.chunk_identifier().index();
1142 let index = at.index();
1143
1144 trace!("truncating items >= {chunk_id}:{index}");
1145
1146 txn.execute("DELETE FROM event_chunks WHERE linked_chunk_id = ? AND chunk_id = ? AND position >= ?", (&hashed_linked_chunk_id, chunk_id, index))?;
1148
1149 }
1152
1153 Update::Clear => {
1154 trace!("clearing items");
1155
1156 txn.execute(
1158 "DELETE FROM linked_chunks WHERE linked_chunk_id = ?",
1159 (&hashed_linked_chunk_id,),
1160 )?;
1161
1162 }
1165
1166 Update::StartReattachItems | Update::EndReattachItems => {
1167 }
1169 }
1170 }
1171
1172 Ok(())
1173 })
1174 .await?;
1175
1176 Ok(())
1177 }
1178
1179 #[instrument(skip(self))]
1180 async fn load_all_chunks(
1181 &self,
1182 linked_chunk_id: LinkedChunkId<'_>,
1183 ) -> Result<Vec<RawChunk<Event, Gap>>, Self::Error> {
1184 let _timer = timer!("method");
1185
1186 let hashed_linked_chunk_id =
1187 self.encryption.encode_linked_chunk(keys::LINKED_CHUNKS, &linked_chunk_id);
1188 let encryption = self.encryption.clone();
1189
1190 let result = self
1191 .read()
1192 .await?
1193 .with_transaction(move |txn| -> Result<_> {
1194 let mut items = Vec::new();
1195
1196 for data in txn
1198 .prepare(
1199 "SELECT id, previous, next, type FROM linked_chunks WHERE linked_chunk_id = ? ORDER BY id",
1200 )?
1201 .query_map((&hashed_linked_chunk_id,), Self::map_row_to_chunk)?
1202 {
1203 let (id, previous, next, chunk_type) = data?;
1204 let new = txn.rebuild_chunk(
1205 &encryption,
1206 &hashed_linked_chunk_id,
1207 previous,
1208 id,
1209 next,
1210 chunk_type.as_str(),
1211 )?;
1212 items.push(new);
1213 }
1214
1215 Ok(items)
1216 })
1217 .await?;
1218
1219 Ok(result)
1220 }
1221
1222 #[instrument(skip(self))]
1223 async fn load_all_chunks_metadata(
1224 &self,
1225 linked_chunk_id: LinkedChunkId<'_>,
1226 ) -> Result<Vec<ChunkMetadata>, Self::Error> {
1227 let _timer = timer!("method");
1228
1229 let hashed_linked_chunk_id =
1230 self.encryption.encode_linked_chunk(keys::LINKED_CHUNKS, &linked_chunk_id);
1231
1232 self.read()
1233 .await?
1234 .with_transaction(move |txn| -> Result<_> {
1235 let num_events_by_chunk_ids = txn
1268 .prepare(
1269 "SELECT ec.chunk_id, COUNT(ec.event_id) \
1270 FROM event_chunks as ec \
1271 WHERE ec.linked_chunk_id = ? \
1272 GROUP BY ec.chunk_id",
1273 )?
1274 .query_map((&hashed_linked_chunk_id,), |row| {
1275 Ok((row.get::<_, u64>(0)?, row.get::<_, usize>(1)?))
1276 })?
1277 .collect::<Result<HashMap<_, _>, _>>()?;
1278
1279 txn.prepare(
1280 "SELECT \
1281 lc.id, \
1282 lc.previous, \
1283 lc.next, \
1284 lc.type \
1285 FROM linked_chunks as lc \
1286 WHERE lc.linked_chunk_id = ? \
1287 ORDER BY lc.id",
1288 )?
1289 .query_map((&hashed_linked_chunk_id,), |row| {
1290 Ok((
1291 row.get::<_, u64>(0)?,
1292 row.get::<_, Option<u64>>(1)?,
1293 row.get::<_, Option<u64>>(2)?,
1294 row.get::<_, String>(3)?,
1295 ))
1296 })?
1297 .map(|data| -> Result<_> {
1298 let (id, previous, next, chunk_type) = data?;
1299
1300 let num_items = if chunk_type == CHUNK_TYPE_GAP_TYPE_STRING {
1307 0
1308 } else {
1309 num_events_by_chunk_ids.get(&id).copied().unwrap_or(0)
1310 };
1311
1312 Ok(ChunkMetadata {
1313 identifier: ChunkIdentifier::new(id),
1314 previous: previous.map(ChunkIdentifier::new),
1315 next: next.map(ChunkIdentifier::new),
1316 num_items,
1317 })
1318 })
1319 .collect::<Result<Vec<_>, _>>()
1320 })
1321 .await
1322 }
1323
1324 #[instrument(skip(self))]
1325 async fn load_last_chunk(
1326 &self,
1327 linked_chunk_id: LinkedChunkId<'_>,
1328 ) -> Result<(Option<RawChunk<Event, Gap>>, ChunkIdentifierGenerator), Self::Error> {
1329 let _timer = timer!("method");
1330
1331 let hashed_linked_chunk_id =
1332 self.encryption.encode_linked_chunk(keys::LINKED_CHUNKS, &linked_chunk_id);
1333 let encryption = self.encryption.clone();
1334
1335 self
1336 .read()
1337 .await?
1338 .with_transaction(move |txn| -> Result<_> {
1339 let (observed_max_identifier, number_of_chunks) = txn
1341 .prepare(
1342 "SELECT MAX(id), COUNT(*) FROM linked_chunks WHERE linked_chunk_id = ?"
1343 )?
1344 .query_one(
1345 (&hashed_linked_chunk_id,),
1346 |row| {
1347 Ok((
1348 row.get::<_, Option<u64>>(0)?,
1353 row.get::<_, u64>(1)?,
1354 ))
1355 }
1356 )?;
1357
1358 let chunk_identifier_generator = match observed_max_identifier {
1359 Some(max_observed_identifier) => {
1360 ChunkIdentifierGenerator::new_from_previous_chunk_identifier(
1361 ChunkIdentifier::new(max_observed_identifier)
1362 )
1363 },
1364 None => ChunkIdentifierGenerator::new_from_scratch(),
1365 };
1366
1367 let Some((chunk_identifier, previous_chunk, chunk_type)) = txn
1369 .prepare(
1370 "SELECT id, previous, type FROM linked_chunks WHERE linked_chunk_id = ? AND next IS NULL"
1371 )?
1372 .query_one(
1373 (&hashed_linked_chunk_id,),
1374 |row| {
1375 Ok((
1376 row.get::<_, u64>(0)?,
1377 row.get::<_, Option<u64>>(1)?,
1378 row.get::<_, String>(2)?,
1379 ))
1380 }
1381 )
1382 .optional()?
1383 else {
1384 if number_of_chunks == 0 {
1387 return Ok((None, chunk_identifier_generator));
1388 }
1389 else {
1396 return Err(Error::InvalidData {
1397 details:
1398 "last chunk is not found but chunks exist: the linked chunk contains a cycle"
1399 .to_owned()
1400 }
1401 )
1402 }
1403 };
1404
1405 let last_chunk = txn.rebuild_chunk(
1407 &encryption,
1408 &hashed_linked_chunk_id,
1409 previous_chunk,
1410 chunk_identifier,
1411 None,
1412 &chunk_type
1413 )?;
1414
1415 Ok((Some(last_chunk), chunk_identifier_generator))
1416 })
1417 .await
1418 }
1419
1420 #[instrument(skip(self))]
1421 async fn load_previous_chunk(
1422 &self,
1423 linked_chunk_id: LinkedChunkId<'_>,
1424 before_chunk_identifier: ChunkIdentifier,
1425 ) -> Result<Option<RawChunk<Event, Gap>>, Self::Error> {
1426 let _timer = timer!("method");
1427
1428 let hashed_linked_chunk_id =
1429 self.encryption.encode_linked_chunk(keys::LINKED_CHUNKS, &linked_chunk_id);
1430 let encryption = self.encryption.clone();
1431
1432 self
1433 .read()
1434 .await?
1435 .with_transaction(move |txn| -> Result<_> {
1436 let Some((chunk_identifier, previous_chunk, next_chunk, chunk_type)) = txn
1438 .prepare(
1439 "SELECT id, previous, next, type FROM linked_chunks WHERE linked_chunk_id = ? AND next = ?"
1440 )?
1441 .query_one(
1442 (&hashed_linked_chunk_id, before_chunk_identifier.index()),
1443 |row| {
1444 Ok((
1445 row.get::<_, u64>(0)?,
1446 row.get::<_, Option<u64>>(1)?,
1447 row.get::<_, Option<u64>>(2)?,
1448 row.get::<_, String>(3)?,
1449 ))
1450 }
1451 )
1452 .optional()?
1453 else {
1454 return Ok(None);
1456 };
1457
1458 let last_chunk = txn.rebuild_chunk(
1460 &encryption,
1461 &hashed_linked_chunk_id,
1462 previous_chunk,
1463 chunk_identifier,
1464 next_chunk,
1465 &chunk_type
1466 )?;
1467
1468 Ok(Some(last_chunk))
1469 })
1470 .await
1471 }
1472
1473 async fn load_thread_info(
1474 &self,
1475 room_id: &RoomId,
1476 thread_id: &EventId,
1477 insert_default_if_missing: bool,
1478 ) -> Result<Option<ThreadInfo>, Self::Error> {
1479 let linked_chunk_id = LinkedChunkId::Thread(room_id, thread_id);
1480 let hashed_linked_chunk_id =
1481 self.encryption.encode_linked_chunk(keys::LINKED_CHUNKS, &linked_chunk_id);
1482 let encryption = self.encryption.clone();
1483
1484 let maybe_thread_info = self
1489 .read()
1490 .await?
1491 .with_transaction(move |txn| {
1492 let maybe_encoded_thread_info = txn
1493 .query_one(
1494 "SELECT info FROM threads WHERE linked_chunk_id = ?",
1495 (hashed_linked_chunk_id,),
1496 |row| row.get::<_, Vec<u8>>(0),
1497 )
1498 .optional()?;
1499
1500 maybe_encoded_thread_info
1501 .map(|encoded_thread_info| {
1502 encryption.decode_thread_info(encoded_thread_info.as_slice())
1503 })
1504 .transpose()
1505 })
1506 .await?;
1507
1508 if let Some(thread_info) = maybe_thread_info {
1509 return Ok(Some(thread_info));
1510 } else if !insert_default_if_missing {
1511 return Ok(None);
1513 }
1514
1515 let thread_info = ThreadInfo::default();
1518 let hashed_linked_chunk_id =
1519 self.encryption.encode_linked_chunk(keys::LINKED_CHUNKS, &linked_chunk_id);
1520 let hashed_room_id = self.encryption.encode_room_id(keys::EVENTS, room_id);
1521 let hashed_thread_id = self.encryption.encode_thread_id(thread_id)?;
1522 let encoded_thread_id = self.encryption.encode_thread_info(&thread_info)?;
1523
1524 self.write()
1525 .await?
1526 .with_immediate_transaction(move |txn| {
1527 txn.execute(
1528 "INSERT INTO threads VALUES (?, ?, ?, ?)",
1529 (hashed_linked_chunk_id, hashed_room_id, hashed_thread_id, encoded_thread_id),
1530 )?;
1531
1532 Ok::<(), Self::Error>(())
1533 })
1534 .await?;
1535
1536 Ok(Some(thread_info))
1537 }
1538
1539 async fn update_thread_info(
1540 &self,
1541 room_id: &RoomId,
1542 thread_id: &EventId,
1543 thread_info: &ThreadInfo,
1544 ) -> Result<(), Self::Error> {
1545 let hashed_linked_chunk_id = self
1546 .encryption
1547 .encode_linked_chunk(keys::LINKED_CHUNKS, &LinkedChunkId::Thread(room_id, thread_id));
1548 let encoded_thread_info = self.encryption.encode_thread_info(thread_info)?;
1549
1550 self.write()
1551 .await?
1552 .with_immediate_transaction(move |txn| {
1553 txn.execute(
1554 "UPDATE threads SET info = ? WHERE linked_chunk_id = ?",
1555 (encoded_thread_info, hashed_linked_chunk_id),
1556 )?;
1557
1558 Ok(())
1559 })
1560 .await
1561 }
1562
1563 #[instrument(skip(self))]
1564 async fn clear_all_events(&self, room_id: Option<&RoomId>) -> Result<(), Self::Error> {
1565 let _timer = timer!("method");
1566
1567 match room_id {
1568 None => {
1570 self.write()
1571 .await?
1572 .with_immediate_transaction(move |txn| {
1573 txn.execute("DELETE FROM linked_chunks", ())?;
1575
1576 txn.execute("DELETE FROM events", ())?;
1579
1580 Ok(())
1581 })
1582 .await
1583 }
1584
1585 Some(room_id) => {
1587 let encryption = self.encryption.clone();
1588 let room_id = room_id.to_owned();
1589
1590 self.write()
1591 .await?
1592 .with_immediate_transaction(move |txn| {
1593 {
1595 let mut delete =
1596 txn.prepare("DELETE FROM linked_chunks WHERE linked_chunk_id = ?")?;
1597
1598 for linked_chunk_id in
1599 [LinkedChunkId::Room(&room_id), LinkedChunkId::PinnedEvents(&room_id)]
1600 {
1601 let linked_chunk_id = encryption.encode_linked_chunk(keys::LINKED_CHUNKS, &linked_chunk_id);
1602
1603 delete.execute((&linked_chunk_id,))?;
1607 }
1608 }
1609
1610 let encoded_room_id = encryption.encode_room_id(keys::EVENTS, &room_id);
1611
1612 {
1614 txn.execute(
1615 "DELETE FROM linked_chunks WHERE linked_chunk_id IN (SELECT linked_chunk_id FROM threads WHERE room_id = ?)",
1616 (&encoded_room_id,),
1617 )?;
1618 }
1619
1620 txn.execute(
1622 "DELETE FROM events WHERE room_id = ?",
1623 (encoded_room_id,),
1624 )?;
1625
1626 Ok(())
1627 })
1628 .await
1629 }
1630 }
1631 }
1632
1633 #[instrument(skip(self, event_ids))]
1634 async fn filter_duplicated_events(
1635 &self,
1636 linked_chunk_id: LinkedChunkId<'_>,
1637 event_ids: Vec<OwnedEventId>,
1638 ) -> Result<Vec<(OwnedEventId, Position)>, Self::Error> {
1639 let _timer = timer!("method");
1640
1641 if event_ids.is_empty() {
1645 return Ok(Vec::new());
1646 }
1647
1648 let hashed_linked_chunk_id =
1650 self.encryption.encode_linked_chunk(keys::LINKED_CHUNKS, &linked_chunk_id);
1651 let event_ids_and_hashed_event_ids = event_ids
1652 .into_iter()
1653 .map(|event_id| {
1654 let hashed_event_id = self.encryption.encode_event_id(
1655 keys::EVENTS,
1660 &event_id,
1661 );
1662
1663 (event_id, hashed_event_id)
1664 })
1665 .collect::<Vec<_>>();
1666
1667 self.read()
1668 .await?
1669 .with_transaction(move |txn| -> Result<_> {
1670 txn.chunk_large_query_over(
1671 event_ids_and_hashed_event_ids,
1672 None,
1673 move |txn, event_ids_and_hashed_event_ids| {
1674 let query = format!(
1675 "SELECT event_id, chunk_id, position \
1676 FROM event_chunks \
1677 WHERE linked_chunk_id = ? AND event_id IN ({}) \
1678 ORDER BY chunk_id ASC, position ASC",
1679 event_ids_and_hashed_event_ids.host_parameters(),
1680 );
1681
1682 let parameters = params_from_iter(
1683 once(
1685 hashed_linked_chunk_id
1686 .to_sql()
1687 .unwrap(),
1689 )
1690 .chain(
1692 event_ids_and_hashed_event_ids.iter().map(
1693 |(_event_id, hashed_event_id)| {
1694 hashed_event_id
1695 .to_sql()
1696 .unwrap()
1699 },
1700 ),
1701 ),
1702 );
1703
1704 let mut duplicated_events = Vec::new();
1705
1706 for duplicated_event in
1707 txn.prepare(&query)?.query_map(parameters, |row| {
1708 Ok((
1709 row.get::<_, Vec<u8>>(0)?,
1710 row.get::<_, u64>(1)?,
1711 row.get::<_, usize>(2)?,
1712 ))
1713 })?
1714 {
1715 let (duplicated_hashed_event_id, chunk_identifier, index) =
1716 duplicated_event?;
1717
1718 let Some(duplicated_event_id) = event_ids_and_hashed_event_ids
1723 .iter()
1724 .find_map(|(event_id, hashed_event_id)| {
1725 (hashed_event_id.deref() == duplicated_hashed_event_id)
1726 .then_some(event_id.clone())
1727 })
1728 else {
1729 error!(
1730 "Unreachable: found a duplicated event that was not requested"
1731 );
1732 continue;
1733 };
1734
1735 duplicated_events.push((
1736 duplicated_event_id,
1737 Position::new(ChunkIdentifier::new(chunk_identifier), index),
1738 ));
1739 }
1740
1741 Ok(duplicated_events)
1742 },
1743 )
1744 })
1745 .await
1746 }
1747
1748 #[instrument(skip(self, event_id))]
1749 async fn find_event(
1750 &self,
1751 room_id: &RoomId,
1752 event_id: &EventId,
1753 ) -> Result<Option<Event>, Self::Error> {
1754 let _timer = timer!("method");
1755
1756 let encryption = self.encryption.clone();
1757
1758 let hashed_room_id = self.encryption.encode_room_id(keys::EVENTS, room_id);
1759 let hashed_event_id = self.encryption.encode_event_id(keys::EVENTS, event_id);
1760
1761 self.read()
1762 .await?
1763 .with_transaction(move |txn| -> Result<_> {
1764 let Some(event) = txn
1765 .prepare("SELECT content FROM events WHERE event_id = ? AND room_id = ?")?
1766 .query_one((hashed_event_id, hashed_room_id), |row| row.get::<_, Vec<u8>>(0))
1767 .optional()?
1768 else {
1769 return Ok(None);
1771 };
1772
1773 Ok(Some(encryption.decode_event(&event)?))
1774 })
1775 .await
1776 }
1777
1778 #[instrument(skip(self, event_id, filters))]
1779 async fn find_event_relations(
1780 &self,
1781 room_id: &RoomId,
1782 event_id: &EventId,
1783 filters: Option<&[RelationType]>,
1784 ) -> Result<Vec<(Event, Option<Position>)>, Self::Error> {
1785 let _timer = timer!("method");
1786
1787 let hashed_room_id = self.encryption.encode_room_id(keys::EVENTS, room_id);
1788 let hashed_linked_chunk_id =
1789 self.encryption.encode_linked_chunk(keys::LINKED_CHUNKS, &LinkedChunkId::Room(room_id));
1790 let hashed_event_id = self.encryption.encode_event_id(keys::EVENTS, event_id);
1791
1792 let filters = filters.map(ToOwned::to_owned);
1793 let encryption = self.encryption.clone();
1794
1795 self.read()
1796 .await?
1797 .with_transaction(move |txn| -> Result<_> {
1798 find_event_relations_transaction(
1799 &encryption,
1800 hashed_room_id,
1801 hashed_linked_chunk_id,
1802 hashed_event_id,
1803 filters,
1804 txn,
1805 )
1806 })
1807 .await
1808 }
1809
1810 #[instrument(skip(self))]
1811 async fn find_events_before_timestamp(
1812 &self,
1813 room_id: &RoomId,
1814 cutoff_ms: u64,
1815 ) -> Result<Vec<Event>, Self::Error> {
1816 let _timer = timer!("method");
1817
1818 let encryption = self.encryption.clone();
1819 let hashed_room_id = self.encryption.encode_room_id(keys::EVENTS, room_id);
1820
1821 self.read()
1822 .await?
1823 .with_transaction(move |txn| -> Result<_> {
1824 let mut results = Vec::new();
1825 let mut statement = txn.prepare(
1826 "SELECT content \
1827 FROM events \
1828 WHERE room_id = ? AND timestamp < ? \
1829 ORDER BY timestamp ASC",
1830 )?;
1831 let rows = statement
1832 .query_map((&hashed_room_id, cutoff_ms), |row| row.get::<_, Vec<u8>>(0))?;
1833
1834 for row in rows {
1835 let event = encryption.decode_event(&row?)?;
1836 results.push(event);
1837 }
1838
1839 Ok(results)
1840 })
1841 .await
1842 }
1843
1844 #[instrument(skip(self))]
1845 async fn get_room_events(
1846 &self,
1847 room_id: &RoomId,
1848 event_type: Option<&str>,
1849 session_id: Option<&str>,
1850 ) -> Result<Vec<Event>, Self::Error> {
1851 let _timer = timer!("method");
1852
1853 let encryption = self.encryption.clone();
1854
1855 let hashed_room_id = self.encryption.encode_room_id(keys::EVENTS, room_id);
1856 let hashed_event_type = event_type.map(|e| self.encryption.encode_key(keys::EVENTS, e));
1857 let hashed_session_id = session_id.map(|s| self.encryption.encode_key(keys::EVENTS, s));
1858
1859 self.read()
1860 .await?
1861 .with_transaction(move |txn| -> Result<_> {
1862 #[allow(clippy::redundant_clone)]
1867 let (query, keys) = match (hashed_event_type, hashed_session_id) {
1868 (None, None) => {
1869 ("SELECT content FROM events WHERE room_id = ?", params![hashed_room_id])
1870 }
1871 (None, Some(session_id)) => (
1872 "SELECT content FROM events WHERE room_id = ?1 AND session_id = ?2",
1873 params![hashed_room_id, session_id.to_owned()],
1874 ),
1875 (Some(event_type), None) => (
1876 "SELECT content FROM events WHERE room_id = ? AND event_type = ?",
1877 params![hashed_room_id, event_type.to_owned()]
1878 ),
1879 (Some(event_type), Some(session_id)) => (
1880 "SELECT content FROM events WHERE room_id = ?1 AND event_type = ?2 AND session_id = ?3",
1881 params![hashed_room_id, event_type.to_owned(), session_id.to_owned()],
1882 ),
1883 };
1884
1885 let mut statement = txn.prepare(query)?;
1886
1887 statement
1888 .query_map(keys, |row| row.get::<_, Vec<u8>>(0))?
1889 .map(|maybe_encoded_event| {
1890 encryption.decode_event(&maybe_encoded_event?)
1891 })
1892 .collect::<Result<Vec<_>>>()
1893 })
1894 .await
1895 }
1896
1897 #[instrument(skip(self, event))]
1898 async fn save_event(&self, room_id: &RoomId, event: Event) -> Result<(), Self::Error> {
1899 let _timer = timer!("method");
1900
1901 let Some(event_id) = event.event_id() else {
1902 error!("Trying to save an event with no ID");
1903 return Ok(());
1904 };
1905
1906 let Some(event_type) = event.kind.event_type() else {
1907 error!(%event_id, "Trying to save an event with no event type");
1908 return Ok(());
1909 };
1910
1911 let hashed_event_type = self.encryption.encode_key(keys::EVENTS, event_type);
1912 let hashed_session_id =
1913 event.kind.session_id().map(|s| self.encryption.encode_key(keys::EVENTS, s));
1914
1915 let hashed_room_id = self.encryption.encode_room_id(keys::EVENTS, room_id);
1916 let hashed_event_id = self.encryption.encode_event_id(keys::EVENTS, event_id);
1917 let encoded_event = self.encryption.encode_event(&event)?;
1918
1919 self.write()
1920 .await?
1921 .with_immediate_transaction(move |txn| -> Result<_> {
1922 let timestamp = event.timestamp.map(|ts| u64::from(ts.get()));
1923 txn.execute(
1924 "INSERT OR REPLACE INTO events(room_id, event_id, event_type, session_id, content, relates_to, rel_type, timestamp, state_key) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
1925 (
1926 &hashed_room_id,
1927 hashed_event_id,
1928 hashed_event_type,
1929 hashed_session_id,
1930 encoded_event.content,
1931 encoded_event.relates_to,
1932 encoded_event.rel_type,
1933 timestamp,
1934 encoded_event.state_key,
1935 )
1936 )?;
1937
1938 Ok(())
1939 })
1940 .await
1941 }
1942
1943 async fn close(&self) -> Result<(), Self::Error> {
1944 SqliteEventCacheStore::close(self).await
1945 }
1946
1947 async fn reopen(&self) -> Result<(), Self::Error> {
1948 SqliteEventCacheStore::reopen(self).await
1949 }
1950
1951 async fn optimize(&self) -> Result<(), Self::Error> {
1952 Ok(self.vacuum().await?)
1953 }
1954
1955 async fn get_size(&self) -> Result<Option<usize>, Self::Error> {
1956 self.get_db_size().await
1957 }
1958}
1959
1960fn find_event_relations_transaction(
1961 encryption: &Encryption,
1962 hashed_room_id: Key,
1963 hashed_linked_chunk_id: Key,
1964 hashed_event_id: Key,
1965 filters: Option<Vec<RelationType>>,
1966 txn: &Transaction<'_>,
1967) -> Result<Vec<(Event, Option<Position>)>> {
1968 let get_rows = |row: &rusqlite::Row<'_>| {
1969 Ok((
1970 row.get::<_, Vec<u8>>(0)?,
1971 row.get::<_, Option<u64>>(1)?,
1972 row.get::<_, Option<usize>>(2)?,
1973 ))
1974 };
1975
1976 let collect_results = |transaction| {
1978 let mut related = Vec::new();
1979
1980 for result in transaction {
1981 let (event, chunk_id, index): (Vec<u8>, Option<u64>, _) = result?;
1982 let event = encryption.decode_event(&event)?;
1983
1984 let pos = chunk_id
1988 .zip(index)
1989 .map(|(chunk_id, index)| Position::new(ChunkIdentifier::new(chunk_id), index));
1990
1991 related.push((event, pos));
1992 }
1993
1994 Ok(related)
1995 };
1996
1997 if let Some(filters) = filters
1998 && filters.is_empty().not()
1999 {
2000 let query = format!(
2001 "SELECT events.content, event_chunks.chunk_id, event_chunks.position \
2002 FROM events \
2003 LEFT JOIN event_chunks ON events.event_id = event_chunks.event_id AND event_chunks.linked_chunk_id = ? \
2004 WHERE events.relates_to = ? AND events.room_id = ? AND events.rel_type IN ({})",
2005 host_parameters(filters.len())
2006 );
2007
2008 let filter_strings: Vec<_> = filters.iter().map(|f| f.to_string()).collect();
2013 let filters_params: Vec<_> = filter_strings
2014 .iter()
2015 .map(|f| f.to_sql().expect("converting a string to SQL should work"))
2016 .collect();
2017
2018 let parameters = params_from_iter(
2019 [
2020 hashed_linked_chunk_id.to_sql().expect(
2021 "We should be able to convert a hashed linked chunk ID to a SQLite value",
2022 ),
2023 hashed_event_id
2024 .to_sql()
2025 .expect("We should be able to convert an event ID to a SQLite value"),
2026 hashed_room_id
2027 .to_sql()
2028 .expect("We should be able to convert a room ID to a SQLite value"),
2029 ]
2030 .into_iter()
2031 .chain(filters_params),
2032 );
2033
2034 let mut transaction = txn.prepare(&query)?;
2035 let transaction = transaction.query_map(parameters, get_rows)?;
2036
2037 collect_results(transaction)
2038 } else {
2039 let query = "SELECT events.content, event_chunks.chunk_id, event_chunks.position \
2040 FROM events \
2041 LEFT JOIN event_chunks ON events.event_id = event_chunks.event_id AND event_chunks.linked_chunk_id = ? \
2042 WHERE events.relates_to = ? AND events.room_id = ?";
2043 let parameters = (hashed_linked_chunk_id, hashed_event_id, hashed_room_id);
2044
2045 let mut transaction = txn.prepare(query)?;
2046 let transaction = transaction.query_map(parameters, get_rows)?;
2047
2048 collect_results(transaction)
2049 }
2050}
2051
2052fn insert_chunk(
2053 txn: &Transaction<'_>,
2054 linked_chunk_id: &Key,
2055 previous: Option<u64>,
2056 new: u64,
2057 next: Option<u64>,
2058 type_str: &str,
2059) -> rusqlite::Result<()> {
2060 txn.execute(
2062 r#"
2063 INSERT INTO linked_chunks(id, linked_chunk_id, previous, next, type)
2064 VALUES (?, ?, ?, ?, ?)
2065 "#,
2066 (new, linked_chunk_id, previous, next, type_str),
2067 )?;
2068
2069 if let Some(previous) = previous {
2071 let updated = txn.execute(
2072 r#"
2073 UPDATE linked_chunks
2074 SET next = ?
2075 WHERE id = ? AND linked_chunk_id = ?
2076 "#,
2077 (new, previous, linked_chunk_id),
2078 )?;
2079 if updated < 1 {
2080 return Err(rusqlite::Error::QueryReturnedNoRows);
2081 }
2082 if updated > 1 {
2083 return Err(rusqlite::Error::QueryReturnedMoreThanOneRow);
2084 }
2085 }
2086
2087 if let Some(next) = next {
2089 let updated = txn.execute(
2090 r#"
2091 UPDATE linked_chunks
2092 SET previous = ?
2093 WHERE id = ? AND linked_chunk_id = ?
2094 "#,
2095 (new, next, linked_chunk_id),
2096 )?;
2097 if updated < 1 {
2098 return Err(rusqlite::Error::QueryReturnedNoRows);
2099 }
2100 if updated > 1 {
2101 return Err(rusqlite::Error::QueryReturnedMoreThanOneRow);
2102 }
2103 }
2104
2105 Ok(())
2106}
2107
2108#[cfg(test)]
2109mod tests {
2110 use std::{
2111 path::PathBuf,
2112 sync::{
2113 LazyLock,
2114 atomic::{AtomicU32, Ordering::SeqCst},
2115 },
2116 };
2117
2118 use assert_matches::assert_matches;
2119 use matrix_sdk_base::{
2120 event_cache::store::{
2121 EventCacheStore, EventCacheStoreError, IntoEventCacheStore,
2122 integration_tests::EventCacheStoreIntegrationTests,
2123 },
2124 event_cache_store_integration_tests, event_cache_store_integration_tests_time,
2125 linked_chunk::{ChunkIdentifier, LinkedChunkId, Update},
2126 };
2127 use matrix_sdk_test::{TestRoom, User, async_test, event_factory::EventFactory};
2128 use ruma::{EventId, OwnedEventId, event_id, room_id};
2129 use tempfile::{TempDir, tempdir};
2130
2131 use super::{SqliteEventCacheStore, keys};
2132 use crate::{
2133 SqliteStoreConfig,
2134 utils::{EncryptableStore, SqliteAsyncConnExt},
2135 };
2136
2137 static TMP_DIR: LazyLock<TempDir> = LazyLock::new(|| tempdir().unwrap());
2138 static NUM: AtomicU32 = AtomicU32::new(0);
2139
2140 fn new_event_cache_store_workspace() -> PathBuf {
2141 let name = NUM.fetch_add(1, SeqCst).to_string();
2142 TMP_DIR.path().join(name)
2143 }
2144
2145 async fn get_event_cache_store() -> Result<SqliteEventCacheStore, EventCacheStoreError> {
2146 let tmpdir_path = new_event_cache_store_workspace();
2147
2148 tracing::info!("using event cache store @ {}", tmpdir_path.to_str().unwrap());
2149
2150 Ok(SqliteEventCacheStore::open(tmpdir_path.to_str().unwrap(), None).await.unwrap())
2151 }
2152
2153 event_cache_store_integration_tests!();
2154 event_cache_store_integration_tests_time!();
2155
2156 #[async_test]
2157 async fn test_encryption_encode_decode_thread_id_roundtrip() {
2158 let store = get_event_cache_store().await.expect("creating cache store failed");
2159 let thread_id: OwnedEventId = event_id!("$event").to_owned();
2160
2161 let encoded_thread_id = store.encryption.encode_thread_id(&thread_id).unwrap();
2162 let decoded_thread_id: OwnedEventId =
2163 store.encryption.decode_thread_id(&encoded_thread_id).unwrap();
2164
2165 assert_eq!(thread_id, decoded_thread_id);
2166 }
2167
2168 #[async_test]
2169 async fn test_state_key_column() {
2170 let store = get_event_cache_store().await.expect("creating cache store failed");
2171
2172 let room_id = room_id!("!test:localhost");
2173 let f = EventFactory::new().room(room_id).sender(User::Alice);
2174
2175 let message_id = event_id!("$message");
2176 let empty_state_key_ev_id = event_id!("$empty_state_key");
2177 let state_key_ev_id = event_id!("$state_key");
2178 let state_key = User::Bob.as_str();
2179
2180 store
2182 .save_event(room_id, f.text_msg("hello").event_id(message_id).into_event())
2183 .await
2184 .unwrap();
2185 store
2187 .save_event(
2188 room_id,
2189 f.room_topic("topic").state_key("").event_id(empty_state_key_ev_id).into_event(),
2190 )
2191 .await
2192 .unwrap();
2193 store
2196 .save_event(room_id, f.member(User::Bob).event_id(state_key_ev_id).into_event())
2197 .await
2198 .unwrap();
2199
2200 let stored_state_key = async |event_id: &EventId| -> Option<Vec<u8>> {
2201 let hashed_event_id = store.encryption.encode_event_id(keys::EVENTS, event_id);
2202 store
2203 .read()
2204 .await
2205 .unwrap()
2206 .with_transaction(move |txn| {
2207 txn.query_one(
2208 "SELECT state_key FROM events WHERE event_id = ?",
2209 (hashed_event_id,),
2210 |row| row.get::<_, Option<Vec<u8>>>(0),
2211 )
2212 })
2213 .await
2214 .unwrap()
2215 };
2216 let encoded_state_key =
2217 |state_key: &str| store.encryption.encode_key(keys::EVENTS, state_key).to_vec();
2218
2219 assert_eq!(stored_state_key(message_id).await, None);
2220 assert_eq!(stored_state_key(empty_state_key_ev_id).await, Some(encoded_state_key("")));
2221 assert_eq!(stored_state_key(state_key_ev_id).await, Some(encoded_state_key(state_key)));
2222 }
2223
2224 #[async_test]
2225 async fn test_pool_size() {
2226 let tmpdir_path = new_event_cache_store_workspace();
2227 let store_open_config = SqliteStoreConfig::new(tmpdir_path).pool_max_size(42);
2228
2229 let store = SqliteEventCacheStore::open_with_config(&store_open_config).await.unwrap();
2230
2231 assert_eq!(store.pool_max_size().await, Some(42));
2232 }
2233
2234 #[async_test]
2235 async fn test_linked_chunk_remove_chunk() {
2236 let store = get_event_cache_store().await.expect("creating cache store failed");
2237
2238 store.clone().into_event_cache_store().test_linked_chunk_remove_chunk().await;
2240
2241 let gaps = store
2243 .read()
2244 .await
2245 .unwrap()
2246 .with_transaction(|txn| -> rusqlite::Result<_> {
2247 let mut gaps = Vec::new();
2248 for data in txn
2249 .prepare("SELECT chunk_id FROM gap_chunks ORDER BY chunk_id")?
2250 .query_map((), |row| row.get::<_, u64>(0))?
2251 {
2252 gaps.push(data?);
2253 }
2254 Ok(gaps)
2255 })
2256 .await
2257 .unwrap();
2258
2259 assert_eq!(gaps, vec![42, 44]);
2262 }
2263
2264 #[async_test]
2265 async fn test_linked_chunk_remove_item() {
2266 let store = get_event_cache_store().await.expect("creating cache store failed");
2267
2268 store.clone().into_event_cache_store().test_linked_chunk_remove_item().await;
2270
2271 let hashed_linked_chunk_id = store.encryption.encode_linked_chunk(
2272 keys::LINKED_CHUNKS,
2273 &LinkedChunkId::Room(TestRoom::Default.into()),
2274 );
2275
2276 let num_rows: u64 = store
2278 .read()
2279 .await
2280 .unwrap()
2281 .with_transaction(move |txn| {
2282 txn.query_one(
2283 "SELECT COUNT(*) FROM event_chunks WHERE chunk_id = 42 AND linked_chunk_id = ? AND position IN (2, 3, 4)",
2284 (hashed_linked_chunk_id,),
2285 |row| row.get(0),
2286 )
2287 })
2288 .await
2289 .unwrap();
2290 assert_eq!(num_rows, 3);
2291 }
2292
2293 #[async_test]
2294 async fn test_linked_chunk_clear() {
2295 let store = get_event_cache_store().await.expect("creating cache store failed");
2296
2297 store.clone().into_event_cache_store().test_linked_chunk_clear().await;
2299
2300 store
2302 .read()
2303 .await
2304 .unwrap()
2305 .with_transaction(|txn| -> rusqlite::Result<_> {
2306 let num_gaps = txn
2307 .prepare("SELECT COUNT(chunk_id) FROM gap_chunks ORDER BY chunk_id")?
2308 .query_one((), |row| row.get::<_, u64>(0))?;
2309 assert_eq!(num_gaps, 0);
2310
2311 let num_events = txn
2312 .prepare("SELECT COUNT(event_id) FROM event_chunks ORDER BY chunk_id")?
2313 .query_one((), |row| row.get::<_, u64>(0))?;
2314 assert_eq!(num_events, 0);
2315
2316 Ok(())
2317 })
2318 .await
2319 .unwrap();
2320 }
2321
2322 #[async_test]
2323 async fn test_linked_chunk_update_is_a_transaction() {
2324 let store = get_event_cache_store().await.expect("creating cache store failed");
2325
2326 let linked_chunk_id = LinkedChunkId::Room(TestRoom::Default.into());
2327
2328 let err = store
2331 .handle_linked_chunk_updates(
2332 linked_chunk_id,
2333 vec![
2334 Update::NewItemsChunk {
2335 previous: None,
2336 new: ChunkIdentifier::new(42),
2337 next: None,
2338 },
2339 Update::NewItemsChunk {
2340 previous: None,
2341 new: ChunkIdentifier::new(42),
2342 next: None,
2343 },
2344 ],
2345 )
2346 .await
2347 .unwrap_err();
2348
2349 assert_matches!(err, crate::error::Error::Sqlite(err) => {
2351 assert_matches!(err.sqlite_error_code(), Some(rusqlite::ErrorCode::ConstraintViolation));
2352 });
2353
2354 let chunks = store.load_all_chunks(linked_chunk_id).await.unwrap();
2358 assert!(chunks.is_empty());
2359 }
2360}
2361
2362#[cfg(test)]
2363mod encrypted_tests {
2364 use std::sync::{
2365 LazyLock,
2366 atomic::{AtomicU32, Ordering::SeqCst},
2367 };
2368
2369 use matrix_sdk_base::{
2370 event_cache::store::{EventCacheStore, EventCacheStoreError},
2371 event_cache_store_integration_tests, event_cache_store_integration_tests_time,
2372 };
2373 use matrix_sdk_test::{async_test, event_factory::EventFactory};
2374 use ruma::{
2375 event_id,
2376 events::{relation::RelationType, room::message::RoomMessageEventContentWithoutRelation},
2377 room_id, user_id,
2378 };
2379 use tempfile::{TempDir, tempdir};
2380
2381 use super::SqliteEventCacheStore;
2382
2383 static TMP_DIR: LazyLock<TempDir> = LazyLock::new(|| tempdir().unwrap());
2384 static NUM: AtomicU32 = AtomicU32::new(0);
2385
2386 async fn get_event_cache_store() -> Result<SqliteEventCacheStore, EventCacheStoreError> {
2387 let name = NUM.fetch_add(1, SeqCst).to_string();
2388 let tmpdir_path = TMP_DIR.path().join(name);
2389
2390 tracing::info!("using event cache store @ {}", tmpdir_path.to_str().unwrap());
2391
2392 Ok(SqliteEventCacheStore::open(
2393 tmpdir_path.to_str().unwrap(),
2394 Some("default_test_password"),
2395 )
2396 .await
2397 .unwrap())
2398 }
2399
2400 event_cache_store_integration_tests!();
2401 event_cache_store_integration_tests_time!();
2402
2403 #[async_test]
2404 async fn test_no_sqlite_injection_in_find_event_relations() {
2405 let room_id = room_id!("!test:localhost");
2406 let another_room_id = room_id!("!r1:matrix.org");
2407 let sender = user_id!("@alice:localhost");
2408
2409 let store = get_event_cache_store()
2410 .await
2411 .expect("We should be able to create a new, empty, event cache store");
2412
2413 let f = EventFactory::new().room(room_id).sender(sender);
2414
2415 let event_id = event_id!("$DO_NOT_FIND_ME:matrix.org");
2417 let event = f.text_msg("DO NOT FIND").event_id(event_id).into_event();
2418
2419 let edit_id = event_id!("$find_me:matrix.org");
2421 let edit = f
2422 .text_msg("Find me")
2423 .event_id(edit_id)
2424 .edit(event_id, RoomMessageEventContentWithoutRelation::text_plain("jebote"))
2425 .into_event();
2426
2427 let f = f.room(another_room_id);
2429
2430 let another_event_id = event_id!("$DO_NOT_FIND_ME_EITHER:matrix.org");
2431 let another_event =
2432 f.text_msg("DO NOT FIND ME EITHER").event_id(another_event_id).into_event();
2433
2434 store.save_event(room_id, event).await.unwrap();
2436 store.save_event(room_id, edit).await.unwrap();
2437 store.save_event(another_room_id, another_event).await.unwrap();
2438
2439 let filter = Some(vec![RelationType::Replacement, "x\") OR 1=1; --".into()]);
2443
2444 let results = store
2446 .find_event_relations(room_id, event_id, filter.as_deref())
2447 .await
2448 .expect("We should be able to attempt to find event relations");
2449
2450 similar_asserts::assert_eq!(
2453 results.len(),
2454 1,
2455 "We should only have loaded events for the first room {results:#?}"
2456 );
2457
2458 let (found_event, _) = &results[0];
2460 assert_eq!(
2461 found_event.event_id(),
2462 Some(edit_id),
2463 "The single event we found should be the edit event"
2464 );
2465 }
2466}
2467
2468#[cfg(test)]
2469mod close_reopen_tests {
2470 use std::sync::{
2471 LazyLock,
2472 atomic::{AtomicU32, Ordering::SeqCst},
2473 };
2474
2475 use matrix_sdk_base::{event_cache::store::EventCacheStore, linked_chunk::LinkedChunkId};
2476 use matrix_sdk_test::{TestRoom, async_test};
2477 use tempfile::{TempDir, tempdir};
2478
2479 use super::SqliteEventCacheStore;
2480
2481 static TMP_DIR: LazyLock<TempDir> = LazyLock::new(|| tempdir().unwrap());
2482 static NUM: AtomicU32 = AtomicU32::new(0);
2483
2484 async fn new_store() -> SqliteEventCacheStore {
2485 let name = NUM.fetch_add(1, SeqCst).to_string();
2486 let tmpdir_path = TMP_DIR.path().join(name);
2487 SqliteEventCacheStore::open(tmpdir_path, None).await.unwrap()
2488 }
2489
2490 #[async_test]
2491 async fn test_close_completes_without_timeout() {
2492 let store = new_store().await;
2493
2494 let start = std::time::Instant::now();
2496 store.close().await.unwrap();
2497 let elapsed = start.elapsed();
2498
2499 assert!(
2500 elapsed < std::time::Duration::from_secs(2),
2501 "close() took {elapsed:?}, expected < 2s (no timeout)"
2502 );
2503
2504 let guard = store.connections.lock().await;
2506 assert!(guard.is_none(), "connections should be None after close");
2507 }
2508
2509 #[async_test]
2510 async fn test_reopen_restores_connections() {
2511 let store = new_store().await;
2512
2513 store.close().await.unwrap();
2514
2515 {
2516 let guard = store.connections.lock().await;
2517 assert!(guard.is_none());
2518 }
2519
2520 store.reopen().await.unwrap();
2521
2522 {
2523 let guard = store.connections.lock().await;
2524 assert!(guard.is_some(), "connections should be Some after reopen");
2525 }
2526 }
2527
2528 #[async_test]
2529 async fn test_close_is_idempotent() {
2530 let store = new_store().await;
2531
2532 store.close().await.unwrap();
2533 store.close().await.unwrap();
2535
2536 let guard = store.connections.lock().await;
2537 assert!(guard.is_none());
2538 }
2539
2540 #[async_test]
2541 async fn test_reopen_is_idempotent() {
2542 let store = new_store().await;
2543
2544 store.reopen().await.unwrap();
2546
2547 let guard = store.connections.lock().await;
2548 assert!(guard.is_some());
2549 }
2550
2551 #[async_test]
2552 async fn test_read_fails_when_closed() {
2553 let store = new_store().await;
2554 store.close().await.unwrap();
2555
2556 let err = store.load_all_chunks(LinkedChunkId::Room(TestRoom::Default.into())).await;
2557 assert!(err.is_err(), "read should fail when closed");
2558
2559 let err_msg = err.unwrap_err().to_string();
2560 assert!(err_msg.contains("closed"), "error should mention 'closed', got: {err_msg}");
2561 }
2562
2563 #[async_test]
2564 async fn test_write_fails_when_closed() {
2565 let store = new_store().await;
2566 store.close().await.unwrap();
2567
2568 let err = store.try_take_leased_lock(1000, "test_lock", "holder").await;
2569 assert!(err.is_err(), "write should fail when closed");
2570
2571 let err_msg = err.unwrap_err().to_string();
2572 assert!(err_msg.contains("closed"), "error should mention 'closed', got: {err_msg}");
2573 }
2574
2575 #[async_test]
2576 async fn test_data_persists_across_close_reopen() {
2577 let store = new_store().await;
2578
2579 let result = store.try_take_leased_lock(60_000, "test_lock", "holder").await.unwrap();
2581 assert!(result.is_some(), "should have acquired the lock");
2582
2583 store.close().await.unwrap();
2585 store.reopen().await.unwrap();
2586
2587 let result = store.try_take_leased_lock(60_000, "test_lock", "other_holder").await.unwrap();
2589 assert!(result.is_none(), "lock should still be held by the original holder after reopen");
2590 }
2591
2592 #[async_test]
2593 async fn test_multiple_close_reopen_cycles() {
2594 let store = new_store().await;
2595
2596 for _ in 0..5 {
2597 store.close().await.unwrap();
2598 store.reopen().await.unwrap();
2599
2600 let result = store.load_all_chunks(LinkedChunkId::Room(TestRoom::Default.into())).await;
2602 assert!(result.is_ok(), "store should work after close/reopen cycle");
2603 }
2604 }
2605
2606 #[async_test]
2607 async fn test_pool_is_fully_drained_after_close() {
2608 let store = new_store().await;
2609
2610 let _ = store.load_all_chunks(LinkedChunkId::Room(TestRoom::Default.into())).await;
2612 let _ = store.load_all_chunks(LinkedChunkId::Room(TestRoom::Default.into())).await;
2613
2614 store.close().await.unwrap();
2615
2616 let guard = store.connections.lock().await;
2619 assert!(guard.is_none(), "all connections should be released after close");
2620 }
2621
2622 #[async_test]
2623 async fn test_operations_work_immediately_after_reopen() {
2624 let store = new_store().await;
2625
2626 store.close().await.unwrap();
2627 store.reopen().await.unwrap();
2628
2629 let result = store.load_all_chunks(LinkedChunkId::Room(TestRoom::Default.into())).await;
2631 assert!(result.is_ok(), "read should succeed immediately after reopen");
2632
2633 let result = store.try_take_leased_lock(1000, "test_lock", "holder").await;
2635 assert!(result.is_ok(), "write should succeed immediately after reopen");
2636 }
2637
2638 #[async_test]
2639 async fn test_close_waits_for_held_read_connection_to_drain() {
2640 let store = new_store().await;
2641
2642 let held_conn = store.read().await.unwrap();
2644
2645 let store_clone = store.clone();
2648 let close_handle = tokio::spawn(async move {
2649 store_clone.close().await.unwrap();
2650 });
2651
2652 tokio::time::sleep(std::time::Duration::from_millis(200)).await;
2654
2655 assert!(!close_handle.is_finished(), "close should be waiting for the held connection");
2657
2658 drop(held_conn);
2660
2661 let timeout = tokio::time::timeout(std::time::Duration::from_secs(3), close_handle).await;
2663 assert!(timeout.is_ok(), "close should complete after the held connection is released");
2664 timeout.unwrap().unwrap();
2665
2666 let guard = store.connections.lock().await;
2668 assert!(guard.is_none(), "connections should be None after close");
2669 }
2670}