1// Copyright 2024 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
1415use std::{fmt::Formatter, sync::Arc};
1617use futures_util::{stream, StreamExt};
18use matrix_sdk::{
19 config::RequestConfig, event_cache::paginator::PaginatorError, BoxFuture, Room,
20 SendOutsideWasm, SyncOutsideWasm,
21};
22use matrix_sdk_base::deserialized_responses::TimelineEvent;
23use ruma::{events::relation::RelationType, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId};
24use thiserror::Error;
25use tracing::{debug, warn};
2627/// Utility to load the pinned events in a room.
28pub struct PinnedEventsLoader {
29/// Backend to load pinned events.
30room: Arc<dyn PinnedEventsRoom>,
3132/// Maximum number of pinned events to load (either from network or the
33 /// cache).
34max_events_to_load: usize,
3536/// Number of requests to load pinned events that can run concurrently. This
37 /// is used to avoid overwhelming a home server with dozens or hundreds
38 /// of concurrent requests.
39max_concurrent_requests: usize,
40}
4142impl PinnedEventsLoader {
43/// Creates a new `PinnedEventsLoader` instance.
44pub fn new(
45 room: Arc<dyn PinnedEventsRoom>,
46 max_events_to_load: usize,
47 max_concurrent_requests: usize,
48 ) -> Self {
49Self { room, max_events_to_load, max_concurrent_requests }
50 }
5152/// Loads the pinned events in this room, using the cache first and then
53 /// requesting the event from the homeserver if it couldn't be found.
54 /// This method will perform as many concurrent requests for events as
55 /// `max_concurrent_requests` allows, to avoid overwhelming the server.
56 ///
57 /// It returns a `Result` with either a
58 /// chronologically sorted list of retrieved [`TimelineEvent`]s
59 /// or a [`PinnedEventsLoaderError`].
60pub async fn load_events(&self) -> Result<Vec<TimelineEvent>, PinnedEventsLoaderError> {
61let pinned_event_ids: Vec<OwnedEventId> = self
62.room
63 .pinned_event_ids()
64 .unwrap_or_default()
65 .into_iter()
66 .rev()
67 .take(self.max_events_to_load)
68 .rev()
69 .collect();
7071if pinned_event_ids.is_empty() {
72return Ok(Vec::new());
73 }
7475let request_config = Some(RequestConfig::default().retry_limit(3));
7677let mut loaded_events: Vec<TimelineEvent> =
78 stream::iter(pinned_event_ids.into_iter().map(|event_id| {
79let provider = self.room.clone();
80let relations_filter =
81Some(vec![RelationType::Annotation, RelationType::Replacement]);
82async move {
83match provider
84 .load_event_with_relations(&event_id, request_config, relations_filter)
85 .await
86{
87Ok((event, related_events)) => {
88let mut events = vec![event];
89 events.extend(related_events);
90Some(events)
91 }
92Err(err) => {
93warn!("error when loading pinned event: {err}");
94None
95}
96 }
97 }
98 }))
99 .buffer_unordered(self.max_concurrent_requests)
100// Get only the `Some<Vec<_>>` results
101.flat_map(stream::iter)
102// Flatten the `Vec`s into a single one containing all their items
103.flat_map(stream::iter)
104 .collect()
105 .await;
106107if loaded_events.is_empty() {
108return Err(PinnedEventsLoaderError::TimelineReloadFailed);
109 }
110111// Sort using chronological ordering (oldest -> newest)
112loaded_events.sort_by_key(|item| {
113 item.raw()
114 .deserialize()
115 .map(|e| e.origin_server_ts())
116 .unwrap_or_else(|_| MilliSecondsSinceUnixEpoch::now())
117 });
118119Ok(loaded_events)
120 }
121}
122123pub trait PinnedEventsRoom: SendOutsideWasm + SyncOutsideWasm {
124/// Load a single room event using the cache or network and any events
125 /// related to it, if they are cached.
126 ///
127 /// You can control which types of related events are retrieved using
128 /// `related_event_filters`. A `None` value will retrieve any type of
129 /// related event.
130fn load_event_with_relations<'a>(
131&'a self,
132 event_id: &'a EventId,
133 request_config: Option<RequestConfig>,
134 related_event_filters: Option<Vec<RelationType>>,
135 ) -> BoxFuture<'a, Result<(TimelineEvent, Vec<TimelineEvent>), PaginatorError>>;
136137/// Get the pinned event ids for a room.
138fn pinned_event_ids(&self) -> Option<Vec<OwnedEventId>>;
139140/// Checks whether an event id is pinned in this room.
141 ///
142 /// It avoids having to clone the whole list of event ids to check a single
143 /// value.
144fn is_pinned_event(&self, event_id: &EventId) -> bool;
145}
146147impl PinnedEventsRoom for Room {
148fn load_event_with_relations<'a>(
149&'a self,
150 event_id: &'a EventId,
151 request_config: Option<RequestConfig>,
152 related_event_filters: Option<Vec<RelationType>>,
153 ) -> BoxFuture<'a, Result<(TimelineEvent, Vec<TimelineEvent>), PaginatorError>> {
154 Box::pin(async move {
155if let Ok((cache, _handles)) = self.event_cache().await {
156if let Some(ret) = cache.event_with_relations(event_id, related_event_filters).await
157{
158debug!("Loaded pinned event {event_id} and related events from cache");
159return Ok(ret);
160 }
161 }
162163debug!("Loading pinned event {event_id} from HS");
164self.event(event_id, request_config)
165 .await
166.map(|e| (e, Vec::new()))
167 .map_err(|err| PaginatorError::SdkError(Box::new(err)))
168 })
169 }
170171fn pinned_event_ids(&self) -> Option<Vec<OwnedEventId>> {
172self.clone_info().pinned_event_ids()
173 }
174175fn is_pinned_event(&self, event_id: &EventId) -> bool {
176self.clone_info().is_pinned_event(event_id)
177 }
178}
179180#[cfg(not(tarpaulin_include))]
181impl std::fmt::Debug for PinnedEventsLoader {
182fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
183 f.debug_struct("PinnedEventsLoader")
184 .field("max_events_to_load", &self.max_events_to_load)
185 .finish()
186 }
187}
188189/// Errors related to `PinnedEventsLoader` usage.
190#[derive(Error, Debug)]
191pub enum PinnedEventsLoaderError {
192#[error("No event found for the given event id.")]
193EventNotFound(OwnedEventId),
194195#[error("Timeline focus is not pinned events.")]
196TimelineFocusNotPinnedEvents,
197198#[error("Could not load pinned events.")]
199TimelineReloadFailed,
200}