242 lines
7.9 KiB
JavaScript
Raw Normal View History

import utils from './utils.js';
2019-10-20 10:00:18 +02:00
import toastService from "./toast.js";
import server from "./server.js";
2020-02-05 22:46:20 +01:00
import options from "./options.js";
2021-08-20 21:42:06 +02:00
import frocaUpdater from "./froca_updater.js";
2022-12-01 13:07:23 +01:00
import appContext from "../components/app_context.js";
const messageHandlers = [];
let ws;
let lastAcceptedEntityChangeId = window.glob.maxEntityChangeIdAtLoad;
2021-03-21 22:43:41 +01:00
let lastAcceptedEntityChangeSyncId = window.glob.maxEntityChangeSyncIdAtLoad;
let lastProcessedEntityChangeId = window.glob.maxEntityChangeIdAtLoad;
let lastPingTs;
2021-03-21 22:43:41 +01:00
let frontendUpdateDataQueue = [];
function logError(message) {
console.error(utils.now(), message); // needs to be separate from .trace()
if (ws && ws.readyState === 1) {
ws.send(JSON.stringify({
type: 'log-error',
error: message,
stack: new Error().stack
}));
}
}
2017-12-17 13:46:18 -05:00
2021-09-17 22:34:23 +02:00
function logInfo(message) {
console.log(utils.now(), message);
if (ws && ws.readyState === 1) {
ws.send(JSON.stringify({
type: 'log-info',
info: message
}));
}
}
window.logError = logError;
2021-09-17 22:34:23 +02:00
window.logInfo = logInfo;
function subscribeToMessages(messageHandler) {
messageHandlers.push(messageHandler);
}
2021-03-21 22:43:41 +01:00
// used to serialize frontend update operations
let consumeQueuePromise = null;
// to make sure each change event is processed only once. Not clear if this is still necessary
const processedEntityChangeIds = new Set();
2020-12-14 14:17:51 +01:00
function logRows(entityChanges) {
const filteredRows = entityChanges.filter(row =>
!processedEntityChangeIds.has(row.id)
&& (row.entityName !== 'options' || row.entityId !== 'openTabs'));
if (filteredRows.length > 0) {
2021-03-21 22:43:41 +01:00
console.debug(utils.now(), "Frontend update data: ", filteredRows);
}
}
async function executeFrontendUpdate(entityChanges) {
lastPingTs = Date.now();
if (entityChanges.length > 0) {
logRows(entityChanges);
frontendUpdateDataQueue.push(...entityChanges);
// we set lastAcceptedEntityChangeId even before frontend update processing and send ping so that backend can start sending more updates
for (const entityChange of entityChanges) {
lastAcceptedEntityChangeId = Math.max(lastAcceptedEntityChangeId, entityChange.id);
if (entityChange.isSynced) {
lastAcceptedEntityChangeSyncId = Math.max(lastAcceptedEntityChangeSyncId, entityChange.id);
}
}
2021-03-21 22:43:41 +01:00
sendPing();
2021-03-21 22:43:41 +01:00
// first wait for all the preceding consumers to finish
while (consumeQueuePromise) {
await consumeQueuePromise;
}
2021-03-21 22:43:41 +01:00
try {
// it's my turn so start it up
consumeQueuePromise = consumeFrontendUpdateData();
2019-12-16 22:47:07 +01:00
await consumeQueuePromise;
} finally {
// finish and set to null to signal somebody else can pick it up
consumeQueuePromise = null;
}
}
}
async function handleMessage(event) {
const message = JSON.parse(event.data);
for (const messageHandler of messageHandlers) {
messageHandler(message);
}
2021-09-26 15:37:18 +02:00
if (message.type === 'ping') {
lastPingTs = Date.now();
}
else if (message.type === 'reload-frontend') {
2021-09-17 22:34:23 +02:00
utils.reloadFrontendApp("received request from backend to reload frontend");
}
else if (message.type === 'frontend-update') {
await executeFrontendUpdate(message.data.entityChanges);
}
else if (message.type === 'sync-hash-check-failed') {
2019-10-20 10:00:18 +02:00
toastService.showError("Sync check failed!", 60000);
}
else if (message.type === 'consistency-checks-failed') {
2019-10-20 10:00:18 +02:00
toastService.showError("Consistency checks failed! See logs for details.", 50 * 60000);
}
2022-09-17 23:06:17 +02:00
else if (message.type === 'api-log-messages') {
appContext.triggerEvent("apiLogMessages", {noteId: message.noteId, messages: message.messages});
}
}
let entityChangeIdReachedListeners = [];
function waitForEntityChangeId(desiredEntityChangeId) {
if (desiredEntityChangeId <= lastProcessedEntityChangeId) {
return Promise.resolve();
}
console.debug(`Waiting for ${desiredEntityChangeId}, last processed is ${lastProcessedEntityChangeId}, last accepted ${lastAcceptedEntityChangeId}`);
return new Promise((res, rej) => {
entityChangeIdReachedListeners.push({
desiredEntityChangeId: desiredEntityChangeId,
resolvePromise: res,
start: Date.now()
})
});
}
function waitForMaxKnownEntityChangeId() {
return waitForEntityChangeId(server.getMaxKnownEntityChangeId());
}
function checkEntityChangeIdListeners() {
entityChangeIdReachedListeners
.filter(l => l.desiredEntityChangeId <= lastProcessedEntityChangeId)
2019-10-28 19:45:36 +01:00
.forEach(l => l.resolvePromise());
entityChangeIdReachedListeners = entityChangeIdReachedListeners
.filter(l => l.desiredEntityChangeId > lastProcessedEntityChangeId);
2019-10-28 19:45:36 +01:00
entityChangeIdReachedListeners.filter(l => Date.now() > l.start - 60000)
.forEach(l => console.log(`Waiting for entityChangeId ${l.desiredEntityChangeId} while last processed is ${lastProcessedEntityChangeId} (last accepted ${lastAcceptedEntityChangeId}) for ${Math.floor((Date.now() - l.start) / 1000)}s`));
2019-10-28 19:45:36 +01:00
}
2021-03-21 22:43:41 +01:00
async function consumeFrontendUpdateData() {
if (frontendUpdateDataQueue.length > 0) {
const allEntityChanges = frontendUpdateDataQueue;
frontendUpdateDataQueue = [];
const nonProcessedEntityChanges = allEntityChanges.filter(ec => !processedEntityChangeIds.has(ec.id));
2019-12-16 22:47:07 +01:00
try {
2021-08-20 21:42:06 +02:00
await utils.timeLimit(frocaUpdater.processEntityChanges(nonProcessedEntityChanges), 30000);
2019-12-16 22:47:07 +01:00
}
catch (e) {
logError(`Encountered error ${e.message}: ${e.stack}, reloading frontend.`);
2020-09-18 23:22:28 +02:00
if (!glob.isDev && !options.is('debugModeEnabled')) {
// if there's an error in updating the frontend then the easy option to recover is to reload the frontend completely
2021-08-24 22:59:51 +02:00
utils.reloadFrontendApp();
}
2020-09-18 23:22:28 +02:00
else {
2020-12-14 14:17:51 +01:00
console.log("nonProcessedEntityChanges causing the timeout", nonProcessedEntityChanges);
2020-09-19 22:47:14 +02:00
2022-08-24 23:20:05 +02:00
toastService.showError(`Encountered error "${e.message}", check out the console.`);
2020-09-18 23:22:28 +02:00
}
2019-12-16 22:47:07 +01:00
}
2020-12-14 14:17:51 +01:00
for (const entityChange of nonProcessedEntityChanges) {
processedEntityChangeIds.add(entityChange.id);
lastProcessedEntityChangeId = Math.max(lastProcessedEntityChangeId, entityChange.id);
}
}
checkEntityChangeIdListeners();
}
function connectWebSocket() {
2019-11-25 21:44:46 +01:00
const loc = window.location;
const webSocketUri = (loc.protocol === "https:" ? "wss:" : "ws:")
+ "//" + loc.host + loc.pathname;
// use wss for secure messaging
2019-11-25 21:44:46 +01:00
const ws = new WebSocket(webSocketUri);
ws.onopen = () => console.debug(utils.now(), `Connected to server ${webSocketUri} with WebSocket`);
ws.onmessage = handleMessage;
2019-07-06 12:03:51 +02:00
// we're not handling ws.onclose here because reconnection is done in sendPing()
return ws;
}
async function sendPing() {
if (Date.now() - lastPingTs > 30000) {
console.log(utils.now(), "Lost websocket connection to the backend. If you keep having this issue repeatedly, you might want to check your reverse proxy (nginx, apache) configuration and allow/unblock WebSocket.");
}
if (ws.readyState === ws.OPEN) {
ws.send(JSON.stringify({
type: 'ping',
lastEntityChangeId: lastAcceptedEntityChangeId
}));
}
else if (ws.readyState === ws.CLOSED || ws.readyState === ws.CLOSING) {
console.log(utils.now(), "WS closed or closing, trying to reconnect");
ws = connectWebSocket();
}
}
setTimeout(() => {
ws = connectWebSocket();
2019-02-10 16:36:25 +01:00
lastPingTs = Date.now();
setInterval(sendPing, 1000);
2018-04-05 23:17:19 -04:00
}, 0);
2017-12-01 22:28:22 -05:00
export default {
logError,
subscribeToMessages,
2021-03-21 22:43:41 +01:00
waitForMaxKnownEntityChangeId,
getMaxKnownEntityChangeSyncId: () => lastAcceptedEntityChangeSyncId
};