matrix-sdk-indexeddb 0.16.1

Web's IndexedDB Storage backend for matrix-sdk
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
// 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

use std::ops::Deref;

use indexed_db_futures::transaction as inner;
use matrix_sdk_base::{
    event_cache::{Event as RawEvent, Gap as RawGap},
    linked_chunk::{ChunkContent, ChunkIdentifier, LinkedChunkId, RawChunk},
};
use ruma::{events::relation::RelationType, EventId, RoomId};
use serde::{de::DeserializeOwned, Serialize};

use crate::{
    error::AsyncErrorDeps,
    event_cache_store::{
        serializer::indexed_types::{
            IndexedChunk, IndexedChunkIdKey, IndexedEvent, IndexedEventIdKey,
            IndexedEventPositionKey, IndexedEventRelationKey, IndexedEventRoomKey, IndexedGapIdKey,
            IndexedLease, IndexedLeaseIdKey, IndexedNextChunkIdKey,
        },
        types::{Chunk, ChunkType, Event, Gap, Lease, Position},
    },
    serializer::{
        Indexed, IndexedKeyRange, IndexedPrefixKeyBounds, IndexedPrefixKeyComponentBounds,
        IndexedTypeSerializer,
    },
    transaction::{Transaction, TransactionError},
};

/// Represents an IndexedDB transaction, but provides a convenient interface for
/// performing operations relevant to the IndexedDB implementation of
/// [`EventCacheStore`](matrix_sdk_base::event_cache::store::EventCacheStore).
pub struct IndexeddbEventCacheStoreTransaction<'a> {
    transaction: Transaction<'a>,
}

impl<'a> Deref for IndexeddbEventCacheStoreTransaction<'a> {
    type Target = Transaction<'a>;

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

impl<'a> IndexeddbEventCacheStoreTransaction<'a> {
    pub fn new(transaction: inner::Transaction<'a>, serializer: &'a IndexedTypeSerializer) -> Self {
        Self { transaction: Transaction::new(transaction, serializer) }
    }

    /// Commit all operations tracked in this transaction to IndexedDB.
    pub async fn commit(self) -> Result<(), TransactionError> {
        self.transaction.commit().await
    }

    /// Query IndexedDB for all items matching the given linked chunk id by key
    /// `K`
    pub async fn get_items_by_linked_chunk_id<'b, T, K>(
        &self,
        linked_chunk_id: LinkedChunkId<'b>,
    ) -> Result<Vec<T>, TransactionError>
    where
        T: Indexed,
        T::IndexedType: DeserializeOwned,
        T::Error: AsyncErrorDeps,
        K: IndexedPrefixKeyBounds<T, LinkedChunkId<'b>> + Serialize,
    {
        self.get_items_by_key::<T, K>(IndexedKeyRange::all_with_prefix(
            linked_chunk_id,
            self.serializer().inner(),
        ))
        .await
    }

    /// Query IndexedDB for all items of type `T` by key `K` in the given room
    pub async fn get_items_in_room<'b, T, K>(
        &self,
        room_id: &'b RoomId,
    ) -> Result<Vec<T>, TransactionError>
    where
        T: Indexed,
        T::IndexedType: DeserializeOwned,
        T::Error: AsyncErrorDeps,
        K: IndexedPrefixKeyBounds<T, &'b RoomId> + Serialize,
    {
        self.get_items_by_key::<T, K>(IndexedKeyRange::all_with_prefix(
            room_id,
            self.serializer().inner(),
        ))
        .await
    }

    /// Query IndexedDB for the number of items matching the given linked chunk
    /// id.
    pub async fn get_items_count_by_linked_chunk_id<'b, T, K>(
        &self,
        linked_chunk_id: LinkedChunkId<'b>,
    ) -> Result<usize, TransactionError>
    where
        T: Indexed,
        T::IndexedType: DeserializeOwned,
        T::Error: AsyncErrorDeps,
        K: IndexedPrefixKeyBounds<T, LinkedChunkId<'b>> + Serialize,
    {
        self.get_items_count_by_key::<T, K>(IndexedKeyRange::all_with_prefix(
            linked_chunk_id,
            self.serializer().inner(),
        ))
        .await
    }

    /// Delete all items of type `T` by key `K` associated with the given linked
    /// chunk id from IndexedDB
    pub async fn delete_items_by_linked_chunk_id<'b, T, K>(
        &self,
        linked_chunk_id: LinkedChunkId<'b>,
    ) -> Result<(), TransactionError>
    where
        T: Indexed,
        K: IndexedPrefixKeyBounds<T, LinkedChunkId<'b>> + Serialize,
    {
        self.delete_items_by_key::<T, K>(IndexedKeyRange::all_with_prefix(
            linked_chunk_id,
            self.serializer().inner(),
        ))
        .await
    }

    /// Query IndexedDB for the lease that matches the given key `id`. If more
    /// than one lease is found, an error is returned.
    pub async fn get_lease_by_id(&self, id: &str) -> Result<Option<Lease>, TransactionError> {
        self.get_item_by_key_components::<Lease, IndexedLeaseIdKey>(id).await
    }

    /// Puts a lease into IndexedDB. If an event with the same key already
    /// exists, it will be overwritten. When the item is successfully put, the
    /// function returns the intermediary type [`IndexedLease`] in case
    /// inspection is needed.
    pub async fn put_lease(&self, lease: &Lease) -> Result<IndexedLease, TransactionError> {
        self.put_item(lease).await
    }

    /// Query IndexedDB for chunks that match the given chunk identifier and the
    /// given linked chunk id. If more than one item is found, an error is
    /// returned.
    pub async fn get_chunk_by_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        chunk_id: ChunkIdentifier,
    ) -> Result<Option<Chunk>, TransactionError> {
        self.get_item_by_key_components::<Chunk, IndexedChunkIdKey>((linked_chunk_id, chunk_id))
            .await
    }

    /// Query IndexedDB for chunks such that the next chunk matches the given
    /// chunk identifier and the given linked chunk id. If more than one item is
    /// found, an error is returned.
    pub async fn get_chunk_by_next_chunk_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        next_chunk_id: Option<ChunkIdentifier>,
    ) -> Result<Option<Chunk>, TransactionError> {
        self.get_item_by_key_components::<Chunk, IndexedNextChunkIdKey>((
            linked_chunk_id,
            next_chunk_id,
        ))
        .await
    }

    /// Query IndexedDB for all chunks matching the given linked chunk id
    pub async fn get_chunks_by_linked_chunk_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
    ) -> Result<Vec<Chunk>, TransactionError> {
        self.get_items_by_linked_chunk_id::<Chunk, IndexedChunkIdKey>(linked_chunk_id).await
    }

    /// Query IndexedDB for the number of chunks matching the given linked chunk
    /// id.
    pub async fn get_chunks_count_by_linked_chunk_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
    ) -> Result<usize, TransactionError> {
        self.get_items_count_by_linked_chunk_id::<Chunk, IndexedChunkIdKey>(linked_chunk_id).await
    }

    /// Query IndexedDB for the chunk with the maximum key matching the given
    /// linked chunk id.
    pub async fn get_max_chunk_by_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
    ) -> Result<Option<Chunk>, TransactionError> {
        let range = IndexedKeyRange::all_with_prefix::<Chunk, _>(
            linked_chunk_id,
            self.serializer().inner(),
        );
        self.get_max_item_by_key::<Chunk, IndexedChunkIdKey>(range).await
    }

    /// Query IndexedDB for given chunk matching the given linked chunk id and
    /// additionally query for events or gap, depending on chunk type, in
    /// order to construct the full chunk.
    pub async fn load_chunk_by_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        chunk_id: ChunkIdentifier,
    ) -> Result<Option<RawChunk<RawEvent, RawGap>>, TransactionError> {
        if let Some(chunk) = self.get_chunk_by_id(linked_chunk_id, chunk_id).await? {
            let content = match chunk.chunk_type {
                ChunkType::Event => {
                    let events = self
                        .get_events_by_chunk(
                            linked_chunk_id,
                            ChunkIdentifier::new(chunk.identifier),
                        )
                        .await?
                        .into_iter()
                        .map(RawEvent::from)
                        .collect();
                    ChunkContent::Items(events)
                }
                ChunkType::Gap => {
                    let gap = self
                        .get_gap_by_id(linked_chunk_id, ChunkIdentifier::new(chunk.identifier))
                        .await?
                        .ok_or(TransactionError::ItemNotFound)?;
                    ChunkContent::Gap(RawGap { prev_token: gap.prev_token })
                }
            };
            return Ok(Some(RawChunk {
                identifier: ChunkIdentifier::new(chunk.identifier),
                content,
                previous: chunk.previous.map(ChunkIdentifier::new),
                next: chunk.next.map(ChunkIdentifier::new),
            }));
        }
        Ok(None)
    }

    /// Add a chunk and ensure that the next and previous
    /// chunks are properly linked to the chunk being added. If a chunk with
    /// the same identifier already exists, the given chunk will be
    /// rejected. When the item is successfully added, the
    /// function returns the intermediary type [`IndexedChunk`] in case
    /// inspection is needed.
    pub async fn add_chunk(&self, chunk: &Chunk) -> Result<IndexedChunk, TransactionError> {
        let indexed = self.add_item(chunk).await?;
        if let Some(previous) = chunk.previous {
            let previous_identifier = ChunkIdentifier::new(previous);
            if let Some(mut previous_chunk) =
                self.get_chunk_by_id(chunk.linked_chunk_id.as_ref(), previous_identifier).await?
            {
                previous_chunk.next = Some(chunk.identifier);
                self.put_item(&previous_chunk).await?;
            }
        }
        if let Some(next) = chunk.next {
            let next_identifier = ChunkIdentifier::new(next);
            if let Some(mut next_chunk) =
                self.get_chunk_by_id(chunk.linked_chunk_id.as_ref(), next_identifier).await?
            {
                next_chunk.previous = Some(chunk.identifier);
                self.put_item(&next_chunk).await?;
            }
        }
        Ok(indexed)
    }

    /// Delete chunk that matches the given id and the given linked chunk id and
    /// ensure that the next and previous chunk are updated to link to one
    /// another. Additionally, ensure that events and gaps in the given
    /// chunk are also deleted.
    pub async fn delete_chunk_by_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        chunk_id: ChunkIdentifier,
    ) -> Result<(), TransactionError> {
        if let Some(chunk) = self.get_chunk_by_id(linked_chunk_id, chunk_id).await? {
            if let Some(previous) = chunk.previous {
                let previous_identifier = ChunkIdentifier::new(previous);
                if let Some(mut previous_chunk) =
                    self.get_chunk_by_id(linked_chunk_id, previous_identifier).await?
                {
                    previous_chunk.next = chunk.next;
                    self.put_item(&previous_chunk).await?;
                }
            }
            if let Some(next) = chunk.next {
                let next_identifier = ChunkIdentifier::new(next);
                if let Some(mut next_chunk) =
                    self.get_chunk_by_id(linked_chunk_id, next_identifier).await?
                {
                    next_chunk.previous = chunk.previous;
                    self.put_item(&next_chunk).await?;
                }
            }
            self.delete_item_by_key::<Chunk, IndexedChunkIdKey>((linked_chunk_id, chunk_id))
                .await?;
            match chunk.chunk_type {
                ChunkType::Event => {
                    self.delete_events_by_chunk(linked_chunk_id, chunk_id).await?;
                }
                ChunkType::Gap => {
                    self.delete_gap_by_id(linked_chunk_id, chunk_id).await?;
                }
            }
        }
        Ok(())
    }

    /// Delete all chunks associated with the given linked chunk id
    pub async fn delete_chunks_by_linked_chunk_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
    ) -> Result<(), TransactionError> {
        self.delete_items_by_linked_chunk_id::<Chunk, IndexedChunkIdKey>(linked_chunk_id).await
    }

    /// Query IndexedDB for events that match the given event id and the given
    /// linked chunk id. If more than one item is found, an error is returned.
    pub async fn get_event_by_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        event_id: &EventId,
    ) -> Result<Option<Event>, TransactionError> {
        let key = self.serializer().encode_key((linked_chunk_id, event_id));
        self.get_item_by_key::<Event, IndexedEventIdKey>(key).await
    }

    /// Query IndexedDB for events that match the given event id in the given
    /// room. If more than one item is found, an error is returned.
    pub async fn get_event_by_room(
        &self,
        room_id: &RoomId,
        event_id: &EventId,
    ) -> Result<Option<Event>, TransactionError> {
        let key = self.serializer().encode_key((room_id, event_id));
        self.get_item_by_key::<Event, IndexedEventRoomKey>(key).await
    }

    /// Query IndexedDB for events that are in the given
    /// room.
    pub async fn get_room_events(&self, room_id: &RoomId) -> Result<Vec<Event>, TransactionError> {
        self.get_items_in_room::<Event, IndexedEventRoomKey>(room_id).await
    }

    /// Query IndexedDB for events in the given chunk matching the given linked
    /// chunk id.
    pub async fn get_events_by_chunk(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        chunk_id: ChunkIdentifier,
    ) -> Result<Vec<Event>, TransactionError> {
        let range = IndexedKeyRange::all_with_prefix(
            (linked_chunk_id, chunk_id),
            self.serializer().inner(),
        );
        self.get_items_by_key::<Event, IndexedEventPositionKey>(range).await
    }

    /// Query IndexedDB for number of events in the given chunk matching the
    /// given linked chunk id.
    pub async fn get_events_count_by_chunk(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        chunk_id: ChunkIdentifier,
    ) -> Result<usize, TransactionError> {
        let range = IndexedKeyRange::all_with_prefix(
            (linked_chunk_id, chunk_id),
            self.serializer().inner(),
        );
        self.get_items_count_by_key::<Event, IndexedEventPositionKey>(range).await
    }

    /// Query IndexedDB for events that match the given relation range in the
    /// given room.
    pub async fn get_events_by_relation(
        &self,
        room_id: &RoomId,
        range: impl Into<IndexedKeyRange<(&EventId, &RelationType)>>,
    ) -> Result<Vec<Event>, TransactionError> {
        let range = range
            .into()
            .map(|(event_id, relation_type)| (room_id, event_id, relation_type))
            .encoded(self.serializer().inner());
        self.get_items_by_key::<Event, IndexedEventRelationKey>(range).await
    }

    /// Query IndexedDB for events that are related to the given event in the
    /// given room.
    pub async fn get_events_by_related_event(
        &self,
        room_id: &RoomId,
        related_event_id: &EventId,
    ) -> Result<Vec<Event>, TransactionError> {
        let range = IndexedKeyRange::all_with_prefix(
            (room_id, related_event_id),
            self.serializer().inner(),
        );
        self.get_items_by_key::<Event, IndexedEventRelationKey>(range).await
    }

    /// Puts an event in IndexedDB. If an event with the same key already
    /// exists, it will be overwritten. When the item is successfully put, the
    /// function returns the intermediary type [`IndexedEvent`] in case
    /// inspection is needed.
    pub async fn put_event(&self, event: &Event) -> Result<IndexedEvent, TransactionError> {
        if let Some(position) = event.position() {
            // For some reason, we can't simply replace an event with `put_item`
            // because we can get an error stating that the data violates a uniqueness
            // constraint on the `events_position` index. This is NOT expected, but
            // it is not clear if this improperly implemented in the browser or the
            // library we are using.
            //
            // As a workaround, if the event has a position, we delete it first and
            // then call `put_item`. This should be fine as it all happens within the
            // context of a single transaction.
            self.delete_event_by_position(event.linked_chunk_id(), position).await?;
        }
        self.put_item(event).await
    }

    /// Delete events in the given position range matching the given linked
    /// chunk id
    pub async fn delete_events_by_position(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        range: impl Into<IndexedKeyRange<Position>>,
    ) -> Result<(), TransactionError> {
        self.delete_items_by_key_components::<Event, IndexedEventPositionKey>(
            range.into().map(|position| (linked_chunk_id, position)),
        )
        .await
    }

    /// Delete event in the given position matching the given linked chunk id
    pub async fn delete_event_by_position(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        position: Position,
    ) -> Result<(), TransactionError> {
        self.delete_item_by_key::<Event, IndexedEventPositionKey>((linked_chunk_id, position)).await
    }

    /// Delete events in the given chunk matching the given linked chunk id
    pub async fn delete_events_by_chunk(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        chunk_id: ChunkIdentifier,
    ) -> Result<(), TransactionError> {
        let range = IndexedKeyRange::all_with_prefix(
            (linked_chunk_id, chunk_id),
            self.serializer().inner(),
        );
        self.delete_items_by_key::<Event, IndexedEventPositionKey>(range).await
    }

    /// Delete events matching the given linked chunk id starting from the given
    /// position until the end of the chunk
    pub async fn delete_events_by_chunk_from_index(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        position: Position,
    ) -> Result<(), TransactionError> {
        let lower = (linked_chunk_id, position);
        let upper = IndexedEventPositionKey::upper_key_components_with_prefix((
            linked_chunk_id,
            ChunkIdentifier::new(position.chunk_identifier),
        ));
        let range = IndexedKeyRange::Bound(lower, upper).map(|(_, position)| position);
        self.delete_events_by_position(linked_chunk_id, range).await
    }

    /// Delete all events matching the given linked chunk id
    pub async fn delete_events_by_linked_chunk_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
    ) -> Result<(), TransactionError> {
        self.delete_items_by_linked_chunk_id::<Event, IndexedEventIdKey>(linked_chunk_id).await
    }

    /// Query IndexedDB for the gap in the given chunk matching the given linked
    /// chunk id.
    pub async fn get_gap_by_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        chunk_id: ChunkIdentifier,
    ) -> Result<Option<Gap>, TransactionError> {
        self.get_item_by_key_components::<Gap, IndexedGapIdKey>((linked_chunk_id, chunk_id)).await
    }

    /// Delete gap that matches the given chunk identifier and the given linked
    /// chunk id
    pub async fn delete_gap_by_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
        chunk_id: ChunkIdentifier,
    ) -> Result<(), TransactionError> {
        self.delete_item_by_key::<Gap, IndexedGapIdKey>((linked_chunk_id, chunk_id)).await
    }

    /// Delete all gaps matching the given linked chunk id
    pub async fn delete_gaps_by_linked_chunk_id(
        &self,
        linked_chunk_id: LinkedChunkId<'_>,
    ) -> Result<(), TransactionError> {
        self.delete_items_by_linked_chunk_id::<Gap, IndexedGapIdKey>(linked_chunk_id).await
    }
}