matrix-sdk 0.19.0

A high level Matrix client-server library.
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
825
826
// 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.

//! The search index is an abstraction layer in the matrix-sdk for the
//! matrix-sdk-search crate. It provides a [`SearchIndex`] which wraps
//! multiple [`RoomIndex`].

use std::{collections::hash_map::HashMap, path::PathBuf, sync::Arc};

use futures_util::future::join_all;
use matrix_sdk_base::{
    check_validity_of_replacement_events, deserialized_responses::TimelineEvent,
};
use matrix_sdk_search::{
    error::IndexError,
    index::{IndexableEvent, RoomIndex, RoomIndexOperation, builder::RoomIndexBuilder},
};
use ruma::{
    EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId,
    events::{
        AnySyncMessageLikeEvent, AnySyncTimelineEvent,
        poll::{
            start::SyncPollStartEvent,
            unstable_start::{SyncUnstablePollStartEvent, UnstablePollStartEventContent},
        },
        room::{
            message::{MessageType, OriginalSyncRoomMessageEvent, Relation, SyncRoomMessageEvent},
            redaction::SyncRoomRedactionEvent,
        },
        sticker::SyncStickerEvent,
    },
    room_version_rules::RedactionRules,
};
use tokio::sync::{Mutex, MutexGuard};
use tracing::{debug, warn};

use crate::event_cache::RoomEventCache;

type Password = String;

/// Type of location to store [`RoomIndex`]
#[derive(Clone, Debug)]
pub enum SearchIndexStoreKind {
    /// Store unencrypted in file system folder
    UnencryptedDirectory(PathBuf),
    /// Store encrypted in file system folder
    EncryptedDirectory(PathBuf, Password),
    /// Store in memory
    InMemory,
}

/// Object that handles inteeraction with [`RoomIndex`]'s for search
#[derive(Clone, Debug)]
pub struct SearchIndex {
    /// HashMap that links each joined room to its RoomIndex
    room_indexes: Arc<Mutex<HashMap<OwnedRoomId, RoomIndex>>>,

    /// Base directory that stores the directories for each RoomIndex
    search_index_store_kind: SearchIndexStoreKind,
}

impl SearchIndex {
    /// Create a new [`SearchIndex`]
    pub fn new(
        room_indexes: Arc<Mutex<HashMap<OwnedRoomId, RoomIndex>>>,
        search_index_store_kind: SearchIndexStoreKind,
    ) -> Self {
        Self { room_indexes, search_index_store_kind }
    }

    /// Acquire [`SearchIndexGuard`] for this [`SearchIndex`].
    pub async fn lock(&self) -> SearchIndexGuard<'_> {
        SearchIndexGuard {
            index_map: self.room_indexes.lock().await,
            search_index_store_kind: &self.search_index_store_kind,
        }
    }
}

/// Object that represents an acquired [`SearchIndex`].
#[derive(Debug)]
pub struct SearchIndexGuard<'a> {
    /// Guard around the [`RoomIndex`] map
    index_map: MutexGuard<'a, HashMap<OwnedRoomId, RoomIndex>>,

    /// Base directory that stores the directories for each RoomIndex
    search_index_store_kind: &'a SearchIndexStoreKind,
}

impl SearchIndexGuard<'_> {
    fn create_index(&self, room_id: &RoomId) -> Result<RoomIndex, IndexError> {
        let index = match self.search_index_store_kind {
            SearchIndexStoreKind::UnencryptedDirectory(path) => {
                RoomIndexBuilder::new_on_disk(path.to_path_buf(), room_id).unencrypted().build()?
            }
            SearchIndexStoreKind::EncryptedDirectory(path, password) => {
                RoomIndexBuilder::new_on_disk(path.to_path_buf(), room_id)
                    .encrypted(password)
                    .build()?
            }
            SearchIndexStoreKind::InMemory => RoomIndexBuilder::new_in_memory(room_id).build(),
        };
        Ok(index)
    }

    /// Handle a [`RoomIndexOperation`] in the [`RoomIndex`] of a given
    /// [`RoomId`]
    ///
    /// This which will add/remove/edit an event in the index based on the
    /// event type.
    ///
    /// Prefer [`SearchIndexGuard::bulk_execute`] for multiple operations.
    pub(crate) fn execute(
        &mut self,
        operation: RoomIndexOperation,
        room_id: &RoomId,
    ) -> Result<(), IndexError> {
        if !self.index_map.contains_key(room_id) {
            let index = self.create_index(room_id)?;
            self.index_map.insert(room_id.to_owned(), index);
        }

        let index = self.index_map.get_mut(room_id).expect("index should exist");

        index.execute(operation)
    }

    /// Handle a [`RoomIndexOperation`] in the [`RoomIndex`] of a given
    /// [`RoomId`]
    ///
    /// This which will add/remove/edit an event in the index based on the
    /// event type.
    pub(crate) fn bulk_execute(
        &mut self,
        operations: Vec<RoomIndexOperation>,
        room_id: &RoomId,
    ) -> Result<(), IndexError> {
        if !self.index_map.contains_key(room_id) {
            let index = self.create_index(room_id)?;
            self.index_map.insert(room_id.to_owned(), index);
        }

        let index = self.index_map.get_mut(room_id).expect("index should exist");

        index.bulk_execute(operations)
    }

    /// Search a [`Room`]'s index for the query and return at most
    /// max_number_of_results results.
    pub(crate) fn search(
        &mut self,
        query: &str,
        max_number_of_results: usize,
        pagination_offset: Option<usize>,
        room_id: &RoomId,
    ) -> Result<Vec<(f32, OwnedEventId)>, IndexError> {
        if !self.index_map.contains_key(room_id) {
            let index = self.create_index(room_id)?;
            self.index_map.insert(room_id.to_owned(), index);
        }

        let index = self.index_map.get_mut(room_id).expect("index should exist");

        index.search(query, max_number_of_results, pagination_offset)
    }

    /// Given a [`TimelineEvent`] this function will derive a
    /// [`RoomIndexOperation`], if it should be handled, and execute it;
    /// returning the result.
    ///
    /// Prefer [`SearchIndexGuard::bulk_handle_timeline_event`] for multiple
    /// events.
    pub async fn handle_timeline_event(
        &mut self,
        event: TimelineEvent,
        room_cache: &RoomEventCache,
        room_id: &RoomId,
        redaction_rules: &RedactionRules,
    ) -> Result<(), IndexError> {
        if let Some(index_operation) =
            parse_timeline_event(room_cache, event, redaction_rules).await
        {
            self.execute(index_operation, room_id)
        } else {
            Ok(())
        }
    }

    /// Run [`SearchIndexGuard::handle_timeline_event`] for multiple
    /// [`TimelineEvent`].
    pub async fn bulk_handle_timeline_event<T>(
        &mut self,
        events: T,
        room_cache: &RoomEventCache,
        room_id: &RoomId,
        redaction_rules: &RedactionRules,
    ) -> Result<(), IndexError>
    where
        T: Iterator<Item = TimelineEvent>,
    {
        let futures = events.map(|ev| parse_timeline_event(room_cache, ev, redaction_rules));

        let operations: Vec<_> = join_all(futures).await.into_iter().flatten().collect();

        self.bulk_execute(operations, room_id)
    }
}

/// Given an event id this function returns the most recent edit on said event
/// or the event itself if there are no edits.
async fn get_most_recent_edit(
    cache: &RoomEventCache,
    original: &EventId,
) -> Option<OriginalSyncRoomMessageEvent> {
    use ruma::events::{AnySyncTimelineEvent, relation::RelationType};

    let Ok(Some((original_ev, related))) =
        cache.find_event_with_relations(original, Some(vec![RelationType::Replacement])).await
    else {
        debug!("Couldn't find relations for {}", original);
        return None;
    };

    // Only index valid replacements (matching sender, type, etc.); otherwise
    // anyone could rewrite another user's indexed message. Fall back to the
    // original event when there is no valid edit.
    let latest = related
        .iter()
        .rev()
        .find(|edit| {
            check_validity_of_replacement_events(
                original_ev.raw(),
                original_ev.encryption_info().map(|info| &**info),
                edit.raw(),
                edit.encryption_info().map(|info| &**info),
            )
            .is_ok()
        })
        .unwrap_or(&original_ev);

    match latest.raw().deserialize() {
        Ok(AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(latest))) => {
            latest.as_original().cloned()
        }
        _ => None,
    }
}

/// Indexable text for a media message: its filename plus any caption.
fn media_body(filename: &str, caption: Option<&str>) -> String {
    match caption {
        Some(caption) => format!("{filename} {caption}"),
        None => filename.to_owned(),
    }
}

/// Extract the searchable text from a room message, or `None` if its type
/// carries no text to index.
fn room_message_body(msgtype: &MessageType) -> Option<String> {
    match msgtype {
        MessageType::Text(content) => Some(content.body.clone()),
        MessageType::Emote(content) => Some(content.body.clone()),
        MessageType::Notice(content) => Some(content.body.clone()),
        MessageType::ServerNotice(content) => Some(content.body.clone()),
        MessageType::Location(content) => Some(content.body.clone()),
        MessageType::Image(content) => Some(media_body(content.filename(), content.caption())),
        MessageType::Video(content) => Some(media_body(content.filename(), content.caption())),
        MessageType::Audio(content) => Some(media_body(content.filename(), content.caption())),
        MessageType::File(content) => Some(media_body(content.filename(), content.caption())),
        _ => None,
    }
}

/// Build an [`IndexableEvent`] from a room message, or `None` if its type
/// carries no searchable text.
fn indexable_from_room_message(
    event: &OriginalSyncRoomMessageEvent,
    timestamp: Option<MilliSecondsSinceUnixEpoch>,
) -> Option<IndexableEvent> {
    let body = room_message_body(&event.content.msgtype)?;
    let original_event_id = match &event.content.relates_to {
        Some(Relation::Replacement(replacement)) => replacement.event_id.clone(),
        _ => event.event_id.clone(),
    };

    Some(IndexableEvent::new(
        event.event_id.clone(),
        original_event_id,
        event.sender.clone(),
        timestamp,
        body,
    ))
}

/// If the given [`OriginalSyncRoomMessageEvent`] is an edit we make an
/// [`RoomIndexOperation::Edit`] with the new most recent version of the
/// original.
async fn handle_possible_edit(
    event: &OriginalSyncRoomMessageEvent,
    timestamp: Option<MilliSecondsSinceUnixEpoch>,
    cache: &RoomEventCache,
) -> Option<RoomIndexOperation> {
    if let Some(Relation::Replacement(replacement_data)) = &event.content.relates_to {
        if let Some(recent) = get_most_recent_edit(cache, &replacement_data.event_id).await {
            return Some(
                indexable_from_room_message(&recent, timestamp).map_or(
                    RoomIndexOperation::Noop,
                    |indexable| {
                        RoomIndexOperation::Edit(replacement_data.event_id.clone(), indexable)
                    },
                ),
            );
        } else {
            return Some(RoomIndexOperation::Noop);
        }
    }
    None
}

/// Return a [`RoomIndexOperation::Edit`] or [`RoomIndexOperation::Add`]
/// depending on the message.
async fn handle_room_message(
    event: SyncRoomMessageEvent,
    timestamp: Option<MilliSecondsSinceUnixEpoch>,
    cache: &RoomEventCache,
) -> Option<RoomIndexOperation> {
    if let Some(event) = event.as_original() {
        return handle_possible_edit(event, timestamp, cache).await.or(get_most_recent_edit(
            cache,
            &event.event_id,
        )
        .await
        .and_then(|recent| {
            indexable_from_room_message(&recent, timestamp).map(RoomIndexOperation::Add)
        }));
    }
    None
}

/// Return a [`RoomIndexOperation`] removing a redacted event from the index, or
/// re-adding the most recent remaining version if an edit was redacted.
async fn handle_room_redaction(
    event: SyncRoomRedactionEvent,
    timestamp: Option<MilliSecondsSinceUnixEpoch>,
    cache: &RoomEventCache,
    rules: &RedactionRules,
) -> Option<RoomIndexOperation> {
    let redacted_event_id = event.redacts(rules)?;

    // If the redacted event was a room message edit, re-add the most recent
    // remaining version instead of just removing it.
    if let Ok(Some(redacted_event)) = cache.find_event(redacted_event_id).await
        && let Ok(AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(
            redacted_event,
        ))) = redacted_event.raw().deserialize()
        && let Some(redacted_event) = redacted_event.as_original()
        && let Some(operation) = handle_possible_edit(redacted_event, timestamp, cache).await
    {
        return Some(operation);
    }

    // Otherwise remove the redacted event from the index. This covers plain
    // messages, stickers and polls.
    Some(RoomIndexOperation::Remove(redacted_event_id.to_owned()))
}

/// Return a [`RoomIndexOperation::Add`] indexing a sticker's descriptive text.
fn handle_sticker(
    event: SyncStickerEvent,
    timestamp: Option<MilliSecondsSinceUnixEpoch>,
) -> Option<RoomIndexOperation> {
    let event = event.as_original()?;

    Some(RoomIndexOperation::Add(IndexableEvent::new(
        event.event_id.clone(),
        event.event_id.clone(),
        event.sender.clone(),
        timestamp,
        event.content.body.clone(),
    )))
}

/// Return a [`RoomIndexOperation::Add`] indexing an unstable poll's question
/// and answers.
///
/// ponytail: only indexes the initial `New` poll — edits (`Replacement`) and
/// poll ends are ignored. Add edit handling if editing a poll needs to update
/// search results.
fn handle_unstable_poll_start(
    event: SyncUnstablePollStartEvent,
    timestamp: Option<MilliSecondsSinceUnixEpoch>,
) -> Option<RoomIndexOperation> {
    let event = event.as_original()?;

    let UnstablePollStartEventContent::New(content) = &event.content else {
        return None;
    };

    let block = &content.poll_start;
    let mut body = block.question.text.clone();
    for answer in block.answers.iter() {
        body.push(' ');
        body.push_str(&answer.text);
    }

    Some(RoomIndexOperation::Add(IndexableEvent::new(
        event.event_id.clone(),
        event.event_id.clone(),
        event.sender.clone(),
        timestamp,
        body,
    )))
}

/// Return a [`RoomIndexOperation::Add`] indexing a stable poll's question and
/// answers.
///
/// ponytail: like [`handle_unstable_poll_start`], edits and poll ends are
/// ignored — only the initial poll is indexed.
fn handle_poll_start(
    event: SyncPollStartEvent,
    timestamp: Option<MilliSecondsSinceUnixEpoch>,
) -> Option<RoomIndexOperation> {
    let event = event.as_original()?;

    // Skip poll edits, matching the unstable poll handling.
    if let Some(Relation::Replacement(_)) = &event.content.relates_to {
        return None;
    }

    let block = &event.content.poll;
    let mut body = block.question.text.find_plain()?.to_owned();
    for answer in block.answers.iter() {
        if let Some(text) = answer.text.find_plain() {
            body.push(' ');
            body.push_str(text);
        }
    }

    Some(RoomIndexOperation::Add(IndexableEvent::new(
        event.event_id.clone(),
        event.event_id.clone(),
        event.sender.clone(),
        timestamp,
        body,
    )))
}

/// Prepare a [`TimelineEvent`] into a [`RoomIndexOperation`] for search
/// indexing.
async fn parse_timeline_event(
    cache: &RoomEventCache,
    event: TimelineEvent,
    redaction_rules: &RedactionRules,
) -> Option<RoomIndexOperation> {
    use ruma::events::AnySyncTimelineEvent;

    if event.kind.is_utd() {
        return None;
    }

    let timestamp = event.timestamp();

    match event.raw().deserialize() {
        Ok(event) => match event {
            AnySyncTimelineEvent::MessageLike(event) => match event {
                AnySyncMessageLikeEvent::RoomMessage(event) => {
                    handle_room_message(event, timestamp, cache).await
                }
                AnySyncMessageLikeEvent::RoomRedaction(event) => {
                    handle_room_redaction(event, timestamp, cache, redaction_rules).await
                }
                AnySyncMessageLikeEvent::Sticker(event) => handle_sticker(event, timestamp),
                AnySyncMessageLikeEvent::PollStart(event) => handle_poll_start(event, timestamp),
                AnySyncMessageLikeEvent::UnstablePollStart(event) => {
                    handle_unstable_poll_start(event, timestamp)
                }
                _ => None,
            },
            AnySyncTimelineEvent::State(_) => None,
        },

        Err(e) => {
            warn!("failed to parse event: {e:?}");
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use matrix_sdk_test::{JoinedRoomBuilder, async_test, event_factory::EventFactory};
    use ruma::{
        event_id, events::room::message::RoomMessageEventContentWithoutRelation, room_id, user_id,
    };

    use crate::test_utils::mocks::MatrixMockServer;

    #[cfg(feature = "experimental-search")]
    #[async_test]
    async fn test_sync_message_is_indexed() {
        let mock_server = MatrixMockServer::new().await;
        let client = mock_server.client_builder().build().await;

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

        let room_id = room_id!("!room_id:localhost");
        let event_id = event_id!("$event_id:localost");
        let user_id = user_id!("@user_id:localost");

        let event_factory = EventFactory::new();
        let room = mock_server
            .sync_room(
                &client,
                JoinedRoomBuilder::new(room_id).add_timeline_bulk(vec![
                    event_factory
                        .text_msg("this is a sentence")
                        .event_id(event_id)
                        .sender(user_id)
                        .into_raw_sync(),
                ]),
            )
            .await;

        let response = room.search("this", 5, None).await.expect("search should have 1 result");

        assert_eq!(response.len(), 1, "unexpected numbers of responses: {response:?}");
        assert_eq!(response[0].1, event_id, "event id doesn't match: {response:?}");
    }

    #[cfg(feature = "experimental-search")]
    #[async_test]
    async fn test_sync_media_message_is_indexed() {
        use ruma::owned_mxc_uri;

        let mock_server = MatrixMockServer::new().await;
        let client = mock_server.client_builder().build().await;

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

        let room_id = room_id!("!room_id:localhost");
        let image_id = event_id!("$image_id:localhost");
        let file_id = event_id!("$file_id:localhost");
        let user_id = user_id!("@user_id:localhost");

        let f = EventFactory::new();
        let room = mock_server
            .sync_room(
                &client,
                JoinedRoomBuilder::new(room_id).add_timeline_bulk(vec![
                    f.image("holiday_beach.jpg".to_owned(), owned_mxc_uri!("mxc://localhost/1"))
                        .caption(Some("sunset over the ocean".to_owned()), None)
                        .event_id(image_id)
                        .sender(user_id)
                        .into_raw_sync(),
                    f.image("quarterly_report.pdf".to_owned(), owned_mxc_uri!("mxc://localhost/2"))
                        .event_id(file_id)
                        .sender(user_id)
                        .into_raw_sync(),
                ]),
            )
            .await;

        // The caption is indexed.
        let response = room.search("sunset", 5, None).await.unwrap();
        assert_eq!(response.len(), 1, "unexpected results for caption search: {response:?}");
        assert_eq!(response[0].1, image_id, "event id doesn't match: {response:?}");

        // The filename is indexed.
        let response = room.search("holiday_beach", 5, None).await.unwrap();
        assert_eq!(response.len(), 1, "unexpected results for filename search: {response:?}");
        assert_eq!(response[0].1, image_id, "event id doesn't match: {response:?}");

        // A media message without a caption still indexes its filename.
        let response = room.search("quarterly_report", 5, None).await.unwrap();
        assert_eq!(response.len(), 1, "unexpected results for filename search: {response:?}");
        assert_eq!(response[0].1, file_id, "event id doesn't match: {response:?}");
    }

    #[cfg(feature = "experimental-search")]
    #[async_test]
    async fn test_sync_sticker_and_poll_are_indexed() {
        use ruma::{events::room::ImageInfo, owned_mxc_uri};

        let mock_server = MatrixMockServer::new().await;
        let client = mock_server.client_builder().build().await;

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

        let room_id = room_id!("!room_id:localhost");
        let sticker_id = event_id!("$sticker_id:localhost");
        let poll_id = event_id!("$poll_id:localhost");
        let user_id = user_id!("@user_id:localhost");

        let f = EventFactory::new().room(room_id).sender(user_id);
        let room = mock_server
            .sync_room(
                &client,
                JoinedRoomBuilder::new(room_id).add_timeline_bulk(vec![
                    f.sticker(
                        "a waving cat",
                        ImageInfo::new(),
                        owned_mxc_uri!("mxc://localhost/1"),
                    )
                    .event_id(sticker_id)
                    .into_raw_sync(),
                    f.poll_start("fallback", "favourite cheese?", vec!["comté", "gruyère"])
                        .event_id(poll_id)
                        .into_raw_sync(),
                ]),
            )
            .await;

        // The sticker's description is indexed.
        let response = room.search("waving", 5, None).await.unwrap();
        assert_eq!(response.len(), 1, "unexpected results for sticker search: {response:?}");
        assert_eq!(response[0].1, sticker_id, "event id doesn't match: {response:?}");

        // The poll question is indexed.
        let response = room.search("cheese", 5, None).await.unwrap();
        assert_eq!(response.len(), 1, "unexpected results for poll question search: {response:?}");
        assert_eq!(response[0].1, poll_id, "event id doesn't match: {response:?}");

        // The poll answers are indexed.
        let response = room.search("gruyère", 5, None).await.unwrap();
        assert_eq!(response.len(), 1, "unexpected results for poll answer search: {response:?}");
        assert_eq!(response[0].1, poll_id, "event id doesn't match: {response:?}");
    }

    #[cfg(feature = "experimental-search")]
    #[async_test]
    async fn test_sync_stable_poll_is_indexed() {
        use ruma::events::{
            message::TextContentBlock,
            poll::start::{PollAnswer, PollAnswers, PollContentBlock, PollStartEventContent},
        };

        let mock_server = MatrixMockServer::new().await;
        let client = mock_server.client_builder().build().await;

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

        let room_id = room_id!("!room_id:localhost");
        let poll_id = event_id!("$stable_poll_id:localhost");
        let user_id = user_id!("@user_id:localhost");

        let answers: PollAnswers = vec![
            PollAnswer::new("0".to_owned(), TextContentBlock::plain("comté")),
            PollAnswer::new("1".to_owned(), TextContentBlock::plain("gruyère")),
        ]
        .try_into()
        .unwrap();
        let poll = PollContentBlock::new(TextContentBlock::plain("favourite cheese?"), answers);
        let content = PollStartEventContent::new(TextContentBlock::plain("fallback"), poll);

        let f = EventFactory::new().room(room_id).sender(user_id);
        let room = mock_server
            .sync_room(
                &client,
                JoinedRoomBuilder::new(room_id)
                    .add_timeline_bulk(vec![f.event(content).event_id(poll_id).into_raw_sync()]),
            )
            .await;

        // The poll question is indexed.
        let response = room.search("cheese", 5, None).await.unwrap();
        assert_eq!(response.len(), 1, "unexpected results for poll question search: {response:?}");
        assert_eq!(response[0].1, poll_id, "event id doesn't match: {response:?}");

        // The poll answers are indexed.
        let response = room.search("gruyère", 5, None).await.unwrap();
        assert_eq!(response.len(), 1, "unexpected results for poll answer search: {response:?}");
        assert_eq!(response[0].1, poll_id, "event id doesn't match: {response:?}");
    }

    #[cfg(feature = "experimental-search")]
    #[async_test]
    async fn test_search_index_edit_ordering() {
        let room_id = room_id!("!room_id:localhost");
        let dummy_id = event_id!("$dummy");
        let edit1_id = event_id!("$edit1");
        let edit2_id = event_id!("$edit2");
        let edit3_id = event_id!("$edit3");
        let original_id = event_id!("$original");

        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

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

        let room = server.sync_joined_room(&client, room_id).await;

        let f = EventFactory::new().room(room_id).sender(user_id!("@user_id:localhost"));

        // Indexable dummy message required because RoomIndex is initialised lazily.
        let dummy = f.text_msg("dummy").event_id(dummy_id);

        let original = f.text_msg("This is a message").event_id(original_id);

        let edit1 = f
            .text_msg("* A new message")
            .edit(original_id, RoomMessageEventContentWithoutRelation::text_plain("A new message"))
            .event_id(edit1_id);

        let edit2 = f
            .text_msg("* An even newer message")
            .edit(
                original_id,
                RoomMessageEventContentWithoutRelation::text_plain("An even newer message"),
            )
            .event_id(edit2_id);

        let edit3 = f
            .text_msg("* The newest message")
            .edit(
                original_id,
                RoomMessageEventContentWithoutRelation::text_plain("The newest message"),
            )
            .event_id(edit3_id);

        server
            .sync_room(
                &client,
                JoinedRoomBuilder::new(room_id)
                    .add_timeline_event(dummy)
                    .add_timeline_event(edit1)
                    .add_timeline_event(edit2),
            )
            .await;

        let results = room.search("message", 3, None).await.unwrap();

        assert_eq!(results.len(), 0, "Search should return 0 results, got {results:?}");

        // Adding the original after some pending edits should add the latest edit
        // instead of the original.
        server
            .sync_room(&client, JoinedRoomBuilder::new(room_id).add_timeline_event(original))
            .await;

        let results = room.search("message", 3, None).await.unwrap();

        assert_eq!(results.len(), 1, "Search should return 1 result, got {results:?}");
        assert_eq!(
            results[0].1, edit2_id,
            "Search should return latest edit, got {:?}",
            results[0].1
        );

        // Editing the original after it exists and there has been another edit should
        // delete the previous edits and add this one
        server.sync_room(&client, JoinedRoomBuilder::new(room_id).add_timeline_event(edit3)).await;

        let results = room.search("message", 3, None).await.unwrap();

        assert_eq!(results.len(), 1, "Search should return 1 result, got {results:?}");
        assert_eq!(
            results[0].1, edit3_id,
            "Search should return latest edit, got {:?}",
            results[0].1
        );
    }

    #[cfg(feature = "experimental-search")]
    #[async_test]
    async fn test_search_index_ignores_cross_sender_edit() {
        let room_id = room_id!("!room_id:localhost");
        let original_id = event_id!("$original");
        let edit_id = event_id!("$edit");

        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

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

        let room = server.sync_joined_room(&client, room_id).await;

        let f = EventFactory::new().room(room_id);

        let original =
            f.text_msg("original alpha").sender(user_id!("@alice:localhost")).event_id(original_id);

        // An edit from a different user than the original sender is not a valid
        // replacement and must be ignored.
        let malicious_edit = f
            .text_msg("* malicious beta")
            .edit(original_id, RoomMessageEventContentWithoutRelation::text_plain("malicious beta"))
            .sender(user_id!("@bob:localhost"))
            .event_id(edit_id);

        server
            .sync_room(&client, JoinedRoomBuilder::new(room_id).add_timeline_event(original))
            .await;

        // The original message is indexed.
        let results = room.search("alpha", 3, None).await.unwrap();
        assert_eq!(results.len(), 1, "Original should be indexed, got {results:?}");
        assert_eq!(results[0].1, original_id, "unexpected event id: {results:?}");

        server
            .sync_room(&client, JoinedRoomBuilder::new(room_id).add_timeline_event(malicious_edit))
            .await;

        // The forged edit's content must not be indexed.
        let results = room.search("beta", 3, None).await.unwrap();
        assert_eq!(results.len(), 0, "Cross-sender edit should be ignored, got {results:?}");

        // The original message stays indexed.
        let results = room.search("alpha", 3, None).await.unwrap();
        assert_eq!(results.len(), 1, "Original should stay indexed, got {results:?}");
        assert_eq!(results[0].1, original_id, "unexpected event id: {results:?}");
    }
}