Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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
}
8 changes: 5 additions & 3 deletions src/rx-collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
21 changes: 16 additions & 5 deletions src/rx-database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ import {
mergeMap
} from 'rxjs/operators';
import {
createRxCollection
createRxCollection,
OPEN_COLLECTIONS
} from './rx-collection.ts';
import {
flatCloneDocWithMeta,
Expand Down Expand Up @@ -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
Expand Down
101 changes: 101 additions & 0 deletions test/unit/migration-schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<DocType>; };
async function createDatabaseWithOldDocument(name: string, storage: RxStorage<any, any>) {
const db = await createRxDatabase<Collections>({
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<Collections>({
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<Collections>({
name,
storage
});
const createdCollections: RxCollection[] = [];
let releaseStrategy: () => void = () => { };
const strategyReleased = new Promise<void>(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,
Expand Down
Loading