Repository navigation
In-memory replica set is never stopped when the api shuts down under NODE_ENV=test #1651
Description
When NODE_ENV=test, PrismaModuleOptionsFactory.createMemoryConnection starts a mongodb-memory-server replica set but keeps it only in a local variable. It never assigns it to this.memoryReplSet, so onApplicationShutdown always sees null and does nothing. app.close() therefore leaves the in-memory mongod running, and its temporary data directory is never removed. The process does not leak forever: the library's mongo_killer helper polls every 2 s and kills mongod once the parent Node process exits. But mongod outlives every app instance until the process exits, and the mongo-mem-* dbPath under the OS temp dir is never deleted. That happens on every integration-test run and on every pnpm dev:test / Playwright run, even though libnest enables shutdown hooks. One development machine had more than ten such directories of 1–7 MB each in /tmp. The code also contradicts apps/api/AGENTS.md, which says app.close() stops the replica set via onApplicationShutdown.
Where
-
apps/api/src/core/prisma.ts:194-199: the replica set is created but not stored:const replSet = await MongoMemoryReplSet.create({ replSet: { count: 1, name: 'rs0' } }); return new URL(replSet.getUri('test')).href;
-
apps/api/src/core/prisma.ts:162-166and188-192:memoryReplSetis set tonulland never assigned again, sostop()is unreachable. -
apps/api/AGENTS.md:236-237: the claim thatapp.close()stops it.
The field has never been assigned since the memory database was introduced (342a41e1f).
Reproduce
- Run
pnpm exec env-cmd vitest run apps/api/test/app.test.ts, or startpnpm --filter @opendatacapture/api dev:testand stop it. - List
mongo-mem-*directories in the OS temp dir (os.tmpdir()).
Actual: a new mongo-mem-* directory remains after every run, and mongod keeps running after app.close() until the process exits.
Expected: app.close() stops the replica set, which also removes its temporary dbPath.
Tests
No test pins this. apps/api/src/core/__tests__/prisma.spec.ts covers only the external-database path ("should shut down cleanly when it started no in-memory replica set"). The fix should add a test there: under NODE_ENV=test, create() followed by onApplicationShutdown() calls stop() on the replica set. The mocked MongoMemoryReplSet.create currently returns only getUri, so the mock also needs a stop spy.
Suggested fix
In createMemoryConnection, assign the created replica set to this.memoryReplSet before returning the URI.
Found while raising unit test coverage in #1632.
Activity
fix(api): stop the in-memory replica set when the app shuts down
fix(api): stop the in-memory replica set when the app shuts down