From e0477fa053868e69ef9ce558964d6627f688b01b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Wed, 6 May 2020 09:38:31 +0200 Subject: [PATCH 01/10] types: Use the released version of ruma-client-api. --- matrix_sdk_types/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix_sdk_types/Cargo.toml b/matrix_sdk_types/Cargo.toml index 9d016f19..9f3e192f 100644 --- a/matrix_sdk_types/Cargo.toml +++ b/matrix_sdk_types/Cargo.toml @@ -13,6 +13,6 @@ version = "0.1.0" [dependencies] js_int = "0.1.5" ruma-api = "0.16.0" -ruma-client-api = { git = "https://github.com/matrix-org/ruma-client-api" } +ruma-client-api = "0.8.0" ruma-events = "0.21.0" ruma-identifiers = "0.16.1" From 39e59792d22042b048718659e00f1fef84e7928f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Wed, 6 May 2020 12:15:15 +0200 Subject: [PATCH 02/10] crypto: Remove the session key in room key events again. --- matrix_sdk_crypto/src/machine.rs | 57 ++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 18 deletions(-) diff --git a/matrix_sdk_crypto/src/machine.rs b/matrix_sdk_crypto/src/machine.rs index b041532a..6c0f6f99 100644 --- a/matrix_sdk_crypto/src/machine.rs +++ b/matrix_sdk_crypto/src/machine.rs @@ -984,7 +984,7 @@ impl OlmMachine { .map_err(|_| EventError::UnsupportedOlmType)?; // Decrypt the OlmMessage and get a Ruma event out of it. - let (mut decrypted_event, signing_key) = self + let (decrypted_event, signing_key) = self .decrypt_olm_message(&event.sender, &content.sender_key, message) .await?; @@ -992,14 +992,23 @@ impl OlmMachine { // Handle the decrypted event, e.g. fetch out Megolm sessions out of // the event. - self.handle_decrypted_to_device_event( - &content.sender_key, - &signing_key, - &mut decrypted_event, - ) - .await?; - - Ok(decrypted_event) + if let Some(event) = self + .handle_decrypted_to_device_event( + &content.sender_key, + &signing_key, + &decrypted_event, + ) + .await? + { + // Some events may have sensitive data e.g. private keys, while we + // wan't to notify our users that a private key was received we + // don't want them to be able to do silly things with it. Handling + // events modifies them and returns a modified one, so replace it + // here if we get one. + Ok(event) + } else { + Ok(decrypted_event) + } } else { warn!("Olm event doesn't contain a ciphertext for our key"); Err(EventError::MissingCiphertext.into()) @@ -1012,7 +1021,7 @@ impl OlmMachine { sender_key: &str, signing_key: &str, event: &mut ToDeviceRoomKey, - ) -> OlmResult<()> { + ) -> OlmResult>> { match event.content.algorithm { Algorithm::MegolmV1AesSha2 => { let session_key = GroupSessionKey(mem::take(&mut event.content.session_key)); @@ -1024,14 +1033,24 @@ impl OlmMachine { session_key, )?; let _ = self.store.save_inbound_group_session(session).await?; - Ok(()) + // TODO ideally we would rewrap the event again just like so + // let event = EventJson::from(ToDeviceEvent::RoomKey(event.clone())); + // This saidly lacks a type once it's serialized again, fix + // this in Ruma. + let mut json = serde_json::to_value(event.clone())?; + json.as_object_mut() + .unwrap() + .insert("type".to_owned(), Value::String("m.room_key".to_owned())); + let event = serde_json::from_value::>(json)?; + + Ok(Some(event)) } _ => { warn!( "Received room key with unsupported key algorithm {}", event.content.algorithm ); - Ok(()) + Ok(None) } } } @@ -1330,25 +1349,26 @@ impl OlmMachine { &mut self, sender_key: &str, signing_key: &str, - event: &mut EventJson, - ) -> OlmResult<()> { + event: &EventJson, + ) -> OlmResult>> { let event = if let Ok(e) = event.deserialize() { e } else { warn!("Decrypted to-device event failed to be parsed correctly"); - return Ok(()); + return Ok(None); }; match event { ToDeviceEvent::RoomKey(mut e) => { - self.add_room_key(sender_key, signing_key, &mut e).await + Ok(self.add_room_key(sender_key, signing_key, &mut e).await?) } ToDeviceEvent::ForwardedRoomKey(e) => { - self.add_forwarded_room_key(sender_key, signing_key, &e) + self.add_forwarded_room_key(sender_key, signing_key, &e)?; + Ok(None) } _ => { warn!("Received a unexpected encrypted to-device event"); - Ok(()) + Ok(None) } } } @@ -2011,6 +2031,7 @@ mod test { if let AnyToDeviceEvent::RoomKey(e) = event.deserialize().unwrap() { assert_eq!(e.sender, alice.user_id); + assert!(e.content.session_key.is_empty()) } else { panic!("Event had the wrong type"); } From 967544bab97c59e00d674750a0d9f634b8c01a34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Wed, 6 May 2020 13:57:58 +0200 Subject: [PATCH 03/10] base_client: Make the base client a bit more threadsafe. This moves the bulk of the sync logic into the base client, to avoid deadlocks while someone tires to send messages from a event callback the base client needed to get a bunch of locks. Ideally the AsyncClient would not need a lock for the base client at all but we're not there yet. --- matrix_sdk/src/async_client.rs | 114 +---------- matrix_sdk/src/base_client.rs | 282 ++++++++++++++++++---------- matrix_sdk/src/models/room.rs | 3 +- matrix_sdk/src/state/mod.rs | 11 +- matrix_sdk/src/state/state_store.rs | 4 +- matrix_sdk/src/test_builder.rs | 2 +- 6 files changed, 203 insertions(+), 213 deletions(-) diff --git a/matrix_sdk/src/async_client.rs b/matrix_sdk/src/async_client.rs index c304b273..f253baa8 100644 --- a/matrix_sdk/src/async_client.rs +++ b/matrix_sdk/src/async_client.rs @@ -17,7 +17,6 @@ use std::collections::BTreeMap; use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; -use std::ops::Deref; use std::result::Result as StdResult; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -339,7 +338,7 @@ impl AsyncClient { /// Returns the rooms this client knows about. /// /// A `HashMap` of room id to `matrix::models::Room` - pub async fn get_rooms(&self) -> HashMap>> { + pub async fn get_rooms(&self) -> Arc>>>> { self.base_client.read().await.joined_rooms.clone() } @@ -645,109 +644,8 @@ impl AsyncClient { let mut response = self.send(request).await?; - let mut updated = false; - for (room_id, room) in &mut response.rooms.join { - let matrix_room = { - let mut client = self.base_client.write().await; - for event in &room.state.events { - if let Ok(e) = event.deserialize() { - if client.receive_joined_state_event(&room_id, &e).await { - updated = true; - } - } - } - - client.get_or_create_room(&room_id).clone() - }; - - // RoomSummary contains information for calculating room name - matrix_room.write().await.set_room_summary(&room.summary); - - // re looping is not ideal here - for event in &mut room.state.events { - if let Ok(e) = event.deserialize() { - let client = self.base_client.read().await; - client.emit_state_event(&room_id, &e).await; - } - } - - for mut event in &mut room.timeline.events { - let decrypted_event = { - let mut client = self.base_client.write().await; - let (decrypt_ev, timeline_update) = client - .receive_joined_timeline_event(room_id, &mut event) - .await; - if timeline_update { - updated = true; - }; - decrypt_ev - }; - - if let Some(e) = decrypted_event { - *event = e; - } - - if let Ok(e) = event.deserialize() { - let client = self.base_client.read().await; - client.emit_timeline_event(&room_id, &e).await; - } - } - - // look at AccountData to further cut down users by collecting ignored users - if let Some(account_data) = &room.account_data { - for account_data in &account_data.events { - { - if let Ok(e) = account_data.deserialize() { - let mut client = self.base_client.write().await; - if client.receive_account_data_event(&room_id, &e).await { - updated = true; - } - client.emit_account_data_event(room_id, &e).await; - } - } - } - } - - // After the room has been created and state/timeline events accounted for we use the room_id of the newly created - // room to add any presence events that relate to a user in the current room. This is not super - // efficient but we need a room_id so we would loop through now or later. - for presence in &mut response.presence.events { - { - if let Ok(e) = presence.deserialize() { - let mut client = self.base_client.write().await; - if client.receive_presence_event(&room_id, &e).await { - updated = true; - } - - client.emit_presence_event(&room_id, &e).await; - } - } - } - - for ephemeral in &mut room.ephemeral.events { - { - if let Ok(e) = ephemeral.deserialize() { - let mut client = self.base_client.write().await; - if client.receive_ephemeral_event(&room_id, &e).await { - updated = true; - } - - client.emit_ephemeral_event(&room_id, &e).await; - } - } - } - - if updated { - if let Some(store) = self.base_client.read().await.state_store.as_ref() { - store - .store_room_state(matrix_room.read().await.deref()) - .await?; - } - } - } - - let mut client = self.base_client.write().await; - client.receive_sync_response(&mut response, updated).await?; + let client = self.base_client.read().await; + client.receive_sync_response(&mut response).await?; Ok(response) } @@ -994,7 +892,7 @@ impl AsyncClient { { let encrypted = { let client = self.base_client.read().await; - let room = client.joined_rooms.get(room_id); + let room = client.get_room(room_id).await; match room { Some(r) => r.read().await.is_encrypted(), @@ -1005,7 +903,7 @@ impl AsyncClient { if encrypted { let missing_sessions = { let client = self.base_client.read().await; - let room = client.joined_rooms.get(room_id); + let room = client.get_room(room_id).await; let room = room.as_ref().unwrap().read().await; let users = room.members.keys(); self.base_client @@ -1158,7 +1056,7 @@ impl AsyncClient { /// Get the current, if any, sync token of the client. /// This will be None if the client didn't sync at least once. pub async fn sync_token(&self) -> Option { - self.base_client.read().await.sync_token.clone() + self.base_client.read().await.sync_token().await } /// Query the server for users device keys. diff --git a/matrix_sdk/src/base_client.rs b/matrix_sdk/src/base_client.rs index 121f7627..4055c5bf 100644 --- a/matrix_sdk/src/base_client.rs +++ b/matrix_sdk/src/base_client.rs @@ -17,6 +17,7 @@ use std::collections::HashMap; #[cfg(feature = "encryption")] use std::collections::{BTreeMap, HashSet}; use std::fmt; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; #[cfg(feature = "encryption")] @@ -37,6 +38,7 @@ use crate::session::Session; use crate::state::{ClientState, StateStore}; use crate::EventEmitter; +use std::ops::Deref; #[cfg(feature = "encryption")] use tokio::sync::Mutex; use tokio::sync::RwLock; @@ -66,13 +68,13 @@ pub struct Client { /// token. pub session: Option, /// The current sync token that should be used for the next sync call. - pub sync_token: Option, + pub sync_token: Arc>>, /// A map of the rooms our user is joined in. - pub joined_rooms: HashMap>>, + pub joined_rooms: Arc>>>>, /// A list of ignored users. - pub ignored_users: Vec, + pub ignored_users: Arc>>, /// The push ruleset for the logged in user. - pub push_ruleset: Option, + pub push_ruleset: Arc>>, /// Any implementor of EventEmitter will act as the callbacks for various /// events. pub event_emitter: Option>, @@ -82,7 +84,7 @@ pub struct Client { /// There is a default implementation `JsonStore` that saves JSON to disk. pub state_store: Option>, /// Does the `Client` need to sync with the state store. - needs_state_store_sync: bool, + needs_state_store_sync: Arc, #[cfg(feature = "encryption")] olm: Arc>>, @@ -117,13 +119,13 @@ impl Client { Ok(Client { session, - sync_token: None, - joined_rooms: HashMap::new(), - ignored_users: Vec::new(), - push_ruleset: None, + sync_token: Arc::new(RwLock::new(None)), + joined_rooms: Arc::new(RwLock::new(HashMap::new())), + ignored_users: Arc::new(RwLock::new(Vec::new())), + push_ruleset: Arc::new(RwLock::new(None)), event_emitter: None, state_store: None, - needs_state_store_sync: true, + needs_state_store_sync: Arc::new(AtomicBool::from(true)), #[cfg(feature = "encryption")] olm: Arc::new(Mutex::new(olm)), }) @@ -143,7 +145,7 @@ impl Client { /// Returns true if the state store has been loaded into the client. pub fn is_state_store_synced(&self) -> bool { - !self.needs_state_store_sync + !self.needs_state_store_sync.load(Ordering::Relaxed) } /// When a client is provided the state store will load state from the `StateStore`. @@ -158,9 +160,9 @@ impl Client { ignored_users, push_ruleset, } = client_state; - self.sync_token = sync_token; - self.ignored_users = ignored_users; - self.push_ruleset = push_ruleset; + *self.sync_token.write().await = sync_token; + *self.ignored_users.write().await = ignored_users; + *self.push_ruleset.write().await = push_ruleset; } else { // return false and continues with a sync request then save the state and create // and populate the files during the sync @@ -168,15 +170,17 @@ impl Client { } let mut rooms = store.load_all_rooms().await?; - self.joined_rooms = rooms - .drain() - .map(|(k, room)| (k, Arc::new(RwLock::new(room)))) - .collect(); + self.joined_rooms = Arc::new(RwLock::new( + rooms + .drain() + .map(|(k, room)| (k, Arc::new(RwLock::new(room)))) + .collect(), + )); - self.needs_state_store_sync = false; + self.needs_state_store_sync.store(false, Ordering::Relaxed); } } - Ok(!self.needs_state_store_sync) + Ok(!self.needs_state_store_sync.load(Ordering::Relaxed)) } /// Receive a login response and update the session of the client. @@ -206,7 +210,7 @@ impl Client { } pub(crate) async fn calculate_room_name(&self, room_id: &RoomId) -> Option { - if let Some(room) = self.joined_rooms.get(room_id) { + if let Some(room) = self.joined_rooms.read().await.get(room_id) { let room = room.read().await; Some(room.room_name.calculate_name(&room.members)) } else { @@ -216,16 +220,17 @@ impl Client { pub(crate) async fn calculate_room_names(&self) -> Vec { let mut res = Vec::new(); - for room in self.joined_rooms.values() { + for room in self.joined_rooms.read().await.values() { let room = room.read().await; res.push(room.room_name.calculate_name(&room.members)) } res } - pub(crate) fn get_or_create_room(&mut self, room_id: &RoomId) -> &mut Arc> { + pub(crate) async fn get_or_create_room(&self, room_id: &RoomId) -> Arc> { #[allow(clippy::or_fun_call)] - self.joined_rooms + let mut rooms = self.joined_rooms.write().await; + rooms .entry(room_id.clone()) .or_insert(Arc::new(RwLock::new(Room::new( room_id, @@ -235,23 +240,24 @@ impl Client { .expect("Receiving events while not being logged in") .user_id, )))) + .clone() } - pub(crate) fn get_room(&self, room_id: &RoomId) -> Option<&Arc>> { - self.joined_rooms.get(room_id) + pub(crate) async fn get_room(&self, room_id: &RoomId) -> Option>> { + self.joined_rooms.read().await.get(room_id).cloned() } /// Handle a m.ignored_user_list event, updating the room state if necessary. /// /// Returns true if the room name changed, false otherwise. - pub(crate) fn handle_ignored_users(&mut self, event: &IgnoredUserListEvent) -> bool { + pub(crate) async fn handle_ignored_users(&self, event: &IgnoredUserListEvent) -> bool { // this avoids cloning every UserId for the eq check - if self.ignored_users.iter().collect::>() + if self.ignored_users.read().await.iter().collect::>() == event.content.ignored_users.iter().collect::>() { false } else { - self.ignored_users = event.content.ignored_users.to_vec(); + *self.ignored_users.write().await = event.content.ignored_users.to_vec(); true } } @@ -259,7 +265,7 @@ impl Client { /// Handle a m.ignored_user_list event, updating the room state if necessary. /// /// Returns true if the room name changed, false otherwise. - pub(crate) fn handle_push_rules(&mut self, event: &PushRulesEvent) -> bool { + pub(crate) async fn handle_push_rules(&self, event: &PushRulesEvent) -> bool { // TODO this is basically a stub // TODO ruma removed PartialEq for evens, so this doesn't work anymore. // Returning always true for now should be ok here since those don't @@ -267,7 +273,7 @@ impl Client { // if self.push_ruleset.as_ref() == Some(&event.content.global) { // false // } else { - self.push_ruleset = Some(event.content.global.clone()); + *self.push_ruleset.write().await = Some(event.content.global.clone()); true // } } @@ -283,7 +289,7 @@ impl Client { /// /// * `event` - The event that should be handled by the client. pub async fn receive_joined_timeline_event( - &mut self, + &self, room_id: &RoomId, event: &mut EventJson, ) -> (Option>, bool) { @@ -307,7 +313,8 @@ impl Client { } } - let mut room = self.get_or_create_room(&room_id).write().await; + let room_lock = self.get_or_create_room(&room_id).await; + let mut room = room_lock.write().await; (decrypted_event, room.receive_timeline_event(&e)) } _ => (None, false), @@ -324,12 +331,9 @@ impl Client { /// * `room_id` - The unique id of the room the event belongs to. /// /// * `event` - The event that should be handled by the client. - pub async fn receive_joined_state_event( - &mut self, - room_id: &RoomId, - event: &StateEvent, - ) -> bool { - let mut room = self.get_or_create_room(room_id).write().await; + pub async fn receive_joined_state_event(&self, room_id: &RoomId, event: &StateEvent) -> bool { + let room_lock = self.get_or_create_room(room_id).await; + let mut room = room_lock.write().await; room.receive_state_event(event) } @@ -343,13 +347,9 @@ impl Client { /// * `room_id` - The unique id of the room the event belongs to. /// /// * `event` - The event that should be handled by the client. - pub async fn receive_presence_event( - &mut self, - room_id: &RoomId, - event: &PresenceEvent, - ) -> bool { + pub async fn receive_presence_event(&self, room_id: &RoomId, event: &PresenceEvent) -> bool { // this should be the room that was just created in the `Client::sync` loop. - if let Some(room) = self.get_room(room_id) { + if let Some(room) = self.get_room(room_id).await { let mut room = room.write().await; room.receive_presence_event(event) } else { @@ -366,15 +366,11 @@ impl Client { /// * `room_id` - The unique id of the room the event belongs to. /// /// * `event` - The presence event for a specified room member. - pub async fn receive_account_data_event( - &mut self, - room_id: &RoomId, - event: &NonRoomEvent, - ) -> bool { + pub async fn receive_account_data_event(&self, room_id: &RoomId, event: &NonRoomEvent) -> bool { match event { - NonRoomEvent::IgnoredUserList(iu) => self.handle_ignored_users(iu), + NonRoomEvent::IgnoredUserList(iu) => self.handle_ignored_users(iu).await, NonRoomEvent::Presence(p) => self.receive_presence_event(room_id, p).await, - NonRoomEvent::PushRules(pr) => self.handle_push_rules(pr), + NonRoomEvent::PushRules(pr) => self.handle_push_rules(pr).await, _ => false, } } @@ -388,19 +384,21 @@ impl Client { /// * `room_id` - The unique id of the room the event belongs to. /// /// * `event` - The presence event for a specified room member. - pub async fn receive_ephemeral_event( - &mut self, - room_id: &RoomId, - event: &NonRoomEvent, - ) -> bool { + pub async fn receive_ephemeral_event(&self, room_id: &RoomId, event: &NonRoomEvent) -> bool { match event { - NonRoomEvent::IgnoredUserList(iu) => self.handle_ignored_users(iu), + NonRoomEvent::IgnoredUserList(iu) => self.handle_ignored_users(iu).await, NonRoomEvent::Presence(p) => self.receive_presence_event(room_id, p).await, - NonRoomEvent::PushRules(pr) => self.handle_push_rules(pr), + NonRoomEvent::PushRules(pr) => self.handle_push_rules(pr).await, _ => false, } } + /// Get the current, if any, sync token of the client. + /// This will be None if the client didn't sync at least once. + pub async fn sync_token(&self) -> Option { + self.sync_token.read().await.clone() + } + /// Receive a response from a sync call. /// /// # Arguments @@ -409,11 +407,10 @@ impl Client { /// /// * `did_update` - Signals to the `StateStore` if the client state needs updating. pub async fn receive_sync_response( - &mut self, + &self, response: &mut api::sync::sync_events::Response, - did_update: bool, ) -> Result<()> { - self.sync_token = Some(response.next_batch.clone()); + *self.sync_token.write().await = Some(response.next_batch.clone()); #[cfg(feature = "encryption")] { @@ -425,8 +422,8 @@ impl Client { // TODO once the base client deals with callbacks move this into the // part where we already iterate through the rooms to avoid yet // another room loop. - for room in self.joined_rooms.values() { - let room = room.write().await; + for room in self.joined_rooms.read().await.values() { + let room = room.read().await; if !room.is_encrypted() { continue; } @@ -436,9 +433,103 @@ impl Client { } } - if did_update { + let mut updated = false; + for (room_id, room) in &mut response.rooms.join { + let matrix_room = { + for event in &room.state.events { + if let Ok(e) = event.deserialize() { + if self.receive_joined_state_event(&room_id, &e).await { + updated = true; + } + } + } + + self.get_or_create_room(&room_id).await.clone() + }; + + // RoomSummary contains information for calculating room name + matrix_room.write().await.set_room_summary(&room.summary); + + // re looping is not ideal here + for event in &mut room.state.events { + if let Ok(e) = event.deserialize() { + self.emit_state_event(&room_id, &e).await; + } + } + + for mut event in &mut room.timeline.events { + let decrypted_event = { + let (decrypt_ev, timeline_update) = self + .receive_joined_timeline_event(room_id, &mut event) + .await; + if timeline_update { + updated = true; + }; + decrypt_ev + }; + + if let Some(e) = decrypted_event { + *event = e; + } + + if let Ok(e) = event.deserialize() { + self.emit_timeline_event(&room_id, &e).await; + } + } + + // look at AccountData to further cut down users by collecting ignored users + if let Some(account_data) = &room.account_data { + for account_data in &account_data.events { + { + if let Ok(e) = account_data.deserialize() { + if self.receive_account_data_event(&room_id, &e).await { + updated = true; + } + self.emit_account_data_event(room_id, &e).await; + } + } + } + } + + // After the room has been created and state/timeline events accounted for we use the room_id of the newly created + // room to add any presence events that relate to a user in the current room. This is not super + // efficient but we need a room_id so we would loop through now or later. + for presence in &mut response.presence.events { + { + if let Ok(e) = presence.deserialize() { + if self.receive_presence_event(&room_id, &e).await { + updated = true; + } + + self.emit_presence_event(&room_id, &e).await; + } + } + } + + for ephemeral in &mut room.ephemeral.events { + { + if let Ok(e) = ephemeral.deserialize() { + if self.receive_ephemeral_event(&room_id, &e).await { + updated = true; + } + + self.emit_ephemeral_event(&room_id, &e).await; + } + } + } + + if updated { + if let Some(store) = self.state_store.as_ref() { + store + .store_room_state(matrix_room.read().await.deref()) + .await?; + } + } + } + + if updated { if let Some(store) = self.state_store.as_ref() { - let state = ClientState::from_base_client(&self); + let state = ClientState::from_base_client(&self).await; store.store_client_state(state).await?; } } @@ -512,7 +603,7 @@ impl Client { &self, room_id: &RoomId, ) -> Result> { - let room = self.get_room(room_id).expect("No room found"); + let room = self.get_room(room_id).await.expect("No room found"); let mut olm = self.olm.lock().await; match &mut *olm { @@ -633,21 +724,21 @@ impl Client { match event { RoomEvent::RoomMember(mem) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_member(Arc::clone(&room), &mem).await; } } } RoomEvent::RoomName(name) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_name(Arc::clone(&room), &name).await; } } } RoomEvent::RoomCanonicalAlias(canonical) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_canonical_alias(Arc::clone(&room), &canonical) .await; } @@ -655,28 +746,28 @@ impl Client { } RoomEvent::RoomAliases(aliases) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_aliases(Arc::clone(&room), &aliases).await; } } } RoomEvent::RoomAvatar(avatar) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_avatar(Arc::clone(&room), &avatar).await; } } } RoomEvent::RoomMessage(msg) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_message(Arc::clone(&room), &msg).await; } } } RoomEvent::RoomMessageFeedback(msg_feedback) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_message_feedback(Arc::clone(&room), &msg_feedback) .await; } @@ -684,21 +775,21 @@ impl Client { } RoomEvent::RoomRedaction(redaction) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_redaction(Arc::clone(&room), &redaction).await; } } } RoomEvent::RoomPowerLevels(power) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_power_levels(Arc::clone(&room), &power).await; } } } RoomEvent::RoomTombstone(tomb) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_tombstone(Arc::clone(&room), &tomb).await; } } @@ -711,21 +802,21 @@ impl Client { match event { StateEvent::RoomMember(member) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_state_member(Arc::clone(&room), &member).await; } } } StateEvent::RoomName(name) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_state_name(Arc::clone(&room), &name).await; } } } StateEvent::RoomCanonicalAlias(canonical) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_state_canonical_alias(Arc::clone(&room), &canonical) .await; } @@ -733,35 +824,35 @@ impl Client { } StateEvent::RoomAliases(aliases) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_state_aliases(Arc::clone(&room), &aliases).await; } } } StateEvent::RoomAvatar(avatar) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_state_avatar(Arc::clone(&room), &avatar).await; } } } StateEvent::RoomPowerLevels(power) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_state_power_levels(Arc::clone(&room), &power).await; } } } StateEvent::RoomJoinRules(rules) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_state_join_rules(Arc::clone(&room), &rules).await; } } } StateEvent::RoomTombstone(tomb) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_room_tombstone(Arc::clone(&room), &tomb).await; } } @@ -774,14 +865,14 @@ impl Client { match event { NonRoomEvent::Presence(presence) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_account_presence(Arc::clone(&room), &presence).await; } } } NonRoomEvent::IgnoredUserList(ignored) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_account_ignored_users(Arc::clone(&room), &ignored) .await; } @@ -789,14 +880,14 @@ impl Client { } NonRoomEvent::PushRules(rules) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_account_push_rules(Arc::clone(&room), &rules).await; } } } NonRoomEvent::FullyRead(full_read) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_account_data_fully_read(Arc::clone(&room), &full_read) .await; } @@ -810,14 +901,14 @@ impl Client { match event { NonRoomEvent::Presence(presence) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_account_presence(Arc::clone(&room), &presence).await; } } } NonRoomEvent::IgnoredUserList(ignored) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_account_ignored_users(Arc::clone(&room), &ignored) .await; } @@ -825,14 +916,14 @@ impl Client { } NonRoomEvent::PushRules(rules) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_account_push_rules(Arc::clone(&room), &rules).await; } } } NonRoomEvent::FullyRead(full_read) => { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_account_data_fully_read(Arc::clone(&room), &full_read) .await; } @@ -844,7 +935,7 @@ impl Client { pub(crate) async fn emit_presence_event(&self, room_id: &RoomId, event: &PresenceEvent) { if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id) { + if let Some(room) = self.get_room(&room_id).await { ee.on_presence_event(Arc::clone(&room), &event).await; } } @@ -889,6 +980,7 @@ mod test { let _response = client.sync(sync_settings).await.unwrap(); let bc = &client.base_client.read().await; - assert_eq!(1, bc.ignored_users.len()) + let ignored_users = bc.ignored_users.read().await; + assert_eq!(1, ignored_users.len()) } } diff --git a/matrix_sdk/src/models/room.rs b/matrix_sdk/src/models/room.rs index 92c808a7..6cc0b5fe 100644 --- a/matrix_sdk/src/models/room.rs +++ b/matrix_sdk/src/models/room.rs @@ -493,7 +493,8 @@ mod test { let _response = client.sync(sync_settings).await.unwrap(); - let rooms = &client.base_client.read().await.joined_rooms; + let rooms_lock = &client.base_client.read().await.joined_rooms; + let rooms = rooms_lock.read().await; let room = &rooms .get(&RoomId::try_from("!SVkFJHzfwvuaIEawgC:localhost").unwrap()) .unwrap() diff --git a/matrix_sdk/src/state/mod.rs b/matrix_sdk/src/state/mod.rs index b670e947..bd201cf0 100644 --- a/matrix_sdk/src/state/mod.rs +++ b/matrix_sdk/src/state/mod.rs @@ -13,13 +13,12 @@ // See the License for the specific language governing permissions and // limitations under the License. +use serde::{Deserialize, Serialize}; use std::collections::HashMap; pub mod state_store; pub use state_store::JsonStore; -use serde::{Deserialize, Serialize}; - use crate::base_client::{Client as BaseClient, Token}; use crate::events::push_rules::Ruleset; use crate::identifiers::{RoomId, UserId}; @@ -48,7 +47,7 @@ impl PartialEq for ClientState { } impl ClientState { - pub fn from_base_client(client: &BaseClient) -> ClientState { + pub async fn from_base_client(client: &BaseClient) -> ClientState { let BaseClient { sync_token, ignored_users, @@ -56,9 +55,9 @@ impl ClientState { .. } = client; Self { - sync_token: sync_token.clone(), - ignored_users: ignored_users.clone(), - push_ruleset: push_ruleset.clone(), + sync_token: sync_token.read().await.clone(), + ignored_users: ignored_users.read().await.clone(), + push_ruleset: push_ruleset.read().await.clone(), } } } diff --git a/matrix_sdk/src/state/state_store.rs b/matrix_sdk/src/state/state_store.rs index 6e085ee9..99e2ac9a 100644 --- a/matrix_sdk/src/state/state_store.rs +++ b/matrix_sdk/src/state/state_store.rs @@ -292,11 +292,11 @@ mod test { // assert the synced client and the logged in client are equal assert_eq!(base_client.session, Some(session)); assert_eq!( - base_client.sync_token, + base_client.sync_token().await, Some("s526_47314_0_7_1_1_1_11444_1".to_string()) ); assert_eq!( - base_client.ignored_users, + *base_client.ignored_users.read().await, vec![UserId::try_from("@someone:example.org").unwrap()] ); } diff --git a/matrix_sdk/src/test_builder.rs b/matrix_sdk/src/test_builder.rs index 1b18c8f3..a54a6d8e 100644 --- a/matrix_sdk/src/test_builder.rs +++ b/matrix_sdk/src/test_builder.rs @@ -343,7 +343,7 @@ impl ClientTestRunner { } async fn stream_client_events(&mut self) { - let mut cli = self + let cli = self .client .as_ref() .expect("`AsyncClient` must be set use `ClientTestRunner::set_client`") From 3a30d53437502d67188a8beb7f0392c3f233cd66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Wed, 6 May 2020 14:27:53 +0200 Subject: [PATCH 04/10] base_client: Move the session behind a lock. --- matrix_sdk/src/async_client.rs | 7 +++---- matrix_sdk/src/base_client.rs | 16 ++++++++++------ matrix_sdk/src/state/state_store.rs | 2 +- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/matrix_sdk/src/async_client.rs b/matrix_sdk/src/async_client.rs index f253baa8..38f9791d 100644 --- a/matrix_sdk/src/async_client.rs +++ b/matrix_sdk/src/async_client.rs @@ -300,9 +300,7 @@ impl AsyncClient { /// Is the client logged in. pub async fn logged_in(&self) -> bool { - // TODO turn this into a atomic bool so this method doesn't need to be - // async. - self.base_client.read().await.logged_in() + self.base_client.read().await.logged_in().await } /// The Homeserver of the client. @@ -806,8 +804,9 @@ impl AsyncClient { let request_builder = if Request::METADATA.requires_authentication { let client = self.base_client.read().await; + let session = client.session.read().await; - if let Some(ref session) = client.session { + if let Some(session) = session.as_ref() { request_builder.bearer_auth(&session.access_token) } else { return Err(Error::AuthenticationRequired); diff --git a/matrix_sdk/src/base_client.rs b/matrix_sdk/src/base_client.rs index 4055c5bf..2acf8e5d 100644 --- a/matrix_sdk/src/base_client.rs +++ b/matrix_sdk/src/base_client.rs @@ -66,7 +66,7 @@ pub type Token = String; pub struct Client { /// The current client session containing our user id, device id and access /// token. - pub session: Option, + pub session: Arc>>, /// The current sync token that should be used for the next sync call. pub sync_token: Arc>>, /// A map of the rooms our user is joined in. @@ -118,7 +118,7 @@ impl Client { }; Ok(Client { - session, + session: Arc::new(RwLock::new(session)), sync_token: Arc::new(RwLock::new(None)), joined_rooms: Arc::new(RwLock::new(HashMap::new())), ignored_users: Arc::new(RwLock::new(Vec::new())), @@ -132,8 +132,10 @@ impl Client { } /// Is the client logged in. - pub fn logged_in(&self) -> bool { - self.session.is_some() + pub async fn logged_in(&self) -> bool { + // TODO turn this into a atomic bool so this method doesn't need to be + // async. + self.session.read().await.is_some() } /// Add `EventEmitter` to `Client`. @@ -153,7 +155,7 @@ impl Client { /// Returns `true` when a state store sync has successfully completed. pub(crate) async fn sync_with_state_store(&mut self) -> Result { if let Some(store) = self.state_store.as_ref() { - if let Some(sess) = self.session.as_ref() { + if let Some(sess) = self.session.read().await.as_ref() { if let Some(client_state) = store.load_client_state(sess).await? { let ClientState { sync_token, @@ -198,7 +200,7 @@ impl Client { device_id: response.device_id.clone(), user_id: response.user_id.clone(), }; - self.session = Some(session); + *self.session.write().await = Some(session); #[cfg(feature = "encryption")] { @@ -236,6 +238,8 @@ impl Client { room_id, &self .session + .read() + .await .as_ref() .expect("Receiving events while not being logged in") .user_id, diff --git a/matrix_sdk/src/state/state_store.rs b/matrix_sdk/src/state/state_store.rs index 99e2ac9a..67880ce5 100644 --- a/matrix_sdk/src/state/state_store.rs +++ b/matrix_sdk/src/state/state_store.rs @@ -290,7 +290,7 @@ mod test { let base_client = client.base_client.read().await; // assert the synced client and the logged in client are equal - assert_eq!(base_client.session, Some(session)); + assert_eq!(*base_client.session.read().await, Some(session)); assert_eq!( base_client.sync_token().await, Some("s526_47314_0_7_1_1_1_11444_1".to_string()) From 3d03f77dba13aa55a9eb6c710062ac473ed2b828 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Wed, 6 May 2020 14:47:58 +0200 Subject: [PATCH 05/10] base: Lock the event emitter option. --- matrix_sdk/src/async_client.rs | 6 +- matrix_sdk/src/base_client.rs | 255 ++++++++++++--------------------- 2 files changed, 98 insertions(+), 163 deletions(-) diff --git a/matrix_sdk/src/async_client.rs b/matrix_sdk/src/async_client.rs index 38f9791d..eb71e8a8 100644 --- a/matrix_sdk/src/async_client.rs +++ b/matrix_sdk/src/async_client.rs @@ -312,7 +312,11 @@ impl AsyncClient { /// /// The methods of `EventEmitter` are called when the respective `RoomEvents` occur. pub async fn add_event_emitter(&mut self, emitter: Box) { - self.base_client.write().await.event_emitter = Some(emitter); + self.base_client + .read() + .await + .add_event_emitter(emitter) + .await; } /// Returns an `Option` of the room name from a `RoomId`. diff --git a/matrix_sdk/src/base_client.rs b/matrix_sdk/src/base_client.rs index 2acf8e5d..6ff39444 100644 --- a/matrix_sdk/src/base_client.rs +++ b/matrix_sdk/src/base_client.rs @@ -77,7 +77,7 @@ pub struct Client { pub push_ruleset: Arc>>, /// Any implementor of EventEmitter will act as the callbacks for various /// events. - pub event_emitter: Option>, + pub event_emitter: Arc>>>, /// Any implementor of `StateStore` will be called to save `Room` and /// some `BaseClient` state during `AsyncClient::sync` calls. /// @@ -123,7 +123,7 @@ impl Client { joined_rooms: Arc::new(RwLock::new(HashMap::new())), ignored_users: Arc::new(RwLock::new(Vec::new())), push_ruleset: Arc::new(RwLock::new(None)), - event_emitter: None, + event_emitter: Arc::new(RwLock::new(None)), state_store: None, needs_state_store_sync: Arc::new(AtomicBool::from(true)), #[cfg(feature = "encryption")] @@ -141,8 +141,8 @@ impl Client { /// Add `EventEmitter` to `Client`. /// /// The methods of `EventEmitter` are called when the respective `RoomEvents` occur. - pub async fn add_event_emitter(&mut self, emitter: Box) { - self.event_emitter = Some(emitter); + pub async fn add_event_emitter(&self, emitter: Box) { + *self.event_emitter.write().await = Some(emitter); } /// Returns true if the state store has been loaded into the client. @@ -725,220 +725,151 @@ impl Client { } pub(crate) async fn emit_timeline_event(&self, room_id: &RoomId, event: &RoomEvent) { + let lock = self.event_emitter.read().await; + let event_emitter = if let Some(ee) = lock.as_ref() { + ee + } else { + return; + }; + + let room = if let Some(room) = self.get_room(&room_id).await { + Arc::clone(&room) + } else { + return; + }; + match event { - RoomEvent::RoomMember(mem) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_member(Arc::clone(&room), &mem).await; - } - } - } - RoomEvent::RoomName(name) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_name(Arc::clone(&room), &name).await; - } - } - } + RoomEvent::RoomMember(mem) => event_emitter.on_room_member(room, &mem).await, + RoomEvent::RoomName(name) => event_emitter.on_room_name(room, &name).await, RoomEvent::RoomCanonicalAlias(canonical) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_canonical_alias(Arc::clone(&room), &canonical) - .await; - } - } - } - RoomEvent::RoomAliases(aliases) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_aliases(Arc::clone(&room), &aliases).await; - } - } - } - RoomEvent::RoomAvatar(avatar) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_avatar(Arc::clone(&room), &avatar).await; - } - } - } - RoomEvent::RoomMessage(msg) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_message(Arc::clone(&room), &msg).await; - } - } + event_emitter + .on_room_canonical_alias(room, &canonical) + .await } + RoomEvent::RoomAliases(aliases) => event_emitter.on_room_aliases(room, &aliases).await, + RoomEvent::RoomAvatar(avatar) => event_emitter.on_room_avatar(room, &avatar).await, + RoomEvent::RoomMessage(msg) => event_emitter.on_room_message(room, &msg).await, RoomEvent::RoomMessageFeedback(msg_feedback) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_message_feedback(Arc::clone(&room), &msg_feedback) - .await; - } - } + event_emitter + .on_room_message_feedback(room, &msg_feedback) + .await } RoomEvent::RoomRedaction(redaction) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_redaction(Arc::clone(&room), &redaction).await; - } - } + event_emitter.on_room_redaction(room, &redaction).await } RoomEvent::RoomPowerLevels(power) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_power_levels(Arc::clone(&room), &power).await; - } - } - } - RoomEvent::RoomTombstone(tomb) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_tombstone(Arc::clone(&room), &tomb).await; - } - } + event_emitter.on_room_power_levels(room, &power).await } + RoomEvent::RoomTombstone(tomb) => event_emitter.on_room_tombstone(room, &tomb).await, _ => {} } } pub(crate) async fn emit_state_event(&self, room_id: &RoomId, event: &StateEvent) { + let lock = self.event_emitter.read().await; + let event_emitter = if let Some(ee) = lock.as_ref() { + ee + } else { + return; + }; + + let room = if let Some(room) = self.get_room(&room_id).await { + Arc::clone(&room) + } else { + return; + }; + match event { - StateEvent::RoomMember(member) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_state_member(Arc::clone(&room), &member).await; - } - } - } - StateEvent::RoomName(name) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_state_name(Arc::clone(&room), &name).await; - } - } - } + StateEvent::RoomMember(member) => event_emitter.on_state_member(room, &member).await, + StateEvent::RoomName(name) => event_emitter.on_state_name(room, &name).await, StateEvent::RoomCanonicalAlias(canonical) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_state_canonical_alias(Arc::clone(&room), &canonical) - .await; - } - } + event_emitter + .on_state_canonical_alias(room, &canonical) + .await } StateEvent::RoomAliases(aliases) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_state_aliases(Arc::clone(&room), &aliases).await; - } - } - } - StateEvent::RoomAvatar(avatar) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_state_avatar(Arc::clone(&room), &avatar).await; - } - } + event_emitter.on_state_aliases(room, &aliases).await } + StateEvent::RoomAvatar(avatar) => event_emitter.on_state_avatar(room, &avatar).await, StateEvent::RoomPowerLevels(power) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_state_power_levels(Arc::clone(&room), &power).await; - } - } + event_emitter.on_state_power_levels(room, &power).await } StateEvent::RoomJoinRules(rules) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_state_join_rules(Arc::clone(&room), &rules).await; - } - } - } - StateEvent::RoomTombstone(tomb) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_room_tombstone(Arc::clone(&room), &tomb).await; - } - } + event_emitter.on_state_join_rules(room, &rules).await } + StateEvent::RoomTombstone(tomb) => event_emitter.on_room_tombstone(room, &tomb).await, _ => {} } } pub(crate) async fn emit_account_data_event(&self, room_id: &RoomId, event: &NonRoomEvent) { + let lock = self.event_emitter.read().await; + let event_emitter = if let Some(ee) = lock.as_ref() { + ee + } else { + return; + }; + + let room = if let Some(room) = self.get_room(&room_id).await { + Arc::clone(&room) + } else { + return; + }; + match event { NonRoomEvent::Presence(presence) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_account_presence(Arc::clone(&room), &presence).await; - } - } + event_emitter.on_account_presence(room, &presence).await } NonRoomEvent::IgnoredUserList(ignored) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_account_ignored_users(Arc::clone(&room), &ignored) - .await; - } - } + event_emitter.on_account_ignored_users(room, &ignored).await } NonRoomEvent::PushRules(rules) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_account_push_rules(Arc::clone(&room), &rules).await; - } - } + event_emitter.on_account_push_rules(room, &rules).await } NonRoomEvent::FullyRead(full_read) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_account_data_fully_read(Arc::clone(&room), &full_read) - .await; - } - } + event_emitter + .on_account_data_fully_read(room, &full_read) + .await } _ => {} } } pub(crate) async fn emit_ephemeral_event(&self, room_id: &RoomId, event: &NonRoomEvent) { + let lock = self.event_emitter.read().await; + let event_emitter = if let Some(ee) = lock.as_ref() { + ee + } else { + return; + }; + + let room = if let Some(room) = self.get_room(&room_id).await { + Arc::clone(&room) + } else { + return; + }; + match event { NonRoomEvent::Presence(presence) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_account_presence(Arc::clone(&room), &presence).await; - } - } + event_emitter.on_account_presence(room, &presence).await } NonRoomEvent::IgnoredUserList(ignored) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_account_ignored_users(Arc::clone(&room), &ignored) - .await; - } - } + event_emitter.on_account_ignored_users(room, &ignored).await } NonRoomEvent::PushRules(rules) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_account_push_rules(Arc::clone(&room), &rules).await; - } - } + event_emitter.on_account_push_rules(room, &rules).await } NonRoomEvent::FullyRead(full_read) => { - if let Some(ee) = &self.event_emitter { - if let Some(room) = self.get_room(&room_id).await { - ee.on_account_data_fully_read(Arc::clone(&room), &full_read) - .await; - } - } + event_emitter + .on_account_data_fully_read(room, &full_read) + .await } _ => {} } } pub(crate) async fn emit_presence_event(&self, room_id: &RoomId, event: &PresenceEvent) { - if let Some(ee) = &self.event_emitter { + if let Some(ee) = &self.event_emitter.read().await.as_ref() { if let Some(room) = self.get_room(&room_id).await { ee.on_presence_event(Arc::clone(&room), &event).await; } From 6e9e81759784304833d2083ea9a56a8ecc2b7f66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Wed, 6 May 2020 15:00:16 +0200 Subject: [PATCH 06/10] crypto: Use next() instead of nth(0). --- matrix_sdk_crypto/src/machine.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/matrix_sdk_crypto/src/machine.rs b/matrix_sdk_crypto/src/machine.rs index 6c0f6f99..c3e63c60 100644 --- a/matrix_sdk_crypto/src/machine.rs +++ b/matrix_sdk_crypto/src/machine.rs @@ -1677,7 +1677,7 @@ mod test { let mut bob_keys = BTreeMap::new(); - let one_time_key = one_time_keys.iter().nth(0).unwrap(); + let one_time_key = one_time_keys.iter().next().unwrap(); let mut keys = BTreeMap::new(); keys.insert(one_time_key.0.clone(), one_time_key.1.clone()); bob_keys.insert(bob.device_id.clone(), keys); @@ -1840,7 +1840,7 @@ mod test { let identity_keys = machine.account.identity_keys(); let ed25519_key = identity_keys.ed25519(); - let mut one_time_key = one_time_keys.values_mut().nth(0).unwrap(); + let mut one_time_key = one_time_keys.values_mut().next().unwrap(); let ret = machine.verify_json( &machine.user_id, @@ -1868,7 +1868,7 @@ mod test { &machine.user_id, &machine.device_id, ed25519_key, - &mut json!(&mut one_time_keys.as_mut().unwrap().values_mut().nth(0)), + &mut json!(&mut one_time_keys.as_mut().unwrap().values_mut().next()), ); assert!(ret.is_ok()); @@ -1943,7 +1943,7 @@ mod test { let mut bob_keys = BTreeMap::new(); - let one_time_key = one_time_keys.iter().nth(0).unwrap(); + let one_time_key = one_time_keys.iter().next().unwrap(); let mut keys = BTreeMap::new(); keys.insert(one_time_key.0.clone(), one_time_key.1.clone()); bob_keys.insert(bob_machine.device_id.clone(), keys); From 02013ac2867e56d63ab59fbfce1fc0f06716ea85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Wed, 6 May 2020 15:20:20 +0200 Subject: [PATCH 07/10] base: Move the state store behind a lock. --- matrix_sdk/src/async_client.rs | 8 ++++---- matrix_sdk/src/base_client.rs | 35 +++++++++++++++++++++++++++++----- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/matrix_sdk/src/async_client.rs b/matrix_sdk/src/async_client.rs index eb71e8a8..d9a62962 100644 --- a/matrix_sdk/src/async_client.rs +++ b/matrix_sdk/src/async_client.rs @@ -285,10 +285,10 @@ impl AsyncClient { let http_client = http_client.default_headers(headers).build()?; - let mut base_client = BaseClient::new(session)?; - - if let Some(store) = config.state_store { - base_client.state_store = Some(store); + let base_client = if let Some(store) = config.state_store { + BaseClient::new_with_state_store(session, store)? + } else { + BaseClient::new(session)? }; Ok(Self { diff --git a/matrix_sdk/src/base_client.rs b/matrix_sdk/src/base_client.rs index 6ff39444..421812d2 100644 --- a/matrix_sdk/src/base_client.rs +++ b/matrix_sdk/src/base_client.rs @@ -82,7 +82,7 @@ pub struct Client { /// some `BaseClient` state during `AsyncClient::sync` calls. /// /// There is a default implementation `JsonStore` that saves JSON to disk. - pub state_store: Option>, + pub state_store: Arc>>>, /// Does the `Client` need to sync with the state store. needs_state_store_sync: Arc, @@ -111,6 +111,26 @@ impl Client { /// * `session` - An optional session if the user already has one from a /// previous login call. pub fn new(session: Option) -> Result { + Client::new_helper(session, None) + } + + /// Create a new client. + /// + /// # Arguments + /// + /// * `session` - An optional session if the user already has one from a + /// previous login call. + /// + /// * `store` - An open state store implementation that will be used through + /// the lifetime of the client. + pub fn new_with_state_store( + session: Option, + store: Box, + ) -> Result { + Client::new_helper(session, Some(store)) + } + + fn new_helper(session: Option, store: Option>) -> Result { #[cfg(feature = "encryption")] let olm = match &session { Some(s) => Some(OlmMachine::new(&s.user_id, &s.device_id)), @@ -124,7 +144,7 @@ impl Client { ignored_users: Arc::new(RwLock::new(Vec::new())), push_ruleset: Arc::new(RwLock::new(None)), event_emitter: Arc::new(RwLock::new(None)), - state_store: None, + state_store: Arc::new(RwLock::new(store)), needs_state_store_sync: Arc::new(AtomicBool::from(true)), #[cfg(feature = "encryption")] olm: Arc::new(Mutex::new(olm)), @@ -154,7 +174,8 @@ impl Client { /// /// Returns `true` when a state store sync has successfully completed. pub(crate) async fn sync_with_state_store(&mut self) -> Result { - if let Some(store) = self.state_store.as_ref() { + let store = self.state_store.read().await; + if let Some(store) = store.as_ref() { if let Some(sess) = self.session.read().await.as_ref() { if let Some(client_state) = store.load_client_state(sess).await? { let ClientState { @@ -523,7 +544,9 @@ impl Client { } if updated { - if let Some(store) = self.state_store.as_ref() { + let store = self.state_store.read().await; + + if let Some(store) = store.as_ref() { store .store_room_state(matrix_room.read().await.deref()) .await?; @@ -532,7 +555,9 @@ impl Client { } if updated { - if let Some(store) = self.state_store.as_ref() { + let store = self.state_store.read().await; + + if let Some(store) = store.as_ref() { let state = ClientState::from_base_client(&self).await; store.store_client_state(state).await?; } From 1639f0fdd8f4d44cf7e9cb33e1888cfaf86dda3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Wed, 6 May 2020 15:36:55 +0200 Subject: [PATCH 08/10] async_client: Remove the lock around the base client. --- matrix_sdk/src/async_client.rs | 85 ++++++++--------------------- matrix_sdk/src/base_client.rs | 17 +++--- matrix_sdk/src/models/room.rs | 2 +- matrix_sdk/src/state/state_store.rs | 2 +- matrix_sdk/src/test_builder.rs | 6 +- 5 files changed, 35 insertions(+), 77 deletions(-) diff --git a/matrix_sdk/src/async_client.rs b/matrix_sdk/src/async_client.rs index d9a62962..745b5b71 100644 --- a/matrix_sdk/src/async_client.rs +++ b/matrix_sdk/src/async_client.rs @@ -53,17 +53,17 @@ use crate::{Error, EventEmitter, Result}; const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30); -#[derive(Clone)] /// An async/await enabled Matrix client. /// /// All of the state is held in an `Arc` so the `AsyncClient` can be cloned freely. +#[derive(Clone)] pub struct AsyncClient { /// The URL of the homeserver to connect to. homeserver: Url, /// The underlying HTTP client. http_client: reqwest::Client, /// User session data. - pub(crate) base_client: Arc>, + pub(crate) base_client: BaseClient, } impl std::fmt::Debug for AsyncClient { @@ -294,13 +294,13 @@ impl AsyncClient { Ok(Self { homeserver, http_client, - base_client: Arc::new(RwLock::new(base_client)), + base_client, }) } /// Is the client logged in. pub async fn logged_in(&self) -> bool { - self.base_client.read().await.logged_in().await + self.base_client.logged_in().await } /// The Homeserver of the client. @@ -312,36 +312,28 @@ impl AsyncClient { /// /// The methods of `EventEmitter` are called when the respective `RoomEvents` occur. pub async fn add_event_emitter(&mut self, emitter: Box) { - self.base_client - .read() - .await - .add_event_emitter(emitter) - .await; + self.base_client.add_event_emitter(emitter).await; } /// Returns an `Option` of the room name from a `RoomId`. /// /// This is a human readable room name. pub async fn get_room_name(&self, room_id: &RoomId) -> Option { - self.base_client - .read() - .await - .calculate_room_name(room_id) - .await + self.base_client.calculate_room_name(room_id).await } /// Returns a `Vec` of the room names this client knows about. /// /// This is a human readable list of room names. pub async fn get_room_names(&self) -> Vec { - self.base_client.read().await.calculate_room_names().await + self.base_client.calculate_room_names().await } /// Returns the rooms this client knows about. /// /// A `HashMap` of room id to `matrix::models::Room` pub async fn get_rooms(&self) -> Arc>>>> { - self.base_client.read().await.joined_rooms.clone() + self.base_client.joined_rooms.clone() } /// This allows `AsyncClient` to manually sync state with the provided `StateStore`. @@ -368,7 +360,7 @@ impl AsyncClient { /// # }); /// ``` pub async fn sync_with_state_store(&self) -> Result { - self.base_client.write().await.sync_with_state_store().await + self.base_client.sync_with_state_store().await } /// Login to the server. @@ -403,9 +395,7 @@ impl AsyncClient { }; let response = self.send(request).await?; - let mut client = self.base_client.write().await; - - client.receive_login_response(&response).await?; + self.base_client.receive_login_response(&response).await?; Ok(response) } @@ -625,7 +615,7 @@ impl AsyncClient { pub async fn sync(&self, mut sync_settings: SyncSettings) -> Result { { // if the client has been synced from the state store don't sync again - if !self.base_client.read().await.is_state_store_synced() { + if !self.base_client.is_state_store_synced() { // this will bail out returning false if the store has not been set up if let Ok(synced) = self.sync_with_state_store().await { if synced { @@ -646,8 +636,9 @@ impl AsyncClient { let mut response = self.send(request).await?; - let client = self.base_client.read().await; - client.receive_sync_response(&mut response).await?; + self.base_client + .receive_sync_response(&mut response) + .await?; Ok(response) } @@ -734,7 +725,7 @@ impl AsyncClient { #[cfg(feature = "encryption")] { - if self.base_client.read().await.should_upload_keys().await { + if self.base_client.should_upload_keys().await { let response = self.keys_upload().await; if let Err(e) = response { @@ -742,7 +733,7 @@ impl AsyncClient { } } - if self.base_client.read().await.should_query_keys().await { + if self.base_client.should_query_keys().await { let response = self.keys_query().await; if let Err(e) = response { @@ -807,8 +798,7 @@ impl AsyncClient { }; let request_builder = if Request::METADATA.requires_authentication { - let client = self.base_client.read().await; - let session = client.session.read().await; + let session = self.base_client.session.read().await; if let Some(session) = session.as_ref() { request_builder.bearer_auth(&session.access_token) @@ -894,8 +884,7 @@ impl AsyncClient { #[cfg(feature = "encryption")] { let encrypted = { - let client = self.base_client.read().await; - let room = client.get_room(room_id).await; + let room = self.base_client.get_room(room_id).await; match room { Some(r) => r.read().await.is_encrypted(), @@ -905,40 +894,24 @@ impl AsyncClient { if encrypted { let missing_sessions = { - let client = self.base_client.read().await; - let room = client.get_room(room_id).await; + let room = self.base_client.get_room(room_id).await; let room = room.as_ref().unwrap().read().await; let users = room.members.keys(); - self.base_client - .read() - .await - .get_missing_sessions(users) - .await? + self.base_client.get_missing_sessions(users).await? }; if !missing_sessions.is_empty() { self.claim_one_time_keys(missing_sessions).await?; } - if self - .base_client - .read() - .await - .should_share_group_session(room_id) - .await - { + if self.base_client.should_share_group_session(room_id).await { // TODO we need to make sure that only one such request is // in flight per room at a time. self.share_group_session(room_id).await?; } raw_content = serde_json::value::to_raw_value( - &self - .base_client - .read() - .await - .encrypt(room_id, content) - .await?, + &self.base_client.encrypt(room_id, content).await?, )?; event_type = EventType::RoomEncrypted; } @@ -979,8 +952,6 @@ impl AsyncClient { let response = self.send(request).await?; self.base_client - .read() - .await .receive_keys_claim_response(&response) .await?; Ok(response) @@ -1002,8 +973,6 @@ impl AsyncClient { async fn share_group_session(&self, room_id: &RoomId) -> Result<()> { let mut requests = self .base_client - .read() - .await .share_group_session(room_id) .await .expect("Keys don't need to be uploaded"); @@ -1030,8 +999,6 @@ impl AsyncClient { async fn keys_upload(&self) -> Result { let (device_keys, one_time_keys) = self .base_client - .read() - .await .keys_for_upload() .await .expect("Keys don't need to be uploaded"); @@ -1049,8 +1016,6 @@ impl AsyncClient { let response = self.send(request).await?; self.base_client - .read() - .await .receive_keys_upload_response(&response) .await?; Ok(response) @@ -1059,7 +1024,7 @@ impl AsyncClient { /// Get the current, if any, sync token of the client. /// This will be None if the client didn't sync at least once. pub async fn sync_token(&self) -> Option { - self.base_client.read().await.sync_token().await + self.base_client.sync_token().await } /// Query the server for users device keys. @@ -1073,8 +1038,6 @@ impl AsyncClient { async fn keys_query(&self) -> Result { let mut users_for_query = self .base_client - .read() - .await .users_for_key_query() .await .expect("Keys don't need to be uploaded"); @@ -1098,8 +1061,6 @@ impl AsyncClient { let response = self.send(request).await?; self.base_client - .read() - .await .receive_keys_query_response(&response) .await?; diff --git a/matrix_sdk/src/base_client.rs b/matrix_sdk/src/base_client.rs index 421812d2..3d38ecee 100644 --- a/matrix_sdk/src/base_client.rs +++ b/matrix_sdk/src/base_client.rs @@ -63,6 +63,7 @@ pub type Token = String; /// /// This Client is a state machine that receives responses and events and /// accordingly updates it's state. +#[derive(Clone)] pub struct Client { /// The current client session containing our user id, device id and access /// token. @@ -173,7 +174,7 @@ impl Client { /// When a client is provided the state store will load state from the `StateStore`. /// /// Returns `true` when a state store sync has successfully completed. - pub(crate) async fn sync_with_state_store(&mut self) -> Result { + pub(crate) async fn sync_with_state_store(&self) -> Result { let store = self.state_store.read().await; if let Some(store) = store.as_ref() { if let Some(sess) = self.session.read().await.as_ref() { @@ -193,12 +194,10 @@ impl Client { } let mut rooms = store.load_all_rooms().await?; - self.joined_rooms = Arc::new(RwLock::new( - rooms - .drain() - .map(|(k, room)| (k, Arc::new(RwLock::new(room)))) - .collect(), - )); + *self.joined_rooms.write().await = rooms + .drain() + .map(|(k, room)| (k, Arc::new(RwLock::new(room)))) + .collect(); self.needs_state_store_sync.store(false, Ordering::Relaxed); } @@ -213,7 +212,7 @@ impl Client { /// * `response` - A successful login response that contains our access token /// and device id. pub async fn receive_login_response( - &mut self, + &self, response: &api::session::login::Response, ) -> Result<()> { let session = Session { @@ -939,7 +938,7 @@ mod test { let _response = client.sync(sync_settings).await.unwrap(); - let bc = &client.base_client.read().await; + let bc = &client.base_client; let ignored_users = bc.ignored_users.read().await; assert_eq!(1, ignored_users.len()) } diff --git a/matrix_sdk/src/models/room.rs b/matrix_sdk/src/models/room.rs index 6cc0b5fe..a5c25f40 100644 --- a/matrix_sdk/src/models/room.rs +++ b/matrix_sdk/src/models/room.rs @@ -493,7 +493,7 @@ mod test { let _response = client.sync(sync_settings).await.unwrap(); - let rooms_lock = &client.base_client.read().await.joined_rooms; + let rooms_lock = &client.base_client.joined_rooms; let rooms = rooms_lock.read().await; let room = &rooms .get(&RoomId::try_from("!SVkFJHzfwvuaIEawgC:localhost").unwrap()) diff --git a/matrix_sdk/src/state/state_store.rs b/matrix_sdk/src/state/state_store.rs index 67880ce5..7bb91aac 100644 --- a/matrix_sdk/src/state/state_store.rs +++ b/matrix_sdk/src/state/state_store.rs @@ -287,7 +287,7 @@ mod test { AsyncClient::new_with_config(homeserver, Some(session.clone()), config).unwrap(); client.sync(sync_settings).await.unwrap(); - let base_client = client.base_client.read().await; + let base_client = &client.base_client; // assert the synced client and the logged in client are equal assert_eq!(*base_client.session.read().await, Some(session)); diff --git a/matrix_sdk/src/test_builder.rs b/matrix_sdk/src/test_builder.rs index a54a6d8e..8f173285 100644 --- a/matrix_sdk/src/test_builder.rs +++ b/matrix_sdk/src/test_builder.rs @@ -343,13 +343,11 @@ impl ClientTestRunner { } async fn stream_client_events(&mut self) { - let cli = self + let cli = &self .client .as_ref() .expect("`AsyncClient` must be set use `ClientTestRunner::set_client`") - .base_client - .write() - .await; + .base_client; let room_id = &self.room_user_id.0; From d8b9dc85192a8c4002caa709235567d7c48ba956 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Wed, 6 May 2020 15:55:18 +0200 Subject: [PATCH 09/10] base: Don't expose the client fields publicly. --- matrix_sdk/src/async_client.rs | 12 ++++---- matrix_sdk/src/base_client.rs | 48 ++++++++++++++++++++--------- matrix_sdk/src/models/room.rs | 2 +- matrix_sdk/src/state/state_store.rs | 2 +- 4 files changed, 41 insertions(+), 23 deletions(-) diff --git a/matrix_sdk/src/async_client.rs b/matrix_sdk/src/async_client.rs index 745b5b71..f884dd6e 100644 --- a/matrix_sdk/src/async_client.rs +++ b/matrix_sdk/src/async_client.rs @@ -329,11 +329,11 @@ impl AsyncClient { self.base_client.calculate_room_names().await } - /// Returns the rooms this client knows about. + /// Returns the joined rooms this client knows about. /// /// A `HashMap` of room id to `matrix::models::Room` - pub async fn get_rooms(&self) -> Arc>>>> { - self.base_client.joined_rooms.clone() + pub fn joined_rooms(&self) -> Arc>>>> { + self.base_client.joined_rooms() } /// This allows `AsyncClient` to manually sync state with the provided `StateStore`. @@ -798,7 +798,7 @@ impl AsyncClient { }; let request_builder = if Request::METADATA.requires_authentication { - let session = self.base_client.session.read().await; + let session = self.base_client.session().read().await; if let Some(session) = session.as_ref() { request_builder.bearer_auth(&session.access_token) @@ -884,7 +884,7 @@ impl AsyncClient { #[cfg(feature = "encryption")] { let encrypted = { - let room = self.base_client.get_room(room_id).await; + let room = self.base_client.get_joined_room(room_id).await; match room { Some(r) => r.read().await.is_encrypted(), @@ -894,7 +894,7 @@ impl AsyncClient { if encrypted { let missing_sessions = { - let room = self.base_client.get_room(room_id).await; + let room = self.base_client.get_joined_room(room_id).await; let room = room.as_ref().unwrap().read().await; let users = room.members.keys(); self.base_client.get_missing_sessions(users).await? diff --git a/matrix_sdk/src/base_client.rs b/matrix_sdk/src/base_client.rs index 3d38ecee..5b9a96bc 100644 --- a/matrix_sdk/src/base_client.rs +++ b/matrix_sdk/src/base_client.rs @@ -67,23 +67,23 @@ pub type Token = String; pub struct Client { /// The current client session containing our user id, device id and access /// token. - pub session: Arc>>, + session: Arc>>, /// The current sync token that should be used for the next sync call. - pub sync_token: Arc>>, + pub(crate) sync_token: Arc>>, /// A map of the rooms our user is joined in. - pub joined_rooms: Arc>>>>, + joined_rooms: Arc>>>>, /// A list of ignored users. - pub ignored_users: Arc>>, + pub(crate) ignored_users: Arc>>, /// The push ruleset for the logged in user. - pub push_ruleset: Arc>>, + pub(crate) push_ruleset: Arc>>, /// Any implementor of EventEmitter will act as the callbacks for various /// events. - pub event_emitter: Arc>>>, + event_emitter: Arc>>>, /// Any implementor of `StateStore` will be called to save `Room` and /// some `BaseClient` state during `AsyncClient::sync` calls. /// /// There is a default implementation `JsonStore` that saves JSON to disk. - pub state_store: Arc>>>, + state_store: Arc>>>, /// Does the `Client` need to sync with the state store. needs_state_store_sync: Arc, @@ -152,6 +152,12 @@ impl Client { }) } + /// The current client session containing our user id, device id and access + /// token. + pub fn session(&self) -> &Arc>> { + &self.session + } + /// Is the client logged in. pub async fn logged_in(&self) -> bool { // TODO turn this into a atomic bool so this method doesn't need to be @@ -267,10 +273,22 @@ impl Client { .clone() } - pub(crate) async fn get_room(&self, room_id: &RoomId) -> Option>> { + /// Get a joined room with the given room id. + /// + /// # Arguments + /// + /// `room_id` - The unique id of the room that should be fetched. + pub(crate) async fn get_joined_room(&self, room_id: &RoomId) -> Option>> { self.joined_rooms.read().await.get(room_id).cloned() } + /// Returns the joined rooms this client knows about. + /// + /// A `HashMap` of room id to `matrix::models::Room` + pub fn joined_rooms(&self) -> Arc>>>> { + self.joined_rooms.clone() + } + /// Handle a m.ignored_user_list event, updating the room state if necessary. /// /// Returns true if the room name changed, false otherwise. @@ -373,7 +391,7 @@ impl Client { /// * `event` - The event that should be handled by the client. pub async fn receive_presence_event(&self, room_id: &RoomId, event: &PresenceEvent) -> bool { // this should be the room that was just created in the `Client::sync` loop. - if let Some(room) = self.get_room(room_id).await { + if let Some(room) = self.get_joined_room(room_id).await { let mut room = room.write().await; room.receive_presence_event(event) } else { @@ -631,7 +649,7 @@ impl Client { &self, room_id: &RoomId, ) -> Result> { - let room = self.get_room(room_id).await.expect("No room found"); + let room = self.get_joined_room(room_id).await.expect("No room found"); let mut olm = self.olm.lock().await; match &mut *olm { @@ -756,7 +774,7 @@ impl Client { return; }; - let room = if let Some(room) = self.get_room(&room_id).await { + let room = if let Some(room) = self.get_joined_room(&room_id).await { Arc::clone(&room) } else { return; @@ -797,7 +815,7 @@ impl Client { return; }; - let room = if let Some(room) = self.get_room(&room_id).await { + let room = if let Some(room) = self.get_joined_room(&room_id).await { Arc::clone(&room) } else { return; @@ -834,7 +852,7 @@ impl Client { return; }; - let room = if let Some(room) = self.get_room(&room_id).await { + let room = if let Some(room) = self.get_joined_room(&room_id).await { Arc::clone(&room) } else { return; @@ -867,7 +885,7 @@ impl Client { return; }; - let room = if let Some(room) = self.get_room(&room_id).await { + let room = if let Some(room) = self.get_joined_room(&room_id).await { Arc::clone(&room) } else { return; @@ -894,7 +912,7 @@ impl Client { pub(crate) async fn emit_presence_event(&self, room_id: &RoomId, event: &PresenceEvent) { if let Some(ee) = &self.event_emitter.read().await.as_ref() { - if let Some(room) = self.get_room(&room_id).await { + if let Some(room) = self.get_joined_room(&room_id).await { ee.on_presence_event(Arc::clone(&room), &event).await; } } diff --git a/matrix_sdk/src/models/room.rs b/matrix_sdk/src/models/room.rs index a5c25f40..da7aba1b 100644 --- a/matrix_sdk/src/models/room.rs +++ b/matrix_sdk/src/models/room.rs @@ -493,7 +493,7 @@ mod test { let _response = client.sync(sync_settings).await.unwrap(); - let rooms_lock = &client.base_client.joined_rooms; + let rooms_lock = &client.base_client.joined_rooms(); let rooms = rooms_lock.read().await; let room = &rooms .get(&RoomId::try_from("!SVkFJHzfwvuaIEawgC:localhost").unwrap()) diff --git a/matrix_sdk/src/state/state_store.rs b/matrix_sdk/src/state/state_store.rs index 7bb91aac..75c9771c 100644 --- a/matrix_sdk/src/state/state_store.rs +++ b/matrix_sdk/src/state/state_store.rs @@ -290,7 +290,7 @@ mod test { let base_client = &client.base_client; // assert the synced client and the logged in client are equal - assert_eq!(*base_client.session.read().await, Some(session)); + assert_eq!(*base_client.session().read().await, Some(session)); assert_eq!( base_client.sync_token().await, Some("s526_47314_0_7_1_1_1_11444_1".to_string()) From e9d6e28e13d5d0f8f5520d7305458fef59fda46e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Wed, 6 May 2020 17:06:24 +0200 Subject: [PATCH 10/10] matrix-sdk: Remove some unused deps. --- matrix_sdk/Cargo.toml | 8 -------- 1 file changed, 8 deletions(-) diff --git a/matrix_sdk/Cargo.toml b/matrix_sdk/Cargo.toml index a21cde7c..36e08cfa 100644 --- a/matrix_sdk/Cargo.toml +++ b/matrix_sdk/Cargo.toml @@ -32,8 +32,6 @@ matrix-sdk-crypto = { path = "../matrix_sdk_crypto", optional = true } # Misc dependencies thiserror = "1.0.16" tracing = "0.1.13" -atomic = "0.4.5" -dashmap = "3.11.1" [dependencies.tracing-futures] version = "0.2.4" @@ -45,12 +43,6 @@ version = "0.2.20" default-features = false features = ["sync", "time", "fs"] -[dependencies.sqlx] -version = "0.3.4" -optional = true -default-features = false -features = ["runtime-tokio", "sqlite"] - [dev-dependencies] tokio = { version = "0.2.20", features = ["rt-threaded", "macros"] } ruma-identifiers = { version = "0.16.1", features = ["rand"] }