trilium/services/sync.js

334 lines
9.8 KiB
JavaScript
Raw Normal View History

2017-10-22 09:10:33 +08:00
"use strict";
2017-10-26 10:39:21 +08:00
const log = require('./log');
const rp = require('request-promise');
const sql = require('./sql');
2017-11-03 08:48:02 +08:00
const options = require('./options');
2017-10-27 09:16:21 +08:00
const utils = require('./utils');
const source_id = require('./source_id');
const notes = require('./notes');
2017-11-10 09:52:47 +08:00
const syncUpdate = require('./sync_update');
2017-11-22 11:11:27 +08:00
const content_hash = require('./content_hash');
const event_log = require('./event_log');
const fs = require('fs');
2017-12-04 11:29:23 +08:00
const app_info = require('./app_info');
const messaging = require('./messaging');
const sync_setup = require('./sync_setup');
2017-10-26 10:39:21 +08:00
let syncInProgress = false;
let proxyToggle = true;
let syncServerCertificate = null;
2017-10-26 10:39:21 +08:00
2017-11-10 09:52:47 +08:00
async function sync() {
if (syncInProgress) {
log.info("Sync already in progress");
2017-11-10 09:52:47 +08:00
return {
success: false,
message: "Sync already in progress"
};
}
syncInProgress = true;
2017-10-30 02:55:48 +08:00
try {
if (!await sql.isDbUpToDate()) {
2017-11-10 09:52:47 +08:00
return {
success: false,
message: "DB not up to date"
};
}
2017-11-01 07:34:58 +08:00
2017-11-10 09:52:47 +08:00
const syncContext = await login();
await pushSync(syncContext);
await pullSync(syncContext);
await pushSync(syncContext);
2017-11-22 11:11:27 +08:00
await checkContentHash(syncContext);
2017-11-10 09:52:47 +08:00
return {
success: true
};
2017-10-30 02:55:48 +08:00
}
catch (e) {
proxyToggle = !proxyToggle;
2017-11-10 09:52:47 +08:00
if (e.message.indexOf('ECONNREFUSED') !== -1) {
log.info("No connection to sync server.");
2017-11-10 09:52:47 +08:00
return {
success: false,
message: "No connection to sync server."
};
2017-11-01 07:34:58 +08:00
}
2017-11-10 09:52:47 +08:00
else {
log.info("sync failed: " + e.stack);
return {
success: false,
message: e.message
}
2017-11-01 07:34:58 +08:00
}
2017-11-10 09:52:47 +08:00
}
finally {
syncInProgress = false;
}
}
async function login() {
2017-12-11 04:45:17 +08:00
const timestamp = utils.nowDate();
2017-11-10 09:52:47 +08:00
const documentSecret = await options.getOption('document_secret');
const hash = utils.hmac(documentSecret, timestamp);
const syncContext = { cookieJar: rp.jar() };
const resp = await syncRequest(syncContext, 'POST', '/api/login/sync', {
2017-11-10 09:52:47 +08:00
timestamp: timestamp,
2017-12-04 11:29:23 +08:00
dbVersion: app_info.db_version,
2017-11-10 09:52:47 +08:00
hash: hash
});
syncContext.sourceId = resp.sourceId;
return syncContext;
}
2017-11-22 11:11:27 +08:00
async function getLastSyncedPull() {
return parseInt(await options.getOption('last_synced_pull'));
}
async function setLastSyncedPull(syncId) {
await sql.doInTransaction(async () => {
await options.setOption('last_synced_pull', syncId);
});
}
2017-11-10 09:52:47 +08:00
async function pullSync(syncContext) {
2017-11-22 11:11:27 +08:00
const lastSyncedPull = await getLastSyncedPull();
2017-11-10 09:52:47 +08:00
const changesUri = '/api/sync/changed?lastSyncId=' + lastSyncedPull;
2017-11-10 09:52:47 +08:00
const syncRows = await syncRequest(syncContext, 'GET', changesUri);
log.info("Pulled " + syncRows.length + " changes from " + changesUri);
for (const sync of syncRows) {
if (source_id.isLocalSourceId(sync.source_id)) {
2017-12-16 13:05:37 +08:00
log.info(`Skipping pull #${sync.id} ${sync.entity_name} ${sync.entity_id} because ${sync.source_id} is a local source id.`);
await setLastSyncedPull(sync.id);
continue;
}
const resp = await syncRequest(syncContext, 'GET', "/api/sync/" + sync.entity_name + "/" + encodeURIComponent(sync.entity_id));
2017-11-01 07:34:58 +08:00
2017-12-17 01:21:56 +08:00
if (!resp || (sync.entity_name === 'notes' && !resp.entity)) {
log.error(`Empty response to pull for sync #${sync.id} ${sync.entity_name}, id=${sync.entity_id}`);
2017-11-24 12:54:54 +08:00
}
2017-12-11 04:45:17 +08:00
else if (sync.entity_name === 'notes') {
await syncUpdate.updateNote(resp.entity, syncContext.sourceId);
2017-11-01 08:09:07 +08:00
}
else if (sync.entity_name === 'notes_tree') {
2017-11-10 09:52:47 +08:00
await syncUpdate.updateNoteTree(resp, syncContext.sourceId);
2017-11-01 08:09:07 +08:00
}
else if (sync.entity_name === 'notes_history') {
2017-11-10 09:52:47 +08:00
await syncUpdate.updateNoteHistory(resp, syncContext.sourceId);
2017-11-01 08:09:07 +08:00
}
2017-11-03 10:55:22 +08:00
else if (sync.entity_name === 'notes_reordering') {
2017-11-10 09:52:47 +08:00
await syncUpdate.updateNoteReordering(resp, syncContext.sourceId);
2017-11-03 10:55:22 +08:00
}
2017-11-03 08:48:02 +08:00
else if (sync.entity_name === 'options') {
2017-11-10 09:52:47 +08:00
await syncUpdate.updateOptions(resp, syncContext.sourceId);
2017-11-03 08:48:02 +08:00
}
2017-11-05 12:16:02 +08:00
else if (sync.entity_name === 'recent_notes') {
2017-11-10 09:52:47 +08:00
await syncUpdate.updateRecentNotes(resp, syncContext.sourceId);
2017-11-05 12:16:02 +08:00
}
2017-11-01 08:09:07 +08:00
else {
throw new Error(`Unrecognized entity type ${sync.entity_name} in sync #${sync.id}`);
2017-11-01 08:09:07 +08:00
}
await setLastSyncedPull(sync.id);
}
2017-11-01 07:34:58 +08:00
2017-11-10 09:52:47 +08:00
log.info("Finished pull");
}
2017-10-26 10:39:21 +08:00
2017-11-22 11:11:27 +08:00
async function getLastSyncedPush() {
return parseInt(await options.getOption('last_synced_push'));
}
async function setLastSyncedPush(lastSyncedPush) {
await sql.doInTransaction(async () => {
await options.setOption('last_synced_push', lastSyncedPush);
});
}
2017-11-10 09:52:47 +08:00
async function pushSync(syncContext) {
2017-11-22 11:11:27 +08:00
let lastSyncedPush = await getLastSyncedPush();
2017-10-26 10:39:21 +08:00
2017-11-10 09:52:47 +08:00
while (true) {
const sync = await sql.getSingleResultOrNull('SELECT * FROM sync WHERE id > ? LIMIT 1', [lastSyncedPush]);
if (sync === null) {
// nothing to sync
log.info("Nothing to push");
break;
2017-10-30 02:55:48 +08:00
}
2017-10-30 10:22:30 +08:00
2017-11-10 09:52:47 +08:00
if (sync.source_id === syncContext.sourceId) {
2017-12-16 10:49:46 +08:00
log.info(`Skipping push #${sync.id} ${sync.entity_name} ${sync.entity_id} because it originates from sync target`);
2017-11-10 09:52:47 +08:00
}
else {
await pushEntity(sync, syncContext);
2017-11-10 09:52:47 +08:00
}
lastSyncedPush = sync.id;
await setLastSyncedPush(lastSyncedPush);
2017-10-27 09:16:21 +08:00
}
2017-10-30 10:22:30 +08:00
}
async function pushEntity(sync, syncContext) {
let entity;
if (sync.entity_name === 'notes') {
entity = await sql.getSingleResult('SELECT * FROM notes WHERE note_id = ?', [sync.entity_id]);
}
else if (sync.entity_name === 'notes_tree') {
entity = await sql.getSingleResult('SELECT * FROM notes_tree WHERE note_tree_id = ?', [sync.entity_id]);
}
else if (sync.entity_name === 'notes_history') {
entity = await sql.getSingleResult('SELECT * FROM notes_history WHERE note_history_id = ?', [sync.entity_id]);
}
2017-11-03 10:55:22 +08:00
else if (sync.entity_name === 'notes_reordering') {
entity = {
note_pid: sync.entity_id,
ordering: await sql.getMap('SELECT note_tree_id, note_pos FROM notes_tree WHERE note_pid = ?', [sync.entity_id])
2017-11-03 10:55:22 +08:00
};
}
2017-11-03 08:48:02 +08:00
else if (sync.entity_name === 'options') {
entity = await sql.getSingleResult('SELECT * FROM options WHERE opt_name = ?', [sync.entity_id]);
}
2017-11-05 12:16:02 +08:00
else if (sync.entity_name === 'recent_notes') {
entity = await sql.getSingleResult('SELECT * FROM recent_notes WHERE note_tree_id = ?', [sync.entity_id]);
2017-11-05 12:16:02 +08:00
}
else {
2017-12-16 10:49:46 +08:00
throw new Error(`Unrecognized entity type ${sync.entity_name} in sync #${sync.id}`);
}
2017-11-05 10:10:41 +08:00
if (!entity) {
2017-12-16 10:49:46 +08:00
log.info(`Sync #${sync.id} entity for ${sync.entity_name} ${sync.entity_id} doesn't exist. Skipping.`);
2017-11-05 10:10:41 +08:00
return;
}
2017-12-16 10:49:46 +08:00
log.info(`Pushing changes in sync #${sync.id} ${sync.entity_name} ${sync.entity_id}`);
2017-11-10 09:52:47 +08:00
const payload = {
sourceId: await source_id.getCurrentSourceId(),
2017-11-10 09:52:47 +08:00
entity: entity
};
2017-10-30 10:22:30 +08:00
await syncRequest(syncContext, 'PUT', '/api/sync/' + sync.entity_name, payload);
2017-11-10 09:52:47 +08:00
}
2017-10-29 10:17:00 +08:00
2017-11-22 11:11:27 +08:00
async function checkContentHash(syncContext) {
const resp = await syncRequest(syncContext, 'GET', '/api/sync/check');
2017-11-22 11:11:27 +08:00
if (await getLastSyncedPull() < resp.max_sync_id) {
log.info("There are some outstanding pulls, skipping content check.");
2017-11-22 11:11:27 +08:00
return;
}
const lastSyncedPush = await getLastSyncedPush();
const notPushedSyncs = await sql.getSingleValue("SELECT COUNT(*) FROM sync WHERE id > ?", [lastSyncedPush]);
2017-11-22 11:11:27 +08:00
if (notPushedSyncs > 0) {
log.info("There's " + notPushedSyncs + " outstanding pushes, skipping content check.");
2017-11-22 11:11:27 +08:00
return;
}
const hashes = await content_hash.getHashes();
let allChecksPassed = true;
for (const key in hashes) {
if (hashes[key] !== resp.hashes[key]) {
allChecksPassed = false;
2017-11-22 11:11:27 +08:00
await event_log.addEvent(`Content hash check for ${key} FAILED. Local is ${hashes[key]}, remote is ${resp.hashes[key]}`);
if (key !== 'recent_notes') {
// let's not get alarmed about recent notes which get updated often and can cause failures in race conditions
await messaging.sendMessage({type: 'sync-hash-check-failed'});
}
}
2017-11-22 11:11:27 +08:00
}
if (allChecksPassed) {
log.info("Content hash checks PASSED");
2017-11-22 11:11:27 +08:00
}
}
2017-11-10 09:52:47 +08:00
async function syncRequest(syncContext, method, uri, body) {
const fullUri = sync_setup.SYNC_SERVER + uri;
2017-10-29 10:17:00 +08:00
2017-10-30 02:55:48 +08:00
try {
2017-11-14 08:45:13 +08:00
const options = {
2017-11-10 09:52:47 +08:00
method: method,
uri: fullUri,
jar: syncContext.cookieJar,
2017-10-30 02:55:48 +08:00
json: true,
2017-11-10 09:52:47 +08:00
body: body,
timeout: sync_setup.SYNC_TIMEOUT
2017-11-14 08:45:13 +08:00
};
if (syncServerCertificate) {
options.ca = syncServerCertificate;
}
if (sync_setup.SYNC_PROXY && proxyToggle) {
options.proxy = sync_setup.SYNC_PROXY;
2017-11-14 08:45:13 +08:00
}
return await rp(options);
2017-10-26 10:39:21 +08:00
}
catch (e) {
2017-12-16 10:49:46 +08:00
throw new Error(`Request to ${method} ${fullUri} failed, inner exception: ${e.stack}`);
2017-11-05 12:16:02 +08:00
}
}
sql.dbReady.then(() => {
if (sync_setup.isSyncSetup) {
log.info("Setting up sync to " + sync_setup.SYNC_SERVER + " with timeout " + sync_setup.SYNC_TIMEOUT);
2017-10-26 10:39:21 +08:00
if (sync_setup.SYNC_PROXY) {
log.info("Sync proxy: " + sync_setup.SYNC_PROXY);
}
if (sync_setup.SYNC_CERT_PATH) {
log.info('Sync certificate: ' + sync_setup.SYNC_CERT_PATH);
syncServerCertificate = fs.readFileSync(sync_setup.SYNC_CERT_PATH);
}
setInterval(sync, 60000);
// kickoff initial sync immediately
setTimeout(sync, 1000);
}
else {
log.info("Sync server not configured, sync timer not running.")
}
});
2017-10-27 09:16:21 +08:00
module.exports = {
sync
2017-10-27 09:16:21 +08:00
};