Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try to reopen database in case of unexpected closure #175

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v14.15.4
v20.16.0
13 changes: 0 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 2 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,8 @@
export function promisifyRequest<T = undefined>(
request: IDBRequest<T> | IDBTransaction,
): Promise<T> {
return new Promise<T>((resolve, reject) => {
// @ts-ignore - file size hacks
request.oncomplete = request.onsuccess = () => resolve(request.result);
// @ts-ignore - file size hacks
request.onabort = request.onerror = () => reject(request.error);
});
}
import { openDatabase, promisifyRequest } from './util';

export function createStore(dbName: string, storeName: string): UseStore {
const request = indexedDB.open(dbName);
request.onupgradeneeded = () => request.result.createObjectStore(storeName);
const dbp = promisifyRequest(request);

return (txMode, callback) =>
dbp.then((db) =>
openDatabase(dbName, storeName).then(db =>
callback(db.transaction(storeName, txMode).objectStore(storeName)),
);
}
Expand Down
70 changes: 70 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
export function promisifyRequest<T = undefined>(
request: IDBRequest<T> | IDBTransaction,
): Promise<T> {
return new Promise<T>((resolve, reject) => {
// @ts-ignore - file size hacks
request.oncomplete = request.onsuccess = () => resolve(request.result);
// @ts-ignore - file size hacks
request.onabort = request.onerror = () => reject(request.error);
});
}

const qq: {[dbName: string]: {promise?: Promise<IDBDatabase>; resolve: (db: IDBDatabase) => void;}} = {};

export async function openDatabase(
dbName: string, storeName: string, retry = true
): Promise<IDBDatabase> {
const q = qq[dbName] || {};
if (!q.promise) {
q.promise = new Promise(resolve => q.resolve = resolve);
qq[dbName] = q;
_openDatabase(dbName, storeName, q.resolve, retry);
}

const db = await q.promise;
delete q.promise;
return db;
}

// Meant to be used only in specific tests
export async function closeDatabase(dbName: string) {
if (!databases[dbName]) {
console.assert(true, `Could not find database "${dbName}" to close.`);
return;
}

databases[dbName].close();
}

const databases: {[dbName: string]: IDBDatabase} = {};

async function _openDatabase(
dbName: string, storeName: string, resolve: (db: IDBDatabase) => void, retry: boolean
): Promise<void> {
if (!databases[dbName]) {
const request = indexedDB.open(dbName);
request.onupgradeneeded = () => request.result.createObjectStore(storeName);
resolve(databases[dbName] = await promisifyRequest(request));
return;
}

if (!retry) {
resolve(databases[dbName]);
return;
}

try {
// Basic way to check if the db is open.
databases[dbName].transaction(storeName);
resolve(databases[dbName]);
} catch (err: any) {
// Log here on purpose.
console.debug(
`Could not open a transaction on "${dbName}" due to ${err.name} (${err.message}). `
+ 'Trying to reopen the connection...'
);
// Try re-open.
delete databases[dbName];
_openDatabase(dbName, storeName, resolve, retry);
}
}
38 changes: 36 additions & 2 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
get,
set,
del,
promisifyRequest,
clear,
createStore,
keys,
Expand All @@ -14,7 +13,8 @@ import {
update,
getMany,
delMany
} from '../src';
} from '../src/index';
import { closeDatabase, promisifyRequest } from '../src/util';
import { assert as typeAssert, IsExact } from 'conditional-type-checks';

const { assert } = chai;
Expand Down Expand Up @@ -551,5 +551,39 @@ mocha.setup('tdd');
});
});

suite('Resilience', () => {
setup(() => Promise.all([clear(), clear(customStore)]));

test('Database connection recovery', async () => {
await set('foo', 'bar');
// Close the database just before getting a value. This is supposed to simulate
// an unexpected/platform closure of the database for whatever reason. The problem
// is present on iOS Safari, but not on Android Chrome/WebView and it's difficult
// to trigger/reproduce since it appears random.
closeDatabase('keyval-store');

let value;
try {
value = await get('foo');
} catch (_) {
assert.fail('A get(...) must not throw if the db connection has been closed.');
}

assert.strictEqual(value, 'bar', 'Could not get value');

closeDatabase('keyval-store');
try {
await setMany([
['bar', 'baz'],
['baz', 'cat'],
]);
} catch (_) {
assert.fail('A setMany(...) must not throw if the db connection has been closed.');
}

assert.deepEqual(await keys(), ['bar', 'baz', 'foo'], 'Could not get all test keys');
});
});

mocha.run();
})();