Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(NODE-5706): make findOne() close implicit session to avoid memory leak #3897

Merged
merged 1 commit into from
Oct 18, 2023
Merged
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
5 changes: 4 additions & 1 deletion src/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,10 @@ export class Collection<TSchema extends Document = Document> {
filter: Filter<TSchema> = {},
options: FindOptions = {}
): Promise<WithId<TSchema> | null> {
return this.find(filter, options).limit(-1).batchSize(1).next();
const cursor = this.find(filter, options).limit(-1).batchSize(1);
const res = await cursor.next();
await cursor.close();
return res;
}

/**
Expand Down
99 changes: 97 additions & 2 deletions test/integration/crud/crud_api.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import { expect } from 'chai';
import { on } from 'events';

import { type MongoClient, MongoError, ObjectId, ReturnDocument } from '../../mongodb';
import * as semver from 'semver';
import * as sinon from 'sinon';

import {
Collection,
CommandFailedEvent,
CommandSucceededEvent,
type MongoClient,
MongoError,
MongoServerError,
ObjectId,
ReturnDocument
} from '../../mongodb';
import { type FailPoint } from '../../tools/utils';
import { assert as test } from '../shared';

// instanceof cannot be use reliably to detect the new models in js due to scoping and new
Expand Down Expand Up @@ -31,6 +43,8 @@ describe('CRUD API', function () {
});

afterEach(async function () {
sinon.restore();

await client?.close();
client = null;

Expand Down Expand Up @@ -61,6 +75,87 @@ describe('CRUD API', function () {
await client.close();
});

describe('findOne()', () => {
let client: MongoClient;
let events;
let collection: Collection<{ _id: number }>;

beforeEach(async function () {
client = this.configuration.newClient({ monitorCommands: true });
events = [];
client.on('commandSucceeded', commandSucceeded =>
commandSucceeded.commandName === 'find' ? events.push(commandSucceeded) : null
);
client.on('commandFailed', commandFailed =>
commandFailed.commandName === 'find' ? events.push(commandFailed) : null
);

collection = client.db('findOne').collection('findOne');
await collection.drop().catch(() => null);
await collection.insertMany([{ _id: 1 }, { _id: 2 }]);
});

afterEach(async () => {
await collection.drop().catch(() => null);
await client.close();
});

describe('when the operation succeeds', () => {
it('the cursor for findOne is closed', async function () {
const spy = sinon.spy(Collection.prototype, 'find');
const result = await collection.findOne({});
expect(result).to.deep.equal({ _id: 1 });
expect(events.at(0)).to.be.instanceOf(CommandSucceededEvent);
expect(spy.returnValues.at(0)).to.have.property('closed', true);
expect(spy.returnValues.at(0)).to.have.nested.property('session.hasEnded', true);
});
});

describe('when the find operation fails', () => {
beforeEach(async function () {
if (semver.lt(this.configuration.version, '4.2.0')) {
if (this.currentTest) {
this.currentTest.skipReason = `Cannot run fail points on server version: ${this.configuration.version}`;
}
return this.skip();
}

const failPoint: FailPoint = {
configureFailPoint: 'failCommand',
mode: 'alwaysOn',
data: {
failCommands: ['find'],
// 1 == InternalError, but this value not important to the test
errorCode: 1
}
};
await client.db().admin().command(failPoint);
});

afterEach(async function () {
if (semver.lt(this.configuration.version, '4.2.0')) {
return;
}

const failPoint: FailPoint = {
configureFailPoint: 'failCommand',
mode: 'off',
data: { failCommands: ['find'] }
};
await client.db().admin().command(failPoint);
});

it('the cursor for findOne is closed', async function () {
const spy = sinon.spy(Collection.prototype, 'find');
const error = await collection.findOne({}).catch(error => error);
expect(error).to.be.instanceOf(MongoServerError);
expect(events.at(0)).to.be.instanceOf(CommandFailedEvent);
expect(spy.returnValues.at(0)).to.have.property('closed', true);
expect(spy.returnValues.at(0)).to.have.nested.property('session.hasEnded', true);
});
});
});

context('when creating a cursor with find', () => {
let collection;

Expand Down