- Performance improvement
- Now `Chunk size` can be set to under one hundred.

New feature:
- The number of transfers required before replication stabilises is now displayed.
This commit is contained in:
vorotamoroz
2023-01-16 17:31:37 +09:00
parent d5e6419504
commit b444082b0c
4 changed files with 104 additions and 116 deletions

View File

@@ -1184,8 +1184,8 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab {
.setValue(this.plugin.settings.customChunkSize + "") .setValue(this.plugin.settings.customChunkSize + "")
.onChange(async (value) => { .onChange(async (value) => {
let v = Number(value); let v = Number(value);
if (isNaN(v) || v < 100) { if (isNaN(v) || v < 1) {
v = 100; v = 1;
} }
this.plugin.settings.customChunkSize = v; this.plugin.settings.customChunkSize = v;
await this.plugin.saveSettings(); await this.plugin.saveSettings();

Submodule src/lib updated: 2284678a59...39628ac8e6

View File

@@ -2,7 +2,7 @@ import { debounce, Notice, Plugin, TFile, addIcon, TFolder, normalizePath, TAbst
import { Diff, DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, diff_match_patch } from "diff-match-patch"; import { Diff, DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, diff_match_patch } from "diff-match-patch";
import { EntryDoc, LoadedEntry, ObsidianLiveSyncSettings, diff_check_result, diff_result_leaf, EntryBody, LOG_LEVEL, VER, DEFAULT_SETTINGS, diff_result, FLAGMD_REDFLAG, SYNCINFO_ID, InternalFileEntry } from "./lib/src/types"; import { EntryDoc, LoadedEntry, ObsidianLiveSyncSettings, diff_check_result, diff_result_leaf, EntryBody, LOG_LEVEL, VER, DEFAULT_SETTINGS, diff_result, FLAGMD_REDFLAG, SYNCINFO_ID, InternalFileEntry } from "./lib/src/types";
import { PluginDataEntry, PERIODIC_PLUGIN_SWEEP, PluginList, DevicePluginList, InternalFileInfo } from "./types"; import { PluginDataEntry, PERIODIC_PLUGIN_SWEEP, PluginList, DevicePluginList, InternalFileInfo, queueItem } from "./types";
import { import {
base64ToString, base64ToString,
arrayBufferToBase64, arrayBufferToBase64,
@@ -11,12 +11,9 @@ import {
versionNumberString2Number, versionNumberString2Number,
runWithLock, runWithLock,
shouldBeIgnored, shouldBeIgnored,
getProcessingCounts,
setLockNotifier,
isPlainText, isPlainText,
setNoticeClass, setNoticeClass,
NewNotice, NewNotice,
getLocks,
WrappedNotice, WrappedNotice,
Semaphore, Semaphore,
getDocData, getDocData,
@@ -38,6 +35,8 @@ const isDebug = false;
import { InputStringDialog, PluginDialogModal, PopoverSelectString } from "./dialogs"; import { InputStringDialog, PluginDialogModal, PopoverSelectString } from "./dialogs";
import { isCloudantURI } from "./lib/src/utils_couchdb"; import { isCloudantURI } from "./lib/src/utils_couchdb";
import { getGlobalStore, observeStores } from "./lib/src/store";
import { lockStore } from "./lib/src/stores";
setNoticeClass(Notice); setNoticeClass(Notice);
@@ -345,7 +344,6 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
this.statusBar = this.addStatusBarItem(); this.statusBar = this.addStatusBarItem();
this.statusBar.addClass("syncstatusbar"); this.statusBar.addClass("syncstatusbar");
this.refreshStatusText = this.refreshStatusText.bind(this);
this.statusBar2 = this.addStatusBarItem(); this.statusBar2 = this.addStatusBarItem();
this.watchVaultChange = this.watchVaultChange.bind(this); this.watchVaultChange = this.watchVaultChange.bind(this);
@@ -360,6 +358,7 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
this.parseReplicationResult = this.parseReplicationResult.bind(this); this.parseReplicationResult = this.parseReplicationResult.bind(this);
this.setPeriodicSync = this.setPeriodicSync.bind(this); this.setPeriodicSync = this.setPeriodicSync.bind(this);
this.clearPeriodicSync = this.clearPeriodicSync.bind(this);
this.periodicSync = this.periodicSync.bind(this); this.periodicSync = this.periodicSync.bind(this);
this.loadQueuedFiles = this.loadQueuedFiles.bind(this); this.loadQueuedFiles = this.loadQueuedFiles.bind(this);
@@ -634,9 +633,7 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
this.triggerRealizeSettingSyncMode = debounce(this.triggerRealizeSettingSyncMode.bind(this), 1000); this.triggerRealizeSettingSyncMode = debounce(this.triggerRealizeSettingSyncMode.bind(this), 1000);
this.triggerCheckPluginUpdate = debounce(this.triggerCheckPluginUpdate.bind(this), 3000); this.triggerCheckPluginUpdate = debounce(this.triggerCheckPluginUpdate.bind(this), 3000);
setLockNotifier(() => {
this.refreshStatusText();
});
this.addCommand({ this.addCommand({
id: "livesync-plugin-dialog", id: "livesync-plugin-dialog",
name: "Show Plugins and their settings", name: "Show Plugins and their settings",
@@ -726,9 +723,7 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
//@ts-ignore //@ts-ignore
const isMobile = this.app.isMobile; const isMobile = this.app.isMobile;
this.localDatabase = new LocalPouchDB(this.settings, vaultName, isMobile); this.localDatabase = new LocalPouchDB(this.settings, vaultName, isMobile);
this.localDatabase.updateInfo = () => { this.observeForLogs();
this.refreshStatusText();
};
return await this.localDatabase.initializeDatabase(); return await this.localDatabase.initializeDatabase();
} }
@@ -870,6 +865,7 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
} }
if (this.watchedFileEventQueue[i].type != type) break; if (this.watchedFileEventQueue[i].type != type) break;
this.watchedFileEventQueue.remove(this.watchedFileEventQueue[i]); this.watchedFileEventQueue.remove(this.watchedFileEventQueue[i]);
this.queuedFilesStore.set({ queuedItems: this.queuedFiles, fileEventItems: this.watchedFileEventQueue });
} }
} }
@@ -882,7 +878,7 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
ctx ctx
} }
}) })
this.refreshStatusText(); this.queuedFilesStore.set({ queuedItems: this.queuedFiles, fileEventItems: this.watchedFileEventQueue });
if (this.isReady) { if (this.isReady) {
await this.procFileEvent(); await this.procFileEvent();
} }
@@ -921,8 +917,6 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
if (queue.type == "DELETE") { if (queue.type == "DELETE") {
if (file instanceof TFile) { if (file instanceof TFile) {
await this.deleteFromDB(file); await this.deleteFromDB(file);
} else if (file instanceof TFolder) {
await this.deleteFolderOnDB(file);
} }
} }
if (queue.type == "RENAME") { if (queue.type == "RENAME") {
@@ -937,11 +931,9 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
await this.localDatabase.kvDB.set(key, file.stat.mtime); await this.localDatabase.kvDB.set(key, file.stat.mtime);
} }
} }
this.refreshStatusText();
} while (this.watchedFileEventQueue.length != 0); } while (this.watchedFileEventQueue.length != 0);
return true; return true;
}) })
this.refreshStatusText();
return ret; return ret;
} }
@@ -1056,30 +1048,13 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
return this.getFilePath(file.parent) + "/" + file.name; return this.getFilePath(file.parent) + "/" + file.name;
} }
async watchVaultRenameAsync(file: TAbstractFile, oldFile: any, cache?: CacheData) { async watchVaultRenameAsync(file: TFile, oldFile: any, cache?: CacheData) {
Logger(`${oldFile} renamed to ${file.path}`, LOG_LEVEL.VERBOSE); Logger(`${oldFile} renamed to ${file.path}`, LOG_LEVEL.VERBOSE);
if (file instanceof TFolder) { if (file instanceof TFile) {
const newFiles = this.GetAllFilesRecursively(file);
// for guard edge cases. this won't happen and each file's event will be raise.
for (const i of newFiles) {
try {
const newFilePath = normalizePath(this.getFilePath(i));
const newFile = getAbstractFileByPath(newFilePath);
if (newFile instanceof TFile) {
Logger(`save ${newFile.path} into db`);
await this.updateIntoDB(newFile);
}
} catch (ex) {
Logger(ex);
}
}
Logger(`delete below ${oldFile} from db`);
await this.deleteFromDBbyPath(oldFile);
} else if (file instanceof TFile) {
try { try {
Logger(`file save ${file.path} into db`); // Logger(`RENAMING.. ${file.path} into db`);
await this.updateIntoDB(file, false, cache); await this.updateIntoDB(file, false, cache);
Logger(`deleted ${oldFile} from db`); // Logger(`deleted ${oldFile} from db`);
await this.deleteFromDBbyPath(oldFile); await this.deleteFromDBbyPath(oldFile);
} catch (ex) { } catch (ex) {
Logger(ex); Logger(ex);
@@ -1200,7 +1175,6 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
ctime: doc.ctime, ctime: doc.ctime,
mtime: doc.mtime, mtime: doc.mtime,
}); });
// this.batchFileChange = this.batchFileChange.filter((e) => e != newFile.path);
Logger(msg + path); Logger(msg + path);
touch(newFile); touch(newFile);
this.app.vault.trigger("create", newFile); this.app.vault.trigger("create", newFile);
@@ -1220,7 +1194,6 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
ctime: doc.ctime, ctime: doc.ctime,
mtime: doc.mtime, mtime: doc.mtime,
}); });
// this.batchFileChange = this.batchFileChange.filter((e) => e != newFile.path);
Logger(msg + path); Logger(msg + path);
touch(newFile); touch(newFile);
this.app.vault.trigger("create", newFile); this.app.vault.trigger("create", newFile);
@@ -1243,11 +1216,11 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
} else { } else {
await this.app.vault.delete(file); await this.app.vault.delete(file);
} }
Logger(`deleted:${file.path}`); Logger(`xxx <- STORAGE (deleted) ${file.path}`);
Logger(`other items:${dir.children.length}`); Logger(`files: ${dir.children.length}`);
if (dir.children.length == 0) { if (dir.children.length == 0) {
if (!this.settings.doNotDeleteFolder) { if (!this.settings.doNotDeleteFolder) {
Logger(`all files deleted by replication, so delete dir`); Logger(`All files under the parent directory (${dir}) have been deleted, so delete this one.`);
await this.deleteVaultItem(dir); await this.deleteVaultItem(dir);
} }
} }
@@ -1355,7 +1328,6 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
} }
} }
); );
this.refreshStatusText();
} }
async handleDBChangedAsync(change: EntryBody) { async handleDBChangedAsync(change: EntryBody) {
@@ -1400,13 +1372,8 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
} }
} }
queuedFiles: { queuedFiles = [] as queueItem[];
entry: EntryBody; queuedFilesStore = getGlobalStore("queuedFiles", { queuedItems: [] as queueItem[], fileEventItems: [] as FileEventItem[] });
missingChildren: string[];
timeout?: number;
done?: boolean;
warned?: boolean;
}[] = [];
chunkWaitTimeout = 60000; chunkWaitTimeout = 60000;
saveQueuedFiles() { saveQueuedFiles() {
@@ -1433,7 +1400,6 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
await this.syncInternalFilesAndDatabase("pull", false, false, w); await this.syncInternalFilesAndDatabase("pull", false, false, w);
Logger(`Applying hidden ${w.length} files changed`); Logger(`Applying hidden ${w.length} files changed`);
}); });
this.refreshStatusText();
} }
procInternalFile(filename: string) { procInternalFile(filename: string) {
this.procInternalFiles.push(filename); this.procInternalFiles.push(filename);
@@ -1465,6 +1431,7 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
} }
} }
this.queuedFiles = this.queuedFiles.filter((e) => !e.done); this.queuedFiles = this.queuedFiles.filter((e) => !e.done);
this.queuedFilesStore.set({ queuedItems: this.queuedFiles, fileEventItems: this.watchedFileEventQueue });
this.saveQueuedFiles(); this.saveQueuedFiles();
} }
parseIncomingChunk(chunk: PouchDB.Core.ExistingDocument<EntryDoc>) { parseIncomingChunk(chunk: PouchDB.Core.ExistingDocument<EntryDoc>) {
@@ -1528,7 +1495,6 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
//---> Sync //---> Sync
async parseReplicationResult(docs: Array<PouchDB.Core.ExistingDocument<EntryDoc>>): Promise<void> { async parseReplicationResult(docs: Array<PouchDB.Core.ExistingDocument<EntryDoc>>): Promise<void> {
this.refreshStatusText();
for (const change of docs) { for (const change of docs) {
if (isPluginChunk(change._id)) { if (isPluginChunk(change._id)) {
if (this.settings.notifyPluginOrSettingUpdated) { if (this.settings.notifyPluginOrSettingUpdated) {
@@ -1600,8 +1566,8 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
} }
setPeriodicSync() { setPeriodicSync() {
this.clearPeriodicSync();
if (this.settings.periodicReplication && this.settings.periodicReplicationInterval > 0) { if (this.settings.periodicReplication && this.settings.periodicReplicationInterval > 0) {
this.clearPeriodicSync();
this.periodicSyncHandler = this.setInterval(async () => await this.periodicSync(), Math.max(this.settings.periodicReplicationInterval, 30) * 1000); this.periodicSyncHandler = this.setInterval(async () => await this.periodicSync(), Math.max(this.settings.periodicReplicationInterval, 30) * 1000);
} }
} }
@@ -1643,7 +1609,6 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
} }
if (this.settings.liveSync) { if (this.settings.liveSync) {
this.localDatabase.openReplication(this.settings, true, false, this.parseReplicationResult); this.localDatabase.openReplication(this.settings, true, false, this.parseReplicationResult);
this.refreshStatusText();
} }
if (this.settings.syncInternalFiles) { if (this.settings.syncInternalFiles) {
await this.syncInternalFilesAndDatabase("safe", false); await this.syncInternalFilesAndDatabase("safe", false);
@@ -1655,63 +1620,80 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
lastMessage = ""; lastMessage = "";
observeForLogs() {
const observer__ = observeStores(this.queuedFilesStore, lockStore);
const observer = observeStores(observer__, this.localDatabase.stat);
observer.observe(e => {
const sent = e.sent;
const arrived = e.arrived;
const maxPullSeq = e.maxPullSeq;
const maxPushSeq = e.maxPushSeq;
const lastSyncPullSeq = e.lastSyncPullSeq;
const lastSyncPushSeq = e.lastSyncPushSeq;
let pushLast = "";
let pullLast = "";
let w = "";
switch (e.syncStatus) {
case "CLOSED":
case "COMPLETED":
case "NOT_CONNECTED":
w = "⏹";
break;
case "STARTED":
w = "🌀";
break;
case "PAUSED":
w = "💤";
break;
case "CONNECTED":
w = "⚡";
pushLast = ((lastSyncPushSeq == 0) ? "" : (lastSyncPushSeq >= maxPushSeq ? " (LIVE)" : ` (${maxPushSeq - lastSyncPushSeq})`));
pullLast = ((lastSyncPullSeq == 0) ? "" : (lastSyncPullSeq >= maxPullSeq ? " (LIVE)" : ` (${maxPullSeq - lastSyncPullSeq})`));
break;
case "ERRORED":
w = "⚠";
break;
default:
w = "?";
}
this.statusBar.title = e.syncStatus;
let waiting = "";
if (this.settings.batchSave) {
waiting = " " + this.watchedFileEventQueue.map((e) => "🛫").join("");
waiting = waiting.replace(/(🛫){10}/g, "🚀");
}
let queued = "";
const queue = Object.entries(e.queuedItems).filter((e) => !e[1].warned);
const queuedCount = queue.length;
if (queuedCount) {
const pieces = queue.map((e) => e[1].missingChildren).reduce((prev, cur) => prev + cur.length, 0);
queued = ` 🧩 ${queuedCount} (${pieces})`;
}
const processes = e.count;
const processesDisp = processes == 0 ? "" : `${processes}`;
const message = `Sync: ${w}${sent}${pushLast}${arrived}${pullLast}${waiting}${processesDisp}${queued}`;
// const locks = getLocks();
const pendingTask = e.pending.length
? "\nPending: " +
Object.entries(e.pending.reduce((p, c) => ({ ...p, [c]: (p[c] ?? 0) + 1 }), {} as { [key: string]: number }))
.map((e) => `${e[0]}${e[1] == 1 ? "" : `(${e[1]})`}`)
.join(", ")
: "";
const runningTask = e.running.length
? "\nRunning: " +
Object.entries(e.running.reduce((p, c) => ({ ...p, [c]: (p[c] ?? 0) + 1 }), {} as { [key: string]: number }))
.map((e) => `${e[0]}${e[1] == 1 ? "" : `(${e[1]})`}`)
.join(", ")
: "";
this.setStatusBarText(message + pendingTask + runningTask);
})
}
refreshStatusText() { refreshStatusText() {
const sent = this.localDatabase.docSent; return;
const arrived = this.localDatabase.docArrived;
let w = "";
switch (this.localDatabase.syncStatus) {
case "CLOSED":
case "COMPLETED":
case "NOT_CONNECTED":
w = "⏹";
break;
case "STARTED":
w = "🌀";
break;
case "PAUSED":
w = "💤";
break;
case "CONNECTED":
w = "⚡";
break;
case "ERRORED":
w = "⚠";
break;
default:
w = "?";
}
this.statusBar.title = this.localDatabase.syncStatus;
let waiting = "";
if (this.settings.batchSave) {
waiting = " " + this.watchedFileEventQueue.map((e) => "🛫").join("");
waiting = waiting.replace(/(🛫){10}/g, "🚀");
}
let queued = "";
const queue = Object.entries(this.queuedFiles).filter((e) => !e[1].warned);
const queuedCount = queue.length;
if (queuedCount) {
const pieces = queue.map((e) => e[1].missingChildren).reduce((prev, cur) => prev + cur.length, 0);
queued = ` 🧩 ${queuedCount} (${pieces})`;
}
const processes = getProcessingCounts();
const processesDisp = processes == 0 ? "" : `${processes}`;
const message = `Sync: ${w}${sent}${arrived}${waiting}${processesDisp}${queued}`;
const locks = getLocks();
const pendingTask = locks.pending.length
? "\nPending: " +
Object.entries(locks.pending.reduce((p, c) => ({ ...p, [c]: (p[c] ?? 0) + 1 }), {} as { [key: string]: number }))
.map((e) => `${e[0]}${e[1] == 1 ? "" : `(${e[1]})`}`)
.join(", ")
: "";
const runningTask = locks.running.length
? "\nRunning: " +
Object.entries(locks.running.reduce((p, c) => ({ ...p, [c]: (p[c] ?? 0) + 1 }), {} as { [key: string]: number }))
.map((e) => `${e[0]}${e[1] == 1 ? "" : `(${e[1]})`}`)
.join(", ")
: "";
this.setStatusBarText(message + pendingTask + runningTask);
} }
logHideTimer: NodeJS.Timeout = null; logHideTimer: NodeJS.Timeout = null;
@@ -1726,10 +1708,8 @@ export default class ObsidianLiveSyncPlugin extends Plugin {
const root = activeDocument.documentElement; const root = activeDocument.documentElement;
const q = root.querySelectorAll(`.CodeMirror-wrap,.cm-s-obsidian>.cm-editor,.canvas-wrapper`); const q = root.querySelectorAll(`.CodeMirror-wrap,.cm-s-obsidian>.cm-editor,.canvas-wrapper`);
q.forEach(e => e.setAttr("data-log", '' + (newMsg + "\n" + newLog) + '')) q.forEach(e => e.setAttr("data-log", '' + (newMsg + "\n" + newLog) + ''))
// root.style.setProperty("--slsmessage", '"' + (newMsg + "\n" + newLog).split("\n").join("\\a ") + '"');
} else { } else {
const root = activeDocument.documentElement; const root = activeDocument.documentElement;
// root.style.setProperty("--slsmessage", '""');
const q = root.querySelectorAll(`.CodeMirror-wrap,.cm-s-obsidian>.cm-editor,.canvas-wrapper`); const q = root.querySelectorAll(`.CodeMirror-wrap,.cm-s-obsidian>.cm-editor,.canvas-wrapper`);
q.forEach(e => e.setAttr("data-log", '')) q.forEach(e => e.setAttr("data-log", ''))
} }

View File

@@ -1,5 +1,5 @@
import { PluginManifest } from "obsidian"; import { PluginManifest } from "obsidian";
import { DatabaseEntry } from "./lib/src/types"; import { DatabaseEntry, EntryBody } from "./lib/src/types";
export interface PluginDataEntry extends DatabaseEntry { export interface PluginDataEntry extends DatabaseEntry {
deviceVaultName: string; deviceVaultName: string;
@@ -30,3 +30,11 @@ export interface InternalFileInfo {
size: number; size: number;
deleted?: boolean; deleted?: boolean;
} }
export type queueItem = {
entry: EntryBody;
missingChildren: string[];
timeout?: number;
done?: boolean;
warned?: boolean;
};