matrix_sdk_indexeddb/crypto_store/migrations/
v10_to_v11.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//! Migration code that moves from `backup_keys.backup_key_v1` to
16//! `backup_keys.backup_version_v1`, switching to a new serialization format.
17
18use indexed_db_futures::{
19    error::OpenDbError, query_source::QuerySource, transaction::TransactionMode, Build,
20};
21use wasm_bindgen::JsValue;
22
23use crate::{
24    crypto_store::{
25        keys,
26        migrations::{do_schema_upgrade, old_keys, MigrationDb},
27    },
28    serializer::SafeEncodeSerializer,
29};
30
31/// Migrate data from `backup_keys.backup_key_v1` to
32/// `backup_keys.backup_version_v1`.
33pub(crate) async fn data_migrate(
34    name: &str,
35    serializer: &SafeEncodeSerializer,
36) -> crate::crypto_store::Result<()> {
37    let db = MigrationDb::new(name, 11).await?;
38    let txn = db.transaction(keys::BACKUP_KEYS).with_mode(TransactionMode::Readwrite).build()?;
39    let store = txn.object_store(keys::BACKUP_KEYS)?;
40
41    let bv = store.get(&JsValue::from_str(old_keys::BACKUP_KEY_V1)).await?;
42
43    let Some(bv) = bv else {
44        return Ok(());
45    };
46
47    // backup_key_v1 was only ever serialized with the legacy format. Also, it's a
48    // string, so if we use `deserialize_value` on it, it will be incorrectly
49    // handled as a new-format object.
50    let bv: String = serializer.deserialize_legacy_value(bv)?;
51
52    // Re-serialize as new format, then store in the new field.
53    let serialized = serializer.serialize_value(&bv)?;
54    store.put(&serialized).with_key(JsValue::from_str(keys::BACKUP_VERSION_V1)).await?;
55    store.delete(&JsValue::from_str(old_keys::BACKUP_KEY_V1)).await?;
56    txn.commit().await?;
57    Ok(())
58}
59
60/// Perform the schema upgrade v10 to v11, just bumping the schema version.
61pub(crate) async fn schema_bump(name: &str) -> crate::crypto_store::Result<(), OpenDbError> {
62    // Just bump the version number to 11 to demonstrate that we have run the data
63    // changes from data_migrate.
64    do_schema_upgrade(name, 11, |_, _| Ok(())).await
65}