Files
wekan/models/lib/changeHistoryGroups.js
T
Lauri Ojansivu 01968fc637 History on FerretDB: date paths are stored as strings, and the migration reports refused documents.
A History row of a date-valued custom field held datePaths as an array of
path arrays, [["3","value"]]. FerretDB v1 does not store an array inside an
array, so on FerretDB the change was not recorded, and migrateTextDatabase
to FerretDB dropped those rows while it swallowed the per-document error and
still reported success.

Each path is now a JSON string, '["3","value"]'. Rows already written in
the array form on MongoDB still restore, and the migration to FerretDB
rewrites them to strings. The migration counts every document the target
refuses and ends as failed with the count per collection and the first
error, instead of success: true.

Thanks to vijlautens and xet7 !

Fixes #6832.
2026-10-29 16:58:21 +02:00

343 lines
12 KiB
JavaScript

'use strict';
// Which group of the card details view a changed field belongs to, and what a
// history row should store for it.
// docs/Features/General/History/History.md §3 (groups) and §4 (content shapes).
//
// Pure and Meteor-free so it is unit-tested directly
// (tests/changeHistoryGroups.test.cjs). It is the table that phase 5 - "roll out
// to every remaining group/entity" - is made of: recording a new field is an
// entry here, not another call site.
//
// WHY A TABLE AND NOT A CALL PER SETTER. §5 suggests "a thin, central choke
// point ... recording history next to Activities.insert avoids sprinkling calls
// everywhere". A hook that diffs the changed fields is that choke point: it
// catches the REST API, imports and rules-engine writes too, none of which go
// through the client setters. The price is that the hook has to be told which
// fields matter and which are noise - that is this file.
/*
* field -> group, per entity type. A field absent from these maps is NOT
* recorded: modifiedAt, dateLastActivity, sort bookkeeping and the denormalised
* counters change on almost every write, and a history full of them is a
* history nobody reads.
*/
const CARD_FIELDS = {
title: 'title',
description: 'description',
labelIds: 'labels',
members: 'members',
assignees: 'assignees',
requesters: 'members',
assigners: 'assignees',
receivedAt: 'dates',
startAt: 'dates',
dueAt: 'dates',
endAt: 'dates',
dueComplete: 'dates',
spentTime: 'dates',
isOvertime: 'dates',
customFields: 'customFields',
cardDependencies: 'dependencies',
color: 'title',
vote: 'customFields',
poker: 'customFields',
archived: 'lifecycle',
deletedAt: 'lifecycle',
// Position is recorded explicitly by Card.move, which knows the whole move as
// one change; the hook would otherwise report the same drag as up to four
// separate field edits.
};
const LIST_FIELDS = {
title: 'title',
color: 'title',
wipLimit: 'title',
archived: 'lifecycle',
deletedAt: 'lifecycle',
};
const SWIMLANE_FIELDS = {
title: 'title',
color: 'title',
archived: 'lifecycle',
deletedAt: 'lifecycle',
};
const CHECKLIST_FIELDS = {
title: 'checklists',
hideCheckedChecklistItems: 'checklists',
hideAllChecklistItems: 'checklists',
};
const CHECKLIST_ITEM_FIELDS = {
title: 'checklists',
isFinished: 'checklists',
};
const COMMENT_FIELDS = {
text: 'comments',
};
/*
* An attachment (History.md §12.2): a rename is the one field edit worth a row.
* Its soft delete and restore are lifecycle rows written by
* server/attachmentSoftDelete.js, with the filename in the content, so the
* bookkeeping fields are deliberately NOT listed here - the diffing hook would
* otherwise describe the same delete a second time as three field edits.
*/
const ATTACHMENT_FIELDS = {
name: 'attachments',
};
const FIELDS_BY_ENTITY = {
card: CARD_FIELDS,
list: LIST_FIELDS,
swimlane: SWIMLANE_FIELDS,
checklist: CHECKLIST_FIELDS,
checklistItem: CHECKLIST_ITEM_FIELDS,
comment: COMMENT_FIELDS,
attachment: ATTACHMENT_FIELDS,
};
/* Fields that are never worth a row, whatever the entity. */
const NEVER_RECORD = new Set([
'_id', 'modifiedAt', 'dateLastActivity', 'createdAt', 'updatedAt',
'sort', 'subtaskSort', 'boardId', 'swimlaneId', 'listId', 'cardId', 'parentId',
]);
function groupForField(entityType, field) {
if (NEVER_RECORD.has(field)) return null;
const map = FIELDS_BY_ENTITY[entityType];
if (!map) return null;
return map[field] || null;
}
/*
* The content a row stores for one field (§4: blackbox, "each entity/group
* stores what it needs"). Kept deliberately simple and uniform - `{ field,
* value }` - because the restore side reads it back by field name, and a
* bespoke shape per field would mean a bespoke applier per field.
*
* A Date becomes a number so the row survives a JSON round trip through the
* snap's database merge unchanged; anything unserialisable is dropped rather
* than stored as something a restore would write back wrong.
*/
function contentForField(field, value) {
if (value === undefined) return null;
if (value === null) return { field, value: null };
if (value instanceof Date) return { field, value: value.getTime(), isDate: true };
const type = typeof value;
if (type === 'string' || type === 'number' || type === 'boolean') {
return { field, value };
}
if (Array.isArray(value)) {
// Label ids, member ids, custom field values: arrays of scalars or plain
// objects, which is what every array field on these entities holds.
try {
return nestedContent(field, value);
} catch {
return null;
}
}
if (type === 'object') {
try {
return nestedContent(field, value);
} catch {
return null;
}
}
return null;
}
// JSON invokes Date.toJSON before a replacer sees it. Visit the original tree
// and record explicit paths instead; ISO-looking user strings remain strings.
// Each path is stored as a JSON string, '["3","value"]': FerretDB v1 rejects an
// array inside an array, and an array of path arrays lost the whole History row
// there (#6832). A JSON string cannot be mistaken whatever the keys contain.
function nestedContent(field, value) {
const datePaths = [];
const ancestors = new Set();
function encode(item, path) {
if (item instanceof Date) {
if (!Number.isFinite(item.getTime())) throw new Error('Invalid History date');
datePaths.push(JSON.stringify(path));
return item.getTime();
}
if (!item || typeof item !== 'object') return item;
if (ancestors.has(item)) throw new Error('Circular History content');
ancestors.add(item);
const result = Array.isArray(item)
? item.map((entry, index) => encode(entry, [...path, String(index)]))
: Object.fromEntries(Object.keys(item).map(key => [key, encode(item[key], [...path, key])]));
ancestors.delete(item);
return result;
}
const encoded = JSON.parse(JSON.stringify(encode(value, [])));
return { field, value: encoded, ...(datePaths.length ? { datePaths } : {}) };
}
function parseDatePath(stored) {
try { return JSON.parse(stored); } catch (_) { throw new Error('Invalid History date path'); }
}
/*
* A changeHistory row with the pre-#6832 array-of-arrays datePaths, rewritten
* to the string form FerretDB v1 stores. Used when a database is copied to
* FerretDB; anything else is returned as it is, the same object.
*/
function withStringDatePaths(row) {
if (!row || typeof row !== 'object') return row;
let copy = row;
for (const side of ['previousContent', 'newContent']) {
const content = row[side];
if (!content || typeof content !== 'object' || !Array.isArray(content.datePaths)) continue;
if (!content.datePaths.some(Array.isArray)) continue;
if (copy === row) copy = { ...row };
copy[side] = { ...content, datePaths: content.datePaths.map(p => (Array.isArray(p) ? JSON.stringify(p) : p)) };
}
return copy;
}
/* Turn stored content back into the value to write. The inverse of the above. */
function valueFromContent(content) {
if (!content || typeof content !== 'object') return undefined;
if (!('value' in content)) return undefined;
if (content.isDate) {
return content.value === null ? null : new Date(content.value);
}
if (content.datePaths !== undefined) {
if (!Array.isArray(content.datePaths)) throw new Error('Invalid History date paths');
const value = JSON.parse(JSON.stringify(content.value));
const seen = new Set();
for (const stored of content.datePaths) {
// A row written before #6832 on MongoDB holds the path as an array.
const path = typeof stored === 'string' ? parseDatePath(stored) : stored;
if (!Array.isArray(path) || !path.length || path.some(key => typeof key !== 'string')) {
throw new Error('Invalid History date path');
}
const identity = JSON.stringify(path);
if (seen.has(identity)) throw new Error('Duplicate History date path');
seen.add(identity);
let parent = value;
for (const key of path.slice(0, -1)) {
if (!parent || typeof parent !== 'object' || !Object.hasOwn(parent, key)) throw new Error('Missing History date path');
parent = parent[key];
}
const key = path.at(-1);
if (!parent || typeof parent !== 'object' || !Object.hasOwn(parent, key) ||
typeof parent[key] !== 'number' || !Number.isFinite(new Date(parent[key]).getTime())) {
throw new Error('Invalid History date value');
}
Object.defineProperty(parent, key, { value: new Date(parent[key]), enumerable: true, writable: true, configurable: true });
}
return value;
}
return content.value;
}
/*
* Did this field actually change? Collection hooks fire for a write whether or
* not the value differs, and a history of "set the title to the title it
* already had" is noise that pushes the real changes off the first page.
*/
function changed(before, after) {
if (before === after) return false;
if (before instanceof Date || after instanceof Date) {
const a = before instanceof Date ? before.getTime() : before;
const b = after instanceof Date ? after.getTime() : after;
return a !== b;
}
if (before === null || before === undefined) {
return !(after === null || after === undefined);
}
if (after === null || after === undefined) return true;
if (typeof before === 'object' || typeof after === 'object') {
try {
return JSON.stringify(nestedContent('', before)) !== JSON.stringify(nestedContent('', after));
} catch {
return true;
}
}
return true;
}
/*
* The whole diff for one update: every recordable field that really changed.
* Returns [{ field, group, previousContent, newContent, changeType }].
*
* changeType follows what the value did rather than what the caller called it:
* empty -> value is 'added', value -> empty is 'removed', otherwise 'edited'.
* That is what lets the History table say "removed" for clearing a due date
* without every caller having to decide.
*/
function isEmpty(value) {
if (value === null || value === undefined || value === '') return true;
if (Array.isArray(value)) return value.length === 0;
return false;
}
function diffFields(entityType, previous, next, fieldNames) {
const changes = [];
const fields = Array.isArray(fieldNames)
? fieldNames
: Object.keys(next || {});
for (const field of fields) {
const group = groupForField(entityType, field);
if (!group) continue;
const before = field === 'cardDependencies' ? (previous?.[field] || [])
: previous ? previous[field] : undefined;
const after = field === 'cardDependencies' ? (next?.[field] || [])
: next ? next[field] : undefined;
if (!changed(before, after)) continue;
const previousContent = contentForField(field, before);
const newContent = contentForField(field, after);
if (previousContent === null && newContent === null) continue;
let changeType = 'edited';
if (isEmpty(before) && !isEmpty(after)) changeType = 'added';
else if (!isEmpty(before) && isEmpty(after)) changeType = 'removed';
changes.push({ field, group, changeType, previousContent, newContent });
}
return changes;
}
/*
* Which of a row's two contents a given operation applies.
*
* 'undo' previousContent - the state before this change.
* 'redo' newContent.
* 'restore' newContent, because that is the value the History table SHOWS for
* the row (History.md §7: the content column holds "the new text").
* The row a reader picks and the value they get must be the same
* thing. Restore used to run 'undo', so picking the row that showed
* the description you wanted gave you the one before it.
*
* A row with no newContent is a removal; restoring one means putting back what
* it removed, hence the fallback.
*/
function contentForDirection(row, direction) {
if (!row) return undefined;
if (direction === 'undo') return row.previousContent;
if (direction === 'restore') {
return (row.newContent === null || row.newContent === undefined)
? row.previousContent
: row.newContent;
}
return row.newContent;
}
module.exports = {
groupForField,
contentForField,
contentForDirection,
valueFromContent,
withStringDatePaths,
changed,
diffFields,
FIELDS_BY_ENTITY,
NEVER_RECORD,
};