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
feat: disable interruptible syncing
thecodrr32d4cfa59455
diff --git a/packages/core/api/sync/__tests__/collector.test.js b/packages/core/api/sync/__tests__/collector.test.jsindex 78e634b65..7a84bbd37 100644--- a/packages/core/api/sync/__tests__/collector.test.js+++ b/packages/core/api/sync/__tests__/collector.test.js@@ -19,9 +19,10 @@ test("newly created note should get included in collector", () =>const noteId = await db.notes.add(TEST_NOTE);const data = await collector.collect(lastSyncedTime);+ const notes = data.items.filter((i) => i.type === "note");- expect(data.notes).toHaveLength(1);- expect(data.notes[0].id).toBe(noteId);+ expect(notes).toHaveLength(1);+ expect(notes[0].id).toBe(noteId);}));test("edited note after last synced time should get included in collector", () =>@@ -36,9 +37,10 @@ test("edited note after last synced time should get included in collector", () =await db.notes.add({ id: noteId, pinned: true });const data = await collector.collect(lastSyncedTime);+ const notes = data.items.filter((i) => i.type === "note");- expect(data.notes).toHaveLength(1);- expect(data.notes[0].id).toBe(noteId);+ expect(notes).toHaveLength(1);+ expect(notes[0].id).toBe(noteId);}));test("note edited before last synced time should not get included in collector", () =>@@ -53,8 +55,9 @@ test("note edited before last synced time should not get included in collector",const lastSyncedTime = Date.now();const data = await collector.collect(lastSyncedTime);+ const notes = data.items.filter((i) => i.type === "note");- expect(data.notes).toHaveLength(0);+ expect(notes).toHaveLength(0);}));test("localOnly note should get included as a deleted item in collector", () =>@@ -63,7 +66,7 @@ test("localOnly note should get included as a deleted item in collector", () =>await db.notes.add({ ...TEST_NOTE, localOnly: true });const data = await collector.collect(0);-- expect(data.notes).toHaveLength(1);- expect(data.notes[0].cipher).toContain(`"deleted":true`);+ const notes = data.items.filter((i) => i.type === "note");+ expect(notes).toHaveLength(1);+ expect(notes[0].deleted).toBe(true);}));diff --git a/packages/core/api/sync/__tests__/sync.test.js b/packages/core/api/sync/__tests__/sync.test.jsindex 33f36e6b9..1d4b50285 100644--- a/packages/core/api/sync/__tests__/sync.test.js+++ b/packages/core/api/sync/__tests__/sync.test.js@@ -56,130 +56,130 @@ test.skip(30 * 1000);-test.skip(- "case 4: Device A's sync is interrupted halfway and Device B makes some changes afterwards and syncs.",- async () => {- const deviceA = await initializeDevice("deviceA");- const deviceB = await initializeDevice("deviceB");-- const unsyncedNoteIds = [];- for (let i = 0; i < 10; ++i) {- const id = await deviceA.notes.add({- title: `Test note ${i} from device A`,- });- unsyncedNoteIds.push(id);- }-- const half = unsyncedNoteIds.length / 2 + 1;- deviceA.eventManager.subscribe(- EVENTS.syncProgress,- async ({ type, current }) => {- if (type === "upload" && current === half) {- await deviceA.syncer.stop();- }- }- );-- await expect(deviceA.sync(true)).rejects.toThrow();-- let syncedNoteIds = [];- for (let i = 0; i < unsyncedNoteIds.length; ++i) {- const expectedNoteId = unsyncedNoteIds[i];- if (deviceB.notes.note(expectedNoteId))- syncedNoteIds.push(expectedNoteId);- }- expect(- syncedNoteIds.length === half - 1 || syncedNoteIds.length === half- ).toBe(true);-- const deviceBNoteId = await deviceB.notes.add({- title: "Test note of case 4 from device B",- });-- await deviceB.sync(true);-- await syncAndWait(deviceA, deviceB);-- expect(deviceA.notes.note(deviceBNoteId)).toBeTruthy();- expect(- unsyncedNoteIds- .map((id) => !!deviceB.notes.note(id))- .every((res) => res === true)- ).toBe(true);-- await cleanup(deviceA, deviceB);- },- 60 * 1000-);--test.skip(- "case 5: Device A's sync is interrupted halfway and Device B makes changes on the same note's content that didn't get synced on Device A due to interruption.",- async () => {- const deviceA = await initializeDevice("deviceA");- const deviceB = await initializeDevice("deviceB");-- const noteIds = [];- for (let i = 0; i < 10; ++i) {- const id = await deviceA.notes.add({- content: {- type: "tiptap",- data: `<p>deviceA=true</p>`,- },- });- noteIds.push(id);- }-- await deviceA.sync(true);- await deviceB.sync(true);-- const unsyncedNoteIds = [];- for (let id of noteIds) {- const noteId = await deviceA.notes.add({- id,- content: {- type: "tiptap",- data: `<p>deviceA=true+changed=true</p>`,- },- });- unsyncedNoteIds.push(noteId);- }-- deviceA.eventManager.subscribe(- EVENTS.syncProgress,- async ({ type, total, current }) => {- const half = total / 2 + 1;- if (type === "upload" && current === half) {- await deviceA.syncer.stop();- }- }- );-- await expect(deviceA.sync(true)).rejects.toThrow();-- await delay(10 * 1000);-- for (let id of unsyncedNoteIds) {- await deviceB.notes.add({- id,- content: {- type: "tiptap",- data: "<p>changes from device B</p>",- },- });- }-- const error = await withError(async () => {- await deviceB.sync(true);- await deviceA.sync(true);- });-- expect(error).not.toBeInstanceOf(NoErrorThrownError);- expect(error.message.includes("Merge")).toBeTruthy();-- await cleanup(deviceA, deviceB);- },- 60 * 1000-);+// test.skip(+// "case 4: Device A's sync is interrupted halfway and Device B makes some changes afterwards and syncs.",+// async () => {+// const deviceA = await initializeDevice("deviceA");+// const deviceB = await initializeDevice("deviceB");++// const unsyncedNoteIds = [];+// for (let i = 0; i < 10; ++i) {+// const id = await deviceA.notes.add({+// title: `Test note ${i} from device A`,+// });+// unsyncedNoteIds.push(id);+// }++// const half = unsyncedNoteIds.length / 2 + 1;+// deviceA.eventManager.subscribe(+// EVENTS.syncProgress,+// async ({ type, current }) => {+// if (type === "upload" && current === half) {+// await deviceA.syncer.stop();+// }+// }+// );++// await expect(deviceA.sync(true)).rejects.toThrow();++// let syncedNoteIds = [];+// for (let i = 0; i < unsyncedNoteIds.length; ++i) {+// const expectedNoteId = unsyncedNoteIds[i];+// if (deviceB.notes.note(expectedNoteId))+// syncedNoteIds.push(expectedNoteId);+// }+// expect(+// syncedNoteIds.length === half - 1 || syncedNoteIds.length === half+// ).toBe(true);++// const deviceBNoteId = await deviceB.notes.add({+// title: "Test note of case 4 from device B",+// });++// await deviceB.sync(true);++// await syncAndWait(deviceA, deviceB);++// expect(deviceA.notes.note(deviceBNoteId)).toBeTruthy();+// expect(+// unsyncedNoteIds+// .map((id) => !!deviceB.notes.note(id))+// .every((res) => res === true)+// ).toBe(true);++// await cleanup(deviceA, deviceB);+// },+// 60 * 1000+// );++// test.only(+// "case 5: Device A's sync is interrupted halfway and Device B makes changes on the same note's content that didn't get synced on Device A due to interruption.",+// async () => {+// const deviceA = await initializeDevice("deviceA");+// const deviceB = await initializeDevice("deviceB");++// const noteIds = [];+// for (let i = 0; i < 10; ++i) {+// const id = await deviceA.notes.add({+// content: {+// type: "tiptap",+// data: `<p>deviceA=true</p>`,+// },+// });+// noteIds.push(id);+// }++// await deviceA.sync(true);+// await deviceB.sync(true);++// const unsyncedNoteIds = [];+// for (let id of noteIds) {+// const noteId = await deviceA.notes.add({+// id,+// content: {+// type: "tiptap",+// data: `<p>deviceA=true+changed=true</p>`,+// },+// });+// unsyncedNoteIds.push(noteId);+// }++// deviceA.eventManager.subscribe(+// EVENTS.syncProgress,+// async ({ type, total, current }) => {+// const half = total / 2 + 1;+// if (type === "upload" && current === half) {+// await deviceA.syncer.stop();+// }+// }+// );++// await expect(deviceA.sync(true)).rejects.toThrow();++// await delay(10 * 1000);++// for (let id of unsyncedNoteIds) {+// await deviceB.notes.add({+// id,+// content: {+// type: "tiptap",+// data: "<p>changes from device B</p>",+// },+// });+// }++// const error = await withError(async () => {+// await deviceB.sync(true);+// await deviceA.sync(true);+// });++// expect(error).not.toBeInstanceOf(NoErrorThrownError);+// expect(error.message.includes("Merge")).toBeTruthy();++// await cleanup(deviceA, deviceB);+// },+// 60 * 1000+// );test.skip("issue: running force sync from device A makes device B always download everything",@@ -228,8 +228,10 @@ test.skip(await syncAndWait(deviceA, deviceB);+ await delay(2000);+const purpleColor = deviceB.colors.tag("purple");- console.log(purpleColor.noteIds, noteIds);+ console.log(noteIds, purpleColor.noteIds);expect(noteIds.every((id) => purpleColor.noteIds.indexOf(id) > -1)).toBe(true);@@ -239,26 +241,6 @@ test.skip(60 * 1000);-test.skip(- "issue: running force sync from device A makes device B always download everything",- async () => {- const deviceA = await initializeDevice("deviceA");- const deviceB = await initializeDevice("deviceB");-- await syncAndWait(deviceA, deviceB, true);-- const handler = jest.fn();- deviceB.eventManager.subscribe(EVENTS.syncProgress, handler);-- await deviceB.sync(true);-- expect(handler).not.toHaveBeenCalled();-- await cleanup(deviceB);- },- 60 * 1000-);-test.skip("issue: new topic on device A gets replaced by the new topic on device B",async () => {@@ -397,13 +379,13 @@ async function cleanup(...devices) {* @param {Database} device* @returns*/-function waitForSyncCompleted(device) {- return new Promise((resolve) =>- device.eventManager.subscribe(EVENTS.syncCompleted, () => {- resolve();- })- );-}+// function waitForSyncCompleted(device) {+// return new Promise((resolve) =>+// device.eventManager.subscribe(EVENTS.syncCompleted, () => {+// resolve();+// })+// );+// }/***diff --git a/packages/core/api/sync/collector.js b/packages/core/api/sync/collector.jsindex 34507c027..838363069 100644--- a/packages/core/api/sync/collector.js+++ b/packages/core/api/sync/collector.js@@ -16,27 +16,20 @@ class Collector {this._lastSyncedTimestamp = lastSyncedTimestamp;this.key = await this._db.user.getEncryptionKey();- return {- // notes: this._collect(await this._db.notes.encrypted()),- // notebooks: this._collect(await this._db.notebooks.encrypted()),- // content: this._collect(await this._db.content.encrypted()),- notes: await this._encrypt(- this._collect(this._db.notes.raw, isForceSync)- ),- notebooks: await this._encrypt(- this._collect(this._db.notebooks.raw, isForceSync)- ),- content: await this._encrypt(- this._collect(await this._db.content.all(), isForceSync)- ),- attachments: await this._encrypt(- this._collect(this._db.attachments.syncable, isForceSync)- ),- settings: await this._encrypt(- this._collect([this._db.settings.raw], isForceSync)++ const items = [+ ...this._collect("note", this._db.notes.raw, isForceSync),+ ...this._collect("notebook", this._db.notebooks.raw, isForceSync),+ ...this._collect("content", await this._db.content.all(), isForceSync),+ ...this._collect(+ "attachment",+ this._db.attachments.syncable,+ isForceSync),- vaultKey: await this._serialize(await this._db.vault._getKey()),- };+ ...this._collect("settings", [this._db.settings.raw], isForceSync),+ ];++ return { items, vaultKey: await this._db.vault._getKey() };}_serialize(item) {@@ -44,7 +37,7 @@ class Collector {return this._db.storage.encrypt(this.key, JSON.stringify(item));}- _encrypt(array) {+ encrypt(array) {if (!array.length) return [];return Promise.all(array.map(this._map, this));}@@ -54,24 +47,32 @@ class Collector {* @param {Array} array* @returns {Array}*/- _collect(array, isForceSync) {+ _collect(type, array, isForceSync) {if (!array.length) return [];const result = array.reduce((prev, item) => {if (!item) return prev;+const isSyncable = !item.synced || isForceSync;const isUnsynced =item.dateModified > this._lastSyncedTimestamp || isForceSync;if (item.localOnly) {- prev.push({ id: item.id, deleted: true, dateModified: Date.now() });+ prev.push({+ id: item.id,+ type,+ deleted: true,+ dateModified: Date.now(),+ });} else if ((isUnsynced && isSyncable) || item.migrated) {- prev.push(item);+ prev.push({ ...item, type });}return prev;}, []);- this.logger.info(`Collected items ${result.length}/${array.length}`);+ this.logger.info(+ `Collected items: ${type} (${result.length}/${array.length})`+ );return result;}diff --git a/packages/core/api/sync/index.js b/packages/core/api/sync/index.jsindex 57791f392..e1c49b53f 100644--- a/packages/core/api/sync/index.js+++ b/packages/core/api/sync/index.js@@ -7,24 +7,14 @@ import {import Constants from "../../utils/constants";import TokenManager from "../token-manager";import Collector from "./collector";-import { areAllEmpty } from "./utils";import * as signalr from "@microsoft/signalr";import Merger from "./merger";import Conflicts from "./conflicts";-import { SyncQueue } from "./syncqueue";import { AutoSync } from "./auto-sync";import { toChunks } from "../../utils/array";import { MessagePackHubProtocol } from "@microsoft/signalr-protocol-msgpack";import { logger } from "../../logger";-const ITEM_TYPE_MAP = {- attachments: "attachment",- content: "content",- notes: "note",- notebooks: "notebook",- settings: "settings",-};-/*** @typedef {{* item: string,@@ -103,7 +93,6 @@ class Sync {this.db = db;this.conflicts = new Conflicts(db);this.collector = new Collector(db);- this.queue = new SyncQueue(db.storage);this.merger = new Merger(db);this.autoSync = new AutoSync(db, 1000);this.logger = logger.scope("Sync");@@ -180,7 +169,8 @@ class Sync {const { newLastSynced, data } = await this.collect(lastSynced, force);this.logger.info("Data collected for sync", {newLastSynced,- isEmpty: areAllEmpty(data),+ length: data.items.length,+ isEmpty: data.items.length <= 0,});const serverResponse = full ? await this.fetch(lastSynced) : null;@@ -259,75 +249,47 @@ class Sync {async collect(lastSynced, force) {const newLastSynced = Date.now();-- let data = await this.collector.collect(lastSynced, force);-- let { syncedAt } = await this.queue.get();- if (syncedAt) {- const newData = this.collector.filter(- data,- (item) => item.dateModified > syncedAt- );- await this.queue.merge(newData, newLastSynced);- } else {- await this.queue.new(data, newLastSynced);- }-+ const data = await this.collector.collect(lastSynced, force);return { newLastSynced, data };}/***- * @param {object} data+ * @param {{ items: any[]; vaultKey: any; }} data* @param {number} lastSynced* @returns {Promise<boolean>}*/async send(data, lastSynced) {await this.uploadAttachments();- if (areAllEmpty(data)) return false;-- const { itemIds } = await this.queue.get();- this.logger.info("Data to send", { itemIds });- if (!itemIds) return false;-- const arrays = itemIds.reduce(- (arrays, id) => {- const [arrayKey, itemId] = id.split(":");- const array = data[arrayKey] || [];-- const item = array.find((item) => item.id === itemId);- if (!item) return arrays;-- const type = ITEM_TYPE_MAP[arrayKey];-- arrays.types.push(type);- arrays.items.push(JSON.stringify(item));- arrays.ids.push(id);+ if (data.items.length <= 0) return false;+ const arrays = data.items.reduce(+ (arrays, item) => {+ arrays.types.push(item.type);+ arrays.items.push(item);return arrays;},- { items: [], types: [], ids: [] }+ { items: [], types: [] });if (data.vaultKey) {- arrays.ids.push("vaultKey");arrays.types.push("vaultKey");- arrays.items.push(JSON.stringify(data.vaultKey));+ arrays.items.push(data.vaultKey);}- let total = arrays.ids.length;+ let total = arrays.items.length;- arrays.ids = toChunks(arrays.ids, 30);arrays.types = toChunks(arrays.types, 30);arrays.items = toChunks(arrays.items, 30);let done = 0;- for (let i = 0; i < arrays.ids.length; ++i) {+ for (let i = 0; i < arrays.items.length; ++i) {this.logger.info(`Sending batch ${done}/${total}`);- const ids = arrays.ids[i];- const items = arrays.items[i];+ const items = (await this.collector.encrypt(arrays.items[i])).map(+ (item) => JSON.stringify(item)+ );const types = arrays.types[i];const result = await this.sendBatchToServer({@@ -339,8 +301,7 @@ class Sync {});if (result) {- done += ids.length;- await this.queue.dequeue(...ids);+ done += items.length;sendSyncProgressEvent(this.db.eventManager, "upload", total, done);this.logger.info(`Batch sent (${done}/${total})`);@@ -362,6 +323,7 @@ class Sync {}async cancel() {+ this.logger.info("Sync canceled");await this.connection.stop();}@@ -383,7 +345,7 @@ class Sync {await this.db.attachments.markAsUploaded(attachment.id);} catch (e) {- console.error(e, attachment);+ logger.error(e, { attachment });const error = e.message;await this.db.attachments.markAsFailed(attachment.id, error);}diff --git a/packages/core/api/sync/merger.js b/packages/core/api/sync/merger.jsindex 006ae9453..1f1b5b6fd 100644--- a/packages/core/api/sync/merger.js+++ b/packages/core/api/sync/merger.js@@ -191,8 +191,6 @@ class Merger {}async mergeItem(type, item) {- this.logger.info(`Merging ${type}`, { itemId: item.id });-this._lastSynced = await this._db.lastSynced();const definition = this._mergeDefinition[type];@@ -217,7 +215,6 @@ class Merger {} else if (!definition.get && definition.set) {await definition.set(item);}- this.logger.info(`Merged`, { itemId: item.id });}}export default Merger;