trilium/src/services/consistency_checks.js

331 lines
10 KiB
JavaScript
Raw Normal View History

2017-12-15 11:16:26 +08:00
"use strict";
const sql = require('./sql');
const sqlInit = require('./sql_init');
2017-12-15 11:16:26 +08:00
const log = require('./log');
const messagingService = require('./messaging');
const syncMutexService = require('./sync_mutex');
2018-11-13 06:34:22 +08:00
const repository = require('./repository.js');
const cls = require('./cls');
2017-12-15 11:16:26 +08:00
async function runCheck(query, errorText, errorList) {
const result = await sql.getColumn(query);
2017-12-15 11:16:26 +08:00
if (result.length > 0) {
2017-12-24 02:16:18 +08:00
const resultText = result.map(val => "'" + val + "'").join(', ');
const err = errorText + ": " + resultText;
2017-12-15 11:16:26 +08:00
errorList.push(err);
log.error(err);
}
}
2018-01-02 08:41:22 +08:00
async function checkTreeCycles(errorList) {
const childToParents = {};
2018-03-25 09:39:15 +08:00
const rows = await sql.getRows("SELECT noteId, parentNoteId FROM branches WHERE isDeleted = 0");
2018-01-02 08:41:22 +08:00
for (const row of rows) {
2018-01-29 08:30:14 +08:00
const childNoteId = row.noteId;
const parentNoteId = row.parentNoteId;
2018-01-02 08:41:22 +08:00
2018-10-22 03:37:34 +08:00
childToParents[childNoteId] = childToParents[childNoteId] || [];
2018-01-02 08:41:22 +08:00
childToParents[childNoteId].push(parentNoteId);
}
function checkTreeCycle(noteId, path, errorList) {
if (noteId === 'root') {
return;
}
if (!childToParents[noteId] || childToParents[noteId].length === 0) {
errorList.push(`No parents found for noteId=${noteId}`);
return;
}
2018-01-02 08:41:22 +08:00
for (const parentNoteId of childToParents[noteId]) {
if (path.includes(parentNoteId)) {
errorList.push(`Tree cycle detected at parent-child relationship: ${parentNoteId} - ${noteId}, whole path: ${path}`);
}
else {
const newPath = path.slice();
newPath.push(noteId);
checkTreeCycle(parentNoteId, newPath, errorList);
}
}
}
const noteIds = Object.keys(childToParents);
for (const noteId of noteIds) {
checkTreeCycle(noteId, [], errorList);
}
2018-10-22 03:37:34 +08:00
if (childToParents['root'].length !== 1 || childToParents['root'][0] !== 'none') {
errorList.push('Incorrect root parent: ' + JSON.stringify(childToParents['root']));
}
2018-01-02 08:41:22 +08:00
}
async function runSyncRowChecks(table, key, errorList) {
await runCheck(`
SELECT
${key}
FROM
${table}
2018-01-29 08:30:14 +08:00
LEFT JOIN sync ON sync.entityName = '${table}' AND entityId = ${key}
WHERE
sync.id IS NULL AND ` + (table === 'options' ? 'isSynced = 1' : '1'),
`Missing sync records for ${key} in table ${table}`, errorList);
await runCheck(`
SELECT
2018-01-29 08:30:14 +08:00
entityId
FROM
sync
2018-01-29 08:30:14 +08:00
LEFT JOIN ${table} ON entityId = ${key}
WHERE
2018-01-29 08:30:14 +08:00
sync.entityName = '${table}'
AND ${key} IS NULL`,
`Missing ${table} records for existing sync rows`, errorList);
2017-12-15 11:16:26 +08:00
}
2018-11-13 06:34:22 +08:00
async function fixEmptyRelationTargets(errorList) {
const emptyRelations = await repository.getEntities("SELECT * FROM attributes WHERE isDeleted = 0 AND type = 'relation' AND value = ''");
for (const relation of emptyRelations) {
relation.isDeleted = true;
await relation.save();
errorList.push(`Relation ${relation.attributeId} of name "${relation.name} has empty target. Autofixed.`);
}
}
async function runAllChecks() {
2017-12-15 11:16:26 +08:00
const errorList = [];
await runCheck(`
SELECT
2018-01-29 08:30:14 +08:00
noteId
FROM
notes
2018-03-25 09:39:15 +08:00
LEFT JOIN branches USING(noteId)
WHERE
2018-01-29 08:30:14 +08:00
noteId != 'root'
2018-03-25 09:39:15 +08:00
AND branches.branchId IS NULL`,
"Missing branches records for following note IDs", errorList);
2017-12-15 11:16:26 +08:00
await runCheck(`
SELECT
2018-03-25 09:39:15 +08:00
branchId || ' > ' || branches.noteId
FROM
2018-03-25 09:39:15 +08:00
branches
2018-01-29 08:30:14 +08:00
LEFT JOIN notes USING(noteId)
WHERE
2018-01-29 08:30:14 +08:00
notes.noteId IS NULL`,
"Missing notes records for following branch ID > note ID", errorList);
2017-12-15 11:16:26 +08:00
await runCheck(`
SELECT
2018-03-25 09:39:15 +08:00
branchId
FROM
2018-03-25 09:39:15 +08:00
branches
2018-01-29 08:30:14 +08:00
JOIN notes USING(noteId)
WHERE
2018-01-29 08:30:14 +08:00
notes.isDeleted = 1
2018-03-25 09:39:15 +08:00
AND branches.isDeleted = 0`,
"Branch is not deleted even though main note is deleted for following branch IDs", errorList);
2017-12-15 11:16:26 +08:00
await runCheck(`
SELECT
2018-03-25 09:39:15 +08:00
child.branchId
FROM
2018-03-25 09:39:15 +08:00
branches AS child
WHERE
2018-01-29 08:30:14 +08:00
child.isDeleted = 0
AND child.parentNoteId != 'none'
2018-03-25 09:39:15 +08:00
AND (SELECT COUNT(*) FROM branches AS parent WHERE parent.noteId = child.parentNoteId
2018-01-29 08:30:14 +08:00
AND parent.isDeleted = 0) = 0`,
"All parent branches are deleted but child branch is not for these child branch IDs", errorList);
// we do extra JOIN to eliminate orphan notes without branches (which are reported separately)
await runCheck(`
SELECT
2018-01-29 08:30:14 +08:00
DISTINCT noteId
FROM
notes
2018-03-25 09:39:15 +08:00
JOIN branches USING(noteId)
WHERE
2018-03-25 09:39:15 +08:00
(SELECT COUNT(*) FROM branches WHERE notes.noteId = branches.noteId AND branches.isDeleted = 0) = 0
2018-01-29 08:30:14 +08:00
AND notes.isDeleted = 0
`, 'No undeleted branches for note IDs', errorList);
await runCheck(`
SELECT
2018-01-29 08:30:14 +08:00
child.parentNoteId || ' > ' || child.noteId
2018-03-25 09:39:15 +08:00
FROM branches
AS child
2018-03-25 09:39:15 +08:00
LEFT JOIN branches AS parent ON parent.noteId = child.parentNoteId
WHERE
2018-01-29 08:30:14 +08:00
parent.noteId IS NULL
AND child.parentNoteId != 'none'`,
2017-12-15 11:16:26 +08:00
"Not existing parent in the following parent > child relations", errorList);
await runCheck(`
SELECT
noteRevisionId || ' > ' || note_revisions.noteId
FROM
note_revisions LEFT JOIN notes USING(noteId)
WHERE
2018-01-29 08:30:14 +08:00
notes.noteId IS NULL`,
"Missing notes records for following note revision ID > note ID", errorList);
2017-12-15 11:16:26 +08:00
await runCheck(`
SELECT
2018-03-25 09:39:15 +08:00
branches.parentNoteId || ' > ' || branches.noteId
FROM
2018-03-25 09:39:15 +08:00
branches
WHERE
2018-03-25 09:39:15 +08:00
branches.isDeleted = 0
GROUP BY
2018-03-25 09:39:15 +08:00
branches.parentNoteId,
branches.noteId
HAVING
COUNT(*) > 1`,
"Duplicate undeleted parent note <-> note relationship - parent note ID > note ID", errorList);
2018-01-21 10:56:03 +08:00
await runCheck(`
SELECT
2018-01-29 08:30:14 +08:00
noteId
2018-01-21 10:56:03 +08:00
FROM
notes
WHERE
2018-11-08 17:11:00 +08:00
type != 'text'
AND type != 'code'
AND type != 'render'
AND type != 'file'
AND type != 'image'
AND type != 'search'
AND type != 'relation-map'`,
2018-01-21 10:56:03 +08:00
"Note has invalid type", errorList);
await runCheck(`
SELECT
parentNoteId
FROM
2018-03-25 09:39:15 +08:00
branches
JOIN notes ON notes.noteId = branches.parentNoteId
WHERE
type == 'search'`,
"Search note has children", errorList);
await fixEmptyRelationTargets(errorList);
await runCheck(`
SELECT
attributeId
FROM
attributes
WHERE
type != 'label'
AND type != 'label-definition'
AND type != 'relation'
AND type != 'relation-definition'`,
"Attribute has invalid type", errorList);
await runCheck(`
SELECT
attributeId
FROM
attributes
LEFT JOIN notes ON attributes.noteId = notes.noteId AND notes.isDeleted = 0
WHERE
attributes.isDeleted = 0
AND notes.noteId IS NULL`,
"Attribute reference to the owning note is broken", errorList);
await runCheck(`
SELECT
attributeId
FROM
attributes
LEFT JOIN notes AS targetNote ON attributes.value = targetNote.noteId AND targetNote.isDeleted = 0
WHERE
attributes.type = 'relation'
AND attributes.isDeleted = 0
AND targetNote.noteId IS NULL`,
"Relation reference to the target note is broken", errorList);
await runCheck(`
SELECT
linkId
FROM
links
WHERE
type != 'image'
AND type != 'hyper'
AND type != 'relation-map'`,
"Link type is invalid", errorList);
await runCheck(`
SELECT
linkId
FROM
links
LEFT JOIN notes AS sourceNote ON sourceNote.noteId = links.noteId AND sourceNote.isDeleted = 0
LEFT JOIN notes AS targetNote ON targetNote.noteId = links.noteId AND targetNote.isDeleted = 0
WHERE
links.isDeleted = 0
AND (sourceNote.noteId IS NULL
OR targetNote.noteId IS NULL)`,
"Link to source/target note link is broken", errorList);
2018-01-29 08:30:14 +08:00
await runSyncRowChecks("notes", "noteId", errorList);
await runSyncRowChecks("note_revisions", "noteRevisionId", errorList);
2018-03-25 09:39:15 +08:00
await runSyncRowChecks("branches", "branchId", errorList);
await runSyncRowChecks("recent_notes", "branchId", errorList);
await runSyncRowChecks("attributes", "attributeId", errorList);
2018-02-11 13:18:59 +08:00
await runSyncRowChecks("api_tokens", "apiTokenId", errorList);
await runSyncRowChecks("options", "name", errorList);
2018-01-02 08:41:22 +08:00
if (errorList.length === 0) {
// we run this only if basic checks passed since this assumes basic data consistency
await checkTreeCycles(errorList);
}
return errorList;
}
async function runChecks() {
let errorList;
let elapsedTimeMs;
await syncMutexService.doExclusively(async () => {
const startTime = new Date();
errorList = await runAllChecks();
elapsedTimeMs = new Date().getTime() - startTime.getTime();
});
if (errorList.length > 0) {
log.info(`Consistency checks failed (took ${elapsedTimeMs}ms) with these errors: ` + JSON.stringify(errorList));
2018-01-02 08:41:22 +08:00
messagingService.sendMessageToAllClients({type: 'consistency-checks-failed'});
}
else {
log.info(`All consistency checks passed (took ${elapsedTimeMs}ms)`);
}
2017-12-15 11:16:26 +08:00
}
sqlInit.dbReady.then(() => {
setInterval(cls.wrap(runChecks), 60 * 60 * 1000);
2017-12-15 11:16:26 +08:00
// kickoff backup immediately
setTimeout(cls.wrap(runChecks), 10000);
2017-12-15 11:16:26 +08:00
});
module.exports = {
runChecks
};