Commit 61897ea6f2

61897ea6f2d2de09b4ce6fd6d1a5a0abf4aa539e

parent: 6a0722795a

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-03-13 17:46 UTC

Fetch scrollback history independently of main loop (#39)

Layout: unified · split

src/base.rs +4 −58
@@ -7,7 +7,6 @@ use std::time::{Duration, Instant};
7 7
8use emojis::Emoji; 8use emojis::Emoji;
9use tokio::sync::Mutex as AsyncMutex; 9use tokio::sync::Mutex as AsyncMutex;
10use tracing::warn;
11 10
12use matrix_sdk::{ 11use matrix_sdk::{
13 encryption::verification::SasVerification, 12 encryption::verification::SasVerification,
@@ -23,7 +22,6 @@ use matrix_sdk::{
23 RoomMessageEventContent, 22 RoomMessageEventContent,
24 }, 23 },
25 tag::{TagName, Tags}, 24 tag::{TagName, Tags},
26 AnyMessageLikeEvent,
27 MessageLikeEvent, 25 MessageLikeEvent,
28 }, 26 },
29 presence::PresenceState, 27 presence::PresenceState,
@@ -412,6 +410,9 @@ pub struct RoomInfo {
412 /// A map of message identifiers to a map of reaction events. 410 /// A map of message identifiers to a map of reaction events.
413 pub reactions: HashMap<OwnedEventId, MessageReactions>, 411 pub reactions: HashMap<OwnedEventId, MessageReactions>,
414 412
413 /// Whether the scrollback for this room is currently being fetched.
414 pub fetching: bool,
415
415 /// Where to continue fetching from when we continue loading scrollback history. 416 /// Where to continue fetching from when we continue loading scrollback history.
416 pub fetch_id: RoomFetchStatus, 417 pub fetch_id: RoomFetchStatus,
417 418
@@ -520,7 +521,7 @@ impl RoomInfo {
520 } 521 }
521 } 522 }
522 523
523 fn recently_fetched(&self) -> bool { 524 pub fn recently_fetched(&self) -> bool {
524 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE) 525 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
525 } 526 }
526 527
@@ -668,61 +669,6 @@ impl ChatStore {
668 self.need_load.insert(room_id); 669 self.need_load.insert(room_id);
669 } 670 }
670 671
671 pub fn load_older(&mut self, limit: u32) {
672 let ChatStore { need_load, presences, rooms, worker, .. } = self;
673
674 for room_id in std::mem::take(need_load).into_iter() {
675 let info = rooms.get_or_default(room_id.clone());
676
677 if info.recently_fetched() {
678 need_load.insert(room_id);
679 continue;
680 } else {
681 info.fetch_last = Instant::now().into();
682 }
683
684 let fetch_id = match &info.fetch_id {
685 RoomFetchStatus::Done => continue,
686 RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
687 RoomFetchStatus::NotStarted => None,
688 };
689
690 let res = worker.load_older(room_id.clone(), fetch_id, limit);
691
692 match res {
693 Ok((fetch_id, msgs)) => {
694 for msg in msgs.into_iter() {
695 let sender = msg.sender().to_owned();
696 let _ = presences.get_or_default(sender);
697
698 match msg {
699 AnyMessageLikeEvent::RoomMessage(msg) => {
700 info.insert(msg);
701 },
702 AnyMessageLikeEvent::Reaction(ev) => {
703 info.insert_reaction(ev);
704 },
705 _ => continue,
706 }
707 }
708
709 info.fetch_id =
710 fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore);
711 },
712 Err(e) => {
713 warn!(
714 room_id = room_id.as_str(),
715 err = e.to_string(),
716 "Failed to load older messages"
717 );
718
719 // Wait and try again.
720 need_load.insert(room_id);
721 },
722 }
723 }
724 }
725
726 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo { 672 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
727 self.rooms.get_or_default(room_id) 673 self.rooms.get_or_default(room_id)
728 } 674 }
src/main.rs −10
@@ -101,14 +101,6 @@ use modalkit::{
101 }, 101 },
102}; 102};
103 103
104const MIN_MSG_LOAD: u32 = 50;
105
106fn msg_load_req(area: Rect) -> u32 {
107 let n = area.height as u32;
108
109 n.max(MIN_MSG_LOAD)
110}
111
112struct Application { 104struct Application {
113 store: AsyncProgramStore, 105 store: AsyncProgramStore,
114 worker: Requester, 106 worker: Requester,
@@ -190,8 +182,6 @@ impl Application {
190 } 182 }
191 f.set_cursor(cx, cy); 183 f.set_cursor(cx, cy);
192 } 184 }
193
194 store.application.load_older(msg_load_req(area));
195 })?; 185 })?;
196 186
197 Ok(()) 187 Ok(())
src/tests.rs +1
@@ -153,6 +153,7 @@ pub fn mock_room() -> RoomInfo {
153 read_till: None, 153 read_till: None,
154 reactions: HashMap::new(), 154 reactions: HashMap::new(),
155 155
156 fetching: false,
156 fetch_id: RoomFetchStatus::NotStarted, 157 fetch_id: RoomFetchStatus::NotStarted,
157 fetch_last: None, 158 fetch_last: None,
158 users_typing: None, 159 users_typing: None,
src/worker.rs +144 −69
@@ -1,3 +1,4 @@
1use std::collections::HashMap;
1use std::convert::TryFrom; 2use std::convert::TryFrom;
2use std::fmt::{Debug, Formatter}; 3use std::fmt::{Debug, Formatter};
3use std::fs::File; 4use std::fs::File;
@@ -5,12 +6,12 @@ use std::io::BufWriter;
5use std::str::FromStr; 6use std::str::FromStr;
6use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; 7use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
7use std::sync::Arc; 8use std::sync::Arc;
8use std::time::Duration; 9use std::time::{Duration, Instant};
9 10
10use gethostname::gethostname; 11use gethostname::gethostname;
11use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; 12use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
12use tokio::task::JoinHandle; 13use tokio::task::JoinHandle;
13use tracing::error; 14use tracing::{error, warn};
14 15
15use matrix_sdk::{ 16use matrix_sdk::{
16 config::{RequestConfig, StoreConfig, SyncSettings}, 17 config::{RequestConfig, StoreConfig, SyncSettings},
@@ -44,6 +45,7 @@ use matrix_sdk::{
44 tag::Tags, 45 tag::Tags,
45 typing::SyncTypingEvent, 46 typing::SyncTypingEvent,
46 AnyInitialStateEvent, 47 AnyInitialStateEvent,
48 AnyMessageLikeEvent,
47 AnyTimelineEvent, 49 AnyTimelineEvent,
48 EmptyStateKey, 50 EmptyStateKey,
49 InitialStateEvent, 51 InitialStateEvent,
@@ -56,6 +58,7 @@ use matrix_sdk::{
56 OwnedRoomId, 58 OwnedRoomId,
57 OwnedRoomOrAliasId, 59 OwnedRoomOrAliasId,
58 OwnedUserId, 60 OwnedUserId,
61 RoomId,
59 RoomVersionId, 62 RoomVersionId,
60 }, 63 },
61 Client, 64 Client,
@@ -68,12 +71,14 @@ use modalkit::editing::action::{EditInfo, InfoMessage, UIError};
68use crate::{ 71use crate::{
69 base::{ 72 base::{
70 AsyncProgramStore, 73 AsyncProgramStore,
74 ChatStore,
71 CreateRoomFlags, 75 CreateRoomFlags,
72 CreateRoomType, 76 CreateRoomType,
73 EventLocation, 77 EventLocation,
74 IambError, 78 IambError,
75 IambResult, 79 IambResult,
76 Receipts, 80 Receipts,
81 RoomFetchStatus,
77 VerifyAction, 82 VerifyAction,
78 }, 83 },
79 message::MessageFetchResult, 84 message::MessageFetchResult,
@@ -82,6 +87,7 @@ use crate::{
82 87
83const IAMB_DEVICE_NAME: &str = "iamb"; 88const IAMB_DEVICE_NAME: &str = "iamb";
84const IAMB_USER_AGENT: &str = "iamb"; 89const IAMB_USER_AGENT: &str = "iamb";
90const MIN_MSG_LOAD: u32 = 50;
85 91
86fn initial_devname() -> String { 92fn initial_devname() -> String {
87 format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy()) 93 format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy())
@@ -158,6 +164,113 @@ pub async fn create_room(
158 return Ok(resp.room_id); 164 return Ok(resp.room_id);
159} 165}
160 166
167async fn load_plan(store: &AsyncProgramStore) -> HashMap<OwnedRoomId, Option<String>> {
168 let mut locked = store.lock().await;
169 let ChatStore { need_load, rooms, .. } = &mut locked.application;
170 let mut plan = HashMap::new();
171
172 for room_id in std::mem::take(need_load).into_iter() {
173 let info = rooms.get_or_default(room_id.clone());
174
175 if info.recently_fetched() || info.fetching {
176 need_load.insert(room_id);
177 continue;
178 } else {
179 info.fetch_last = Instant::now().into();
180 info.fetching = true;
181 }
182
183 let fetch_id = match &info.fetch_id {
184 RoomFetchStatus::Done => continue,
185 RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
186 RoomFetchStatus::NotStarted => None,
187 };
188
189 plan.insert(room_id, fetch_id);
190 }
191
192 return plan;
193}
194
195async fn load_older_one(
196 client: Client,
197 room_id: &RoomId,
198 fetch_id: Option<String>,
199 limit: u32,
200) -> MessageFetchResult {
201 if let Some(room) = client.get_room(room_id) {
202 let mut opts = match &fetch_id {
203 Some(id) => MessagesOptions::backward().from(id.as_str()),
204 None => MessagesOptions::backward(),
205 };
206 opts.limit = limit.into();
207
208 let Messages { end, chunk, .. } = room.messages(opts).await.map_err(IambError::from)?;
209
210 let msgs = chunk.into_iter().filter_map(|ev| {
211 match ev.event.deserialize() {
212 Ok(AnyTimelineEvent::MessageLike(msg)) => Some(msg),
213 Ok(AnyTimelineEvent::State(_)) => None,
214 Err(_) => None,
215 }
216 });
217
218 Ok((end, msgs.collect()))
219 } else {
220 Err(IambError::UnknownRoom(room_id.to_owned()).into())
221 }
222}
223
224async fn load_insert(room_id: OwnedRoomId, res: MessageFetchResult, store: AsyncProgramStore) {
225 let mut locked = store.lock().await;
226 let ChatStore { need_load, presences, rooms, .. } = &mut locked.application;
227 let info = rooms.get_or_default(room_id.clone());
228 info.fetching = false;
229
230 match res {
231 Ok((fetch_id, msgs)) => {
232 for msg in msgs.into_iter() {
233 let sender = msg.sender().to_owned();
234 let _ = presences.get_or_default(sender);
235
236 match msg {
237 AnyMessageLikeEvent::RoomMessage(msg) => {
238 info.insert(msg);
239 },
240 AnyMessageLikeEvent::Reaction(ev) => {
241 info.insert_reaction(ev);
242 },
243 _ => continue,
244 }
245 }
246
247 info.fetch_id = fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore);
248 },
249 Err(e) => {
250 warn!(room_id = room_id.as_str(), err = e.to_string(), "Failed to load older messages");
251
252 // Wait and try again.
253 need_load.insert(room_id);
254 },
255 }
256}
257
258async fn load_older(client: &Client, store: &AsyncProgramStore) {
259 let limit = MIN_MSG_LOAD;
260 let plan = load_plan(store).await;
261
262 // Fetch each room separately, so they don't block each other.
263 for (room_id, fetch_id) in plan.into_iter() {
264 let client = client.clone();
265 let store = store.clone();
266
267 tokio::spawn(async move {
268 let res = load_older_one(client, room_id.as_ref(), fetch_id, limit).await;
269 load_insert(room_id, res, store).await;
270 });
271 }
272}
273
161#[derive(Debug)] 274#[derive(Debug)]
162pub enum LoginStyle { 275pub enum LoginStyle {
163 SessionRestore(Session), 276 SessionRestore(Session),
@@ -216,7 +329,6 @@ pub enum WorkerTask {
216 ActiveRooms(ClientReply<Vec<FetchedRoom>>), 329 ActiveRooms(ClientReply<Vec<FetchedRoom>>),
217 DirectMessages(ClientReply<Vec<FetchedRoom>>), 330 DirectMessages(ClientReply<Vec<FetchedRoom>>),
218 Init(AsyncProgramStore, ClientReply<()>), 331 Init(AsyncProgramStore, ClientReply<()>),
219 LoadOlder(OwnedRoomId, Option<String>, u32, ClientReply<MessageFetchResult>),
220 Login(LoginStyle, ClientReply<IambResult<EditInfo>>), 332 Login(LoginStyle, ClientReply<IambResult<EditInfo>>),
221 GetInviter(Invited, ClientReply<IambResult<Option<RoomMember>>>), 333 GetInviter(Invited, ClientReply<IambResult<Option<RoomMember>>>),
222 GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>), 334 GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>),
@@ -246,14 +358,6 @@ impl Debug for WorkerTask {
246 .field(&format_args!("_")) 358 .field(&format_args!("_"))
247 .finish() 359 .finish()
248 }, 360 },
249 WorkerTask::LoadOlder(room_id, from, n, _) => {
250 f.debug_tuple("WorkerTask::LoadOlder")
251 .field(room_id)
252 .field(from)
253 .field(n)
254 .field(&format_args!("_"))
255 .finish()
256 },
257 WorkerTask::Login(style, _) => { 361 WorkerTask::Login(style, _) => {
258 f.debug_tuple("WorkerTask::Login") 362 f.debug_tuple("WorkerTask::Login")
259 .field(style) 363 .field(style)
@@ -325,21 +429,6 @@ impl Requester {
325 return response.recv(); 429 return response.recv();
326 } 430 }
327 431
328 pub fn load_older(
329 &self,
330 room_id: OwnedRoomId,
331 fetch_id: Option<String>,
332 limit: u32,
333 ) -> MessageFetchResult {
334 let (reply, response) = oneshot();
335
336 self.tx
337 .send(WorkerTask::LoadOlder(room_id, fetch_id, limit, reply))
338 .unwrap();
339
340 return response.recv();
341 }
342
343 pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> { 432 pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> {
344 let (reply, response) = oneshot(); 433 let (reply, response) = oneshot();
345 434
@@ -437,8 +526,9 @@ pub struct ClientWorker {
437 initialized: bool, 526 initialized: bool,
438 settings: ApplicationSettings, 527 settings: ApplicationSettings,
439 client: Client, 528 client: Client,
440 sync_handle: Option<JoinHandle<()>>, 529 load_handle: Option<JoinHandle<()>>,
441 rcpt_handle: Option<JoinHandle<()>>, 530 rcpt_handle: Option<JoinHandle<()>>,
531 sync_handle: Option<JoinHandle<()>>,
442} 532}
443 533
444impl ClientWorker { 534impl ClientWorker {
@@ -476,8 +566,9 @@ impl ClientWorker {
476 initialized: false, 566 initialized: false,
477 settings, 567 settings,
478 client: client.clone(), 568 client: client.clone(),
479 sync_handle: None, 569 load_handle: None,
480 rcpt_handle: None, 570 rcpt_handle: None,
571 sync_handle: None,
481 }; 572 };
482 573
483 tokio::spawn(async move { 574 tokio::spawn(async move {
@@ -535,10 +626,6 @@ impl ClientWorker {
535 assert!(self.initialized); 626 assert!(self.initialized);
536 reply.send(self.active_rooms().await); 627 reply.send(self.active_rooms().await);
537 }, 628 },
538 WorkerTask::LoadOlder(room_id, fetch_id, limit, reply) => {
539 assert!(self.initialized);
540 reply.send(self.load_older(room_id, fetch_id, limit).await);
541 },
542 WorkerTask::Login(style, reply) => { 629 WorkerTask::Login(style, reply) => {
543 assert!(self.initialized); 630 assert!(self.initialized);
544 reply.send(self.login_and_sync(style).await); 631 reply.send(self.login_and_sync(style).await);
@@ -811,17 +898,34 @@ impl ClientWorker {
811 }, 898 },
812 ); 899 );
813 900
814 let client = self.client.clone(); 901 self.rcpt_handle = tokio::spawn({
902 let store = store.clone();
903 let client = self.client.clone();
815 904
816 self.rcpt_handle = tokio::spawn(async move { 905 async move {
817 // Update the displayed read receipts ever 5 seconds. 906 // Update the displayed read receipts every 5 seconds.
818 let mut interval = tokio::time::interval(Duration::from_secs(5)); 907 let mut interval = tokio::time::interval(Duration::from_secs(5));
819 908
820 loop { 909 loop {
821 interval.tick().await; 910 interval.tick().await;
911
912 let receipts = update_receipts(&client).await;
913 store.lock().await.application.set_receipts(receipts).await;
914 }
915 }
916 })
917 .into();
918
919 self.load_handle = tokio::spawn({
920 let client = self.client.clone();
822 921
823 let receipts = update_receipts(&client).await; 922 async move {
824 store.lock().await.application.set_receipts(receipts).await; 923 // Load older messages every 2 seconds.
924 let mut interval = tokio::time::interval(Duration::from_secs(2));
925 loop {
926 interval.tick().await;
927 load_older(&client, &store).await;
928 }
825 } 929 }
826 }) 930 })
827 .into(); 931 .into();
@@ -991,35 +1095,6 @@ impl ClientWorker {
991 return rooms; 1095 return rooms;
992 } 1096 }
993 1097
994 async fn load_older(
995 &mut self,
996 room_id: OwnedRoomId,
997 fetch_id: Option<String>,
998 limit: u32,
999 ) -> MessageFetchResult {
1000 if let Some(room) = self.client.get_room(room_id.as_ref()) {
1001 let mut opts = match &fetch_id {
1002 Some(id) => MessagesOptions::backward().from(id.as_str()),
1003 None => MessagesOptions::backward(),
1004 };
1005 opts.limit = limit.into();
1006
1007 let Messages { end, chunk, .. } = room.messages(opts).await.map_err(IambError::from)?;
1008
1009 let msgs = chunk.into_iter().filter_map(|ev| {
1010 match ev.event.deserialize() {
1011 Ok(AnyTimelineEvent::MessageLike(msg)) => Some(msg),
1012 Ok(AnyTimelineEvent::State(_)) => None,
1013 Err(_) => None,
1014 }
1015 });
1016
1017 Ok((end, msgs.collect()))
1018 } else {
1019 Err(IambError::UnknownRoom(room_id).into())
1020 }
1021 }
1022
1023 async fn members(&mut self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> { 1098 async fn members(&mut self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
1024 if let Some(room) = self.client.get_room(room_id.as_ref()) { 1099 if let Some(room) = self.client.get_room(room_id.as_ref()) {
1025 Ok(room.active_members().await.map_err(IambError::from)?) 1100 Ok(room.active_members().await.map_err(IambError::from)?)