@xyo-network/archivist-indexeddb 2.96.2 → 2.97.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/Archivist.d.cts +3 -2
- package/dist/browser/Archivist.d.cts.map +1 -1
- package/dist/browser/Archivist.d.mts +3 -2
- package/dist/browser/Archivist.d.mts.map +1 -1
- package/dist/browser/Archivist.d.ts +3 -2
- package/dist/browser/Archivist.d.ts.map +1 -1
- package/dist/browser/index.cjs +2 -0
- package/dist/browser/index.cjs.map +1 -1
- package/dist/browser/index.js +2 -0
- package/dist/browser/index.js.map +1 -1
- package/dist/node/Archivist.d.cts +3 -2
- package/dist/node/Archivist.d.cts.map +1 -1
- package/dist/node/Archivist.d.mts +3 -2
- package/dist/node/Archivist.d.mts.map +1 -1
- package/dist/node/Archivist.d.ts +3 -2
- package/dist/node/Archivist.d.ts.map +1 -1
- package/dist/node/index.cjs +5 -0
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.js +5 -0
- package/dist/node/index.js.map +1 -1
- package/package.json +9 -9
- package/src/Archivist.ts +3 -2
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { Hash } from '@xylabs/hex';
|
|
2
2
|
import { AbstractArchivist } from '@xyo-network/archivist-abstract';
|
|
3
3
|
import { ArchivistModuleEventData } from '@xyo-network/archivist-model';
|
|
4
|
-
import { Payload, PayloadWithMeta } from '@xyo-network/payload-model';
|
|
4
|
+
import { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model';
|
|
5
5
|
import { IDBPDatabase } from 'idb';
|
|
6
6
|
import { IndexedDbArchivistParams } from './Params';
|
|
7
7
|
export interface PayloadStore {
|
|
8
8
|
[s: string]: Payload;
|
|
9
9
|
}
|
|
10
10
|
export declare class IndexedDbArchivist<TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams, TEventData extends ArchivistModuleEventData = ArchivistModuleEventData> extends AbstractArchivist<TParams, TEventData> {
|
|
11
|
-
static configSchemas:
|
|
11
|
+
static configSchemas: Schema[];
|
|
12
|
+
static defaultConfigSchema: Schema;
|
|
12
13
|
static readonly defaultDbName = "archivist";
|
|
13
14
|
static readonly defaultDbVersion = 1;
|
|
14
15
|
static readonly defaultStoreName = "payloads";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAA;
|
|
1
|
+
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAA;AAC7E,OAAO,EAAE,YAAY,EAAU,MAAM,KAAK,CAAA;AAG1C,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,WAAW,YAAY;IAC3B,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;CACrB;AAED,qBACa,kBAAkB,CAC7B,OAAO,SAAS,wBAAwB,GAAG,wBAAwB,EACnE,UAAU,SAAS,wBAAwB,GAAG,wBAAwB,CACtE,SAAQ,iBAAiB,CAAC,OAAO,EAAE,UAAU,CAAC;IAC9C,OAAgB,aAAa,EAAE,MAAM,EAAE,CAA2D;IAClG,OAAgB,mBAAmB,EAAE,MAAM,CAAiC;IAC5E,MAA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KAAK;CAWpB"}
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { Hash } from '@xylabs/hex';
|
|
2
2
|
import { AbstractArchivist } from '@xyo-network/archivist-abstract';
|
|
3
3
|
import { ArchivistModuleEventData } from '@xyo-network/archivist-model';
|
|
4
|
-
import { Payload, PayloadWithMeta } from '@xyo-network/payload-model';
|
|
4
|
+
import { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model';
|
|
5
5
|
import { IDBPDatabase } from 'idb';
|
|
6
6
|
import { IndexedDbArchivistParams } from './Params';
|
|
7
7
|
export interface PayloadStore {
|
|
8
8
|
[s: string]: Payload;
|
|
9
9
|
}
|
|
10
10
|
export declare class IndexedDbArchivist<TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams, TEventData extends ArchivistModuleEventData = ArchivistModuleEventData> extends AbstractArchivist<TParams, TEventData> {
|
|
11
|
-
static configSchemas:
|
|
11
|
+
static configSchemas: Schema[];
|
|
12
|
+
static defaultConfigSchema: Schema;
|
|
12
13
|
static readonly defaultDbName = "archivist";
|
|
13
14
|
static readonly defaultDbVersion = 1;
|
|
14
15
|
static readonly defaultStoreName = "payloads";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAA;
|
|
1
|
+
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO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AAI,OAAO,CAAC,IAAI,CAAC;cAI7B,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IA0BvE;;;;;;;OAOG;cACa,0BAA0B,CACxC,EAAE,EAAE,YAAY,CAAC,YAAY,CAAC,EAC9B,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,WAAW,GACf,OAAO,CAAC,CAAC,MAAM,EAAE,eAAe,CAAC,GAAG,SAAS,CAAC;cAgBxB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cAmCxD,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cA0C9D,YAAY;IAQrC;;;OAGG;YACW,gBAAgB;IAiD9B;;;;OAIG;YACW,KAAK;CAWpB"}
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { Hash } from '@xylabs/hex';
|
|
2
2
|
import { AbstractArchivist } from '@xyo-network/archivist-abstract';
|
|
3
3
|
import { ArchivistModuleEventData } from '@xyo-network/archivist-model';
|
|
4
|
-
import { Payload, PayloadWithMeta } from '@xyo-network/payload-model';
|
|
4
|
+
import { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model';
|
|
5
5
|
import { IDBPDatabase } from 'idb';
|
|
6
6
|
import { IndexedDbArchivistParams } from './Params';
|
|
7
7
|
export interface PayloadStore {
|
|
8
8
|
[s: string]: Payload;
|
|
9
9
|
}
|
|
10
10
|
export declare class IndexedDbArchivist<TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams, TEventData extends ArchivistModuleEventData = ArchivistModuleEventData> extends AbstractArchivist<TParams, TEventData> {
|
|
11
|
-
static configSchemas:
|
|
11
|
+
static configSchemas: Schema[];
|
|
12
|
+
static defaultConfigSchema: Schema;
|
|
12
13
|
static readonly defaultDbName = "archivist";
|
|
13
14
|
static readonly defaultDbVersion = 1;
|
|
14
15
|
static readonly defaultStoreName = "payloads";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAA;
|
|
1
|
+
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAA;AAC7E,OAAO,EAAE,YAAY,EAAU,MAAM,KAAK,CAAA;AAG1C,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,WAAW,YAAY;IAC3B,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;CACrB;AAED,qBACa,kBAAkB,CAC7B,OAAO,SAAS,wBAAwB,GAAG,wBAAwB,EACnE,UAAU,SAAS,wBAAwB,GAAG,wBAAwB,CACtE,SAAQ,iBAAiB,CAAC,OAAO,EAAE,UAAU,CAAC;IAC9C,OAAgB,aAAa,EAAE,MAAM,EAAE,CAA2D;IAClG,OAAgB,mBAAmB,EAAE,MAAM,CAAiC;IAC5E,MAAM,CAAC,QAAQ,CAAC,aAAa,eAAc;IAC3C,MAAM,CAAC,QAAQ,CAAC,gBAAgB,KAAI;IACpC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,cAAa;I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IndexedDbArchivist");
|
|
59
59
|
}
|
|
60
60
|
static configSchemas = [
|
|
61
|
+
...super.configSchemas,
|
|
61
62
|
IndexedDbArchivistConfigSchema
|
|
62
63
|
];
|
|
64
|
+
static defaultConfigSchema = IndexedDbArchivistConfigSchema;
|
|
63
65
|
static defaultDbName = "archivist";
|
|
64
66
|
static defaultDbVersion = 1;
|
|
65
67
|
static defaultStoreName = "payloads";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts","../../src/Archivist.ts","../../src/Schema.ts","../../src/Config.ts"],"sourcesContent":["export * from './Archivist'\nexport * from './Config'\nexport * from './Params'\nexport * from './Schema'\n","import { exists } from '@xylabs/exists'\nimport { Hash } from '@xylabs/hex'\nimport { AbstractArchivist } from '@xyo-network/archivist-abstract'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistDeleteQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistModuleEventData,\n buildStandardIndexName,\n IndexDescription,\n} from '@xyo-network/archivist-model'\nimport { creatableModule } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload, PayloadWithMeta } from '@xyo-network/payload-model'\nimport { IDBPDatabase, openDB } from 'idb'\n\nimport { IndexedDbArchivistConfigSchema } from './Config'\nimport { IndexedDbArchivistParams } from './Params'\n\nexport interface PayloadStore {\n [s: string]: Payload\n}\n\n@creatableModule()\nexport class IndexedDbArchivist<\n TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n> extends AbstractArchivist<TParams, TEventData> {\n static override configSchemas = [IndexedDbArchivistConfigSchema]\n static readonly defaultDbName = 'archivist'\n static readonly defaultDbVersion = 1\n static readonly defaultStoreName = 'payloads'\n private static readonly dataHashIndex: IndexDescription = { key: { $hash: 1 }, multiEntry: false, unique: false }\n private static readonly hashIndex: IndexDescription = { key: { _hash: 1 }, multiEntry: false, unique: true }\n private static readonly schemaIndex: IndexDescription = { key: { schema: 1 }, multiEntry: false, unique: false }\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly hashIndexName = buildStandardIndexName(IndexedDbArchivist.hashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly dataHashIndexName = buildStandardIndexName(IndexedDbArchivist.dataHashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly schemaIndexName = buildStandardIndexName(IndexedDbArchivist.schemaIndex)\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the module name (not guaranteed to be unique) and if module\n * name is not supplied, it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.name ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to 1.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n override get queries() {\n return [ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, ...super.queries]\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n /**\n * The indexes to create on the store\n */\n private get indexes() {\n return [IndexedDbArchivist.dataHashIndex, IndexedDbArchivist.hashIndex, IndexedDbArchivist.schemaIndex, ...(this.config?.storage?.indexes ?? [])]\n }\n\n protected override async allHandler(): Promise<PayloadWithMeta[]> {\n // Get all payloads from the store\n const payloads = await this.useDb((db) => db.getAll(this.storeName))\n // Remove any metadata before returning to the client\n return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)))\n }\n\n protected override async clearHandler(): Promise<void> {\n await this.useDb((db) => db.clear(this.storeName))\n }\n\n protected override async deleteHandler(hashes: Hash[]): Promise<Hash[]> {\n const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes))\n const hashesToDelete = pairs.flatMap<Hash>((pair) => [pair[0].$hash, pair[1]])\n // Remove any duplicates\n const distinctHashes = [...new Set(hashesToDelete)]\n return await this.useDb(async (db) => {\n // Only return hashes that were successfully deleted\n const found = await Promise.all(\n distinctHashes.map(async (hash) => {\n // Check if the hash exists\n const existing =\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.hashIndexName, hash)) ??\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.dataHashIndexName, hash))\n // If it does exist\n if (existing) {\n // Delete it\n await db.delete(this.storeName, existing)\n // Return the hash so it gets added to the list of deleted hashes\n return hash\n }\n }),\n )\n return found.filter(exists).filter((hash) => hashes.includes(hash))\n })\n }\n\n /**\n * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)\n * @param db The db instance to use\n * @param storeName The name of the store to use\n * @param indexName The index to use\n * @param key The key to get from the index\n * @returns The primary key and the payload, or undefined if not found\n */\n protected async getFromIndexWithPrimaryKey(\n db: IDBPDatabase<PayloadStore>,\n storeName: string,\n indexName: string,\n key: IDBValidKey,\n ): Promise<[number, PayloadWithMeta] | undefined> {\n const transaction = db.transaction(storeName, 'readonly')\n const store = transaction.objectStore(storeName)\n const index = store.index(indexName)\n const cursor = await index.openCursor(key)\n if (cursor) {\n const singleValue = cursor.value\n // NOTE: It's known to be a number because we are using IndexedDB supplied auto-incrementing keys\n if (typeof cursor.primaryKey !== 'number') {\n throw new TypeError('primaryKey must be a number')\n }\n\n return [cursor.primaryKey, singleValue]\n }\n }\n\n protected override async getHandler(hashes: string[]): Promise<PayloadWithMeta[]> {\n const payloads = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.hashIndexName, hash))),\n )\n const payloadsFromDataHashes = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.dataHashIndexName, hash))),\n )\n //filter out duplicates\n const found = new Set<string>()\n const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n return (\n // Merge what we found from the hash and data hash indexes\n [...payloadsFromHash, ...payloadsFromDataHash]\n // Sort in ascending order by primary key (for semi-predictable ordering in terms of insertion order)\n .sort((a, b) => a[0] - b[0])\n // Return just the payloads\n .map(([_key, payload]) => payload)\n )\n }\n\n protected override async insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]> {\n const pairs = await PayloadBuilder.hashPairs(payloads)\n\n const db = await this.getInitializedDb()\n try {\n // Only return the payloads that were successfully inserted\n const inserted = await Promise.all(\n pairs.map(async ([payload, _hash]) => {\n const existing = (await this.getHandler([_hash])).shift()\n if (existing) {\n return\n }\n // Perform each insert via a transaction to ensure it is atomic\n // with respect to checking for the pre-existence of the hash.\n // This is done to preserve iteration via insertion order.\n const tx = db.transaction(this.storeName, 'readwrite')\n try {\n // Get the object store\n const store = tx.objectStore(this.storeName)\n\n // Check if the hash already exists\n const existingTopHash = await store.index(IndexedDbArchivist.hashIndexName).get(_hash)\n // If it does not already exist\n if (!existingTopHash) {\n // Insert the payload\n await store.put({ ...payload, _hash })\n }\n\n // Return it so it gets added to the list of inserted payloads\n return payload\n } finally {\n // Close the transaction\n await tx.done\n }\n }),\n )\n return inserted.filter(exists)\n } finally {\n db.close()\n }\n }\n\n protected override async startHandler() {\n await super.startHandler()\n // NOTE: We could defer this creation to first access but we\n // want to fail fast here in case something is wrong\n await this.useDb(() => {})\n return true\n }\n\n /**\n * Returns that the desired DB/Store initialized to the correct version\n * @returns The initialized DB\n */\n private async getInitializedDb(): Promise<IDBPDatabase<PayloadStore>> {\n const { dbName, dbVersion, indexes, storeName, logger } = this\n const db = await openDB<PayloadStore>(dbName, dbVersion, {\n blocked(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event)\n },\n blocking(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event)\n },\n terminated() {\n logger.log('IndexedDbArchivist: Terminated')\n },\n upgrade(database, oldVersion, newVersion, transaction) {\n // NOTE: This is called whenever the DB is created/updated. We could simply ensure the desired end\n // state but, out of an abundance of caution, we will just delete (so we know where we are starting\n // from a known good point) and recreate the desired state. This prioritizes resilience over data\n // retention but we can revisit that tradeoff when it becomes limiting. Because distributed browser\n // state is extremely hard to debug, this seems like fair tradeoff for now.\n if (oldVersion !== newVersion) {\n logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`)\n // Delete any existing databases that are not the current version\n const objectStores = transaction.objectStoreNames\n for (const name of objectStores) {\n try {\n database.deleteObjectStore(name)\n } catch {\n logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`)\n }\n }\n }\n // Create the store\n const store = database.createObjectStore(storeName, {\n // If it isn't explicitly set, create a value by auto incrementing.\n autoIncrement: true,\n })\n // Name the store\n store.name = storeName\n // Create an index on the hash\n for (const { key, multiEntry, unique } of indexes) {\n const indexKeys = Object.keys(key)\n const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys\n const indexName = buildStandardIndexName({ key, unique })\n store.createIndex(indexName, keys, { multiEntry, unique })\n }\n },\n })\n return db\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async useDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T> {\n // Get the initialized DB\n const db = await this.getInitializedDb()\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n}\n","export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\nexport const IndexedDbArchivistSchema: IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\n","import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model'\n\nimport { IndexedDbArchivistSchema } from './Schema'\n\nexport type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\nexport const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\n\nexport type IndexedDbArchivistConfig = ArchivistConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbArchivistConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main archivist config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACAA,oBAAuB;AAEvB,gCAAkC;AAClC,6BAQO;AACP,0BAAgC;AAChC,6BAA+B;AAE/B,iBAAqC;;;ACd9B,IAAMA,2BAAqD;;;ACI3D,IAAMC,iCAAiE,GAAGC,wBAAAA;;;;;;;;;;;;;;AFoB1E,IAAMC,qBAAN,MAAMA,4BAGHC,4CAAAA;SAAAA;;;EACR,OAAgBC,gBAAgB;IAACC;;EACjC,OAAgBC,gBAAgB;EAChC,OAAgBC,mBAAmB;EACnC,OAAgBC,mBAAmB;EACnC,OAAwBC,gBAAkC;IAAEC,KAAK;MAAEC,OAAO;IAAE;IAAGC,YAAY;IAAOC,QAAQ;EAAM;EAChH,OAAwBC,YAA8B;IAAEJ,KAAK;MAAEK,OAAO;IAAE;IAAGH,YAAY;IAAOC,QAAQ;EAAK;EAC3G,OAAwBG,cAAgC;IAAEN,KAAK;MAAEO,QAAQ;IAAE;IAAGL,YAAY;IAAOC,QAAQ;EAAM;;EAE/G,OAAgBK,oBAAgBC,+CAAuBjB,oBAAmBY,SAAS;;EAEnF,OAAgBM,wBAAoBD,+CAAuBjB,oBAAmBO,aAAa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5G,GAAAA;AAC9B,gBAAM4G,OAAOF,UAAUG,WAAW,IAAIH,UAAU,CAAA,IAAKA;AACrD,gBAAMlD,gBAAY/C,+CAAuB;YAAET;YAAKG;UAAO,CAAA;AACvDuD,gBAAMoD,YAAYtD,WAAWoD,MAAM;YAAE1G;YAAYC;UAAO,CAAA;QAC1D;MACF;IACF,CAAA;AACA,WAAOwB;EACT;;;;;;EAOA,MAAcD,MAASqF,UAA0E;AAE/F,UAAMpF,KAAK,MAAM,KAAKkD,iBAAgB;AACtC,QAAI;AAEF,aAAO,MAAMkC,SAASpF,EAAAA;IACxB,UAAA;AAEEA,SAAG0D,MAAK;IACV;EACF;AACF;AAnRa7F,qBAAAA,aAAAA;MADZwH,qCAAAA;GACYxH,kBAAAA;","names":["IndexedDbArchivistSchema","IndexedDbArchivistConfigSchema","IndexedDbArchivistSchema","IndexedDbArchivist","AbstractArchivist","configSchemas","IndexedDbArchivistConfigSchema","defaultDbName","defaultDbVersion","defaultStoreName","dataHashIndex","key","$hash","multiEntry","unique","hashIndex","_hash","schemaIndex","schema","hashIndexName","buildStandardIndexName","dataHashIndexName","schemaIndexName","dbName","config","name","dbVersion","queries","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","storeName","indexes","storage","allHandler","payloads","useDb","db","getAll","Promise","all","map","payload","PayloadBuilder","build","clearHandler","clear","deleteHandler","hashes","pairs","hashPairs","getHandler","hashesToDelete","flatMap","pair","distinctHashes","Set","found","hash","existing","getKeyFromIndex","delete","filter","exists","includes","getFromIndexWithPrimaryKey","indexName","transaction","store","objectStore","index","cursor","openCursor","singleValue","value","primaryKey","TypeError","payloadsFromDataHashes","payloadsFromHash","_key","has","add","payloadsFromDataHash","sort","a","b","insertHandler","getInitializedDb","inserted","shift","tx","existingTopHash","get","put","done","close","startHandler","logger","openDB","blocked","currentVersion","blockedVersion","event","warn","blocking","terminated","log","upgrade","database","oldVersion","newVersion","objectStores","objectStoreNames","deleteObjectStore","createObjectStore","autoIncrement","indexKeys","Object","keys","length","createIndex","callback","creatableModule"]}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts","../../src/Archivist.ts","../../src/Schema.ts","../../src/Config.ts"],"sourcesContent":["export * from './Archivist'\nexport * from './Config'\nexport * from './Params'\nexport * from './Schema'\n","import { exists } from '@xylabs/exists'\nimport { Hash } from '@xylabs/hex'\nimport { AbstractArchivist } from '@xyo-network/archivist-abstract'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistDeleteQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistModuleEventData,\n buildStandardIndexName,\n IndexDescription,\n} from '@xyo-network/archivist-model'\nimport { creatableModule } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model'\nimport { IDBPDatabase, openDB } from 'idb'\n\nimport { IndexedDbArchivistConfigSchema } from './Config'\nimport { IndexedDbArchivistParams } from './Params'\n\nexport interface PayloadStore {\n [s: string]: Payload\n}\n\n@creatableModule()\nexport class IndexedDbArchivist<\n TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n> extends AbstractArchivist<TParams, TEventData> {\n static override configSchemas: Schema[] = [...super.configSchemas, IndexedDbArchivistConfigSchema]\n static override defaultConfigSchema: Schema = IndexedDbArchivistConfigSchema\n static readonly defaultDbName = 'archivist'\n static readonly defaultDbVersion = 1\n static readonly defaultStoreName = 'payloads'\n private static readonly dataHashIndex: IndexDescription = { key: { $hash: 1 }, multiEntry: false, unique: false }\n private static readonly hashIndex: IndexDescription = { key: { _hash: 1 }, multiEntry: false, unique: true }\n private static readonly schemaIndex: IndexDescription = { key: { schema: 1 }, multiEntry: false, unique: false }\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly hashIndexName = buildStandardIndexName(IndexedDbArchivist.hashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly dataHashIndexName = buildStandardIndexName(IndexedDbArchivist.dataHashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly schemaIndexName = buildStandardIndexName(IndexedDbArchivist.schemaIndex)\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the module name (not guaranteed to be unique) and if module\n * name is not supplied, it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.name ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to 1.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n override get queries() {\n return [ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, ...super.queries]\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n /**\n * The indexes to create on the store\n */\n private get indexes() {\n return [IndexedDbArchivist.dataHashIndex, IndexedDbArchivist.hashIndex, IndexedDbArchivist.schemaIndex, ...(this.config?.storage?.indexes ?? [])]\n }\n\n protected override async allHandler(): Promise<PayloadWithMeta[]> {\n // Get all payloads from the store\n const payloads = await this.useDb((db) => db.getAll(this.storeName))\n // Remove any metadata before returning to the client\n return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)))\n }\n\n protected override async clearHandler(): Promise<void> {\n await this.useDb((db) => db.clear(this.storeName))\n }\n\n protected override async deleteHandler(hashes: Hash[]): Promise<Hash[]> {\n const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes))\n const hashesToDelete = pairs.flatMap<Hash>((pair) => [pair[0].$hash, pair[1]])\n // Remove any duplicates\n const distinctHashes = [...new Set(hashesToDelete)]\n return await this.useDb(async (db) => {\n // Only return hashes that were successfully deleted\n const found = await Promise.all(\n distinctHashes.map(async (hash) => {\n // Check if the hash exists\n const existing =\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.hashIndexName, hash)) ??\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.dataHashIndexName, hash))\n // If it does exist\n if (existing) {\n // Delete it\n await db.delete(this.storeName, existing)\n // Return the hash so it gets added to the list of deleted hashes\n return hash\n }\n }),\n )\n return found.filter(exists).filter((hash) => hashes.includes(hash))\n })\n }\n\n /**\n * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)\n * @param db The db instance to use\n * @param storeName The name of the store to use\n * @param indexName The index to use\n * @param key The key to get from the index\n * @returns The primary key and the payload, or undefined if not found\n */\n protected async getFromIndexWithPrimaryKey(\n db: IDBPDatabase<PayloadStore>,\n storeName: string,\n indexName: string,\n key: IDBValidKey,\n ): Promise<[number, PayloadWithMeta] | undefined> {\n const transaction = db.transaction(storeName, 'readonly')\n const store = transaction.objectStore(storeName)\n const index = store.index(indexName)\n const cursor = await index.openCursor(key)\n if (cursor) {\n const singleValue = cursor.value\n // NOTE: It's known to be a number because we are using IndexedDB supplied auto-incrementing keys\n if (typeof cursor.primaryKey !== 'number') {\n throw new TypeError('primaryKey must be a number')\n }\n\n return [cursor.primaryKey, singleValue]\n }\n }\n\n protected override async getHandler(hashes: string[]): Promise<PayloadWithMeta[]> {\n const payloads = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.hashIndexName, hash))),\n )\n const payloadsFromDataHashes = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.dataHashIndexName, hash))),\n )\n //filter out duplicates\n const found = new Set<string>()\n const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n return (\n // Merge what we found from the hash and data hash indexes\n [...payloadsFromHash, ...payloadsFromDataHash]\n // Sort in ascending order by primary key (for semi-predictable ordering in terms of insertion order)\n .sort((a, b) => a[0] - b[0])\n // Return just the payloads\n .map(([_key, payload]) => payload)\n )\n }\n\n protected override async insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]> {\n const pairs = await PayloadBuilder.hashPairs(payloads)\n\n const db = await this.getInitializedDb()\n try {\n // Only return the payloads that were successfully inserted\n const inserted = await Promise.all(\n pairs.map(async ([payload, _hash]) => {\n const existing = (await this.getHandler([_hash])).shift()\n if (existing) {\n return\n }\n // Perform each insert via a transaction to ensure it is atomic\n // with respect to checking for the pre-existence of the hash.\n // This is done to preserve iteration via insertion order.\n const tx = db.transaction(this.storeName, 'readwrite')\n try {\n // Get the object store\n const store = tx.objectStore(this.storeName)\n\n // Check if the hash already exists\n const existingTopHash = await store.index(IndexedDbArchivist.hashIndexName).get(_hash)\n // If it does not already exist\n if (!existingTopHash) {\n // Insert the payload\n await store.put({ ...payload, _hash })\n }\n\n // Return it so it gets added to the list of inserted payloads\n return payload\n } finally {\n // Close the transaction\n await tx.done\n }\n }),\n )\n return inserted.filter(exists)\n } finally {\n db.close()\n }\n }\n\n protected override async startHandler() {\n await super.startHandler()\n // NOTE: We could defer this creation to first access but we\n // want to fail fast here in case something is wrong\n await this.useDb(() => {})\n return true\n }\n\n /**\n * Returns that the desired DB/Store initialized to the correct version\n * @returns The initialized DB\n */\n private async getInitializedDb(): Promise<IDBPDatabase<PayloadStore>> {\n const { dbName, dbVersion, indexes, storeName, logger } = this\n const db = await openDB<PayloadStore>(dbName, dbVersion, {\n blocked(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event)\n },\n blocking(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event)\n },\n terminated() {\n logger.log('IndexedDbArchivist: Terminated')\n },\n upgrade(database, oldVersion, newVersion, transaction) {\n // NOTE: This is called whenever the DB is created/updated. We could simply ensure the desired end\n // state but, out of an abundance of caution, we will just delete (so we know where we are starting\n // from a known good point) and recreate the desired state. This prioritizes resilience over data\n // retention but we can revisit that tradeoff when it becomes limiting. Because distributed browser\n // state is extremely hard to debug, this seems like fair tradeoff for now.\n if (oldVersion !== newVersion) {\n logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`)\n // Delete any existing databases that are not the current version\n const objectStores = transaction.objectStoreNames\n for (const name of objectStores) {\n try {\n database.deleteObjectStore(name)\n } catch {\n logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`)\n }\n }\n }\n // Create the store\n const store = database.createObjectStore(storeName, {\n // If it isn't explicitly set, create a value by auto incrementing.\n autoIncrement: true,\n })\n // Name the store\n store.name = storeName\n // Create an index on the hash\n for (const { key, multiEntry, unique } of indexes) {\n const indexKeys = Object.keys(key)\n const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys\n const indexName = buildStandardIndexName({ key, unique })\n store.createIndex(indexName, keys, { multiEntry, unique })\n }\n },\n })\n return db\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async useDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T> {\n // Get the initialized DB\n const db = await this.getInitializedDb()\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n}\n","export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\nexport const IndexedDbArchivistSchema: IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\n","import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model'\n\nimport { IndexedDbArchivistSchema } from './Schema'\n\nexport type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\nexport const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\n\nexport type IndexedDbArchivistConfig = ArchivistConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbArchivistConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main archivist config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACAA,oBAAuB;AAEvB,gCAAkC;AAClC,6BAQO;AACP,0BAAgC;AAChC,6BAA+B;AAE/B,iBAAqC;;;ACd9B,IAAMA,2BAAqD;;;ACI3D,IAAMC,iCAAiE,GAAGC,wBAAAA;;;;;;;;;;;;;;AFoB1E,IAAMC,qBAAN,MAAMA,4BAGHC,4CAAAA;SAAAA;;;EACR,OAAgBC,gBAA0B;OAAI,MAAMA;IAAeC;;EACnE,OAAgBC,sBAA8BD;EAC9C,OAAgBE,gBAAgB;EAChC,OAAgBC,mBAAmB;EACnC,OAAgBC,mBAAmB;EACnC,OAAwBC,gBAAkC;IAAEC,KAAK;MAAEC,OAAO;IAAE;IAAGC,YAAY;IAAOC,QAAQ;EAAM;EAChH,OAAwBC,YAA8B;IAAEJ,KAAK;MAAEK,OAAO;IAAE;IAAGH,YAAY;IAAOC,QAAQ;EAAK;EAC3G,OAAwBG,cAAgC;IAAEN,KAAK;MAAEO,QAAQ;IAAE;IAAGL,YAAY;IAAOC,QAAQ;EAAM;;EAE/G,OAAgBK,oBAAgBC,+CAAuBlB,oBAAmBa,SAAS;;EAEnF,OAAgBM,wBAAoBD,+CAAuBlB,oBAAmBQ,aAAa;;EAE3F,OAAgBY,sBAAkBF,+CAAuBlB,oBAAmBe,WAAW;;;;;;;;EASvF,IAAIM,SAAS;AACX,WAAO,KAAKC,QAAQD,U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;YAAET;YAAKG;UAAO,CAAA;AACvDuD,gBAAMoD,YAAYtD,WAAWoD,MAAM;YAAE1G;YAAYC;UAAO,CAAA;QAC1D;MACF;IACF,CAAA;AACA,WAAOwB;EACT;;;;;;EAOA,MAAcD,MAASqF,UAA0E;AAE/F,UAAMpF,KAAK,MAAM,KAAKkD,iBAAgB;AACtC,QAAI;AAEF,aAAO,MAAMkC,SAASpF,EAAAA;IACxB,UAAA;AAEEA,SAAG0D,MAAK;IACV;EACF;AACF;AApRa9F,qBAAAA,aAAAA;MADZyH,qCAAAA;GACYzH,kBAAAA;","names":["IndexedDbArchivistSchema","IndexedDbArchivistConfigSchema","IndexedDbArchivistSchema","IndexedDbArchivist","AbstractArchivist","configSchemas","IndexedDbArchivistConfigSchema","defaultConfigSchema","defaultDbName","defaultDbVersion","defaultStoreName","dataHashIndex","key","$hash","multiEntry","unique","hashIndex","_hash","schemaIndex","schema","hashIndexName","buildStandardIndexName","dataHashIndexName","schemaIndexName","dbName","config","name","dbVersion","queries","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","storeName","indexes","storage","allHandler","payloads","useDb","db","getAll","Promise","all","map","payload","PayloadBuilder","build","clearHandler","clear","deleteHandler","hashes","pairs","hashPairs","getHandler","hashesToDelete","flatMap","pair","distinctHashes","Set","found","hash","existing","getKeyFromIndex","delete","filter","exists","includes","getFromIndexWithPrimaryKey","indexName","transaction","store","objectStore","index","cursor","openCursor","singleValue","value","primaryKey","TypeError","payloadsFromDataHashes","payloadsFromHash","_key","has","add","payloadsFromDataHash","sort","a","b","insertHandler","getInitializedDb","inserted","shift","tx","existingTopHash","get","put","done","close","startHandler","logger","openDB","blocked","currentVersion","blockedVersion","event","warn","blocking","terminated","log","upgrade","database","oldVersion","newVersion","objectStores","objectStoreNames","deleteObjectStore","createObjectStore","autoIncrement","indexKeys","Object","keys","length","createIndex","callback","creatableModule"]}
|
package/dist/browser/index.js
CHANGED
|
@@ -32,8 +32,10 @@ var IndexedDbArchivist = class _IndexedDbArchivist extends AbstractArchivist {
|
|
|
32
32
|
__name(this, "IndexedDbArchivist");
|
|
33
33
|
}
|
|
34
34
|
static configSchemas = [
|
|
35
|
+
...super.configSchemas,
|
|
35
36
|
IndexedDbArchivistConfigSchema
|
|
36
37
|
];
|
|
38
|
+
static defaultConfigSchema = IndexedDbArchivistConfigSchema;
|
|
37
39
|
static defaultDbName = "archivist";
|
|
38
40
|
static defaultDbVersion = 1;
|
|
39
41
|
static defaultStoreName = "payloads";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Archivist.ts","../../src/Schema.ts","../../src/Config.ts"],"sourcesContent":["import { exists } from '@xylabs/exists'\nimport { Hash } from '@xylabs/hex'\nimport { AbstractArchivist } from '@xyo-network/archivist-abstract'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistDeleteQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistModuleEventData,\n buildStandardIndexName,\n IndexDescription,\n} from '@xyo-network/archivist-model'\nimport { creatableModule } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload, PayloadWithMeta } from '@xyo-network/payload-model'\nimport { IDBPDatabase, openDB } from 'idb'\n\nimport { IndexedDbArchivistConfigSchema } from './Config'\nimport { IndexedDbArchivistParams } from './Params'\n\nexport interface PayloadStore {\n [s: string]: Payload\n}\n\n@creatableModule()\nexport class IndexedDbArchivist<\n TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n> extends AbstractArchivist<TParams, TEventData> {\n static override configSchemas = [IndexedDbArchivistConfigSchema]\n static readonly defaultDbName = 'archivist'\n static readonly defaultDbVersion = 1\n static readonly defaultStoreName = 'payloads'\n private static readonly dataHashIndex: IndexDescription = { key: { $hash: 1 }, multiEntry: false, unique: false }\n private static readonly hashIndex: IndexDescription = { key: { _hash: 1 }, multiEntry: false, unique: true }\n private static readonly schemaIndex: IndexDescription = { key: { schema: 1 }, multiEntry: false, unique: false }\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly hashIndexName = buildStandardIndexName(IndexedDbArchivist.hashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly dataHashIndexName = buildStandardIndexName(IndexedDbArchivist.dataHashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly schemaIndexName = buildStandardIndexName(IndexedDbArchivist.schemaIndex)\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the module name (not guaranteed to be unique) and if module\n * name is not supplied, it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.name ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to 1.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n override get queries() {\n return [ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, ...super.queries]\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n /**\n * The indexes to create on the store\n */\n private get indexes() {\n return [IndexedDbArchivist.dataHashIndex, IndexedDbArchivist.hashIndex, IndexedDbArchivist.schemaIndex, ...(this.config?.storage?.indexes ?? [])]\n }\n\n protected override async allHandler(): Promise<PayloadWithMeta[]> {\n // Get all payloads from the store\n const payloads = await this.useDb((db) => db.getAll(this.storeName))\n // Remove any metadata before returning to the client\n return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)))\n }\n\n protected override async clearHandler(): Promise<void> {\n await this.useDb((db) => db.clear(this.storeName))\n }\n\n protected override async deleteHandler(hashes: Hash[]): Promise<Hash[]> {\n const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes))\n const hashesToDelete = pairs.flatMap<Hash>((pair) => [pair[0].$hash, pair[1]])\n // Remove any duplicates\n const distinctHashes = [...new Set(hashesToDelete)]\n return await this.useDb(async (db) => {\n // Only return hashes that were successfully deleted\n const found = await Promise.all(\n distinctHashes.map(async (hash) => {\n // Check if the hash exists\n const existing =\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.hashIndexName, hash)) ??\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.dataHashIndexName, hash))\n // If it does exist\n if (existing) {\n // Delete it\n await db.delete(this.storeName, existing)\n // Return the hash so it gets added to the list of deleted hashes\n return hash\n }\n }),\n )\n return found.filter(exists).filter((hash) => hashes.includes(hash))\n })\n }\n\n /**\n * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)\n * @param db The db instance to use\n * @param storeName The name of the store to use\n * @param indexName The index to use\n * @param key The key to get from the index\n * @returns The primary key and the payload, or undefined if not found\n */\n protected async getFromIndexWithPrimaryKey(\n db: IDBPDatabase<PayloadStore>,\n storeName: string,\n indexName: string,\n key: IDBValidKey,\n ): Promise<[number, PayloadWithMeta] | undefined> {\n const transaction = db.transaction(storeName, 'readonly')\n const store = transaction.objectStore(storeName)\n const index = store.index(indexName)\n const cursor = await index.openCursor(key)\n if (cursor) {\n const singleValue = cursor.value\n // NOTE: It's known to be a number because we are using IndexedDB supplied auto-incrementing keys\n if (typeof cursor.primaryKey !== 'number') {\n throw new TypeError('primaryKey must be a number')\n }\n\n return [cursor.primaryKey, singleValue]\n }\n }\n\n protected override async getHandler(hashes: string[]): Promise<PayloadWithMeta[]> {\n const payloads = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.hashIndexName, hash))),\n )\n const payloadsFromDataHashes = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.dataHashIndexName, hash))),\n )\n //filter out duplicates\n const found = new Set<string>()\n const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n return (\n // Merge what we found from the hash and data hash indexes\n [...payloadsFromHash, ...payloadsFromDataHash]\n // Sort in ascending order by primary key (for semi-predictable ordering in terms of insertion order)\n .sort((a, b) => a[0] - b[0])\n // Return just the payloads\n .map(([_key, payload]) => payload)\n )\n }\n\n protected override async insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]> {\n const pairs = await PayloadBuilder.hashPairs(payloads)\n\n const db = await this.getInitializedDb()\n try {\n // Only return the payloads that were successfully inserted\n const inserted = await Promise.all(\n pairs.map(async ([payload, _hash]) => {\n const existing = (await this.getHandler([_hash])).shift()\n if (existing) {\n return\n }\n // Perform each insert via a transaction to ensure it is atomic\n // with respect to checking for the pre-existence of the hash.\n // This is done to preserve iteration via insertion order.\n const tx = db.transaction(this.storeName, 'readwrite')\n try {\n // Get the object store\n const store = tx.objectStore(this.storeName)\n\n // Check if the hash already exists\n const existingTopHash = await store.index(IndexedDbArchivist.hashIndexName).get(_hash)\n // If it does not already exist\n if (!existingTopHash) {\n // Insert the payload\n await store.put({ ...payload, _hash })\n }\n\n // Return it so it gets added to the list of inserted payloads\n return payload\n } finally {\n // Close the transaction\n await tx.done\n }\n }),\n )\n return inserted.filter(exists)\n } finally {\n db.close()\n }\n }\n\n protected override async startHandler() {\n await super.startHandler()\n // NOTE: We could defer this creation to first access but we\n // want to fail fast here in case something is wrong\n await this.useDb(() => {})\n return true\n }\n\n /**\n * Returns that the desired DB/Store initialized to the correct version\n * @returns The initialized DB\n */\n private async getInitializedDb(): Promise<IDBPDatabase<PayloadStore>> {\n const { dbName, dbVersion, indexes, storeName, logger } = this\n const db = await openDB<PayloadStore>(dbName, dbVersion, {\n blocked(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event)\n },\n blocking(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event)\n },\n terminated() {\n logger.log('IndexedDbArchivist: Terminated')\n },\n upgrade(database, oldVersion, newVersion, transaction) {\n // NOTE: This is called whenever the DB is created/updated. We could simply ensure the desired end\n // state but, out of an abundance of caution, we will just delete (so we know where we are starting\n // from a known good point) and recreate the desired state. This prioritizes resilience over data\n // retention but we can revisit that tradeoff when it becomes limiting. Because distributed browser\n // state is extremely hard to debug, this seems like fair tradeoff for now.\n if (oldVersion !== newVersion) {\n logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`)\n // Delete any existing databases that are not the current version\n const objectStores = transaction.objectStoreNames\n for (const name of objectStores) {\n try {\n database.deleteObjectStore(name)\n } catch {\n logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`)\n }\n }\n }\n // Create the store\n const store = database.createObjectStore(storeName, {\n // If it isn't explicitly set, create a value by auto incrementing.\n autoIncrement: true,\n })\n // Name the store\n store.name = storeName\n // Create an index on the hash\n for (const { key, multiEntry, unique } of indexes) {\n const indexKeys = Object.keys(key)\n const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys\n const indexName = buildStandardIndexName({ key, unique })\n store.createIndex(indexName, keys, { multiEntry, unique })\n }\n },\n })\n return db\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async useDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T> {\n // Get the initialized DB\n const db = await this.getInitializedDb()\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n}\n","export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\nexport const IndexedDbArchivistSchema: IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\n","import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model'\n\nimport { IndexedDbArchivistSchema } from './Schema'\n\nexport type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\nexport const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\n\nexport type IndexedDbArchivistConfig = ArchivistConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbArchivistConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main archivist config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n"],"mappings":";;;;AAAA,SAASA,cAAc;AAEvB,SAASC,yBAAyB;AAClC,SACEC,yBACAC,2BACAC,4BACAC,4BAEAC,8BAEK;AACP,SAASC,uBAAuB;AAChC,SAASC,sBAAsB;AAE/B,SAAuBC,cAAc;;;ACd9B,IAAMC,2BAAqD;;;ACI3D,IAAMC,iCAAiE,GAAGC,wBAAAA;;;;;;;;;;;;;;AFoB1E,IAAMC,qBAAN,MAAMA,4BAGHC,kBAAAA;SAAAA;;;EACR,OAAgBC,gBAAgB;IAACC;;EACjC,OAAgBC,gBAAgB;EAChC,OAAgBC,mBAAmB;EACnC,OAAgBC,mBAAmB;EACnC,OAAwBC,gBAAkC;IAAEC,KAAK;MAAEC,OAAO;IAAE;IAAGC,YAAY;IAAOC,QAAQ;EAAM;EAChH,OAAwBC,YAA8B;IAAEJ,KAAK;MAAEK,OAAO;IAAE;IAAGH,YAAY;IAAOC,QAAQ;EAAK;EAC3G,OAAwBG,cAAgC;IAAEN,KAAK;MAAEO,QAAQ;IAAE;IAAGL,YAAY;IAAOC,QAAQ;EAAM;;EAE/G,OAAgBK,gBAAgBC,uBAAuBjB,oBAAmBY,SAAS;;EAEn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;AACjD,gBAAMoF,YAAYC,OAAOC,KAAK5G,GAAAA;AAC9B,gBAAM4G,OAAOF,UAAUG,WAAW,IAAIH,UAAU,CAAA,IAAKA;AACrD,gBAAMlD,YAAY/C,uBAAuB;YAAET;YAAKG;UAAO,CAAA;AACvDuD,gBAAMoD,YAAYtD,WAAWoD,MAAM;YAAE1G;YAAYC;UAAO,CAAA;QAC1D;MACF;IACF,CAAA;AACA,WAAOwB;EACT;;;;;;EAOA,MAAcD,MAASqF,UAA0E;AAE/F,UAAMpF,KAAK,MAAM,KAAKkD,iBAAgB;AACtC,QAAI;AAEF,aAAO,MAAMkC,SAASpF,EAAAA;IACxB,UAAA;AAEEA,SAAG0D,MAAK;IACV;EACF;AACF;AAnRa7F,qBAAAA,aAAAA;EADZwH,gBAAAA;GACYxH,kBAAAA;","names":["exists","AbstractArchivist","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","buildStandardIndexName","creatableModule","PayloadBuilder","openDB","IndexedDbArchivistSchema","IndexedDbArchivistConfigSchema","IndexedDbArchivistSchema","IndexedDbArchivist","AbstractArchivist","configSchemas","IndexedDbArchivistConfigSchema","defaultDbName","defaultDbVersion","defaultStoreName","dataHashIndex","key","$hash","multiEntry","unique","hashIndex","_hash","schemaIndex","schema","hashIndexName","buildStandardIndexName","dataHashIndexName","schemaIndexName","dbName","config","name","dbVersion","queries","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","storeName","indexes","storage","allHandler","payloads","useDb","db","getAll","Promise","all","map","payload","PayloadBuilder","build","clearHandler","clear","deleteHandler","hashes","pairs","hashPairs","getHandler","hashesToDelete","flatMap","pair","distinctHashes","Set","found","hash","existing","getKeyFromIndex","delete","filter","exists","includes","getFromIndexWithPrimaryKey","indexName","transaction","store","objectStore","index","cursor","openCursor","singleValue","value","primaryKey","TypeError","payloadsFromDataHashes","payloadsFromHash","_key","has","add","payloadsFromDataHash","sort","a","b","insertHandler","getInitializedDb","inserted","shift","tx","existingTopHash","get","put","done","close","startHandler","logger","openDB","blocked","currentVersion","blockedVersion","event","warn","blocking","terminated","log","upgrade","database","oldVersion","newVersion","objectStores","objectStoreNames","deleteObjectStore","createObjectStore","autoIncrement","indexKeys","Object","keys","length","createIndex","callback","creatableModule"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Archivist.ts","../../src/Schema.ts","../../src/Config.ts"],"sourcesContent":["import { exists } from '@xylabs/exists'\nimport { Hash } from '@xylabs/hex'\nimport { AbstractArchivist } from '@xyo-network/archivist-abstract'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistDeleteQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistModuleEventData,\n buildStandardIndexName,\n IndexDescription,\n} from '@xyo-network/archivist-model'\nimport { creatableModule } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model'\nimport { IDBPDatabase, openDB } from 'idb'\n\nimport { IndexedDbArchivistConfigSchema } from './Config'\nimport { IndexedDbArchivistParams } from './Params'\n\nexport interface PayloadStore {\n [s: string]: Payload\n}\n\n@creatableModule()\nexport class IndexedDbArchivist<\n TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n> extends AbstractArchivist<TParams, TEventData> {\n static override configSchemas: Schema[] = [...super.configSchemas, IndexedDbArchivistConfigSchema]\n static override defaultConfigSchema: Schema = IndexedDbArchivistConfigSchema\n static readonly defaultDbName = 'archivist'\n static readonly defaultDbVersion = 1\n static readonly defaultStoreName = 'payloads'\n private static readonly dataHashIndex: IndexDescription = { key: { $hash: 1 }, multiEntry: false, unique: false }\n private static readonly hashIndex: IndexDescription = { key: { _hash: 1 }, multiEntry: false, unique: true }\n private static readonly schemaIndex: IndexDescription = { key: { schema: 1 }, multiEntry: false, unique: false }\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly hashIndexName = buildStandardIndexName(IndexedDbArchivist.hashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly dataHashIndexName = buildStandardIndexName(IndexedDbArchivist.dataHashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly schemaIndexName = buildStandardIndexName(IndexedDbArchivist.schemaIndex)\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the module name (not guaranteed to be unique) and if module\n * name is not supplied, it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.name ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to 1.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n override get queries() {\n return [ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, ...super.queries]\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n /**\n * The indexes to create on the store\n */\n private get indexes() {\n return [IndexedDbArchivist.dataHashIndex, IndexedDbArchivist.hashIndex, IndexedDbArchivist.schemaIndex, ...(this.config?.storage?.indexes ?? [])]\n }\n\n protected override async allHandler(): Promise<PayloadWithMeta[]> {\n // Get all payloads from the store\n const payloads = await this.useDb((db) => db.getAll(this.storeName))\n // Remove any metadata before returning to the client\n return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)))\n }\n\n protected override async clearHandler(): Promise<void> {\n await this.useDb((db) => db.clear(this.storeName))\n }\n\n protected override async deleteHandler(hashes: Hash[]): Promise<Hash[]> {\n const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes))\n const hashesToDelete = pairs.flatMap<Hash>((pair) => [pair[0].$hash, pair[1]])\n // Remove any duplicates\n const distinctHashes = [...new Set(hashesToDelete)]\n return await this.useDb(async (db) => {\n // Only return hashes that were successfully deleted\n const found = await Promise.all(\n distinctHashes.map(async (hash) => {\n // Check if the hash exists\n const existing =\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.hashIndexName, hash)) ??\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.dataHashIndexName, hash))\n // If it does exist\n if (existing) {\n // Delete it\n await db.delete(this.storeName, existing)\n // Return the hash so it gets added to the list of deleted hashes\n return hash\n }\n }),\n )\n return found.filter(exists).filter((hash) => hashes.includes(hash))\n })\n }\n\n /**\n * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)\n * @param db The db instance to use\n * @param storeName The name of the store to use\n * @param indexName The index to use\n * @param key The key to get from the index\n * @returns The primary key and the payload, or undefined if not found\n */\n protected async getFromIndexWithPrimaryKey(\n db: IDBPDatabase<PayloadStore>,\n storeName: string,\n indexName: string,\n key: IDBValidKey,\n ): Promise<[number, PayloadWithMeta] | undefined> {\n const transaction = db.transaction(storeName, 'readonly')\n const store = transaction.objectStore(storeName)\n const index = store.index(indexName)\n const cursor = await index.openCursor(key)\n if (cursor) {\n const singleValue = cursor.value\n // NOTE: It's known to be a number because we are using IndexedDB supplied auto-incrementing keys\n if (typeof cursor.primaryKey !== 'number') {\n throw new TypeError('primaryKey must be a number')\n }\n\n return [cursor.primaryKey, singleValue]\n }\n }\n\n protected override async getHandler(hashes: string[]): Promise<PayloadWithMeta[]> {\n const payloads = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.hashIndexName, hash))),\n )\n const payloadsFromDataHashes = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.dataHashIndexName, hash))),\n )\n //filter out duplicates\n const found = new Set<string>()\n const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n return (\n // Merge what we found from the hash and data hash indexes\n [...payloadsFromHash, ...payloadsFromDataHash]\n // Sort in ascending order by primary key (for semi-predictable ordering in terms of insertion order)\n .sort((a, b) => a[0] - b[0])\n // Return just the payloads\n .map(([_key, payload]) => payload)\n )\n }\n\n protected override async insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]> {\n const pairs = await PayloadBuilder.hashPairs(payloads)\n\n const db = await this.getInitializedDb()\n try {\n // Only return the payloads that were successfully inserted\n const inserted = await Promise.all(\n pairs.map(async ([payload, _hash]) => {\n const existing = (await this.getHandler([_hash])).shift()\n if (existing) {\n return\n }\n // Perform each insert via a transaction to ensure it is atomic\n // with respect to checking for the pre-existence of the hash.\n // This is done to preserve iteration via insertion order.\n const tx = db.transaction(this.storeName, 'readwrite')\n try {\n // Get the object store\n const store = tx.objectStore(this.storeName)\n\n // Check if the hash already exists\n const existingTopHash = await store.index(IndexedDbArchivist.hashIndexName).get(_hash)\n // If it does not already exist\n if (!existingTopHash) {\n // Insert the payload\n await store.put({ ...payload, _hash })\n }\n\n // Return it so it gets added to the list of inserted payloads\n return payload\n } finally {\n // Close the transaction\n await tx.done\n }\n }),\n )\n return inserted.filter(exists)\n } finally {\n db.close()\n }\n }\n\n protected override async startHandler() {\n await super.startHandler()\n // NOTE: We could defer this creation to first access but we\n // want to fail fast here in case something is wrong\n await this.useDb(() => {})\n return true\n }\n\n /**\n * Returns that the desired DB/Store initialized to the correct version\n * @returns The initialized DB\n */\n private async getInitializedDb(): Promise<IDBPDatabase<PayloadStore>> {\n const { dbName, dbVersion, indexes, storeName, logger } = this\n const db = await openDB<PayloadStore>(dbName, dbVersion, {\n blocked(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event)\n },\n blocking(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event)\n },\n terminated() {\n logger.log('IndexedDbArchivist: Terminated')\n },\n upgrade(database, oldVersion, newVersion, transaction) {\n // NOTE: This is called whenever the DB is created/updated. We could simply ensure the desired end\n // state but, out of an abundance of caution, we will just delete (so we know where we are starting\n // from a known good point) and recreate the desired state. This prioritizes resilience over data\n // retention but we can revisit that tradeoff when it becomes limiting. Because distributed browser\n // state is extremely hard to debug, this seems like fair tradeoff for now.\n if (oldVersion !== newVersion) {\n logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`)\n // Delete any existing databases that are not the current version\n const objectStores = transaction.objectStoreNames\n for (const name of objectStores) {\n try {\n database.deleteObjectStore(name)\n } catch {\n logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`)\n }\n }\n }\n // Create the store\n const store = database.createObjectStore(storeName, {\n // If it isn't explicitly set, create a value by auto incrementing.\n autoIncrement: true,\n })\n // Name the store\n store.name = storeName\n // Create an index on the hash\n for (const { key, multiEntry, unique } of indexes) {\n const indexKeys = Object.keys(key)\n const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys\n const indexName = buildStandardIndexName({ key, unique })\n store.createIndex(indexName, keys, { multiEntry, unique })\n }\n },\n })\n return db\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async useDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T> {\n // Get the initialized DB\n const db = await this.getInitializedDb()\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n}\n","export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\nexport const IndexedDbArchivistSchema: IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\n","import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model'\n\nimport { IndexedDbArchivistSchema } from './Schema'\n\nexport type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\nexport const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\n\nexport type IndexedDbArchivistConfig = ArchivistConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbArchivistConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main archivist config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n"],"mappings":";;;;AAAA,SAASA,cAAc;AAEvB,SAASC,yBAAyB;AAClC,SACEC,yBACAC,2BACAC,4BACAC,4BAEAC,8BAEK;AACP,SAASC,uBAAuB;AAChC,SAASC,sBAAsB;AAE/B,SAAuBC,cAAc;;;ACd9B,IAAMC,2BAAqD;;;ACI3D,IAAMC,iCAAiE,GAAGC,wBAAAA;;;;;;;;;;;;;;AFoB1E,IAAMC,qBAAN,MAAMA,4BAGHC,kBAAAA;SAAAA;;;EACR,OAAgBC,gBAA0B;OAAI,MAAMA;IAAeC;;EACnE,OAAgBC,sBAA8BD;EAC9C,OAAgBE,gBAAgB;EAChC,OAAgBC,mBAAmB;EACnC,OAAgBC,mBAAmB;EACnC,OAAwBC,gBAAkC;IAAEC,KAAK;MAAEC,OAAO;IAAE;IAAGC,YAAY;IAAOC,QAAQ;EAAM;EAChH,OAAwBC,YAA8B;IAAEJ,KAAK;MAAEK,OAAO;IAAE;IAAGH,YAAY;IAAOC,QAAQ;EAAK;EAC3G,OAAwBG,cAAgC;IAAEN,KAAK;MAAEO,QAAQ;IAAE;IAAGL,YAAY;IAAOC,QAAQ;EAAM;;EAE/G,OAAgBK,gBAAgBC,uBAAuBlB,oBAAmBa,SAAS;;EAEnF,OAAgBM,oBAAoBD,uBAAuBlB,oBA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AAK5G,GAAAA;AAC9B,gBAAM4G,OAAOF,UAAUG,WAAW,IAAIH,UAAU,CAAA,IAAKA;AACrD,gBAAMlD,YAAY/C,uBAAuB;YAAET;YAAKG;UAAO,CAAA;AACvDuD,gBAAMoD,YAAYtD,WAAWoD,MAAM;YAAE1G;YAAYC;UAAO,CAAA;QAC1D;MACF;IACF,CAAA;AACA,WAAOwB;EACT;;;;;;EAOA,MAAcD,MAASqF,UAA0E;AAE/F,UAAMpF,KAAK,MAAM,KAAKkD,iBAAgB;AACtC,QAAI;AAEF,aAAO,MAAMkC,SAASpF,EAAAA;IACxB,UAAA;AAEEA,SAAG0D,MAAK;IACV;EACF;AACF;AApRa9F,qBAAAA,aAAAA;EADZyH,gBAAAA;GACYzH,kBAAAA;","names":["exists","AbstractArchivist","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","buildStandardIndexName","creatableModule","PayloadBuilder","openDB","IndexedDbArchivistSchema","IndexedDbArchivistConfigSchema","IndexedDbArchivistSchema","IndexedDbArchivist","AbstractArchivist","configSchemas","IndexedDbArchivistConfigSchema","defaultConfigSchema","defaultDbName","defaultDbVersion","defaultStoreName","dataHashIndex","key","$hash","multiEntry","unique","hashIndex","_hash","schemaIndex","schema","hashIndexName","buildStandardIndexName","dataHashIndexName","schemaIndexName","dbName","config","name","dbVersion","queries","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","storeName","indexes","storage","allHandler","payloads","useDb","db","getAll","Promise","all","map","payload","PayloadBuilder","build","clearHandler","clear","deleteHandler","hashes","pairs","hashPairs","getHandler","hashesToDelete","flatMap","pair","distinctHashes","Set","found","hash","existing","getKeyFromIndex","delete","filter","exists","includes","getFromIndexWithPrimaryKey","indexName","transaction","store","objectStore","index","cursor","openCursor","singleValue","value","primaryKey","TypeError","payloadsFromDataHashes","payloadsFromHash","_key","has","add","payloadsFromDataHash","sort","a","b","insertHandler","getInitializedDb","inserted","shift","tx","existingTopHash","get","put","done","close","startHandler","logger","openDB","blocked","currentVersion","blockedVersion","event","warn","blocking","terminated","log","upgrade","database","oldVersion","newVersion","objectStores","objectStoreNames","deleteObjectStore","createObjectStore","autoIncrement","indexKeys","Object","keys","length","createIndex","callback","creatableModule"]}
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { Hash } from '@xylabs/hex';
|
|
2
2
|
import { AbstractArchivist } from '@xyo-network/archivist-abstract';
|
|
3
3
|
import { ArchivistModuleEventData } from '@xyo-network/archivist-model';
|
|
4
|
-
import { Payload, PayloadWithMeta } from '@xyo-network/payload-model';
|
|
4
|
+
import { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model';
|
|
5
5
|
import { IDBPDatabase } from 'idb';
|
|
6
6
|
import { IndexedDbArchivistParams } from './Params';
|
|
7
7
|
export interface PayloadStore {
|
|
8
8
|
[s: string]: Payload;
|
|
9
9
|
}
|
|
10
10
|
export declare class IndexedDbArchivist<TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams, TEventData extends ArchivistModuleEventData = ArchivistModuleEventData> extends AbstractArchivist<TParams, TEventData> {
|
|
11
|
-
static configSchemas:
|
|
11
|
+
static configSchemas: Schema[];
|
|
12
|
+
static defaultConfigSchema: Schema;
|
|
12
13
|
static readonly defaultDbName = "archivist";
|
|
13
14
|
static readonly defaultDbVersion = 1;
|
|
14
15
|
static readonly defaultStoreName = "payloads";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAA;
|
|
1
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AAI,SAAS,WAEZ;IAED,IAAa,OAAO,aAEnB;IAED;;;OAGG;IACH,IAAI,SAAS,WAEZ;IAED;;OAEG;IACH,OAAO,KAAK,OAAO,GAElB;cAEwB,UAAU,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;cAOxC,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;cAI7B,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IA0BvE;;;;;;;OAOG;cACa,0BAA0B,CACxC,EAAE,EAAE,YAAY,CAAC,YAAY,CAAC,EAC9B,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,WAAW,GACf,OAAO,CAAC,CAAC,MAAM,EAAE,eAAe,CAAC,GAAG,SAAS,CAAC;cAgBxB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cAmCxD,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cA0C9D,YAAY;IAQrC;;;OAGG;YACW,gBAAgB;IAiD9B;;;;OAIG;YACW,KAAK;CAWpB"}
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { Hash } from '@xylabs/hex';
|
|
2
2
|
import { AbstractArchivist } from '@xyo-network/archivist-abstract';
|
|
3
3
|
import { ArchivistModuleEventData } from '@xyo-network/archivist-model';
|
|
4
|
-
import { Payload, PayloadWithMeta } from '@xyo-network/payload-model';
|
|
4
|
+
import { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model';
|
|
5
5
|
import { IDBPDatabase } from 'idb';
|
|
6
6
|
import { IndexedDbArchivistParams } from './Params';
|
|
7
7
|
export interface PayloadStore {
|
|
8
8
|
[s: string]: Payload;
|
|
9
9
|
}
|
|
10
10
|
export declare class IndexedDbArchivist<TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams, TEventData extends ArchivistModuleEventData = ArchivistModuleEventData> extends AbstractArchivist<TParams, TEventData> {
|
|
11
|
-
static configSchemas:
|
|
11
|
+
static configSchemas: Schema[];
|
|
12
|
+
static defaultConfigSchema: Schema;
|
|
12
13
|
static readonly defaultDbName = "archivist";
|
|
13
14
|
static readonly defaultDbVersion = 1;
|
|
14
15
|
static readonly defaultStoreName = "payloads";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAA;
|
|
1
|
+
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAA;AAC7E,OAAO,EAAE,YAAY,EAAU,MAAM,KAAK,CAAA;AAG1C,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,WAAW,YAAY;IAC3B,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;CACrB;AAED,qBACa,kBAAkB,CAC7B,OAAO,SAAS,wBAAwB,GAAG,wBAAwB,EACnE,UAAU,SAAS,wBAAwB,GAAG,wBAAwB,CACtE,SAAQ,iBAAiB,CAAC,OAAO,EAAE,UAAU,CAAC;IAC9C,OAAgB,aAAa,EAAE,MAAM,EAAE,CA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AAY;IAQrC;;;OAGG;YACW,gBAAgB;IAiD9B;;;;OAIG;YACW,KAAK;CAWpB"}
|
package/dist/node/Archivist.d.ts
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { Hash } from '@xylabs/hex';
|
|
2
2
|
import { AbstractArchivist } from '@xyo-network/archivist-abstract';
|
|
3
3
|
import { ArchivistModuleEventData } from '@xyo-network/archivist-model';
|
|
4
|
-
import { Payload, PayloadWithMeta } from '@xyo-network/payload-model';
|
|
4
|
+
import { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model';
|
|
5
5
|
import { IDBPDatabase } from 'idb';
|
|
6
6
|
import { IndexedDbArchivistParams } from './Params';
|
|
7
7
|
export interface PayloadStore {
|
|
8
8
|
[s: string]: Payload;
|
|
9
9
|
}
|
|
10
10
|
export declare class IndexedDbArchivist<TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams, TEventData extends ArchivistModuleEventData = ArchivistModuleEventData> extends AbstractArchivist<TParams, TEventData> {
|
|
11
|
-
static configSchemas:
|
|
11
|
+
static configSchemas: Schema[];
|
|
12
|
+
static defaultConfigSchema: Schema;
|
|
12
13
|
static readonly defaultDbName = "archivist";
|
|
13
14
|
static readonly defaultDbVersion = 1;
|
|
14
15
|
static readonly defaultStoreName = "payloads";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAA;
|
|
1
|
+
{"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAA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O,KAAK,OAAO,GAElB;cAEwB,UAAU,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;cAOxC,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;cAI7B,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IA0BvE;;;;;;;OAOG;cACa,0BAA0B,CACxC,EAAE,EAAE,YAAY,CAAC,YAAY,CAAC,EAC9B,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,WAAW,GACf,OAAO,CAAC,CAAC,MAAM,EAAE,eAAe,CAAC,GAAG,SAAS,CAAC;cAgBxB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cAmCxD,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cA0C9D,YAAY;IAQrC;;;OAGG;YACW,gBAAgB;IAiD9B;;;;OAIG;YACW,KAAK;CAWpB"}
|
package/dist/node/index.cjs
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
var __defProp = Object.defineProperty;
|
|
3
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
6
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __reflectGet = Reflect.get;
|
|
6
8
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
7
9
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
8
10
|
var __export = (target, all) => {
|
|
@@ -22,6 +24,7 @@ var __publicField = (obj, key, value) => {
|
|
|
22
24
|
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
23
25
|
return value;
|
|
24
26
|
};
|
|
27
|
+
var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
|
|
25
28
|
|
|
26
29
|
// src/index.ts
|
|
27
30
|
var src_exports = {};
|
|
@@ -287,8 +290,10 @@ var _IndexedDbArchivist = class _IndexedDbArchivist extends import_archivist_abs
|
|
|
287
290
|
};
|
|
288
291
|
__name(_IndexedDbArchivist, "IndexedDbArchivist");
|
|
289
292
|
__publicField(_IndexedDbArchivist, "configSchemas", [
|
|
293
|
+
...__superGet(_IndexedDbArchivist, _IndexedDbArchivist, "configSchemas"),
|
|
290
294
|
IndexedDbArchivistConfigSchema
|
|
291
295
|
]);
|
|
296
|
+
__publicField(_IndexedDbArchivist, "defaultConfigSchema", IndexedDbArchivistConfigSchema);
|
|
292
297
|
__publicField(_IndexedDbArchivist, "defaultDbName", "archivist");
|
|
293
298
|
__publicField(_IndexedDbArchivist, "defaultDbVersion", 1);
|
|
294
299
|
__publicField(_IndexedDbArchivist, "defaultStoreName", "payloads");
|
package/dist/node/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts","../../src/Archivist.ts","../../src/Schema.ts","../../src/Config.ts"],"sourcesContent":["export * from './Archivist'\nexport * from './Config'\nexport * from './Params'\nexport * from './Schema'\n","import { exists } from '@xylabs/exists'\nimport { Hash } from '@xylabs/hex'\nimport { AbstractArchivist } from '@xyo-network/archivist-abstract'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistDeleteQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistModuleEventData,\n buildStandardIndexName,\n IndexDescription,\n} from '@xyo-network/archivist-model'\nimport { creatableModule } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload, PayloadWithMeta } from '@xyo-network/payload-model'\nimport { IDBPDatabase, openDB } from 'idb'\n\nimport { IndexedDbArchivistConfigSchema } from './Config'\nimport { IndexedDbArchivistParams } from './Params'\n\nexport interface PayloadStore {\n [s: string]: Payload\n}\n\n@creatableModule()\nexport class IndexedDbArchivist<\n TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n> extends AbstractArchivist<TParams, TEventData> {\n static override configSchemas = [IndexedDbArchivistConfigSchema]\n static readonly defaultDbName = 'archivist'\n static readonly defaultDbVersion = 1\n static readonly defaultStoreName = 'payloads'\n private static readonly dataHashIndex: IndexDescription = { key: { $hash: 1 }, multiEntry: false, unique: false }\n private static readonly hashIndex: IndexDescription = { key: { _hash: 1 }, multiEntry: false, unique: true }\n private static readonly schemaIndex: IndexDescription = { key: { schema: 1 }, multiEntry: false, unique: false }\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly hashIndexName = buildStandardIndexName(IndexedDbArchivist.hashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly dataHashIndexName = buildStandardIndexName(IndexedDbArchivist.dataHashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly schemaIndexName = buildStandardIndexName(IndexedDbArchivist.schemaIndex)\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the module name (not guaranteed to be unique) and if module\n * name is not supplied, it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.name ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to 1.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n override get queries() {\n return [ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, ...super.queries]\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n /**\n * The indexes to create on the store\n */\n private get indexes() {\n return [IndexedDbArchivist.dataHashIndex, IndexedDbArchivist.hashIndex, IndexedDbArchivist.schemaIndex, ...(this.config?.storage?.indexes ?? [])]\n }\n\n protected override async allHandler(): Promise<PayloadWithMeta[]> {\n // Get all payloads from the store\n const payloads = await this.useDb((db) => db.getAll(this.storeName))\n // Remove any metadata before returning to the client\n return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)))\n }\n\n protected override async clearHandler(): Promise<void> {\n await this.useDb((db) => db.clear(this.storeName))\n }\n\n protected override async deleteHandler(hashes: Hash[]): Promise<Hash[]> {\n const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes))\n const hashesToDelete = pairs.flatMap<Hash>((pair) => [pair[0].$hash, pair[1]])\n // Remove any duplicates\n const distinctHashes = [...new Set(hashesToDelete)]\n return await this.useDb(async (db) => {\n // Only return hashes that were successfully deleted\n const found = await Promise.all(\n distinctHashes.map(async (hash) => {\n // Check if the hash exists\n const existing =\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.hashIndexName, hash)) ??\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.dataHashIndexName, hash))\n // If it does exist\n if (existing) {\n // Delete it\n await db.delete(this.storeName, existing)\n // Return the hash so it gets added to the list of deleted hashes\n return hash\n }\n }),\n )\n return found.filter(exists).filter((hash) => hashes.includes(hash))\n })\n }\n\n /**\n * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)\n * @param db The db instance to use\n * @param storeName The name of the store to use\n * @param indexName The index to use\n * @param key The key to get from the index\n * @returns The primary key and the payload, or undefined if not found\n */\n protected async getFromIndexWithPrimaryKey(\n db: IDBPDatabase<PayloadStore>,\n storeName: string,\n indexName: string,\n key: IDBValidKey,\n ): Promise<[number, PayloadWithMeta] | undefined> {\n const transaction = db.transaction(storeName, 'readonly')\n const store = transaction.objectStore(storeName)\n const index = store.index(indexName)\n const cursor = await index.openCursor(key)\n if (cursor) {\n const singleValue = cursor.value\n // NOTE: It's known to be a number because we are using IndexedDB supplied auto-incrementing keys\n if (typeof cursor.primaryKey !== 'number') {\n throw new TypeError('primaryKey must be a number')\n }\n\n return [cursor.primaryKey, singleValue]\n }\n }\n\n protected override async getHandler(hashes: string[]): Promise<PayloadWithMeta[]> {\n const payloads = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.hashIndexName, hash))),\n )\n const payloadsFromDataHashes = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.dataHashIndexName, hash))),\n )\n //filter out duplicates\n const found = new Set<string>()\n const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n return (\n // Merge what we found from the hash and data hash indexes\n [...payloadsFromHash, ...payloadsFromDataHash]\n // Sort in ascending order by primary key (for semi-predictable ordering in terms of insertion order)\n .sort((a, b) => a[0] - b[0])\n // Return just the payloads\n .map(([_key, payload]) => payload)\n )\n }\n\n protected override async insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]> {\n const pairs = await PayloadBuilder.hashPairs(payloads)\n\n const db = await this.getInitializedDb()\n try {\n // Only return the payloads that were successfully inserted\n const inserted = await Promise.all(\n pairs.map(async ([payload, _hash]) => {\n const existing = (await this.getHandler([_hash])).shift()\n if (existing) {\n return\n }\n // Perform each insert via a transaction to ensure it is atomic\n // with respect to checking for the pre-existence of the hash.\n // This is done to preserve iteration via insertion order.\n const tx = db.transaction(this.storeName, 'readwrite')\n try {\n // Get the object store\n const store = tx.objectStore(this.storeName)\n\n // Check if the hash already exists\n const existingTopHash = await store.index(IndexedDbArchivist.hashIndexName).get(_hash)\n // If it does not already exist\n if (!existingTopHash) {\n // Insert the payload\n await store.put({ ...payload, _hash })\n }\n\n // Return it so it gets added to the list of inserted payloads\n return payload\n } finally {\n // Close the transaction\n await tx.done\n }\n }),\n )\n return inserted.filter(exists)\n } finally {\n db.close()\n }\n }\n\n protected override async startHandler() {\n await super.startHandler()\n // NOTE: We could defer this creation to first access but we\n // want to fail fast here in case something is wrong\n await this.useDb(() => {})\n return true\n }\n\n /**\n * Returns that the desired DB/Store initialized to the correct version\n * @returns The initialized DB\n */\n private async getInitializedDb(): Promise<IDBPDatabase<PayloadStore>> {\n const { dbName, dbVersion, indexes, storeName, logger } = this\n const db = await openDB<PayloadStore>(dbName, dbVersion, {\n blocked(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event)\n },\n blocking(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event)\n },\n terminated() {\n logger.log('IndexedDbArchivist: Terminated')\n },\n upgrade(database, oldVersion, newVersion, transaction) {\n // NOTE: This is called whenever the DB is created/updated. We could simply ensure the desired end\n // state but, out of an abundance of caution, we will just delete (so we know where we are starting\n // from a known good point) and recreate the desired state. This prioritizes resilience over data\n // retention but we can revisit that tradeoff when it becomes limiting. Because distributed browser\n // state is extremely hard to debug, this seems like fair tradeoff for now.\n if (oldVersion !== newVersion) {\n logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`)\n // Delete any existing databases that are not the current version\n const objectStores = transaction.objectStoreNames\n for (const name of objectStores) {\n try {\n database.deleteObjectStore(name)\n } catch {\n logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`)\n }\n }\n }\n // Create the store\n const store = database.createObjectStore(storeName, {\n // If it isn't explicitly set, create a value by auto incrementing.\n autoIncrement: true,\n })\n // Name the store\n store.name = storeName\n // Create an index on the hash\n for (const { key, multiEntry, unique } of indexes) {\n const indexKeys = Object.keys(key)\n const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys\n const indexName = buildStandardIndexName({ key, unique })\n store.createIndex(indexName, keys, { multiEntry, unique })\n }\n },\n })\n return db\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async useDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T> {\n // Get the initialized DB\n const db = await this.getInitializedDb()\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n}\n","export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\nexport const IndexedDbArchivistSchema: IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\n","import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model'\n\nimport { IndexedDbArchivistSchema } from './Schema'\n\nexport type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\nexport const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\n\nexport type IndexedDbArchivistConfig = ArchivistConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbArchivistConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main archivist config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACAA,oBAAuB;AAEvB,gCAAkC;AAClC,6BAQO;AACP,0BAAgC;AAChC,6BAA+B;AAE/B,iBAAqC;;;ACd9B,IAAMA,2BAAqD;;;ACI3D,IAAMC,iCAAiE,GAAGC,wBAAAA;;;;;;;;;;;;;;AFoB1E,IAAMC,sBAAN,MAAMA,4BAGHC,4CAAAA;;;;;;;;EAsBR,IAAIC,SAAS;;AACX,aAAO,UAAKC,WAAL,mBAAaD,aAAU,UAAKC,WAAL,mBAAaC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;YAAKoD;UAAO,CAAA;AACvDlD,gBAAMwD,YAAY3D,WAAWwD,MAAM;YAAEJ;YAAYC;UAAO,CAAA;QAC1D;MACF;IACF,CAAA;AACA,WAAOrF;EACT;;;;;;EAOA,MAAcD,MAAS6F,UAA0E;AAE/F,UAAM5F,KAAK,MAAM,KAAKsD,iBAAgB;AACtC,QAAI;AAEF,aAAO,MAAMsC,SAAS5F,EAAAA;IACxB,UAAA;AAEEA,SAAG+D,MAAK;IACV;EACF;AACF;AAhRUrF;AACR,cAJWD,qBAIKoH,iBAAgB;EAACC;;AACjC,cALWrH,qBAKKK,iBAAgB;AAChC,cANWL,qBAMKO,oBAAmB;AACnC,cAPWP,qBAOKc,oBAAmB;AACnC,cARWd,qBAQagB,iBAAkC;EAAEwC,KAAK;IAAEf,OAAO;EAAE;EAAGkE,YAAY;EAAOC,QAAQ;AAAM;AAChH,cATW5G,qBASaiB,aAA8B;EAAEuC,KAAK;IAAEuB,OAAO;EAAE;EAAG4B,YAAY;EAAOC,QAAQ;AAAK;AAC3G,cAVW5G,qBAUakB,eAAgC;EAAEsC,KAAK;IAAE8D,QAAQ;EAAE;EAAGX,YAAY;EAAOC,QAAQ;AAAM;;AAE/G,cAZW5G,qBAYKgD,qBAAgBiE,+CAAuBjH,oBAAmBiB,SAAS;;AAEnF,cAdWjB,qBAcKiD,yBAAoBgE,+CAAuBjH,oBAAmBgB,aAAa;;AAE3F,cAhBWhB,qBAgBKuH,uBAAkBN,+CAAuBjH,oBAAmBkB,WAAW;AAhBlF,IAAMlB,qBAAN;AAAMA,qBAAAA,aAAAA;MADZwH,qCAAAA;GACYxH,kBAAAA;","names":["IndexedDbArchivistSchema","IndexedDbArchivistConfigSchema","IndexedDbArchivistSchema","IndexedDbArchivist","AbstractArchivist","dbName","config","name","defaultDbName","dbVersion","defaultDbVersion","queries","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","storeName","defaultStoreName","indexes","dataHashIndex","hashIndex","schemaIndex","storage","allHandler","payloads","useDb","db","getAll","Promise","all","map","payload","PayloadBuilder","build","clearHandler","clear","deleteHandler","hashes","pairs","hashPairs","getHandler","hashesToDelete","flatMap","pair","$hash","distinctHashes","Set","found","hash","existing","getKeyFromIndex","hashIndexName","dataHashIndexName","delete","filter","exists","includes","getFromIndexWithPrimaryKey","indexName","key","transaction","store","objectStore","index","cursor","openCursor","singleValue","value","primaryKey","TypeError","payloadsFromDataHashes","payloadsFromHash","_key","has","add","payloadsFromDataHash","sort","a","b","insertHandler","getInitializedDb","inserted","_hash","shift","tx","existingTopHash","get","put","done","close","startHandler","logger","openDB","blocked","currentVersion","blockedVersion","event","warn","blocking","terminated","log","upgrade","database","oldVersion","newVersion","objectStores","objectStoreNames","deleteObjectStore","createObjectStore","autoIncrement","multiEntry","unique","indexKeys","Object","keys","length","buildStandardIndexName","createIndex","callback","configSchemas","IndexedDbArchivistConfigSchema","schema","schemaIndexName","creatableModule"]}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts","../../src/Archivist.ts","../../src/Schema.ts","../../src/Config.ts"],"sourcesContent":["export * from './Archivist'\nexport * from './Config'\nexport * from './Params'\nexport * from './Schema'\n","import { exists } from '@xylabs/exists'\nimport { Hash } from '@xylabs/hex'\nimport { AbstractArchivist } from '@xyo-network/archivist-abstract'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistDeleteQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistModuleEventData,\n buildStandardIndexName,\n IndexDescription,\n} from '@xyo-network/archivist-model'\nimport { creatableModule } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model'\nimport { IDBPDatabase, openDB } from 'idb'\n\nimport { IndexedDbArchivistConfigSchema } from './Config'\nimport { IndexedDbArchivistParams } from './Params'\n\nexport interface PayloadStore {\n [s: string]: Payload\n}\n\n@creatableModule()\nexport class IndexedDbArchivist<\n TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n> extends AbstractArchivist<TParams, TEventData> {\n static override configSchemas: Schema[] = [...super.configSchemas, IndexedDbArchivistConfigSchema]\n static override defaultConfigSchema: Schema = IndexedDbArchivistConfigSchema\n static readonly defaultDbName = 'archivist'\n static readonly defaultDbVersion = 1\n static readonly defaultStoreName = 'payloads'\n private static readonly dataHashIndex: IndexDescription = { key: { $hash: 1 }, multiEntry: false, unique: false }\n private static readonly hashIndex: IndexDescription = { key: { _hash: 1 }, multiEntry: false, unique: true }\n private static readonly schemaIndex: IndexDescription = { key: { schema: 1 }, multiEntry: false, unique: false }\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly hashIndexName = buildStandardIndexName(IndexedDbArchivist.hashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly dataHashIndexName = buildStandardIndexName(IndexedDbArchivist.dataHashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly schemaIndexName = buildStandardIndexName(IndexedDbArchivist.schemaIndex)\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the module name (not guaranteed to be unique) and if module\n * name is not supplied, it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.name ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to 1.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n override get queries() {\n return [ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, ...super.queries]\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n /**\n * The indexes to create on the store\n */\n private get indexes() {\n return [IndexedDbArchivist.dataHashIndex, IndexedDbArchivist.hashIndex, IndexedDbArchivist.schemaIndex, ...(this.config?.storage?.indexes ?? [])]\n }\n\n protected override async allHandler(): Promise<PayloadWithMeta[]> {\n // Get all payloads from the store\n const payloads = await this.useDb((db) => db.getAll(this.storeName))\n // Remove any metadata before returning to the client\n return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)))\n }\n\n protected override async clearHandler(): Promise<void> {\n await this.useDb((db) => db.clear(this.storeName))\n }\n\n protected override async deleteHandler(hashes: Hash[]): Promise<Hash[]> {\n const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes))\n const hashesToDelete = pairs.flatMap<Hash>((pair) => [pair[0].$hash, pair[1]])\n // Remove any duplicates\n const distinctHashes = [...new Set(hashesToDelete)]\n return await this.useDb(async (db) => {\n // Only return hashes that were successfully deleted\n const found = await Promise.all(\n distinctHashes.map(async (hash) => {\n // Check if the hash exists\n const existing =\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.hashIndexName, hash)) ??\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.dataHashIndexName, hash))\n // If it does exist\n if (existing) {\n // Delete it\n await db.delete(this.storeName, existing)\n // Return the hash so it gets added to the list of deleted hashes\n return hash\n }\n }),\n )\n return found.filter(exists).filter((hash) => hashes.includes(hash))\n })\n }\n\n /**\n * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)\n * @param db The db instance to use\n * @param storeName The name of the store to use\n * @param indexName The index to use\n * @param key The key to get from the index\n * @returns The primary key and the payload, or undefined if not found\n */\n protected async getFromIndexWithPrimaryKey(\n db: IDBPDatabase<PayloadStore>,\n storeName: string,\n indexName: string,\n key: IDBValidKey,\n ): Promise<[number, PayloadWithMeta] | undefined> {\n const transaction = db.transaction(storeName, 'readonly')\n const store = transaction.objectStore(storeName)\n const index = store.index(indexName)\n const cursor = await index.openCursor(key)\n if (cursor) {\n const singleValue = cursor.value\n // NOTE: It's known to be a number because we are using IndexedDB supplied auto-incrementing keys\n if (typeof cursor.primaryKey !== 'number') {\n throw new TypeError('primaryKey must be a number')\n }\n\n return [cursor.primaryKey, singleValue]\n }\n }\n\n protected override async getHandler(hashes: string[]): Promise<PayloadWithMeta[]> {\n const payloads = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.hashIndexName, hash))),\n )\n const payloadsFromDataHashes = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.dataHashIndexName, hash))),\n )\n //filter out duplicates\n const found = new Set<string>()\n const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n return (\n // Merge what we found from the hash and data hash indexes\n [...payloadsFromHash, ...payloadsFromDataHash]\n // Sort in ascending order by primary key (for semi-predictable ordering in terms of insertion order)\n .sort((a, b) => a[0] - b[0])\n // Return just the payloads\n .map(([_key, payload]) => payload)\n )\n }\n\n protected override async insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]> {\n const pairs = await PayloadBuilder.hashPairs(payloads)\n\n const db = await this.getInitializedDb()\n try {\n // Only return the payloads that were successfully inserted\n const inserted = await Promise.all(\n pairs.map(async ([payload, _hash]) => {\n const existing = (await this.getHandler([_hash])).shift()\n if (existing) {\n return\n }\n // Perform each insert via a transaction to ensure it is atomic\n // with respect to checking for the pre-existence of the hash.\n // This is done to preserve iteration via insertion order.\n const tx = db.transaction(this.storeName, 'readwrite')\n try {\n // Get the object store\n const store = tx.objectStore(this.storeName)\n\n // Check if the hash already exists\n const existingTopHash = await store.index(IndexedDbArchivist.hashIndexName).get(_hash)\n // If it does not already exist\n if (!existingTopHash) {\n // Insert the payload\n await store.put({ ...payload, _hash })\n }\n\n // Return it so it gets added to the list of inserted payloads\n return payload\n } finally {\n // Close the transaction\n await tx.done\n }\n }),\n )\n return inserted.filter(exists)\n } finally {\n db.close()\n }\n }\n\n protected override async startHandler() {\n await super.startHandler()\n // NOTE: We could defer this creation to first access but we\n // want to fail fast here in case something is wrong\n await this.useDb(() => {})\n return true\n }\n\n /**\n * Returns that the desired DB/Store initialized to the correct version\n * @returns The initialized DB\n */\n private async getInitializedDb(): Promise<IDBPDatabase<PayloadStore>> {\n const { dbName, dbVersion, indexes, storeName, logger } = this\n const db = await openDB<PayloadStore>(dbName, dbVersion, {\n blocked(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event)\n },\n blocking(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event)\n },\n terminated() {\n logger.log('IndexedDbArchivist: Terminated')\n },\n upgrade(database, oldVersion, newVersion, transaction) {\n // NOTE: This is called whenever the DB is created/updated. We could simply ensure the desired end\n // state but, out of an abundance of caution, we will just delete (so we know where we are starting\n // from a known good point) and recreate the desired state. This prioritizes resilience over data\n // retention but we can revisit that tradeoff when it becomes limiting. Because distributed browser\n // state is extremely hard to debug, this seems like fair tradeoff for now.\n if (oldVersion !== newVersion) {\n logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`)\n // Delete any existing databases that are not the current version\n const objectStores = transaction.objectStoreNames\n for (const name of objectStores) {\n try {\n database.deleteObjectStore(name)\n } catch {\n logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`)\n }\n }\n }\n // Create the store\n const store = database.createObjectStore(storeName, {\n // If it isn't explicitly set, create a value by auto incrementing.\n autoIncrement: true,\n })\n // Name the store\n store.name = storeName\n // Create an index on the hash\n for (const { key, multiEntry, unique } of indexes) {\n const indexKeys = Object.keys(key)\n const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys\n const indexName = buildStandardIndexName({ key, unique })\n store.createIndex(indexName, keys, { multiEntry, unique })\n }\n },\n })\n return db\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async useDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T> {\n // Get the initialized DB\n const db = await this.getInitializedDb()\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n}\n","export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\nexport const IndexedDbArchivistSchema: IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\n","import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model'\n\nimport { IndexedDbArchivistSchema } from './Schema'\n\nexport type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\nexport const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\n\nexport type IndexedDbArchivistConfig = ArchivistConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbArchivistConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main archivist config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACAA,oBAAuB;AAEvB,gCAAkC;AAClC,6BAQO;AACP,0BAAgC;AAChC,6BAA+B;AAE/B,iBAAqC;;;ACd9B,IAAMA,2BAAqD;;;ACI3D,IAAMC,iCAAiE,GAAGC,wBAAAA;;;;;;;;;;;;;;AFoB1E,IAAMC,sBAAN,MAAMA,4BAGHC,4CAAAA;;;;;;;;EAuBR,IAAIC,SAAS;;AACX,aAAO,UAAKC,WAAL,mBAAaD,aAAU,UAAKC,WA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uB;YAAEzD;YAAKoD;UAAO,CAAA;AACvDlD,gBAAMwD,YAAY3D,WAAWwD,MAAM;YAAEJ;YAAYC;UAAO,CAAA;QAC1D;MACF;IACF,CAAA;AACA,WAAOrF;EACT;;;;;;EAOA,MAAcD,MAAS6F,UAA0E;AAE/F,UAAM5F,KAAK,MAAM,KAAKsD,iBAAgB;AACtC,QAAI;AAEF,aAAO,MAAMsC,SAAS5F,EAAAA;IACxB,UAAA;AAEEA,SAAG+D,MAAK;IACV;EACF;AACF;AAjRUrF;AACR,cAJWD,qBAIKoH,iBAA0B;KAAI,qDAAMA;EAAeC;;AACnE,cALWrH,qBAKKsH,uBAA8BD;AAC9C,cANWrH,qBAMKK,iBAAgB;AAChC,cAPWL,qBAOKO,oBAAmB;AACnC,cARWP,qBAQKc,oBAAmB;AACnC,cATWd,qBASagB,iBAAkC;EAAEwC,KAAK;IAAEf,OAAO;EAAE;EAAGkE,YAAY;EAAOC,QAAQ;AAAM;AAChH,cAVW5G,qBAUaiB,aAA8B;EAAEuC,KAAK;IAAEuB,OAAO;EAAE;EAAG4B,YAAY;EAAOC,QAAQ;AAAK;AAC3G,cAXW5G,qBAWakB,eAAgC;EAAEsC,KAAK;IAAE+D,QAAQ;EAAE;EAAGZ,YAAY;EAAOC,QAAQ;AAAM;;AAE/G,cAbW5G,qBAaKgD,qBAAgBiE,+CAAuBjH,oBAAmBiB,SAAS;;AAEnF,cAfWjB,qBAeKiD,yBAAoBgE,+CAAuBjH,oBAAmBgB,aAAa;;AAE3F,cAjBWhB,qBAiBKwH,uBAAkBP,+CAAuBjH,oBAAmBkB,WAAW;AAjBlF,IAAMlB,qBAAN;AAAMA,qBAAAA,aAAAA;MADZyH,qCAAAA;GACYzH,kBAAAA;","names":["IndexedDbArchivistSchema","IndexedDbArchivistConfigSchema","IndexedDbArchivistSchema","IndexedDbArchivist","AbstractArchivist","dbName","config","name","defaultDbName","dbVersion","defaultDbVersion","queries","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","storeName","defaultStoreName","indexes","dataHashIndex","hashIndex","schemaIndex","storage","allHandler","payloads","useDb","db","getAll","Promise","all","map","payload","PayloadBuilder","build","clearHandler","clear","deleteHandler","hashes","pairs","hashPairs","getHandler","hashesToDelete","flatMap","pair","$hash","distinctHashes","Set","found","hash","existing","getKeyFromIndex","hashIndexName","dataHashIndexName","delete","filter","exists","includes","getFromIndexWithPrimaryKey","indexName","key","transaction","store","objectStore","index","cursor","openCursor","singleValue","value","primaryKey","TypeError","payloadsFromDataHashes","payloadsFromHash","_key","has","add","payloadsFromDataHash","sort","a","b","insertHandler","getInitializedDb","inserted","_hash","shift","tx","existingTopHash","get","put","done","close","startHandler","logger","openDB","blocked","currentVersion","blockedVersion","event","warn","blocking","terminated","log","upgrade","database","oldVersion","newVersion","objectStores","objectStoreNames","deleteObjectStore","createObjectStore","autoIncrement","multiEntry","unique","indexKeys","Object","keys","length","buildStandardIndexName","createIndex","callback","configSchemas","IndexedDbArchivistConfigSchema","defaultConfigSchema","schema","schemaIndexName","creatableModule"]}
|
package/dist/node/index.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
3
|
+
var __reflectGet = Reflect.get;
|
|
2
4
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
5
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
4
6
|
var __publicField = (obj, key, value) => {
|
|
5
7
|
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
6
8
|
return value;
|
|
7
9
|
};
|
|
10
|
+
var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
|
|
8
11
|
|
|
9
12
|
// src/Archivist.ts
|
|
10
13
|
import { exists } from "@xylabs/exists";
|
|
@@ -261,8 +264,10 @@ var _IndexedDbArchivist = class _IndexedDbArchivist extends AbstractArchivist {
|
|
|
261
264
|
};
|
|
262
265
|
__name(_IndexedDbArchivist, "IndexedDbArchivist");
|
|
263
266
|
__publicField(_IndexedDbArchivist, "configSchemas", [
|
|
267
|
+
...__superGet(_IndexedDbArchivist, _IndexedDbArchivist, "configSchemas"),
|
|
264
268
|
IndexedDbArchivistConfigSchema
|
|
265
269
|
]);
|
|
270
|
+
__publicField(_IndexedDbArchivist, "defaultConfigSchema", IndexedDbArchivistConfigSchema);
|
|
266
271
|
__publicField(_IndexedDbArchivist, "defaultDbName", "archivist");
|
|
267
272
|
__publicField(_IndexedDbArchivist, "defaultDbVersion", 1);
|
|
268
273
|
__publicField(_IndexedDbArchivist, "defaultStoreName", "payloads");
|
package/dist/node/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Archivist.ts","../../src/Schema.ts","../../src/Config.ts"],"sourcesContent":["import { exists } from '@xylabs/exists'\nimport { Hash } from '@xylabs/hex'\nimport { AbstractArchivist } from '@xyo-network/archivist-abstract'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistDeleteQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistModuleEventData,\n buildStandardIndexName,\n IndexDescription,\n} from '@xyo-network/archivist-model'\nimport { creatableModule } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload, PayloadWithMeta } from '@xyo-network/payload-model'\nimport { IDBPDatabase, openDB } from 'idb'\n\nimport { IndexedDbArchivistConfigSchema } from './Config'\nimport { IndexedDbArchivistParams } from './Params'\n\nexport interface PayloadStore {\n [s: string]: Payload\n}\n\n@creatableModule()\nexport class IndexedDbArchivist<\n TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n> extends AbstractArchivist<TParams, TEventData> {\n static override configSchemas = [IndexedDbArchivistConfigSchema]\n static readonly defaultDbName = 'archivist'\n static readonly defaultDbVersion = 1\n static readonly defaultStoreName = 'payloads'\n private static readonly dataHashIndex: IndexDescription = { key: { $hash: 1 }, multiEntry: false, unique: false }\n private static readonly hashIndex: IndexDescription = { key: { _hash: 1 }, multiEntry: false, unique: true }\n private static readonly schemaIndex: IndexDescription = { key: { schema: 1 }, multiEntry: false, unique: false }\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly hashIndexName = buildStandardIndexName(IndexedDbArchivist.hashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly dataHashIndexName = buildStandardIndexName(IndexedDbArchivist.dataHashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly schemaIndexName = buildStandardIndexName(IndexedDbArchivist.schemaIndex)\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the module name (not guaranteed to be unique) and if module\n * name is not supplied, it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.name ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to 1.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n override get queries() {\n return [ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, ...super.queries]\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n /**\n * The indexes to create on the store\n */\n private get indexes() {\n return [IndexedDbArchivist.dataHashIndex, IndexedDbArchivist.hashIndex, IndexedDbArchivist.schemaIndex, ...(this.config?.storage?.indexes ?? [])]\n }\n\n protected override async allHandler(): Promise<PayloadWithMeta[]> {\n // Get all payloads from the store\n const payloads = await this.useDb((db) => db.getAll(this.storeName))\n // Remove any metadata before returning to the client\n return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)))\n }\n\n protected override async clearHandler(): Promise<void> {\n await this.useDb((db) => db.clear(this.storeName))\n }\n\n protected override async deleteHandler(hashes: Hash[]): Promise<Hash[]> {\n const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes))\n const hashesToDelete = pairs.flatMap<Hash>((pair) => [pair[0].$hash, pair[1]])\n // Remove any duplicates\n const distinctHashes = [...new Set(hashesToDelete)]\n return await this.useDb(async (db) => {\n // Only return hashes that were successfully deleted\n const found = await Promise.all(\n distinctHashes.map(async (hash) => {\n // Check if the hash exists\n const existing =\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.hashIndexName, hash)) ??\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.dataHashIndexName, hash))\n // If it does exist\n if (existing) {\n // Delete it\n await db.delete(this.storeName, existing)\n // Return the hash so it gets added to the list of deleted hashes\n return hash\n }\n }),\n )\n return found.filter(exists).filter((hash) => hashes.includes(hash))\n })\n }\n\n /**\n * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)\n * @param db The db instance to use\n * @param storeName The name of the store to use\n * @param indexName The index to use\n * @param key The key to get from the index\n * @returns The primary key and the payload, or undefined if not found\n */\n protected async getFromIndexWithPrimaryKey(\n db: IDBPDatabase<PayloadStore>,\n storeName: string,\n indexName: string,\n key: IDBValidKey,\n ): Promise<[number, PayloadWithMeta] | undefined> {\n const transaction = db.transaction(storeName, 'readonly')\n const store = transaction.objectStore(storeName)\n const index = store.index(indexName)\n const cursor = await index.openCursor(key)\n if (cursor) {\n const singleValue = cursor.value\n // NOTE: It's known to be a number because we are using IndexedDB supplied auto-incrementing keys\n if (typeof cursor.primaryKey !== 'number') {\n throw new TypeError('primaryKey must be a number')\n }\n\n return [cursor.primaryKey, singleValue]\n }\n }\n\n protected override async getHandler(hashes: string[]): Promise<PayloadWithMeta[]> {\n const payloads = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.hashIndexName, hash))),\n )\n const payloadsFromDataHashes = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.dataHashIndexName, hash))),\n )\n //filter out duplicates\n const found = new Set<string>()\n const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n return (\n // Merge what we found from the hash and data hash indexes\n [...payloadsFromHash, ...payloadsFromDataHash]\n // Sort in ascending order by primary key (for semi-predictable ordering in terms of insertion order)\n .sort((a, b) => a[0] - b[0])\n // Return just the payloads\n .map(([_key, payload]) => payload)\n )\n }\n\n protected override async insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]> {\n const pairs = await PayloadBuilder.hashPairs(payloads)\n\n const db = await this.getInitializedDb()\n try {\n // Only return the payloads that were successfully inserted\n const inserted = await Promise.all(\n pairs.map(async ([payload, _hash]) => {\n const existing = (await this.getHandler([_hash])).shift()\n if (existing) {\n return\n }\n // Perform each insert via a transaction to ensure it is atomic\n // with respect to checking for the pre-existence of the hash.\n // This is done to preserve iteration via insertion order.\n const tx = db.transaction(this.storeName, 'readwrite')\n try {\n // Get the object store\n const store = tx.objectStore(this.storeName)\n\n // Check if the hash already exists\n const existingTopHash = await store.index(IndexedDbArchivist.hashIndexName).get(_hash)\n // If it does not already exist\n if (!existingTopHash) {\n // Insert the payload\n await store.put({ ...payload, _hash })\n }\n\n // Return it so it gets added to the list of inserted payloads\n return payload\n } finally {\n // Close the transaction\n await tx.done\n }\n }),\n )\n return inserted.filter(exists)\n } finally {\n db.close()\n }\n }\n\n protected override async startHandler() {\n await super.startHandler()\n // NOTE: We could defer this creation to first access but we\n // want to fail fast here in case something is wrong\n await this.useDb(() => {})\n return true\n }\n\n /**\n * Returns that the desired DB/Store initialized to the correct version\n * @returns The initialized DB\n */\n private async getInitializedDb(): Promise<IDBPDatabase<PayloadStore>> {\n const { dbName, dbVersion, indexes, storeName, logger } = this\n const db = await openDB<PayloadStore>(dbName, dbVersion, {\n blocked(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event)\n },\n blocking(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event)\n },\n terminated() {\n logger.log('IndexedDbArchivist: Terminated')\n },\n upgrade(database, oldVersion, newVersion, transaction) {\n // NOTE: This is called whenever the DB is created/updated. We could simply ensure the desired end\n // state but, out of an abundance of caution, we will just delete (so we know where we are starting\n // from a known good point) and recreate the desired state. This prioritizes resilience over data\n // retention but we can revisit that tradeoff when it becomes limiting. Because distributed browser\n // state is extremely hard to debug, this seems like fair tradeoff for now.\n if (oldVersion !== newVersion) {\n logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`)\n // Delete any existing databases that are not the current version\n const objectStores = transaction.objectStoreNames\n for (const name of objectStores) {\n try {\n database.deleteObjectStore(name)\n } catch {\n logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`)\n }\n }\n }\n // Create the store\n const store = database.createObjectStore(storeName, {\n // If it isn't explicitly set, create a value by auto incrementing.\n autoIncrement: true,\n })\n // Name the store\n store.name = storeName\n // Create an index on the hash\n for (const { key, multiEntry, unique } of indexes) {\n const indexKeys = Object.keys(key)\n const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys\n const indexName = buildStandardIndexName({ key, unique })\n store.createIndex(indexName, keys, { multiEntry, unique })\n }\n },\n })\n return db\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async useDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T> {\n // Get the initialized DB\n const db = await this.getInitializedDb()\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n}\n","export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\nexport const IndexedDbArchivistSchema: IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\n","import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model'\n\nimport { IndexedDbArchivistSchema } from './Schema'\n\nexport type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\nexport const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\n\nexport type IndexedDbArchivistConfig = ArchivistConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbArchivistConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main archivist config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n"],"mappings":";;;;;;;;;AAAA,SAASA,cAAc;AAEvB,SAASC,yBAAyB;AAClC,SACEC,yBACAC,2BACAC,4BACAC,4BAEAC,8BAEK;AACP,SAASC,uBAAuB;AAChC,SAASC,sBAAsB;AAE/B,SAAuBC,cAAc;;;ACd9B,IAAMC,2BAAqD;;;ACI3D,IAAMC,iCAAiE,GAAGC,wBAAAA;;;;;;;;;;;;;;AFoB1E,IAAMC,sBAAN,MAAMA,4BAGHC,kBAAAA;;;;;;;;EAsBR,IAAIC,SAAS;;AACX,aAAO,UAAKC,WAAL,mBAAaD,aAAU,UAAKC,WAAL,mBAAaC,SAAQJ,oBAAmBK;EACxE;;;;EAKA,IAAIC,YAAY;;AACd,aAAO,UAAKH,WAAL,mBAAaG,cAAaN,oBAAmBO;EACtD;EAEA,IAAaC,UAAU;AACrB,WAAO;MAACC;MAAyBC;MAA2BC;MAA4BC;SAA+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AAK,MAAM,KAAKsD,iBAAgB;AACtC,QAAI;AAEF,aAAO,MAAMsC,SAAS5F,EAAAA;IACxB,UAAA;AAEEA,SAAG+D,MAAK;IACV;EACF;AACF;AAhRUrF;AACR,cAJWD,qBAIKoH,iBAAgB;EAACC;;AACjC,cALWrH,qBAKKK,iBAAgB;AAChC,cANWL,qBAMKO,oBAAmB;AACnC,cAPWP,qBAOKc,oBAAmB;AACnC,cARWd,qBAQagB,iBAAkC;EAAEwC,KAAK;IAAEf,OAAO;EAAE;EAAGkE,YAAY;EAAOC,QAAQ;AAAM;AAChH,cATW5G,qBASaiB,aAA8B;EAAEuC,KAAK;IAAEuB,OAAO;EAAE;EAAG4B,YAAY;EAAOC,QAAQ;AAAK;AAC3G,cAVW5G,qBAUakB,eAAgC;EAAEsC,KAAK;IAAE8D,QAAQ;EAAE;EAAGX,YAAY;EAAOC,QAAQ;AAAM;;AAE/G,cAZW5G,qBAYKgD,iBAAgBiE,uBAAuBjH,oBAAmBiB,SAAS;;AAEnF,cAdWjB,qBAcKiD,qBAAoBgE,uBAAuBjH,oBAAmBgB,aAAa;;AAE3F,cAhBWhB,qBAgBKuH,mBAAkBN,uBAAuBjH,oBAAmBkB,WAAW;AAhBlF,IAAMlB,qBAAN;AAAMA,qBAAAA,aAAAA;EADZwH,gBAAAA;GACYxH,kBAAAA;","names":["exists","AbstractArchivist","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","buildStandardIndexName","creatableModule","PayloadBuilder","openDB","IndexedDbArchivistSchema","IndexedDbArchivistConfigSchema","IndexedDbArchivistSchema","IndexedDbArchivist","AbstractArchivist","dbName","config","name","defaultDbName","dbVersion","defaultDbVersion","queries","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","storeName","defaultStoreName","indexes","dataHashIndex","hashIndex","schemaIndex","storage","allHandler","payloads","useDb","db","getAll","Promise","all","map","payload","PayloadBuilder","build","clearHandler","clear","deleteHandler","hashes","pairs","hashPairs","getHandler","hashesToDelete","flatMap","pair","$hash","distinctHashes","Set","found","hash","existing","getKeyFromIndex","hashIndexName","dataHashIndexName","delete","filter","exists","includes","getFromIndexWithPrimaryKey","indexName","key","transaction","store","objectStore","index","cursor","openCursor","singleValue","value","primaryKey","TypeError","payloadsFromDataHashes","payloadsFromHash","_key","has","add","payloadsFromDataHash","sort","a","b","insertHandler","getInitializedDb","inserted","_hash","shift","tx","existingTopHash","get","put","done","close","startHandler","logger","openDB","blocked","currentVersion","blockedVersion","event","warn","blocking","terminated","log","upgrade","database","oldVersion","newVersion","objectStores","objectStoreNames","deleteObjectStore","createObjectStore","autoIncrement","multiEntry","unique","indexKeys","Object","keys","length","buildStandardIndexName","createIndex","callback","configSchemas","IndexedDbArchivistConfigSchema","schema","schemaIndexName","creatableModule"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Archivist.ts","../../src/Schema.ts","../../src/Config.ts"],"sourcesContent":["import { exists } from '@xylabs/exists'\nimport { Hash } from '@xylabs/hex'\nimport { AbstractArchivist } from '@xyo-network/archivist-abstract'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistDeleteQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistModuleEventData,\n buildStandardIndexName,\n IndexDescription,\n} from '@xyo-network/archivist-model'\nimport { creatableModule } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model'\nimport { IDBPDatabase, openDB } from 'idb'\n\nimport { IndexedDbArchivistConfigSchema } from './Config'\nimport { IndexedDbArchivistParams } from './Params'\n\nexport interface PayloadStore {\n [s: string]: Payload\n}\n\n@creatableModule()\nexport class IndexedDbArchivist<\n TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n> extends AbstractArchivist<TParams, TEventData> {\n static override configSchemas: Schema[] = [...super.configSchemas, IndexedDbArchivistConfigSchema]\n static override defaultConfigSchema: Schema = IndexedDbArchivistConfigSchema\n static readonly defaultDbName = 'archivist'\n static readonly defaultDbVersion = 1\n static readonly defaultStoreName = 'payloads'\n private static readonly dataHashIndex: IndexDescription = { key: { $hash: 1 }, multiEntry: false, unique: false }\n private static readonly hashIndex: IndexDescription = { key: { _hash: 1 }, multiEntry: false, unique: true }\n private static readonly schemaIndex: IndexDescription = { key: { schema: 1 }, multiEntry: false, unique: false }\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly hashIndexName = buildStandardIndexName(IndexedDbArchivist.hashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly dataHashIndexName = buildStandardIndexName(IndexedDbArchivist.dataHashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly schemaIndexName = buildStandardIndexName(IndexedDbArchivist.schemaIndex)\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the module name (not guaranteed to be unique) and if module\n * name is not supplied, it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.name ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to 1.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n override get queries() {\n return [ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, ...super.queries]\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n /**\n * The indexes to create on the store\n */\n private get indexes() {\n return [IndexedDbArchivist.dataHashIndex, IndexedDbArchivist.hashIndex, IndexedDbArchivist.schemaIndex, ...(this.config?.storage?.indexes ?? [])]\n }\n\n protected override async allHandler(): Promise<PayloadWithMeta[]> {\n // Get all payloads from the store\n const payloads = await this.useDb((db) => db.getAll(this.storeName))\n // Remove any metadata before returning to the client\n return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)))\n }\n\n protected override async clearHandler(): Promise<void> {\n await this.useDb((db) => db.clear(this.storeName))\n }\n\n protected override async deleteHandler(hashes: Hash[]): Promise<Hash[]> {\n const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes))\n const hashesToDelete = pairs.flatMap<Hash>((pair) => [pair[0].$hash, pair[1]])\n // Remove any duplicates\n const distinctHashes = [...new Set(hashesToDelete)]\n return await this.useDb(async (db) => {\n // Only return hashes that were successfully deleted\n const found = await Promise.all(\n distinctHashes.map(async (hash) => {\n // Check if the hash exists\n const existing =\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.hashIndexName, hash)) ??\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.dataHashIndexName, hash))\n // If it does exist\n if (existing) {\n // Delete it\n await db.delete(this.storeName, existing)\n // Return the hash so it gets added to the list of deleted hashes\n return hash\n }\n }),\n )\n return found.filter(exists).filter((hash) => hashes.includes(hash))\n })\n }\n\n /**\n * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)\n * @param db The db instance to use\n * @param storeName The name of the store to use\n * @param indexName The index to use\n * @param key The key to get from the index\n * @returns The primary key and the payload, or undefined if not found\n */\n protected async getFromIndexWithPrimaryKey(\n db: IDBPDatabase<PayloadStore>,\n storeName: string,\n indexName: string,\n key: IDBValidKey,\n ): Promise<[number, PayloadWithMeta] | undefined> {\n const transaction = db.transaction(storeName, 'readonly')\n const store = transaction.objectStore(storeName)\n const index = store.index(indexName)\n const cursor = await index.openCursor(key)\n if (cursor) {\n const singleValue = cursor.value\n // NOTE: It's known to be a number because we are using IndexedDB supplied auto-incrementing keys\n if (typeof cursor.primaryKey !== 'number') {\n throw new TypeError('primaryKey must be a number')\n }\n\n return [cursor.primaryKey, singleValue]\n }\n }\n\n protected override async getHandler(hashes: string[]): Promise<PayloadWithMeta[]> {\n const payloads = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.hashIndexName, hash))),\n )\n const payloadsFromDataHashes = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.dataHashIndexName, hash))),\n )\n //filter out duplicates\n const found = new Set<string>()\n const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n return (\n // Merge what we found from the hash and data hash indexes\n [...payloadsFromHash, ...payloadsFromDataHash]\n // Sort in ascending order by primary key (for semi-predictable ordering in terms of insertion order)\n .sort((a, b) => a[0] - b[0])\n // Return just the payloads\n .map(([_key, payload]) => payload)\n )\n }\n\n protected override async insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]> {\n const pairs = await PayloadBuilder.hashPairs(payloads)\n\n const db = await this.getInitializedDb()\n try {\n // Only return the payloads that were successfully inserted\n const inserted = await Promise.all(\n pairs.map(async ([payload, _hash]) => {\n const existing = (await this.getHandler([_hash])).shift()\n if (existing) {\n return\n }\n // Perform each insert via a transaction to ensure it is atomic\n // with respect to checking for the pre-existence of the hash.\n // This is done to preserve iteration via insertion order.\n const tx = db.transaction(this.storeName, 'readwrite')\n try {\n // Get the object store\n const store = tx.objectStore(this.storeName)\n\n // Check if the hash already exists\n const existingTopHash = await store.index(IndexedDbArchivist.hashIndexName).get(_hash)\n // If it does not already exist\n if (!existingTopHash) {\n // Insert the payload\n await store.put({ ...payload, _hash })\n }\n\n // Return it so it gets added to the list of inserted payloads\n return payload\n } finally {\n // Close the transaction\n await tx.done\n }\n }),\n )\n return inserted.filter(exists)\n } finally {\n db.close()\n }\n }\n\n protected override async startHandler() {\n await super.startHandler()\n // NOTE: We could defer this creation to first access but we\n // want to fail fast here in case something is wrong\n await this.useDb(() => {})\n return true\n }\n\n /**\n * Returns that the desired DB/Store initialized to the correct version\n * @returns The initialized DB\n */\n private async getInitializedDb(): Promise<IDBPDatabase<PayloadStore>> {\n const { dbName, dbVersion, indexes, storeName, logger } = this\n const db = await openDB<PayloadStore>(dbName, dbVersion, {\n blocked(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event)\n },\n blocking(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event)\n },\n terminated() {\n logger.log('IndexedDbArchivist: Terminated')\n },\n upgrade(database, oldVersion, newVersion, transaction) {\n // NOTE: This is called whenever the DB is created/updated. We could simply ensure the desired end\n // state but, out of an abundance of caution, we will just delete (so we know where we are starting\n // from a known good point) and recreate the desired state. This prioritizes resilience over data\n // retention but we can revisit that tradeoff when it becomes limiting. Because distributed browser\n // state is extremely hard to debug, this seems like fair tradeoff for now.\n if (oldVersion !== newVersion) {\n logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`)\n // Delete any existing databases that are not the current version\n const objectStores = transaction.objectStoreNames\n for (const name of objectStores) {\n try {\n database.deleteObjectStore(name)\n } catch {\n logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`)\n }\n }\n }\n // Create the store\n const store = database.createObjectStore(storeName, {\n // If it isn't explicitly set, create a value by auto incrementing.\n autoIncrement: true,\n })\n // Name the store\n store.name = storeName\n // Create an index on the hash\n for (const { key, multiEntry, unique } of indexes) {\n const indexKeys = Object.keys(key)\n const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys\n const indexName = buildStandardIndexName({ key, unique })\n store.createIndex(indexName, keys, { multiEntry, unique })\n }\n },\n })\n return db\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async useDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T> {\n // Get the initialized DB\n const db = await this.getInitializedDb()\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n}\n","export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\nexport const IndexedDbArchivistSchema: IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\n","import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model'\n\nimport { IndexedDbArchivistSchema } from './Schema'\n\nexport type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\nexport const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\n\nexport type IndexedDbArchivistConfig = ArchivistConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbArchivistConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main archivist config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n"],"mappings":";;;;;;;;;;;;AAAA,SAASA,cAAc;AAEvB,SAASC,yBAAyB;AAClC,SACEC,yBACAC,2BACAC,4BACAC,4BAEAC,8BAEK;AACP,SAASC,uBAAuB;AAChC,SAASC,sBAAsB;AAE/B,SAAuBC,cAAc;;;ACd9B,IAAMC,2BAAqD;;;ACI3D,IAAMC,iCAAiE,GAAGC,wBAAAA;;;;;;;;;;;;;;AFoB1E,IAAMC,sBAAN,MAAMA,4BAGHC,kBAAAA;;;;;;;;EAuBR,IAAIC,SAAS;;AACX,aAAO,UAAKC,WAAL,mBAAaD,aAAU,UAAKC,WAAL,mBAAaC,SAAQJ,oBAAmBK;EACxE;;;;EAKA,IAAIC,YAAY;;AACd,aAAO,UAAKH,WAAL,mBAAaG,cAAa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MACF;IACF,CAAA;AACA,WAAOrF;EACT;;;;;;EAOA,MAAcD,MAAS6F,UAA0E;AAE/F,UAAM5F,KAAK,MAAM,KAAKsD,iBAAgB;AACtC,QAAI;AAEF,aAAO,MAAMsC,SAAS5F,EAAAA;IACxB,UAAA;AAEEA,SAAG+D,MAAK;IACV;EACF;AACF;AAjRUrF;AACR,cAJWD,qBAIKoH,iBAA0B;KAAI,qDAAMA;EAAeC;;AACnE,cALWrH,qBAKKsH,uBAA8BD;AAC9C,cANWrH,qBAMKK,iBAAgB;AAChC,cAPWL,qBAOKO,oBAAmB;AACnC,cARWP,qBAQKc,oBAAmB;AACnC,cATWd,qBASagB,iBAAkC;EAAEwC,KAAK;IAAEf,OAAO;EAAE;EAAGkE,YAAY;EAAOC,QAAQ;AAAM;AAChH,cAVW5G,qBAUaiB,aAA8B;EAAEuC,KAAK;IAAEuB,OAAO;EAAE;EAAG4B,YAAY;EAAOC,QAAQ;AAAK;AAC3G,cAXW5G,qBAWakB,eAAgC;EAAEsC,KAAK;IAAE+D,QAAQ;EAAE;EAAGZ,YAAY;EAAOC,QAAQ;AAAM;;AAE/G,cAbW5G,qBAaKgD,iBAAgBiE,uBAAuBjH,oBAAmBiB,SAAS;;AAEnF,cAfWjB,qBAeKiD,qBAAoBgE,uBAAuBjH,oBAAmBgB,aAAa;;AAE3F,cAjBWhB,qBAiBKwH,mBAAkBP,uBAAuBjH,oBAAmBkB,WAAW;AAjBlF,IAAMlB,qBAAN;AAAMA,qBAAAA,aAAAA;EADZyH,gBAAAA;GACYzH,kBAAAA;","names":["exists","AbstractArchivist","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","buildStandardIndexName","creatableModule","PayloadBuilder","openDB","IndexedDbArchivistSchema","IndexedDbArchivistConfigSchema","IndexedDbArchivistSchema","IndexedDbArchivist","AbstractArchivist","dbName","config","name","defaultDbName","dbVersion","defaultDbVersion","queries","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","storeName","defaultStoreName","indexes","dataHashIndex","hashIndex","schemaIndex","storage","allHandler","payloads","useDb","db","getAll","Promise","all","map","payload","PayloadBuilder","build","clearHandler","clear","deleteHandler","hashes","pairs","hashPairs","getHandler","hashesToDelete","flatMap","pair","$hash","distinctHashes","Set","found","hash","existing","getKeyFromIndex","hashIndexName","dataHashIndexName","delete","filter","exists","includes","getFromIndexWithPrimaryKey","indexName","key","transaction","store","objectStore","index","cursor","openCursor","singleValue","value","primaryKey","TypeError","payloadsFromDataHashes","payloadsFromHash","_key","has","add","payloadsFromDataHash","sort","a","b","insertHandler","getInitializedDb","inserted","_hash","shift","tx","existingTopHash","get","put","done","close","startHandler","logger","openDB","blocked","currentVersion","blockedVersion","event","warn","blocking","terminated","log","upgrade","database","oldVersion","newVersion","objectStores","objectStoreNames","deleteObjectStore","createObjectStore","autoIncrement","multiEntry","unique","indexKeys","Object","keys","length","buildStandardIndexName","createIndex","callback","configSchemas","IndexedDbArchivistConfigSchema","defaultConfigSchema","schema","schemaIndexName","creatableModule"]}
|
package/package.json
CHANGED
|
@@ -12,19 +12,19 @@
|
|
|
12
12
|
"dependencies": {
|
|
13
13
|
"@xylabs/exists": "^3.1.8",
|
|
14
14
|
"@xylabs/hex": "^3.1.8",
|
|
15
|
-
"@xyo-network/archivist-abstract": "~2.
|
|
16
|
-
"@xyo-network/archivist-model": "~2.
|
|
17
|
-
"@xyo-network/module-model": "~2.
|
|
18
|
-
"@xyo-network/payload-builder": "~2.
|
|
19
|
-
"@xyo-network/payload-model": "~2.
|
|
15
|
+
"@xyo-network/archivist-abstract": "~2.97.0",
|
|
16
|
+
"@xyo-network/archivist-model": "~2.97.0",
|
|
17
|
+
"@xyo-network/module-model": "~2.97.0",
|
|
18
|
+
"@xyo-network/payload-builder": "~2.97.0",
|
|
19
|
+
"@xyo-network/payload-model": "~2.97.0",
|
|
20
20
|
"idb": "^8.0.0"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
23
|
"@xylabs/ts-scripts-yarn3": "^3.9.1",
|
|
24
24
|
"@xylabs/tsconfig": "^3.9.1",
|
|
25
|
-
"@xyo-network/account": "~2.
|
|
26
|
-
"@xyo-network/id-payload-plugin": "~2.
|
|
27
|
-
"@xyo-network/payload-wrapper": "~2.
|
|
25
|
+
"@xyo-network/account": "~2.97.0",
|
|
26
|
+
"@xyo-network/id-payload-plugin": "~2.97.0",
|
|
27
|
+
"@xyo-network/payload-wrapper": "~2.97.0",
|
|
28
28
|
"fake-indexeddb": "^5.0.2",
|
|
29
29
|
"typescript": "^5.4.5"
|
|
30
30
|
},
|
|
@@ -67,6 +67,6 @@
|
|
|
67
67
|
"url": "https://github.com/XYOracleNetwork/sdk-xyo-client-js.git"
|
|
68
68
|
},
|
|
69
69
|
"sideEffects": false,
|
|
70
|
-
"version": "2.
|
|
70
|
+
"version": "2.97.0",
|
|
71
71
|
"type": "module"
|
|
72
72
|
}
|
package/src/Archivist.ts
CHANGED
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
} from '@xyo-network/archivist-model'
|
|
13
13
|
import { creatableModule } from '@xyo-network/module-model'
|
|
14
14
|
import { PayloadBuilder } from '@xyo-network/payload-builder'
|
|
15
|
-
import { Payload, PayloadWithMeta } from '@xyo-network/payload-model'
|
|
15
|
+
import { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model'
|
|
16
16
|
import { IDBPDatabase, openDB } from 'idb'
|
|
17
17
|
|
|
18
18
|
import { IndexedDbArchivistConfigSchema } from './Config'
|
|
@@ -27,7 +27,8 @@ export class IndexedDbArchivist<
|
|
|
27
27
|
TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,
|
|
28
28
|
TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,
|
|
29
29
|
> extends AbstractArchivist<TParams, TEventData> {
|
|
30
|
-
static override configSchemas = [IndexedDbArchivistConfigSchema]
|
|
30
|
+
static override configSchemas: Schema[] = [...super.configSchemas, IndexedDbArchivistConfigSchema]
|
|
31
|
+
static override defaultConfigSchema: Schema = IndexedDbArchivistConfigSchema
|
|
31
32
|
static readonly defaultDbName = 'archivist'
|
|
32
33
|
static readonly defaultDbVersion = 1
|
|
33
34
|
static readonly defaultStoreName = 'payloads'
|