Skip to content
Open
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
4 changes: 4 additions & 0 deletions packages/connect-multichain/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- Recover `StoreAdapterWeb` when the browser or WKWebView force-closes IndexedDB. The adapter now invalidates the cached `IDBDatabase` on `close` / `versionchange` and retries `get` / `set` / `delete` once after `InvalidStateError` or `UnknownError`, so storage keeps working without a page reload. ([#351](https://github.com/MetaMask/connect-monorepo/pull/351))

## [1.2.0]

### Added
Expand Down
169 changes: 154 additions & 15 deletions packages/connect-multichain/src/store/adapters/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,46 @@
/* eslint-disable no-restricted-syntax -- Private class properties use established patterns */
/* eslint-disable @typescript-eslint/parameter-properties -- Constructor shorthand is intentional */
/* eslint-disable @typescript-eslint/prefer-promise-reject-errors -- Custom error objects */
/* eslint-disable @typescript-eslint/promise-function-async -- IndexedDB wrappers return IDBRequest promises */
import { StoreAdapter } from '../../domain';

type KvStores = 'sdk-kv-store' | 'key-value-pairs';

/**
* IndexedDB errors that mean the cached connection is dead and should be reopened.
* Typical browser/WebView strings: "The database connection is closing" and
* "Connection to Indexed Database server lost".
*
* @param error - Caught error from open, transaction, or a request.
* @returns True when a single reopen-and-retry is appropriate.
*/
function isRecoverableIndexedDbError(error: unknown): boolean {
if (!(error instanceof Error)) {
return false;
}

if (error.name === 'InvalidStateError' || error.name === 'UnknownError') {
return true;
}

return (
/database connection is closing/iu.test(error.message) ||
/Connection to Indexed Database server lost/iu.test(error.message)
);
}

export class StoreAdapterWeb extends StoreAdapter {
static readonly stores: KvStores[] = ['sdk-kv-store', 'key-value-pairs'];

static readonly DB_NAME = 'mmconnect';

readonly platform = 'web';

readonly dbPromise: Promise<IDBDatabase>;
private readonly dbName: string;

private cachedDbPromise: Promise<IDBDatabase> | null = null;

private cachedDb: IDBDatabase | null = null;

private get internal(): IDBFactory {
if (typeof window === 'undefined' || !window.indexedDB) {
Expand All @@ -30,12 +58,69 @@ export class StoreAdapterWeb extends StoreAdapter {
) {
super();

const dbName = `${StoreAdapterWeb.DB_NAME}${dbNameSuffix}`;
this.dbPromise = new Promise((resolve, reject) => {
this.dbName = `${StoreAdapterWeb.DB_NAME}${dbNameSuffix}`;
this.cachedDbPromise = this.openDatabase();
}

/**
* Current (or newly opened) IndexedDB connection. Kept as a getter so existing
* `dbPromise` access still works after a close / reopen.
*
* @returns Promise that resolves to an open `IDBDatabase`.
*/
get dbPromise(): Promise<IDBDatabase> {
return this.getDatabase();
}

async get(key: string): Promise<string | null> {
return this.withDatabase((db) => this.getFromDatabase(db, key));
}

async set(key: string, value: string): Promise<void> {
return this.withDatabase((db) => this.setInDatabase(db, key, value));
}

async delete(key: string): Promise<void> {
return this.withDatabase((db) => this.deleteFromDatabase(db, key));
}

private getDatabase(): Promise<IDBDatabase> {
this.cachedDbPromise ??= this.openDatabase();
return this.cachedDbPromise;
}

private invalidateConnection(db?: IDBDatabase): void {
if (db && this.cachedDb !== db) {
return;
}
this.cachedDb = null;
this.cachedDbPromise = null;
}

private attachConnectionHandlers(db: IDBDatabase): void {
db.onclose = () => {
this.invalidateConnection(db);
};
db.onversionchange = () => {
db.close();
this.invalidateConnection(db);
};
}

private openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
try {
const request = this.internal.open(dbName, 1);
request.onerror = () => reject(new Error('Failed to open IndexedDB.'));
request.onsuccess = () => resolve(request.result);
const request = this.internal.open(this.dbName, 1);
request.onerror = () => {
this.invalidateConnection();
reject(new Error('Failed to open IndexedDB.'));
};
request.onsuccess = () => {
const db = request.result;
this.cachedDb = db;
this.attachConnectionHandlers(db);
resolve(db);
};
request.onupgradeneeded = () => {
const db = request.result;
for (const name of StoreAdapterWeb.stores) {
Expand All @@ -45,55 +130,109 @@ export class StoreAdapterWeb extends StoreAdapter {
}
};
} catch (error) {
this.invalidateConnection();
reject(error);
}
});
}

async get(key: string): Promise<string | null> {
private async withDatabase<T>(
operation: (db: IDBDatabase) => Promise<T>,
): Promise<T> {
try {
const db = await this.getDatabase();
return await operation(db);
} catch (error) {
if (!isRecoverableIndexedDbError(error)) {
throw error;
}
this.invalidateConnection();
const db = await this.getDatabase();
return await operation(db);
}
}

/**
* Surface connection-loss errors so `withDatabase` can retry once.
* Every other request failure keeps the historical generic `Error`.
*
* @param request - Failed IndexedDB request.
* @param fallbackMessage - Message used when the failure is not recoverable.
* @param reject - Promise reject callback for this operation.
*/
private rejectStoreError(
request: IDBRequest,
fallbackMessage: string,
reject: (reason?: unknown) => void,
): void {
const { error } = request;
if (error && isRecoverableIndexedDbError(error)) {
reject(error);
return;
}
reject(new Error(fallbackMessage));
}

private getFromDatabase(
db: IDBDatabase,
key: string,
): Promise<string | null> {
const { storeName } = this;
const db = await this.dbPromise;
return new Promise((resolve, reject) => {
try {
const tx = db.transaction(storeName, 'readonly');
const store = tx.objectStore(storeName);
const request = store.get(key);
request.onerror = () =>
reject(new Error('Failed to get value from IndexedDB.'));
this.rejectStoreError(
request,
'Failed to get value from IndexedDB.',
reject,
);
request.onsuccess = () => resolve((request.result as string) ?? null);
} catch (error) {
reject(error);
}
});
}

async set(key: string, value: string): Promise<void> {
private setInDatabase(
db: IDBDatabase,
key: string,
value: string,
): Promise<void> {
const { storeName } = this;
const db = await this.dbPromise;
return new Promise((resolve, reject) => {
try {
const tx = db.transaction(storeName, 'readwrite');
const store = tx.objectStore(storeName);
const request = store.put(value, key);
request.onerror = () =>
reject(new Error('Failed to set value in IndexedDB.'));
this.rejectStoreError(
request,
'Failed to set value in IndexedDB.',
reject,
);
request.onsuccess = () => resolve();
} catch (error) {
reject(error);
}
});
}

async delete(key: string): Promise<void> {
private deleteFromDatabase(db: IDBDatabase, key: string): Promise<void> {
const { storeName } = this;
const db = await this.dbPromise;
return new Promise((resolve, reject) => {
try {
const tx = db.transaction(storeName, 'readwrite');
const store = tx.objectStore(storeName);
const request = store.delete(key);
request.onerror = () =>
reject(new Error('Failed to delete value from IndexedDB.'));
this.rejectStoreError(
request,
'Failed to delete value from IndexedDB.',
reject,
);
request.onsuccess = () => resolve();
} catch (error) {
reject(error);
Expand Down
Loading
Loading