Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(client): spaced update can cross note boundaries (closes #9614)
Elian Doranaf1e4b2eec61
diff --git a/apps/client/src/services/spaced_update.spec.ts b/apps/client/src/services/spaced_update.spec.tsindex dd71c2d7e8..9dbe58b810 100644--- a/apps/client/src/services/spaced_update.spec.ts+++ b/apps/client/src/services/spaced_update.spec.ts@@ -232,6 +232,116 @@ describe("SpacedUpdate", () => {});});+ describe("keyed bindings (prepare/commit)", () => {+ function setupKeyedHarness() {+ // Stand-in for a reused editor: holds whichever note's content was last loaded.+ const editor = { content: "A content" };+ const commits: { key: string; data: string }[] = [];+ const makeBinding = (key: string) => ({+ key,+ prepare: () => editor.content,+ commit: async (data: string) => {+ commits.push({ key, data });+ }+ });+ return { editor, commits, makeBinding };+ }++ it("commits a pending change under the binding that scheduled it, even after rebinding", async () => {+ const { editor, commits, makeBinding } = setupKeyedHarness();+ const spacedUpdate = new SpacedUpdate<string>(makeBinding("A"), 50);++ // A change is pending against A when the consumer rebinds to B; the snapshot is+ // taken with A's binding before the swap, so it can never be saved under B.+ spacedUpdate.scheduleUpdate();+ const b = makeBinding("B");+ spacedUpdate.rebind(b.key, b.prepare, b.commit);+ editor.content = "B content"; // B's content arrives only after the rebind++ await vi.runAllTimersAsync();+ expect(commits).toEqual([{ key: "A", data: "A content" }]);++ // A change made after the rebind saves under the new binding.+ spacedUpdate.scheduleUpdate();+ await vi.runAllTimersAsync();+ expect(commits).toEqual([+ { key: "A", data: "A content" },+ { key: "B", data: "B content" }+ ]);+ });++ it("retries a failed commit with the frozen snapshot, not the live state", async () => {+ const editor = { content: "typed into A" };+ const commits: string[] = [];+ let failuresLeft = 1;+ const spacedUpdate = new SpacedUpdate<string>({+ key: "A",+ prepare: () => editor.content,+ commit: async (data) => {+ if (failuresLeft > 0) {+ failuresLeft--;+ throw new Error("offline");+ }+ commits.push(data);+ }+ }, 50);++ spacedUpdate.scheduleUpdate();+ await vi.advanceTimersByTimeAsync(60); // first attempt fails++ // The live state moves on (e.g. another note's content is loaded into the editor),+ // but the retry must persist the snapshot taken when the change was flushed.+ editor.content = "now showing B";+ await vi.advanceTimersByTimeAsync(200); // backoff retry fires++ expect(commits).toEqual(["typed into A"]);+ });++ it("supersedes a queued failed snapshot with a newer one for the same key", async () => {+ const editor = { content: "v1" };+ const commits: string[] = [];+ let failuresLeft = 1;+ const spacedUpdate = new SpacedUpdate<string>({+ key: "A",+ prepare: () => editor.content,+ commit: async (data) => {+ if (failuresLeft > 0) {+ failuresLeft--;+ throw new Error("offline");+ }+ commits.push(data);+ }+ }, 50);++ spacedUpdate.scheduleUpdate();+ await vi.advanceTimersByTimeAsync(60); // "v1" fails and stays queued++ editor.content = "v2";+ spacedUpdate.scheduleUpdate();+ await vi.advanceTimersByTimeAsync(300);++ // The newer snapshot replaced the queued one: a single save with the latest data,+ // not a stale "v1" overwriting "v2".+ expect(commits).toEqual(["v2"]);+ });++ it("supports an asynchronous prepare", async () => {+ const commits: string[] = [];+ const spacedUpdate = new SpacedUpdate<string>({+ key: "A",+ prepare: () => Promise.resolve("async snapshot"),+ commit: async (data) => {+ commits.push(data);+ }+ }, 50);++ spacedUpdate.scheduleUpdate();+ await spacedUpdate.updateNowIfNecessary();++ expect(commits).toEqual(["async snapshot"]);+ });+ });+describe("allowUpdateWithoutChange", () => {it("suppresses scheduleUpdate while the callback runs and re-enables it afterwards", async () => {const updater = vi.fn(async () => {});diff --git a/apps/client/src/services/spaced_update.ts b/apps/client/src/services/spaced_update.tsindex 13cdbd7b5e..b011bdeb03 100644--- a/apps/client/src/services/spaced_update.ts+++ b/apps/client/src/services/spaced_update.ts@@ -5,8 +5,37 @@ type Callback = () => Promise<void> | void;export type StateCallback = (state: SaveState) => void;-export default class SpacedUpdate {- private updater: Callback;+type PrepareCallback<T> = () => T | Promise<T>;+type CommitCallback<T> = (data: T) => Promise<void> | void;++/**+ * Binds pending changes to the target they belong to (see #9614).+ *+ * A change scheduled while one binding is active is always *snapshotted* (via {@link SpacedUpdateBinding.prepare})+ * before the binding can be swapped to a different key, and the snapshot is committed together with the+ * `commit` closure that was current when it was taken. This makes it impossible for a pending change to be+ * persisted under a different target than the one it was made against, no matter when the save fires.+ */+export interface SpacedUpdateBinding<T> {+ /** Identity of the save target (e.g. a noteId). Pending changes never cross a key change. */+ key: string | null;+ /** Snapshots the live state that should be saved. May refuse by returning a value `commit` treats as a no-op. */+ prepare: PrepareCallback<T>;+ /** Persists a snapshot. Retries always reuse the closure that was current when the snapshot was taken. */+ commit: CommitCallback<T>;+}++interface PendingCommit<T> {+ data: T;+ commit: CommitCallback<T>;+}++const MAX_RETRY_DELAY = 60_000;++export default class SpacedUpdate<T = void> {+ private bindingKey: string | null;+ private prepare: PrepareCallback<T>;+ private commit: CommitCallback<T>;private lastUpdated: number;private changed: boolean;private updateInterval: number;@@ -14,8 +43,30 @@ export default class SpacedUpdate {private stateCallback?: StateCallback;private lastState: SaveState = "saved";- constructor(updater: Callback, updateInterval = 1000, stateCallback?: StateCallback) {- this.updater = updater;+ /**+ * Snapshots that have been taken but not successfully persisted yet, by binding key.+ * A newer snapshot for the same key supersedes the queued one. Entries survive failed+ * commits and are retried (with backoff) until they land — they are never dropped.+ */+ private pendingCommits = new Map<string | null, PendingCommit<T>>();+ private drainPromise: Promise<void> | null = null;+ private debounceTimer?: ReturnType<typeof setTimeout>;+ private retryTimer?: ReturnType<typeof setTimeout>;+ private retryCount = 0;++ constructor(updaterOrBinding: Callback | SpacedUpdateBinding<T>, updateInterval = 1000, stateCallback?: StateCallback) {+ if (typeof updaterOrBinding === "function") {+ // Legacy single-callback mode: the updater reads live state and persists it in one+ // step, so there is nothing to snapshot and the binding key never changes.+ this.bindingKey = null;+ this.prepare = () => undefined as T;+ this.commit = () => updaterOrBinding();+ } else {+ this.bindingKey = updaterOrBinding.key;+ this.prepare = updaterOrBinding.prepare;+ this.commit = updaterOrBinding.commit;+ }+this.lastUpdated = Date.now();this.changed = false;this.updateInterval = updateInterval;@@ -26,38 +77,56 @@ export default class SpacedUpdate {if (!this.changeForbidden) {this.changed = true;this.onStateChanged("unsaved");- setTimeout(() => this.triggerUpdate());+ this.armDebounceTimer();}}- async updateNowIfNecessary() {- if (this.changed) {- this.changed = false; // optimistic...+ /**+ * Swaps the binding to a new target. If the key changes while a change is still pending,+ * the change is first snapshotted with the *previous* binding (and committed in the+ * background, addressed to the previous key), so it can never be saved under the new key.+ */+ rebind(key: string | null, prepare: PrepareCallback<T>, commit: CommitCallback<T>) {+ if (key !== this.bindingKey && this.changed) {+ const snapshotted = this.snapshotPending();+ const drainInBackground = () => {+ this.drain().catch(() => {+ // Failures are logged in runDrain and retried; the snapshot stays addressed to the old key.+ });+ };- try {- this.onStateChanged("saving");- await this.updater();- this.onStateChanged("saved");- } catch (e) {- this.changed = true;- this.onStateChanged("error");- logError(getErrorMessage(e));- throw e;+ if (snapshotted instanceof Promise) {+ // The old prepare() was already invoked synchronously, so swapping the binding+ // below cannot leak the pending change to the new key.+ snapshotted.then(drainInBackground, () => {});+ } else {+ drainInBackground();}}++ this.bindingKey = key;+ this.prepare = prepare;+ this.commit = commit;+ }++ /** Flushes the pending change (if any) and waits until all queued snapshots are persisted. */+ updateNowIfNecessary(): Promise<void> {+ return this.drain();}isAllSavedAndTriggerUpdate() {- const allSaved = !this.changed;+ const allSaved = !this.changed && this.pendingCommits.size === 0 && !this.drainPromise;- this.updateNowIfNecessary();+ this.updateNowIfNecessary().catch(() => {+ // Failures are logged in runDrain and retried.+ });return allSaved;}/*** Normally {@link scheduleUpdate()} would actually trigger the update only once per {@link updateInterval}. If the method is called 200 times within 20s, it will execute only 20 times.- * Sometimes, if the updates are continuous this would cause a performance impact. Resetting the time ensures that the calls to {@link triggerUpdate} have stopped before actually triggering an update.+ * Sometimes, if the updates are continuous this would cause a performance impact. Resetting the time ensures that the calls to the update have stopped before actually triggering an update.*/resetUpdateTimer() {this.lastUpdated = Date.now();@@ -71,34 +140,6 @@ export default class SpacedUpdate {this.updateInterval = interval;}- async triggerUpdate() {- if (!this.changed) {- return;- }-- if (Date.now() - this.lastUpdated > this.updateInterval) {- // Update these BEFORE the async call to prevent race conditions.- // Multiple setTimeout callbacks may be pending from recursive scheduleUpdate() calls.- // Without this, they would all pass the time check during the await and trigger multiple requests.- this.lastUpdated = Date.now();- this.changed = false;-- this.onStateChanged("saving");- try {- await this.updater();- this.onStateChanged("saved");- } catch (e) {- // Restore changed flag on error so a retry can happen- this.changed = true;- this.onStateChanged("error");- logError(getErrorMessage(e));- }- } else {- // update isn't triggered but changes are still pending, so we need to schedule another check- this.scheduleUpdate();- }- }-onStateChanged(state: SaveState) {if (state === this.lastState) return;@@ -115,4 +156,154 @@ export default class SpacedUpdate {this.changeForbidden = false;}}++ /**+ * Single debounce timer replacing the old 0-ms self-rescheduling loop: armed with the time+ * remaining until the interval elapses, re-armed if {@link resetUpdateTimer} pushed it back.+ */+ private armDebounceTimer() {+ if (this.debounceTimer) {+ return;+ }++ const delay = Math.max(1, this.updateInterval - (Date.now() - this.lastUpdated));+ this.debounceTimer = setTimeout(() => {+ this.debounceTimer = undefined;++ if (!this.changed) {+ return;+ }++ if (Date.now() - this.lastUpdated >= this.updateInterval) {+ this.drain().catch(() => {+ // Failures are logged in runDrain and retried.+ });+ } else {+ this.armDebounceTimer();+ }+ }, delay);+ }++ /**+ * Snapshots the pending change with the *current* binding and queues it for commit.+ * Returns a promise only when `prepare` is asynchronous; in the synchronous case the+ * snapshot is queued before this method returns, so callers (notably the `beforeunload`+ * path) can rely on the commit starting synchronously within {@link drain}.+ */+ private snapshotPending(): void | Promise<void> {+ if (!this.changed) {+ return;+ }++ this.changed = false;+ this.lastUpdated = Date.now();++ const { bindingKey, commit } = this;+ const restoreOnError = (e: unknown): never => {+ this.changed = true;+ this.onStateChanged("error");+ throw e;+ };++ let result: T | Promise<T>;+ try {+ result = this.prepare();+ } catch (e) {+ return restoreOnError(e);+ }++ if (result instanceof Promise) {+ return result.then(+ (data) => {+ this.pendingCommits.set(bindingKey, { data, commit });+ },+ restoreOnError+ );+ }++ this.pendingCommits.set(bindingKey, { data: result, commit });+ }++ private drain(): Promise<void> {+ if (this.drainPromise) {+ return this.drainPromise;+ }++ if (!this.changed && this.pendingCommits.size === 0) {+ return Promise.resolve();+ }++ this.drainPromise = this.runDrain().finally(() => {+ this.drainPromise = null;+ });++ return this.drainPromise;+ }++ private async runDrain(): Promise<void> {+ while (true) {+ // Fold any pending change into the queue first, so a queued snapshot and a newer+ // pending change for the same key result in a single save, not two.+ const snapshotted = this.snapshotPending();+ if (snapshotted instanceof Promise) {+ await snapshotted;+ }++ if (this.pendingCommits.size === 0) {+ break;+ }++ this.onStateChanged("saving");++ let failed = false;+ let firstError: unknown;++ for (const key of [ ...this.pendingCommits.keys() ]) {+ const entry = this.pendingCommits.get(key);+ if (!entry) {+ continue;+ }++ try {+ await entry.commit(entry.data);+ this.retryCount = 0;++ // Delete only if the entry was not superseded by a newer snapshot during the await.+ if (this.pendingCommits.get(key) === entry) {+ this.pendingCommits.delete(key);+ }+ } catch (e) {+ if (!failed) {+ failed = true;+ firstError = e;+ }+ logError(getErrorMessage(e));+ }+ }++ if (failed) {+ this.onStateChanged("error");+ this.scheduleRetry();+ throw firstError;+ }+ }++ this.onStateChanged(this.changed ? "unsaved" : "saved");+ }++ private scheduleRetry() {+ if (this.retryTimer) {+ return;+ }++ const delay = Math.min(this.updateInterval * 2 ** this.retryCount, MAX_RETRY_DELAY);+ this.retryCount++;++ this.retryTimer = setTimeout(() => {+ this.retryTimer = undefined;+ this.drain().catch(() => {+ // Failures are logged in runDrain and will be retried again.+ });+ }, delay);+ }}diff --git a/apps/client/src/widgets/react/editor_save_race.spec.tsx b/apps/client/src/widgets/react/editor_save_race.spec.tsxindex 2f59072d0c..48e5fa06af 100644--- a/apps/client/src/widgets/react/editor_save_race.spec.tsx+++ b/apps/client/src/widgets/react/editor_save_race.spec.tsx@@ -26,13 +26,13 @@ import type FNote from "../../entities/fnote";import server from "../../services/server";import type SpacedUpdate from "../../services/spaced_update";import { buildNote } from "../../test/easy-froca";-import { useEditorSpacedUpdate } from "./hooks";+import { type SavedData, useEditorSpacedUpdate } from "./hooks";import { ParentComponent } from "./react_utils";vi.stubGlobal("logError", vi.fn());vi.stubGlobal("logInfo", vi.fn());-let currentSpacedUpdate: SpacedUpdate | undefined;+let currentSpacedUpdate: SpacedUpdate<SavedData | undefined> | undefined;/** Stand-in for EditableText: `editor.content` plays the role of the live CKEditor document. */function FakeEditor({ note, noteContext, editor }: {@@ -52,7 +52,7 @@ function FakeEditor({ note, noteContext, editor }: {return null;}-function getSpacedUpdate(): SpacedUpdate {+function getSpacedUpdate(): SpacedUpdate<SavedData | undefined> {if (!currentSpacedUpdate) {throw new Error("Harness was not rendered yet");}diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex 672922d012..6449b0fa8f 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -115,33 +115,61 @@ export function useEditorSpacedUpdate({ note, noteType, noteContext, getData, onconst parentComponent = useContext(ParentComponent);const blob = useNoteBlob(note, parentComponent?.componentId);- const callback = useMemo(() => {- return async () => {- const data = await getData();+ // The note whose content is currently loaded in the editor. Editor instances are reused+ // across note switches, so until the new note's blob arrives the editor still holds the+ // previous note's content — content that must never be saved under the new noteId (#9614).+ const loadedNoteIdRef = useRef<string>();- // for read only notes, or if note is not yet available (e.g. lazy creation)- if (data === undefined || !note || note.type !== noteType) return;+ const prepare = useCallback(() => {+ if (!note || loadedNoteIdRef.current !== note.noteId) return undefined;+ return getData();+ }, [ note, getData ]);- protected_session_holder.touchProtectedSessionIfNecessary(note);+ const commit = useCallback(async (data: SavedData | undefined) => {+ // for read only notes, or if note is not yet available (e.g. lazy creation)+ if (data === undefined || !note || note.type !== noteType) return;- await server.put(`notes/${note.noteId}/data`, data, parentComponent?.componentId);+ protected_session_holder.touchProtectedSessionIfNecessary(note);++ await server.put(`notes/${note.noteId}/data`, data, parentComponent?.componentId);++ noteSavedDataStore.set(note.noteId, data.content);+ dataSaved?.(data);+ }, [ note, dataSaved, noteType, parentComponent ]);- noteSavedDataStore.set(note.noteId, data.content);- dataSaved?.(data);- };- }, [ note, getData, dataSaved, noteType, parentComponent ]);const stateCallback = useCallback<StateCallback>((state) => {noteContext?.setContextData("saveState", {state});}, [ noteContext ]);- const spacedUpdate = useSpacedUpdate(callback, updateInterval, stateCallback);+ const stateCallbackRef = useRef(stateCallback);+ useEffect(() => {+ stateCallbackRef.current = stateCallback;+ }, [ stateCallback ]);++ const spacedUpdateRef = useRef<SpacedUpdate<SavedData | undefined>>();+ if (!spacedUpdateRef.current) {+ spacedUpdateRef.current = new SpacedUpdate<SavedData | undefined>(+ { key: note?.noteId ?? null, prepare, commit },+ updateInterval,+ (state) => stateCallbackRef.current(state)+ );+ }+ const spacedUpdate = spacedUpdateRef.current;++ // Rebind to the current note on every render. When the note changes while a change is+ // still pending, rebind() snapshots it with the previous binding first, so it is saved+ // under the note it was typed into rather than the note the component now displays.+ useEffect(() => {+ spacedUpdate.rebind(note?.noteId ?? null, prepare, commit);+ });// React to note/blob changes.useEffect(() => {if (!blob || !note) return;noteSavedDataStore.set(note.noteId, blob.content);spacedUpdate.allowUpdateWithoutChange(() => onContentChange(blob.content));+ loadedNoteIdRef.current = note.noteId;}, [ blob ]);// React to update interval changes.@@ -186,29 +214,55 @@ export function useBlobEditorSpacedUpdate({ note, noteType, noteContext, getDataconst parentComponent = useContext(ParentComponent);const blob = useNoteBlob(note, parentComponent?.componentId);- const callback = useMemo(() => {- return async () => {- const data = await getData();+ // Same provenance guard as useEditorSpacedUpdate: never save content under a note it+ // was not loaded from (#9614).+ const loadedNoteIdRef = useRef<string>();- // for read only notes- if (data === undefined || note.type !== noteType) return;+ const prepare = useCallback(() => {+ if (loadedNoteIdRef.current !== note.noteId) return undefined;+ return getData();+ }, [ note, getData ]);++ const commit = useCallback(async (data: Blob | undefined) => {+ // for read only notes+ if (data === undefined || note.type !== noteType) return;++ protected_session_holder.touchProtectedSessionIfNecessary(note);+ await server.upload(`notes/${note.noteId}/file?replace=${replaceWithoutRevision ? "1" : "0"}`, new File([ data ], note.title, { type: note.mime }), parentComponent?.componentId);+ dataSaved?.(data);+ }, [ note, dataSaved, noteType, parentComponent, replaceWithoutRevision ]);- protected_session_holder.touchProtectedSessionIfNecessary(note);- await server.upload(`notes/${note.noteId}/file?replace=${replaceWithoutRevision ? "1" : "0"}`, new File([ data ], note.title, { type: note.mime }), parentComponent?.componentId);- dataSaved?.(data);- };- }, [ note, getData, dataSaved, noteType, parentComponent, replaceWithoutRevision ]);const stateCallback = useCallback<StateCallback>((state) => {noteContext?.setContextData("saveState", {state});}, [ noteContext ]);- const spacedUpdate = useSpacedUpdate(callback, updateInterval, stateCallback);+ const stateCallbackRef = useRef(stateCallback);+ useEffect(() => {+ stateCallbackRef.current = stateCallback;+ }, [ stateCallback ]);++ const spacedUpdateRef = useRef<SpacedUpdate<Blob | undefined>>();+ if (!spacedUpdateRef.current) {+ spacedUpdateRef.current = new SpacedUpdate<Blob | undefined>(+ { key: note.noteId, prepare, commit },+ updateInterval,+ (state) => stateCallbackRef.current(state)+ );+ }+ const spacedUpdate = spacedUpdateRef.current;++ // Rebind to the current note on every render; flushes a pending change with the previous+ // binding when the note changes (see useEditorSpacedUpdate).+ useEffect(() => {+ spacedUpdate.rebind(note.noteId, prepare, commit);+ });// React to note/blob changes.useEffect(() => {if (!blob) return;spacedUpdate.allowUpdateWithoutChange(() => onContentChange(blob));+ loadedNoteIdRef.current = note.noteId;}, [ blob ]);// React to update interval changes.