matrix_sdk_base/store/send_queue.rs
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.
14
15//! All data types related to the send queue.
16
17use std::{collections::BTreeMap, fmt, ops::Deref};
18
19use as_variant::as_variant;
20#[cfg(feature = "unstable-msc4354")]
21use ruma::events::sticky::StickyDurationMs;
22use ruma::{
23 MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedEventId, OwnedTransactionId, OwnedUserId,
24 TransactionId, UInt,
25 events::{
26 AnyMessageLikeEventContent, MessageLikeEventContent as _, RawExt as _,
27 room::{MediaSource, message::RoomMessageEventContent},
28 },
29 serde::Raw,
30};
31use serde::{Deserialize, Serialize};
32
33use crate::media::MediaRequestParameters;
34
35/// A thin wrapper to serialize a `AnyMessageLikeEventContent`.
36#[derive(Clone, Serialize, Deserialize)]
37pub struct SerializableEventContent {
38 event: Raw<AnyMessageLikeEventContent>,
39 event_type: String,
40}
41
42#[cfg(not(tarpaulin_include))]
43impl fmt::Debug for SerializableEventContent {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 // Don't include the event in the debug display.
46 f.debug_struct("SerializedEventContent")
47 .field("event_type", &self.event_type)
48 .finish_non_exhaustive()
49 }
50}
51
52impl SerializableEventContent {
53 /// Create a [`SerializableEventContent`] from a raw
54 /// [`AnyMessageLikeEventContent`] along with its type.
55 pub fn from_raw(event: Raw<AnyMessageLikeEventContent>, event_type: String) -> Self {
56 Self { event_type, event }
57 }
58
59 /// Create a [`SerializableEventContent`] from an
60 /// [`AnyMessageLikeEventContent`].
61 pub fn new(event: &AnyMessageLikeEventContent) -> Result<Self, serde_json::Error> {
62 Ok(Self::from_raw(Raw::new(event)?, event.event_type().to_string()))
63 }
64
65 /// Convert a [`SerializableEventContent`] back into a
66 /// [`AnyMessageLikeEventContent`].
67 pub fn deserialize(&self) -> Result<AnyMessageLikeEventContent, serde_json::Error> {
68 self.event.deserialize_with_type(&self.event_type)
69 }
70
71 /// Returns the raw event content along with its type, borrowed variant.
72 ///
73 /// Useful for callers manipulating custom events.
74 pub fn raw(&self) -> (&Raw<AnyMessageLikeEventContent>, &str) {
75 (&self.event, &self.event_type)
76 }
77
78 /// Returns the raw event content along with its type, owned variant.
79 ///
80 /// Useful for callers manipulating custom events.
81 pub fn into_raw(self) -> (Raw<AnyMessageLikeEventContent>, String) {
82 (self.event, self.event_type)
83 }
84}
85
86/// The kind of a send queue request.
87#[derive(Clone, Debug, Serialize, Deserialize)]
88pub enum QueuedRequestKind {
89 /// An event to be sent via the send queue.
90 Event {
91 /// The content of the message-like event we'd like to send.
92 content: SerializableEventContent,
93
94 /// How long the event should be sticky for, if it is to be sent as a
95 /// sticky event.
96 #[cfg(feature = "unstable-msc4354")]
97 #[serde(default, skip_serializing_if = "Option::is_none")]
98 sticky_duration: Option<StickyDurationMs>,
99 },
100
101 /// Content to upload on the media server.
102 ///
103 /// The bytes must be stored in the media cache, and are identified by the
104 /// cache key.
105 MediaUpload {
106 /// Content type of the media to be uploaded.
107 ///
108 /// Stored as a `String` because `Mime` which we'd really want to use
109 /// here, is not serializable. Oh well.
110 content_type: String,
111
112 /// The cache key used to retrieve the media's bytes in the event cache
113 /// store.
114 cache_key: MediaRequestParameters,
115
116 /// An optional media source for a thumbnail already uploaded.
117 thumbnail_source: Option<MediaSource>,
118
119 /// To which media event transaction does this upload relate?
120 related_to: OwnedTransactionId,
121
122 /// Accumulated list of infos for previously uploaded files and
123 /// thumbnails if used during a gallery transaction. Otherwise empty.
124 #[cfg(feature = "unstable-msc4274")]
125 #[serde(default)]
126 accumulated: Vec<AccumulatedSentMediaInfo>,
127 },
128
129 /// A redaction of another event to send.
130 Redaction {
131 /// The ID of the event to redact.
132 redacts: OwnedEventId,
133 /// The reason for the event being redacted.
134 reason: Option<String>,
135 },
136}
137
138impl From<SerializableEventContent> for QueuedRequestKind {
139 fn from(content: SerializableEventContent) -> Self {
140 Self::Event {
141 content,
142 #[cfg(feature = "unstable-msc4354")]
143 sticky_duration: None,
144 }
145 }
146}
147
148/// A request to be sent with a send queue.
149#[derive(Clone)]
150pub struct QueuedRequest {
151 /// The kind of queued request we're going to send.
152 pub kind: QueuedRequestKind,
153
154 /// Unique transaction id for the queued request, acting as a key.
155 pub transaction_id: OwnedTransactionId,
156
157 /// Error returned when the request couldn't be sent and is stuck in the
158 /// unrecoverable state.
159 ///
160 /// `None` if the request is in the queue, waiting to be sent.
161 pub error: Option<QueueWedgeError>,
162
163 /// At which priority should this be handled?
164 ///
165 /// The bigger the value, the higher the priority at which this request
166 /// should be handled.
167 pub priority: usize,
168
169 /// The time that the request was originally attempted.
170 pub created_at: MilliSecondsSinceUnixEpoch,
171}
172
173impl QueuedRequest {
174 /// Returns `Some` if the queued request is about sending an event.
175 pub fn as_event(&self) -> Option<&SerializableEventContent> {
176 as_variant!(&self.kind, QueuedRequestKind::Event { content, .. } => content)
177 }
178
179 /// True if the request couldn't be sent because of an unrecoverable API
180 /// error. See [`Self::error`] for more details on the reason.
181 pub fn is_wedged(&self) -> bool {
182 self.error.is_some()
183 }
184}
185
186/// Represents a failed to send unrecoverable error of an event sent via the
187/// send queue.
188///
189/// It is a serializable representation of a client error, see `From`
190/// implementation for more details. These errors can not be automatically
191/// retried, but yet some manual action can be taken before retry sending. If
192/// not the only solution is to delete the local event.
193#[derive(Clone, Debug, Serialize, Deserialize, thiserror::Error)]
194pub enum QueueWedgeError {
195 /// This error occurs when there are some insecure devices in the room, and
196 /// the current encryption setting prohibits sharing with them.
197 #[error("There are insecure devices in the room")]
198 InsecureDevices {
199 /// The insecure devices as a Map of userID to deviceID.
200 user_device_map: BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
201 },
202
203 /// This error occurs when a previously verified user is not anymore, and
204 /// the current encryption setting prohibits sharing when it happens.
205 #[error("Some users that were previously verified are not anymore")]
206 IdentityViolations {
207 /// The users that are expected to be verified but are not.
208 users: Vec<OwnedUserId>,
209 },
210
211 /// It is required to set up cross-signing and properly verify the current
212 /// session before sending.
213 #[error("Own verification is required")]
214 CrossVerificationRequired,
215
216 /// The homeserver rejected the session's access token and the request can't
217 /// go out until the session has a working one again.
218 #[error("The access token was rejected")]
219 ExpiredAccessToken,
220
221 /// Media content was cached in the media store, but has disappeared before
222 /// we could upload it.
223 #[error("Media content disappeared")]
224 MissingMediaContent,
225
226 /// We tried to upload some media content with an unknown mime type.
227 #[error("Invalid mime type '{mime_type}' for media")]
228 InvalidMimeType {
229 /// The observed mime type that's expected to be invalid.
230 mime_type: String,
231 },
232
233 /// Other errors.
234 #[error("Other unrecoverable error: {msg}")]
235 GenericApiError {
236 /// Description of the error.
237 msg: String,
238 },
239}
240
241/// The specific user intent that characterizes a [`DependentQueuedRequest`].
242#[derive(Clone, Debug, Serialize, Deserialize)]
243pub enum DependentQueuedRequestKind {
244 /// The event should be edited.
245 EditEvent {
246 /// The new event for the content.
247 new_content: SerializableEventContent,
248 },
249
250 /// The event should be redacted/aborted/removed, with a reason applied to
251 /// the redaction if the event was sent by the time the abort was processed
252 /// and must be redacted server-side.
253 RedactEventWithReason {
254 /// Reason for the redaction, if any.
255 #[serde(default, skip_serializing_if = "Option::is_none")]
256 reason: Option<String>,
257 },
258
259 /// The event should be reacted to, with the given key.
260 ReactEvent {
261 /// Key used for the reaction.
262 key: String,
263 },
264
265 /// Upload a file or thumbnail depending on another file or thumbnail
266 /// upload.
267 #[serde(alias = "UploadFileWithThumbnail")]
268 UploadFileOrThumbnail {
269 /// Content type for the file or thumbnail.
270 content_type: String,
271
272 /// Media request necessary to retrieve the file or thumbnail itself.
273 cache_key: MediaRequestParameters,
274
275 /// To which media transaction id does this upload relate to?
276 related_to: OwnedTransactionId,
277
278 /// Whether the depended upon request was a thumbnail or a file upload.
279 #[serde(default = "default_parent_is_thumbnail_upload")]
280 parent_is_thumbnail_upload: bool,
281 },
282
283 /// Finish an upload by updating references to the media cache and sending
284 /// the final media event with the remote MXC URIs.
285 FinishUpload {
286 /// Local echo for the event (containing the local MXC URIs).
287 ///
288 /// `Box` the local echo so that it reduces the size of the whole enum.
289 local_echo: Box<RoomMessageEventContent>,
290
291 /// Transaction id for the file upload.
292 file_upload: OwnedTransactionId,
293
294 /// Information about the thumbnail, if present.
295 thumbnail_info: Option<FinishUploadThumbnailInfo>,
296
297 /// Additional top-level fields to merge into the final event content
298 /// before it is sent.
299 #[serde(default, skip_serializing_if = "Option::is_none")]
300 extra_content: Option<serde_json::Map<String, serde_json::Value>>,
301 },
302
303 /// Finish a gallery upload by updating references to the media cache and
304 /// sending the final gallery event with the remote MXC URIs.
305 #[cfg(feature = "unstable-msc4274")]
306 FinishGallery {
307 /// Local echo for the event (containing the local MXC URIs).
308 ///
309 /// `Box` the local echo so that it reduces the size of the whole enum.
310 local_echo: Box<RoomMessageEventContent>,
311
312 /// Metadata about the gallery items.
313 item_infos: Vec<FinishGalleryItemInfo>,
314
315 /// Additional top-level fields to merge into the final event content
316 /// before it is sent.
317 #[serde(default, skip_serializing_if = "Option::is_none")]
318 extra_content: Option<serde_json::Map<String, serde_json::Value>>,
319 },
320}
321
322/// If parent_is_thumbnail_upload is missing, we assume the request is for a
323/// file upload following a thumbnail upload. This was the only possible case
324/// before parent_is_thumbnail_upload was introduced.
325fn default_parent_is_thumbnail_upload() -> bool {
326 true
327}
328
329/// Detailed record about a thumbnail used when finishing a media upload.
330#[derive(Clone, Debug, Serialize, Deserialize)]
331pub struct FinishUploadThumbnailInfo {
332 /// Transaction id for the thumbnail upload.
333 pub txn: OwnedTransactionId,
334 /// Thumbnail's width.
335 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub width: Option<UInt>,
337 /// Thumbnail's height.
338 #[serde(default, skip_serializing_if = "Option::is_none")]
339 pub height: Option<UInt>,
340}
341
342/// Detailed record about a file and thumbnail. When finishing a gallery upload,
343/// one [`FinishGalleryItemInfo`] will be used for each media in the gallery.
344#[cfg(feature = "unstable-msc4274")]
345#[derive(Clone, Debug, Serialize, Deserialize)]
346pub struct FinishGalleryItemInfo {
347 /// Transaction id for the file upload.
348 pub file_upload: OwnedTransactionId,
349 /// Information about the thumbnail, if present.
350 pub thumbnail_info: Option<FinishUploadThumbnailInfo>,
351 /// Additional fields to merge into this item's content before sending.
352 #[serde(default, skip_serializing_if = "Option::is_none")]
353 pub extra_content: Option<serde_json::Map<String, serde_json::Value>>,
354}
355
356/// A transaction id identifying a [`DependentQueuedRequest`] rather than its
357/// parent [`QueuedRequest`].
358///
359/// This thin wrapper adds some safety to some APIs, making it possible to
360/// distinguish between the parent's `TransactionId` and the dependent event's
361/// own `TransactionId`.
362#[repr(transparent)]
363#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
364#[serde(transparent)]
365pub struct ChildTransactionId(OwnedTransactionId);
366
367impl ChildTransactionId {
368 /// Returns a new [`ChildTransactionId`].
369 #[allow(clippy::new_without_default)]
370 pub fn new() -> Self {
371 Self(TransactionId::new())
372 }
373}
374
375impl Deref for ChildTransactionId {
376 type Target = TransactionId;
377
378 fn deref(&self) -> &Self::Target {
379 &self.0
380 }
381}
382
383impl From<String> for ChildTransactionId {
384 fn from(val: String) -> Self {
385 Self(val.into())
386 }
387}
388
389impl From<ChildTransactionId> for OwnedTransactionId {
390 fn from(val: ChildTransactionId) -> Self {
391 val.0
392 }
393}
394
395impl From<OwnedTransactionId> for ChildTransactionId {
396 fn from(val: OwnedTransactionId) -> Self {
397 Self(val)
398 }
399}
400
401/// Information about a media (and its thumbnail) that have been sent to a
402/// homeserver.
403#[derive(Clone, Debug, Serialize, Deserialize)]
404pub struct SentMediaInfo {
405 /// File that was uploaded by this request.
406 ///
407 /// If the request related to a thumbnail upload, this contains the
408 /// thumbnail media source.
409 pub file: MediaSource,
410
411 /// Optional thumbnail previously uploaded, when uploading a file.
412 ///
413 /// When uploading a thumbnail, this is set to `None`.
414 pub thumbnail: Option<MediaSource>,
415
416 /// Accumulated list of infos for previously uploaded files and thumbnails
417 /// if used during a gallery transaction. Otherwise empty.
418 #[cfg(feature = "unstable-msc4274")]
419 #[serde(default)]
420 pub accumulated: Vec<AccumulatedSentMediaInfo>,
421}
422
423/// Accumulated information about a media (and its thumbnail) that have been
424/// sent to a homeserver.
425#[cfg(feature = "unstable-msc4274")]
426#[derive(Clone, Debug, Serialize, Deserialize)]
427pub struct AccumulatedSentMediaInfo {
428 /// File that was uploaded by this request.
429 ///
430 /// If the request related to a thumbnail upload, this contains the
431 /// thumbnail media source.
432 pub file: MediaSource,
433
434 /// Optional thumbnail previously uploaded, when uploading a file.
435 ///
436 /// When uploading a thumbnail, this is set to `None`.
437 pub thumbnail: Option<MediaSource>,
438}
439
440#[cfg(feature = "unstable-msc4274")]
441impl From<AccumulatedSentMediaInfo> for SentMediaInfo {
442 fn from(value: AccumulatedSentMediaInfo) -> Self {
443 Self { file: value.file, thumbnail: value.thumbnail, accumulated: vec![] }
444 }
445}
446
447/// A unique key (identifier) indicating that a transaction has been
448/// successfully sent to the server.
449///
450/// The owning child transactions can now be resolved.
451#[derive(Clone, Debug, Serialize, Deserialize)]
452pub enum SentRequestKey {
453 /// The parent transaction returned an event when it succeeded.
454 Event {
455 /// The event ID returned by the server.
456 event_id: OwnedEventId,
457
458 /// The sent event.
459 event: Raw<AnyMessageLikeEventContent>,
460
461 /// The type of the sent event.
462 event_type: String,
463 },
464
465 /// The parent transaction returned an uploaded resource URL.
466 Media(SentMediaInfo),
467
468 /// The parent transaction returned a redaction event when it succeeded.
469 Redaction {
470 /// The event ID returned by the server.
471 event_id: OwnedEventId,
472
473 /// The ID of the redacted event.
474 redacts: OwnedEventId,
475
476 /// The reason for the event being redacted.
477 reason: Option<String>,
478 },
479}
480
481impl SentRequestKey {
482 /// Converts the current parent key into an event id, if possible.
483 pub fn into_event_id(self) -> Option<OwnedEventId> {
484 match self {
485 Self::Event { event_id, .. } | Self::Redaction { event_id, .. } => Some(event_id),
486 _ => None,
487 }
488 }
489
490 /// Converts the current parent key into information about a sent media, if
491 /// possible.
492 pub fn into_media(self) -> Option<SentMediaInfo> {
493 as_variant!(self, Self::Media)
494 }
495}
496
497/// A request to be sent, depending on a [`QueuedRequest`] to be sent first.
498///
499/// Depending on whether the parent request has been sent or not, this will
500/// either update the local echo in the storage, or materialize an equivalent
501/// request implementing the user intent to the homeserver.
502#[derive(Clone, Debug, Serialize, Deserialize)]
503pub struct DependentQueuedRequest {
504 /// Unique identifier for this dependent queued request.
505 ///
506 /// Useful for deletion.
507 pub own_transaction_id: ChildTransactionId,
508
509 /// The kind of user intent.
510 pub kind: DependentQueuedRequestKind,
511
512 /// Transaction id for the parent's local echo / used in the server request.
513 ///
514 /// Note: this is the transaction id used for the depended-on request, i.e.
515 /// the one that was originally sent and that's being modified with this
516 /// dependent request.
517 pub parent_transaction_id: OwnedTransactionId,
518
519 /// If the parent request has been sent, the parent's request identifier
520 /// returned by the server once the local echo has been sent out.
521 pub parent_key: Option<SentRequestKey>,
522
523 /// The time that the request was originally attempted.
524 pub created_at: MilliSecondsSinceUnixEpoch,
525}
526
527impl DependentQueuedRequest {
528 /// Does the dependent request represent a new event that is _not_
529 /// aggregated, aka it is going to be its own item in a timeline?
530 pub fn is_own_event(&self) -> bool {
531 match self.kind {
532 DependentQueuedRequestKind::EditEvent { .. }
533 | DependentQueuedRequestKind::RedactEventWithReason { .. }
534 | DependentQueuedRequestKind::ReactEvent { .. }
535 | DependentQueuedRequestKind::UploadFileOrThumbnail { .. } => {
536 // These are all aggregated events, or non-visible items (file
537 // upload producing a new MXC ID).
538 false
539 }
540 DependentQueuedRequestKind::FinishUpload { .. } => {
541 // This one graduates into a new media event.
542 true
543 }
544 #[cfg(feature = "unstable-msc4274")]
545 DependentQueuedRequestKind::FinishGallery { .. } => {
546 // This one graduates into a new gallery event.
547 true
548 }
549 }
550 }
551}
552
553#[cfg(not(tarpaulin_include))]
554impl fmt::Debug for QueuedRequest {
555 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
556 // Hide the content from the debug log.
557 f.debug_struct("QueuedRequest")
558 .field("transaction_id", &self.transaction_id)
559 .field("is_wedged", &self.is_wedged())
560 .finish_non_exhaustive()
561 }
562}
563
564#[cfg(test)]
565mod tests {
566 use strass::assert_let;
567
568 use super::DependentQueuedRequestKind;
569
570 #[cfg(feature = "unstable-msc4274")]
571 #[test]
572 fn test_gallery_extra_content_storage_compatibility() {
573 let legacy = serde_json::json!({
574 "FinishGallery": {
575 "local_echo": { "msgtype": "dm.filament.gallery", "body": "gallery", "itemtypes": [] },
576 "item_infos": [{ "file_upload": "upload", "thumbnail_info": null }],
577 }
578 });
579 let kind: DependentQueuedRequestKind = serde_json::from_value(legacy.clone()).unwrap();
580 assert_let!(
581 DependentQueuedRequestKind::FinishGallery { item_infos, extra_content, .. } = &kind
582 );
583 assert!(extra_content.is_none());
584 assert!(item_infos[0].extra_content.is_none());
585 assert_eq!(serde_json::to_value(&kind).unwrap(), legacy);
586
587 let mut with_extra = legacy;
588 with_extra["FinishGallery"]["extra_content"] =
589 serde_json::json!({ "com.example.gallery": true });
590 with_extra["FinishGallery"]["item_infos"][0]["extra_content"] =
591 serde_json::json!({ "org.matrix.msc2448.is_spoiler": true });
592 let kind: DependentQueuedRequestKind = serde_json::from_value(with_extra.clone()).unwrap();
593 assert_eq!(serde_json::to_value(kind).unwrap(), with_extra);
594 }
595
596 #[test]
597 fn test_redact_event_with_reason_round_trip() {
598 for reason in [None, Some("spam".to_owned())] {
599 let kind = DependentQueuedRequestKind::RedactEventWithReason { reason: reason.clone() };
600 let serialized = serde_json::to_string(&kind).unwrap();
601 let deserialized: DependentQueuedRequestKind =
602 serde_json::from_str(&serialized).unwrap();
603 assert_let!(
604 DependentQueuedRequestKind::RedactEventWithReason { reason: deserialized } =
605 deserialized
606 );
607 assert_eq!(deserialized, reason);
608 }
609 }
610}