Skip to content

Build your personal knowledge base with Trilium Notes

test(cls): cover the execution context and its emitter binding

Elian Doran22a3b4a43816
diff --git a/apps/server/spec/etapi/cls-context.spec.ts b/apps/server/spec/etapi/cls-context.spec.ts
new file mode 100644
index 0000000000..93c39d7596
--- /dev/null
+++ b/apps/server/spec/etapi/cls-context.spec.ts
@@ -0,0 +1,52 @@
+import type { Application } from "express";
+import supertest from "supertest";
+import { beforeAll, describe, expect, it } from "vitest";
+
+import buildApp from "../../src/app.js";
+import sql from "../../src/services/sql.js";
+import { createNote, login } from "./utils.js";
+
+let app: Application;
+let token: string;
+
+/**
+ * ETAPI opens a CLS context per request and stamps it with the "etapi" componentId. That stamp
+ * lands on every entity change the request produces, which is how the frontend update message
+ * tells an external write apart from one the client made itself.
+ */
+describe("etapi/cls-context", () => {
+ beforeAll(async () => {
+ app = await buildApp();
+ token = await login(app);
+ });
+
+ it("stamps every entity change of an ETAPI write with the etapi componentId", async () => {
+ const noteId = await createNote(app, token);
+
+ const componentIds = sql.getColumn<string>(
+ `SELECT DISTINCT componentId FROM entity_changes
+ WHERE (entityName = 'notes' AND entityId = ?)
+ OR (entityName = 'branches' AND entityId LIKE ?)`,
+ [noteId, `%${noteId}`]
+ );
+
+ expect(componentIds).toEqual(["etapi"]);
+ });
+
+ it("does not carry a context over from a request that failed", async () => {
+ const failed = await supertest(app)
+ .post("/etapi/create-note")
+ .auth("etapi", token, { type: "basic" })
+ .send({ parentNoteId: "root", title: "Bad", type: "text" });
+ expect(failed.status).toBeGreaterThanOrEqual(400);
+
+ // The next write still gets its own context, rather than the failed one or none at all.
+ const noteId = await createNote(app, token);
+ const componentId = sql.getValue<string>(
+ "SELECT componentId FROM entity_changes WHERE entityName = 'notes' AND entityId = ?",
+ [noteId]
+ );
+
+ expect(componentId).toBe("etapi");
+ });
+});
diff --git a/apps/server/src/cls_provider.spec.ts b/apps/server/src/cls_provider.spec.ts
index bd94bd6495..51725e6688 100644
--- a/apps/server/src/cls_provider.spec.ts
+++ b/apps/server/src/cls_provider.spec.ts
@@ -1,28 +1,175 @@
import clsHooked from "cls-hooked";
+import { EventEmitter } from "events";
import { afterEach, describe, expect, it, vi } from "vitest";
-import ClsHookedExecutionContext from "./cls_provider.js";
+import ClsHookedExecutionContext, { namespace } from "./cls_provider.js";
afterEach(() => vi.restoreAllMocks());
+/**
+ * The contract every `ExecutionContext` on the Node side has to satisfy. `route_api`, `etapi_utils`
+ * and `custom` all rely on it, and `putEntityChange()` writes through it on every entity save, so a
+ * gap here surfaces as lost entity changes rather than as a thrown error.
+ */
describe("ClsHookedExecutionContext", () => {
- it("stores and retrieves values within an init() context", () => {
- const ctx = new ClsHookedExecutionContext();
- const result = ctx.init(() => {
- ctx.set("alpha", 42);
- return ctx.get<number>("alpha");
+ const ctx = new ClsHookedExecutionContext();
+
+ // Binding an emitter is not part of ExecutionContext — the three route modules reach for the
+ // namespace directly. Routed through one helper so the tests below describe behaviour only.
+ const bindEmitter = (emitter: EventEmitter) => namespace.bindEmitter(emitter);
+
+ describe("value storage", () => {
+ it("round-trips values inside init() and returns the callback's value", () => {
+ const returned = ctx.init(() => {
+ ctx.set("alpha", 42);
+ return ctx.get<number>("alpha");
+ });
+
+ expect(returned).toBe(42);
+ });
+
+ it("returns undefined from get() outside a context, and throws from set()", () => {
+ expect(ctx.get("never-set")).toBeUndefined();
+ expect(() => ctx.set("alpha", 1)).toThrow(/No context available/);
+ });
+
+ it("isolates sibling scopes", () => {
+ ctx.init(() => ctx.set("shared", "first"));
+
+ expect(ctx.init(() => ctx.get<string>("shared"))).toBeUndefined();
+ });
+
+ // `llm.ts` opens a nested init() while the request that started it is still on the stack,
+ // and relies on inheriting its componentId and hoistedNoteId — an empty child context would
+ // stamp the entity changes its tool calls produce with "NA" instead of the request's id.
+ it("inherits the enclosing context, and shadows rather than overwrites it", () => {
+ ctx.init(() => {
+ ctx.set("componentId", "request");
+ ctx.set("hoistedNoteId", "noteABC");
+
+ const inner = ctx.init(() => {
+ expect(ctx.get<string>("componentId")).toBe("request");
+ ctx.set("componentId", "nested");
+ return ctx.get<string>("componentId");
+ });
+
+ expect(inner).toBe("nested");
+ expect(ctx.get<string>("componentId")).toBe("request");
+ expect(ctx.get<string>("hoistedNoteId")).toBe("noteABC");
+ });
+ });
+
+ it("propagates a throw out of init()", () => {
+ expect(() => ctx.init(() => { throw new Error("kaboom"); })).toThrow("kaboom");
+ expect(ctx.get("shared")).toBeUndefined();
+ });
+ });
+
+ describe("async propagation", () => {
+ it("keeps the context across await, timers, nextTick and promise chains", async () => {
+ const seen: Record<string, string | undefined> = {};
+
+ await ctx.init(async () => {
+ ctx.set("id", "X");
+
+ await Promise.resolve();
+ seen.afterAwait = ctx.get<string>("id");
+
+ await new Promise<void>((resolve) => setTimeout(() => {
+ seen.inTimer = ctx.get<string>("id");
+ resolve();
+ }, 1));
+
+ await new Promise<void>((resolve) => process.nextTick(() => {
+ seen.inNextTick = ctx.get<string>("id");
+ resolve();
+ }));
+
+ seen.inChain = await Promise.resolve().then(() => ctx.get<string>("id"));
+ });
+
+ expect(seen).toEqual({ afterAwait: "X", inTimer: "X", inNextTick: "X", inChain: "X" });
+ });
+
+ it("keeps concurrent contexts separate while they interleave", async () => {
+ const request = (id: string, delayMs: number) => ctx.init(async () => {
+ ctx.set("componentId", id);
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+ return ctx.get<string>("componentId");
+ });
+
+ // The slow one starts first and finishes last, so the two overlap.
+ const seen = await Promise.all([request("slow", 20), request("fast", 1)]);
+
+ expect(seen).toEqual(["slow", "fast"]);
+ expect(ctx.get("componentId")).toBeUndefined();
});
- expect(result).toBe(42);
});
- it("returns undefined for keys outside any active context", () => {
- const ctx = new ClsHookedExecutionContext();
- expect(ctx.get("never-set")).toBeUndefined();
+ describe("bindEmitter", () => {
+ it("runs a listener in its add-time context, even when emitted from outside", async () => {
+ const emitter = new EventEmitter();
+ bindEmitter(emitter);
+ let seen: string | undefined;
+
+ ctx.init(() => {
+ ctx.set("componentId", "handler");
+ emitter.on("close", () => { seen = ctx.get<string>("componentId"); });
+ });
+
+ // Emit from a later macrotask, so nothing is active — as when a client aborts a request
+ // long after the route handler returned.
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(ctx.get("componentId")).toBeUndefined();
+
+ emitter.emit("close");
+
+ expect(seen).toBe("handler");
+ });
+
+ it("gives a listener added outside any context a fresh one, so set() works", () => {
+ const emitter = new EventEmitter();
+ bindEmitter(emitter);
+ const seen: Array<string | undefined> = [];
+
+ emitter.on("close", () => {
+ seen.push(ctx.get<string>("mark"));
+ ctx.set("mark", "written");
+ });
+
+ // Each emit gets its own context: the second must not see the first one's write.
+ expect(() => { emitter.emit("close"); emitter.emit("close"); }).not.toThrow();
+ expect(seen).toEqual([undefined, undefined]);
+ });
+
+ it("leaves the emitter's own mechanics untouched", () => {
+ const emitter = new EventEmitter();
+ bindEmitter(emitter);
+ let thisArg: unknown;
+ function listener(this: unknown) { thisArg = this; }
+
+ emitter.on("close", listener);
+ expect(emitter.listenerCount("close")).toBe(1);
+ expect(emitter.listeners("close")).toContain(listener);
+
+ emitter.emit("close");
+ expect(thisArg).toBe(emitter);
+
+ emitter.off("close", listener);
+ expect(emitter.listenerCount("close")).toBe(0);
+
+ let onceCount = 0;
+ emitter.once("finish", () => { onceCount += 1; });
+ emitter.emit("finish");
+ emitter.emit("finish");
+ expect(onceCount).toBe(1);
+ expect(emitter.listenerCount("finish")).toBe(0);
+ });
});
- it("delegates reset() to cls-hooked", () => {
+ it("delegates reset() to the underlying implementation", () => {
const resetSpy = vi.spyOn(clsHooked, "reset").mockImplementation(() => {});
- new ClsHookedExecutionContext().reset();
+ ctx.reset();
expect(resetSpy).toHaveBeenCalled();
});
});
diff --git a/apps/server/src/routes/custom.spec.ts b/apps/server/src/routes/custom.spec.ts
index 61da40bac5..757f067024 100644
--- a/apps/server/src/routes/custom.spec.ts
+++ b/apps/server/src/routes/custom.spec.ts
@@ -1,12 +1,38 @@
-import { cls, getConfig, note_service as noteService } from "@triliumnext/core";
+import { becca, cls, getConfig, note_service as noteService } from "@triliumnext/core";
import type { Application } from "express";
+import type { AddressInfo } from "net";
import supertest from "supertest";
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import config from "../services/config.js";
+import sql from "../services/sql.js";
let app: Application;
+/** What a handler script reports back, via a global the script and the spec share. */
+interface ScriptProbe {
+ noteId?: string;
+ error?: string;
+}
+
+function readProbe(key: string): ScriptProbe {
+ return (globalThis as unknown as Record<string, ScriptProbe | undefined>)[key] ?? {};
+}
+
+/** A handler script that writes a note from a `res` listener and reports the id it created. */
+function listenerHandlerScript(probeName: string, title: string, respond: string) {
+ return `
+const probe = globalThis.${probeName} = {};
+api.res.on("close", () => {
+ try {
+ probe.noteId = api.createTextNote(api.currentNote.noteId, "${title}", "x").note.noteId;
+ } catch (e) {
+ probe.error = e.message;
+ }
+});
+${respond}`;
+}
+
describe("Custom request/resource handlers", () => {
// Custom request handlers run backend scripts, gated by the backendScriptingEnabled toggle at
// two layers: the /custom route checks the server config, while execution (executeBundle) checks
@@ -51,6 +77,39 @@ describe("Custom request/resource handlers", () => {
}).note;
resource.setLabel("customResourceProvider", "resource");
+ // `api.res` is a plain Express response and the User Guide points users at Express's
+ // own documentation, so a handler registering listeners on it is supported surface.
+ // These two write a note from the listener, which needs the request's CLS context:
+ // putEntityChange() writes the new entity change id into it.
+ const onClose = noteService.createNewNote({
+ parentNoteId: "root",
+ title: "Close listener handler",
+ type: "code",
+ mime: "application/javascript;env=backend",
+ content: listenerHandlerScript(
+ "__clsCloseProbe",
+ "from-close",
+ `api.res.status(200).send("closing");`
+ )
+ }).note;
+ onClose.setLabel("customRequestHandler", "on-close");
+
+ // Same, but the response is left open so the listener fires from the client's abort —
+ // an emit that originates outside the handler's async context entirely.
+ const onAbort = noteService.createNewNote({
+ parentNoteId: "root",
+ title: "Abort listener handler",
+ type: "code",
+ mime: "application/javascript;env=backend",
+ content: listenerHandlerScript(
+ "__clsAbortProbe",
+ "from-abort",
+ `api.res.writeHead(200, { "Content-Type": "text/plain" });
+api.res.write("streaming");`
+ )
+ }).note;
+ onAbort.setLabel("customRequestHandler", "abortable");
+
// Empty value → skipped; invalid regex → caught and skipped. Both are
// exercised by the "no handler matches" request below.
noteService.createNewNote({ parentNoteId: "root", title: "Empty handler", type: "text", content: "x" })
@@ -111,4 +170,52 @@ describe("Custom request/resource handlers", () => {
config.Security.backendScriptingEnabled = true;
}
});
+ // A handler script that keeps working after it has responded relies on the response emitter
+ // carrying the request's CLS context: without it the write below has nowhere to record its
+ // entity change, so it either throws or is silently dropped from the sync queue.
+ it("runs a handler's res listener in the request's context after responding", async () => {
+ const res = await supertest(app).get("/custom/on-close").expect(200);
+ expect(res.text).toBe("closing");
+
+ await vi.waitFor(() => {
+ const probe = readProbe("__clsCloseProbe");
+ expect(probe.noteId ?? probe.error).toBeDefined();
+ });
+
+ const probe = readProbe("__clsCloseProbe");
+ expect(probe.error).toBeUndefined();
+ const noteId = probe.noteId ?? "";
+ expect(becca.getNote(noteId)?.title).toBe("from-close");
+ const changeCount = sql.getValue<number>(
+ "SELECT COUNT(1) FROM entity_changes WHERE entityId = ?", [noteId]
+ );
+ expect(changeCount).toBeGreaterThan(0);
+ });
+
+ it("runs a handler's res listener in context when the client aborts", async () => {
+ const server = app.listen(0);
+
+ try {
+ const { port } = server.address() as AddressInfo;
+ const controller = new AbortController();
+ const response = await fetch(`http://127.0.0.1:${port}/custom/abortable`, {
+ signal: controller.signal
+ });
+ expect(response.status).toBe(200);
+
+ controller.abort();
+
+ await vi.waitFor(() => {
+ const probe = readProbe("__clsAbortProbe");
+ expect(probe.noteId ?? probe.error).toBeDefined();
+ });
+
+ const probe = readProbe("__clsAbortProbe");
+ expect(probe.error).toBeUndefined();
+ const noteId = probe.noteId ?? "";
+ expect(becca.getNote(noteId)?.title).toBe("from-abort");
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ });
});
diff --git a/apps/server/src/routes/route_api.spec.ts b/apps/server/src/routes/route_api.spec.ts
index b089aa06e5..5da90dc6d3 100644
--- a/apps/server/src/routes/route_api.spec.ts
+++ b/apps/server/src/routes/route_api.spec.ts
@@ -1,9 +1,17 @@
+import { cls } from "@triliumnext/core";
import express from "express";
import { existsSync } from "fs";
import request from "supertest";
-import { describe, expect, it } from "vitest";
+import { beforeAll, describe, expect, it, vi } from "vitest";
-import { importMiddlewareWithErrorHandling, uploadMiddlewareWithErrorHandling } from "./route_api.js";
+import {
+ apiResultHandler,
+ asyncRoute,
+ importMiddlewareWithErrorHandling,
+ route,
+ router,
+ uploadMiddlewareWithErrorHandling
+} from "./route_api.js";
/** Minimal app mounting only the import middleware + a handler that reports what it received. */
function buildApp() {
@@ -132,3 +140,90 @@ describe("uploadMiddlewareWithErrorHandling (in-memory)", () => {
expect(res.body.hasFile).toBe(false);
});
});
+
+/**
+ * `internalRoute` opens the CLS context every API handler runs in and seeds it from the
+ * `trilium-*` request headers. Entity changes are collected against that context, so losing it
+ * mid-request means writes are attributed to no component rather than failing loudly.
+ */
+describe("internalRoute CLS wiring", () => {
+ const closeProbe: { componentId?: string; wrote?: string; error?: string } = {};
+ let app: express.Application;
+
+ beforeAll(() => {
+ route("get", "/cls/echo", [], () => ({
+ componentId: cls.getComponentId(),
+ hoistedNoteId: cls.getHoistedNoteId(),
+ localNowDateTime: cls.get<string>("localNowDateTime")
+ }), apiResultHandler);
+
+ asyncRoute("get", "/cls/async", [], async (req) => {
+ await new Promise((resolve) => setTimeout(resolve, Number(req.query.delay ?? 0)));
+ return { componentId: cls.getComponentId() };
+ }, apiResultHandler);
+
+ asyncRoute("get", "/cls/close-listener", [], (_req, res) => {
+ res.on("close", () => {
+ try {
+ closeProbe.componentId = cls.getComponentId();
+ cls.set("probe", "written");
+ closeProbe.wrote = cls.get<string>("probe");
+ } catch (e: unknown) {
+ closeProbe.error = e instanceof Error ? e.message : String(e);
+ }
+ });
+ return { ok: true };
+ }, apiResultHandler);
+
+ app = express();
+ app.use(router);
+ });
+
+ it("seeds the context from the trilium-* headers", async () => {
+ const res = await request(app)
+ .get("/cls/echo")
+ .set("trilium-component-id", "comp-1")
+ .set("trilium-hoisted-note-id", "noteABC")
+ .set("trilium-local-now-datetime", "2026-01-01 10:00:00.000+0100")
+ .expect(200);
+
+ expect(res.body).toEqual({
+ componentId: "comp-1",
+ hoistedNoteId: "noteABC",
+ localNowDateTime: "2026-01-01 10:00:00.000+0100"
+ });
+ });
+
+ it("defaults hoistedNoteId to root when the header is absent", async () => {
+ const res = await request(app).get("/cls/echo").expect(200);
+
+ expect(res.body.hoistedNoteId).toBe("root");
+ expect(res.body.componentId).toBeUndefined();
+ });
+
+ it("keeps each request's context across an await, including while they overlap", async () => {
+ const call = (componentId: string, delay: number) => request(app)
+ .get(`/cls/async?delay=${delay}`)
+ .set("trilium-component-id", componentId)
+ .expect(200);
+
+ // The slow request starts first and finishes last, so the two are in flight together.
+ const [slow, fast] = await Promise.all([call("slow", 30), call("fast", 1)]);
+
+ expect(slow.body.componentId).toBe("slow");
+ expect(fast.body.componentId).toBe("fast");
+ });
+
+ it("runs a res close listener inside the request's context", async () => {
+ await request(app)
+ .get("/cls/close-listener")
+ .set("trilium-component-id", "comp-close")
+ .expect(200);
+
+ await vi.waitFor(() => expect(closeProbe.componentId ?? closeProbe.error).toBeDefined());
+
+ expect(closeProbe.error).toBeUndefined();
+ expect(closeProbe.componentId).toBe("comp-close");
+ expect(closeProbe.wrote).toBe("written");
+ });
+});
diff --git a/apps/standalone/src/lightweight/cls_provider.spec.ts b/apps/standalone/src/lightweight/cls_provider.spec.ts
index f85e602022..aa9f1d8ee7 100644
--- a/apps/standalone/src/lightweight/cls_provider.spec.ts
+++ b/apps/standalone/src/lightweight/cls_provider.spec.ts
@@ -38,6 +38,46 @@ describe("BrowserExecutionContext", () => {
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 cls-hooked 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: cls-hooked 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");
+ });
+ });
+
+ it("lets overlapping scopes read each other's values", async () => {
+ vi.useRealTimers();
+ const ctx = new BrowserExecutionContext();
+
+ const request = (componentId: string, delayMs: number) => ctx.init(async () => {
+ ctx.set("componentId", componentId);
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+ 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"]);
+ });
+ });
+
it("cleans up after an async init() resolves", async () => {
const ctx = new BrowserExecutionContext();
const promise = ctx.init(async () => {
diff --git a/packages/trilium-core/src/services/context.spec.ts b/packages/trilium-core/src/services/context.spec.ts
index 446ec5be35..38963148b3 100644
--- a/packages/trilium-core/src/services/context.spec.ts
+++ b/packages/trilium-core/src/services/context.spec.ts
@@ -21,10 +21,11 @@ import {
/**
* The real `ExecutionContext` is installed by `initializeCore` (run once in the
- * server spec `setup.ts`). It is backed by `cls-hooked`: each `init()` runs the
- * callback in a fresh namespace store, so state written inside one `init()`
- * block is isolated from other blocks — which keeps these tests independent
- * without needing `becca.reset()` or DB access.
+ * server spec `setup.ts`). Sibling `init()` scopes are isolated from one another
+ * on both runtimes, which keeps these tests independent without needing
+ * `becca.reset()` or DB access. Nesting is where the two implementations differ,
+ * so it is covered per runtime in `apps/server/src/cls_provider.spec.ts` and
+ * `apps/standalone/src/lightweight/cls_provider.spec.ts`, not here.
*/
function makeEntityChange(id: string): EntityChange {