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 {
64#[async_trait(?Send)] 64#[async_trait(?Send)]
65impl BufferInputCallbackAsync for MatrixRoom { 65impl BufferInputCallbackAsync for MatrixRoom {
66 async fn callback(&mut self, buffer: BufferHandle, input: String) { 66 async fn callback(&mut self, buffer: BufferHandle, input: String) {
67 let room_id = &self.room_id;
68 let connection = &self.connection; 67 let connection = &self.connection;
69 68
70 let buffer = buffer 69 let buffer = buffer
@@ -73,7 +72,10 @@ impl BufferInputCallbackAsync for MatrixRoom {
73 72
74 if let Some(c) = &*connection.borrow() { 73 if let Some(c) = &*connection.borrow() {
75 // TODO check for errors and print them out. 74 // 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 }
77 } else { 79 } else {
78 buffer.print("Error not connected"); 80 buffer.print("Error not connected");
79 return; 81 return;
@@ -159,10 +161,8 @@ impl RoomBuffer {
159 let room = self.room(); 161 let room = self.room();
160 let buffer = self.weechat_buffer(); 162 let buffer = self.weechat_buffer();
161 163
162 Weechat::print(&format!("HELLO WORLD RESTORING {}", buffer.name()));
163 if buffer.num_lines() == 0 { 164 if buffer.num_lines() == 0 {
164 for message in room.messages.iter() { 165 for message in room.messages.iter() {
165 Weechat::print(&format!("RESTOGIN MESSAGE {:?}", message));
166 self.handle_room_message(message) 166 self.handle_room_message(message)
167 } 167 }
168 } 168 }
src/server.rs +42 −56
@@ -6,12 +6,15 @@
6//! server they need to be removed from the server section when the server is 6//! server they need to be removed from the server section when the server is
7//! dropped. 7//! dropped.
8//! 8//!
9//! The server will create a tokio runtime which will spawn two tasks, one for 9//! The server will create a tokio runtime which will spawn a task for the sync
10//! the sync loop and one to send out room messages. 10//! loop.
11//! 11//!
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
13//! responses from the sync loop. 13//! responses from the sync loop.
14//! 14//!
15//! A separate task is spawned every time Weechat wants to send a message to the
16//! server.
17//!
15//! 18//!
16//! Schematically this looks like the following diagram. 19//! Schematically this looks like the following diagram.
17//! 20//!
@@ -29,8 +32,8 @@
29//! | | +--------------------+ | | +----------------+ | | 32//! | | +--------------------+ | | +----------------+ | |
30//! | | | | | | 33//! | | | | | |
31//! | | +--------------------+ | | +----------------+ | | 34//! | | +--------------------+ | | +----------------+ | |
32//! | | | | | | | | | | 35//! | | | | | Spawn | | | | |
33//! | | | Roombuffer input +--------------->+ Send loop | | | 36//! | | | Roombuffer input +--------------->+ Send coroutine | | |
34//! | | | callback +<---------------+ | | | 37//! | | | callback +<---------------+ | | |
35//! | | | | | | | | | | 38//! | | | | | | | | | |
36//! | | +--------------------+ | | +----------------+ | | 39//! | | +--------------------+ | | +----------------+ | |
@@ -66,12 +69,13 @@ use matrix_sdk::api::r0::session::login::Response as LoginResponse;
66 69
67use matrix_sdk::{ 70use matrix_sdk::{
68 self, 71 self,
72 api::r0::message::create_message_event::Response as RoomSendResponse,
69 events::{ 73 events::{
70 collections::all::{RoomEvent, StateEvent}, 74 collections::all::{RoomEvent, StateEvent},
71 room::message::{MessageEventContent, TextMessageEventContent}, 75 room::message::{MessageEventContent, TextMessageEventContent},
72 }, 76 },
73 identifiers::{RoomId, UserId}, 77 identifiers::{RoomId, UserId},
74 Client, ClientConfig, Room, SyncSettings, 78 Client, ClientConfig, Result as MatrixResult, Room, SyncSettings,
75}; 79};
76 80
77use weechat::buffer::{BufferHandle, BufferSettings}; 81use weechat::buffer::{BufferHandle, BufferSettings};
@@ -100,10 +104,6 @@ pub enum ServerError {
100 IoError(String), 104 IoError(String),
101} 105}
102 106
103pub enum ServerMessage {
104 RoomSend(RoomId, String),
105}
106
107#[derive(Default)] 107#[derive(Default)]
108pub struct ServerSettings { 108pub struct ServerSettings {
109 homeserver: Option<Url>, 109 homeserver: Option<Url>,
@@ -124,22 +124,43 @@ pub struct LoginInfo {
124} 124}
125 125
126pub struct Connection { 126pub struct Connection {
127 client_channel: Sender<ServerMessage>,
128 response_receiver: JoinHandle<(), ()>, 127 response_receiver: JoinHandle<(), ()>,
129 // TODO move the runtime into the plugin, once we're able to cancel tokio 128 client: Client,
130 // tasks.
131 #[used] 129 #[used]
132 runtime: Runtime, 130 runtime: Runtime,
133} 131}
134 132
135impl Connection { 133impl Connection {
136 pub async fn send_message(&self, room_id: &RoomId, message: &str) { 134 pub async fn send_message(
137 self.client_channel 135 &self,
138 .send(ServerMessage::RoomSend( 136 room_id: &RoomId,
139 room_id.to_owned(), 137 message: String,
140 message.to_owned(), 138 ) -> MatrixResult<RoomSendResponse> {
141 )) 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 })
142 .await; 158 .await;
159
160 match handle {
161 Ok(response) => response,
162 Err(e) => panic!("Tokio error while sending a message {:?}", e),
163 }
143 } 164 }
144} 165}
145 166
@@ -427,14 +448,11 @@ impl MatrixServer {
427 MatrixServer::response_receiver(rx, Rc::downgrade(&self.inner)), 448 MatrixServer::response_receiver(rx, Rc::downgrade(&self.inner)),
428 ); 449 );
429 450
430 let (client_sender, client_receiver) = async_channel(10);
431 runtime.spawn(MatrixServer::send_loop(client, client_receiver));
432
433 let mut connected_state = server.connected_state.borrow_mut(); 451 let mut connected_state = server.connected_state.borrow_mut();
434 452
435 *connected_state = Some(Connection { 453 *connected_state = Some(Connection {
454 client,
436 response_receiver, 455 response_receiver,
437 client_channel: client_sender,
438 runtime, 456 runtime,
439 }); 457 });
440 458
@@ -464,7 +482,7 @@ impl MatrixServer {
464 } 482 }
465 483
466 { 484 {
467 let server = self.inner.borrow_mut(); 485 let server = self.inner();
468 let mut connected_state = server.connected_state.borrow_mut(); 486 let mut connected_state = server.connected_state.borrow_mut();
469 let state = connected_state.take(); 487 let state = connected_state.take();
470 488
@@ -635,38 +653,6 @@ impl MatrixServer {
635 }; 653 };
636 } 654 }
637 } 655 }
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 }
670} 656}
671 657
672impl Drop for MatrixServer { 658impl Drop for MatrixServer {