matrix-sdk 0.17.0

A high level Matrix client-server library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
// Copyright 2025 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod builder;

use std::ops::{Deref, DerefMut, Not};

use builder::{BufferOfValuesForLocalEvents, Builder};
use eyeball::{AsyncLock, ObservableWriteGuard, SharedObservable, Subscriber};
pub use matrix_sdk_base::latest_event::{
    LatestEventValue, LocalLatestEventValue, RemoteLatestEventValue,
};
use matrix_sdk_base::{RoomInfoNotableUpdateReasons, RoomState};
use ruma::{EventId, OwnedEventId, UserId, events::room::power_levels::RoomPowerLevels};
use tracing::{error, info, instrument, trace, warn};

use crate::{Room, event_cache::RoomEventCache, room::WeakRoom, send_queue::RoomSendQueueUpdate};

/// The latest event of a room or a thread.
///
/// Use [`LatestEvent::subscribe`] to get a stream of updates.
#[derive(Debug)]
pub(super) struct LatestEvent {
    /// The room owning this latest event.
    weak_room: WeakRoom,

    /// The thread (if any) owning this latest event.
    _thread_id: Option<OwnedEventId>,

    /// A buffer of the current [`LatestEventValue`]s computed for local events
    /// seen by the send queue. See [`BufferOfValuesForLocalEvents`] to learn
    /// more.
    buffer_of_values_for_local_events: BufferOfValuesForLocalEvents,

    /// The latest event value.
    current_value: SharedObservable<LatestEventValue, AsyncLock>,
}

impl LatestEvent {
    pub fn new(
        weak_room: &WeakRoom,
        thread_id: Option<&EventId>,
    ) -> With<Self, IsLatestEventValueNone> {
        let latest_event_value = match thread_id {
            Some(_thread_id) => LatestEventValue::default(),
            None => weak_room.get().map(|room| room.latest_event()).unwrap_or_default(),
        };
        let is_none = latest_event_value.is_none();

        With {
            result: Self {
                weak_room: weak_room.clone(),
                _thread_id: thread_id.map(ToOwned::to_owned),
                buffer_of_values_for_local_events: BufferOfValuesForLocalEvents::new(),
                current_value: SharedObservable::new_async(latest_event_value),
            },
            with: is_none,
        }
    }

    /// Return a [`Subscriber`] to new values.
    pub async fn subscribe(&self) -> Subscriber<LatestEventValue, AsyncLock> {
        self.current_value.subscribe().await
    }

    #[cfg(test)]
    pub async fn get(&self) -> LatestEventValue {
        self.current_value.get().await
    }

    /// Update the inner latest event value, based on the event cache
    /// (specifically with the [`RoomEventCache`]), if and only if there is no
    /// local latest event value waiting.
    ///
    /// It is only necessary to compute a new [`LatestEventValue`] from the
    /// event cache if there is no [`LatestEventValue`] to be compute from the
    /// send queue. Indeed, anything coming from the send queue has the priority
    /// over the anything coming from the event cache. We believe it provides a
    /// better user experience.
    pub async fn update_with_event_cache(
        &mut self,
        room_event_cache: &RoomEventCache,
        own_user_id: &UserId,
        power_levels: Option<&RoomPowerLevels>,
    ) {
        if self.buffer_of_values_for_local_events.is_empty().not() {
            // At least one `LatestEventValue` exists for local events (i.e. coming from the
            // send queue). In this case, we don't overwrite the current value with a newly
            // computed one from the event cache.
            return;
        }

        let current_event = self.current_value.get().await;
        let new_value =
            Builder::new_remote(room_event_cache, current_event, own_user_id, power_levels).await;

        trace!(value = ?new_value, "Computed a remote `LatestEventValue`");

        if let Some(new_value) = new_value {
            self.update(new_value).await;
        }
    }

    /// Update the inner latest event value, based on the send queue
    /// (specifically with the [`RoomSendQueueUpdate`]).
    pub async fn update_with_send_queue(
        &mut self,
        send_queue_update: &RoomSendQueueUpdate,
        room_event_cache: &RoomEventCache,
        own_user_id: &UserId,
        power_levels: Option<&RoomPowerLevels>,
    ) {
        let current_event = self.current_value.get().await;
        let new_value = Builder::new_local(
            send_queue_update,
            &mut self.buffer_of_values_for_local_events,
            room_event_cache,
            current_event,
            own_user_id,
            power_levels,
        )
        .await;

        trace!(value = ?new_value, "Computed a local `LatestEventValue`");

        if let Some(new_value) = new_value {
            self.update(new_value).await;
        }
    }

    /// Update the inner latest event value, based on the room info.
    pub async fn update_with_room_info(
        &mut self,
        room: Room,
        reasons: RoomInfoNotableUpdateReasons,
    ) {
        // If the `RoomInfo` has been updated due to a change of the own membership.
        if reasons.contains(RoomInfoNotableUpdateReasons::MEMBERSHIP) {
            let new_value = match room.state() {
                // If the room' state is `Invited`, it means the current user has been recently
                // invited to this room.
                RoomState::Invited => {
                    // Short: Let's not update a `RemoteInvite` to another `RemoteInvite`.
                    //
                    // Long: An invite room is only constituted of stripped-state events. These
                    // events do not have an `origin_server_ts` field. It means we cannot compute
                    // the timestamp of the `LatestEventValue`. To workaround this, we set the
                    // timestamp to `now()`. See `Builder::new_remote_for_invite` to learn more.
                    // If an invite room receives a new event, its `LatestEventValue`'s timestamp
                    // will be updated to `now()`, which will make the room bumps to the top of the
                    // room list for example. This is not an acceptable behaviour because it can be
                    // an “attack vector”, i.e. a way to annoy people with spammy invites. That's
                    // why, once a `RemoteInvite` has been computed, we do not refresh it.
                    if matches!(
                        self.current_value.read().await.deref(),
                        LatestEventValue::RemoteInvite { .. }
                    ) {
                        return;
                    }

                    let new_value = Builder::new_remote_for_invite(&room).await;

                    trace!(value = ?new_value, "Computed a remote `LatestEventValue` for invite");

                    new_value
                }

                _ => {
                    info!(
                        "Skipping the computation of a remote `LatestEventValue` from a `RoomInfo`"
                    );

                    return;
                }
            };

            self.update(new_value).await;
        }
    }

    /// Update [`Self::current_value`], and persist the `new_value` in the
    /// store.
    ///
    /// If the `new_value` is [`LatestEventValue::None`], it is accepted: if the
    /// previous latest event value has been redacted and no other candidate has
    /// been found, we want to latest event value to be `None`, so that it is
    /// erased correctly.
    async fn update(&mut self, new_value: LatestEventValue) {
        // Ideally, we would set `new_value` if and only if it is different from the
        // previous value. However, `LatestEventValue` cannot implement `PartialEq` at
        // the time of writing (2025-12-12). So we are only updating if:
        //
        // - if `LatestEventValue` and the previous value aren't `None`,
        // - if the event IDs are different.
        //
        // We must be careful when comparing the event IDs: `None` and `Local*` have no
        // event ID, we can't compare them at this point. Hence the `match` statement to
        // have a fine-grained decision.
        {
            let mut guard = self.current_value.write().await;
            let previous_value = guard.deref();

            let do_update = match (previous_value, &new_value) {
                // If both are `None`, no.
                (LatestEventValue::None, LatestEventValue::None) => false,

                // If at least one is `None`, yes.
                (_, LatestEventValue::None) | (LatestEventValue::None, _) => true,

                // If the event IDs are identical, no.
                (previous, new) if previous.event_id() == new.event_id() => false,

                // Otherwise, yes.
                (_, _) => true,
            };

            if do_update {
                ObservableWriteGuard::set(&mut guard, new_value.clone());

                // Release the write guard over the current value before hitting the store.
                drop(guard);

                self.store(new_value).await;
            }
        }
    }

    /// Update the `RoomInfo` associated to this room to set the new
    /// [`LatestEventValue`], and persist it in the
    /// [`StateStore`][matrix_sdk_base::StateStore] (the one from
    /// [`Client::state_store`][crate::Client::state_store]).
    #[instrument(skip_all)]
    async fn store(&mut self, new_value: LatestEventValue) {
        let Some(room) = self.weak_room.get() else {
            warn!(room_id = ?self.weak_room.room_id(), "Cannot store the latest event value because the room cannot be accessed");
            return;
        };
        let result = room
            .update_and_save_room_info(|mut info| {
                info.set_latest_event(new_value);
                (info, RoomInfoNotableUpdateReasons::LATEST_EVENT)
            })
            .await;
        if let Err(error) = result {
            error!(room_id = ?room.room_id(), ?error, "Failed to save the changes");
        }
    }
}

/// Semantic type similar to a tuple where the left part is the main result and
/// the right part is an “attached” value.
pub(super) struct With<T, W> {
    /// The main value.
    result: T,

    /// The “attached” value.
    with: W,
}

impl<T, W> With<T, W> {
    /// Map the main result without changing the “attached” value.
    pub fn map<F, O>(this: With<T, W>, f: F) -> With<O, W>
    where
        F: FnOnce(T) -> O,
    {
        With { result: f(this.result), with: this.with }
    }

    /// Get the main result.
    pub fn inner(this: With<T, W>) -> T {
        this.result
    }

    /// Get a tuple.
    pub fn unzip(this: With<T, W>) -> (T, W) {
        (this.result, this.with)
    }
}

impl<T, W> Deref for With<T, W> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.result
    }
}

impl<T, W> DerefMut for With<T, W> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.result
    }
}

pub(super) type IsLatestEventValueNone = bool;

#[cfg(all(not(target_family = "wasm"), test))]
mod tests_latest_event {
    use std::ops::Not;

    use assert_matches::assert_matches;
    use matrix_sdk_base::{
        RoomInfoNotableUpdateReasons, RoomState,
        latest_event::RemoteLatestEventValue,
        linked_chunk::{ChunkIdentifier, LinkedChunkId, Position, Update},
        store::{SerializableEventContent, StoreConfig},
    };
    use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
    use matrix_sdk_test::{JoinedRoomBuilder, async_test, event_factory::EventFactory};
    use ruma::{
        MilliSecondsSinceUnixEpoch, OwnedTransactionId, event_id,
        events::{AnyMessageLikeEventContent, room::message::RoomMessageEventContent},
        owned_event_id, owned_room_id, room_id, user_id,
    };
    use stream_assert::{assert_next_matches, assert_pending};
    use tokio::task::yield_now;

    use super::{super::local_room_message, LatestEvent, LatestEventValue, With};
    use crate::{
        client::WeakClient,
        room::WeakRoom,
        send_queue::{LocalEcho, LocalEchoContent, RoomSendQueue, RoomSendQueueUpdate, SendHandle},
        test_utils::mocks::MatrixMockServer,
    };

    fn new_local_echo_content(
        room_send_queue: &RoomSendQueue,
        transaction_id: &OwnedTransactionId,
        body: &str,
    ) -> LocalEchoContent {
        LocalEchoContent::Event {
            serialized_event: SerializableEventContent::new(
                &AnyMessageLikeEventContent::RoomMessage(RoomMessageEventContent::text_plain(body)),
            )
            .unwrap(),
            send_handle: SendHandle::new(
                room_send_queue.clone(),
                transaction_id.clone(),
                MilliSecondsSinceUnixEpoch::now(),
            ),
            send_error: None,
        }
    }

    #[async_test]
    async fn test_new_loads_from_room_info() {
        let room_id = room_id!("!r0");

        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let weak_client = WeakClient::from_client(&client);

        // Create the room.
        let room = client.base_client().get_or_create_room(room_id, RoomState::Joined);
        let weak_room = WeakRoom::new(weak_client, room_id.to_owned());

        // First time `LatestEvent` is created: we get `None`.
        {
            let (latest_event, is_none) = With::unzip(LatestEvent::new(&weak_room, None));

            // By default, it's `None`.
            assert_matches!(latest_event.current_value.get().await, LatestEventValue::None);
            assert!(is_none);
        }

        // Set the `RoomInfo`.
        {
            room.update_room_info(|mut info| {
                info.set_latest_event(LatestEventValue::LocalIsSending(local_room_message("foo")));
                (info, Default::default())
            })
            .await;
        }

        // Second time. We get `LocalIsSending` from `RoomInfo`.
        {
            let (latest_event, is_none) = With::unzip(LatestEvent::new(&weak_room, None));

            // By default, it's `None`.
            assert_matches!(
                latest_event.current_value.get().await,
                LatestEventValue::LocalIsSending(_)
            );
            assert!(is_none.not());
        }
    }

    #[async_test]
    async fn test_update_do_not_ignore_none_value() {
        let room_id = room_id!("!r0");

        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let weak_client = WeakClient::from_client(&client);

        // Create the room.
        client.base_client().get_or_create_room(room_id, RoomState::Joined);
        let weak_room = WeakRoom::new(weak_client, room_id.to_owned());

        // Get a `RoomEventCache`.
        let event_cache = client.event_cache();
        event_cache.subscribe().unwrap();

        let mut latest_event = LatestEvent::new(&weak_room, None);

        // First off, check the default value is `None`!
        assert_matches!(latest_event.current_value.get().await, LatestEventValue::None);

        // Second, set a new value.
        latest_event.update(LatestEventValue::LocalIsSending(local_room_message("foo"))).await;

        assert_matches!(
            latest_event.current_value.get().await,
            LatestEventValue::LocalIsSending(_)
        );

        // Finally, set a new `None` value. It must NOT be ignored.
        latest_event.update(LatestEventValue::None).await;

        assert_matches!(latest_event.current_value.get().await, LatestEventValue::None);
    }

    #[async_test]
    async fn test_update_ignore_none_if_previous_value_is_none() {
        let room_id = room_id!("!r0");

        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let weak_client = WeakClient::from_client(&client);

        // Create the room.
        client.base_client().get_or_create_room(room_id, RoomState::Joined);
        let weak_room = WeakRoom::new(weak_client, room_id.to_owned());

        let mut latest_event = LatestEvent::new(&weak_room, None);

        let mut stream = latest_event.subscribe().await;
        assert_pending!(stream);

        // Set a non-`None` value.
        latest_event.update(LatestEventValue::LocalIsSending(local_room_message("foo"))).await;
        // We get it.
        assert_next_matches!(stream, LatestEventValue::LocalIsSending(_));

        // Set a `None` value.
        latest_event.update(LatestEventValue::None).await;
        // We get it.
        assert_next_matches!(stream, LatestEventValue::None);

        // Set a `None` value, again!
        latest_event.update(LatestEventValue::None).await;
        // We get it? No!
        assert_pending!(stream);

        // Set a `None` value, again, and again!
        latest_event.update(LatestEventValue::None).await;
        // No means No!
        assert_pending!(stream);

        // Set a non-`None` value.
        latest_event.update(LatestEventValue::LocalIsSending(local_room_message("bar"))).await;
        // We get it. Oof.
        assert_next_matches!(stream, LatestEventValue::LocalIsSending(_));

        assert_pending!(stream);
    }

    #[async_test]
    async fn test_update_ignore_when_previous_value_has_the_same_event_id() {
        let room_id = room_id!("!r0");
        let user_id = user_id!("@mnt_io:matrix.org");
        let event_factory = EventFactory::new().sender(user_id).room(room_id);

        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let weak_client = WeakClient::from_client(&client);

        // Create the room.
        client.base_client().get_or_create_room(room_id, RoomState::Joined);
        let weak_room = WeakRoom::new(weak_client, room_id.to_owned());

        let mut latest_event = LatestEvent::new(&weak_room, None);

        let mut stream = latest_event.subscribe().await;
        assert_pending!(stream);

        // Set a non-`None` value.
        latest_event.update(LatestEventValue::LocalIsSending(local_room_message("foo"))).await;
        // We get it.
        assert_next_matches!(stream, LatestEventValue::LocalIsSending(_));

        // Set a non-`None` value, with a specific event ID.
        let first_event: RemoteLatestEventValue =
            event_factory.text_msg("A").event_id(event_id!("$ev0")).into();
        latest_event.update(LatestEventValue::Remote(first_event.clone())).await;
        // We get it.
        assert_next_matches!(stream, LatestEventValue::Remote(_));

        // Set a non-`None` value again, with the same event ID!
        latest_event.update(LatestEventValue::Remote(first_event)).await;
        // It's ignored!
        assert_pending!(stream);

        // Set a non-`None` value again, with a different event ID!
        let second_event = event_factory.text_msg("A").event_id(event_id!("$ev1")).into();
        latest_event.update(LatestEventValue::Remote(second_event)).await;
        // We get it!
        assert_next_matches!(stream, LatestEventValue::Remote(_));

        assert_pending!(stream);
    }

    #[async_test]
    async fn test_local_has_priority_over_remote() {
        let room_id = owned_room_id!("!r0");
        let user_id = user_id!("@mnt_io:matrix.org");
        let event_factory = EventFactory::new().sender(user_id).room(&room_id);

        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        client.base_client().get_or_create_room(&room_id, RoomState::Joined);
        let room = client.get_room(&room_id).unwrap();
        let weak_room = WeakRoom::new(WeakClient::from_client(&client), room_id.clone());

        let event_cache = client.event_cache();
        event_cache.subscribe().unwrap();

        // Fill the event cache with one event.
        client
            .event_cache_store()
            .lock()
            .await
            .expect("Could not acquire the event cache lock")
            .as_clean()
            .expect("Could not acquire a clean event cache lock")
            .handle_linked_chunk_updates(
                LinkedChunkId::Room(&room_id),
                vec![
                    Update::NewItemsChunk {
                        previous: None,
                        new: ChunkIdentifier::new(0),
                        next: None,
                    },
                    Update::PushItems {
                        at: Position::new(ChunkIdentifier::new(0), 0),
                        items: vec![event_factory.text_msg("A").event_id(event_id!("$ev0")).into()],
                    },
                ],
            )
            .await
            .unwrap();

        let (room_event_cache, _) = event_cache.for_room(&room_id).await.unwrap();

        let send_queue = client.send_queue();
        let room_send_queue = send_queue.for_room(room);

        let mut latest_event = LatestEvent::new(&weak_room, None);

        // First, let's create a `LatestEventValue` from the event cache. It must work.
        {
            latest_event.update_with_event_cache(&room_event_cache, user_id, None).await;

            assert_matches!(latest_event.current_value.get().await, LatestEventValue::Remote(_));
        }

        // Second, let's create a `LatestEventValue` from the send queue. It
        // must overwrite the current `LatestEventValue`.
        let transaction_id = OwnedTransactionId::from("txnid0");

        {
            let content = new_local_echo_content(&room_send_queue, &transaction_id, "B");

            let update = RoomSendQueueUpdate::NewLocalEvent(LocalEcho {
                transaction_id: transaction_id.clone(),
                content,
            });

            latest_event.update_with_send_queue(&update, &room_event_cache, user_id, None).await;

            assert_matches!(
                latest_event.current_value.get().await,
                LatestEventValue::LocalIsSending(_)
            );
        }

        // Third, let's create a `LatestEventValue` from the event cache.
        // Nothing must happen, it cannot overwrite the current
        // `LatestEventValue` because the local event isn't sent yet.
        {
            latest_event.update_with_event_cache(&room_event_cache, user_id, None).await;

            assert_matches!(
                latest_event.current_value.get().await,
                LatestEventValue::LocalIsSending(_)
            );
        }

        // Fourth, let's a `LatestEventValue` from the send queue. It must stay the
        // same, but now the local event is sent.
        {
            let update = RoomSendQueueUpdate::SentEvent {
                transaction_id,
                event_id: owned_event_id!("$ev1"),
            };

            latest_event.update_with_send_queue(&update, &room_event_cache, user_id, None).await;

            assert_matches!(
                latest_event.current_value.get().await,
                LatestEventValue::LocalHasBeenSent { .. }
            );
        }

        // Finally, let's create a `LatestEventValue` from the event cache. _Now_ it's
        // possible, because there is no more local events.
        {
            latest_event.update_with_event_cache(&room_event_cache, user_id, None).await;

            assert_matches!(latest_event.current_value.get().await, LatestEventValue::Remote(_));
        }
    }

    #[async_test]
    async fn test_redacted_latest_event_is_removed() {
        let room_id = owned_room_id!("!r0");
        let user_id = user_id!("@mnt_io:matrix.org");
        let event_factory = EventFactory::new().sender(user_id).room(&room_id);

        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        client.base_client().get_or_create_room(&room_id, RoomState::Joined);
        let _room = client.get_room(&room_id).unwrap();
        let weak_room = WeakRoom::new(WeakClient::from_client(&client), room_id.clone());

        let event_cache = client.event_cache();
        event_cache.subscribe().unwrap();

        let event_id_0 = event_id!("$ev0");
        let event_id_1 = event_id!("$ev1");

        // Fill the event cache with two events.
        client
            .event_cache_store()
            .lock()
            .await
            .expect("Could not acquire the event cache lock")
            .as_clean()
            .expect("Could not acquire a clean event cache lock")
            .handle_linked_chunk_updates(
                LinkedChunkId::Room(&room_id),
                vec![
                    Update::NewItemsChunk {
                        previous: None,
                        new: ChunkIdentifier::new(0),
                        next: None,
                    },
                    Update::PushItems {
                        at: Position::new(ChunkIdentifier::new(0), 0),
                        items: vec![
                            event_factory.text_msg("A").event_id(event_id_0).into(),
                            event_factory.text_msg("B").event_id(event_id_1).into(),
                        ],
                    },
                ],
            )
            .await
            .unwrap();

        let (room_event_cache, _) = event_cache.for_room(&room_id).await.unwrap();

        let mut latest_event = LatestEvent::new(&weak_room, None);

        // Let's create a `LatestEventValue` from the event cache. It must work.
        {
            latest_event.update_with_event_cache(&room_event_cache, user_id, None).await;

            assert_matches!(
                latest_event.current_value.get().await,
                LatestEventValue::Remote(remote) => {
                    assert_eq!(remote.event_id().as_deref(), Some(event_id_1));
                }
            );
        }

        // Now, let's redact `$ev1`.
        {
            server
                .mock_sync()
                .ok_and_run(&client, |builder| {
                    builder.add_joined_room(
                        JoinedRoomBuilder::new(&room_id)
                            .add_timeline_event(event_factory.redaction(event_id_1)),
                    );
                })
                .await;

            yield_now().await;

            latest_event.update_with_event_cache(&room_event_cache, user_id, None).await;

            assert_matches!(
                latest_event.current_value.get().await,
                LatestEventValue::Remote(remote) => {
                    // `$ev1` has been redacted, so `$ev0` is the new candidate!
                    assert_eq!(remote.event_id().as_deref(), Some(event_id_0));
                }
            );
        }
    }

    #[async_test]
    async fn test_store_latest_event_value() {
        let room_id = owned_room_id!("!r0");
        let user_id = user_id!("@mnt_io:matrix.org");
        let event_factory = EventFactory::new().sender(user_id).room(&room_id);

        let server = MatrixMockServer::new().await;

        let store_config =
            StoreConfig::new(CrossProcessLockConfig::multi_process("cross-process-lock-holder"));

        // Load the client for the first time, and run some operations.
        {
            let client = server
                .client_builder()
                .on_builder(|builder| builder.store_config(store_config.clone()))
                .build()
                .await;
            let mut room_info_notable_update_receiver = client.room_info_notable_update_receiver();
            let room = client.base_client().get_or_create_room(&room_id, RoomState::Joined);
            let weak_room = WeakRoom::new(WeakClient::from_client(&client), room_id.clone());

            let event_cache = client.event_cache();
            event_cache.subscribe().unwrap();

            // Fill the event cache with one event.
            client
                .event_cache_store()
                .lock()
                .await
                .expect("Could not acquire the event cache lock")
                .as_clean()
                .expect("Could not acquire a clean event cache lock")
                .handle_linked_chunk_updates(
                    LinkedChunkId::Room(&room_id),
                    vec![
                        Update::NewItemsChunk {
                            previous: None,
                            new: ChunkIdentifier::new(0),
                            next: None,
                        },
                        Update::PushItems {
                            at: Position::new(ChunkIdentifier::new(0), 0),
                            items: vec![
                                event_factory.text_msg("A").event_id(event_id!("$ev0")).into(),
                            ],
                        },
                    ],
                )
                .await
                .unwrap();

            let (room_event_cache, _) = event_cache.for_room(&room_id).await.unwrap();

            // Check there is no `LatestEventValue` for the moment.
            {
                let latest_event = room.latest_event();

                assert_matches!(latest_event, LatestEventValue::None);
            }

            // Generate a new `LatestEventValue`.
            {
                let mut latest_event = LatestEvent::new(&weak_room, None);
                latest_event.update_with_event_cache(&room_event_cache, user_id, None).await;

                assert_matches!(
                    latest_event.current_value.get().await,
                    LatestEventValue::Remote(_)
                );
            }

            // We see the `RoomInfoNotableUpdateReasons`.
            {
                let update = room_info_notable_update_receiver.recv().await.unwrap();

                assert_eq!(update.room_id, room_id);
                assert!(update.reasons.contains(RoomInfoNotableUpdateReasons::LATEST_EVENT));
            }

            // Check it's in the `RoomInfo` and in `Room`.
            {
                let latest_event = room.latest_event();

                assert_matches!(latest_event, LatestEventValue::Remote(_));
            }
        }

        // Reload the client with the same store config, and see the `LatestEventValue`
        // is inside the `RoomInfo`.
        {
            let client = server
                .client_builder()
                .on_builder(|builder| builder.store_config(store_config))
                .build()
                .await;
            let room = client.get_room(&room_id).unwrap();
            let latest_event = room.latest_event();

            assert_matches!(latest_event, LatestEventValue::Remote(_));
        }
    }
}