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"]
11 11
12[dependencies] 12[dependencies]
13url = "2.1.1" 13url = "2.1.1"
14futures = "0.3.6"
14tokio = { version = "0.2.22", features = [ "rt-threaded", "sync" ] } 15tokio = { version = "0.2.22", features = [ "rt-threaded", "sync" ] }
15tracing = "0.1.19" 16tracing = "0.1.21"
16tracing-subscriber = "0.2.12" 17tracing-subscriber = "0.2.13"
17async-std = { version = "1.6.4", features = [ "unstable" ] } 18async-std = { version = "1.6.5", features = [ "unstable" ] }
18clap = "2.33.3" 19clap = "2.33.3"
19async-trait = "0.1.40" 20async-trait = "0.1.41"
20uuid = { version = "0.8.1", features = ["v4"] } 21uuid = { version = "0.8.1", features = ["v4"] }
21indoc = "1.0.2" 22indoc = "1.0.2"
22chrono = "0.4.15" 23chrono = "0.4.19"
23 24
24[dependencies.weechat] 25[dependencies.weechat]
25git = "https://github.com/poljar/rust-weechat" 26git = "https://github.com/poljar/rust-weechat"
26features = ["async", "config_macro"] 27features = ["async", "config_macro"]
27 28
28[dependencies.matrix-sdk] 29[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};
2 2
3use async_std::sync::{channel as async_channel, Receiver, Sender}; 3use async_std::sync::{channel as async_channel, Receiver, Sender};
4use tokio::runtime::Runtime; 4use tokio::runtime::Runtime;
@@ -18,7 +18,8 @@ pub use matrix_sdk::{
18 AnyMessageEventContent, AnySyncRoomEvent, AnySyncStateEvent, 18 AnyMessageEventContent, AnySyncRoomEvent, AnySyncStateEvent,
19 }, 19 },
20 identifiers::{RoomId, UserId}, 20 identifiers::{RoomId, UserId},
21 Client, ClientConfig, Result as MatrixResult, Room, SyncSettings, 21 locks::RwLock,
22 Client, ClientConfig, LoopCtrl, Result as MatrixResult, Room, SyncSettings,
22}; 23};
23 24
24use weechat::{JoinHandle, Weechat}; 25use weechat::{JoinHandle, Weechat};
@@ -32,7 +33,7 @@ pub enum ClientMessage {
32 LoginMessage(LoginResponse), 33 LoginMessage(LoginResponse),
33 SyncState(RoomId, AnySyncStateEvent), 34 SyncState(RoomId, AnySyncStateEvent),
34 SyncEvent(RoomId, AnySyncRoomEvent), 35 SyncEvent(RoomId, AnySyncRoomEvent),
35 RestoredRoom(Room), 36 RestoredRoom(Arc<RwLock<Room>>),
36} 37}
37 38
38/// Struc representing an active connection to the homeserver. 39/// Struc representing an active connection to the homeserver.
@@ -327,8 +328,6 @@ impl Connection {
327 if !first_login { 328 if !first_login {
328 let joined_rooms = client.joined_rooms(); 329 let joined_rooms = client.joined_rooms();
329 for room in joined_rooms.read().await.values() { 330 for room in joined_rooms.read().await.values() {
330 let room = room.read().await;
331 let room: &Room = &*room;
332 channel 331 channel
333 .send(Ok(ClientMessage::RestoredRoom(room.clone()))) 332 .send(Ok(ClientMessage::RestoredRoom(room.clone())))
334 .await 333 .await
@@ -348,7 +347,7 @@ impl Connection {
348 let sync_channel = &channel; 347 let sync_channel = &channel;
349 348
350 client 349 client
351 .sync_forever(sync_settings, async move |response| { 350 .sync_with_callback(sync_settings, async move |response| {
352 let channel = sync_channel; 351 let channel = sync_channel;
353 352
354 for (room_id, room) in response.rooms.join { 353 for (room_id, room) in response.rooms.join {
@@ -383,6 +382,8 @@ impl Connection {
383 } 382 }
384 } 383 }
385 } 384 }
385
386 LoopCtrl::Continue
386 }) 387 })
387 .await; 388 .await;
388 } 389 }
src/room_buffer.rs +37 −39
@@ -34,19 +34,20 @@ use matrix_sdk::{
34 MembershipState, 34 MembershipState,
35 }, 35 },
36 message::{MessageEventContent, TextMessageEventContent}, 36 message::{MessageEventContent, TextMessageEventContent},
37 name::NameEventContent,
38 }, 37 },
39 AnyMessageEventContent, AnyPossiblyRedactedSyncMessageEvent, 38 AnyMessageEventContent, AnyPossiblyRedactedSyncMessageEvent,
40 AnySyncMessageEvent, AnySyncRoomEvent, AnySyncStateEvent, 39 AnySyncMessageEvent, AnySyncRoomEvent, AnySyncStateEvent,
41 SyncStateEvent, 40 SyncStateEvent,
42 }, 41 },
43 identifiers::{RoomId, UserId}, 42 identifiers::{RoomId, UserId},
43 locks::{RwLock, RwLockReadGuard},
44 uuid::Uuid, 44 uuid::Uuid,
45 PossiblyRedactedExt, Room, 45 PossiblyRedactedExt, Room,
46}; 46};
47use url::Url; 47use url::Url;
48 48
49use async_trait::async_trait; 49use async_trait::async_trait;
50use futures::executor::block_on;
50use tracing::{debug, error, trace}; 51use tracing::{debug, error, trace};
51 52
52use crate::{ 53use crate::{
@@ -55,11 +56,11 @@ use crate::{
55}; 56};
56use std::{ 57use std::{
57 borrow::Cow, 58 borrow::Cow,
58 cell::{Ref, RefCell, RefMut}, 59 cell::RefCell,
59 collections::HashMap, 60 collections::HashMap,
60 convert::TryFrom, 61 convert::TryFrom,
61 rc::Rc, 62 rc::Rc,
62 sync::Mutex, 63 sync::{Arc, Mutex},
63 time::Instant, 64 time::Instant,
64}; 65};
65use weechat::{ 66use weechat::{
@@ -113,6 +114,7 @@ struct MatrixRoom {
113 homeserver: Rc<Url>, 114 homeserver: Rc<Url>,
114 room_id: Rc<RoomId>, 115 room_id: Rc<RoomId>,
115 own_user_id: Rc<UserId>, 116 own_user_id: Rc<UserId>,
117 room: Arc<RwLock<Room>>,
116 118
117 connection: Rc<RefCell<Option<Connection>>>, 119 connection: Rc<RefCell<Option<Connection>>>,
118 120
@@ -121,7 +123,6 @@ struct MatrixRoom {
121 123
122 local_echo_queue: Rc<RefCell<HashMap<Uuid, MessageEventContent>>>, 124 local_echo_queue: Rc<RefCell<HashMap<Uuid, MessageEventContent>>>,
123 125
124 room: Rc<RefCell<Room>>,
125 members: Rc<RefCell<HashMap<UserId, WeechatRoomMember>>>, 126 members: Rc<RefCell<HashMap<UserId, WeechatRoomMember>>>,
126} 127}
127 128
@@ -236,6 +237,7 @@ impl MatrixRoom {
236impl RoomBuffer { 237impl RoomBuffer {
237 pub fn new( 238 pub fn new(
238 connection: &Rc<RefCell<Option<Connection>>>, 239 connection: &Rc<RefCell<Option<Connection>>>,
240 room: Arc<RwLock<Room>>,
239 homeserver: &Url, 241 homeserver: &Url,
240 room_id: RoomId, 242 room_id: RoomId,
241 own_user_id: &UserId, 243 own_user_id: &UserId,
@@ -246,7 +248,7 @@ impl RoomBuffer {
246 connection: connection.clone(), 248 connection: connection.clone(),
247 typing_notice_time: Rc::new(RefCell::new(None)), 249 typing_notice_time: Rc::new(RefCell::new(None)),
248 typing_in_flight: Rc::new(Mutex::new(())), 250 typing_in_flight: Rc::new(Mutex::new(())),
249 room: Rc::new(RefCell::new(Room::new(&room_id, &own_user_id))), 251 room,
250 own_user_id: Rc::new(own_user_id.to_owned()), 252 own_user_id: Rc::new(own_user_id.to_owned()),
251 members: Rc::new(RefCell::new(HashMap::new())), 253 members: Rc::new(RefCell::new(HashMap::new())),
252 local_echo_queue: Rc::new(RefCell::new(HashMap::new())), 254 local_echo_queue: Rc::new(RefCell::new(HashMap::new())),
@@ -275,28 +277,34 @@ impl RoomBuffer {
275 } 277 }
276 278
277 pub fn restore( 279 pub fn restore(
278 room: Room, 280 room: Arc<RwLock<Room>>,
279 connection: &Rc<RefCell<Option<Connection>>>, 281 connection: &Rc<RefCell<Option<Connection>>>,
280 homeserver: &Url, 282 homeserver: &Url,
281 ) -> Self { 283 ) -> 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(
283 connection, 290 connection,
291 room_clone,
284 homeserver, 292 homeserver,
285 room.room_id.clone(), 293 room_id,
286 &room.own_user_id, 294 own_user_id,
287 ); 295 );
288 296
289 debug!("Restoring room {}", room.room_id); 297 debug!("Restoring room {}", room_lock.room_id);
290 298
291 let matrix_members = room 299 let matrix_members = room_lock
292 .joined_members 300 .joined_members
293 .values() 301 .values()
294 .chain(room.invited_members.values()); 302 .chain(room_lock.invited_members.values());
295 303
296 let mut weechat_members = HashMap::new(); 304 let mut weechat_members = HashMap::new();
297 305
298 for member in matrix_members { 306 for member in matrix_members {
299 let display_name = room 307 let display_name = room_lock
300 .get_member(&member.user_id) 308 .get_member(&member.user_id)
301 .unwrap() 309 .unwrap()
302 .display_name 310 .display_name
@@ -323,7 +331,6 @@ impl RoomBuffer {
323 .expect("Can't add nick to nicklist"); 331 .expect("Can't add nick to nicklist");
324 } 332 }
325 333
326 room_buffer.inner.room = Rc::new(RefCell::new(room));
327 room_buffer.inner.members.replace(weechat_members); 334 room_buffer.inner.members.replace(weechat_members);
328 room_buffer.update_buffer_name(); 335 room_buffer.update_buffer_name();
329 room_buffer.restore_messages(); 336 room_buffer.restore_messages();
@@ -365,12 +372,12 @@ impl RoomBuffer {
365 self.inner.send_message(buffer, content).await 372 self.inner.send_message(buffer, content).await
366 } 373 }
367 374
368 pub fn room_mut(&mut self) -> RefMut<'_, Room> { 375 pub fn room(&self) -> RwLockReadGuard<'_, Room> {
369 self.inner.room.borrow_mut() 376 block_on(self.inner.room.read())
370 } 377 }
371 378
372 pub fn room(&self) -> Ref<'_, Room> { 379 pub fn room_id(&self) -> &RoomId {
373 self.inner.room.borrow() 380 &self.inner.room_id
374 } 381 }
375 382
376 /// Retrieve a reference to a Weechat room member by user ID. 383 /// Retrieve a reference to a Weechat room member by user ID.
@@ -587,6 +594,7 @@ impl RoomBuffer {
587 /// 594 ///
588 /// Disambiguations are a hashmap of user ID -> bool indicating that this user is either newly 595 /// Disambiguations are a hashmap of user ID -> bool indicating that this user is either newly
589 /// ambiguous (true) or no longer ambiguous (false). 596 /// ambiguous (true) or no longer ambiguous (false).
597 #[allow(dead_code)]
590 fn process_disambiguations( 598 fn process_disambiguations(
591 &mut self, 599 &mut self,
592 disambiguations: &HashMap<UserId, bool>, 600 disambiguations: &HashMap<UserId, bool>,
@@ -648,10 +656,6 @@ impl RoomBuffer {
648 return; 656 return;
649 } 657 }
650 658
651 // Handle the event in the SDK room model
652 let (_, disambiguations) =
653 self.room_mut().handle_membership(event, state_event);
654
655 let new_nick = self.calculate_user_name(&target_id); 659 let new_nick = self.calculate_user_name(&target_id);
656 660
657 if state_event { 661 if state_event {
@@ -685,7 +689,9 @@ impl RoomBuffer {
685 _ => (), 689 _ => (),
686 } 690 }
687 691
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);
689 695
690 // Names of rooms without display names can get affected by the member list so we need to 696 // Names of rooms without display names can get affected by the member list so we need to
691 // update them. 697 // update them.
@@ -792,7 +798,9 @@ impl RoomBuffer {
792 } 798 }
793 }; 799 };
794 800
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);
796 804
797 // Names of rooms without display names can get affected by the member list so we need to 805 // Names of rooms without display names can get affected by the member list so we need to
798 // update them. 806 // update them.
@@ -860,11 +868,7 @@ impl RoomBuffer {
860 buffer.print_date_tags(timestamp as i64, &[], &message); 868 buffer.print_date_tags(timestamp as i64, &[], &message);
861 } 869 }
862 870
863 pub fn handle_room_name( 871 pub fn handle_room_name(&self) {
864 &mut self,
865 event: &SyncStateEvent<NameEventContent>,
866 ) {
867 self.room_mut().handle_room_name(event);
868 self.update_buffer_name(); 872 self.update_buffer_name();
869 } 873 }
870 874
@@ -885,14 +889,11 @@ impl RoomBuffer {
885 AnySyncStateEvent::RoomMember(e) => { 889 AnySyncStateEvent::RoomMember(e) => {
886 self.handle_membership_event(e, false) 890 self.handle_membership_event(e, false)
887 } 891 }
888 AnySyncStateEvent::RoomName(n) => self.handle_room_name(n), 892 AnySyncStateEvent::RoomName(_) => self.handle_room_name(),
889 _ => (), 893 _ => (),
890 }, 894 },
891 895
892 event => { 896 _ => (),
893 let mut room = self.room_mut();
894 room.receive_timeline_event(event);
895 }
896 } 897 }
897 } 898 }
898 899
@@ -901,11 +902,8 @@ impl RoomBuffer {
901 AnySyncStateEvent::RoomMember(e) => { 902 AnySyncStateEvent::RoomMember(e) => {
902 self.handle_membership_event(e, true) 903 self.handle_membership_event(e, true)
903 } 904 }
904 AnySyncStateEvent::RoomName(n) => self.handle_room_name(n), 905 AnySyncStateEvent::RoomName(_) => self.handle_room_name(),
905 _ => { 906 _ => (),
906 let mut room = self.room_mut();
907 room.receive_state_event(&event);
908 }
909 } 907 }
910 } 908 }
911} 909}
src/server.rs +14 −3
@@ -55,12 +55,14 @@
55//! that processing events will not block the Weechat mainloop for too long. 55//! that processing events will not block the Weechat mainloop for too long.
56 56
57use chrono::{offset::Utc, DateTime}; 57use chrono::{offset::Utc, DateTime};
58use futures::executor::block_on;
58use indoc::indoc; 59use indoc::indoc;
59use std::{ 60use std::{
60 cell::{Ref, RefCell, RefMut}, 61 cell::{Ref, RefCell, RefMut},
61 collections::HashMap, 62 collections::HashMap,
62 path::PathBuf, 63 path::PathBuf,
63 rc::{Rc, Weak}, 64 rc::{Rc, Weak},
65 sync::Arc,
64}; 66};
65use url::Url; 67use url::Url;
66 68
@@ -69,6 +71,7 @@ use matrix_sdk::{
69 api::r0::session::login::Response as LoginResponse, 71 api::r0::session::login::Response as LoginResponse,
70 events::{AnySyncRoomEvent, AnySyncStateEvent}, 72 events::{AnySyncRoomEvent, AnySyncStateEvent},
71 identifiers::{RoomId, UserId}, 73 identifiers::{RoomId, UserId},
74 locks::RwLock,
72 Client, ClientConfig, Room, 75 Client, ClientConfig, Room,
73}; 76};
74 77
@@ -549,8 +552,17 @@ impl InnerServer {
549 .login_state 552 .login_state
550 .as_ref() 553 .as_ref()
551 .expect("Receiving events while not being logged in"); 554 .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");
552 let buffer = RoomBuffer::new( 563 let buffer = RoomBuffer::new(
553 &self.connection, 564 &self.connection,
565 room,
554 homeserver, 566 homeserver,
555 room_id.clone(), 567 room_id.clone(),
556 &login_state.user_id, 568 &login_state.user_id,
@@ -573,16 +585,15 @@ impl InnerServer {
573 self.config.borrow() 585 self.config.borrow()
574 } 586 }
575 587
576 pub fn restore_room(&mut self, room: Room) { 588 pub fn restore_room(&mut self, room: Arc<RwLock<Room>>) {
577 let homeserver = self 589 let homeserver = self
578 .settings 590 .settings
579 .homeserver 591 .homeserver
580 .as_ref() 592 .as_ref()
581 .expect("Creating room buffer while no homeserver"); 593 .expect("Creating room buffer while no homeserver");
582 594
583 let room_id = room.room_id.clone();
584
585 let buffer = RoomBuffer::restore(room, &self.connection, homeserver); 595 let buffer = RoomBuffer::restore(room, &self.connection, homeserver);
596 let room_id = buffer.room_id().to_owned();
586 597
587 self.room_buffers.insert(room_id, buffer); 598 self.room_buffers.insert(room_id, buffer);
588 } 599 }