Commit a95b6ca9e8

a95b6ca9e89108bf60eae6a7117266339267dba9

parent: 5db630db37

Unsigned

Damir Jelić <poljar@termina.org.uk> · 2020-07-06 17:41 UTC

server: Get rid of the send loop and spawn tasks directly.

Layout: unified · split

src/room_buffer.rs +4 −4
@@ -64,7 +64,6 @@ pub struct MatrixRoom {
6464#[async_trait(?Send)]
6565impl BufferInputCallbackAsync for MatrixRoom {
6666 async fn callback(&mut self, buffer: BufferHandle, input: String) {
67 let room_id = &self.room_id;
6867 let connection = &self.connection;
6968
7069 let buffer = buffer
@@ -73,7 +72,10 @@ impl BufferInputCallbackAsync for MatrixRoom {
7372
7473 if let Some(c) = &*connection.borrow() {
7574 // TODO check for errors and print them out.
76 c.send_message(&room_id, &input).await;
75 match c.send_message(&self.room_id, input).await {
76 Ok(_r) => (),
77 Err(_e) => (),
78 }
7779 } else {
7880 buffer.print("Error not connected");
7981 return;
@@ -159,10 +161,8 @@ impl RoomBuffer {
159161 let room = self.room();
160162 let buffer = self.weechat_buffer();
161163
162 Weechat::print(&format!("HELLO WORLD RESTORING {}", buffer.name()));
163164 if buffer.num_lines() == 0 {
164165 for message in room.messages.iter() {
165 Weechat::print(&format!("RESTOGIN MESSAGE {:?}", message));
166166 self.handle_room_message(message)
167167 }
168168 }
src/server.rs +42 −56
@@ -6,12 +6,15 @@
66//! server they need to be removed from the server section when the server is
77//! dropped.
88//!
9//! The server will create a tokio runtime which will spawn two tasks, one for
10//! the sync loop and one to send out room messages.
9//! The server will create a tokio runtime which will spawn a task for the sync
10//! loop.
1111//!
12//! If will also spawn a task on the Weechat mainloop, this one waits for
12//! It will also spawn a task on the Weechat mainloop, this one waits for
1313//! responses from the sync loop.
1414//!
15//! A separate task is spawned every time Weechat wants to send a message to the
16//! server.
17//!
1518//!
1619//! Schematically this looks like the following diagram.
1720//!
@@ -29,8 +32,8 @@
2932//! | | +--------------------+ | | +----------------+ | |
3033//! | | | | | |
3134//! | | +--------------------+ | | +----------------+ | |
32//! | | | | | | | | | |
33//! | | | Roombuffer input +--------------->+ Send loop | | |
35//! | | | | | Spawn | | | | |
36//! | | | Roombuffer input +--------------->+ Send coroutine | | |
3437//! | | | callback +<---------------+ | | |
3538//! | | | | | | | | | |
3639//! | | +--------------------+ | | +----------------+ | |
@@ -66,12 +69,13 @@ use matrix_sdk::api::r0::session::login::Response as LoginResponse;
6669
6770use matrix_sdk::{
6871 self,
72 api::r0::message::create_message_event::Response as RoomSendResponse,
6973 events::{
7074 collections::all::{RoomEvent, StateEvent},
7175 room::message::{MessageEventContent, TextMessageEventContent},
7276 },
7377 identifiers::{RoomId, UserId},
74 Client, ClientConfig, Room, SyncSettings,
78 Client, ClientConfig, Result as MatrixResult, Room, SyncSettings,
7579};
7680
7781use weechat::buffer::{BufferHandle, BufferSettings};
@@ -100,10 +104,6 @@ pub enum ServerError {
100104 IoError(String),
101105}
102106
103pub enum ServerMessage {
104 RoomSend(RoomId, String),
105}
106
107107#[derive(Default)]
108108pub struct ServerSettings {
109109 homeserver: Option<Url>,
@@ -124,22 +124,43 @@ pub struct LoginInfo {
124124}
125125
126126pub struct Connection {
127 client_channel: Sender<ServerMessage>,
128127 response_receiver: JoinHandle<(), ()>,
129 // TODO move the runtime into the plugin, once we're able to cancel tokio
130 // tasks.
128 client: Client,
131129 #[used]
132130 runtime: Runtime,
133131}
134132
135133impl Connection {
136 pub async fn send_message(&self, room_id: &RoomId, message: &str) {
137 self.client_channel
138 .send(ServerMessage::RoomSend(
139 room_id.to_owned(),
140 message.to_owned(),
141 ))
134 pub async fn send_message(
135 &self,
136 room_id: &RoomId,
137 message: String,
138 ) -> MatrixResult<RoomSendResponse> {
139 let room_id = room_id.to_owned();
140 let client = self.client.clone();
141
142 let handle = self
143 .runtime
144 .spawn(async move {
145 let content =
146 MessageEventContent::Text(TextMessageEventContent {
147 body: message,
148 format: None,
149 formatted_body: None,
150 relates_to: None,
151 });
152
153 let ret = client
154 .room_send(&room_id, content, Some(Uuid::new_v4()))
155 .await;
156 ret
157 })
142158 .await;
159
160 match handle {
161 Ok(response) => response,
162 Err(e) => panic!("Tokio error while sending a message {:?}", e),
163 }
143164 }
144165}
145166
@@ -427,14 +448,11 @@ impl MatrixServer {
427448 MatrixServer::response_receiver(rx, Rc::downgrade(&self.inner)),
428449 );
429450
430 let (client_sender, client_receiver) = async_channel(10);
431 runtime.spawn(MatrixServer::send_loop(client, client_receiver));
432
433451 let mut connected_state = server.connected_state.borrow_mut();
434452
435453 *connected_state = Some(Connection {
454 client,
436455 response_receiver,
437 client_channel: client_sender,
438456 runtime,
439457 });
440458
@@ -464,7 +482,7 @@ impl MatrixServer {
464482 }
465483
466484 {
467 let server = self.inner.borrow_mut();
485 let server = self.inner();
468486 let mut connected_state = server.connected_state.borrow_mut();
469487 let state = connected_state.take();
470488
@@ -635,38 +653,6 @@ impl MatrixServer {
635653 };
636654 }
637655 }
638
639 /// Send loop that waits for requests that need to be sent out using our
640 /// Matrix client.
641 pub async fn send_loop(client: Client, channel: Receiver<ServerMessage>) {
642 while let Ok(message) = channel.recv().await {
643 match message {
644 ServerMessage::RoomSend(room_id, message) => {
645 let content =
646 MessageEventContent::Text(TextMessageEventContent {
647 body: message,
648 format: None,
649 formatted_body: None,
650 relates_to: None,
651 });
652
653 // TODO awaiting here means we can only send one message
654 // at a time, we need to spawn a task here and return a
655 // oneshot channel that the caller can await.
656 // TODO the room should remember the UUID for the local echo
657 // implementation.
658 let ret = client
659 .room_send(&room_id, content, Some(Uuid::new_v4()))
660 .await;
661
662 match ret {
663 Ok(_r) => (),
664 Err(_e) => (),
665 }
666 }
667 }
668 }
669 }
670656}
671657
672658impl Drop for MatrixServer {