Files
wekan/tests/exporterBackpressure.test.cjs
T
Lauri Ojansivu 2f7b49d8de Fix FerretDB migration non-finite doubles, LDAP email mapping, and export listener leak.
#6481 (Nissulya): after MongoDB 3.x -> FerretDB v1 migration, cards with a
non-finite `sort` (±Infinity / NaN, written by old WeKan before #6472) failed to
insert: FerretDB/SQLite rejects non-finite doubles ("invalid value { sort: +Inf }
(infinity values are not allowed)"), aborting the document and leaving boards
stuck on the loading spinner. sanitizeNonFinite() only made the bare mongoexport
tokens PARSE; the parsed value was still a JS Infinity/NaN. Added clampNonFinite()
in the migration tool to reset every non-finite number to a finite 0 before
insert, and a `nonfinite-sort-repair` startup schema-upgrade step that heals the
same corruption in an already-running database (MongoDB or FerretDB), using a
predicate built from finite literals only so it is safe on FerretDB too.

#6481 (Nissulya): LDAP `mail` -> `email` fieldmap returned `undefined` (worked in
6.09). getDataToSyncUserData's email branch read the mapped attribute
case-SENSITIVELY (ldapUser.hasOwnProperty / ldapUser[field]) while the rest of
wekan-ldap uses the case-insensitive getLDAPValue(); a directory returning the
attribute with a different case (exposed by ldapjs -> ldapts, which preserves the
server's case) missed it. The email branch (and the addLdapUser fallback) now
read via getLDAPValue().

#6480 (uusijani): board/CSV export paused on socket backpressure with
`res.once('drain', resolve); res.once('error', reject)`, which leaked one 'error'
listener per backpressured write ("MaxListenersExceededWarning: 11 error
listeners added to [ServerResponse]"). writeWithBackpressure() now removes both
listeners once either settles.

Added tests and negative tests for all three fixes.

Thanks to Nissulya, uusijani and xet7 !

Fixes #6480,
Fixes #6481.
2026-07-19 18:36:11 +03:00

114 lines
4.5 KiB
JavaScript

'use strict';
// Regression test for #6480: the board/CSV export writers paused on socket
// backpressure with `res.once('drain', resolve); res.once('error', reject)`.
// The 'drain' listener self-removes when it fires, but the paired 'error'
// listener never does — so every backpressured write leaked one 'error' listener
// on the ServerResponse. A large export (an 11 MB board) accumulated dozens,
// tripping Node's "MaxListenersExceededWarning: 11 error listeners added to
// [ServerResponse]" and holding listeners for the life of the socket.
// writeWithBackpressure() must remove BOTH listeners once either settles.
//
// Run: node tests/exporterBackpressure.test.cjs
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const { EventEmitter } = require('events');
let passed = 0;
function test(name, fn) {
const r = fn();
if (r && typeof r.then === 'function') return r.then(() => { passed += 1; console.log(' ok -', name); });
passed += 1;
console.log(' ok -', name);
return Promise.resolve();
}
// Mirrors writeWithBackpressure() in models/exporter.js.
function writeWithBackpressure(res, str) {
return new Promise((resolve, reject) => {
if (res.write(str)) { resolve(); return; }
const cleanup = () => {
res.removeListener('drain', onDrain);
res.removeListener('error', onError);
};
const onDrain = () => { cleanup(); resolve(); };
const onError = err => { cleanup(); reject(err); };
res.once('drain', onDrain);
res.once('error', onError);
});
}
// A fake ServerResponse whose write() reports backpressure (returns false) until
// a 'drain' is emitted — like a full socket buffer.
function fakeRes() {
const res = new EventEmitter();
res.setMaxListeners(10); // Node's default; the leak would trip a warning past it
res.write = () => false; // always backpressured, forcing the drain path
return res;
}
console.log('exporterBackpressure:');
(async () => {
await test('no drain/error listeners remain after a backpressured write drains', async () => {
const res = fakeRes();
const p = writeWithBackpressure(res, 'chunk');
assert.strictEqual(res.listenerCount('drain'), 1);
assert.strictEqual(res.listenerCount('error'), 1);
res.emit('drain');
await p;
assert.strictEqual(res.listenerCount('drain'), 0, 'drain listener removed');
assert.strictEqual(res.listenerCount('error'), 0, 'error listener removed (this was the leak)');
});
await test('listeners never accumulate across many backpressured writes', async () => {
const res = fakeRes();
for (let i = 0; i < 100; i++) {
const p = writeWithBackpressure(res, 'x');
res.emit('drain');
await p;
assert.ok(res.listenerCount('error') <= 1, `error listeners leaked at write ${i}`);
assert.ok(res.listenerCount('drain') <= 1, `drain listeners leaked at write ${i}`);
}
assert.strictEqual(res.listenerCount('error'), 0);
assert.strictEqual(res.listenerCount('drain'), 0);
});
await test('a socket error rejects and still removes both listeners', async () => {
const res = fakeRes();
const p = writeWithBackpressure(res, 'x');
res.emit('error', new Error('socket closed'));
await assert.rejects(p, /socket closed/);
assert.strictEqual(res.listenerCount('drain'), 0);
assert.strictEqual(res.listenerCount('error'), 0);
});
await test('a write that does NOT backpressure registers no listeners at all', async () => {
const res = fakeRes();
res.write = () => true; // buffer has room
await writeWithBackpressure(res, 'x');
assert.strictEqual(res.listenerCount('drain'), 0);
assert.strictEqual(res.listenerCount('error'), 0);
});
// Source guard: the real exporter must use the shared helper and must NOT carry
// the leaky inline `once('drain', resolve); once('error', reject)` pattern.
await test('source: exporter.js uses writeWithBackpressure and drops the leaky pattern', () => {
const src = fs.readFileSync(path.join(__dirname, '..', 'models', 'exporter.js'), 'utf8');
assert.ok(/export function writeWithBackpressure/.test(src), 'helper must exist');
assert.ok(/removeListener\('drain'/.test(src) && /removeListener\('error'/.test(src),
'helper must remove both listeners on settle');
assert.ok(!/once\('drain',\s*resolve\)\s*;\s*res\.once\('error',\s*reject\)/.test(src),
'the leaky inline once(drain)/once(error) pattern must be gone');
// both writers delegate to the helper
assert.ok((src.match(/writeWithBackpressure\(res,\s*str\)/g) || []).length >= 2,
'both the JSON and CSV writers must delegate to the helper');
});
console.log(`\n${passed} passed`);
})();