Commit da75661f41

da75661f41bffeddc34c4ae08ce635a616f4aa6d

parent: cdaaf98d43

Unsigned

Damir Jelić <poljar@termina.org.uk> · 2020-10-10 10:12 UTC

room_buffer: Abandon the lockless design with a room copy.

This instead uses the room that the client holds. The locks around the
room are handled using block_on.

Layout: unified · split

Cargo.toml +8 −6
@@ -11,19 +11,21 @@ crate-type = ["cdylib"]
1111
1212[dependencies]
1313url = "2.1.1"
14futures = "0.3.6"
1415tokio = { version = "0.2.22", features = [ "rt-threaded", "sync" ] }
15tracing = "0.1.19"
16tracing-subscriber = "0.2.12"
17async-std = { version = "1.6.4", features = [ "unstable" ] }
16tracing = "0.1.21"
17tracing-subscriber = "0.2.13"
18async-std = { version = "1.6.5", features = [ "unstable" ] }
1819clap = "2.33.3"
19async-trait = "0.1.40"
20async-trait = "0.1.41"
2021uuid = { version = "0.8.1", features = ["v4"] }
2122indoc = "1.0.2"
22chrono = "0.4.15"
23chrono = "0.4.19"
2324
2425[dependencies.weechat]
2526git = "https://github.com/poljar/rust-weechat"
2627features = ["async", "config_macro"]
2728
2829[dependencies.matrix-sdk]
29git = "https://github.com/matrix-org/matrix-rust-sdk/"
30path = "/home/poljar/werk/priv/nio-rust/matrix_sdk"
31features = ["messages"]
src/connection.rs +7 −6
@@ -1,4 +1,4 @@
1use std::{cell::RefCell, path::PathBuf, rc::Weak, time::Duration};
1use std::{cell::RefCell, path::PathBuf, rc::Weak, sync::Arc, time::Duration};
22
33use async_std::sync::{channel as async_channel, Receiver, Sender};
44use tokio::runtime::Runtime;
@@ -18,7 +18,8 @@ pub use matrix_sdk::{
1818 AnyMessageEventContent, AnySyncRoomEvent, AnySyncStateEvent,
1919 },
2020 identifiers::{RoomId, UserId},
21 Client, ClientConfig, Result as MatrixResult, Room, SyncSettings,
21 locks::RwLock,
22 Client, ClientConfig, LoopCtrl, Result as MatrixResult, Room, SyncSettings,
2223};
2324
2425use weechat::{JoinHandle, Weechat};
@@ -32,7 +33,7 @@ pub enum ClientMessage {
3233 LoginMessage(LoginResponse),
3334 SyncState(RoomId, AnySyncStateEvent),
3435 SyncEvent(RoomId, AnySyncRoomEvent),
35 RestoredRoom(Room),
36 RestoredRoom(Arc<RwLock<Room>>),
3637}
3738
3839/// Struc representing an active connection to the homeserver.
@@ -327,8 +328,6 @@ impl Connection {
327328 if !first_login {
328329 let joined_rooms = client.joined_rooms();
329330 for room in joined_rooms.read().await.values() {
330 let room = room.read().await;
331 let room: &Room = &*room;
332331 channel
333332 .send(Ok(ClientMessage::RestoredRoom(room.clone())))
334333 .await
@@ -348,7 +347,7 @@ impl Connection {
348347 let sync_channel = &channel;
349348
350349 client
351 .sync_forever(sync_settings, async move |response| {
350 .sync_with_callback(sync_settings, async move |response| {
352351 let channel = sync_channel;
353352
354353 for (room_id, room) in response.rooms.join {
@@ -383,6 +382,8 @@ impl Connection {
383382 }
384383 }
385384 }
385
386 LoopCtrl::Continue
386387 })
387388 .await;
388389 }
src/room_buffer.rs +37 −39
@@ -34,19 +34,20 @@ use matrix_sdk::{
3434 MembershipState,
3535 },
3636 message::{MessageEventContent, TextMessageEventContent},
37 name::NameEventContent,
3837 },
3938 AnyMessageEventContent, AnyPossiblyRedactedSyncMessageEvent,
4039 AnySyncMessageEvent, AnySyncRoomEvent, AnySyncStateEvent,
4140 SyncStateEvent,
4241 },
4342 identifiers::{RoomId, UserId},
43 locks::{RwLock, RwLockReadGuard},
4444 uuid::Uuid,
4545 PossiblyRedactedExt, Room,
4646};
4747use url::Url;
4848
4949use async_trait::async_trait;
50use futures::executor::block_on;
5051use tracing::{debug, error, trace};
5152
5253use crate::{
@@ -55,11 +56,11 @@ use crate::{
5556};
5657use std::{
5758 borrow::Cow,
58 cell::{Ref, RefCell, RefMut},
59 cell::RefCell,
5960 collections::HashMap,
6061 convert::TryFrom,
6162 rc::Rc,
62 sync::Mutex,
63 sync::{Arc, Mutex},
6364 time::Instant,
6465};
6566use weechat::{
@@ -113,6 +114,7 @@ struct MatrixRoom {
113114 homeserver: Rc<Url>,
114115 room_id: Rc<RoomId>,
115116 own_user_id: Rc<UserId>,
117 room: Arc<RwLock<Room>>,
116118
117119 connection: Rc<RefCell<Option<Connection>>>,
118120
@@ -121,7 +123,6 @@ struct MatrixRoom {
121123
122124 local_echo_queue: Rc<RefCell<HashMap<Uuid, MessageEventContent>>>,
123125
124 room: Rc<RefCell<Room>>,
125126 members: Rc<RefCell<HashMap<UserId, WeechatRoomMember>>>,
126127}
127128
@@ -236,6 +237,7 @@ impl MatrixRoom {
236237impl RoomBuffer {
237238 pub fn new(
238239 connection: &Rc<RefCell<Option<Connection>>>,
240 room: Arc<RwLock<Room>>,
239241 homeserver: &Url,
240242 room_id: RoomId,
241243 own_user_id: &UserId,
@@ -246,7 +248,7 @@ impl RoomBuffer {
246248 connection: connection.clone(),
247249 typing_notice_time: Rc::new(RefCell::new(None)),
248250 typing_in_flight: Rc::new(Mutex::new(())),
249 room: Rc::new(RefCell::new(Room::new(&room_id, &own_user_id))),
251 room,
250252 own_user_id: Rc::new(own_user_id.to_owned()),
251253 members: Rc::new(RefCell::new(HashMap::new())),
252254 local_echo_queue: Rc::new(RefCell::new(HashMap::new())),
@@ -275,28 +277,34 @@ impl RoomBuffer {
275277 }
276278
277279 pub fn restore(
278 room: Room,
280 room: Arc<RwLock<Room>>,
279281 connection: &Rc<RefCell<Option<Connection>>>,
280282 homeserver: &Url,
281283 ) -> Self {
282 let mut room_buffer = RoomBuffer::new(
284 let room_clone = room.clone();
285 let room_lock = block_on(room.read());
286 let room_id = room_lock.room_id.to_owned();
287 let own_user_id = &room_lock.own_user_id;
288
289 let room_buffer = RoomBuffer::new(
283290 connection,
291 room_clone,
284292 homeserver,
285 room.room_id.clone(),
286 &room.own_user_id,
293 room_id,
294 own_user_id,
287295 );
288296
289 debug!("Restoring room {}", room.room_id);
297 debug!("Restoring room {}", room_lock.room_id);
290298
291 let matrix_members = room
299 let matrix_members = room_lock
292300 .joined_members
293301 .values()
294 .chain(room.invited_members.values());
302 .chain(room_lock.invited_members.values());
295303
296304 let mut weechat_members = HashMap::new();
297305
298306 for member in matrix_members {
299 let display_name = room
307 let display_name = room_lock
300308 .get_member(&member.user_id)
301309 .unwrap()
302310 .display_name
@@ -323,7 +331,6 @@ impl RoomBuffer {
323331 .expect("Can't add nick to nicklist");
324332 }
325333
326 room_buffer.inner.room = Rc::new(RefCell::new(room));
327334 room_buffer.inner.members.replace(weechat_members);
328335 room_buffer.update_buffer_name();
329336 room_buffer.restore_messages();
@@ -365,12 +372,12 @@ impl RoomBuffer {
365372 self.inner.send_message(buffer, content).await
366373 }
367374
368 pub fn room_mut(&mut self) -> RefMut<'_, Room> {
369 self.inner.room.borrow_mut()
375 pub fn room(&self) -> RwLockReadGuard<'_, Room> {
376 block_on(self.inner.room.read())
370377 }
371378
372 pub fn room(&self) -> Ref<'_, Room> {
373 self.inner.room.borrow()
379 pub fn room_id(&self) -> &RoomId {
380 &self.inner.room_id
374381 }
375382
376383 /// Retrieve a reference to a Weechat room member by user ID.
@@ -587,6 +594,7 @@ impl RoomBuffer {
587594 ///
588595 /// Disambiguations are a hashmap of user ID -> bool indicating that this user is either newly
589596 /// ambiguous (true) or no longer ambiguous (false).
597 #[allow(dead_code)]
590598 fn process_disambiguations(
591599 &mut self,
592600 disambiguations: &HashMap<UserId, bool>,
@@ -648,10 +656,6 @@ impl RoomBuffer {
648656 return;
649657 }
650658
651 // Handle the event in the SDK room model
652 let (_, disambiguations) =
653 self.room_mut().handle_membership(event, state_event);
654
655659 let new_nick = self.calculate_user_name(&target_id);
656660
657661 if state_event {
@@ -685,7 +689,9 @@ impl RoomBuffer {
685689 _ => (),
686690 }
687691
688 self.process_disambiguations(&disambiguations);
692 // TODO enable this again once we receive the event via an event
693 // emitter.
694 // self.process_disambiguations(&disambiguations);
689695
690696 // Names of rooms without display names can get affected by the member list so we need to
691697 // update them.
@@ -792,7 +798,9 @@ impl RoomBuffer {
792798 }
793799 };
794800
795 self.process_disambiguations(&disambiguations);
801 // TODO enable this again once we receive the event via an event
802 // emitter.
803 // self.process_disambiguations(&disambiguations);
796804
797805 // Names of rooms without display names can get affected by the member list so we need to
798806 // update them.
@@ -860,11 +868,7 @@ impl RoomBuffer {
860868 buffer.print_date_tags(timestamp as i64, &[], &message);
861869 }
862870
863 pub fn handle_room_name(
864 &mut self,
865 event: &SyncStateEvent<NameEventContent>,
866 ) {
867 self.room_mut().handle_room_name(event);
871 pub fn handle_room_name(&self) {
868872 self.update_buffer_name();
869873 }
870874
@@ -885,14 +889,11 @@ impl RoomBuffer {
885889 AnySyncStateEvent::RoomMember(e) => {
886890 self.handle_membership_event(e, false)
887891 }
888 AnySyncStateEvent::RoomName(n) => self.handle_room_name(n),
892 AnySyncStateEvent::RoomName(_) => self.handle_room_name(),
889893 _ => (),
890894 },
891895
892 event => {
893 let mut room = self.room_mut();
894 room.receive_timeline_event(event);
895 }
896 _ => (),
896897 }
897898 }
898899
@@ -901,11 +902,8 @@ impl RoomBuffer {
901902 AnySyncStateEvent::RoomMember(e) => {
902903 self.handle_membership_event(e, true)
903904 }
904 AnySyncStateEvent::RoomName(n) => self.handle_room_name(n),
905 _ => {
906 let mut room = self.room_mut();
907 room.receive_state_event(&event);
908 }
905 AnySyncStateEvent::RoomName(_) => self.handle_room_name(),
906 _ => (),
909907 }
910908 }
911909}
src/server.rs +14 −3
@@ -55,12 +55,14 @@
5555//! that processing events will not block the Weechat mainloop for too long.
5656
5757use chrono::{offset::Utc, DateTime};
58use futures::executor::block_on;
5859use indoc::indoc;
5960use std::{
6061 cell::{Ref, RefCell, RefMut},
6162 collections::HashMap,
6263 path::PathBuf,
6364 rc::{Rc, Weak},
65 sync::Arc,
6466};
6567use url::Url;
6668
@@ -69,6 +71,7 @@ use matrix_sdk::{
6971 api::r0::session::login::Response as LoginResponse,
7072 events::{AnySyncRoomEvent, AnySyncStateEvent},
7173 identifiers::{RoomId, UserId},
74 locks::RwLock,
7275 Client, ClientConfig, Room,
7376};
7477
@@ -549,8 +552,17 @@ impl InnerServer {
549552 .login_state
550553 .as_ref()
551554 .expect("Receiving events while not being logged in");
555 let room = block_on(
556 self.client
557 .as_ref()
558 .expect("Receiving events without a client")
559 .get_joined_room(room_id),
560 );
561 let room =
562 room.expect("Receiving events for a room while no room found");
552563 let buffer = RoomBuffer::new(
553564 &self.connection,
565 room,
554566 homeserver,
555567 room_id.clone(),
556568 &login_state.user_id,
@@ -573,16 +585,15 @@ impl InnerServer {
573585 self.config.borrow()
574586 }
575587
576 pub fn restore_room(&mut self, room: Room) {
588 pub fn restore_room(&mut self, room: Arc<RwLock<Room>>) {
577589 let homeserver = self
578590 .settings
579591 .homeserver
580592 .as_ref()
581593 .expect("Creating room buffer while no homeserver");
582594
583 let room_id = room.room_id.clone();
584
585595 let buffer = RoomBuffer::restore(room, &self.connection, homeserver);
596 let room_id = buffer.room_id().to_owned();
586597
587598 self.room_buffers.insert(room_id, buffer);
588599 }