diff --git a/orga/changelog/fix-close-collection-of-failed-or-interrupted-add-collections.json b/orga/changelog/fix-close-collection-of-failed-or-interrupted-add-collections.json new file mode 100644 index 00000000000..a07c9170a80 --- /dev/null +++ b/orga/changelog/fix-close-collection-of-failed-or-interrupted-add-collections.json @@ -0,0 +1,6 @@ +{ + "$schema": "./schema.json", + "text": "FIX a collection that was created by an `addCollections()` call which failed (for example with `DM4` from the `autoMigrate` migration) or which was still running when `database.close()` was called, was never closed, so its timeouts (like the 60 seconds wait of the cleanup plugin) kept the JavaScript process alive", + "links": [], + "priority": 5 +} diff --git a/src/rx-collection.ts b/src/rx-collection.ts index f8facf57a22..6fb9d93ad78 100644 --- a/src/rx-collection.ts +++ b/src/rx-collection.ts @@ -1363,10 +1363,12 @@ export async function createRxCollection( } catch (err) { /** * If the collection creation fails, - * we yet have to close the storage instances. + * the collection must be closed so that its storage instance, + * its timeouts and everything that was started by the plugin hooks is stopped. + * When prepare() has failed before the storage instance was wrapped, + * the given storage instance is closed directly. */ - OPEN_COLLECTIONS.delete(collection); - await storageInstance.close(); + await collection.close().catch(() => storageInstance.close()); throw err; } diff --git a/src/rx-database.ts b/src/rx-database.ts index 2d948c7bb45..b405d8814e2 100644 --- a/src/rx-database.ts +++ b/src/rx-database.ts @@ -70,7 +70,8 @@ import { mergeMap } from 'rxjs/operators'; import { - createRxCollection + createRxCollection, + OPEN_COLLECTIONS } from './rx-collection.ts'; import { flatCloneDocWithMeta, @@ -657,11 +658,21 @@ export class RxDatabaseBase< closingError = err as Error; } - // close all collections + /** + * Close all collections. + * This includes collections that are still created by a running addCollections() call + * and therefore are not in this.collections. + * Each collection must be closed only once because + * a second close() call would run the onClose handlers again. + */ await Promise.all( - Object.keys(this.collections as any) - .map(key => (this.collections as any)[key]) - .map(col => col.close()) + Array.from( + new Set( + Array.from(OPEN_COLLECTIONS) + .filter(col => col.database === this.asRxDatabase) + .concat(Object.values(this.collections as any)) + ) + ).map(col => col.close()) ); // close internal storage instances diff --git a/test/unit/migration-schema.test.ts b/test/unit/migration-schema.test.ts index 737429b310d..f81a4048c71 100644 --- a/test/unit/migration-schema.test.ts +++ b/test/unit/migration-schema.test.ts @@ -2794,6 +2794,107 @@ describe('migration-schema.test.ts', function () { await db2.remove(); }); + describe('collection of a not finished addCollections() call', () => { + const schemaV0 = { + version: 0, + primaryKey: 'id', + type: 'object', + properties: { + id: { + type: 'string', + maxLength: 100 + }, + name: { + type: 'string' + } + }, + required: ['id', 'name'] + } as const; + const schemaV1 = Object.assign({}, schemaV0, { version: 1 } as const); + type DocType = { id: string; name: string; }; + type Collections = { todos: RxCollection; }; + async function createDatabaseWithOldDocument(name: string, storage: RxStorage) { + const db = await createRxDatabase({ + name, + storage + }); + await db.addCollections({ todos: { schema: schemaV0 } }); + await db.todos.insert({ id: 'todo1', name: 'Learn RxDB' }); + await db.close(); + } + it('should close the collection when the automatic migration fails', async () => { + const name = randomToken(10); + const storage = config.storage.getStorage(); + await createDatabaseWithOldDocument(name, storage); + + const db = await createRxDatabase({ + name, + storage + }); + const createdCollections: RxCollection[] = []; + await assertThrows( + () => db.addCollections({ + todos: { + schema: schemaV1, + migrationStrategies: { + 1: (_oldDoc, collection) => { + createdCollections.push(collection); + throw new Error('migration strategy failed'); + } + } + } + }), + 'RxError', + 'DM4' + ); + assert.ok(createdCollections.length > 0); + assert.strictEqual(createdCollections[0].closed, true); + assert.deepStrictEqual(Object.keys(db.collections), []); + + await db.close(); + }); + it('should close the collection when the database is closed during the automatic migration', async () => { + const name = randomToken(10); + const storage = config.storage.getStorage(); + await createDatabaseWithOldDocument(name, storage); + + const db = await createRxDatabase({ + name, + storage + }); + const createdCollections: RxCollection[] = []; + let releaseStrategy: () => void = () => { }; + const strategyReleased = new Promise(res => releaseStrategy = res); + const addPromise = db.addCollections({ + todos: { + schema: schemaV1, + migrationStrategies: { + 1: async (oldDoc, collection) => { + createdCollections.push(collection); + await strategyReleased; + return oldDoc; + } + } + } + }); + addPromise.catch(() => { }); + await waitUntil(() => createdCollections.length > 0); + assert.strictEqual(createdCollections[0].closed, false); + + /** + * Closing the database cancels the migration and then waits + * until the running batch of the migration has ended, + * so the strategy must be released before the close can resolve. + */ + const closePromise = db.close(); + await waitUntil(() => createdCollections[0].getMigrationState().canceled); + releaseStrategy(); + await closePromise; + + assert.strictEqual(createdCollections[0].closed, true); + assert.deepStrictEqual(Object.keys(db.collections), []); + }); + }); /** * An interrupted schema migration could never complete. * As soon as a document was already stored in the new storage,