Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions crates/matrix-sdk-indexeddb/src/event_cache_store/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,26 @@ use thiserror::Error;
use wasm_bindgen::JsValue;
use web_sys::{DomException, IdbIndexParameters};

const CURRENT_DB_VERSION: Version = Version::V1;
/// The current version and keys used in the database.
pub mod current {
use super::{v1, Version};

pub const VERSION: Version = Version::V1;
pub use v1::keys;
}

/// Opens a connection to the IndexedDB database and takes care of upgrading it
/// if necessary.
#[allow(unused)]
pub async fn open_and_upgrade_db(name: &str) -> Result<IdbDatabase, DomException> {
let mut request = IdbDatabase::open_u32(name, CURRENT_DB_VERSION as u32)?;
let mut request = IdbDatabase::open_u32(name, current::VERSION as u32)?;
request.set_on_upgrade_needed(Some(|event: &IdbVersionChangeEvent| -> Result<(), JsValue> {
let mut version =
Version::try_from(event.old_version() as u32).map_err(DomException::from)?;
while version < CURRENT_DB_VERSION {
while version < current::VERSION {
version = match version.upgrade(event.db())? {
Some(next) => next,
None => CURRENT_DB_VERSION, /* No more upgrades to apply, jump forward! */
None => current::VERSION, /* No more upgrades to apply, jump forward! */
};
}
Ok(())
Expand Down Expand Up @@ -103,6 +109,7 @@ pub mod v1 {

pub mod keys {
pub const CORE: &str = "core";
pub const ROOMS: &str = "rooms";
pub const LINKED_CHUNKS: &str = "linked_chunks";
pub const LINKED_CHUNKS_KEY_PATH: &str = "id";
pub const LINKED_CHUNKS_NEXT: &str = "linked_chunks_next";
Expand All @@ -113,6 +120,8 @@ pub mod v1 {
pub const EVENTS_POSITION_KEY_PATH: &str = "position";
pub const EVENTS_RELATION: &str = "events_relation";
pub const EVENTS_RELATION_KEY_PATH: &str = "relation";
pub const EVENTS_RELATION_RELATED_EVENTS: &str = "events_relation_related_event";
pub const EVENTS_RELATION_RELATION_TYPES: &str = "events_relation_relation_type";
pub const GAPS: &str = "gaps";
pub const GAPS_KEY_PATH: &str = "id";
}
Expand Down
2 changes: 2 additions & 0 deletions crates/matrix-sdk-indexeddb/src/event_cache_store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License

#![allow(unused)]

mod migrations;
mod serializer;
mod types;
142 changes: 142 additions & 0 deletions crates/matrix-sdk-indexeddb/src/event_cache_store/serializer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,146 @@
// See the License for the specific language governing permissions and
// limitations under the License

use gloo_utils::format::JsValueSerdeExt;
use matrix_sdk_crypto::CryptoStoreError;
use ruma::RoomId;
use serde::{de::DeserializeOwned, Serialize};
use thiserror::Error;
use wasm_bindgen::JsValue;
use web_sys::IdbKeyRange;

use crate::{
event_cache_store::serializer::traits::{Indexed, IndexedKey, IndexedKeyBounds},
serializer::IndexeddbSerializer,
};

mod traits;
mod types;

#[derive(Debug, Error)]
pub enum IndexeddbEventCacheStoreSerializerError {
#[error("indexing: {0}")]
Indexing(Box<dyn std::error::Error>),
#[error("serialization: {0}")]
Serialization(#[from] serde_json::Error),
}

impl From<serde_wasm_bindgen::Error> for IndexeddbEventCacheStoreSerializerError {
fn from(e: serde_wasm_bindgen::Error) -> Self {
Self::Serialization(serde::de::Error::custom(e.to_string()))
}
}

/// A (de)serializer for an IndexedDB implementation of [`EventCacheStore`][1].
///
/// This is primarily a wrapper around [`IndexeddbSerializer`] with a
/// convenience functions for (de)serializing types specific to the
/// [`EventCacheStore`][1].
///
/// [1]: matrix_sdk_base::event_cache::store::EventCacheStore
pub struct IndexeddbEventCacheStoreSerializer {
inner: IndexeddbSerializer,
}

impl IndexeddbEventCacheStoreSerializer {
pub fn new(inner: IndexeddbSerializer) -> Self {
Self { inner }
}

/// Encodes an key for a [`Indexed`] type.
///
/// Note that the particular key which is encoded is defined by the type
/// `K`.
pub fn encode_key<T, K>(&self, room_id: &RoomId, components: &K::KeyComponents) -> K
where
T: Indexed,
K: IndexedKey<T>,
{
K::encode(room_id, components, &self.inner)
}

/// Encodes a key for a [`Indexed`] type as a [`JsValue`].
///
/// Note that the particular key which is encoded is defined by the type
/// `K`.
pub fn encode_key_as_value<T, K>(
&self,
room_id: &RoomId,
components: &K::KeyComponents,
) -> Result<JsValue, serde_wasm_bindgen::Error>
where
T: Indexed,
K: IndexedKey<T> + Serialize,
{
serde_wasm_bindgen::to_value(&self.encode_key::<T, K>(room_id, components))
}

/// Encodes the entire key range for an [`Indexed`] type.
///
/// Note that the particular key which is encoded is defined by the type
/// `K`.
pub fn encode_key_range<T, K>(
&self,
room_id: &RoomId,
) -> Result<IdbKeyRange, serde_wasm_bindgen::Error>
where
T: Indexed,
K: IndexedKeyBounds<T> + Serialize,
{
let lower = serde_wasm_bindgen::to_value(&K::encode_lower(room_id, &self.inner))?;
let upper = serde_wasm_bindgen::to_value(&K::encode_upper(room_id, &self.inner))?;
IdbKeyRange::bound(&lower, &upper).map_err(Into::into)
}

/// Encodes a bounded key range for an [`Indexed`] type from `lower` to
/// `upper`.
///
/// Note that the particular key which is encoded is defined by the type
/// `K`.
pub fn encode_key_range_from_to<T, K>(
&self,
room_id: &RoomId,
lower: &K::KeyComponents,
upper: &K::KeyComponents,
) -> Result<IdbKeyRange, serde_wasm_bindgen::Error>
where
T: Indexed,
K: IndexedKeyBounds<T> + Serialize,
{
let lower = serde_wasm_bindgen::to_value(&K::encode(room_id, lower, &self.inner))?;
let upper = serde_wasm_bindgen::to_value(&K::encode(room_id, upper, &self.inner))?;
IdbKeyRange::bound(&lower, &upper).map_err(Into::into)
}

/// Serializes an [`Indexed`] type into a [`JsValue`]
pub fn serialize<T>(
&self,
room_id: &RoomId,
t: &T,
) -> Result<JsValue, IndexeddbEventCacheStoreSerializerError>
where
T: Indexed,
T::IndexedType: Serialize,
T::Error: std::error::Error + 'static,
{
let indexed = t
.to_indexed(room_id, &self.inner)
.map_err(|e| IndexeddbEventCacheStoreSerializerError::Indexing(Box::new(e)))?;
serde_wasm_bindgen::to_value(&indexed).map_err(Into::into)
}

/// Deserializes an [`Indexed`] type from a [`JsValue`]
pub fn deserialize<T>(
&self,
value: JsValue,
) -> Result<T, IndexeddbEventCacheStoreSerializerError>
where
T: Indexed,
T::IndexedType: DeserializeOwned,
T::Error: std::error::Error + 'static,
{
let indexed: T::IndexedType = value.into_serde()?;
T::from_indexed(indexed, &self.inner)
.map_err(|e| IndexeddbEventCacheStoreSerializerError::Indexing(Box::new(e)))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// 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 ruma::RoomId;

use crate::serializer::IndexeddbSerializer;

/// A conversion trait for preparing high-level types into indexed types
/// which are better suited for storage in IndexedDB.
///
/// Note that the functions below take an [`IndexeddbSerializer`] as an
/// argument, which provides the necessary context for encryption and
/// decryption, in the case the high-level type must be encrypted before
/// storage.
pub trait Indexed: Sized {
/// The indexed type that is used for storage in IndexedDB.
type IndexedType;
/// The error type that is returned when conversion fails.
type Error;

/// Converts the high-level type into an indexed type.
fn to_indexed(
&self,
room_id: &RoomId,
serializer: &IndexeddbSerializer,
) -> Result<Self::IndexedType, Self::Error>;

/// Converts an indexed type into the high-level type.
fn from_indexed(
indexed: Self::IndexedType,
serializer: &IndexeddbSerializer,
) -> Result<Self, Self::Error>;
}

/// A trait for encoding types which will be used as keys in IndexedDB.
///
/// Each implementation represents a key on an [`Indexed`] type.
pub trait IndexedKey<T: Indexed> {
/// Any extra data used to construct the key.
type KeyComponents;

/// Encodes the key components into a type that can be used as a key in
/// IndexedDB.
///
/// Note that this function takes an [`IndexeddbSerializer`] as an
/// argument, which provides the necessary context for encryption and
/// decryption, in the case that certain components of the key must be
/// encrypted before storage.
fn encode(
room_id: &RoomId,
components: &Self::KeyComponents,
serializer: &IndexeddbSerializer,
) -> Self;
}

/// A trait for constructing the bounds of an [`IndexedKey`].
///
/// This is useful when constructing range queries in IndexedDB.
pub trait IndexedKeyBounds<T: Indexed>: IndexedKey<T> {
/// Encodes the lower bound of the key.
fn encode_lower(room_id: &RoomId, serializer: &IndexeddbSerializer) -> Self;

/// Encodes the upper bound of the key.
fn encode_upper(room_id: &RoomId, serializer: &IndexeddbSerializer) -> Self;
}
Loading
Loading