From b40de269b9e8e178f11b098f6eb3112e4c5d53d6 Mon Sep 17 00:00:00 2001 From: Greg Baker Date: Thu, 10 Feb 2022 10:16:34 -0800 Subject: [PATCH] refactor: Rename ReplicacheOptions.userID and Replicache.userID back to name. (#835) This reverts commit d95d8bf18d84dc465f2cbe58069668fc86a2a6cd. We realized we will need both a userID, and another identifier to support multiple Replicache instance for the same user (e.g. roomID). We will do this api change in v10 rather than v9. Added details to documentation for `name` around Replicache bootsrapping and mutation recovery. --- doc/docs/launch-checklist.md | 12 +++++-- perf/replicache.ts | 26 +++++++------- src/persist/idb-databases-store.test.ts | 10 +++--- src/persist/idb-databases-store.ts | 4 +-- src/replicache-mutation-recovery.test.ts | 30 ++++++++-------- src/replicache-options.ts | 25 +++++++------ src/replicache-types.test.ts | 22 ++++++------ src/replicache.test.ts | 34 +++++++++--------- src/replicache.ts | 38 ++++++++------------ src/test-util.ts | 45 +++++++++++++----------- src/worker-tests/worker-test.ts | 8 ++--- 11 files changed, 131 insertions(+), 123 deletions(-) diff --git a/doc/docs/launch-checklist.md b/doc/docs/launch-checklist.md index f6ed8ceb..786923cb 100644 --- a/doc/docs/launch-checklist.md +++ b/doc/docs/launch-checklist.md @@ -36,8 +36,16 @@ Before you launch with Replicache in your product, it's a good idea to double-ch cookie values across clients, resulting in new clients being able to startup from previous clients' state with minimal download at startup. - The `name` property of `ReplicacheOptions` is required to differentiate - Replicache instances for different users; otherwise Replicache may try to fork - state from a different user at startup. + Replicache instances for different users. This is important for the following + reasons: + - For efficiency and performance, a new [[Replicache]] instance will + initialize its state from the persisted state of an existing [[Replicache]] + instance with the same `name`, domain and browser profile. + - Mutations from one [[Replicache]] instance may be pushed using the + [[ReplicacheOptions.auth]], [[ReplicacheOptions.pushURL]], + [[ReplicacheOptions.pullURL]], [[ReplicacheOptions.pusher]], and + [[ReplicacheOptions.puller]] of another Replicache instance with the same + `name`, domain and browser profile. ## All endpoints diff --git a/perf/replicache.ts b/perf/replicache.ts index 292f26f1..0985d33c 100644 --- a/perf/replicache.ts +++ b/perf/replicache.ts @@ -72,7 +72,7 @@ class ReplicacheWithPersist extends Replicache { } async function setupPersistedData( - userID: string, + replicacheName: string, numKeys: number, ): Promise { const randomValues = jsonArrayTestData(numKeys, valSize); @@ -92,7 +92,7 @@ async function setupPersistedData( // so that a snapshot commit is created, which new clients // can use to bootstrap. const rep = (repToClose = new ReplicacheWithPersist({ - userID, + name: replicacheName, pullInterval: null, puller: async (_: Request) => { return { @@ -124,14 +124,14 @@ export function benchmarkStartupUsingBasicReadsFromPersistedData(opts: { numKeysPersisted: number; numKeysToRead: number; }): Benchmark { - const userID = makeUserID(); + const repName = makeRepName(); let repToClose: Replicache | undefined; return { name: `startup read ${valSize}x${opts.numKeysToRead} from ${valSize}x${opts.numKeysPersisted} stored`, group: 'replicache', byteSize: opts.numKeysToRead * valSize, async setup() { - await setupPersistedData(userID, opts.numKeysPersisted); + await setupPersistedData(repName, opts.numKeysPersisted); }, async setupEach() { setupIDBDatabasesStoreForTest(); @@ -150,7 +150,7 @@ export function benchmarkStartupUsingBasicReadsFromPersistedData(opts: { ).map(i => `key${i}`); bencher.reset(); const rep = (repToClose = new Replicache({ - userID, + name: repName, pullInterval: null, })); let getCount = 0; @@ -172,14 +172,14 @@ export function benchmarkStartupUsingScanFromPersistedData(opts: { numKeysPersisted: number; numKeysToRead: number; }): Benchmark { - const userID = makeUserID(); + const repName = makeRepName(); let repToClose: Replicache | undefined; return { name: `startup scan ${valSize}x${opts.numKeysToRead} from ${valSize}x${opts.numKeysPersisted} stored`, group: 'replicache', byteSize: opts.numKeysToRead * valSize, async setup() { - await setupPersistedData(userID, opts.numKeysPersisted); + await setupPersistedData(repName, opts.numKeysPersisted); }, async setupEach() { setupIDBDatabasesStoreForTest(); @@ -203,7 +203,7 @@ export function benchmarkStartupUsingScanFromPersistedData(opts: { const randomStartKey = sortedKeys[randomIndex]; bencher.reset(); const rep = (repToClose = new Replicache({ - userID, + name: repName, pullInterval: null, })); await rep.query(async (tx: ReadTransaction) => { @@ -441,16 +441,16 @@ export function benchmarkWriteSubRead(opts: { }; } -function makeUserID(): string { - return `user-${uuid()}`; +function makeRepName(): string { + return `bench${uuid()}`; } function makeRep( - options: Omit, 'userID'> = {}, + options: Omit, 'name'> = {}, ) { - const userID = makeUserID(); + const name = makeRepName(); return new Replicache({ - userID, + name, pullInterval: null, ...options, }); diff --git a/src/persist/idb-databases-store.test.ts b/src/persist/idb-databases-store.test.ts index 9ec95978..4d31b1a0 100644 --- a/src/persist/idb-databases-store.test.ts +++ b/src/persist/idb-databases-store.test.ts @@ -11,7 +11,7 @@ test('putDatabase with no existing record in db', async () => { const store = new IDBDatabasesStore(_ => new TestMemStore()); const testDB = { name: 'testName', - userID: 'testUserID', + replicacheName: 'testReplicacheName', replicacheFormatVersion: 1, schemaVersion: 'testSchemaVersion', }; @@ -27,7 +27,7 @@ test('putDatabase sequence', async () => { const store = new IDBDatabasesStore(_ => new TestMemStore()); const testDB1 = { name: 'testName1', - userID: 'testUserID1', + replicacheName: 'testReplicacheName1', replicacheFormatVersion: 1, schemaVersion: 'testSchemaVersion1', }; @@ -41,7 +41,7 @@ test('putDatabase sequence', async () => { const testDB2 = { name: 'testName2', - userID: 'testUserID2', + replicacheName: 'testReplicacheName2', replicacheFormatVersion: 2, schemaVersion: 'testSchemaVersion2', }; @@ -68,7 +68,7 @@ test('clear', async () => { const store = new IDBDatabasesStore(_ => new TestMemStore()); const testDB1 = { name: 'testName1', - userID: 'testUserID1', + replicacheName: 'testReplicacheName1', replicacheFormatVersion: 1, schemaVersion: 'testSchemaVersion1', }; @@ -86,7 +86,7 @@ test('clear', async () => { const testDB2 = { name: 'testName2', - userID: 'testUserID2', + replicacheName: 'testReplicacheName2', replicacheFormatVersion: 2, schemaVersion: 'testSchemaVersion2', }; diff --git a/src/persist/idb-databases-store.ts b/src/persist/idb-databases-store.ts index ecca4897..7e7dbf9a 100644 --- a/src/persist/idb-databases-store.ts +++ b/src/persist/idb-databases-store.ts @@ -27,7 +27,7 @@ export type IndexedDBName = string; export type IndexedDBDatabase = { name: IndexedDBName; - userID: string; + replicacheName: string; replicacheFormatVersion: number; schemaVersion: string; }; @@ -50,7 +50,7 @@ function assertIndexedDBDatabase( ): asserts value is IndexedDBDatabase { assertObject(value); assertString(value.name); - assertString(value.userID); + assertString(value.replicacheName); assertNumber(value.replicacheFormatVersion); assertString(value.schemaVersion); } diff --git a/src/replicache-mutation-recovery.test.ts b/src/replicache-mutation-recovery.test.ts index b58a9ca7..24f47695 100644 --- a/src/replicache-mutation-recovery.test.ts +++ b/src/replicache-mutation-recovery.test.ts @@ -4,7 +4,7 @@ import { tickAFewTimes, dbsToDrop, clock, - createUserIDForTest, + createReplicacheNameForTest, } from './test-util'; import {makeIdbName, REPLICACHE_FORMAT_VERSION} from './replicache'; import {addGenesis, addLocal, addSnapshot, Chain} from './db/test-helpers'; @@ -38,11 +38,11 @@ teardown(async () => { }); async function createPerdag(args: { - userID: string; + replicacheName: string; schemaVersion: string; }): Promise { - const {userID, schemaVersion} = args; - const idbName = makeIdbName(userID, schemaVersion); + const {replicacheName, schemaVersion} = args; + const idbName = makeIdbName(replicacheName, schemaVersion); dbsToDrop.add(idbName); const idb = new kv.IDBStore(idbName); @@ -50,7 +50,7 @@ async function createPerdag(args: { try { await idbDatabases.putDatabase({ name: idbName, - userID, + replicacheName, schemaVersion, replicacheFormatVersion: REPLICACHE_FORMAT_VERSION, }); @@ -137,7 +137,7 @@ async function testRecoveringMutationsOfClient(args: { await tickAFewTimes(); const testPerdag = await createPerdag({ - userID: rep.userID, + replicacheName: rep.name, schemaVersion: schemaVersionOfClientWPendingMutations, }); @@ -250,7 +250,9 @@ test('client does not attempt to recover mutations from IndexedDB with different await tickAFewTimes(); const testPerdag = await createPerdag({ - userID: createUserIDForTest(replicachePartialNameOfClientWPendingMutations), + replicacheName: createReplicacheNameForTest( + replicachePartialNameOfClientWPendingMutations, + ), schemaVersion, }); @@ -305,7 +307,7 @@ test('successfully recovering mutations of multiple clients with mix of schema v await tickAFewTimes(); const testPerdagForClients1Thru3 = await createPerdag({ - userID: rep.userID, + replicacheName: rep.name, schemaVersion: schemaVersionOfClients1Thru3AndClientRecoveringMutations, }); @@ -327,7 +329,7 @@ test('successfully recovering mutations of multiple clients with mix of schema v ); const testPerdagForClient4 = await createPerdag({ - userID: rep.userID, + replicacheName: rep.name, schemaVersion: schemaVersionOfClient4, }); const client4PendingLocalMetas = await createAndPersistClientWithPendingLocal( @@ -493,7 +495,7 @@ test('if a push error occurs, continues to try to recover other clients', async await tickAFewTimes(); const testPerdag = await createPerdag({ - userID: rep.userID, + replicacheName: rep.name, schemaVersion, }); @@ -645,7 +647,7 @@ test('if an error occurs recovering one client, continues to try to recover othe await tickAFewTimes(); const testPerdag = await createPerdag({ - userID: rep.userID, + replicacheName: rep.name, schemaVersion, }); @@ -785,7 +787,7 @@ test('if an error occurs recovering one db, continues to try to recover clients await tickAFewTimes(); const testPerdagForClient1 = await createPerdag({ - userID: rep.userID, + replicacheName: rep.name, schemaVersion: schemaVersionOfClient1, }); await createAndPersistClientWithPendingLocal( @@ -795,7 +797,7 @@ test('if an error occurs recovering one db, continues to try to recover clients ); const testPerdagForClient2 = await createPerdag({ - userID: rep.userID, + replicacheName: rep.name, schemaVersion: schemaVersionOfClient2, }); const client2PendingLocalMetas = await createAndPersistClientWithPendingLocal( @@ -907,7 +909,7 @@ test('mutation recovery exits early if Replicache is closed', async () => { await tickAFewTimes(); const testPerdag = await createPerdag({ - userID: rep.userID, + replicacheName: rep.name, schemaVersion, }); diff --git a/src/replicache-options.ts b/src/replicache-options.ts index 6919a598..4eec42cf 100644 --- a/src/replicache-options.ts +++ b/src/replicache-options.ts @@ -37,20 +37,25 @@ export interface ReplicacheOptions { pullURL?: string; /** - * A unique identifier for the user authenticated by - * [[ReplicacheOptions.auth]]. Must be non-empty. + * The name of the Replicache database. * - * This is used to keep different user's state separate. + * It is important to use user specific names so that if there are multiple + * tabs open for different distinct users their data is kept separate. * - * For efficiency, a new Replicache instance will initialize its state from - * the persisted state of an existing Replicache instance with the same - * `userID`, domain and browser profile. + * For efficiency and performance, a new [[Replicache]] instance will + * initialize its state from the persisted state of an existing [[Replicache]] + * instance with the same `name`, domain and browser profile. * - * Mutations from one Replicache instance may be pushed using the - * [[ReplicacheOptions.auth]] of another Replicache instance with the same - * `userID`, domain and browser profile. + * Mutations from one [[Replicache]] instance may be pushed using the + * [[ReplicacheOptions.auth]], [[ReplicacheOptions.pushURL]], + * [[ReplicacheOptions.pullURL]], [[ReplicacheOptions.pusher]], and + * [[ReplicacheOptions.puller]] of another Replicache instance with the same + * `name`, domain and browser profile. + * + * You can use multiple Replicache instances for the same user as long as the + * names are unique. e.g. `name: `$userID:$roomID` */ - userID: string; + name: string; /** * The schema version of the data understood by this application. This enables diff --git a/src/replicache-types.test.ts b/src/replicache-types.test.ts index 5a696ce4..6a36f620 100644 --- a/src/replicache-types.test.ts +++ b/src/replicache-types.test.ts @@ -4,7 +4,7 @@ import type {WriteTransaction} from './transactions'; // Only used for type checking test.skip('mutator optional args [type checking only]', async () => { const rep = new Replicache({ - userID: 'test-types', + name: 'test-types', mutators: { mut: async (tx: WriteTransaction, x: number) => { console.log(tx); @@ -45,7 +45,7 @@ test.skip('mutator optional args [type checking only]', async () => { console.log(res4); // This should be an error! - // new Replicache({userID: 'test-types-2', { + // new Replicache({name: 'test-types-2', { // mutators: { // // @ts-expect-error symbol is not a JSONValue // mut5: (tx: WriteTransaction, x: symbol) => { @@ -59,7 +59,7 @@ test.skip('mutator optional args [type checking only]', async () => { // Only used for type checking test.skip('Test partial JSONObject [type checking only]', async () => { const rep = new Replicache({ - userID: 'test-types', + name: 'test-types', mutators: { mut: async (tx: WriteTransaction, todo: Partial) => { console.log(tx); @@ -84,7 +84,7 @@ test.skip('Test partial JSONObject [type checking only]', async () => { // Only used for type checking test.skip('Test register param [type checking only]', async () => { const rep = new Replicache({ - userID: 'test-types', + name: 'test-types', mutators: { mut: async (tx: WriteTransaction) => { console.log(tx); @@ -119,7 +119,7 @@ test.skip('Test register param [type checking only]', async () => { /* eslint-enable prefer-destructuring */ new Replicache({ - userID: 'test-types', + name: 'test-types', mutators: { // @ts-expect-error Type '(tx: WriteTransaction, a: string, b: number) => // Promise' is not assignable to type '(tx: WriteTransaction, @@ -133,7 +133,7 @@ test.skip('Test register param [type checking only]', async () => { // Only used for type checking test.skip('Key type for scans [type checking only]', async () => { - const rep = new Replicache({userID: 'test-types'}); + const rep = new Replicache({name: 'test-types'}); for await (const k of rep.scan({indexName: 'n'}).keys()) { // @ts-expect-error Type '[secondary: string, primary?: string | undefined]' is not assignable to type 'string'.ts(2322) @@ -183,7 +183,7 @@ test.skip('mut [type checking only]', async () => { type ToRecord = {[P in keyof T]: T[P]}; const rep = new Replicache({ - userID: 'type-checking-only', + name: 'type-checking-only', mutators: { a: (tx: WriteTransaction) => { console.log(tx); @@ -292,19 +292,19 @@ test.skip('mut [type checking only]', async () => { await rep.mutate.h(null); { - const rep = new Replicache({userID: 'type-checking-only', mutators: {}}); + const rep = new Replicache({name: 'type-checking-only', mutators: {}}); // @ts-expect-error Property 'abc' does not exist on type 'MakeMutators<{}>'.ts(2339) rep.mutate.abc(43); } { - const rep = new Replicache({userID: 'type-checking-only'}); + const rep = new Replicache({name: 'type-checking-only'}); // @ts-expect-error Property 'abc' does not exist on type 'MakeMutators<{}>'.ts(2339) rep.mutate.abc(1, 2, 3); } { - const rep = new Replicache({userID: 'type-checking-only'}); + const rep = new Replicache({name: 'type-checking-only'}); // @ts-expect-error Property 'abc' does not exist on type 'MakeMutators<{}>'.ts(2339) rep.mutate.abc(1, 2, 3); } @@ -312,7 +312,7 @@ test.skip('mut [type checking only]', async () => { // Only used for type checking test.skip('scan with index [type checking only]', async () => { - const rep = new Replicache({userID: 'scan-with-index'}); + const rep = new Replicache({name: 'scan-with-index'}); (await rep.scan({indexName: 'a'}).keys().toArray()) as [ secondary: string, diff --git a/src/replicache.test.ts b/src/replicache.test.ts index 5b831d27..32329094 100644 --- a/src/replicache.test.ts +++ b/src/replicache.test.ts @@ -56,16 +56,14 @@ async function expectAsyncFuncToThrow(f: () => unknown, c: unknown) { (await expectPromiseToReject(f())).to.be.instanceof(c); } -test('userID is required', () => { +test('name is required', () => { expect( () => new Replicache({} as ReplicacheOptions>), - ).to.throw(/userID.*required/); + ).to.throw(/name.*required/); }); -test('userID cannot be empty', () => { - expect(() => new Replicache({userID: ''})).to.throw( - /userID.*must be non-empty/, - ); +test('name cannot be empty', () => { + expect(() => new Replicache({name: ''})).to.throw(/name.*must be non-empty/); }); test('get, has, scan on empty db', async () => { @@ -283,7 +281,7 @@ test('scan', async () => { ); }); -test('userID', async () => { +test('name', async () => { const repA = await replicacheForTesting('a', {mutators: {addData}}); const repB = await replicacheForTesting('b', {mutators: {addData}}); @@ -1442,7 +1440,7 @@ test('logLevel', async () => { expect( debug .getCalls() - .some(call => (call.firstArg + '').startsWith(`db=${rep.idbName}`)), + .some(call => (call.firstArg + '').startsWith(`db=${rep.name}`)), ).to.equal(true); expect( debug.getCalls().some(call => call.firstArg.startsWith('PULL')), @@ -1761,23 +1759,23 @@ test('clientID', async () => { const re = /^[0-9:A-z]{8}-[0-9:A-z]{4}-4[0-9:A-z]{3}-[0-9:A-z]{4}-[0-9:A-z]{12}$/; - let rep = await replicacheForTesting('userID'); + let rep = await replicacheForTesting('clientID'); const clientID = await rep.clientID; expect(clientID).to.match(re); await rep.close(); - const rep2 = await replicacheForTesting('userID2'); + const rep2 = await replicacheForTesting('clientID2'); const clientID2 = await rep2.clientID; expect(clientID2).to.match(re); expect(clientID2).to.not.equal(clientID); - rep = await replicacheForTesting('userID3'); + rep = await replicacheForTesting('clientID'); const clientID3 = await rep.clientID; expect(clientID3).to.match(re); // With SDD we never reuse client IDs. expect(clientID3).to.not.equal(clientID); - const rep4 = new Replicache({userID: 'userID4', pullInterval: null}); + const rep4 = new Replicache({name: 'clientID4', pullInterval: null}); const clientID4 = await rep4.clientID; expect(clientID4).to.match(re); await rep4.close(); @@ -1964,15 +1962,15 @@ test('online', async () => { test('overlapping open/close', async () => { const pullInterval = 60_000; - const userID = 'overlapping-open-close'; + const name = 'overlapping-open-close'; - const rep = new Replicache({userID, pullInterval}); + const rep = new Replicache({name, pullInterval}); const p = rep.close(); - const rep2 = new Replicache({userID, pullInterval}); + const rep2 = new Replicache({name, pullInterval}); const p2 = rep2.close(); - const rep3 = new Replicache({userID, pullInterval}); + const rep3 = new Replicache({name, pullInterval}); const p3 = rep3.close(); await p; @@ -1980,10 +1978,10 @@ test('overlapping open/close', async () => { await p3; { - const rep = new Replicache({userID, pullInterval}); + const rep = new Replicache({name, pullInterval}); await rep.clientID; const p = rep.close(); - const rep2 = new Replicache({userID, pullInterval}); + const rep2 = new Replicache({name, pullInterval}); await rep2.clientID; const p2 = rep2.close(); await p; diff --git a/src/replicache.ts b/src/replicache.ts index bbd7eff4..c85cce1f 100644 --- a/src/replicache.ts +++ b/src/replicache.ts @@ -68,8 +68,8 @@ export type MaybePromise = T | Promise; type ToPromise

= P extends Promise ? P : Promise

; -export function makeIdbName(userID: string, schemaVersion?: string): string { - const n = `${userID}:${REPLICACHE_FORMAT_VERSION}`; +export function makeIdbName(name: string, schemaVersion?: string): string { + const n = `${name}:${REPLICACHE_FORMAT_VERSION}`; return schemaVersion ? `${n}:${schemaVersion}` : n; } @@ -146,21 +146,15 @@ export class Replicache { /** The authorization token used when doing a push request. */ auth: string; - /** A unique identifier for the user authenticated by [[auth]]. */ - readonly userID: string; - - /** - * The name of the Replicache database. - * @deprecated Replaced by [[userID]]. - */ - readonly name?: string; + /** The name of the Replicache database. */ + readonly name: string; /** * This is the name Replicache uses for the IndexedDB database where data is * stored. */ get idbName(): string { - return makeIdbName(this.userID, this.schemaVersion); + return makeIdbName(this.name, this.schemaVersion); } /** The schema version of the data understood by this application. */ @@ -169,7 +163,7 @@ export class Replicache { private get _idbDatabase(): persist.IndexedDBDatabase { return { name: this.idbName, - userID: this.userID, + replicacheName: this.name, replicacheFormatVersion: REPLICACHE_FORMAT_VERSION, schemaVersion: this.schemaVersion, }; @@ -276,7 +270,7 @@ export class Replicache { constructor(options: ReplicacheOptions) { const { - userID, + name, logLevel = 'info', pullURL = '', auth, @@ -294,10 +288,10 @@ export class Replicache { this.auth = auth ?? ''; this.pullURL = pullURL; this.pushURL = pushURL; - if (userID === undefined || userID === '') { - throw new Error('userID is required and must be non-empty'); + if (name === undefined || name === '') { + throw new Error('name is required and must be non-empty'); } - this.userID = this.name = userID; + this.name = name; this.schemaVersion = schemaVersion; this.pullInterval = pullInterval; this.pushDelay = pushDelay; @@ -357,8 +351,6 @@ export class Replicache { this.mutate = this._registerMutators(mutators); - this._lc = new LogContext(logLevel).addContext('db', this.idbName); - const clientIDResolver = resolver(); this._clientIDPromise = clientIDResolver.promise; @@ -375,9 +367,9 @@ export class Replicache { resolveClientID: (clientID: string) => void, resolveReady: () => void, ): Promise { - // If we are currently closing a Replicache instance with the same db, + // If we are currently closing a Replicache instance with the same name, // wait for it to finish closing. - await closingInstances.get(this.idbName); + await closingInstances.get(this.name); await this._idbDatabases.putDatabase(this._idbDatabase); const [clientID, client, clients] = await persist.initClient(this._perdag); resolveClientID(clientID); @@ -446,7 +438,7 @@ export class Replicache { async close(): Promise { this._closed = true; const {promise, resolve} = resolver(); - closingInstances.set(this.idbName, promise); + closingInstances.set(this.name, promise); this._endHearbeats(); this._endClientsGC(); @@ -469,7 +461,7 @@ export class Replicache { this._subscriptions.clear(); await Promise.all(closingPromises); - closingInstances.delete(this.idbName); + closingInstances.delete(this.name); resolve(); } @@ -1215,7 +1207,7 @@ export class Replicache { } if ( database.name === this.idbName || - database.userID !== this.userID || + database.replicacheName !== this.name || // TODO: when REPLICACHE_FORMAT_VERSION is update // need to also handle previous REPLICACHE_FORMAT_VERSIONs database.replicacheFormatVersion !== REPLICACHE_FORMAT_VERSION diff --git a/src/test-util.ts b/src/test-util.ts index d3ee49cf..de5db9c3 100644 --- a/src/test-util.ts +++ b/src/test-util.ts @@ -80,49 +80,52 @@ export async function deleteAllDatabases(): Promise { dbsToDrop.clear(); } -const partialUserIDsToUserIDs: Map = new Map(); -/** Namespace userIDS with uuid to isolate tests' indexeddb state. */ -export function createUserIDForTest(partialUserID: string): string { - let userID = partialUserIDsToUserIDs.get(partialUserID); - if (!userID) { +const partialNamesToRepliacheNames: Map = new Map(); +/** Namespace replicache names to isolate tests' indexeddb state. */ +export function createReplicacheNameForTest(partialName: string): string { + let replicacheName = partialNamesToRepliacheNames.get(partialName); + if (!replicacheName) { const namespaceForTest = uuid(); - userID = `${namespaceForTest}:${partialUserID}`; - partialUserIDsToUserIDs.set(partialUserID, userID); + replicacheName = `${namespaceForTest}:${partialName}`; + partialNamesToRepliacheNames.set(partialName, replicacheName); } - return userID; + return replicacheName; } // eslint-disable-next-line @typescript-eslint/ban-types export async function replicacheForTesting( - partialUserID: string, - options: Omit, 'userID'> = {}, + partialName: string, + options: Omit, 'name'> = {}, ): Promise> { - const pullURL = 'https://pull.com/?userID=' + partialUserID; - const pushURL = 'https://push.com/?userID=' + partialUserID; - return replicacheForTestingNoDefaultURLs(createUserIDForTest(partialUserID), { - pullURL, - pushURL, - ...options, - }); + const pullURL = 'https://pull.com/?name=' + partialName; + const pushURL = 'https://push.com/?name=' + partialName; + return replicacheForTestingNoDefaultURLs( + createReplicacheNameForTest(partialName), + { + pullURL, + pushURL, + ...options, + }, + ); } export async function replicacheForTestingNoDefaultURLs< // eslint-disable-next-line @typescript-eslint/ban-types MD extends MutatorDefs = {}, >( - userID: string, + name: string, { pullURL, pushDelay = 60_000, // Large to prevent interfering pushURL, ...rest - }: Omit, 'userID'> = {}, + }: Omit, 'name'> = {}, ): Promise> { const rep = new ReplicacheTest({ pullURL, pushDelay, pushURL, - userID, + name, ...rest, }); dbsToDrop.add(rep.idbName); @@ -149,7 +152,7 @@ export function initReplicacheTesting(): void { clock.restore(); fetchMock.restore(); sinon.restore(); - partialUserIDsToUserIDs.clear(); + partialNamesToRepliacheNames.clear(); await closeAllReps(); await deleteAllDatabases(); await persist.teardownIDBDatabasesStoreForTest(); diff --git a/src/worker-tests/worker-test.ts b/src/worker-tests/worker-test.ts index bb14892e..8af00c5c 100644 --- a/src/worker-tests/worker-test.ts +++ b/src/worker-tests/worker-test.ts @@ -8,9 +8,9 @@ import type {JSONValue} from '../json'; import {closeAllReps, reps} from '../test-util'; onmessage = async (e: MessageEvent) => { - const {userID} = e.data; + const {name} = e.data; try { - await testGetHasScanOnEmptyDB(userID); + await testGetHasScanOnEmptyDB(name); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore TypeScripts type defs are incorrect. postMessage(undefined); @@ -23,10 +23,10 @@ onmessage = async (e: MessageEvent) => { } }; -async function testGetHasScanOnEmptyDB(userID: string) { +async function testGetHasScanOnEmptyDB(name: string) { const rep = new ReplicacheTest({ pushDelay: 60_000, // Large to prevent interferin;, - userID, + name, mutators: { testMut: async ( tx: WriteTransaction,