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(standalone): give a scheduled execution its own context
Elian Dorancc94b6c22872
diff --git a/packages/trilium-core/src/services/one_time_timer.spec.ts b/packages/trilium-core/src/services/one_time_timer.spec.tsindex b9de733b26..bab0d84d13 100644--- a/packages/trilium-core/src/services/one_time_timer.spec.ts+++ b/packages/trilium-core/src/services/one_time_timer.spec.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as cls from "./context.js";import { getLog } from "./log.js";import oneTimeTimer from "./one_time_timer.js";@@ -133,4 +134,34 @@ describe("oneTimeTimer", () => {expect(inner).toHaveBeenCalledTimes(1);});});++ describe("execution context", () => {+ beforeEach(() => {+ // Real timers, because what is under test is what survives an actual asynchronous+ // hop: AsyncLocalStorage carries a scope across one, the browser context's stack+ // has already unwound by then.+ vi.useRealTimers();+ });++ it("runs the callback inside an execution context, so a committing write can record its entity changes", async () => {+ let failure: unknown;++ // The entity-deletion handler schedules "hidden-subtree-check" from inside the scope+ // of the write that triggered it. checkHiddenSubtree() commits a transaction, and+ // ws.sendTransactionEntityChangesToAllClients() then calls this on the way out.+ cls.init(() => {+ oneTimeTimer.scheduleExecution("context-scope", 1, () => {+ try {+ cls.getAndClearEntityChangeIds();+ } catch (e: unknown) {+ failure = e;+ }+ });+ });++ await new Promise((resolve) => setTimeout(resolve, 20));++ expect(failure).toBeUndefined();+ });+ });});diff --git a/packages/trilium-core/src/services/one_time_timer.ts b/packages/trilium-core/src/services/one_time_timer.tsindex d06e2c84a7..016d61778b 100644--- a/packages/trilium-core/src/services/one_time_timer.ts+++ b/packages/trilium-core/src/services/one_time_timer.ts@@ -1,3 +1,4 @@+import * as cls from "./context.js";import { getLog } from "./log.js";const scheduledExecutions: Record<string, boolean> = {};@@ -19,7 +20,9 @@ function scheduleExecution(name: string, milliseconds: number, cb: () => void) {delete scheduledExecutions[name];try {- cb();+ // A scope of its own, because the browser ExecutionContext cannot carry one across a+ // timer, and a write in the callback needs somewhere to record its entity changes.+ cls.init(cb);} catch (e: unknown) {// A synchronous throw here would surface as an uncaughtException and kill the process// (see #10549), so contain it — a scheduled maintenance task must never take the app down.