Files
wekan/tests/ddpSessionSendGuard.test.cjs
T
Lauri Ojansivu 302bd90410 A removed DDP session no longer crashes the server on its 101st message.
From the #6492 comments today, on WeKan 10.40 with real users:

  SyncedCron: Fatal error encountered (uncaughtException):
  TypeError: self._pendingRemoveFunction is not a function
      at Session.send (packages/ddp-server/livedata_server.js:362:14)
      at Session._stopSubscription (packages/ddp-server/livedata_server.js:823:10)
      at Session.unsub (packages/ddp-server/livedata_server.js:562:12)
  snap.wekan.wekan.service: Main process exited, code=exited, status=1/FAILURE
  snap.wekan.wekan.service: Scheduled restart job, restart counter is at 4.

It is a state-machine hole in Meteor's ddp-server. `_removeSession` sets
`session.messageQueue = []` and `session._pendingRemoveFunction = remove`; when
`remove()` runs it clears the function and deletes the session but LEAVES the
queue - an empty array, which is truthy. `Session.send` then takes the queueing
branch for a session that no longer exists, and the message past
`maxMessageQueueLength` (100 by default) calls that now-null function. It runs
from an Immediate, via unsub -> _stopSubscription -> send, with no try/catch
above it, so it is an uncaught exception - and synced-cron's handler exits the
process on one. systemd restarts, every user is disconnected, new cards stop
arriving until a reload, and the restart loop reads as "WeKan is slow and the CPU
is high", which is exactly what the reporter describes.

It needs a busy server: a session has to disconnect while more than ~100 further
messages are still addressed to it. That is why it shows up with fifty users and
never in a quiet test.

The guard patches Session.send once, from the first connection (the Session class
is not exported, so an instance is how the prototype is reached): a queue with no
remove function belongs to a session that is already gone, so the queue is
dropped and send() takes its ordinary path - which, with no socket, does nothing.
Nothing is lost that was not already lost, the disconnect-grace queue for a real
reconnect is untouched, and a valid overflow still removes the session.

tests/ddpSessionSendGuard.test.cjs replays the upstream state machine: it asserts
the unguarded version really does throw on the 101st message, that the guarded
one does not, that a session still waiting for its client keeps its queue, that a
legitimate overflow still calls the remove function exactly once, and that a live
session sends as before.

NOT verified here: there is no server in this environment, so this is reasoned
from the ddp-server source in .meteor/local and replayed against a model of it.
The high CPU the issue opened with is a separate thread (the FerretDB
$changeStream busy loop); this fixes the crash-restart loop reported today.

Thanks to bluetopaz1204, Nissulya and xet7 !

Fixes #6492,
2026-07-27 17:17:36 +03:00

142 lines
5.8 KiB
JavaScript

'use strict';
// #6492: "TypeError: self._pendingRemoveFunction is not a function" took the
// server down, again and again, on a busy instance.
//
// Meteor's ddp-server removes a disconnected session in two steps:
//
// _removeSession(session) -> session.messageQueue = []
// session._pendingRemoveFunction = remove
// remove() -> session._pendingRemoveFunction = null
// sessions.delete(session.id)
// ... and messageQueue is left in place
//
// so a REMOVED session still has a truthy queue. Session.send then queues to it,
// and the message after maxMessageQueueLength calls `_pendingRemoveFunction()` -
// which is now null. That throws from an Immediate (unsub -> _stopSubscription ->
// send), i.e. uncaught, and the process exits.
//
// This replays that state machine against the guard: a queue with no owner is
// dropped, so send() takes its ordinary path instead of calling null.
//
// Run: node tests/ddpSessionSendGuard.test.cjs
const assert = require('assert');
const fs = require('fs');
const path = require('path');
let passed = 0;
function test(name, fn) { fn(); passed += 1; console.log(' ok -', name); }
const read = rel => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8');
// --- Meteor's Session.send, as it is in ddp-server (the part that matters) ----
function makeSession({ maxMessageQueueLength = 100 } = {}) {
return {
id: 's1',
socket: null,
sentCount: 0,
messageQueue: null,
_pendingRemoveFunction: null,
_removeTimeoutHandle: null,
options: { maxMessageQueueLength },
sent: [],
send(msg) {
if (this.messageQueue) {
this.messageQueue.push(msg);
if (this.messageQueue.length > this.options.maxMessageQueueLength) {
this._pendingRemoveFunction(); // upstream: no typeof check
}
return;
}
if (this.socket) this.sent.push(msg);
},
};
}
// The guard this repo installs, applied to that same send().
function guard(session) {
const original = session.send.bind(session);
session.send = function guardedSend(msg) {
if (this.messageQueue && typeof this._pendingRemoveFunction !== 'function') {
this.messageQueue = null;
}
return original(msg);
}.bind(session);
return session;
}
// _removeSession + its remove function, as upstream writes them.
function removeSession(session) {
session.messageQueue = [];
const remove = () => {
session._removeTimeoutHandle = null;
session._pendingRemoveFunction = null; // ... messageQueue stays
};
session._pendingRemoveFunction = remove;
return remove;
}
console.log('ddpSessionSendGuard:');
test('the upstream bug is real: a removed session throws on the 101st message', () => {
const session = makeSession();
const remove = removeSession(session);
remove(); // the grace period expired
assert.strictEqual(session._pendingRemoveFunction, null);
assert.ok(Array.isArray(session.messageQueue), 'the queue outlives the session');
assert.throws(() => {
for (let i = 0; i <= 100; i += 1) session.send({ msg: 'nosub', id: `${i}` });
}, /not a function/, 'this is the crash from the report');
});
test('with the guard, the same sequence does not throw', () => {
const session = guard(makeSession());
const remove = removeSession(session);
remove();
for (let i = 0; i <= 250; i += 1) session.send({ msg: 'nosub', id: `${i}` });
assert.strictEqual(session.messageQueue, null, 'the ownerless queue is dropped');
assert.deepStrictEqual(session.sent, [], 'and nothing is sent to a socket that is gone');
});
test('a session that is still queueing for a real reconnect keeps its queue', () => {
// The queue is the point of the disconnect grace period: messages sent while
// the client is away are replayed when it comes back. The guard must not touch
// that case - only the one where the remove function is already gone.
const session = guard(makeSession());
removeSession(session); // disconnected, remove pending
for (let i = 0; i < 5; i += 1) session.send({ msg: 'added', id: `${i}` });
assert.strictEqual(session.messageQueue.length, 5, 'still queued for the replay');
assert.strictEqual(typeof session._pendingRemoveFunction, 'function');
});
test('an overflow while the remove function IS there still removes the session', () => {
const session = guard(makeSession({ maxMessageQueueLength: 10 }));
let removed = 0;
session.messageQueue = [];
session._pendingRemoveFunction = () => { removed += 1; session._pendingRemoveFunction = null; };
for (let i = 0; i <= 10; i += 1) session.send({ msg: 'added', id: `${i}` });
assert.strictEqual(removed, 1, 'upstream behaviour is unchanged when it is valid');
});
test('a live session sends as usual', () => {
const session = guard(makeSession());
session.socket = {};
session.send({ msg: 'connected' });
assert.deepStrictEqual(session.sent, [{ msg: 'connected' }]);
});
test('the guard is installed on the server, once, and cannot itself throw', () => {
const src = read('server/lib/ddpSessionSendGuard.js');
assert.ok(/typeof this\._pendingRemoveFunction !== 'function'/.test(src),
'the check that replaces the unguarded call');
assert.ok(/this\.messageQueue = null;/.test(src), 'and what it does instead');
assert.ok(/Meteor\.onConnection/.test(src),
'the Session class is not exported - an instance is how the prototype is reached');
assert.ok(/patched\.done/.test(src), 'patched once, not once per connection');
assert.ok(/catch \(e\)/.test(src), 'a guard that throws would be worse than the bug');
assert.ok(read('server/imports.js').includes("import '/server/lib/ddpSessionSendGuard';"),
'and it must actually be loaded');
});
console.log(`\n${passed} tests passed`);