Skip to content

Build your personal knowledge base with Trilium Notes

5.0 KB
Raw Blame
import eraseService from "./erase.js";
import { getLog } from "./log.js";
import { getSql } from "./sql/index.js";
import { hash } from "./utils/index.js";

type SectorHash = Record<string, string>;

export interface FailedCheck {
    entityName: string;
    /** Single character: the first character of the entity ID the sector groups by. */
    sector: string;
}

/**
 * Cached sector hashes together with the entity_changes fingerprint they were computed at.
 *
 * Every write to entity_changes moves the fingerprint: updates go through a REPLACE that assigns a
 * fresh autoincrement id (raising MAX(id)) and deletions lower COUNT(*), so `(count, maxId)`
 * changing is a reliable "something changed" signal regardless of which code path wrote. No current
 * code path flips a row's isSynced flag in place (that too goes through REPLACE), but since the
 * hash computation filters on isSynced, the fingerprint also tracks the synced-row count as cheap
 * insurance against such a writer ever appearing. The check runs at the end of every sync cycle of
 * every connected client (every ~60 s), and in the common idle case nothing has changed — the
 * cache turns a full scan-and-hash of entity_changes (plus the unused-blob sweep) into a single
 * index-only query. Cache hits are deliberately not logged (they would fire every cycle for every
 * client); a check without a "Content hash computation took" log line was served from cache.
 */
let cached: { hashes: Record<string, SectorHash>; count: number; maxId: number; syncedCount: number } | null = null;

function getEntityChangesFingerprint() {
    return getSql().getRow<{ count: number; maxId: number; syncedCount: number }>(
        "SELECT COUNT(*) AS count, COALESCE(MAX(id), 0) AS maxId, COALESCE(SUM(isSynced), 0) AS syncedCount FROM entity_changes");
}

function getEntityHashes() {
    const fingerprint = getEntityChangesFingerprint();

    if (cached
        && cached.count === fingerprint.count
        && cached.maxId === fingerprint.maxId
        && cached.syncedCount === fingerprint.syncedCount) {
        // Nothing changed since the last computation. The unused-blob sweep can be skipped too:
        // a blob can only become unused through a change that itself writes entity_changes.
        return cached.hashes;
    }

    // blob erasure is not synced, we should check before each sync if there's some blob to erase
    eraseService.eraseUnusedBlobs();

    const startTime = new Date();

    // we know this is slow and the total content hash calculation time is logged
    type HashRow = [string, string, string, boolean];
    const sql = getSql();
    const hashRows = sql.disableSlowQueryLogging(() =>
        sql.getRawRows<HashRow>(`
            SELECT entityName,
                    entityId,
                    hash,
                    isErased
            FROM entity_changes
            WHERE isSynced = 1
            AND entityName != 'note_reordering'`)
    );

    // sorting is faster in memory
    // sorting by entityId is enough, hashes will be segmented by entityName later on anyway
    hashRows.sort((a, b) => (a[1] < b[1] ? -1 : 1));

    const hashMap: Record<string, SectorHash> = {};

    for (const [entityName, entityId, hash, isErased] of hashRows) {
        const entityHashMap = (hashMap[entityName] = hashMap[entityName] || {});

        const sector = entityId[0];

        // if the entity is erased, its hash is not updated, so it has to be added extra
        entityHashMap[sector] = (entityHashMap[sector] || "") + hash + isErased;
    }

    for (const entityHashMap of Object.values(hashMap)) {
        for (const key in entityHashMap) {
            entityHashMap[key] = hash(entityHashMap[key]);
        }
    }

    const elapsedTimeMs = Date.now() - startTime.getTime();

    getLog().info(`Content hash computation took ${elapsedTimeMs}ms`);

    // fingerprint re-read AFTER the computation: eraseUnusedBlobs above may have deleted rows
    cached = { hashes: hashMap, ...getEntityChangesFingerprint() };

    return hashMap;
}

function checkContentHashes(otherHashes: Record<string, SectorHash>) {
    const entityHashes = getEntityHashes();
    const failedChecks: FailedCheck[] = [];

    for (const entityName in entityHashes) {
        const thisSectorHashes: SectorHash = entityHashes[entityName] || {};
        const otherSectorHashes: SectorHash = otherHashes[entityName] || {};

        const sectors = new Set(Object.keys(thisSectorHashes).concat(Object.keys(otherSectorHashes)));

        for (const sector of sectors) {
            if (thisSectorHashes[sector] !== otherSectorHashes[sector]) {
                getLog().info(`Content hash check for ${entityName} sector ${sector} FAILED. Local is ${thisSectorHashes[sector]}, remote is ${otherSectorHashes[sector]}`);

                failedChecks.push({ entityName, sector });
            }
        }
    }

    if (failedChecks.length === 0) {
        getLog().info("Content hash checks PASSED");
    }

    return failedChecks;
}

export default {
    getEntityHashes,
    checkContentHashes
};