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
59 changes: 50 additions & 9 deletions lib/storage/providers/IDBKeyValProvider/createStore.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,45 @@
import * as IDB from 'idb-keyval';
import type {UseStore} from 'idb-keyval';
import {logInfo} from '../../../Logger';
import {logAlert, logInfo} from '../../../Logger';

// This is a copy of the createStore function from idb-keyval, we need a custom implementation
// because we need to create the database manually in order to ensure that the store exists before we use it.
// If the store does not exist, idb-keyval will throw an error
// source: https://github.com/jakearchibald/idb-keyval/blob/9d19315b4a83897df1e0193dccdc29f78466a0f3/src/index.ts#L12
function createStore(dbName: string, storeName: string): UseStore {
let dbp: Promise<IDBDatabase> | undefined;
let closedBy: 'browser' | 'versionchange' | 'verifyStoreExists' | 'unknown' = 'unknown';

const attachHandlers = (db: IDBDatabase) => {
// It seems like Safari sometimes likes to just close the connection.
// It's supposed to fire this event when that happens. Let's hope it does!
// eslint-disable-next-line no-param-reassign
db.onclose = () => {
logInfo('IDB connection closed by browser', {dbName, storeName});
closedBy = 'browser';
dbp = undefined;
};

// When another tab triggers a DB version upgrade, we must close the connection
// to unblock the upgrade; otherwise the other tab's open request hangs indefinitely.
// https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/versionchange_event
// eslint-disable-next-line no-param-reassign
db.onversionchange = () => {
logInfo('IDB connection closing due to versionchange', {dbName, storeName});
closedBy = 'versionchange';
db.close();
dbp = undefined;
};
};

const getDB = () => {
if (dbp) return dbp;
const request = indexedDB.open(dbName);
request.onupgradeneeded = () => request.result.createObjectStore(storeName);
dbp = IDB.promisifyRequest(request);

dbp.then(
(db) => {
// It seems like Safari sometimes likes to just close the connection.
// It's supposed to fire this event when that happens. Let's hope it does!
// eslint-disable-next-line no-param-reassign
db.onclose = () => (dbp = undefined);
},
attachHandlers,
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {},
);
Expand All @@ -36,6 +55,7 @@ function createStore(dbName: string, storeName: string): UseStore {

logInfo(`Store ${storeName} does not exist in database ${dbName}.`);
const nextVersion = db.version + 1;
closedBy = 'verifyStoreExists';
db.close();

const request = indexedDB.open(dbName, nextVersion);
Expand All @@ -50,13 +70,34 @@ function createStore(dbName: string, storeName: string): UseStore {
};

dbp = IDB.promisifyRequest(request);
// eslint-disable-next-line @typescript-eslint/no-empty-function
dbp.then(attachHandlers, () => {});
return dbp;
};

return (txMode, callback) =>
getDB()
function executeTransaction<T>(txMode: IDBTransactionMode, callback: (store: IDBObjectStore) => T | PromiseLike<T>): Promise<T> {
return getDB()
.then(verifyStoreExists)
.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
}

return (txMode, callback) =>
executeTransaction(txMode, callback).catch((error) => {
if (error instanceof DOMException && error.name === 'InvalidStateError') {
logAlert('IDB InvalidStateError, retrying with fresh connection', {
dbName,
storeName,
txMode,
closedBy,
errorMessage: error.message,
});
dbp = undefined;
closedBy = 'unknown';
// Retry only once — this call is not wrapped, so if it also fails the error propagates normally.
return executeTransaction(txMode, callback);
}
throw error;
});
}

export default createStore;
Loading
Loading