Skip to content

Build your personal knowledge base with Trilium Notes

fix(standalone): keep each request's execution context to itself

Elian Doran9bab5ca89547
diff --git a/apps/standalone/src/lightweight/browser_router.spec.ts b/apps/standalone/src/lightweight/browser_router.spec.ts
index 81408f11f9..09b0c8fd0a 100644
--- a/apps/standalone/src/lightweight/browser_router.spec.ts
+++ b/apps/standalone/src/lightweight/browser_router.spec.ts
@@ -1,6 +1,8 @@
+import { getContext } from "@triliumnext/core";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BrowserRouter, createRouter } from "./browser_router.js";
+import { dbLock } from "./db_lock.js";
const RAW_RESPONSE = Symbol.for("RAW_RESPONSE");
const encoder = new TextEncoder();
@@ -266,3 +268,59 @@ describe("BrowserRouter error formatting", () => {
expect(JSON.parse(decodeBody(res.body))).toEqual({ message: "plain string" });
});
});
+
+/**
+ * Every route `browser_routes.ts` registers opens its own execution context inside `dbLock`, which
+ * is what keeps one scope live at a time: a synchronous handler cannot be interleaved, and an
+ * asynchronous one holds the connection exclusively. A context opened by `dispatch` itself would
+ * sit outside that lock, so a second request in flight would cover the first — which the first
+ * reads again after its awaits.
+ */
+describe("BrowserRouter execution context", () => {
+ it("leaves a request's context to it while another request dispatches", async () => {
+ const router = new BrowserRouter();
+ const ctx = getContext();
+ let release = () => {};
+ const paused = new Promise<void>((resolve) => { release = resolve; });
+ let seenAfterAwait: string | undefined;
+
+ // Mirrors createAsyncRoute: exclusive for as long as its transaction stays open.
+ router.get("/slow", () => dbLock.runExclusive(() => ctx.init(async () => {
+ ctx.set("componentId", "slow");
+ await paused;
+ seenAfterAwait = ctx.get<string>("componentId");
+ return {};
+ })));
+
+ // Mirrors wrapHandler: shared, and synchronous once it holds the lock.
+ router.get("/quick", () => dbLock.runShared(() => ctx.init(() => {
+ ctx.set("componentId", "quick");
+ return {};
+ })));
+
+ const slow = router.dispatch("GET", "http://localhost/slow");
+ const quick = router.dispatch("GET", "http://localhost/quick");
+ release();
+ await Promise.all([slow, quick]);
+
+ expect(seenAfterAwait).toBe("slow");
+ });
+
+ it("does not open an execution context of its own", async () => {
+ const router = new BrowserRouter();
+ const ctx = getContext();
+ let scoped = true;
+ router.get("/bare", () => {
+ try {
+ ctx.set("componentId", "bare");
+ } catch {
+ scoped = false;
+ }
+ return {};
+ });
+
+ await router.dispatch("GET", "http://localhost/bare");
+
+ expect(scoped).toBe(false);
+ });
+});
diff --git a/apps/standalone/src/lightweight/browser_router.ts b/apps/standalone/src/lightweight/browser_router.ts
index c8e0d2635b..0b1396de33 100644
--- a/apps/standalone/src/lightweight/browser_router.ts
+++ b/apps/standalone/src/lightweight/browser_router.ts
@@ -3,7 +3,7 @@
* Supports path parameters (e.g., /api/notes/:noteId) and query strings.
*/
-import { getContext, routes } from "@triliumnext/core";
+import { routes } from "@triliumnext/core";
export interface UploadedFile {
originalname: string;
@@ -226,7 +226,10 @@ export class BrowserRouter {
};
try {
- const result = await getContext().init(async () => await route.handler(request));
+ // No execution context is opened here: every route registered by
+ // `browser_routes.ts` opens its own inside `dbLock`, which is what keeps one
+ // asynchronous scope live at a time. One opened here would sit outside that lock.
+ const result = await route.handler(request);
return this.formatResult(result);
} catch (error) {
return this.formatError(error, `Error handling ${method} ${path}`);
diff --git a/apps/standalone/src/lightweight/cls_provider.spec.ts b/apps/standalone/src/lightweight/cls_provider.spec.ts
index 794a1b911f..bc178183fa 100644
--- a/apps/standalone/src/lightweight/cls_provider.spec.ts
+++ b/apps/standalone/src/lightweight/cls_provider.spec.ts
@@ -1,110 +1,113 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import BrowserExecutionContext from "./cls_provider.js";
+/**
+ * The browser has no `AsyncLocalStorage`, so scopes are tracked on a stack. That model is sound
+ * as long as one scope is live at a time, which `dbLock` gives the worker: a synchronous scope
+ * cannot be interleaved, and an asynchronous one holds the connection exclusively. What the stack
+ * still owes is LIFO discipline — a scope ends when its callback does, and ending it uncovers the
+ * one it was opened inside.
+ *
+ * Isolating scopes that genuinely overlap is not something a stack can do, so that is asserted
+ * where it is enforced instead: `browser_router.spec.ts`.
+ */
describe("BrowserExecutionContext", () => {
beforeEach(() => {
- vi.useFakeTimers();
+ // Nothing here is timer-driven. Faked so a stray cleanup timer cannot outlive its test.
+ vi.useFakeTimers({ shouldAdvanceTime: false });
});
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("returns undefined from get() when no context is active", () => {
+ it("returns undefined from get() outside a scope, and throws from set()", () => {
const ctx = new BrowserExecutionContext();
+
expect(ctx.get("anything")).toBeUndefined();
+ expect(() => ctx.set("k", "v")).toThrow("ExecutionContext not initialized");
});
- it("throws from set() when no context is active", () => {
+ it("ends a synchronous scope as soon as its callback returns", () => {
const ctx = new BrowserExecutionContext();
- expect(() => ctx.set("k", "v")).toThrow("ExecutionContext not initialized");
+
+ const returned = ctx.init(() => {
+ ctx.set("k", 42);
+ return ctx.get<number>("k");
+ });
+
+ expect(returned).toBe(42);
+ expect(ctx.get("k")).toBeUndefined();
});
- it("exposes get/set within a synchronous init() scope and cleans up after the grace period", () => {
+ it("keeps an async scope across its awaits and ends it once the promise settles", async () => {
const ctx = new BrowserExecutionContext();
- const result = ctx.init(() => {
- ctx.set("k", 42);
- expect(ctx.get<number>("k")).toBe(42);
- return "done";
+ let release = () => {};
+ const paused = new Promise<void>((resolve) => { release = resolve; });
+
+ const running = ctx.init(async () => {
+ ctx.set("k", "async");
+ await paused;
+ return ctx.get<string>("k");
});
- expect(result).toBe("done");
- // Still readable during the grace period.
- expect(ctx.get<number>("k")).toBe(42);
+ release();
- // After the grace period the context is popped off the stack.
- vi.advanceTimersByTime(1000);
+ await expect(running).resolves.toBe("async");
expect(ctx.get("k")).toBeUndefined();
});
- // Known limitation, recorded so a fix flips these assertions rather than passing silently.
- // A stack is not async-context propagation: the browser has no AsyncLocalStorage, so scopes
- // are pushed and popped, and a scope stays on the stack for the grace period after it ends.
- // The server's AsyncLocalStorage context gets both of these right.
- describe("stack-based scoping (known divergence from the server context)", () => {
- it("starts a nested scope empty, leaving the enclosing one reading it", () => {
- const ctx = new BrowserExecutionContext();
-
- ctx.init(() => {
- ctx.set("componentId", "outer");
-
- ctx.init(() => {
- // No inheritance: the server context would report "outer" here.
- expect(ctx.get("componentId")).toBeUndefined();
- ctx.set("componentId", "inner");
- });
-
- // The nested scope is still on top of the stack until its cleanup timer fires,
- // so the enclosing scope reads the nested scope's value instead of its own.
- expect(ctx.get<string>("componentId")).toBe("inner");
- });
- });
+ // Matches the server context, which routes/api/llm.ts depends on: it opens a nested scope
+ // while its request is still on the stack and reads the request's componentId through it.
+ it("inherits the enclosing scope, and uncovers it when the nested one ends", () => {
+ const ctx = new BrowserExecutionContext();
- it("lets overlapping scopes read each other's values", async () => {
- vi.useRealTimers();
- const ctx = new BrowserExecutionContext();
+ ctx.init(() => {
+ ctx.set("componentId", "outer");
+ ctx.set("hoistedNoteId", "noteABC");
- const request = (componentId: string, delayMs: number) => ctx.init(async () => {
- ctx.set("componentId", componentId);
- await new Promise((resolve) => setTimeout(resolve, delayMs));
+ const inner = ctx.init(() => {
+ expect(ctx.get<string>("componentId")).toBe("outer");
+ ctx.set("componentId", "inner");
return ctx.get<string>("componentId");
});
- // The worker's onmessage handler is async and unserialized, so requests do overlap.
- // Both read whichever scope is on top, rather than ["slow", "fast"].
- expect(await Promise.all([request("slow", 30), request("fast", 1)]))
- .toEqual(["fast", "fast"]);
+ expect(inner).toBe("inner");
+ expect(ctx.get<string>("componentId")).toBe("outer");
+ expect(ctx.get<string>("hoistedNoteId")).toBe("noteABC");
});
});
- it("cleans up after an async init() resolves", async () => {
+ it("ends a scope whose callback throws, leaving the enclosing one readable", () => {
const ctx = new BrowserExecutionContext();
- const promise = ctx.init(async () => {
- ctx.set("async", "yes");
- return "ok";
+
+ ctx.init(() => {
+ ctx.set("componentId", "outer");
+
+ expect(() => ctx.init(() => { throw new Error("kaboom"); })).toThrow("kaboom");
+
+ expect(ctx.get<string>("componentId")).toBe("outer");
});
- await expect(promise).resolves.toBe("ok");
- vi.advanceTimersByTime(1000);
- expect(ctx.get("async")).toBeUndefined();
+ expect(ctx.get("componentId")).toBeUndefined();
});
- it("schedules cleanup and rethrows when the synchronous callback throws", () => {
+ it("ends an async scope whose promise rejects", async () => {
const ctx = new BrowserExecutionContext();
- expect(() => ctx.init(() => { throw new Error("kaboom"); })).toThrow("kaboom");
- // The errored context is still cleaned up after the grace period (no throw).
- expect(() => vi.advanceTimersByTime(1000)).not.toThrow();
+ const running = ctx.init(async () => {
+ ctx.set("k", "doomed");
+ throw new Error("kaboom");
+ });
+
+ await expect(running).rejects.toThrow("kaboom");
+ expect(ctx.get("k")).toBeUndefined();
});
- it("reset() empties the stack, leaving a pending cleanup timer a no-op", () => {
+ it("drops every scope on reset()", () => {
const ctx = new BrowserExecutionContext();
- ctx.init(() => "x");
- ctx.reset();
- expect(ctx.get("anything")).toBeUndefined();
- // The cleanup timer fires but the context is already gone (index === -1).
- expect(() => vi.advanceTimersByTime(1000)).not.toThrow();
+ ctx.init(() => {
+ ctx.set("k", 1);
+ ctx.reset();
+ expect(ctx.get("k")).toBeUndefined();
+ });
});
});
diff --git a/apps/standalone/src/lightweight/cls_provider.ts b/apps/standalone/src/lightweight/cls_provider.ts
index 51b66b4154..82a593ec3e 100644
--- a/apps/standalone/src/lightweight/cls_provider.ts
+++ b/apps/standalone/src/lightweight/cls_provider.ts
@@ -1,81 +1,80 @@
import { ExecutionContext } from "@triliumnext/core";
/**
- * Browser execution context implementation.
- *
- * Handles per-request context isolation with support for fire-and-forget async operations
- * using a context stack and grace-period cleanup to allow unawaited promises to complete.
+ * Browser execution context.
+ *
+ * The browser has no `AsyncLocalStorage`, so scopes are tracked on a stack. That model holds
+ * because the worker keeps at most one *asynchronous* scope live at a time: `dbLock` gives an
+ * async route exclusive use of the connection, and a synchronous scope cannot be interleaved at
+ * all. What the stack owes in return is LIFO discipline — a scope ends when its callback does,
+ * and ending it uncovers the one it was opened inside.
*/
export default class BrowserExecutionContext implements ExecutionContext {
- private contextStack: Map<string, any>[] = [];
- private cleanupTimers = new WeakMap<Map<string, any>, ReturnType<typeof setTimeout>>();
- private readonly CLEANUP_GRACE_PERIOD = 1000; // 1 second for fire-and-forget operations
-
- private getCurrentContext(): Map<string, any> {
- if (this.contextStack.length === 0) {
- throw new Error("ExecutionContext not initialized");
- }
- return this.contextStack[this.contextStack.length - 1];
- }
+ private stack: Map<string, any>[] = [];
get<T = any>(key: string): T | undefined {
- if (this.contextStack.length === 0) {
- return undefined;
- }
- return this.contextStack[this.contextStack.length - 1].get(key);
+ return this.current()?.get(key);
}
set(key: string, value: any): void {
- this.getCurrentContext().set(key, value);
+ const current = this.current();
+
+ if (!current) {
+ throw new Error("ExecutionContext not initialized");
+ }
+
+ current.set(key, value);
}
reset(): void {
- this.contextStack = [];
+ this.stack = [];
}
init<T>(callback: () => T): T {
- const context = new Map<string, any>();
- this.contextStack.push(context);
-
- // Cancel any pending cleanup timer for this context
- const existingTimer = this.cleanupTimers.get(context);
- /* v8 ignore next 3 -- @preserve: `context` is freshly created above, so it can never already have a pending cleanup timer; guard kept defensively. */
- if (existingTimer) {
- clearTimeout(existingTimer);
- this.cleanupTimers.delete(context);
- }
+ // A nested scope starts from a copy of the enclosing one, as it does on the server:
+ // `routes/api/llm.ts` opens one while its request is still on the stack and reads the
+ // request's componentId and hoistedNoteId through it. Writes land on the copy.
+ const enclosing = this.current();
+ const scope = enclosing ? new Map(enclosing) : new Map<string, any>();
+ this.stack.push(scope);
+
+ let result: T;
try {
- const result = callback();
-
- // If the result is a Promise
- if (result && typeof result === 'object' && 'then' in result && 'catch' in result) {
- const promise = result as unknown as Promise<any>;
- return promise.finally(() => {
- this.scheduleContextCleanup(context);
- }) as T;
- } else {
- // For synchronous results, schedule delayed cleanup to allow fire-and-forget operations
- this.scheduleContextCleanup(context);
- return result;
- }
+ result = callback();
} catch (error) {
- // Always clean up on error with grace period
- this.scheduleContextCleanup(context);
+ this.end(scope);
throw error;
}
+
+ if (isThenable(result)) {
+ return result.finally(() => this.end(scope)) as T;
+ }
+
+ this.end(scope);
+
+ return result;
}
- private scheduleContextCleanup(context: Map<string, any>): void {
- const timer = setTimeout(() => {
- // Remove from stack if still present
- const index = this.contextStack.indexOf(context);
- if (index !== -1) {
- this.contextStack.splice(index, 1);
- }
- this.cleanupTimers.delete(context);
- }, this.CLEANUP_GRACE_PERIOD);
-
- this.cleanupTimers.set(context, timer);
+ private current(): Map<string, any> | undefined {
+ return this.stack[this.stack.length - 1];
}
+
+ /**
+ * Ends `scope`, which is the top of the stack unless an asynchronous scope opened inside it is
+ * still running. Matched by identity so that one outliving its parent removes the right entry.
+ */
+ private end(scope: Map<string, any>) {
+ const at = this.stack.lastIndexOf(scope);
+
+ if (at !== -1) {
+ this.stack.splice(at, 1);
+ }
+ }
+}
+
+function isThenable(value: unknown): value is Promise<unknown> {
+ const candidate = value as { then?: unknown; finally?: unknown } | null;
+
+ return typeof candidate?.then === "function" && typeof candidate.finally === "function";
}
diff --git a/packages/trilium-core/src/services/image_download.ts b/packages/trilium-core/src/services/image_download.ts
index 6d30de9729..9c401c2e4e 100644
--- a/packages/trilium-core/src/services/image_download.ts
+++ b/packages/trilium-core/src/services/image_download.ts
@@ -140,7 +140,12 @@ async function downloadImage(noteId: string, imageUrl: string) {
const parsedUrl = url.parse(unescapedUrl);
const title = basename(parsedUrl.pathname || "");
- const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, title, true, true);
+ // Given a context of its own, as the link rewrite below is: the download resumes long
+ // after the request that started it has answered, and a write with no context around it
+ // has nowhere to record its entity change.
+ const attachment = cls.getContext().init(
+ () => imageService.saveImageToAttachment(noteId, imageBuffer, title, true, true)
+ );
if (attachment.attachmentId) {
imageUrlToAttachmentIdMapping[imageUrl] = attachment.attachmentId;