Skip to content

Commit 3e80b03

Browse files
author
dragonfly1033
committed
fixup! fixup! test(sdk): Add integration test for search
1 parent b4069df commit 3e80b03

File tree

8 files changed

+284
-263
lines changed

8 files changed

+284
-263
lines changed

crates/matrix-sdk/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,9 @@ matrix-sdk-base.workspace = true
9292
matrix-sdk-common.workspace = true
9393
matrix-sdk-ffi-macros = { workspace = true, optional = true }
9494
matrix-sdk-indexeddb = { workspace = true, optional = true }
95+
matrix-sdk-search = { workspace = true, optional = true }
9596
matrix-sdk-sqlite = { workspace = true, optional = true }
9697
matrix-sdk-test = { workspace = true, optional = true }
97-
matrix-sdk-search = { workspace = true, optional = true }
9898
mime.workspace = true
9999
mime2ext = "0.1.53"
100100
oauth2.workspace = true

crates/matrix-sdk/src/client/builder/mod.rs

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,8 @@ use homeserver_config::*;
2727
#[cfg(feature = "e2e-encryption")]
2828
use matrix_sdk_base::crypto::DecryptionSettings;
2929
use matrix_sdk_base::{store::StoreConfig, BaseClient, ThreadingSupport};
30-
#[cfg(feature = "experimental-search")]
31-
use matrix_sdk_search::index::RoomIndex;
3230
#[cfg(feature = "sqlite")]
3331
use matrix_sdk_sqlite::SqliteStoreConfig;
34-
#[cfg(feature = "experimental-search")]
35-
use ruma::OwnedRoomId;
3632
use ruma::{
3733
api::{error::FromHttpResponseError, MatrixVersion, SupportedVersions},
3834
OwnedServerName, ServerName,
@@ -42,6 +38,10 @@ use tokio::sync::{broadcast, Mutex, OnceCell};
4238
use tracing::{debug, field::debug, instrument, Span};
4339

4440
use super::{Client, ClientInner};
41+
#[cfg(feature = "experimental-search")]
42+
use crate::client::search::SearchIndex;
43+
#[cfg(feature = "experimental-search")]
44+
use crate::client::search::SearchIndexStoreKind;
4545
#[cfg(feature = "e2e-encryption")]
4646
use crate::crypto::{CollectStrategy, TrustRequirement};
4747
#[cfg(feature = "e2e-encryption")]
@@ -123,7 +123,7 @@ pub struct ClientBuilder {
123123
cross_process_store_locks_holder_name: String,
124124
threading_support: ThreadingSupport,
125125
#[cfg(feature = "experimental-search")]
126-
index_base_dir: IndexBaseDir,
126+
search_index_store_kind: SearchIndexStoreKind,
127127
}
128128

129129
impl ClientBuilder {
@@ -156,7 +156,7 @@ impl ClientBuilder {
156156
Self::DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME.to_owned(),
157157
threading_support: ThreadingSupport::Disabled,
158158
#[cfg(feature = "experimental-search")]
159-
index_base_dir: IndexBaseDir::Ram,
159+
search_index_store_kind: SearchIndexStoreKind::InMemory,
160160
}
161161
}
162162

@@ -503,8 +503,8 @@ impl ClientBuilder {
503503

504504
/// The base directory in which each room's index directory will be stored.
505505
#[cfg(feature = "experimental-search")]
506-
pub fn index_base_directory(mut self, path: IndexBaseDir) -> Self {
507-
self.index_base_dir = path;
506+
pub fn index_base_directory(mut self, path: SearchIndexStoreKind) -> Self {
507+
self.search_index_store_kind = path;
508508
self
509509
}
510510

@@ -610,8 +610,10 @@ impl ClientBuilder {
610610
let latest_events = OnceCell::new();
611611

612612
#[cfg(feature = "experimental-search")]
613-
let room_indexes: Arc<Mutex<HashMap<OwnedRoomId, RoomIndex>>> =
614-
Arc::new(Mutex::new(HashMap::new()));
613+
let room_indexes = Arc::new(Mutex::new(HashMap::new()));
614+
615+
#[cfg(feature = "experimental-search")]
616+
let search_index = SearchIndex::new(room_indexes, self.search_index_store_kind);
615617

616618
let inner = ClientInner::new(
617619
auth_ctx,
@@ -631,9 +633,7 @@ impl ClientBuilder {
631633
self.enable_share_history_on_invite,
632634
self.cross_process_store_locks_holder_name,
633635
#[cfg(feature = "experimental-search")]
634-
room_indexes,
635-
#[cfg(feature = "experimental-search")]
636-
self.index_base_dir,
636+
search_index,
637637
)
638638
.await;
639639

@@ -744,14 +744,6 @@ async fn build_indexeddb_store_config(
744744
panic!("the IndexedDB is only available on the 'wasm32' arch")
745745
}
746746

747-
#[cfg(feature = "experimental-search")]
748-
#[allow(dead_code)]
749-
#[derive(Clone, Debug)]
750-
pub enum IndexBaseDir {
751-
Directory(PathBuf),
752-
Ram,
753-
}
754-
755747
#[derive(Clone, Debug)]
756748
enum HttpConfig {
757749
#[cfg(not(target_family = "wasm"))]

crates/matrix-sdk/src/client/mod.rs

Lines changed: 11 additions & 126 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,6 @@
1414
// See the License for the specific language governing permissions and
1515
// limitations under the License.
1616

17-
#[cfg(feature = "experimental-search")]
18-
use std::collections::HashMap;
1917
use std::{
2018
collections::{btree_map, BTreeMap, BTreeSet},
2119
fmt::{self, Debug},
@@ -40,12 +38,6 @@ use matrix_sdk_base::{
4038
StateStoreDataKey, StateStoreDataValue, SyncOutsideWasm, ThreadingSupport,
4139
};
4240
use matrix_sdk_common::ttl_cache::TtlCache;
43-
#[cfg(feature = "experimental-search")]
44-
use matrix_sdk_search::error::IndexError;
45-
#[cfg(feature = "experimental-search")]
46-
use matrix_sdk_search::index::RoomIndex;
47-
#[cfg(feature = "experimental-search")]
48-
use ruma::events::AnyMessageLikeEvent;
4941
#[cfg(feature = "e2e-encryption")]
5042
use ruma::events::{room::encryption::RoomEncryptionEventContent, InitialStateEvent};
5143
use ruma::{
@@ -80,15 +72,11 @@ use ruma::{
8072
RoomAliasId, RoomId, RoomOrAliasId, ServerName, UInt, UserId,
8173
};
8274
use serde::de::DeserializeOwned;
83-
#[cfg(feature = "experimental-search")]
84-
use tokio::sync::MutexGuard;
8575
use tokio::sync::{broadcast, Mutex, OnceCell, RwLock, RwLockReadGuard};
8676
use tracing::{debug, error, instrument, trace, warn, Instrument, Span};
8777
use url::Url;
8878

8979
use self::futures::SendRequest;
90-
#[cfg(feature = "experimental-search")]
91-
use crate::client::builder::IndexBaseDir;
9280
use crate::{
9381
authentication::{
9482
matrix::MatrixAuth, oauth::OAuth, AuthCtx, AuthData, ReloadSessionCallback,
@@ -123,8 +111,12 @@ use crate::{
123111
mod builder;
124112
pub(crate) mod caches;
125113
pub(crate) mod futures;
114+
#[cfg(feature = "experimental-search")]
115+
pub(crate) mod search;
126116

127117
pub use self::builder::{sanitize_server_name, ClientBuildError, ClientBuilder};
118+
#[cfg(feature = "experimental-search")]
119+
use crate::client::search::SearchIndex;
128120

129121
#[cfg(not(target_family = "wasm"))]
130122
type NotificationHandlerFut = Pin<Box<dyn Future<Output = ()> + Send>>;
@@ -363,13 +355,9 @@ pub(crate) struct ClientInner {
363355
/// [`LatestEvent`]: crate::latest_event::LatestEvent
364356
latest_events: OnceCell<LatestEvents>,
365357

366-
/// HashMap that links each joined room to its RoomIndex
367-
#[cfg(feature = "experimental-search")]
368-
room_indexes: Arc<Mutex<HashMap<OwnedRoomId, RoomIndex>>>,
369-
370-
/// Base directory that stores the directories for each RoomIndex
371358
#[cfg(feature = "experimental-search")]
372-
index_base_dir: IndexBaseDir,
359+
/// Handler for [`RoomIndex`]'s of each room
360+
search_index: SearchIndex,
373361
}
374362

375363
impl ClientInner {
@@ -394,10 +382,7 @@ impl ClientInner {
394382
#[cfg(feature = "e2e-encryption")] encryption_settings: EncryptionSettings,
395383
#[cfg(feature = "e2e-encryption")] enable_share_history_on_invite: bool,
396384
cross_process_store_locks_holder_name: String,
397-
#[cfg(feature = "experimental-search")] room_indexes: Arc<
398-
Mutex<HashMap<OwnedRoomId, RoomIndex>>,
399-
>,
400-
#[cfg(feature = "experimental-search")] index_base_dir: IndexBaseDir,
385+
#[cfg(feature = "experimental-search")] search_index_handler: SearchIndex,
401386
) -> Arc<Self> {
402387
let caches = ClientCaches {
403388
server_info: server_info.into(),
@@ -434,9 +419,7 @@ impl ClientInner {
434419
enable_share_history_on_invite,
435420
server_max_upload_size: Mutex::new(OnceCell::new()),
436421
#[cfg(feature = "experimental-search")]
437-
room_indexes,
438-
#[cfg(feature = "experimental-search")]
439-
index_base_dir,
422+
search_index: search_index_handler,
440423
};
441424

442425
#[allow(clippy::let_and_return)]
@@ -2742,9 +2725,7 @@ impl Client {
27422725
self.inner.enable_share_history_on_invite,
27432726
cross_process_store_locks_holder_name,
27442727
#[cfg(feature = "experimental-search")]
2745-
self.inner.room_indexes.clone(),
2746-
#[cfg(feature = "experimental-search")]
2747-
self.inner.index_base_dir.clone(),
2728+
self.inner.search_index.clone(),
27482729
)
27492730
.await,
27502731
};
@@ -2842,105 +2823,9 @@ impl Client {
28422823
&self.base_client().decryption_settings
28432824
}
28442825

2845-
/// Add [`AnyMessageLikeEvent`] to [`RoomIndex`] of given [`RoomId`]
2846-
#[cfg(feature = "experimental-search")]
2847-
pub async fn index_event(
2848-
&self,
2849-
event: AnyMessageLikeEvent,
2850-
room_id: &RoomId,
2851-
) -> Result<(), IndexError> {
2852-
let mut hash_map = self.inner.room_indexes.lock().await;
2853-
2854-
let result = if let Some(index) = hash_map.get_mut(room_id) {
2855-
index.add_event(event)
2856-
} else {
2857-
self.add_index_impl(room_id, &mut hash_map)?;
2858-
let index = hash_map.get_mut(room_id).expect("key just added");
2859-
index.add_event(event)
2860-
};
2861-
2862-
match result {
2863-
Ok(_) => {}
2864-
Err(IndexError::CannotIndexRedactedMessage)
2865-
| Err(IndexError::EmptyMessage)
2866-
| Err(IndexError::MessageTypeNotSupported) => {
2867-
debug!("failed to parse event for indexing: {result:?}")
2868-
}
2869-
Err(IndexError::TantivyError(err)) => {
2870-
error!("failed to add/commit event to index: {err:?}")
2871-
}
2872-
Err(_) => error!("unexpected error during indexing: {result:?}"),
2873-
};
2874-
Ok(())
2875-
}
2876-
2877-
/// Add [`RoomIndex`] for given [`RoomId`] to room_indexes
28782826
#[cfg(feature = "experimental-search")]
2879-
pub async fn add_index(&self, room_id: &RoomId) -> Result<(), IndexError> {
2880-
let mut hash_map = self.inner.room_indexes.lock().await;
2881-
self.add_index_impl(room_id, &mut hash_map)?;
2882-
Ok(())
2883-
}
2884-
2885-
#[cfg(feature = "experimental-search")]
2886-
fn add_index_impl(
2887-
&self,
2888-
room_id: &RoomId,
2889-
hash_map: &mut MutexGuard<'_, HashMap<OwnedRoomId, RoomIndex>>,
2890-
) -> Result<(), IndexError> {
2891-
if !hash_map.contains_key(room_id) {
2892-
let index = match &self.inner.index_base_dir {
2893-
IndexBaseDir::Directory(path) => RoomIndex::open_or_create(path, room_id)?,
2894-
IndexBaseDir::Ram => RoomIndex::new_in_ram(room_id)?,
2895-
};
2896-
hash_map.insert(room_id.to_owned(), index);
2897-
}
2898-
Ok(())
2899-
}
2900-
2901-
/// Search a [`Room`]'s index for the query and return at most
2902-
/// max_number_of_results results.
2903-
#[cfg(feature = "experimental-search")]
2904-
pub async fn search_index(
2905-
&self,
2906-
query: &str,
2907-
max_number_of_results: usize,
2908-
room_id: &RoomId,
2909-
) -> Option<Vec<OwnedEventId>> {
2910-
let hash_map = self.inner.room_indexes.lock().await;
2911-
if let Some(index) = hash_map.get(room_id) {
2912-
index
2913-
.search(query, max_number_of_results)
2914-
.inspect_err(|err| {
2915-
error!("error occurred while searching index: {err:?}");
2916-
})
2917-
.ok()
2918-
} else {
2919-
warn!("Tried to search in a room with no index");
2920-
None
2921-
}
2922-
}
2923-
2924-
/// Commit a [`Room`]'s [`RoomIndex`]
2925-
#[cfg(feature = "experimental-search")]
2926-
pub async fn commit(&self, room_id: &RoomId) {
2927-
let mut hash_map = self.inner.room_indexes.lock().await;
2928-
if let Some(index) = hash_map.get_mut(room_id) {
2929-
let _ = index.commit().inspect_err(|err| {
2930-
error!("error occurred while committing: {err:?}");
2931-
});
2932-
}
2933-
}
2934-
2935-
/// Commit a [`Room`]'s [`RoomIndex`] and reload searchers
2936-
#[cfg(feature = "experimental-search")]
2937-
pub async fn commit_and_reload(&self, room_id: &RoomId) {
2938-
let mut hash_map = self.inner.room_indexes.lock().await;
2939-
if let Some(index) = hash_map.get_mut(room_id) {
2940-
let _ = index.commit_and_reload().inspect_err(|err| {
2941-
error!("error occurred while committing: {err:?}");
2942-
});
2943-
}
2827+
pub(crate) fn search_index(&self) -> &SearchIndex {
2828+
&self.inner.search_index
29442829
}
29452830

29462831
/// Whether the client is configured to take thread subscriptions (MSC4306

0 commit comments

Comments
 (0)