A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
fix: improve sync & SSE reliability
thecodrr67674cbc336c
diff --git a/packages/core/api/index.js b/packages/core/api/index.jsindex 628e5182e..3ed4f8c8f 100644--- a/packages/core/api/index.js+++ b/packages/core/api/index.js@@ -22,6 +22,7 @@ import Monographs from "./monographs";import Offers from "./offers";import Attachments from "../collections/attachments";import Debug from "./debug";+import { Mutex } from "async-mutex";/*** @type {EventSource}@@ -34,10 +35,13 @@ class Database {* @param {EventSource} eventsource*/constructor(storage, eventsource, fs) {+ /**+ * @type {EventSource}+ */+ this.evtSource = null;this.storage = new Storage(storage);this.fs = new FileStorage(fs, storage);NNEventSource = eventsource;- this._syncTimeout = 0;}async _validate() {@@ -60,13 +64,9 @@ class Database {});EV.subscribe(EVENTS.userLoggedOut, async () => {await this.monographs.deinit();- clearTimeout(this._syncTimeout);- if (this.evtSource) {- this.evtSource.close();- this.evtSource = null;- }+ this.syncer.stopAutoSync();+ disconnectSSE();});- EV.subscribe(EVENTS.databaseUpdated, this._onDBWrite.bind(this));this.session = new Session(this.storage);await this._validate();@@ -111,85 +111,79 @@ class Database {this.monographs.init();}- async connectSSE(args) {- if (args && !!args.error) return;-- this.monographs.init();+ disconnectSSE() {+ if (!this.evtSource) return;+ this.evtSource.onopen = null;+ this.evtSource.onmessage = null;+ this.evtSource.onerror = null;+ this.evtSource.close();+ this.evtSource = null;+ }- if (!NNEventSource) return;- if (this.evtSource) {- this.evtSource.close();- this.evtSource = null;- }+ async connectSSE(args) {+ await this.sseMutex.runExclusive(() => {+ if (args && !!args.error) return;++ if (!NNEventSource) return;+ this.disconnectSSE();++ let token = await this.user.tokenManager.getAccessToken();+ this.evtSource = new NNEventSource(`${Constants.SSE_HOST}/sse`, {+ headers: { Authorization: `Bearer ${token}` },+ });++ this.evtSource.onopen = async () => {+ console.log("SSE: opened channel successfully!");+ };++ this.evtSource.onerror = function (error) {+ console.log("SSE: error:", error);+ };++ this.evtSource.onmessage = async (event) => {+ try {+ var { type, data } = JSON.parse(event.data);+ data = JSON.parse(data);+ // console.log(type, data);+ } catch (e) {+ console.log("SSE: Unsupported message. Message = ", event.data);+ return;+ }++ switch (type) {+ case "upgrade":+ const user = await this.user.getUser();+ user.subscription = data;+ await this.user.setUser(user);+ EV.publish(EVENTS.userSubscriptionUpdated, data);+ break;+ case "userDeleted":+ await this.user.logout(false, "Account Deleted");+ break;+ case "userPasswordChanged":+ await this.user.logout(true, "Password Changed");+ break;+ case "emailConfirmed":+ const token = await this.storage.read("token");+ await this.user.tokenManager._refreshToken(token);+ await this.user.fetchUser(true);+ EV.publish(EVENTS.userEmailConfirmed);+ break;+ case "sync":+ if (!(await checkIsUserPremium(CHECK_IDS.databaseSync))) break;- let token = await this.user.tokenManager.getAccessToken();- this.evtSource = new NNEventSource(`${Constants.SSE_HOST}/sse`, {- headers: { Authorization: `Bearer ${token}` },+ await this.syncer.remoteSync(data);+ break;+ }+ };});-- this.evtSource.onopen = async () => {- console.log("SSE: opened channel successfully!");- };-- this.evtSource.onerror = function (error) {- console.log("SSE: error:", error);- };-- this.evtSource.onmessage = async (event) => {- try {- var { type, data } = JSON.parse(event.data);- data = JSON.parse(data);- // console.log(type, data);- } catch (e) {- console.log("SSE: Unsupported message. Message = ", event.data);- return;- }-- switch (type) {- case "upgrade":- const user = await this.user.getUser();- user.subscription = data;- await this.user.setUser(user);- EV.publish(EVENTS.userSubscriptionUpdated, data);- break;- case "userDeleted":- await this.user.logout(false, "Account Deleted");- break;- case "userPasswordChanged":- await this.user.logout(true, "Password Changed");- break;- case "emailConfirmed":- const token = await this.storage.read("token");- await this.user.tokenManager._refreshToken(token);- await this.user.fetchUser(true);- EV.publish(EVENTS.userEmailConfirmed);- break;- case "sync":- if (!(await checkIsUserPremium(CHECK_IDS.databaseSync))) break;- break;- }- };}async lastSynced() {return this.storage.read("lastSynced");}- async _onDBWrite(item) {- if (- item.remote ||- !(await sendCheckUserStatusEvent(CHECK_IDS.databaseSync))- ) {- return;- }- clearTimeout(this._syncTimeout);- this._syncTimeout = setTimeout(() => {- EV.publish(EVENTS.databaseSyncRequested);- }, 5 * 1000);- }-sync(full = true, force = false) {- clearTimeout(this._syncTimeout);return this.syncer.start(full, force);}diff --git a/packages/core/api/sync/index.js b/packages/core/api/sync/index.jsindex f3b2311a1..f826c46cc 100644--- a/packages/core/api/sync/index.js+++ b/packages/core/api/sync/index.js@@ -25,13 +25,21 @@* Syncing should pause until all the conflicts have been resolved* And then it should continue.*/-import { EV, EVENTS, sendAttachmentsProgressEvent } from "../../common";+import {+ checkIsUserPremium,+ CHECK_IDS,+ EV,+ EVENTS,+ sendAttachmentsProgressEvent,+} from "../../common";import Constants from "../../utils/constants";import http from "../../utils/http";import TokenManager from "../token-manager";import Collector from "./collector";import Merger from "./merger";import { areAllEmpty } from "./utils";+import { Mutex, withTimeout } from "async-mutex";+export default class Sync {/***@@ -42,109 +50,107 @@ export default class Sync {this._collector = new Collector(this._db);this._merger = new Merger(this._db);this._tokenManager = new TokenManager(this._db.storage);- this._isSyncing = false;- }+ this._autoSyncTimeout = 0;+ this._autoSyncInterval = 0;- async _fetch(lastSynced, token) {- return await http.get(- `${Constants.API_HOST}/sync?lst=${lastSynced}`,- token+ this.syncMutex = withTimeout(+ new Mutex(),+ 20 * 1000,+ new Error("Sync timed out."));}- async _fetchAttachments(lastSynced, token) {- return await http.get(- `${Constants.API_HOST}/sync/attachments?lst=${lastSynced}`,- token- );- }-- async _performChecks() {- let lastSynced = (await this._db.storage.read("lastSynced")) || 0;- let token = await this._tokenManager.getAccessToken();-- // update the conflicts status and if find any, throw- await this._db.conflicts.recalculate();- await this._db.conflicts.check();-- return { lastSynced, token };- }-async start(full, force) {- if (this._isSyncing) return false;+ if (this.syncMutex.isLocked()) return false;++ return this.syncMutex+ .runExclusive(() => {+ this.stopAutoSync();+ return this._sync(full, force);+ })+ .finally(() => this._afterSync());+ }- if (force) await this._db.storage.write("lastSynced", 0);+ async _sync(full, force) {let { lastSynced, token } = await this._performChecks();-- try {- const now = Date.now();- this._isSyncing = true;-- await this._mergeAttachments(token, lastSynced);- await this._uploadAttachments();-- // we prepare local data before merging so we always have correct data- const data = await this._collector.collect(lastSynced);- data.lastSynced = now;-- if (full) {- var serverResponse = await this._fetch(lastSynced, token);- // merge the server response- await this._merger.merge(serverResponse, lastSynced);- }-- // check for conflicts and throw+ if (force) lastSynced = 0;++ // We request and merge remote attachments beforehand to handle+ // all possible conflicts that will occur if a user attaches+ // the same file/image on both his devices. Since both files+ // will have the same hash but different encryption key, it+ // will cause problems on the local device.+ await this._mergeAttachments(token, lastSynced);++ // All pending attachments are uploaded before anything else.+ // This is done to ensure that when any note arrives on user's+ // device, its attachments can be downloaded.+ await this._uploadAttachments();++ // We collect, encrypt, and ready local changes before asking+ // the server for remote changes. This is done to ensure we+ // don't accidentally send the remote changes back to the server.+ const data = await this._collector.collect(lastSynced);+ if (full) {+ // We request remote changes and merge them. If any new changes+ // come before or during this step (e.g. SSE), it can be safely+ // ignored because the `lastSynced` time can never be newer+ // than the change time.+ var serverResponse = await this._fetch(lastSynced, token);+ await this._merger.merge(serverResponse, lastSynced);await this._db.conflicts.check();+ // ignore the changes that have arrived uptil this point.+ this.hasNewChanges = false;+ }- // send the data back to server- lastSynced = await this._send(data, token);+ // We update the local last synced time before pushing local data+ // to the server. This is necessary to ensure that if the user+ // makes any local changes during the HTTP request, it is not ignored.+ // This is also the last synced time that is set for later sync cycles.+ data.lastSynced = Date.now();+ if (areAllEmpty(data)) await this._send(data, token);- // update our lastSynced time- if (lastSynced) {- await this._db.storage.write("lastSynced", lastSynced);- }+ await this._db.storage.write("lastSynced", data.lastSynced);+ return true;+ }- return true;- } catch (e) {- this._isSyncing = false;- throw e;- } finally {- this._isSyncing = false;+ async remoteSync() {+ if (this.syncMutex.isLocked()) {+ this.hasNewChanges = true;+ return;}+ await this.syncMutex+ .runExclusive(async () => {+ this.stopAutoSync();+ await this._sync(true, false);+ EV.publish(EVENTS.appRefreshRequested);+ })+ .finally(() => this._afterSync());}- async eventMerge(serverResponse) {- let { lastSynced, token } = await this._performChecks();-- const data = await this._collector.collect(lastSynced);-- // merge the server response- await this._merger.merge(serverResponse, lastSynced);-- // check for conflicts and throw- await this._db.conflicts.check();-- // send the data back to server- lastSynced = await this._send(data, token);-- // update our lastSynced time- if (lastSynced) {- await this._db.storage.write("lastSynced", lastSynced);- }+ async startAutoSync() {+ if (!(await checkIsUserPremium(CHECK_IDS.databaseSync))) return;+ this.databaseUpdatedEvent = EV.subscribe(+ EVENTS.databaseUpdated,+ this._scheduleSync.bind(this)+ );+ }- EV.publish(EVENTS.appRefreshRequested);+ stopAutoSync() {+ clearTimeout(this._autoSyncTimeout);+ this.databaseUpdatedEvent.unsubscribe();+ }- // check for conflicts and throw- // await this._db.conflicts.check();+ async _afterSync() {+ if (!this.nextSyncTimestamp) this.startAutoSync();+ else return this.remoteSync();+ }- // TODO test this.- // we won't be updating lastSynced time here because- // it can cause the lastSynced time to move ahead of any- // last edited (but unsynced) time resulting in edited notes- // not getting synced.- // if (serverResponse.lastSynced) {- // await this._db.storage.write("lastSynced", serverResponse.lastSynced);- // }+ _scheduleSync() {+ this.stopAutoSync();+ this._autoSyncTimeout = setTimeout(() => {+ EV.publish(EVENTS.databaseSyncRequested);+ }, this._autoSyncTimeout);}async _send(data, token) {@@ -181,4 +187,29 @@ export default class Sync {sendAttachmentsProgressEvent("upload", null, attachments.length);}}++ async _performChecks() {+ let lastSynced = (await this._db.lastSynced()) || 0;+ let token = await this._tokenManager.getAccessToken();++ // update the conflicts status and if find any, throw+ await this._db.conflicts.recalculate();+ await this._db.conflicts.check();++ return { lastSynced, token };+ }++ async _fetch(lastSynced, token) {+ return await http.get(+ `${Constants.API_HOST}/sync?lst=${lastSynced}`,+ token+ );+ }++ async _fetchAttachments(lastSynced, token) {+ return await http.get(+ `${Constants.API_HOST}/sync/attachments?lst=${lastSynced}`,+ token+ );+ }}diff --git a/packages/core/package-lock.json b/packages/core/package-lock.jsonindex 50a860c7e..558f89d32 100644--- a/packages/core/package-lock.json+++ b/packages/core/package-lock.json@@ -9,6 +9,7 @@"version": "6.8.4","dependencies": {"@stablelib/blake2s": "^1.0.1",+ "async-mutex": "^0.3.2","dayjs": "^1.10.6","fast-sort": "^2.0.1","no-internet": "^1.5.2",@@ -1951,6 +1952,14 @@"integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==","dev": true},+ "node_modules/async-mutex": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.3.2.tgz",+ "integrity": "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA==",+ "dependencies": {+ "tslib": "^2.3.1"+ }+ },"node_modules/asynckit": {"version": "0.4.0","resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",@@ -7657,6 +7666,11 @@"node": ">=0.10.0"}},+ "node_modules/tslib": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz",+ "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw=="+ },"node_modules/tunnel-agent": {"version": "0.6.0","resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",@@ -9722,6 +9736,14 @@"integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==","dev": true},+ "async-mutex": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.3.2.tgz",+ "integrity": "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA==",+ "requires": {+ "tslib": "^2.3.1"+ }+ },"asynckit": {"version": "0.4.0","resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",@@ -14432,6 +14454,11 @@"integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=","dev": true},+ "tslib": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz",+ "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw=="+ },"tunnel-agent": {"version": "0.6.0","resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",diff --git a/packages/core/package.json b/packages/core/package.jsonindex 75e36d602..34fbd9a57 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -24,6 +24,7 @@},"dependencies": {"@stablelib/blake2s": "^1.0.1",+ "async-mutex": "^0.3.2","dayjs": "^1.10.6","fast-sort": "^2.0.1","no-internet": "^1.5.2",diff --git a/packages/core/yarn.lock b/packages/core/yarn.lockindex 2b89fe66c..5ee02cb4c 100644--- a/packages/core/yarn.lock+++ b/packages/core/yarn.lock@@ -1231,6 +1231,13 @@"resolved" "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz""version" "1.0.1"+"async-mutex@^0.3.2":+ "integrity" "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA=="+ "resolved" "https://registry.npmjs.org/async-mutex/-/async-mutex-0.3.2.tgz"+ "version" "0.3.2"+ dependencies:+ "tslib" "^2.3.1"+"asynckit@^0.4.0":"integrity" "sha1-x57Zf380y48robyXkLzDZkdLS3k=""resolved" "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz"@@ -4992,6 +4999,11 @@"resolved" "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz""version" "1.0.1"+"tslib@^2.3.1":+ "integrity" "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw=="+ "resolved" "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz"+ "version" "2.3.1"+"tunnel-agent@^0.6.0":"integrity" "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=""resolved" "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz"