Skip to content

Commit 0ac8699

Browse files
committed
feat(event cache): also subscribe to a thread if we've sent a message into it
1 parent aa23aab commit 0ac8699

File tree

2 files changed

+257
-10
lines changed

2 files changed

+257
-10
lines changed

crates/matrix-sdk/src/event_cache/mod.rs

Lines changed: 144 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
#![forbid(missing_docs)]
2929

3030
use std::{
31-
collections::BTreeMap,
31+
collections::{BTreeMap, HashMap},
3232
fmt,
3333
sync::{Arc, OnceLock},
3434
};
@@ -44,13 +44,18 @@ use matrix_sdk_base::{
4444
},
4545
executor::AbortOnDrop,
4646
linked_chunk::{self, lazy_loader::LazyLoaderError, OwnedLinkedChunkId},
47+
store::SerializableEventContent,
4748
store_locks::LockStoreError,
4849
sync::RoomUpdates,
4950
timer,
5051
};
5152
use matrix_sdk_common::executor::{spawn, JoinHandle};
5253
use room::RoomEventCacheState;
53-
use ruma::{events::AnySyncEphemeralRoomEvent, serde::Raw, OwnedEventId, OwnedRoomId, RoomId};
54+
use ruma::{
55+
events::{room::encrypted, AnySyncEphemeralRoomEvent},
56+
serde::Raw,
57+
OwnedEventId, OwnedRoomId, OwnedTransactionId, RoomId,
58+
};
5459
use tokio::{
5560
select,
5661
sync::{
@@ -60,7 +65,11 @@ use tokio::{
6065
};
6166
use tracing::{debug, error, info, info_span, instrument, trace, warn, Instrument as _, Span};
6267

63-
use crate::{client::WeakClient, Client};
68+
use crate::{
69+
client::WeakClient,
70+
send_queue::{LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate},
71+
Client,
72+
};
6473

6574
mod deduplicator;
6675
mod pagination;
@@ -418,6 +427,7 @@ impl EventCache {
418427
self.inner.generic_update_sender.subscribe()
419428
}
420429

430+
#[instrument(skip(client, thread_subscriber_sender))]
421431
async fn handle_thread_subscriber_linked_chunk_update(
422432
client: &WeakClient,
423433
thread_subscriber_sender: &Sender<()>,
@@ -501,7 +511,102 @@ impl EventCache {
501511
}
502512
}
503513

504-
return true;
514+
true
515+
}
516+
517+
#[instrument(skip(client, thread_subscriber_sender))]
518+
async fn handle_thread_subscriber_send_queue_update(
519+
client: &WeakClient,
520+
thread_subscriber_sender: &Sender<()>,
521+
events_being_sent: &mut HashMap<OwnedTransactionId, OwnedEventId>,
522+
up: SendQueueUpdate,
523+
) -> bool {
524+
let Some(client) = client.get() else {
525+
// Client shutting down.
526+
debug!("Client is shutting down, exiting thread subscriber task");
527+
return false;
528+
};
529+
530+
let room_id = up.room_id;
531+
let Some(room) = client.get_room(&room_id) else {
532+
warn!(%room_id, "unknown room");
533+
return true;
534+
};
535+
536+
let extract_thread_root = |serialized_event: SerializableEventContent| {
537+
match serialized_event.deserialize() {
538+
Ok(content) => {
539+
if let Some(encrypted::Relation::Thread(thread)) = content.relation() {
540+
return Some(thread.event_id);
541+
}
542+
}
543+
Err(err) => {
544+
warn!("error when deserializing content of a local echo: {err}");
545+
}
546+
}
547+
None
548+
};
549+
550+
let (thread_root, subscribe_up_to) = match up.update {
551+
RoomSendQueueUpdate::NewLocalEvent(local_echo) => {
552+
match local_echo.content {
553+
LocalEchoContent::Event { serialized_event, .. } => {
554+
if let Some(thread_root) = extract_thread_root(serialized_event) {
555+
events_being_sent.insert(local_echo.transaction_id, thread_root);
556+
}
557+
}
558+
LocalEchoContent::React { .. } => {
559+
// Nothing to do, reactions don't count as a thread
560+
// subscription.
561+
}
562+
}
563+
return true;
564+
}
565+
566+
RoomSendQueueUpdate::CancelledLocalEvent { transaction_id } => {
567+
events_being_sent.remove(&transaction_id);
568+
return true;
569+
}
570+
571+
RoomSendQueueUpdate::ReplacedLocalEvent { transaction_id, new_content } => {
572+
if let Some(thread_root) = extract_thread_root(new_content) {
573+
events_being_sent.insert(transaction_id, thread_root);
574+
} else {
575+
// It could be that the event isn't part of a thread anymore; handle that by
576+
// removing the pending transaction id.
577+
events_being_sent.remove(&transaction_id);
578+
}
579+
return true;
580+
}
581+
582+
RoomSendQueueUpdate::SentEvent { transaction_id, event_id } => {
583+
if let Some(thread_root) = events_being_sent.remove(&transaction_id) {
584+
(thread_root, event_id)
585+
} else {
586+
// We don't know about the event that has been sent, so ignore it.
587+
trace!(%transaction_id, "received a sent event that we didn't know about, ignoring");
588+
return true;
589+
}
590+
}
591+
592+
RoomSendQueueUpdate::SendError { .. }
593+
| RoomSendQueueUpdate::RetryEvent { .. }
594+
| RoomSendQueueUpdate::MediaUpload { .. } => {
595+
// Nothing to do for these bad boys.
596+
return true;
597+
}
598+
};
599+
600+
// And if we've found such a mention, subscribe to the thread up to this event.
601+
trace!(thread = %thread_root, up_to = %subscribe_up_to, "found a new thread to subscribe to");
602+
if let Err(err) = room.subscribe_thread_if_needed(&thread_root, Some(subscribe_up_to)).await
603+
{
604+
warn!(%err, "Failed to subscribe to thread");
605+
} else {
606+
let _ = thread_subscriber_sender.send(());
607+
}
608+
609+
true
505610
}
506611

507612
#[instrument(skip_all)]
@@ -510,16 +615,46 @@ impl EventCache {
510615
linked_chunk_update_sender: Sender<RoomEventCacheLinkedChunkUpdate>,
511616
thread_subscriber_sender: Sender<()>,
512617
) {
513-
if client.get().map_or(false, |client| !client.enabled_thread_subscriptions()) {
514-
trace!("Not spawning the thread subscriber task, because the client is shutting down or is not interested in those");
618+
let mut send_q_rx = if let Some(client) = client.get() {
619+
if !client.enabled_thread_subscriptions() {
620+
trace!("Thread subscriptions are not enabled, not spawning thread subscriber task");
621+
return;
622+
}
623+
624+
client.send_queue().subscribe()
625+
} else {
626+
trace!("Client is shutting down, not spawning thread subscriber task");
515627
return;
516-
}
628+
};
629+
630+
let mut linked_chunk_rx = linked_chunk_update_sender.subscribe();
517631

518-
let mut rx = linked_chunk_update_sender.subscribe();
632+
// A mapping of local echoes (events being sent), to their thread root, if
633+
// they're in an in-thread reply.
634+
//
635+
// Entirely managed by `handle_thread_subscriber_send_queue_update`.
636+
let mut events_being_sent = HashMap::new();
519637

520638
loop {
521639
select! {
522-
res = rx.recv() => {
640+
res = send_q_rx.recv() => {
641+
match res {
642+
Ok(up) => {
643+
if !Self::handle_thread_subscriber_send_queue_update(&client, &thread_subscriber_sender, &mut events_being_sent, up).await {
644+
break;
645+
}
646+
}
647+
Err(RecvError::Closed) => {
648+
debug!("Linked chunk update channel has been closed, exiting thread subscriber task");
649+
break;
650+
}
651+
Err(RecvError::Lagged(num_skipped)) => {
652+
warn!(num_skipped, "Lagged behind linked chunk updates");
653+
}
654+
}
655+
}
656+
657+
res = linked_chunk_rx.recv() => {
523658
match res {
524659
Ok(up) => {
525660
if !Self::handle_thread_subscriber_linked_chunk_update(&client, &thread_subscriber_sender, up).await {

crates/matrix-sdk/tests/integration/send_queue.rs

Lines changed: 113 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use matrix_sdk::{
1414
RoomSendQueueStorageError, RoomSendQueueUpdate, SendHandle, SendQueueUpdate,
1515
},
1616
test_utils::mocks::{MatrixMock, MatrixMockServer},
17-
Client, MemoryStore,
17+
Client, MemoryStore, ThreadingSupport,
1818
};
1919
use matrix_sdk_test::{
2020
async_test, event_factory::EventFactory, InvitedRoomBuilder, KnockedRoomBuilder,
@@ -29,6 +29,7 @@ use ruma::{
2929
NewUnstablePollStartEventContent, UnstablePollAnswer, UnstablePollAnswers,
3030
UnstablePollStartContentBlock, UnstablePollStartEventContent,
3131
},
32+
relation::Thread,
3233
room::{
3334
message::{
3435
ImageMessageEventContent, MessageType, Relation, ReplyWithinThread,
@@ -3712,3 +3713,114 @@ async fn test_update_caption_while_sending_media_event() {
37123713
// That's all, folks!
37133714
assert!(watch.is_empty());
37143715
}
3716+
3717+
#[async_test]
3718+
async fn test_sending_reply_in_thread_auto_subscribe() {
3719+
let server = MatrixMockServer::new().await;
3720+
3721+
// Assuming a client that's interested in thread subscriptions,
3722+
let client = server
3723+
.client_builder()
3724+
.on_builder(|builder| {
3725+
builder.with_threading_support(ThreadingSupport::Enabled { with_subscriptions: true })
3726+
})
3727+
.build()
3728+
.await;
3729+
3730+
client.event_cache().subscribe().unwrap();
3731+
3732+
let room_id = room_id!("!a:b.c");
3733+
let room = server.sync_joined_room(&client, room_id).await;
3734+
3735+
server.mock_room_state_encryption().plain().mount().await;
3736+
3737+
// When I send a message to a thread,
3738+
let thread_root = event_id!("$thread");
3739+
3740+
let mut content = RoomMessageEventContent::text_plain("hello world");
3741+
content.relates_to =
3742+
Some(Relation::Thread(Thread::plain(thread_root.to_owned(), thread_root.to_owned())));
3743+
3744+
server.mock_room_send().ok(event_id!("$reply")).mock_once().mount().await;
3745+
3746+
server
3747+
.mock_put_thread_subscription()
3748+
.match_room_id(room_id.to_owned())
3749+
.match_thread_id(thread_root.to_owned())
3750+
.ok()
3751+
.mock_once()
3752+
.mount()
3753+
.await;
3754+
3755+
let (_, mut stream) = room.send_queue().subscribe().await.unwrap();
3756+
room.send_queue().send(content.into()).await.unwrap();
3757+
3758+
// Let the send queue process the event.
3759+
assert_let_timeout!(Ok(RoomSendQueueUpdate::NewLocalEvent(..)) = stream.recv());
3760+
assert_let_timeout!(Ok(RoomSendQueueUpdate::SentEvent { .. }) = stream.recv());
3761+
assert_let_timeout!(Ok(()) = thread_subscriber_updates.recv());
3762+
3763+
// Check the endpoints have been correctly called.
3764+
server.server().reset().await;
3765+
3766+
// Now, if I send a message in a thread I've already subscribed to, in automatic
3767+
// mode, this promotes the subscription to manual.
3768+
3769+
// Subscribed, automatically.
3770+
server
3771+
.mock_get_thread_subscription()
3772+
.match_room_id(room_id.to_owned())
3773+
.match_thread_id(thread_root.to_owned())
3774+
.ok(true)
3775+
.mount()
3776+
.await;
3777+
3778+
// I'll get one subscription.
3779+
server
3780+
.mock_put_thread_subscription()
3781+
.match_room_id(room_id.to_owned())
3782+
.match_thread_id(thread_root.to_owned())
3783+
.ok()
3784+
.mock_once()
3785+
.mount()
3786+
.await;
3787+
3788+
server.mock_room_send().ok(event_id!("$reply")).mock_once().mount().await;
3789+
3790+
let mut content = RoomMessageEventContent::text_plain("hello world");
3791+
content.relates_to =
3792+
Some(Relation::Thread(Thread::plain(thread_root.to_owned(), thread_root.to_owned())));
3793+
room.send_queue().send(content.into()).await.unwrap();
3794+
3795+
// Let the send queue process the event.
3796+
assert_let!(RoomSendQueueUpdate::NewLocalEvent(..) = stream.recv().await.unwrap());
3797+
assert_let!(RoomSendQueueUpdate::SentEvent { .. } = stream.recv().await.unwrap());
3798+
3799+
// Check the endpoints have been correctly called.
3800+
server.server().reset().await;
3801+
3802+
// Subscribed, but manually.
3803+
server
3804+
.mock_get_thread_subscription()
3805+
.match_room_id(room_id.to_owned())
3806+
.match_thread_id(thread_root.to_owned())
3807+
.ok(false)
3808+
.mount()
3809+
.await;
3810+
3811+
// I'll get zero subscription.
3812+
server.mock_put_thread_subscription().ok().expect(0).mount().await;
3813+
3814+
server.mock_room_send().ok(event_id!("$reply")).mock_once().mount().await;
3815+
3816+
let mut content = RoomMessageEventContent::text_plain("hello world");
3817+
content.relates_to =
3818+
Some(Relation::Thread(Thread::plain(thread_root.to_owned(), thread_root.to_owned())));
3819+
room.send_queue().send(content.into()).await.unwrap();
3820+
3821+
// Let the send queue process the event.
3822+
assert_let!(RoomSendQueueUpdate::NewLocalEvent(..) = stream.recv().await.unwrap());
3823+
assert_let!(RoomSendQueueUpdate::SentEvent { .. } = stream.recv().await.unwrap());
3824+
3825+
sleep(Duration::from_millis(100)).await;
3826+
}

0 commit comments

Comments
 (0)