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};
77
88use emojis::Emoji;
99use tokio::sync::Mutex as AsyncMutex;
10use tracing::warn;
1110
1211use matrix_sdk::{
1312 encryption::verification::SasVerification,
@@ -23,7 +22,6 @@ use matrix_sdk::{
2322 RoomMessageEventContent,
2423 },
2524 tag::{TagName, Tags},
26 AnyMessageLikeEvent,
2725 MessageLikeEvent,
2826 },
2927 presence::PresenceState,
@@ -412,6 +410,9 @@ pub struct RoomInfo {
412410 /// A map of message identifiers to a map of reaction events.
413411 pub reactions: HashMap<OwnedEventId, MessageReactions>,
414412
413 /// Whether the scrollback for this room is currently being fetched.
414 pub fetching: bool,
415
415416 /// Where to continue fetching from when we continue loading scrollback history.
416417 pub fetch_id: RoomFetchStatus,
417418
@@ -520,7 +521,7 @@ impl RoomInfo {
520521 }
521522 }
522523
523 fn recently_fetched(&self) -> bool {
524 pub fn recently_fetched(&self) -> bool {
524525 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
525526 }
526527
@@ -668,61 +669,6 @@ impl ChatStore {
668669 self.need_load.insert(room_id);
669670 }
670671
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
726672 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
727673 self.rooms.get_or_default(room_id)
728674 }
src/main.rs −10
@@ -101,14 +101,6 @@ use modalkit::{
101101 },
102102};
103103
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
112104struct Application {
113105 store: AsyncProgramStore,
114106 worker: Requester,
@@ -190,8 +182,6 @@ impl Application {
190182 }
191183 f.set_cursor(cx, cy);
192184 }
193
194 store.application.load_older(msg_load_req(area));
195185 })?;
196186
197187 Ok(())
src/tests.rs +1
@@ -153,6 +153,7 @@ pub fn mock_room() -> RoomInfo {
153153 read_till: None,
154154 reactions: HashMap::new(),
155155
156 fetching: false,
156157 fetch_id: RoomFetchStatus::NotStarted,
157158 fetch_last: None,
158159 users_typing: None,
src/worker.rs +144 −69
@@ -1,3 +1,4 @@
1use std::collections::HashMap;
12use std::convert::TryFrom;
23use std::fmt::{Debug, Formatter};
34use std::fs::File;
@@ -5,12 +6,12 @@ use std::io::BufWriter;
56use std::str::FromStr;
67use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
78use std::sync::Arc;
8use std::time::Duration;
9use std::time::{Duration, Instant};
910
1011use gethostname::gethostname;
1112use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
1213use tokio::task::JoinHandle;
13use tracing::error;
14use tracing::{error, warn};
1415
1516use matrix_sdk::{
1617 config::{RequestConfig, StoreConfig, SyncSettings},
@@ -44,6 +45,7 @@ use matrix_sdk::{
4445 tag::Tags,
4546 typing::SyncTypingEvent,
4647 AnyInitialStateEvent,
48 AnyMessageLikeEvent,
4749 AnyTimelineEvent,
4850 EmptyStateKey,
4951 InitialStateEvent,
@@ -56,6 +58,7 @@ use matrix_sdk::{
5658 OwnedRoomId,
5759 OwnedRoomOrAliasId,
5860 OwnedUserId,
61 RoomId,
5962 RoomVersionId,
6063 },
6164 Client,
@@ -68,12 +71,14 @@ use modalkit::editing::action::{EditInfo, InfoMessage, UIError};
6871use crate::{
6972 base::{
7073 AsyncProgramStore,
74 ChatStore,
7175 CreateRoomFlags,
7276 CreateRoomType,
7377 EventLocation,
7478 IambError,
7579 IambResult,
7680 Receipts,
81 RoomFetchStatus,
7782 VerifyAction,
7883 },
7984 message::MessageFetchResult,
@@ -82,6 +87,7 @@ use crate::{
8287
8388const IAMB_DEVICE_NAME: &str = "iamb";
8489const IAMB_USER_AGENT: &str = "iamb";
90const MIN_MSG_LOAD: u32 = 50;
8591
8692fn initial_devname() -> String {
8793 format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy())
@@ -158,6 +164,113 @@ pub async fn create_room(
158164 return Ok(resp.room_id);
159165}
160166
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
161274#[derive(Debug)]
162275pub enum LoginStyle {
163276 SessionRestore(Session),
@@ -216,7 +329,6 @@ pub enum WorkerTask {
216329 ActiveRooms(ClientReply<Vec<FetchedRoom>>),
217330 DirectMessages(ClientReply<Vec<FetchedRoom>>),
218331 Init(AsyncProgramStore, ClientReply<()>),
219 LoadOlder(OwnedRoomId, Option<String>, u32, ClientReply<MessageFetchResult>),
220332 Login(LoginStyle, ClientReply<IambResult<EditInfo>>),
221333 GetInviter(Invited, ClientReply<IambResult<Option<RoomMember>>>),
222334 GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>),
@@ -246,14 +358,6 @@ impl Debug for WorkerTask {
246358 .field(&format_args!("_"))
247359 .finish()
248360 },
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 },
257361 WorkerTask::Login(style, _) => {
258362 f.debug_tuple("WorkerTask::Login")
259363 .field(style)
@@ -325,21 +429,6 @@ impl Requester {
325429 return response.recv();
326430 }
327431
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
343432 pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> {
344433 let (reply, response) = oneshot();
345434
@@ -437,8 +526,9 @@ pub struct ClientWorker {
437526 initialized: bool,
438527 settings: ApplicationSettings,
439528 client: Client,
440 sync_handle: Option<JoinHandle<()>>,
529 load_handle: Option<JoinHandle<()>>,
441530 rcpt_handle: Option<JoinHandle<()>>,
531 sync_handle: Option<JoinHandle<()>>,
442532}
443533
444534impl ClientWorker {
@@ -476,8 +566,9 @@ impl ClientWorker {
476566 initialized: false,
477567 settings,
478568 client: client.clone(),
479 sync_handle: None,
569 load_handle: None,
480570 rcpt_handle: None,
571 sync_handle: None,
481572 };
482573
483574 tokio::spawn(async move {
@@ -535,10 +626,6 @@ impl ClientWorker {
535626 assert!(self.initialized);
536627 reply.send(self.active_rooms().await);
537628 },
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 },
542629 WorkerTask::Login(style, reply) => {
543630 assert!(self.initialized);
544631 reply.send(self.login_and_sync(style).await);
@@ -811,17 +898,34 @@ impl ClientWorker {
811898 },
812899 );
813900
814 let client = self.client.clone();
901 self.rcpt_handle = tokio::spawn({
902 let store = store.clone();
903 let client = self.client.clone();
815904
816 self.rcpt_handle = tokio::spawn(async move {
817 // Update the displayed read receipts ever 5 seconds.
818 let mut interval = tokio::time::interval(Duration::from_secs(5));
905 async move {
906 // Update the displayed read receipts every 5 seconds.
907 let mut interval = tokio::time::interval(Duration::from_secs(5));
819908
820 loop {
821 interval.tick().await;
909 loop {
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();
822921
823 let receipts = update_receipts(&client).await;
824 store.lock().await.application.set_receipts(receipts).await;
922 async move {
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 }
825929 }
826930 })
827931 .into();
@@ -991,35 +1095,6 @@ impl ClientWorker {
9911095 return rooms;
9921096 }
9931097
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
10231098 async fn members(&mut self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
10241099 if let Some(room) = self.client.get_room(room_id.as_ref()) {
10251100 Ok(room.active_members().await.map_err(IambError::from)?)