Notes/src/services/sync.js

331 lines
9.1 KiB
JavaScript
Raw Normal View History

2017-10-21 21:10:33 -04:00
"use strict";
2017-10-25 22:39:21 -04:00
const log = require('./log');
const rp = require('request-promise');
const sql = require('./sql');
const sqlInit = require('./sql_init');
const optionService = require('./options');
2017-10-26 21:16:21 -04:00
const utils = require('./utils');
const sourceIdService = require('./source_id');
2018-04-02 20:46:46 -04:00
const dateUtils = require('./date_utils');
const syncUpdateService = require('./sync_update');
const contentHashService = require('./content_hash');
const appInfo = require('./app_info');
const syncSetup = require('./sync_setup');
const syncMutexService = require('./sync_mutex');
const cls = require('./cls');
2017-10-25 22:39:21 -04:00
let proxyToggle = true;
2017-10-25 22:39:21 -04:00
const stats = {
outstandingPushes: 0,
outstandingPulls: 0
};
2017-11-09 20:52:47 -05:00
async function sync() {
2017-10-29 14:55:48 -04:00
try {
return await syncMutexService.doExclusively(async () => {
if (!await syncSetup.isSyncSetup()) {
return { success: false, message: 'Sync not configured' };
}
const syncContext = await login();
2017-11-09 20:52:47 -05:00
await pushSync(syncContext);
2017-11-09 20:52:47 -05:00
await pullSync(syncContext);
2017-11-09 20:52:47 -05:00
await pushSync(syncContext);
2017-11-09 20:52:47 -05:00
await syncFinished(syncContext);
await checkContentHash(syncContext);
2017-11-21 22:11:27 -05:00
return {
success: true
};
});
2017-10-29 14:55:48 -04:00
}
catch (e) {
proxyToggle = !proxyToggle;
2017-11-09 20:52:47 -05:00
if (e.message.indexOf('ECONNREFUSED') !== -1) {
log.info("No connection to sync server.");
2017-11-09 20:52:47 -05:00
return {
success: false,
message: "No connection to sync server."
};
2017-10-31 19:34:58 -04:00
}
2017-11-09 20:52:47 -05:00
else {
log.info("sync failed: " + e.message);
2017-11-09 20:52:47 -05:00
return {
success: false,
message: e.message
}
2017-10-31 19:34:58 -04:00
}
2017-11-09 20:52:47 -05:00
}
}
async function login() {
2018-04-02 20:46:46 -04:00
const timestamp = dateUtils.nowDate();
2017-11-09 20:52:47 -05:00
2018-04-02 21:47:46 -04:00
const documentSecret = await optionService.getOption('documentSecret');
2017-11-09 20:52:47 -05:00
const hash = utils.hmac(documentSecret, timestamp);
const syncContext = { cookieJar: rp.jar() };
const resp = await syncRequest(syncContext, 'POST', '/api/login/sync', {
2017-11-09 20:52:47 -05:00
timestamp: timestamp,
syncVersion: appInfo.syncVersion,
2017-11-09 20:52:47 -05:00
hash: hash
});
if (sourceIdService.isLocalSourceId(resp.sourceId)) {
throw new Error(`Sync server has source ID ${resp.sourceId} which is also local. Try restarting sync server.`);
}
2017-11-09 20:52:47 -05:00
syncContext.sourceId = resp.sourceId;
return syncContext;
}
async function pullSync(syncContext) {
while (true) {
const lastSyncedPull = await getLastSyncedPull();
const changesUri = '/api/sync/changed?lastSyncId=' + lastSyncedPull;
2017-11-09 20:52:47 -05:00
const resp = await syncRequest(syncContext, 'GET', changesUri);
stats.outstandingPulls = resp.maxSyncId - lastSyncedPull;
2017-11-09 20:52:47 -05:00
const rows = resp.syncs;
2017-11-09 20:52:47 -05:00
if (rows.length === 0) {
break;
2017-10-31 20:09:07 -04:00
}
log.info("Pulled " + rows.length + " changes from " + changesUri);
for (const {sync, entity} of rows) {
if (sourceIdService.isLocalSourceId(sync.sourceId)) {
// too noisy
//log.info(`Skipping pull #${sync.id} ${sync.entityName} ${sync.entityId} because ${sync.sourceId} is a local source id.`);
}
else {
await syncUpdateService.updateEntity(sync, entity, syncContext.sourceId);
}
stats.outstandingPulls = resp.maxSyncId - sync.id;
await setLastSyncedPull(sync.id);
}
}
2017-10-31 19:34:58 -04:00
2017-11-09 20:52:47 -05:00
log.info("Finished pull");
}
2017-10-25 22:39:21 -04:00
2017-11-09 20:52:47 -05:00
async function pushSync(syncContext) {
2017-11-21 22:11:27 -05:00
let lastSyncedPush = await getLastSyncedPush();
2017-10-25 22:39:21 -04:00
2017-11-09 20:52:47 -05:00
while (true) {
2018-04-07 22:25:28 -04:00
const syncs = await sql.getRows('SELECT * FROM sync WHERE id > ? LIMIT 1000', [lastSyncedPush]);
2017-11-09 20:52:47 -05:00
2018-04-07 22:25:28 -04:00
const filteredSyncs = syncs.filter(sync => {
if (sync.sourceId === syncContext.sourceId) {
// too noisy
//log.info(`Skipping push #${sync.id} ${sync.entityName} ${sync.entityId} because it originates from sync target`);
2017-11-09 20:52:47 -05:00
2018-04-07 22:25:28 -04:00
// this may set lastSyncedPush beyond what's actually sent (because of size limit)
// so this is applied to the database only if there's no actual update
// TODO: it would be better to simplify this somehow
lastSyncedPush = sync.id;
2017-11-09 20:52:47 -05:00
2018-04-07 22:25:28 -04:00
return false;
}
else {
return true;
}
});
2017-10-29 22:22:30 -04:00
2018-04-07 22:25:28 -04:00
if (filteredSyncs.length === 0) {
log.info("Nothing to push");
2018-02-18 22:55:36 -05:00
2018-04-07 22:25:28 -04:00
await setLastSyncedPush(lastSyncedPush);
2018-01-06 15:56:00 -05:00
2018-04-07 22:25:28 -04:00
break;
2018-01-06 15:56:00 -05:00
}
2018-04-07 22:25:28 -04:00
const syncRecords = await getSyncRecords(filteredSyncs);
2017-11-04 22:10:41 -04:00
2018-04-08 10:09:33 -04:00
log.info(`Pushing ${syncRecords.length} syncs.`);
2018-04-07 22:25:28 -04:00
await syncRequest(syncContext, 'PUT', '/api/sync/update', {
sourceId: sourceIdService.getCurrentSourceId(),
entities: syncRecords
});
2018-04-07 22:25:28 -04:00
lastSyncedPush = syncRecords[syncRecords.length - 1].sync.id;
2017-10-29 22:22:30 -04:00
2018-04-07 22:25:28 -04:00
await setLastSyncedPush(lastSyncedPush);
}
2017-11-09 20:52:47 -05:00
}
2017-10-28 22:17:00 -04:00
async function syncFinished(syncContext) {
await syncRequest(syncContext, 'POST', '/api/sync/finished');
}
2017-11-21 22:11:27 -05:00
async function checkContentHash(syncContext) {
const resp = await syncRequest(syncContext, 'GET', '/api/sync/check');
2017-11-21 22:11:27 -05:00
2018-04-07 22:25:28 -04:00
if (await getLastSyncedPull() < resp.maxSyncId) {
log.info("There are some outstanding pulls, skipping content check.");
2017-11-21 22:11:27 -05:00
return;
}
2018-04-08 10:09:33 -04:00
const notPushedSyncs = await sql.getValue("SELECT COUNT(*) FROM sync WHERE id > ?", [await getLastSyncedPush()]);
2017-11-21 22:11:27 -05:00
if (notPushedSyncs > 0) {
2018-04-08 10:09:33 -04:00
log.info(`There's ${notPushedSyncs} outstanding pushes, skipping content check.`);
2017-11-21 22:11:27 -05:00
return;
}
2018-04-07 22:59:47 -04:00
await contentHashService.checkContentHashes(resp.hashes);
2017-11-21 22:11:27 -05:00
}
2017-11-09 20:52:47 -05:00
async function syncRequest(syncContext, method, uri, body) {
const fullUri = await syncSetup.getSyncServer() + uri;
2017-10-28 22:17:00 -04:00
2017-10-29 14:55:48 -04:00
try {
2017-11-13 19:45:13 -05:00
const options = {
2017-11-09 20:52:47 -05:00
method: method,
uri: fullUri,
jar: syncContext.cookieJar,
2017-10-29 14:55:48 -04:00
json: true,
2017-11-09 20:52:47 -05:00
body: body,
timeout: await syncSetup.getSyncTimeout()
2017-11-13 19:45:13 -05:00
};
const syncProxy = await syncSetup.getSyncProxy();
if (syncProxy && proxyToggle) {
options.proxy = syncProxy;
2017-11-13 19:45:13 -05:00
}
return await rp(options);
2017-10-25 22:39:21 -04:00
}
catch (e) {
throw new Error(`Request to ${method} ${fullUri} failed, error: ${e.message}`);
2017-11-05 00:16:02 -04:00
}
}
2018-04-07 22:25:28 -04:00
const primaryKeys = {
"notes": "noteId",
"branches": "branchId",
"note_revisions": "noteRevisionId",
"recent_notes": "branchId",
"images": "imageId",
"note_images": "noteImageId",
"labels": "labelId",
2018-05-21 20:12:46 -04:00
"api_tokens": "apiTokenId",
2018-06-13 19:10:28 -04:00
"options": "name"
2018-04-07 22:25:28 -04:00
};
async function getEntityRow(entityName, entityId) {
if (entityName === 'note_reordering') {
2018-04-07 22:59:47 -04:00
return await sql.getMap("SELECT branchId, notePosition FROM branches WHERE parentNoteId = ? AND isDeleted = 0", [entityId]);
2018-04-07 22:25:28 -04:00
}
else {
const primaryKey = primaryKeys[entityName];
if (!primaryKey) {
throw new Error("Unknown entity " + entityName);
}
2018-04-07 22:59:47 -04:00
const entity = await sql.getRow(`SELECT * FROM ${entityName} WHERE ${primaryKey} = ?`, [entityId]);
2018-04-07 22:25:28 -04:00
2018-04-07 22:59:47 -04:00
if (entityName === 'notes' && entity.type === 'file') {
entity.content = entity.content.toString("binary");
2018-04-07 22:25:28 -04:00
}
else if (entityName === 'images') {
2018-04-07 22:59:47 -04:00
entity.data = entity.data.toString('base64');
2018-04-07 22:25:28 -04:00
}
2018-04-07 22:59:47 -04:00
return entity;
2018-04-07 22:25:28 -04:00
}
}
async function getSyncRecords(syncs) {
const records = [];
let length = 0;
for (const sync of syncs) {
const record = {
sync: sync,
entity: await getEntityRow(sync.entityName, sync.entityId)
};
records.push(record);
length += JSON.stringify(record).length;
if (length > 1000000) {
break;
}
}
return records;
}
2018-04-08 10:09:33 -04:00
async function getLastSyncedPull() {
return parseInt(await optionService.getOption('lastSyncedPull'));
}
async function setLastSyncedPull(syncId) {
await optionService.setOption('lastSyncedPull', syncId);
}
async function getLastSyncedPush() {
return parseInt(await optionService.getOption('lastSyncedPush'));
}
async function setLastSyncedPush(lastSyncedPush) {
await optionService.setOption('lastSyncedPush', lastSyncedPush);
}
async function updatePushStats() {
const lastSyncedPush = await optionService.getOption('lastSyncedPush');
stats.outstandingPushes = await sql.getValue("SELECT COUNT(*) FROM sync WHERE id > ?", [lastSyncedPush]);
}
sqlInit.dbReady.then(async () => {
if (await syncSetup.isSyncSetup()) {
log.info("Setting up sync to " + await syncSetup.getSyncServer() + " with timeout " + await syncSetup.getSyncTimeout());
const syncProxy = await syncSetup.getSyncProxy();
if (syncProxy) {
log.info("Sync proxy: " + syncProxy);
}
setInterval(cls.wrap(sync), 60000);
// kickoff initial sync immediately
setTimeout(cls.wrap(sync), 1000);
setInterval(cls.wrap(updatePushStats), 1000);
}
else {
log.info("Sync server not configured, sync timer not running.")
}
});
2017-10-26 21:16:21 -04:00
module.exports = {
2018-02-18 22:55:36 -05:00
sync,
2018-07-23 10:29:17 +02:00
login,
getSyncRecords,
stats
2017-10-26 21:16:21 -04:00
};