Skip to content

Commit

Permalink
fix(model): avoid adding timeout on Model.init() buffering to avoid…
Browse files Browse the repository at this point in the history
… unintentional dangling open handles

Fix #15241
  • Loading branch information
vkarpov15 committed Feb 11, 2025
1 parent 61d16b0 commit 9159ced
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 15 deletions.
36 changes: 22 additions & 14 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -818,32 +818,40 @@ Connection.prototype.dropCollection = async function dropCollection(collection)
/**
* Waits for connection to be established, so the connection has a `client`
*
* @param {Boolean} [noTimeout=false] if set, don't put a timeout on the operation. Used internally so `mongoose.model()` doesn't leave open handles.
* @return Promise
* @api private
*/

Connection.prototype._waitForConnect = async function _waitForConnect() {
Connection.prototype._waitForConnect = async function _waitForConnect(noTimeout) {
if ((this.readyState === STATES.connecting || this.readyState === STATES.disconnected) && this._shouldBufferCommands()) {
const bufferTimeoutMS = this._getBufferTimeoutMS();
let timeout = null;
let timedOut = false;
// The element that this function pushes onto `_queue`, stored to make it easy to remove later
const queueElement = {};
await Promise.race([
new Promise(resolve => {
if (noTimeout) {
await new Promise(resolve => {
queueElement.fn = resolve;
this._queue.push(queueElement);
}),
new Promise(resolve => {
timeout = setTimeout(
() => {
timedOut = true;
resolve();
},
bufferTimeoutMS
);
})
]);
});
} else {
await Promise.race([
new Promise(resolve => {
queueElement.fn = resolve;
this._queue.push(queueElement);
}),
new Promise(resolve => {
timeout = setTimeout(
() => {
timedOut = true;
resolve();
},
bufferTimeoutMS
);
})
]);
}

if (timedOut) {
const index = this._queue.indexOf(queueElement);
Expand Down
2 changes: 1 addition & 1 deletion lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -1112,7 +1112,7 @@ Model.init = function init() {
);
if (autoCreate == null) {
// `autoCreate` may later be set when the connection is opened, so wait for connect before checking
await conn._waitForConnect();
await conn._waitForConnect(true);
autoCreate = utils.getOption(
'autoCreate',
this.schema.options,
Expand Down

0 comments on commit 9159ced

Please sign in to comment.