Skip to main content

matrix_sdk_indexeddb/event_cache_store/
types.rs

1// Copyright 2025 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
15use std::time::Duration;
16
17use matrix_sdk_base::{
18    cross_process_lock::CrossProcessLockGeneration,
19    deserialized_responses::TimelineEvent,
20    event_cache::{store::extract_event_relation, thread::ThreadInfo},
21    linked_chunk::{ChunkIdentifier, LinkedChunkId, OwnedLinkedChunkId},
22};
23use ruma::{EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId};
24use serde::{Deserialize, Serialize};
25
26/// Representation of a time-based lock on the entire
27/// [`IndexeddbEventCacheStore`](crate::event_cache_store::IndexeddbEventCacheStore)
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct Lease {
30    pub key: String,
31    pub holder: String,
32    pub expiration: Duration,
33    pub generation: CrossProcessLockGeneration,
34}
35
36/// Representation of a [`Chunk`](matrix_sdk_base::linked_chunk::Chunk) which
37/// can be stored in IndexedDB.
38#[derive(Debug, Serialize, Deserialize)]
39pub struct Chunk {
40    /// The linked chunk id in which the chunk exists.
41    pub linked_chunk_id: OwnedLinkedChunkId,
42    /// The identifier of the chunk - i.e.,
43    /// [`ChunkIdentifier`](matrix_sdk_base::linked_chunk::ChunkIdentifier).
44    pub identifier: u64,
45    /// The previous chunk in the list.
46    pub previous: Option<u64>,
47    /// The next chunk in the list.
48    pub next: Option<u64>,
49    /// The type of the chunk.
50    pub chunk_type: ChunkType,
51}
52
53/// The type of a [`Chunk`](Chunk)
54#[derive(Debug, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56pub enum ChunkType {
57    /// A chunk that holds events.
58    Event,
59    /// A chunk that represents a gap.
60    Gap,
61}
62
63/// An inclusive representation of an
64/// [`Event`](matrix_sdk_base::event_cache::Event) which can be stored in
65/// IndexedDB.
66///
67/// This is useful when (de)serializing an event which may either be in-band or
68/// out-of-band.
69#[derive(Debug, Serialize, Deserialize)]
70#[serde(untagged)]
71pub enum Event {
72    /// An in-band event, i.e., an event which is part of a chunk.
73    InBand(InBandEvent),
74    /// An out-of-band event, i.e., an event which is not part of a chunk.
75    OutOfBand(OutOfBandEvent),
76}
77
78impl From<Event> for TimelineEvent {
79    fn from(value: Event) -> Self {
80        match value {
81            Event::InBand(e) => e.content,
82            Event::OutOfBand(e) => e.content,
83        }
84    }
85}
86
87impl Event {
88    /// The [`LinkedChunkId`] in which the underlying event exists.
89    pub fn linked_chunk_id(&self) -> LinkedChunkId<'_> {
90        match self {
91            Event::InBand(e) => e.linked_chunk_id.as_ref(),
92            Event::OutOfBand(e) => e.linked_chunk_id.as_ref(),
93        }
94    }
95
96    /// The [`RoomId`] of the room in which the underlying event exists.
97    pub fn room_id(&self) -> &RoomId {
98        match self {
99            Event::InBand(e) => e.room_id(),
100            Event::OutOfBand(e) => e.room_id(),
101        }
102    }
103
104    /// The [`EventId`] of the underlying event.
105    pub fn event_id(&self) -> Option<&EventId> {
106        match self {
107            Event::InBand(e) => e.event_id(),
108            Event::OutOfBand(e) => e.event_id(),
109        }
110    }
111
112    /// The [`Position`] of the underlying event, if it is in a chunk.
113    pub fn position(&self) -> Option<Position> {
114        match self {
115            Event::InBand(e) => Some(e.position),
116            Event::OutOfBand(_) => None,
117        }
118    }
119
120    /// The timestamp of the underlying event, if known.
121    pub fn timestamp(&self) -> Option<MilliSecondsSinceUnixEpoch> {
122        match self {
123            Event::InBand(e) => e.timestamp(),
124            Event::OutOfBand(e) => e.timestamp(),
125        }
126    }
127
128    /// The [`OwnedEventId`] and
129    /// [`RelationType`](ruma::events::relation::RelationType) of the underlying
130    /// event as a [`String`].
131    pub fn relation(&self) -> Option<(OwnedEventId, String)> {
132        match self {
133            Event::InBand(e) => e.relation(),
134            Event::OutOfBand(e) => e.relation(),
135        }
136    }
137
138    /// A reference to the underlying event.
139    pub fn content(&self) -> &TimelineEvent {
140        match self {
141            Event::InBand(e) => &e.content,
142            Event::OutOfBand(e) => &e.content,
143        }
144    }
145
146    /// Sets the content of the underlying [`GenericEvent`] and returns the
147    /// mutated [`Event`]
148    pub fn with_content(mut self, content: TimelineEvent) -> Self {
149        match self {
150            Event::InBand(ref mut i) => i.content = content,
151            Event::OutOfBand(ref mut o) => o.content = content,
152        }
153        self
154    }
155
156    /// Ensures that the underlying [`GenericEvent`] is an [`OutOfBandEvent`].
157    /// If it is not an [`OutOfBandEvent`], then it is converted into one.
158    pub fn into_out_of_band_event(self) -> Self {
159        match self {
160            Event::InBand(i) => Self::OutOfBand(i.into()),
161            o @ Event::OutOfBand(_) => o,
162        }
163    }
164}
165
166/// A generic representation of an
167/// [`Event`](matrix_sdk_base::event_cache::Event) which can be stored in
168/// IndexedDB.
169///
170/// This is useful when (de)serializing an event which is required to be either
171/// in-band or out-of-band.
172#[derive(Debug, Serialize, Deserialize)]
173pub struct GenericEvent<P> {
174    /// The linked chunk id in which the event exists.
175    pub linked_chunk_id: OwnedLinkedChunkId,
176    /// The full content of the event.
177    pub content: TimelineEvent,
178    /// The position of the event, if it is in a chunk.
179    pub position: P,
180}
181
182impl<P> GenericEvent<P> {
183    /// The [`RoomId`] of the room in which the event exists.
184    pub fn room_id(&self) -> &RoomId {
185        self.linked_chunk_id.room_id()
186    }
187
188    /// The [`EventId`] of the underlying event.
189    pub fn event_id(&self) -> Option<&EventId> {
190        self.content.event_id()
191    }
192
193    /// The event that the underlying event relates to, if any.
194    ///
195    /// Returns the related [`OwnedEventId`] and the
196    /// [`RelationType`](ruma::events::relation::RelationType) as a [`String`].
197    pub fn relation(&self) -> Option<(OwnedEventId, String)> {
198        extract_event_relation(self.content.raw())
199    }
200
201    /// The timestamp of the underlying event, if known.
202    pub fn timestamp(&self) -> Option<MilliSecondsSinceUnixEpoch> {
203        self.content.timestamp
204    }
205}
206
207/// A concrete instance of [`GenericEvent`] for in-band events, i.e., events
208/// which are part of a chunk and therefore have a position.
209pub type InBandEvent = GenericEvent<Position>;
210
211/// A concrete instance of [`GenericEvent`] for out-of-band events, i.e., events
212/// which are not part of a chunk and therefore have no position.
213pub type OutOfBandEvent = GenericEvent<()>;
214
215impl From<InBandEvent> for OutOfBandEvent {
216    fn from(value: InBandEvent) -> Self {
217        Self { linked_chunk_id: value.linked_chunk_id, content: value.content, position: () }
218    }
219}
220
221/// A representation of [`Position`](matrix_sdk_base::linked_chunk::Position)
222/// which can be stored in IndexedDB.
223#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize)]
224pub struct Position {
225    /// The identifier of the chunk.
226    pub chunk_identifier: u64,
227    /// The index of the event within the chunk.
228    pub index: usize,
229}
230
231impl From<Position> for matrix_sdk_base::linked_chunk::Position {
232    fn from(value: Position) -> Self {
233        Self::new(ChunkIdentifier::new(value.chunk_identifier), value.index)
234    }
235}
236
237impl From<matrix_sdk_base::linked_chunk::Position> for Position {
238    fn from(value: matrix_sdk_base::linked_chunk::Position) -> Self {
239        Self { chunk_identifier: value.chunk_identifier().index(), index: value.index() }
240    }
241}
242
243/// A representation of [`Gap`](matrix_sdk_base::linked_chunk::Gap) which can be
244/// stored in IndexedDB.
245#[derive(Debug, Serialize, Deserialize)]
246pub struct Gap {
247    /// The linked chunk id in which the gap exists.
248    pub linked_chunk_id: OwnedLinkedChunkId,
249    /// The identifier of the chunk containing this gap.
250    pub chunk_identifier: u64,
251    /// The token to use in the query, extracted from a previous "from" / "end"
252    /// field of a `/messages` response.
253    #[serde(alias = "prev_token")]
254    pub token: String,
255}
256
257/// A representation of a _thread_ for the thread list which can be stored in
258/// IndexedDB.
259#[derive(Debug, Serialize, Deserialize)]
260pub struct Thread {
261    /// The room of the thread.
262    pub room_id: OwnedRoomId,
263    /// The root of the thread.
264    pub thread_id: OwnedEventId,
265    /// Information about the thread.
266    pub info: ThreadInfo,
267}
268
269impl Thread {
270    /// Get the [`LinkedChunkId`] associated to this [`Thread`].
271    pub fn linked_chunk(&self) -> LinkedChunkId<'_> {
272        LinkedChunkId::Thread(&self.room_id, &self.thread_id)
273    }
274}