Skip to content

Commit

Permalink
Resolve memory leak when using cursor operations like $count in mongo…
Browse files Browse the repository at this point in the history
…db@4-6

Starting in Mongo Node driver `mongodb@4`, up through the latest version `mongodb@6`, using `cursor.count()` results in a memory leak. `mongodb@3` doesn't leak in the same situation.

The driver creates an implicit client session, but it doesn't automatically close the session when getting the results back from the server. Those unclosed sessions build up over time, causing a memory leak.

sharedb-mongo exposes document counting via a user passing the `$count: true` property on query objects, and it currently uses `cursor.count()`.

There are a couple ways sharedb-mongo could address the leak:
- Switch to `Collection#countDocuments()`, which is the recommended replacement for the deprecated `FindCursor#count()`. This is better long-term, but it's more work since we have to map things like `$limit` from using chained cursor calls over to the equivalent property in CountOptions, where appropriate.
- Explicitly close the cursor. Easy and safe, since the cursor is created inside sharedb-mongo and not exposed externally.

To resolve the leak more quickly, this change opts for the latter, explicitly closing the cursor for the "cursor operations" `$count`, `$explain`, and `$map`.
  • Loading branch information
ericyhwang committed Feb 13, 2024
1 parent 5e6fc4c commit 06b5c78
Showing 1 changed file with 3 additions and 0 deletions.
3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1510,19 +1510,22 @@ var cursorOperationsMap = {
$count: function(cursor, value, cb) {
cursor.count()
.then(function(result) {
cursor.close();
cb(null, result);
}, cb);
},
$explain: function(cursor, verbosity, cb) {
cursor.explain(verbosity)
.then(function(result) {
cursor.close();
cb(null, result);
}, cb);
},
$map: function(cursor, fn, cb) {
cursor.map(fn)
.toArray()
.then(function(result) {
cursor.close();
cb(null, result);
}, cb);
}
Expand Down

0 comments on commit 06b5c78

Please sign in to comment.