2020-08-05 22:08:55 +05:30
|
|
|
/*
|
|
|
|
Copyright 2020 Bruno Windels <bruno@windels.cloud>
|
2020-09-28 18:58:51 +05:30
|
|
|
Copyright 2020 The Matrix.org Foundation C.I.C.
|
2020-08-05 22:08:55 +05:30
|
|
|
|
|
|
|
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.
|
|
|
|
*/
|
|
|
|
|
2021-08-10 07:54:09 +05:30
|
|
|
import { IDBRequestError } from "./error";
|
2021-08-10 02:14:07 +05:30
|
|
|
import { StorageError } from "../common";
|
2021-09-17 21:53:31 +05:30
|
|
|
import { AbortError } from "../../../utils/error.js";
|
2019-06-27 01:30:50 +05:30
|
|
|
|
2020-09-28 18:21:41 +05:30
|
|
|
let needsSyncPromise = false;
|
|
|
|
|
2021-08-10 02:26:20 +05:30
|
|
|
export const DONE = { done: true }
|
|
|
|
export const NOT_DONE = { done: false }
|
|
|
|
|
2020-09-28 18:21:41 +05:30
|
|
|
/* should be called on legacy platforms to see
|
|
|
|
if transactions close before draining the microtask queue (IE11 on Windows 7).
|
|
|
|
If this is the case, promises need to be resolved
|
|
|
|
synchronously from the idb request handler to prevent the transaction from closing prematurely.
|
|
|
|
*/
|
2021-08-10 02:26:20 +05:30
|
|
|
export async function checkNeedsSyncPromise(): Promise<boolean> {
|
2020-09-28 18:21:41 +05:30
|
|
|
// important to have it turned off while doing the test,
|
|
|
|
// otherwise reqAsPromise would not fail
|
|
|
|
needsSyncPromise = false;
|
|
|
|
const NAME = "test-idb-needs-sync-promise";
|
|
|
|
const db = await openDatabase(NAME, db => {
|
|
|
|
db.createObjectStore("test", {keyPath: "key"});
|
|
|
|
}, 1);
|
|
|
|
const txn = db.transaction("test", "readonly");
|
|
|
|
try {
|
|
|
|
await reqAsPromise(txn.objectStore("test").get(1));
|
|
|
|
await reqAsPromise(txn.objectStore("test").get(2));
|
|
|
|
} catch (err) {
|
|
|
|
// err.name would be either TransactionInactiveError or InvalidStateError,
|
|
|
|
// but let's not exclude any other failure modes
|
|
|
|
needsSyncPromise = true;
|
|
|
|
}
|
|
|
|
// we could delete the store here,
|
|
|
|
// but let's not create it on every page load on legacy platforms,
|
|
|
|
// and just keep it around
|
|
|
|
return needsSyncPromise;
|
|
|
|
}
|
|
|
|
|
2020-10-26 15:04:35 +05:30
|
|
|
// storage keys are defined to be unsigned 32bit numbers in KeyLimits, which is assumed by idb
|
2021-08-10 02:26:20 +05:30
|
|
|
export function encodeUint32(n: number): string {
|
2019-07-01 13:30:29 +05:30
|
|
|
const hex = n.toString(16);
|
|
|
|
return "0".repeat(8 - hex.length) + hex;
|
|
|
|
}
|
|
|
|
|
2021-02-12 17:34:05 +05:30
|
|
|
// used for logs where timestamp is part of key, which is larger than 32 bit
|
2021-08-10 02:26:20 +05:30
|
|
|
export function encodeUint64(n: number): string {
|
2021-02-12 17:34:05 +05:30
|
|
|
const hex = n.toString(16);
|
|
|
|
return "0".repeat(16 - hex.length) + hex;
|
|
|
|
}
|
|
|
|
|
2021-08-10 02:26:20 +05:30
|
|
|
export function decodeUint32(str: string): number {
|
2019-07-01 13:30:29 +05:30
|
|
|
return parseInt(str, 16);
|
|
|
|
}
|
|
|
|
|
2021-08-10 02:26:20 +05:30
|
|
|
type CreateObjectStore = (db : IDBDatabase, txn: IDBTransaction | null, oldVersion: number, version: number) => any
|
|
|
|
|
|
|
|
export function openDatabase(name: string, createObjectStore: CreateObjectStore, version: number, idbFactory: IDBFactory = window.indexedDB): Promise<IDBDatabase> {
|
2021-06-02 16:01:13 +05:30
|
|
|
const req = idbFactory.open(name, version);
|
2021-08-31 12:09:12 +05:30
|
|
|
req.onupgradeneeded = async (ev : IDBVersionChangeEvent) => {
|
2021-08-10 02:26:20 +05:30
|
|
|
const req = ev.target as IDBRequest<IDBDatabase>;
|
|
|
|
const db = req.result;
|
2021-08-31 12:13:39 +05:30
|
|
|
const txn = req.transaction!;
|
2019-02-07 03:36:56 +05:30
|
|
|
const oldVersion = ev.oldVersion;
|
2021-08-27 22:37:27 +05:30
|
|
|
try {
|
|
|
|
await createObjectStore(db, txn, oldVersion, version);
|
|
|
|
} catch (err) {
|
2021-08-30 18:22:04 +05:30
|
|
|
// try aborting on error, if that hasn't been done already
|
|
|
|
try {
|
|
|
|
txn.abort();
|
|
|
|
} catch (err) {}
|
2021-08-27 22:37:27 +05:30
|
|
|
}
|
2019-02-07 03:36:56 +05:30
|
|
|
};
|
|
|
|
return reqAsPromise(req);
|
2019-01-09 15:36:09 +05:30
|
|
|
}
|
|
|
|
|
2021-08-10 02:26:20 +05:30
|
|
|
export function reqAsPromise<T>(req: IDBRequest<T>): Promise<T> {
|
2019-01-09 15:36:09 +05:30
|
|
|
return new Promise((resolve, reject) => {
|
2020-09-25 20:23:19 +05:30
|
|
|
req.addEventListener("success", event => {
|
2021-08-10 02:26:20 +05:30
|
|
|
resolve((event.target as IDBRequest<T>).result);
|
|
|
|
// @ts-ignore
|
2020-09-28 18:21:41 +05:30
|
|
|
needsSyncPromise && Promise._flush && Promise._flush();
|
2020-09-25 20:23:19 +05:30
|
|
|
});
|
2021-05-05 18:06:43 +05:30
|
|
|
req.addEventListener("error", event => {
|
2021-09-22 00:32:39 +05:30
|
|
|
const error = new IDBRequestError(event);
|
2021-05-05 18:06:43 +05:30
|
|
|
reject(error);
|
2021-08-10 02:26:20 +05:30
|
|
|
// @ts-ignore
|
2020-09-28 18:21:41 +05:30
|
|
|
needsSyncPromise && Promise._flush && Promise._flush();
|
2020-09-25 20:23:19 +05:30
|
|
|
});
|
2019-01-09 15:36:09 +05:30
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-08-10 02:26:20 +05:30
|
|
|
export function txnAsPromise(txn): Promise<void> {
|
2021-05-05 19:32:39 +05:30
|
|
|
let error;
|
2019-01-09 15:36:09 +05:30
|
|
|
return new Promise((resolve, reject) => {
|
2020-09-25 20:23:19 +05:30
|
|
|
txn.addEventListener("complete", () => {
|
|
|
|
resolve();
|
2021-08-10 02:26:20 +05:30
|
|
|
// @ts-ignore
|
2020-09-28 18:21:41 +05:30
|
|
|
needsSyncPromise && Promise._flush && Promise._flush();
|
2020-09-25 20:23:19 +05:30
|
|
|
});
|
2021-05-05 19:32:39 +05:30
|
|
|
txn.addEventListener("abort", event => {
|
2021-09-17 21:53:31 +05:30
|
|
|
reject(new AbortError());
|
2021-08-10 02:26:20 +05:30
|
|
|
// @ts-ignore
|
2020-09-28 18:21:41 +05:30
|
|
|
needsSyncPromise && Promise._flush && Promise._flush();
|
2020-09-25 20:23:19 +05:30
|
|
|
});
|
2019-01-09 15:36:09 +05:30
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-08-20 23:04:06 +05:30
|
|
|
/**
|
|
|
|
* This type is rather complicated, but I hope that this is for a good reason. There
|
|
|
|
* are currently two uses for `iterateCursor`: iterating a regular cursor, and iterating
|
|
|
|
* a key-only cursor, which does not have values. These two uses are distinct, and iteration
|
|
|
|
* never stops or starts having a value halfway through.
|
|
|
|
*
|
|
|
|
* Each of the argument functions currently either assumes the value will be there, or that it won't. We thus can't
|
|
|
|
* just accept a function argument `(T | undefined) => { done: boolean }`, since this messes with
|
|
|
|
* the type safety in both cases: the former case will have to check for `undefined`, and
|
|
|
|
* the latter would have an argument that can be `T`, even though it never will.
|
|
|
|
*
|
|
|
|
* So the approach here is to let TypeScript infer and accept (via generics) the type of
|
|
|
|
* the cursor, which is either `IDBCursorWithValue` or `IDBCursor`. Since the type is accepted
|
|
|
|
* via generics, we can actually vary the types of the actual function arguments depending on it.
|
|
|
|
* Thus, when a value is available (an `IDBCursorWithValue` is given), we require a function `(T) => ...`, and when it is not, we require
|
|
|
|
* a function `(undefined) => ...`.
|
|
|
|
*/
|
2021-08-24 23:41:30 +05:30
|
|
|
type CursorIterator<T, I extends IDBCursor> = (value: I extends IDBCursorWithValue ? T : undefined, key: IDBValidKey, cursor: I) => { done: boolean, jumpTo?: IDBValidKey }
|
2021-08-10 02:26:20 +05:30
|
|
|
|
|
|
|
export function iterateCursor<T, I extends IDBCursor = IDBCursorWithValue>(cursorRequest: IDBRequest<I | null>, processValue: CursorIterator<T, I>): Promise<boolean> {
|
2019-02-07 03:36:56 +05:30
|
|
|
// TODO: does cursor already have a value here??
|
2021-08-10 02:26:20 +05:30
|
|
|
return new Promise<boolean>((resolve, reject) => {
|
2021-09-22 00:32:39 +05:30
|
|
|
cursorRequest.onerror = event => {
|
|
|
|
reject(new IDBRequestError(event));
|
2021-08-10 02:26:20 +05:30
|
|
|
// @ts-ignore
|
2020-09-28 18:21:41 +05:30
|
|
|
needsSyncPromise && Promise._flush && Promise._flush();
|
2019-01-09 15:36:09 +05:30
|
|
|
};
|
|
|
|
// collect results
|
2019-09-15 15:53:54 +05:30
|
|
|
cursorRequest.onsuccess = (event) => {
|
2021-08-10 02:26:20 +05:30
|
|
|
const cursor = (event.target as IDBRequest<I>).result;
|
2019-01-09 15:36:09 +05:30
|
|
|
if (!cursor) {
|
|
|
|
resolve(false);
|
2021-08-10 02:26:20 +05:30
|
|
|
// @ts-ignore
|
2020-09-28 18:21:41 +05:30
|
|
|
needsSyncPromise && Promise._flush && Promise._flush();
|
2019-01-09 15:36:09 +05:30
|
|
|
return; // end of results
|
|
|
|
}
|
2021-08-10 02:26:20 +05:30
|
|
|
const result = processValue(cursor["value"], cursor.key, cursor);
|
2020-09-28 18:21:41 +05:30
|
|
|
// TODO: don't use object for result and assume it's jumpTo when not === true/false or undefined
|
2020-08-19 21:55:38 +05:30
|
|
|
const done = result?.done;
|
|
|
|
const jumpTo = result?.jumpTo;
|
2020-06-27 02:56:24 +05:30
|
|
|
|
2019-05-11 16:40:31 +05:30
|
|
|
if (done) {
|
2019-02-07 03:36:56 +05:30
|
|
|
resolve(true);
|
2021-08-10 02:26:20 +05:30
|
|
|
// @ts-ignore
|
2020-09-28 18:21:41 +05:30
|
|
|
needsSyncPromise && Promise._flush && Promise._flush();
|
2019-06-27 01:32:00 +05:30
|
|
|
} else if(jumpTo) {
|
2019-05-11 16:40:31 +05:30
|
|
|
cursor.continue(jumpTo);
|
2019-06-27 01:32:00 +05:30
|
|
|
} else {
|
|
|
|
cursor.continue();
|
2019-01-09 15:36:09 +05:30
|
|
|
}
|
|
|
|
};
|
2019-06-27 01:30:50 +05:30
|
|
|
}).catch(err => {
|
|
|
|
throw new StorageError("iterateCursor failed", err);
|
2019-01-09 15:36:09 +05:30
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-08-10 02:26:20 +05:30
|
|
|
type Pred<T> = (value: T) => boolean
|
|
|
|
|
|
|
|
export async function fetchResults<T>(cursor: IDBRequest, isDone: Pred<T[]>): Promise<T[]> {
|
|
|
|
const results: T[] = [];
|
|
|
|
await iterateCursor<T>(cursor, (value) => {
|
2019-02-07 03:36:56 +05:30
|
|
|
results.push(value);
|
2019-05-11 16:40:31 +05:30
|
|
|
return {done: isDone(results)};
|
2019-01-09 15:36:09 +05:30
|
|
|
});
|
|
|
|
return results;
|
|
|
|
}
|
|
|
|
|
2021-08-10 02:26:20 +05:30
|
|
|
type ToCursor = (store: IDBObjectStore) => IDBRequest
|
|
|
|
|
|
|
|
export async function select<T>(db: IDBDatabase, storeName: string, toCursor: ToCursor, isDone: Pred<T[]>): Promise<T[]> {
|
2019-02-07 03:36:56 +05:30
|
|
|
if (!isDone) {
|
|
|
|
isDone = () => false;
|
|
|
|
}
|
|
|
|
if (!toCursor) {
|
|
|
|
toCursor = store => store.openCursor();
|
|
|
|
}
|
|
|
|
const tx = db.transaction([storeName], "readonly");
|
|
|
|
const store = tx.objectStore(storeName);
|
|
|
|
const cursor = toCursor(store);
|
|
|
|
return await fetchResults(cursor, isDone);
|
2019-01-09 15:36:09 +05:30
|
|
|
}
|
|
|
|
|
2021-08-10 02:26:20 +05:30
|
|
|
export async function findStoreValue<T>(db: IDBDatabase, storeName: string, toCursor: ToCursor, matchesValue: Pred<T>): Promise<T> {
|
2019-02-07 03:36:56 +05:30
|
|
|
if (!matchesValue) {
|
|
|
|
matchesValue = () => true;
|
|
|
|
}
|
|
|
|
if (!toCursor) {
|
|
|
|
toCursor = store => store.openCursor();
|
|
|
|
}
|
2019-01-09 15:36:09 +05:30
|
|
|
|
2019-02-07 03:36:56 +05:30
|
|
|
const tx = db.transaction([storeName], "readwrite");
|
|
|
|
const store = tx.objectStore(storeName);
|
|
|
|
const cursor = await reqAsPromise(toCursor(store));
|
|
|
|
let match;
|
2021-08-10 02:26:20 +05:30
|
|
|
const matched = await iterateCursor<T>(cursor, (value) => {
|
2019-02-07 03:36:56 +05:30
|
|
|
if (matchesValue(value)) {
|
|
|
|
match = value;
|
2021-08-10 07:43:32 +05:30
|
|
|
return DONE;
|
2019-02-07 03:36:56 +05:30
|
|
|
}
|
2021-08-10 07:43:32 +05:30
|
|
|
return NOT_DONE;
|
2019-02-07 03:36:56 +05:30
|
|
|
});
|
|
|
|
if (!matched) {
|
2019-06-27 01:30:50 +05:30
|
|
|
throw new StorageError("Value not found");
|
2019-02-07 03:36:56 +05:30
|
|
|
}
|
|
|
|
return match;
|
2019-05-11 16:40:31 +05:30
|
|
|
}
|