Skip to content

Commit 29e5824

Browse files
committed
refactor(timeline): Hold a Decryptor inside TimelineController instead of passing it in when needed
1 parent 6c944a9 commit 29e5824

File tree

6 files changed

+165
-133
lines changed

6 files changed

+165
-133
lines changed

crates/matrix-sdk-ui/src/timeline/builder.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ impl TimelineBuilder {
171171
.unwrap_or_default();
172172

173173
let controller = TimelineController::new(
174+
room.clone(),
174175
room.clone(),
175176
focus.clone(),
176177
internal_id_prefix.clone(),

crates/matrix-sdk-ui/src/timeline/controller/mod.rs

Lines changed: 18 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,17 @@ use eyeball_im_util::vector::{FilterMap, VectorObserverExt};
2121
use futures_core::Stream;
2222
use imbl::Vector;
2323
#[cfg(test)]
24-
use matrix_sdk::crypto::OlmMachine;
24+
use matrix_sdk::Result;
2525
use matrix_sdk::{
26-
Result, Room,
2726
deserialized_responses::TimelineEvent,
2827
event_cache::{RoomEventCache, RoomPaginationStatus},
2928
paginators::{PaginationResult, Paginator},
3029
send_queue::{
3130
LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendHandle, SendReactionHandle,
3231
},
3332
};
33+
#[cfg(test)]
34+
use ruma::events::receipt::ReceiptEventContent;
3435
use ruma::{
3536
EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, TransactionId, UserId,
3637
api::client::receipt::create_receipt::v3::ReceiptType as SendReceiptType,
@@ -46,8 +47,6 @@ use ruma::{
4647
room_version_rules::RoomVersionRules,
4748
serde::Raw,
4849
};
49-
#[cfg(test)]
50-
use ruma::{OwnedRoomId, RoomId, events::receipt::ReceiptEventContent};
5150
use tokio::sync::{RwLock, RwLockWriteGuard};
5251
use tracing::{debug, error, field::debug, info, instrument, trace, warn};
5352

@@ -72,7 +71,7 @@ use super::{
7271
};
7372
use crate::{
7473
timeline::{
75-
MsgLikeContent, MsgLikeKind, TimelineEventFilterFn,
74+
MsgLikeContent, MsgLikeKind, Room, TimelineEventFilterFn,
7675
algorithms::rfind_event_by_item_id,
7776
date_dividers::DateDividerAdjuster,
7877
event_item::TimelineItemHandle,
@@ -161,9 +160,15 @@ pub(super) struct TimelineController<P: RoomDataProvider = Room, D: Decryptor =
161160

162161
/// A [`RoomDataProvider`] implementation, providing data.
163162
///
164-
/// Useful for testing only; in the real world, it's just a [`Room`].
163+
/// In the real world, this is just a [`Room`].
165164
pub(crate) room_data_provider: P,
166165

166+
/// A [`Decryptor`] implementation, providing the ability to decrypt
167+
/// messages.
168+
///
169+
/// In the real world, this is just a [`Room`].
170+
pub(crate) decryptor: D,
171+
167172
/// Settings applied to this timeline.
168173
pub(super) settings: TimelineSettings,
169174

@@ -293,6 +298,7 @@ pub fn default_event_filter(event: &AnySyncTimelineEvent, rules: &RoomVersionRul
293298
impl<P: RoomDataProvider, D: Decryptor> TimelineController<P, D> {
294299
pub(super) fn new(
295300
room_data_provider: P,
301+
decryptor: D,
296302
focus: TimelineFocus,
297303
internal_id_prefix: Option<String>,
298304
unable_to_decrypt_hook: Option<Arc<UtdHookManager>>,
@@ -337,7 +343,7 @@ impl<P: RoomDataProvider, D: Decryptor> TimelineController<P, D> {
337343
let decryption_retry_task =
338344
DecryptionRetryTask::new(state.clone(), room_data_provider.clone());
339345

340-
Self { state, focus, room_data_provider, settings, decryption_retry_task }
346+
Self { state, focus, room_data_provider, decryptor, settings, decryption_retry_task }
341347
}
342348

343349
/// Initializes the configured focus with appropriate data.
@@ -1099,12 +1105,10 @@ impl<P: RoomDataProvider, D: Decryptor> TimelineController<P, D> {
10991105
true
11001106
}
11011107

1102-
async fn retry_event_decryption_inner(
1103-
&self,
1104-
decryptor: D,
1105-
session_ids: Option<BTreeSet<String>>,
1106-
) {
1107-
self.decryption_retry_task.decrypt(decryptor, session_ids, self.settings.clone()).await;
1108+
pub(crate) async fn retry_event_decryption_inner(&self, session_ids: Option<BTreeSet<String>>) {
1109+
self.decryption_retry_task
1110+
.decrypt(self.decryptor.clone(), session_ids, self.settings.clone())
1111+
.await;
11081112
}
11091113

11101114
pub(super) async fn set_sender_profiles_pending(&self) {
@@ -1591,7 +1595,7 @@ impl TimelineController {
15911595

15921596
#[instrument(skip(self), fields(room_id = ?self.room().room_id()))]
15931597
pub(super) async fn retry_event_decryption(&self, session_ids: Option<BTreeSet<String>>) {
1594-
self.retry_event_decryption_inner(self.room().clone(), session_ids).await
1598+
self.retry_event_decryption_inner(session_ids).await
15951599
}
15961600

15971601
/// Combine the global (event cache) pagination status with the local state
@@ -1625,18 +1629,6 @@ impl TimelineController {
16251629
}
16261630
}
16271631

1628-
#[cfg(test)]
1629-
impl<P: RoomDataProvider> TimelineController<P, (OlmMachine, OwnedRoomId)> {
1630-
pub(super) async fn retry_event_decryption_test(
1631-
&self,
1632-
room_id: &RoomId,
1633-
olm_machine: OlmMachine,
1634-
session_ids: Option<BTreeSet<String>>,
1635-
) {
1636-
self.retry_event_decryption_inner((olm_machine, room_id.to_owned()), session_ids).await
1637-
}
1638-
}
1639-
16401632
#[allow(clippy::too_many_arguments)]
16411633
async fn fetch_replied_to_event<P: RoomDataProvider>(
16421634
mut state_guard: RwLockWriteGuard<'_, TimelineState<P>>,

crates/matrix-sdk-ui/src/timeline/tests/encryption.rs

Lines changed: 70 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ use super::TestTimeline;
5353
use crate::{
5454
timeline::{
5555
EncryptedMessage, MsgLikeContent, MsgLikeKind, TimelineDetails, TimelineItemContent,
56-
tests::{TestRoomDataProvider, TestTimelineBuilder},
56+
tests::{TestDecryptor, TestRoomDataProvider, TestTimelineBuilder},
5757
},
5858
unable_to_decrypt_hook::{UnableToDecryptHook, UnableToDecryptInfo, UtdHookManager},
5959
};
@@ -90,7 +90,16 @@ async fn test_retry_message_decryption() {
9090
let client = test_client_builder(None).build().await.unwrap();
9191
let utd_hook = Arc::new(UtdHookManager::new(hook.clone(), client));
9292

93-
let timeline = TestTimelineBuilder::new().unable_to_decrypt_hook(utd_hook.clone()).build();
93+
let own_user_id = user_id!("@example:morheus.localhost");
94+
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
95+
96+
let timeline = TestTimelineBuilder::new()
97+
.unable_to_decrypt_hook(utd_hook.clone())
98+
.decryptor(TestDecryptor::new(
99+
room_id!("!DovneieKSTkdHKpIXy:morpheus.localhost"),
100+
&olm_machine,
101+
))
102+
.build();
94103
let mut stream = timeline.subscribe().await;
95104

96105
let f = &timeline.factory;
@@ -146,19 +155,13 @@ async fn test_retry_message_decryption() {
146155
assert!(utds[0].time_to_decrypt.is_none());
147156
}
148157

149-
let own_user_id = user_id!("@example:morheus.localhost");
150158
let exported_keys = decrypt_room_key_export(Cursor::new(SESSION_KEY), "1234").unwrap();
151159

152-
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
153160
olm_machine.store().import_exported_room_keys(exported_keys, |_, _| {}).await.unwrap();
154161

155162
timeline
156163
.controller
157-
.retry_event_decryption_test(
158-
room_id!("!DovneieKSTkdHKpIXy:morpheus.localhost"),
159-
olm_machine,
160-
Some(iter::once(SESSION_ID.to_owned()).collect()),
161-
)
164+
.retry_event_decryption_test(Some(iter::once(SESSION_ID.to_owned()).collect()))
162165
.await;
163166

164167
assert_eq!(timeline.controller.items().await.len(), 2);
@@ -198,7 +201,16 @@ async fn test_false_positive_late_decryption_regression() {
198201
UtdHookManager::new(hook.clone(), client).with_max_delay(Duration::from_millis(500)),
199202
);
200203

201-
let timeline = TestTimelineBuilder::new().unable_to_decrypt_hook(utd_hook.clone()).build();
204+
let own_user_id = user_id!("@example:morheus.localhost");
205+
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
206+
207+
let timeline = TestTimelineBuilder::new()
208+
.unable_to_decrypt_hook(utd_hook.clone())
209+
.decryptor(TestDecryptor::new(
210+
room_id!("!DovneieKSTkdHKpIXy:morpheus.localhost"),
211+
&olm_machine,
212+
))
213+
.build();
202214

203215
let f = &timeline.factory;
204216
timeline
@@ -227,21 +239,14 @@ async fn test_false_positive_late_decryption_regression() {
227239
)
228240
.await;
229241

230-
let own_user_id = user_id!("@example:morheus.localhost");
231-
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
232-
233242
sleep(Duration::from_millis(200)).await;
234243

235244
// Simulate a retry decryption.
236245
// Due to the regression this was marking the event as successfully decrypted on
237246
// retry
238247
timeline
239248
.controller
240-
.retry_event_decryption_test(
241-
room_id!("!DovneieKSTkdHKpIXy:morpheus.localhost"),
242-
olm_machine,
243-
Some(iter::once(SESSION_ID.to_owned()).collect()),
244-
)
249+
.retry_event_decryption_test(Some(iter::once(SESSION_ID.to_owned()).collect()))
245250
.await;
246251
assert_eq!(timeline.controller.items().await.len(), 2);
247252

@@ -287,7 +292,16 @@ async fn test_retry_edit_decryption() {
287292
rHCyB4ElRjU\n\
288293
-----END MEGOLM SESSION DATA-----";
289294

290-
let timeline = TestTimeline::new();
295+
let own_user_id = user_id!("@example:morheus.localhost");
296+
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
297+
298+
let timeline = TestTimelineBuilder::new()
299+
.decryptor(TestDecryptor::new(
300+
room_id!("!bdsREiCPHyZAPkpXer:morpheus.localhost"),
301+
&olm_machine,
302+
))
303+
.build();
304+
291305
let f = &timeline.factory;
292306
let mut stream = timeline.subscribe_events().await;
293307

@@ -353,18 +367,9 @@ async fn test_retry_edit_decryption() {
353367
let mut keys = decrypt_room_key_export(Cursor::new(SESSION1_KEY), "1234").unwrap();
354368
keys.extend(decrypt_room_key_export(Cursor::new(SESSION2_KEY), "1234").unwrap());
355369

356-
let own_user_id = user_id!("@example:morheus.localhost");
357-
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
358370
olm_machine.store().import_exported_room_keys(keys, |_, _| {}).await.unwrap();
359371

360-
timeline
361-
.controller
362-
.retry_event_decryption_test(
363-
room_id!("!bdsREiCPHyZAPkpXer:morpheus.localhost"),
364-
olm_machine,
365-
None,
366-
)
367-
.await;
372+
timeline.controller.retry_event_decryption_test(None).await;
368373

369374
// Then first, the first item gets decrypted on its own
370375
assert_next_matches_with_timeout!(stream, VectorDiff::Set { index: 0, .. });
@@ -419,7 +424,12 @@ async fn test_retry_edit_and_more() {
419424
)
420425
}
421426

422-
let timeline = TestTimeline::new();
427+
let olm_machine = OlmMachine::new(user_id!("@jptest:matrix.org"), DEVICE_ID.into()).await;
428+
429+
let timeline = TestTimelineBuilder::new()
430+
.decryptor(TestDecryptor::new(room_id!("!wFnAUSQbxMcfIMgvNX:flipdot.org"), &olm_machine))
431+
.build();
432+
423433
let f = &timeline.factory;
424434
let mut stream = timeline.subscribe().await;
425435

@@ -480,17 +490,12 @@ async fn test_retry_edit_and_more() {
480490
assert_next_matches_with_timeout!(stream, VectorDiff::PushBack { .. });
481491
assert_next_matches_with_timeout!(stream, VectorDiff::PushBack { .. });
482492

483-
let olm_machine = OlmMachine::new(user_id!("@jptest:matrix.org"), DEVICE_ID.into()).await;
484493
let keys = decrypt_room_key_export(Cursor::new(SESSION_KEY), "testing").unwrap();
485494
olm_machine.store().import_exported_room_keys(keys, |_, _| {}).await.unwrap();
486495

487496
timeline
488497
.controller
489-
.retry_event_decryption_test(
490-
room_id!("!wFnAUSQbxMcfIMgvNX:flipdot.org"),
491-
olm_machine,
492-
Some(iter::once(SESSION_ID.to_owned()).collect()),
493-
)
498+
.retry_event_decryption_test(Some(iter::once(SESSION_ID.to_owned()).collect()))
494499
.await;
495500

496501
// Then first, the original item got decrypted
@@ -536,7 +541,13 @@ async fn test_retry_message_decryption_highlighted() {
536541
FM8H2PpVkKgrA+tx8LNQD+FWDfp6MyhmEJEvk9r5vU9LtTXtZl4toYvNY0UHUBbZj2xF9U9Z9A\n\
537542
-----END MEGOLM SESSION DATA-----";
538543

539-
let timeline = TestTimeline::new();
544+
let own_user_id = user_id!("@example:matrix.org");
545+
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
546+
547+
let timeline = TestTimelineBuilder::new()
548+
.decryptor(TestDecryptor::new(room_id!("!rYtFvMGENJleNQVJzb:matrix.org"), &olm_machine))
549+
.build();
550+
540551
let f = &timeline.factory;
541552
let mut stream = timeline.subscribe().await;
542553

@@ -583,19 +594,13 @@ async fn test_retry_message_decryption_highlighted() {
583594
let date_divider = assert_next_matches!(stream, VectorDiff::PushFront { value } => value);
584595
assert!(date_divider.is_date_divider());
585596

586-
let own_user_id = user_id!("@example:matrix.org");
587597
let exported_keys = decrypt_room_key_export(Cursor::new(SESSION_KEY), "1234").unwrap();
588598

589-
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
590599
olm_machine.store().import_exported_room_keys(exported_keys, |_, _| {}).await.unwrap();
591600

592601
timeline
593602
.controller
594-
.retry_event_decryption_test(
595-
room_id!("!rYtFvMGENJleNQVJzb:matrix.org"),
596-
olm_machine,
597-
Some(iter::once(SESSION_ID.to_owned()).collect()),
598-
)
603+
.retry_event_decryption_test(Some(iter::once(SESSION_ID.to_owned()).collect()))
599604
.await;
600605

601606
assert_eq!(timeline.controller.items().await.len(), 2);
@@ -615,12 +620,20 @@ async fn test_retry_fetching_encryption_info() {
615620
let sender = user_id!("@sender:s.co");
616621
let room_id = room_id!("!room:s.co");
617622

623+
let own_user_id = user_id!("@me:s.co");
624+
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
625+
618626
// Given when I ask the room for new encryption info for any session, it will
619627
// say "verified"
620628
let verified_encryption_info = make_encryption_info(SESSION_ID, VerificationState::Verified);
621629
let provider =
622630
TestRoomDataProvider::default().with_encryption_info(SESSION_ID, verified_encryption_info);
623-
let timeline = TestTimelineBuilder::new().provider(provider).build();
631+
632+
let timeline = TestTimelineBuilder::new()
633+
.provider(provider)
634+
.decryptor(TestDecryptor::new(room_id, &olm_machine))
635+
.build();
636+
624637
let f = &timeline.factory;
625638
let mut stream = timeline.subscribe_events().await;
626639

@@ -671,15 +684,9 @@ async fn test_retry_fetching_encryption_info() {
671684
}
672685

673686
// When we retry the session with ID SESSION_ID
674-
let own_user_id = user_id!("@me:s.co");
675-
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
676687
timeline
677688
.controller
678-
.retry_event_decryption_test(
679-
room_id,
680-
olm_machine,
681-
Some(iter::once(SESSION_ID.to_owned()).collect()),
682-
)
689+
.retry_event_decryption_test(Some(iter::once(SESSION_ID.to_owned()).collect()))
683690
.await;
684691

685692
// Then the event in that session has been updated to be verified
@@ -817,7 +824,16 @@ async fn test_retry_decryption_updates_response() {
817824
HztoSJUr/2Y\n\
818825
-----END MEGOLM SESSION DATA-----";
819826

820-
let timeline = TestTimeline::new();
827+
let own_user_id = user_id!("@example:morheus.localhost");
828+
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
829+
830+
let timeline = TestTimelineBuilder::new()
831+
.decryptor(TestDecryptor::new(
832+
room_id!("!DovneieKSTkdHKpIXy:morpheus.localhost"),
833+
&olm_machine,
834+
))
835+
.build();
836+
821837
let mut stream = timeline.subscribe_events().await;
822838

823839
let original_event_id = event_id!("$original");
@@ -883,20 +899,14 @@ async fn test_retry_decryption_updates_response() {
883899
}
884900

885901
// Import a room key backup.
886-
let own_user_id = user_id!("@example:morheus.localhost");
887902
let exported_keys = decrypt_room_key_export(Cursor::new(SESSION_KEY), "1234").unwrap();
888903

889-
let olm_machine = OlmMachine::new(own_user_id, "SomeDeviceId".into()).await;
890904
olm_machine.store().import_exported_room_keys(exported_keys, |_, _| {}).await.unwrap();
891905

892906
// Retry decrypting the UTD.
893907
timeline
894908
.controller
895-
.retry_event_decryption_test(
896-
room_id!("!DovneieKSTkdHKpIXy:morpheus.localhost"),
897-
olm_machine,
898-
Some(iter::once(SESSION_ID.to_owned()).collect()),
899-
)
909+
.retry_event_decryption_test(Some(iter::once(SESSION_ID.to_owned()).collect()))
900910
.await;
901911

902912
// The response is updated.

0 commit comments

Comments
 (0)