Notes/src/routes/api/sync.js

212 lines
6.1 KiB
JavaScript
Raw Normal View History

2017-10-24 22:58:59 -04:00
"use strict";
const syncService = require('../../services/sync');
const syncUpdateService = require('../../services/sync_update');
2021-06-29 22:15:57 +02:00
const entityChangesService = require('../../services/entity_changes');
2017-10-31 19:34:58 -04:00
const sql = require('../../services/sql');
const sqlInit = require('../../services/sql_init');
const optionService = require('../../services/options');
const contentHashService = require('../../services/content_hash');
2017-12-23 13:16:18 -05:00
const log = require('../../services/log');
const syncOptions = require('../../services/sync_options');
const utils = require('../../services/utils');
const ws = require('../../services/ws');
2017-11-21 22:11:27 -05:00
async function testSync() {
2018-07-23 10:29:17 +02:00
try {
2020-06-20 12:31:38 +02:00
if (!syncOptions.isSyncSetup()) {
return { success: false, message: "Sync server host is not configured. Please configure sync first." };
}
await syncService.login();
2018-07-23 10:29:17 +02:00
// login was successful, so we'll kick off sync now
// this is important in case when sync server has been just initialized
syncService.sync();
return { success: true, message: "Sync server handshake has been successful, sync has been started." };
2018-07-23 10:29:17 +02:00
}
catch (e) {
return {
success: false,
message: e.message
2018-07-23 10:29:17 +02:00
};
}
}
2020-06-20 12:31:38 +02:00
function getStats() {
if (!sqlInit.schemaExists()) {
2018-07-25 09:46:57 +02:00
// fail silently but prevent errors from not existing options table
return {};
}
2020-08-27 22:03:56 +02:00
const stats = {
2021-05-02 22:47:57 +02:00
initialized: sql.getValue("SELECT value FROM options WHERE name = 'initialized'") === 'true',
outstandingPullCount: syncService.getOutstandingPullCount()
};
2020-08-27 22:03:56 +02:00
log.info(`Returning sync stats: ${JSON.stringify(stats)}`);
return stats;
}
2020-06-20 12:31:38 +02:00
function checkSync() {
2018-03-30 14:27:41 -04:00
return {
2020-06-20 12:31:38 +02:00
entityHashes: contentHashService.getEntityHashes(),
maxEntityChangeId: sql.getValue('SELECT COALESCE(MAX(id), 0) FROM entity_changes WHERE isSynced = 1')
2018-03-30 14:27:41 -04:00
};
}
2017-10-24 22:58:59 -04:00
2020-06-20 12:31:38 +02:00
function syncNow() {
log.info("Received request to trigger sync now.");
// when explicitly asked for set in progress status immediately for faster user feedback
ws.syncPullInProgress();
2020-06-20 12:31:38 +02:00
return syncService.sync();
2018-03-30 14:27:41 -04:00
}
2017-10-29 11:22:41 -04:00
function fillEntityChanges() {
entityChangesService.fillAllEntityChanges();
2017-12-23 13:16:18 -05:00
log.info("Sync rows have been filled.");
2018-03-30 14:27:41 -04:00
}
2017-12-23 13:16:18 -05:00
2020-06-20 12:31:38 +02:00
function forceFullSync() {
optionService.setOption('lastSyncedPull', 0);
optionService.setOption('lastSyncedPush', 0);
2017-12-23 13:16:18 -05:00
log.info("Forcing full sync.");
// not awaiting for the job to finish (will probably take a long time)
syncService.sync();
2018-03-30 14:27:41 -04:00
}
2020-06-20 12:31:38 +02:00
function getChanged(req) {
const startTime = Date.now();
let lastEntityChangeId = parseInt(req.query.lastEntityChangeId);
2023-07-29 21:59:20 +02:00
const clientInstanceId = req.query.instanceId;
let filteredEntityChanges = [];
2023-07-29 21:59:20 +02:00
do {
const entityChanges = sql.getRows(`
SELECT *
FROM entity_changes
WHERE isSynced = 1
AND id > ?
ORDER BY id
LIMIT 1000`, [lastEntityChangeId]);
if (entityChanges.length === 0) {
break;
}
2023-07-29 21:59:20 +02:00
filteredEntityChanges = entityChanges.filter(ec => ec.instanceId !== clientInstanceId);
2022-01-09 21:25:15 +01:00
if (filteredEntityChanges.length === 0) {
lastEntityChangeId = entityChanges[entityChanges.length - 1].id;
}
2023-07-29 21:59:20 +02:00
} while (filteredEntityChanges.length === 0);
2017-10-24 22:58:59 -04:00
2022-01-09 21:25:15 +01:00
const entityChangeRecords = syncService.getEntityChangeRecords(filteredEntityChanges);
2022-01-09 21:25:15 +01:00
if (entityChangeRecords.length > 0) {
lastEntityChangeId = entityChangeRecords[entityChangeRecords.length - 1].entityChange.id;
2023-07-29 21:59:20 +02:00
log.info(`Returning ${entityChangeRecords.length} entity changes in ${Date.now() - startTime}ms`);
}
2023-07-29 21:59:20 +02:00
return {
2022-01-09 21:25:15 +01:00
entityChanges: entityChangeRecords,
lastEntityChangeId,
outstandingPullCount: sql.getValue(`
SELECT COUNT(id)
FROM entity_changes
WHERE isSynced = 1
AND instanceId != ?
2023-07-29 21:59:20 +02:00
AND id > ?`, [clientInstanceId, lastEntityChangeId])
};
}
2021-01-10 21:56:40 +01:00
const partialRequests = {};
2020-06-20 12:31:38 +02:00
function update(req) {
2021-01-10 21:56:40 +01:00
let {body} = req;
const pageCount = parseInt(req.get('pageCount'));
const pageIndex = parseInt(req.get('pageIndex'));
if (pageCount !== 1) {
const requestId = req.get('requestId');
if (pageIndex === 0) {
partialRequests[requestId] = {
createdAt: Date.now(),
payload: ''
};
}
if (!partialRequests[requestId]) {
2023-07-29 21:59:20 +02:00
throw new Error(`Partial request ${requestId}, page ${pageIndex + 1} of ${pageCount} of pages does not have expected record.`);
2021-01-10 21:56:40 +01:00
}
partialRequests[requestId].payload += req.body;
2023-07-29 21:59:20 +02:00
log.info(`Receiving a partial request ${requestId}, page ${pageIndex + 1} out of ${pageCount} pages.`);
2021-01-11 22:48:51 +01:00
2021-01-10 21:56:40 +01:00
if (pageIndex !== pageCount - 1) {
return;
}
else {
body = JSON.parse(partialRequests[requestId].payload);
delete partialRequests[requestId];
}
}
2022-01-09 21:25:15 +01:00
const {entities, instanceId} = body;
2023-09-21 18:13:14 +02:00
sql.transactional(() => syncUpdateService.updateEntities(entities, instanceId));
2018-03-30 14:27:41 -04:00
}
2017-10-26 21:16:21 -04:00
2021-01-10 21:56:40 +01:00
setInterval(() => {
for (const key in partialRequests) {
if (Date.now() - partialRequests[key].createdAt > 20 * 60 * 1000) {
2021-01-11 22:48:51 +01:00
log.info(`Cleaning up unfinished partial requests for ${key}`);
2021-01-10 21:56:40 +01:00
delete partialRequests[key];
}
}
}, 60 * 1000);
2020-06-20 12:31:38 +02:00
function syncFinished() {
2023-06-30 11:18:34 +02:00
// after the first sync finishes, the application is ready to be used
// this is meaningless but at the same time harmless (idempotent) for further syncs
2020-06-20 21:42:41 +02:00
sqlInit.setDbAsInitialized();
}
2020-06-20 12:31:38 +02:00
function queueSector(req) {
const entityName = utils.sanitizeSqlIdentifier(req.params.entityName);
const sector = utils.sanitizeSqlIdentifier(req.params.sector);
entityChangesService.addEntityChangesForSector(entityName, sector);
}
function checkEntityChanges() {
2023-07-29 21:59:20 +02:00
require("../../services/consistency_checks").runEntityChangesChecks();
}
2018-03-30 14:27:41 -04:00
module.exports = {
2018-07-23 10:29:17 +02:00
testSync,
2018-03-30 14:27:41 -04:00
checkSync,
syncNow,
fillEntityChanges,
2018-03-30 14:27:41 -04:00
forceFullSync,
getChanged,
update,
getStats,
syncFinished,
queueSector,
checkEntityChanges
};