Files
wekan/tests/schemaUpgradeSteps.test.cjs
T
Lauri Ojansivu d42369e96a Full collection scans run once, not at every start of every server; due-date reminders are sent once.
The startup schema re-check claims a run in _wekan_migration so one server
re-checks while the others skip (a claim older than 2 hours is taken over),
and a run that leaves work unresolved is retried once a day instead of at
every start. The daily due-date reminder scan is claimed per day in
dueReminderRuns, so 24 replicas no longer send 24 reminders per card.
A partial index on lists serves the 15-minute list sync scan, and a sparse
index on boards.dueReminderDays serves the due-date lookup.

Thanks to Raymond-Voogt and xet7 !

Fixes #6855,
2026-11-02 11:28:44 +02:00

1217 lines
62 KiB
JavaScript

'use strict';
// Plain-Node BEHAVIORAL tests (no Meteor) for the startup schema upgrade
// (server/lib/schemaUpgradeSteps.js) — the #6473 follow-up that brings TEXT
// DATA from every old WeKan version to the newest database structure on all
// platforms and both databases. Guards the whole contract so later changes
// that would break migrating SOME data shape fail here:
// - every step migrates its old shape (positive) and leaves healthy/explicit
// data alone (negative);
// - the re-check is VERSION-GATED: mandatory only after a new WeKan release,
// a single findOne while the version is unchanged;
// - big-database speed: checks are bounded probes/distinct() set-joins and
// fixes are server-side updateMany batches (asserted via op counters);
// - a failing or unresolved step never blocks startup and forces the next
// boot to re-check.
//
// Runs against a minimal in-memory mongodb-driver-compatible Db fake (only
// the operators the module actually uses).
// Run: node tests/schemaUpgradeSteps.test.cjs
const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const repoRoot = path.resolve(__dirname, '..');
const read = rel => fs.readFileSync(path.join(repoRoot, rel), 'utf8');
const {
runSchemaUpgrade,
getUpgradeState,
BOARD_ALLOWS_TRUE_DEFAULTS,
randomId,
versionNeedsHeal,
MARKER_ID,
CLAIM_ID,
CLAIM_STALE_MS,
RETRY_UNCLEAN_MS,
steps,
} = require('../server/lib/schemaUpgradeSteps');
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();
}
// ── minimal in-memory Db fake (mongodb driver surface the module uses) ───────
function getPath(doc, key) {
return key.split('.').reduce((v, part) => (v == null ? v : v[part]), doc);
}
function matchCond(value, cond) {
if (cond && typeof cond === 'object' && !Array.isArray(cond)) {
if ('$exists' in cond) return cond.$exists === (value !== undefined);
if ('$in' in cond) {
return cond.$in.some(x => (x === null ? value === undefined || value === null : String(value) === String(x)));
}
if ('$nin' in cond) {
return !cond.$nin.some(x => (x === null ? value === undefined || value === null : String(value) === String(x)));
}
if ('$ne' in cond) {
return String(value) !== String(cond.$ne);
}
if ('$elemMatch' in cond) {
if (!Array.isArray(value)) return false;
return value.some(el => matches(el, cond.$elemMatch));
}
// numeric type/range (nonfinite-sort-repair). Multiple ops AND together.
if ('$type' in cond || '$gte' in cond || '$lte' in cond || '$lt' in cond) {
let ok = true;
if ('$lt' in cond) ok = ok && (typeof value === 'number' && value < cond.$lt);
if ('$type' in cond) ok = ok && (cond.$type === 'number' ? typeof value === 'number' : false);
if ('$gte' in cond) ok = ok && (typeof value === 'number' && value >= cond.$gte);
if ('$lte' in cond) ok = ok && (typeof value === 'number' && value <= cond.$lte);
return ok;
}
throw new Error('fake db: unsupported operator in ' + JSON.stringify(cond));
}
return String(value) === String(cond) || value === cond;
}
function matches(doc, filter) {
for (const [key, cond] of Object.entries(filter || {})) {
if (key === '$or') {
if (!cond.some(sub => matches(doc, sub))) return false;
continue;
}
if (key === '$nor') {
if (cond.some(sub => matches(doc, sub))) return false;
continue;
}
if (!matchCond(getPath(doc, key), cond)) return false;
}
return true;
}
function applyUpdate(doc, update) {
for (const [k, v] of Object.entries(update.$set || {})) {
const parts = k.split('.');
let target = doc;
for (const p of parts.slice(0, -1)) {
if (typeof target[p] !== 'object' || target[p] === null) target[p] = {};
target = target[p];
}
target[parts[parts.length - 1]] = v;
}
for (const k of Object.keys(update.$unset || {})) {
const parts = k.split('.');
let target = doc;
for (const p of parts.slice(0, -1)) {
target = target && target[p];
if (!target) break;
}
if (target) delete target[parts[parts.length - 1]];
}
}
function fakeDb(initial = {}) {
const data = new Map(Object.entries(initial).map(([k, docs]) => [k, docs.map(d => JSON.parse(JSON.stringify(d)))]));
const ops = { findOne: 0, find: 0, distinct: 0, updateMany: 0, updateOne: 0, insertOne: 0, insertMany: 0, countDocuments: 0 };
const coll = name => {
if (!data.has(name)) data.set(name, []);
const docs = () => data.get(name);
return {
async findOne(filter = {}, opts = {}) {
ops.findOne++;
let found = docs().filter(d => matches(d, filter));
if (opts.sort) {
const [[k, dir]] = Object.entries(opts.sort);
found = found.sort((a, b) => ((a[k] || 0) - (b[k] || 0)) * dir);
}
return found[0] ? JSON.parse(JSON.stringify(found[0])) : null;
},
find(filter = {}) {
ops.find++;
const found = docs().filter(d => matches(d, filter)).map(d => JSON.parse(JSON.stringify(d)));
let i = 0;
return {
async toArray() { return found; },
async close() {},
[Symbol.asyncIterator]() {
return { async next() { return i < found.length ? { value: found[i++], done: false } : { value: undefined, done: true }; } };
},
};
},
async distinct(field, filter = {}) {
ops.distinct++;
const vals = new Set();
for (const d of docs()) if (matches(d, filter)) {
const v = getPath(d, field);
// MongoDB's distinct() returns each element of an array field.
for (const x of Array.isArray(v) ? v : [v]) {
if (x !== undefined) vals.add(typeof x === 'string' ? x : String(x));
}
}
return [...vals];
},
async countDocuments(filter = {}) {
ops.countDocuments++;
return docs().filter(d => matches(d, filter)).length;
},
async deleteOne(filter) {
const i = docs().findIndex(d => matches(d, filter));
if (i >= 0) { docs().splice(i, 1); return { deletedCount: 1 }; }
return { deletedCount: 0 };
},
async insertOne(doc) {
ops.insertOne++;
if (doc._id !== undefined && docs().some(d => String(d._id) === String(doc._id))) {
throw Object.assign(new Error('E11000 duplicate key error'), { code: 11000 });
}
docs().push(JSON.parse(JSON.stringify(doc)));
return { insertedId: doc._id };
},
async insertMany(list) { ops.insertMany++; for (const d of list) docs().push(JSON.parse(JSON.stringify(d))); return { insertedCount: list.length }; },
async updateOne(filter, update, opts = {}) {
ops.updateOne++;
const target = docs().find(d => matches(d, filter));
if (target) { applyUpdate(target, update); return { modifiedCount: 1 }; }
if (opts.upsert) {
const fresh = { ...(filter._id ? { _id: filter._id } : {}) };
applyUpdate(fresh, update);
docs().push(fresh);
return { upsertedId: fresh._id, modifiedCount: 0 };
}
return { modifiedCount: 0 };
},
async updateMany(filter, update) {
ops.updateMany++;
let n = 0;
for (const d of docs()) if (matches(d, filter)) { applyUpdate(d, update); n++; }
return { modifiedCount: n };
},
};
};
return { collection: coll, _dump: name => data.get(name) || [], _ops: ops };
}
const tmpWritable = fs.mkdtempSync(path.join(os.tmpdir(), 'schema-upgrade-'));
const opts = { writablePath: tmpWritable, appVersion: 'v9.97.0' };
(async () => {
await test('randomId produces Meteor-style 17-char ids', () => {
const id = randomId();
assert.strictEqual(id.length, 17);
assert.ok(/^[23456789A-HJKLMNP-Zabcdefghijkmnop-z]+$/.test(id));
assert.notStrictEqual(randomId(), randomId());
// custom lengths still exact despite rejection resampling
assert.strictEqual(randomId(64).length, 64);
});
await test('negative: randomId uses rejection sampling, not biased modulo (CodeQL js/biased-cryptographic-random)', () => {
const src = read('server/lib/schemaUpgradeSteps.js');
const fn = src.match(/function randomId\([\s\S]*?\n\}/)[0];
assert.ok(fn.includes('256 % ID_CHARS.length'),
'bytes at/above the largest alphabet multiple must be rejected, or ids skew toward the first characters');
assert.ok(/if \(bytes\[i\] < limit\)/.test(fn), 'out-of-range bytes are resampled, never wrapped');
});
// ── swimlane-structure ────────────────────────────────────────────────────────
await test('swimlane-structure: creates Default swimlane, backfills lists/cards, rescues dangling listId', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', title: 'Old board' }],
lists: [{ _id: 'l1', boardId: 'b1', title: 'Todo' }], // no swimlaneId
cards: [
{ _id: 'c1', boardId: 'b1', listId: 'l1', title: 'ok card' }, // no swimlaneId
{ _id: 'c2', boardId: 'b1', listId: 'GONE', title: 'orphan' },// dangling listId
],
});
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('swimlane-structure'));
const sw = db._dump('swimlanes');
assert.strictEqual(sw.length, 1);
assert.strictEqual(sw[0].title, 'Default');
const l1 = db._dump('lists').find(l => l._id === 'l1');
assert.strictEqual(l1.swimlaneId, undefined,
'lists are NOT stamped: empty/missing swimlaneId means SHARED across swimlanes');
const c1 = db._dump('cards').find(c => c._id === 'c1');
assert.strictEqual(c1.swimlaneId, String(sw[0]._id));
const c2 = db._dump('cards').find(c => c._id === 'c2');
assert.strictEqual(c2.listId, 'l1', 'orphan rescued to the board\'s first list');
});
await test('swimlane-structure: creates a Rescued Data list when the board has none', async () => {
const db = fakeDb({
boards: [{ _id: 'b1' }],
swimlanes: [{ _id: 's1', boardId: 'b1', title: 'Default', sort: 0 }],
cards: [{ _id: 'c1', boardId: 'b1', listId: 'GONE', swimlaneId: 's1' }],
});
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('swimlane-structure'));
const rescued = db._dump('lists').find(l => l.title === 'Rescued Data');
assert.ok(rescued, 'Rescued Data list created');
assert.strictEqual(db._dump('cards')[0].listId, String(rescued._id));
});
await test('speed: card fixes are server-side updateMany batches, never per-card round trips', async () => {
const manyCards = [];
for (let i = 0; i < 500; i++) manyCards.push({ _id: 'c' + i, boardId: 'b1', listId: 'l1', title: 't' + i });
const db = fakeDb({
boards: [{ _id: 'b1' }],
lists: [{ _id: 'l1', boardId: 'b1' }],
cards: manyCards, // 500 cards all missing swimlaneId
});
await runSchemaUpgrade(db, opts);
assert.ok(db._dump('cards').every(c => c.swimlaneId), 'all 500 cards fixed');
assert.ok(db._ops.updateOne < 20,
`per-document updateOne calls must stay constant-ish (got ${db._ops.updateOne}) — thousands of cards must not mean thousands of round trips`);
assert.ok(db._ops.updateMany >= 2, 'fixes go through updateMany');
});
// ── card-list-other-board (#5874) ─────────────────────────────────────────────
// A card moved to another board before the move hook existed kept the list of
// the board it left: it exists, so the dangling-listId rescue does not see it,
// and the card is shown nowhere.
const foreignListStep = steps.find(s => s.name === 'card-list-other-board');
await test('card-list-other-board: a card on a list of the board it left gets its own board\'s first list', async () => {
const db = fakeDb({
boards: [{ _id: 'A' }, { _id: 'B' }, { _id: 'C' }],
lists: [
{ _id: 'la', boardId: 'A', sort: 0 },
{ _id: 'lbArchived', boardId: 'B', sort: 0, archived: true },
{ _id: 'lb2', boardId: 'B', sort: 2 },
{ _id: 'lb1', boardId: 'B', sort: 1, swimlaneId: 'swB' },
],
cards: [
{ _id: 'moved', boardId: 'B', listId: 'la', swimlaneId: 'x' }, // the bug
{ _id: 'movedArchived', boardId: 'B', listId: 'la', archived: true },
{ _id: 'toC', boardId: 'C', listId: 'la' }, // C has no list at all
{ _id: 'fine', boardId: 'A', listId: 'la' },
],
});
assert.strictEqual(await foreignListStep.check(db), true);
const res = await foreignListStep.run(db);
assert.strictEqual(res.fixed, 3);
const card = id => db._dump('cards').find(c => c._id === id);
assert.strictEqual(card('moved').listId, 'lb1', 'first unarchived list by sort');
assert.strictEqual(card('moved').swimlaneId, 'swB', 'a list bound to a swimlane brings the card into it');
assert.strictEqual(card('movedArchived').listId, 'lb1');
const rescued = db._dump('lists').find(l => l.boardId === 'C');
assert.ok(rescued && rescued.title === 'Rescued Data', 'a board without lists gets Rescued Data');
assert.strictEqual(card('toC').listId, rescued._id);
assert.strictEqual(card('fine').listId, 'la', 'a card on its own board is untouched');
assert.strictEqual(await foreignListStep.check(db), false, 'idempotent');
});
// #6814: the rescued card keeps the swimlane of the board it LEFT when its new
// list is not bound to one - swimlane-structure's foreign-swimlane rescue must
// see it in the same pass, so the step runs before it.
await test('card-list-other-board runs before swimlane-structure, which then gives the card a swimlane of its board', async () => {
const names = steps.map(st => st.name);
assert.ok(names.indexOf('card-list-other-board') < names.indexOf('swimlane-structure'), 'the order the runner walks');
const db = fakeDb({
boards: [{ _id: 'A' }, { _id: 'B' }],
swimlanes: [{ _id: 'swA', boardId: 'A', sort: 0, archived: false }, { _id: 'swB', boardId: 'B', sort: 0, archived: false }],
lists: [{ _id: 'la', boardId: 'A', sort: 0, swimlaneId: '' }, { _id: 'lb', boardId: 'B', sort: 0, swimlaneId: '' }],
cards: [{ _id: 'moved', boardId: 'B', listId: 'la', swimlaneId: 'swA', archived: false }],
});
for (const name of ['card-list-other-board', 'swimlane-structure']) {
const step = steps.find(st => st.name === name);
if (await step.check(db)) await step.run(db);
}
const card = db._dump('cards').find(c => c._id === 'moved');
assert.strictEqual(card.listId, 'lb');
assert.strictEqual(card.swimlaneId, 'swB', 'negative: not left on the swimlane of the board it left');
});
await test('negative: card-list-other-board leaves a missing list to swimlane-structure', async () => {
const db = fakeDb({
boards: [{ _id: 'A' }],
lists: [{ _id: 'la', boardId: 'A', sort: 0 }],
cards: [{ _id: 'c1', boardId: 'A', listId: 'la' }, { _id: 'c2', boardId: 'A', listId: 'gone' }],
});
assert.strictEqual(await foreignListStep.check(db), false);
});
await test('negative: swimlane-structure does not run on healthy data', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false }],
swimlanes: [{ _id: 's1', boardId: 'b1', archived: false }],
lists: [{ _id: 'l1', boardId: 'b1', swimlaneId: 's1', archived: false }],
cards: [{ _id: 'c1', boardId: 'b1', listId: 'l1', swimlaneId: 's1', archived: false }],
});
const res = await runSchemaUpgrade(db, opts);
assert.ok(!res.ran.includes('swimlane-structure'));
assert.ok(!res.ran.includes('archived-flag-backfill'));
});
// ── views visibility: Swimlanes view + Lists view (#1959, #1971) ─────────────
await test('archived-flag-backfill: docs missing `archived` become visible to archived:false view queries', async () => {
const db = fakeDb({
boards: [{ _id: 'b1' }], // LibreBoard-era: no archived field
swimlanes: [{ _id: 's1', boardId: 'b1' }],
lists: [{ _id: 'l1', boardId: 'b1', swimlaneId: 's1' }],
cards: [{ _id: 'c1', boardId: 'b1', listId: 'l1', swimlaneId: 's1' }],
});
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('archived-flag-backfill'));
for (const coll of ['boards', 'swimlanes', 'lists', 'cards']) {
assert.strictEqual(db._dump(coll)[0].archived, false, `${coll} now matches archived:false`);
}
});
await test('negative: archived-flag-backfill never flips explicitly archived docs', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: true }],
swimlanes: [{ _id: 's1', boardId: 'b1', archived: false }],
});
await runSchemaUpgrade(db, opts);
assert.strictEqual(db._dump('boards')[0].archived, true, 'archived board stays archived');
});
await test('type-defaults-backfill: a MongoDB 3 era board without `type` is published to All Boards again', async () => {
// The shape of the Sandstorm grain that opened onto an empty page: its board
// ('sandstorm', from before the templates feature) and everything on it had
// no `type`, and All Boards publishes { archived: false, type: 'board' }.
const db = fakeDb({
boards: [{ _id: 'sandstorm', slug: 'libreboard', archived: false }],
swimlanes: [{ _id: 's1', boardId: 'sandstorm', archived: false }],
lists: [{ _id: 'l1', boardId: 'sandstorm', archived: false, type: null }],
cards: [{ _id: 'c1', boardId: 'sandstorm', listId: 'l1', swimlaneId: 's1', archived: false, type: '' }],
});
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('type-defaults-backfill'));
assert.strictEqual(db._dump('boards')[0].type, 'board', 'matches the All Boards publication');
assert.strictEqual(db._dump('swimlanes')[0].type, 'swimlane');
assert.strictEqual(db._dump('lists')[0].type, 'list', 'null type backfilled');
assert.strictEqual(db._dump('cards')[0].type, 'cardType-card', 'empty type backfilled');
const names = steps.map(st => st.name);
assert.ok(names.indexOf('type-defaults-backfill') < names.indexOf('swimlane-structure'),
'types are set before the visibility rescues read the data');
});
await test('negative: type-defaults-backfill never changes an explicit type, and is idle on typed data', async () => {
const db = fakeDb({
boards: [{ _id: 't', archived: false, type: 'template-container' }, { _id: 'b', archived: false, type: 'template-board' }],
swimlanes: [{ _id: 's1', boardId: 't', archived: false, type: 'template-container' }],
lists: [{ _id: 'l1', boardId: 'b', archived: false, type: 'template-list' }],
cards: [{ _id: 'c1', boardId: 'b', listId: 'l1', archived: false, type: 'cardType-linkedBoard' }],
});
const step = steps.find(st => st.name === 'type-defaults-backfill');
assert.strictEqual(await step.check(db), false, 'nothing to do');
await step.run(db);
assert.deepStrictEqual(db._dump('boards').map(b => b.type), ['template-container', 'template-board']);
assert.strictEqual(db._dump('swimlanes')[0].type, 'template-container');
assert.strictEqual(db._dump('lists')[0].type, 'template-list');
assert.strictEqual(db._dump('cards')[0].type, 'cardType-linkedBoard');
});
await test('negative: every schema default the backfill writes is the one the model inserts', () => {
// A backfill that wrote a different word than the model's defaultValue would
// hide the boards it was meant to show; read the defaults from the models.
for (const [file, value] of [['models/swimlanes.js', 'swimlane'], ['models/lists.js', 'list']]) {
assert.match(read(file), new RegExp(`defaultValue: '${value}'`), file);
}
assert.match(read('config/const.js'), /TYPE_BOARD = 'board'/);
assert.match(read('config/const.js'), /TYPE_CARD = 'cardType-card'/);
});
await test('#1959: card under a DELETED swimlane is rescued to the board\'s visible swimlane', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false }],
swimlanes: [{ _id: 'sVisible', boardId: 'b1', archived: false, sort: 0 }],
lists: [{ _id: 'l1', boardId: 'b1', swimlaneId: 'sVisible', archived: false }],
cards: [{ _id: 'c1', boardId: 'b1', listId: 'l1', swimlaneId: 'sDELETED', archived: false }],
});
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('swimlane-structure'));
assert.strictEqual(db._dump('cards')[0].swimlaneId, 'sVisible', 'card visible in Swimlanes view again');
});
await test('a card under an ARCHIVED swimlane STAYS there - archiving is not breakage', async () => {
// This assertion used to be the opposite, and the opposite is what an email
// on 2026-08-13 reported: "Previously archived cards (some several years old)
// have reappeared. These cards have incorrectly been placed in the top
// swimlane." Archiving a swimlane leaves its cards where they are - they are
// hidden because the swimlane is - so sweeping them into the first visible
// swimlane un-archives, silently, years later.
//
// #1971 itself is about cards ADDED in List view landing in an archived
// swimlane, and that is fixed where cards are created: getDefaultSwimline()
// (models/boards.js) picks a non-archived swimlane. It never needed a bulk
// sweep over data somebody archived on purpose.
const db = fakeDb({
boards: [{ _id: 'b1', archived: false }],
swimlanes: [
{ _id: 'sArchived', boardId: 'b1', archived: true, sort: 0 },
{ _id: 'sVisible', boardId: 'b1', archived: false, sort: 1 },
],
lists: [{ _id: 'l1', boardId: 'b1', swimlaneId: 'sVisible', archived: false }],
cards: [{ _id: 'c1', boardId: 'b1', listId: 'l1', swimlaneId: 'sArchived', archived: false }],
});
await runSchemaUpgrade(db, opts);
assert.strictEqual(db._dump('cards')[0].swimlaneId, 'sArchived',
'the card is where its owner put it');
});
await test('a board whose every swimlane is archived is left exactly as it is', async () => {
// Nothing here is broken: an archived swimlane holding archived work is a
// board somebody put away. The step used to create a visible Default and move
// the card into it, which is the reappearance from the report. Where a board
// genuinely needs a swimlane - somebody adds a card to it - the app creates
// one then (models/boards.js getDefaultSwimline -> ensureDefaultSwimlaneId),
// which is the right moment for it.
const db = fakeDb({
boards: [{ _id: 'b1', archived: false }],
swimlanes: [{ _id: 'sArchived', boardId: 'b1', archived: true, sort: 0 }],
lists: [{ _id: 'l1', boardId: 'b1', swimlaneId: 'sArchived', archived: false }],
cards: [{ _id: 'c1', boardId: 'b1', listId: 'l1', swimlaneId: 'sArchived', archived: false }],
});
await runSchemaUpgrade(db, opts);
assert.strictEqual(db._dump('cards')[0].swimlaneId, 'sArchived',
'the card stayed where it was archived');
assert.strictEqual(db._dump('swimlanes').length, 1,
'and no swimlane was invented for data nobody is looking at');
});
await test('negative: ARCHIVED cards under archived swimlanes are left alone (intentionally hidden)', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false }],
swimlanes: [
{ _id: 'sArchived', boardId: 'b1', archived: true, sort: 0 },
{ _id: 'sVisible', boardId: 'b1', archived: false, sort: 1 },
],
lists: [{ _id: 'l1', boardId: 'b1', swimlaneId: 'sVisible', archived: false }],
cards: [{ _id: 'c1', boardId: 'b1', listId: 'l1', swimlaneId: 'sArchived', archived: true }],
});
await runSchemaUpgrade(db, opts);
assert.strictEqual(db._dump('cards')[0].swimlaneId, 'sArchived', 'archived card untouched');
});
await test('cross-board: card pointing at ANOTHER board\'s swimlane is pulled back to its own board', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false }, { _id: 'b2', archived: false }],
swimlanes: [
{ _id: 's1', boardId: 'b1', archived: false, sort: 0 },
{ _id: 's2', boardId: 'b2', archived: false, sort: 0 },
],
lists: [{ _id: 'l1', boardId: 'b1', swimlaneId: 's1', archived: false }],
cards: [{ _id: 'c1', boardId: 'b1', listId: 'l1', swimlaneId: 's2', archived: false }],
});
await runSchemaUpgrade(db, opts);
assert.strictEqual(db._dump('cards')[0].swimlaneId, 's1');
});
await test('merge-per-swimlane-lists: v8.x duplicate list copies merged into one shared list', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false, fixMissingListsCompleted: true }],
swimlanes: [
{ _id: 's1', boardId: 'b1', archived: false, sort: 0 },
{ _id: 's2', boardId: 'b1', archived: false, sort: 1 },
],
lists: [
{ _id: 'l1', boardId: 'b1', title: 'Todo', swimlaneId: 's1', archived: false, createdAt: 1 },
{ _id: 'l2', boardId: 'b1', title: 'Todo', swimlaneId: 's2', archived: false, createdAt: 2 },
],
cards: [
{ _id: 'c1', boardId: 'b1', listId: 'l1', swimlaneId: 's1', archived: false },
{ _id: 'c2', boardId: 'b1', listId: 'l2', swimlaneId: 's2', archived: false },
],
});
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('merge-per-swimlane-lists'));
const lists = db._dump('lists');
assert.strictEqual(lists.length, 1, 'duplicate copy deleted');
assert.strictEqual(lists[0].swimlaneId, '', 'canonical list is SHARED (renders in every swimlane)');
const cards = db._dump('cards');
assert.ok(cards.every(c => c.listId === 'l1'), 'cards repointed to the canonical list');
assert.strictEqual(cards[0].swimlaneId, 's1', 'cards KEEP their swimlane (per-swimlane grouping preserved)');
assert.strictEqual(cards[1].swimlaneId, 's2');
const b = db._dump('boards')[0];
assert.strictEqual(b.fixMissingListsCompleted, undefined, 'era marker cleared so repair tools work again');
});
await test('merge-per-swimlane-lists: v7.98 stamped lists (Shape A) become shared again', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false }],
swimlanes: [
{ _id: 's1', boardId: 'b1', archived: false, sort: 0 },
{ _id: 's2', boardId: 'b1', archived: false, sort: 1 },
],
lists: [{ _id: 'l1', boardId: 'b1', title: 'Todo', swimlaneId: 's1', archived: false }],
cards: [{ _id: 'c2', boardId: 'b1', listId: 'l1', swimlaneId: 's2', archived: false }], // other swimlane's card
});
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('merge-per-swimlane-lists'));
assert.strictEqual(db._dump('lists')[0].swimlaneId, '', 'stamped list unshared so every swimlane renders it');
assert.strictEqual(db._dump('cards')[0].swimlaneId, 's2', 'card untouched');
});
await test('negative: merge-per-swimlane-lists leaves healthy and RENAMED per-swimlane lists alone', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false, fixMissingListsCompleted: true }],
swimlanes: [
{ _id: 's1', boardId: 'b1', archived: false, sort: 0 },
{ _id: 's2', boardId: 'b1', archived: false, sort: 1 },
],
lists: [
{ _id: 'l1', boardId: 'b1', title: 'Todo (team A)', swimlaneId: 's1', archived: false },
{ _id: 'l2', boardId: 'b1', title: 'Todo (team B)', swimlaneId: 's2', archived: false },
],
cards: [
{ _id: 'c1', boardId: 'b1', listId: 'l1', swimlaneId: 's1', archived: false },
{ _id: 'c2', boardId: 'b1', listId: 'l2', swimlaneId: 's2', archived: false },
],
});
await runSchemaUpgrade(db, opts);
const lists = db._dump('lists');
assert.strictEqual(lists.length, 2, 'differently RENAMED copies are kept (their names carry meaning)');
assert.ok(lists.every(l => l.swimlaneId === ''), 'both become shared');
assert.ok(db._dump('cards').every((c, i) => c.listId === ['l1', 'l2'][i]), 'cards keep their own list');
});
// #6787: Admin Panel / Problems / "Restore" binds a list back to the swimlane
// it was created in (positionHistory). This step un-bound it again on every new
// WeKan release, so the "Lists missing their swimlane" count came back to
// exactly the same number after each upgrade.
await test('#6787 merge-per-swimlane-lists keeps a list bound to the swimlane it was created in', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false }],
swimlanes: [
{ _id: 's1', boardId: 'b1', archived: false, sort: 0 },
{ _id: 's2', boardId: 'b1', archived: false, sort: 1 },
],
lists: [
// Restored: bound to its recorded swimlane, its cards there too.
{ _id: 'r1', boardId: 'b1', title: 'Todo', swimlaneId: 's1', archived: false },
{ _id: 'r2', boardId: 'b1', title: 'Todo', swimlaneId: 's2', archived: false },
// A v7.98 stamp on the same board: cards of another swimlane in it.
{ _id: 'st', boardId: 'b1', title: 'Done', swimlaneId: 's1', archived: false },
],
positionHistory: [
{ _id: 'h1', entityType: 'list', entityId: 'r1', originalSwimlaneId: 's1' },
{ _id: 'h2', entityType: 'list', entityId: 'r2', originalSwimlaneId: 's2' },
],
cards: [
{ _id: 'c1', boardId: 'b1', listId: 'r1', swimlaneId: 's1', archived: false },
{ _id: 'c2', boardId: 'b1', listId: 'r2', swimlaneId: 's2', archived: false },
{ _id: 'c3', boardId: 'b1', listId: 'st', swimlaneId: 's2', archived: false },
],
});
await runSchemaUpgrade(db, opts);
const byId = Object.fromEntries(db._dump('lists').map(l => [l._id, l]));
assert.strictEqual(byId.r1 && byId.r1.swimlaneId, 's1', 'restored list stays in its swimlane');
assert.strictEqual(byId.r2 && byId.r2.swimlaneId, 's2', 'and is not merged with its namesake');
assert.strictEqual(byId.st.swimlaneId, '', 'negative: the stamped list on the same board is still un-bound');
});
await test('#6787 a board of only by-design lists does not trigger the step at all', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false }],
swimlanes: [{ _id: 's1', boardId: 'b1', archived: false, sort: 0 }, { _id: 's2', boardId: 'b1', archived: false, sort: 1 }],
lists: [
{ _id: 'r1', boardId: 'b1', title: 'Todo', swimlaneId: 's1', archived: false },
{ _id: 'r2', boardId: 'b1', title: 'Todo', swimlaneId: 's2', archived: false },
],
positionHistory: [
{ _id: 'h1', entityType: 'list', entityId: 'r1', originalSwimlaneId: 's1' },
{ _id: 'h2', entityType: 'list', entityId: 'r2', originalSwimlaneId: 's2' },
],
cards: [],
});
const res = await runSchemaUpgrade(db, opts);
assert.ok(!res.ran.includes('merge-per-swimlane-lists'), 'same titles in their own swimlanes are not era duplicates');
assert.deepStrictEqual(db._dump('lists').map(l => l.swimlaneId), ['s1', 's2']);
});
await test('#6787 negative: a recorded binding does not protect a list whose cards are elsewhere', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false }],
swimlanes: [{ _id: 's1', boardId: 'b1', archived: false, sort: 0 }, { _id: 's2', boardId: 'b1', archived: false, sort: 1 }],
lists: [{ _id: 'l1', boardId: 'b1', title: 'Todo', swimlaneId: 's1', archived: false }],
positionHistory: [{ _id: 'h1', entityType: 'list', entityId: 'l1', originalSwimlaneId: 's1' }],
cards: [{ _id: 'c1', boardId: 'b1', listId: 'l1', swimlaneId: 's2', archived: false }],
});
await runSchemaUpgrade(db, opts);
assert.strictEqual(db._dump('lists')[0].swimlaneId, '', 'binding it would hide the card, so it is shared');
});
await test('#6787 negative: a list bound somewhere OTHER than its record is still un-bound', async () => {
const db = fakeDb({
boards: [{ _id: 'b1', archived: false, fixMissingListsCompleted: true }],
swimlanes: [{ _id: 's1', boardId: 'b1', archived: false, sort: 0 }, { _id: 's2', boardId: 'b1', archived: false, sort: 1 }],
lists: [{ _id: 'l1', boardId: 'b1', title: 'Todo', swimlaneId: 's1', archived: false }],
positionHistory: [{ _id: 'h1', entityType: 'list', entityId: 'l1', originalSwimlaneId: 's2' }],
cards: [],
});
await runSchemaUpgrade(db, opts);
assert.strictEqual(db._dump('lists')[0].swimlaneId, '');
});
await test('write path (#1959/#1971): card insert hook validates client-supplied swimlaneIds', () => {
const hook = read('server/migrations/ensureValidSwimlaneIds.js');
assert.ok(hook.includes('#1959/#1971'), 'the visibility fix is documented at the hook');
const insertHook = hook.match(/Cards\.before\.insert\([\s\S]*?\n \}\);/)[0];
assert.ok(/if \(doc\.swimlaneId\) \{/.test(insertHook),
'a PROVIDED swimlaneId must be validated, not only a missing one');
assert.ok(insertHook.includes('archived: false'), 'must resolve to a VISIBLE swimlane');
assert.ok(insertHook.includes('boardId: doc.boardId'), 'must belong to the same board');
});
// ── checklist-items-embedded ─────────────────────────────────────────────────
await test('checklist-items-embedded: extracts pre-v0.79 embedded items to ChecklistItems', async () => {
const db = fakeDb({
checklists: [{
_id: 'ck1', cardId: 'c1', title: 'Todo',
items: [
{ title: 'second', sort: 2, isFinished: true },
{ title: 'first', sort: 1, isFinished: false },
{ sort: 3 }, // untitled item — original migration used 'Checklist'
],
}],
});
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('checklist-items-embedded'));
const items = db._dump('checklistItems');
assert.strictEqual(items.length, 3);
assert.deepStrictEqual(items.map(i => i.title), ['first', 'second', 'Checklist'], 'sorted by embedded sort');
assert.deepStrictEqual(items.map(i => i.sort), [0, 1, 2], 're-numbered like the v8.00 migration');
assert.strictEqual(items[1].isFinished, true);
assert.ok(items.every(i => i.checklistId === 'ck1' && i.cardId === 'c1' && i._id.length === 17));
assert.strictEqual(db._dump('checklists')[0].items, undefined, 'embedded array removed');
});
await test('negative: checklist extraction does not duplicate items on a re-run after a crash', async () => {
const db = fakeDb({
checklists: [{ _id: 'ck1', cardId: 'c1', items: [{ title: 'a', sort: 0 }, { title: 'b', sort: 1 }] }],
// 'a' was already extracted before the interruption:
checklistItems: [{ _id: 'x1', checklistId: 'ck1', cardId: 'c1', title: 'a', sort: 0, isFinished: false }],
});
await runSchemaUpgrade(db, opts);
const items = db._dump('checklistItems');
assert.strictEqual(items.length, 2, 'no duplicate of "a"');
});
// ── customfields-boardIds ────────────────────────────────────────────────────
await test('customfields-boardIds: scalar boardId becomes boardIds array', async () => {
const db = fakeDb({ customFields: [{ _id: 'cf1', name: 'Severity', boardId: 'b1' }] });
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('customfields-boardIds'));
const cf = db._dump('customFields')[0];
assert.deepStrictEqual(cf.boardIds, ['b1']);
assert.strictEqual(cf.boardId, undefined);
});
await test('negative: customfields with an existing boardIds array only lose the stale scalar', async () => {
const db = fakeDb({ customFields: [{ _id: 'cf1', boardId: 'old', boardIds: ['b1', 'b2'] }] });
await runSchemaUpgrade(db, opts);
const cf = db._dump('customFields')[0];
assert.deepStrictEqual(cf.boardIds, ['b1', 'b2'], 'existing array untouched');
assert.strictEqual(cf.boardId, undefined);
});
// ── board-allows-defaults ────────────────────────────────────────────────────
await test('board-allows-defaults: missing true-default flags are backfilled, explicit false respected', async () => {
const db = fakeDb({ boards: [
{ _id: 'b1', allowsComments: false }, // user turned comments OFF
{ _id: 'b2' }, // ancient board: nothing set
] });
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('board-allows-defaults'));
const [b1, b2] = db._dump('boards');
assert.strictEqual(b1.allowsComments, false, 'explicit user choice untouched');
assert.strictEqual(b1.allowsChecklists, true, 'missing flag backfilled');
assert.strictEqual(b2.allowsDescriptionText, true);
assert.strictEqual(b2.allowsAttachments, true);
});
await test('the true-defaults list stays in sync with models/boards.js', () => {
const src = read('models/boards.js');
const re = /(allows[A-Za-z0-9]+):\s*\{[^}]*?defaultValue:\s*(true|false)/g;
const fromSchema = [];
let m;
while ((m = re.exec(src))) if (m[2] === 'true') fromSchema.push(m[1]);
assert.deepStrictEqual([...BOARD_ALLOWS_TRUE_DEFAULTS].sort(), fromSchema.sort(),
'BOARD_ALLOWS_TRUE_DEFAULTS must match the schema defaults (update both together)');
});
// ── board-members-isactive ───────────────────────────────────────────────────
await test('board-members-isactive: missing isActive becomes true, explicit false stays false', async () => {
const db = fakeDb({ boards: [
{ _id: 'b1', members: [{ userId: 'u1' }, { userId: 'u2', isActive: false }, { userId: 'u3', isActive: true }] },
] });
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('board-members-isactive'));
const members = db._dump('boards')[0].members;
assert.strictEqual(members[0].isActive, true, 'pre-2015 member regains access');
assert.strictEqual(members[1].isActive, false, 'deactivated member stays deactivated');
assert.strictEqual(members[2].isActive, true);
});
// ── board-permission-lowercase ───────────────────────────────────────────────
await test('board-permission-lowercase: PUBLIC boards become public again (batched updateMany)', async () => {
const db = fakeDb({ boards: [
{ _id: 'b1', permission: 'PUBLIC' },
{ _id: 'b2', permission: 'private' },
] });
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('board-permission-lowercase'));
assert.strictEqual(db._dump('boards')[0].permission, 'public');
assert.strictEqual(db._dump('boards')[1].permission, 'private', 'already-lowercase untouched');
});
// ── checklist-minicard-unset (email report: "Show on minicard" did nothing) ──
// The old schema wrote showChecklistAtMinicard: false on every checklist, and the
// minicard ORed it with the board default - so that false meant "follow the board".
// It is an OVERRIDE now, so the same false would mean "hide this one", and leaving
// the ones the default wrote would hide every checklist on every minicard: the
// mirror image of the reported bug. They are cleared ONCE.
const clUnsetStep = steps.find(s => s.name === 'checklist-minicard-unset');
await test('checklist-minicard-unset: the old default is cleared, an explicit true is kept', async () => {
const db = fakeDb({
checklists: [
{ _id: 'k1', showChecklistAtMinicard: false }, // written by the old default
{ _id: 'k2', showChecklistAtMinicard: true }, // somebody asked for this one
{ _id: 'k3' }, // already has no opinion
],
});
assert.strictEqual(await clUnsetStep.check(db), true, 'the old default is detected');
const res = await clUnsetStep.run(db);
assert.strictEqual(res.fixed, 1, 'only the false is touched');
const by = id => db._dump('checklists').find(c => c._id === id);
assert.strictEqual('showChecklistAtMinicard' in by('k1'), false,
'cleared, so the checklist follows the board exactly as it did before');
assert.strictEqual(by('k2').showChecklistAtMinicard, true, 'an explicit yes is not data to clean up');
assert.strictEqual('showChecklistAtMinicard' in by('k3'), false);
});
await test('checklist-minicard-unset: runs ONCE EVER, so a later "hidden" survives the next release (negative)', async () => {
const db = fakeDb({ checklists: [{ _id: 'k1', showChecklistAtMinicard: false }] });
await clUnsetStep.run(db);
// After the step, a false is a CHOICE - somebody switched "Show on minicard" off.
// Every other step here may re-run on the next version because re-running changes
// nothing; this one would quietly put their checklist back on the minicard.
db._dump('checklists')[0].showChecklistAtMinicard = false;
assert.strictEqual(await clUnsetStep.check(db), false,
'the marker has to stop it, not the absence of matching documents');
assert.strictEqual(db._dump('checklists')[0].showChecklistAtMinicard, false,
'and the choice stands');
});
// ── cover-on-card-on (the opened card shows its cover by default) ──────────
// The cover on the opened card was opt-in, and the schema's false was written
// into every board created since. Turned on ONCE; after that a false is a choice.
const coverStep = steps.find(s => s.name === 'cover-on-card-on');
await test('cover-on-card-on: boards that never chose show the cover', async () => {
const db = fakeDb({ boards: [
{ _id: 'b1', allowsCoverAttachmentOnCard: false },
{ _id: 'b2', allowsCoverAttachmentOnCard: true },
{ _id: 'b3' },
] });
assert.strictEqual(await coverStep.check(db), true);
const res = await coverStep.run(db);
assert.strictEqual(res.fixed, 2);
assert.ok(db._dump('boards').every(b => b.allowsCoverAttachmentOnCard === true));
});
await test('cover-on-card-on: ONCE EVER - a later "off" stands (negative)', async () => {
const db = fakeDb({ boards: [{ _id: 'b1', allowsCoverAttachmentOnCard: false }] });
await coverStep.run(db);
db._dump('boards')[0].allowsCoverAttachmentOnCard = false; // turned off afterwards
assert.strictEqual(await coverStep.check(db), false, 'the marker stops it');
assert.strictEqual(db._dump('boards')[0].allowsCoverAttachmentOnCard, false);
});
await test('cover-on-card-on: a new install with no board marks it done, so a later "off" stands (negative)', async () => {
const db = fakeDb({ boards: [] });
assert.strictEqual(await coverStep.check(db), false, 'nothing to turn on');
db._dump('boards').push({ _id: 'b9', allowsCoverAttachmentOnCard: false });
assert.strictEqual(await coverStep.check(db), false, 'and the marker is written, so it never runs later');
});
// ── custom-fields-minicard-on (fields "Show on card" stay on the minicard) ─
// The minicard switch for custom fields is opt-in and false in every board. A
// board with a field marked "Show on card" had that field on its minicards
// before; it is turned on there, ONCE.
const cfMinicardStep = steps.find(s => s.name === 'custom-fields-minicard-on');
await test('custom-fields-minicard-on: boards with a "Show on card" field keep it on the minicard', async () => {
const db = fakeDb({
customFields: [
{ _id: 'f1', boardIds: ['b1', 'b2'], showOnCard: true },
{ _id: 'f2', boardIds: ['b3'], showOnCard: false },
{ _id: 'f3', boardIds: ['b4'], showOnCard: true },
],
boards: [
{ _id: 'b1', allowsCustomFieldsOnMinicard: false },
{ _id: 'b2' },
{ _id: 'b3', allowsCustomFieldsOnMinicard: false },
{ _id: 'b4', allowsCustomFieldsOnMinicard: true },
{ _id: 'b5', allowsCustomFieldsOnMinicard: false },
],
});
assert.strictEqual(await cfMinicardStep.check(db), true);
const res = await cfMinicardStep.run(db);
assert.strictEqual(res.fixed, 2);
const on = Object.fromEntries(db._dump('boards').map(b => [b._id, b.allowsCustomFieldsOnMinicard]));
assert.deepStrictEqual(on, { b1: true, b2: true, b3: false, b4: true, b5: false },
'only boards with a "Show on card" field; the others keep the opt-in default');
});
await test('custom-fields-minicard-on: ONCE EVER - a later "off" stands (negative)', async () => {
const db = fakeDb({
customFields: [{ _id: 'f1', boardIds: ['b1'], showOnCard: true }],
boards: [{ _id: 'b1', allowsCustomFieldsOnMinicard: false }],
});
await cfMinicardStep.run(db);
db._dump('boards')[0].allowsCustomFieldsOnMinicard = false; // turned off afterwards
assert.strictEqual(await cfMinicardStep.check(db), false, 'the marker stops it');
assert.strictEqual(db._dump('boards')[0].allowsCustomFieldsOnMinicard, false);
});
await test('custom-fields-minicard-on: no "Show on card" field anywhere marks it done (negative)', async () => {
const db = fakeDb({ customFields: [], boards: [{ _id: 'b1', allowsCustomFieldsOnMinicard: false }] });
assert.strictEqual(await cfMinicardStep.check(db), false, 'nothing to turn on');
db._dump('customFields').push({ _id: 'f9', boardIds: ['b1'], showOnCard: true });
assert.strictEqual(await cfMinicardStep.check(db), false, 'a field added later is a choice made with the switch in place');
});
// ── nonfinite-sort-repair (#6481) ────────────────────────────────────────────
// The global fakeDb JSON-clones documents, which turns Infinity/NaN into null,
// so build a NON-cloning db here to keep the non-finite sorts intact and drive
// the step object directly (it uses only findOne + updateMany).
function liveSortDb(initial) {
const data = new Map(Object.entries(initial));
return {
collection(name) {
if (!data.has(name)) data.set(name, []);
const arr = data.get(name);
return {
async findOne(filter) { return arr.find(d => matches(d, filter)) || null; },
async updateMany(filter, update) {
let n = 0;
for (const d of arr) if (matches(d, filter)) { applyUpdate(d, update); n++; }
return { modifiedCount: n };
},
};
},
_dump: name => data.get(name) || [],
};
}
const sortStep = steps.find(s => s.name === 'nonfinite-sort-repair');
await test('nonfinite-sort-repair: +Inf / -Inf / NaN sorts reset to 0, finite ones untouched', async () => {
const cards = [
{ _id: 'c1', sort: Infinity },
{ _id: 'c2', sort: -Infinity },
{ _id: 'c3', sort: NaN },
{ _id: 'c4', sort: 5 }, // finite -> keep
{ _id: 'c5', sort: 0 }, // finite -> keep
{ _id: 'c6' }, // missing sort -> not numeric, ignore
{ _id: 'c7', sort: 'x' }, // non-numeric -> ignore
];
const db = liveSortDb({ cards });
assert.strictEqual(await sortStep.check(db), true, 'non-finite sorts are detected');
const res = await sortStep.run(db);
assert.strictEqual(res.fixed, 3, 'exactly the three non-finite cards are repaired');
const by = id => cards.find(c => c._id === id);
assert.strictEqual(by('c1').sort, 0);
assert.strictEqual(by('c2').sort, 0);
assert.strictEqual(by('c3').sort, 0);
assert.strictEqual(by('c4').sort, 5, 'finite sort left as-is');
assert.strictEqual(by('c5').sort, 0);
assert.strictEqual(by('c6').sort, undefined, 'missing sort not invented');
assert.strictEqual(by('c7').sort, 'x', 'non-numeric sort not touched');
// idempotent: a second run finds nothing to do
assert.strictEqual(await sortStep.check(db), false);
});
await test('nonfinite-sort-repair: repairs every sorted collection (lists/swimlanes/checklists/checklistItems)', async () => {
const db = liveSortDb({
lists: [{ _id: 'l1', sort: Infinity }],
swimlanes: [{ _id: 's1', sort: NaN }],
checklists: [{ _id: 'k1', sort: -Infinity }],
checklistItems: [{ _id: 'i1', sort: Infinity }, { _id: 'i2', sort: 2 }],
});
const res = await sortStep.run(db);
assert.strictEqual(res.fixed, 4);
assert.strictEqual(db._dump('lists')[0].sort, 0);
assert.strictEqual(db._dump('swimlanes')[0].sort, 0);
assert.strictEqual(db._dump('checklists')[0].sort, 0);
assert.strictEqual(db._dump('checklistItems')[0].sort, 0);
assert.strictEqual(db._dump('checklistItems')[1].sort, 2);
});
await test('negative: nonfinite-sort-repair does not run on healthy finite sorts', async () => {
const db = liveSortDb({ cards: [{ _id: 'c1', sort: 0 }, { _id: 'c2', sort: 1e300 }, { _id: 'c3', sort: -1e300 }] });
assert.strictEqual(await sortStep.check(db), false);
const res = await sortStep.run(db);
assert.strictEqual(res.fixed, 0);
});
await test('negative: the non-finite predicate uses only finite literals (FerretDB rejects Infinity/NaN in filters)', () => {
const src = read('server/lib/schemaUpgradeSteps.js');
const block = src.slice(src.indexOf('const NON_FINITE_SORT'), src.indexOf('const SORTED_COLLECTIONS'));
assert.ok(!/Infinity|NaN/.test(block), 'predicate must not embed Infinity/NaN literals');
assert.ok(/\$type/.test(block) && /\$nor/.test(block), 'matches non-finite numeric sorts via $type + $nor bounds');
});
// ── fs-path-heal ─────────────────────────────────────────────────────────────
await test('fs-path-heal: stale-path record repointed to the binary found under the old uploads layout', async () => {
const attachDir = path.join(tmpWritable, 'files', 'attachments');
const oldDir = path.join(tmpWritable, 'files', 'uploads', 'attachments');
fs.mkdirSync(attachDir, { recursive: true });
fs.mkdirSync(oldDir, { recursive: true });
fs.writeFileSync(path.join(oldDir, 'legacy.bin'), 'legacy-bytes');
const db = fakeDb({ attachments: [{
_id: 'a1', name: 'legacy.bin',
versions: { original: { storage: 'fs', path: '/nonexistent/old/legacy.bin', size: 12 } },
}] });
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('fs-path-heal'));
const a = db._dump('attachments')[0];
assert.ok(a.versions.original.path.startsWith(attachDir), 'repointed into the current layout');
assert.ok(fs.existsSync(a.versions.original.path), 'binary copied');
assert.strictEqual(fs.readFileSync(a.versions.original.path, 'utf8'), 'legacy-bytes');
assert.strictEqual(a.versions.original.storage, 'fs');
});
await test('fs-path-heal: flagless record without gridFsFileId (failed v6.10-18 GridFS copy) is healed too', () => {
assert.strictEqual(versionNeedsHeal({}, { size: 1, path: '/gone' }), true, 'no flag + no gridFsFileId + missing path');
assert.strictEqual(versionNeedsHeal({}, { size: 1, meta: { gridFsFileId: 'x' } }), false, 'gridfs reference -> not an fs heal case');
assert.strictEqual(versionNeedsHeal({}, { storage: 's3', path: '/gone' }), false, 'cloud storage untouched');
});
await test('negative: fs-path-heal with an unfindable binary leaves the version UN-STAMPED so the next boot re-checks', async () => {
const db = fakeDb({ avatars: [{
_id: 'av1', name: 'gone.png',
versions: { original: { storage: 'fs', path: '/nonexistent/gone.png' } },
}] });
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.ran.includes('fs-path-heal'));
assert.strictEqual(res.results['fs-path-heal'].unresolved, 1);
const marker = await db.collection('_wekan_migration').findOne({ _id: MARKER_ID });
assert.ok(!marker || !marker.lastCheck || marker.lastCheck.version !== opts.appVersion,
'unresolved work must keep the version un-stamped (re-check next boot)');
});
// ── version gating: re-check mandatory only after a NEW RELEASE ───────────────
await test('same WeKan version: second boot is gated to a single findOne (no scans, no fixes)', async () => {
const db = fakeDb({});
const first = await runSchemaUpgrade(db, opts);
assert.strictEqual(first.gated, false);
const marker = await db.collection('_wekan_migration').findOne({ _id: MARKER_ID });
assert.strictEqual(marker.lastCheck.version, opts.appVersion, 'version + datetime recorded');
assert.ok(marker.lastCheck.at, 'datetime of the re-check saved');
// plant NEW old-shape data; same version -> must NOT be scanned or touched
await db.collection('checklists').insertOne({ _id: 'ck9', cardId: 'c9', items: [{ title: 'x', sort: 0 }] });
const before = { ...db._ops };
const second = await runSchemaUpgrade(db, opts);
assert.strictEqual(second.gated, true, 'gated: version unchanged');
assert.strictEqual(second.ran.length, 0);
assert.strictEqual(db._dump('checklistItems').length, 0, 'no work performed while gated');
assert.ok(db._ops.findOne - before.findOne <= 2, 'gated boot costs at most the marker read (+product name)');
assert.strictEqual(db._ops.updateMany, before.updateMany, 'no writes while gated');
});
await test('NEW WeKan version: the re-check is mandatory and picks up newly-broken data', async () => {
const db = fakeDb({});
await runSchemaUpgrade(db, opts); // v9.97.0 clean
await db.collection('checklists').insertOne({ _id: 'ck9', cardId: 'c9', items: [{ title: 'x', sort: 0 }] });
const res = await runSchemaUpgrade(db, { ...opts, appVersion: 'v9.98.0' });
assert.strictEqual(res.gated, false, 'new release -> full re-check');
assert.ok(res.ran.includes('checklist-items-embedded'));
assert.strictEqual(db._dump('checklistItems').length, 1, 'the new old-shape data was migrated');
const marker = await db.collection('_wekan_migration').findOne({ _id: MARKER_ID });
assert.strictEqual(marker.lastCheck.version, 'v9.98.0');
});
await test('force option overrides the version gate', async () => {
const db = fakeDb({});
await runSchemaUpgrade(db, opts);
await db.collection('boards').insertOne({ _id: 'b1', permission: 'PUBLIC' });
const res = await runSchemaUpgrade(db, { ...opts, force: true });
assert.strictEqual(res.gated, false);
assert.strictEqual(db._dump('boards')[0].permission, 'public');
});
await test('negative: unresolved work prevents the version stamp; the SAME version re-checks once a day, not at every start', async () => {
const db = fakeDb({ avatars: [{ _id: 'av1', name: 'gone.png', versions: { original: { storage: 'fs', path: '/nonexistent/gone.png' } } }] });
await runSchemaUpgrade(db, opts); // unresolved heal
const marker = await db.collection('_wekan_migration').findOne({ _id: MARKER_ID });
assert.ok(!marker.lastCheck, 'version NOT stamped');
assert.strictEqual(marker.lastAttempt.version, opts.appVersion, 'the unclean attempt is recorded');
const before = { ...db._ops };
const res2 = await runSchemaUpgrade(db, opts); // restart a minute later
assert.strictEqual(res2.gated, true, 'a restart within the retry period does not scan again');
assert.ok(db._ops.findOne - before.findOne <= 2 && db._ops.distinct === before.distinct && db._ops.find === before.find,
'gated retry costs the marker read only');
// a day later
await db.collection('_wekan_migration').updateOne({ _id: MARKER_ID },
{ $set: { 'lastAttempt.atMs': Date.now() - RETRY_UNCLEAN_MS - 1000 } });
const res3 = await runSchemaUpgrade(db, opts);
assert.strictEqual(res3.gated, false, 'retried after the retry period');
});
await test('a clean run after an unclean one stamps the version and clears lastAttempt', async () => {
const db = fakeDb({ avatars: [{ _id: 'av1', name: 'gone.png', versions: { original: { storage: 'fs', path: '/nonexistent/gone.png' } } }] });
await runSchemaUpgrade(db, opts);
db._dump('avatars').length = 0;
await runSchemaUpgrade(db, { ...opts, force: true });
const marker = await db.collection('_wekan_migration').findOne({ _id: MARKER_ID });
assert.strictEqual(marker.lastCheck.version, opts.appVersion);
assert.ok(!marker.lastAttempt, 'lastAttempt cleared');
});
await test('one server at a time: while another server holds the claim, a start skips every scan', async () => {
const db = fakeDb({ boards: [{ _id: 'b1', permission: 'PUBLIC' }] });
await db.collection('_wekan_migration').insertOne({ _id: CLAIM_ID, sinceMs: Date.now(), version: opts.appVersion });
const before = { ...db._ops };
const res = await runSchemaUpgrade(db, opts);
assert.strictEqual(res.gated, true);
assert.strictEqual(res.ran.length, 0);
assert.strictEqual(db._dump('boards')[0].permission, 'PUBLIC', 'nothing touched: the claim holder does the work');
assert.strictEqual(db._ops.distinct, before.distinct);
assert.strictEqual(db._ops.find, before.find);
const claim = await db.collection('_wekan_migration').findOne({ _id: CLAIM_ID });
assert.ok(claim, "the other server's claim is left alone");
});
await test('a stale claim (server killed mid-run) is taken over, and released afterwards', async () => {
const db = fakeDb({ boards: [{ _id: 'b1', permission: 'PUBLIC' }] });
await db.collection('_wekan_migration').insertOne({ _id: CLAIM_ID, sinceMs: Date.now() - CLAIM_STALE_MS - 1000, version: opts.appVersion });
const res = await runSchemaUpgrade(db, opts);
assert.strictEqual(res.gated, false);
assert.strictEqual(db._dump('boards')[0].permission, 'public');
assert.strictEqual(await db.collection('_wekan_migration').findOne({ _id: CLAIM_ID }), null, 'claim released');
});
await test('a server that claims just after another finished reads the fresh marker and does not scan again', async () => {
const db = fakeDb({});
await runSchemaUpgrade(db, opts); // server A, clean
const stale = {}; // server B read the marker before A finished
const real = db.collection;
let first = true;
db.collection = name => {
const c = real(name);
if (name !== '_wekan_migration') return c;
return { ...c, findOne: async (f, o) => {
if (first && f && f._id === MARKER_ID) { first = false; return stale; }
return c.findOne(f, o);
} };
};
const before = { ...db._ops };
const res = await runSchemaUpgrade(db, opts);
assert.strictEqual(res.gated, true);
assert.strictEqual(db._ops.distinct, before.distinct, 'no step ran');
assert.strictEqual(await real('_wekan_migration').findOne({ _id: CLAIM_ID }), null, 'claim released');
});
// ── orchestrator semantics ───────────────────────────────────────────────────
await test('healthy database: everything skipped, version stamped', async () => {
const db = fakeDb({});
const res = await runSchemaUpgrade(db, opts);
assert.strictEqual(res.ran.length, 0);
const marker = await db.collection('_wekan_migration').findOne({ _id: MARKER_ID });
assert.ok(marker && marker.lastCheck, 'lastCheck written so later boots cost one findOne');
});
await test('a throwing step never breaks the run: later steps still execute, version stays un-stamped', async () => {
const db = fakeDb({ boards: [{ _id: 'b1', permission: 'PUBLIC' }] });
const real = db.collection;
db.collection = name => {
const c = real(name);
if (name === 'checklists') return { ...c, findOne: async () => { throw new Error('boom'); } };
return c;
};
const res = await runSchemaUpgrade(db, opts);
assert.ok(res.results['checklist-items-embedded'].error, 'failure recorded');
assert.ok(res.ran.includes('board-permission-lowercase'), 'later steps still ran');
assert.strictEqual(db._dump('boards')[0].permission, 'public');
const marker = await db.collection('_wekan_migration').findOne({ _id: MARKER_ID });
assert.ok(!marker || !marker.lastCheck, 'failed step keeps the version un-stamped');
});
// ── progress state for the migration dashboard ───────────────────────────────
await test('dashboard state: progress, per-step results, and the product name when set', async () => {
const db = fakeDb({
settings: [{ _id: 's1', productName: 'AcmeBoards' }],
boards: [{ _id: 'b1', permission: 'PUBLIC' }],
});
await runSchemaUpgrade(db, opts);
const state = getUpgradeState();
assert.strictEqual(state.product, 'AcmeBoards', 'dashboard shows the Admin Panel product name, not WeKan');
assert.strictEqual(state.running, false);
assert.ok(state.startedAt && state.finishedAt);
assert.strictEqual(state.steps['board-permission-lowercase'].status, 'done');
assert.strictEqual(state.steps['board-permission-lowercase'].fixed, 1);
assert.strictEqual(state.steps['checklist-items-embedded'].status, 'skipped');
});
await test('negative: no product name set -> dashboard says WeKan', async () => {
const db = fakeDb({});
await runSchemaUpgrade(db, opts);
assert.strictEqual(getUpgradeState().product, 'WeKan');
});
// ── wiring ───────────────────────────────────────────────────────────────────
await test('the startup wrapper is imported, non-blocking, and serves the dashboard route', () => {
assert.ok(read('server/imports.js').includes("import '/server/startupSchemaUpgrade'"));
const wrapper = read('server/startupSchemaUpgrade.js');
assert.ok(wrapper.includes('runSchemaUpgrade'));
assert.ok(wrapper.includes('Meteor.startup'));
assert.ok(wrapper.includes('WEKAN_SKIP_SCHEMA_UPGRADE'), 'opt-out env var exists');
assert.ok(wrapper.includes("WebApp.handlers.get('/schema-upgrade-status'"), 'dashboard route registered');
assert.ok(wrapper.includes('state.product'), 'dashboard uses the product name');
assert.ok(/Deliberately NOT awaited/i.test(wrapper), 'upgrade must not block WeKan from serving');
assert.ok(wrapper.includes("require('/package.json').version"), 'version for the release gate');
});
await test('the importer no longer stamps the flags that disabled the repair tools', () => {
const importer = read('releases/migrate-mongodb-to-ferretdb.mjs');
const fn = importer.match(/function upgradeBoard\(doc\) \{[\s\S]*?\n\}/)[0];
assert.ok(!fn.includes('comprehensiveMigrationCompleted: true'));
assert.ok(!fn.includes('fixMissingListsCompleted: true'));
assert.ok(fn.includes('migrationVersion: SCHEMA_VER'));
});
await test('speed: importer text phase batches with insertMany and only falls back per-document', () => {
const importer = read('releases/migrate-mongodb-to-ferretdb.mjs');
const flush = importer.match(/const flush = async \(\) => \{[\s\S]*?\n \};/)[0];
assert.ok(flush.includes('insertMany(batch, { ordered: false })'),
'one round trip per batch — per-document replaceOne made big migrations take hours');
assert.ok(flush.includes('replaceOne({ _id: doc._id }, doc, { upsert: true })'),
'per-document fallback for resumed/re-run migrations still exists');
});
await test('speed: importer file phases use the preloaded target map, not per-file findOne', () => {
const importer = read('releases/migrate-mongodb-to-ferretdb.mjs');
assert.ok(importer.includes('async function getTgtRec(collName, id)'));
assert.ok((importer.match(/await getTgtRec\(/g) || []).length >= 4,
'CFS phase, FS-store phase, pass A and pass B all use the cache');
assert.ok(importer.includes('TGT_PRELOAD_LIMIT'),
'very large collections fall back to per-file lookups to bound memory');
});
console.log(`schemaUpgradeSteps.test.cjs: ${passed} tests passed`);
})().catch(e => { console.error('FAIL:', e); process.exit(1); });