Skip to content

Build your personal knowledge base with Trilium Notes

fix(server): options crashing due to bad async handling

Elian Doran66f67c1ae6a8
diff --git a/apps/server/src/routes/api/options.spec.ts b/apps/server/src/routes/api/options.spec.ts
new file mode 100644
index 0000000000..6be2998b46
--- /dev/null
+++ b/apps/server/src/routes/api/options.spec.ts
@@ -0,0 +1,76 @@
+import { getSql, options as optionService } from "@triliumnext/core";
+import type { Application } from "express";
+import i18next from "i18next";
+import supertest from "supertest";
+import { beforeAll, describe, expect, it } from "vitest";
+
+let app: Application;
+let agent: ReturnType<typeof supertest.agent>;
+let csrfToken: string;
+
+// optionService.getOption() reads from becca's in-memory cache, which is mutated
+// *before* the SQL write runs. A rolled-back write therefore leaves becca stale,
+// so the rollback test asserts against the DB row directly.
+function readOptionFromDb(name: string): string | null {
+ const row = getSql().getRowOrNull<{ value: string }>(
+ "SELECT value FROM options WHERE name = ?",
+ [name]
+ );
+ return row?.value ?? null;
+}
+
+function putOptions(body: Record<string, string>) {
+ return agent
+ .put("/api/options")
+ .set("x-csrf-token", csrfToken)
+ .send(body);
+}
+
+describe("Options API", () => {
+ beforeAll(async () => {
+ const buildApp = (await import("../../app.js")).default;
+ app = await buildApp();
+ agent = supertest.agent(app);
+
+ await agent.post("/login").send({ password: "demo1234" }).expect(302);
+
+ const boot = await agent.get("/bootstrap").expect(200);
+ csrfToken = boot.body.csrfToken;
+ expect(csrfToken).toBeTruthy();
+ });
+
+ it("updates a batch of allowed options", async () => {
+ await putOptions({ mainFontSize: "115", treeFontSize: "85" }).expect(204);
+
+ expect(readOptionFromDb("mainFontSize")).toBe("115");
+ expect(readOptionFromDb("treeFontSize")).toBe("85");
+ });
+
+ it("rolls back the entire batch when one option is not allowed", async () => {
+ // Establish a known baseline before the failing batch.
+ await putOptions({ mainFontSize: "100" }).expect(204);
+
+ // The allowed option is iterated first, so without an outer transaction
+ // it would be committed before the disallowed key triggers the throw.
+ await putOptions({ mainFontSize: "200", notAnAllowedOption: "x" }).expect(500);
+
+ expect(readOptionFromDb("mainFontSize")).toBe("100");
+ });
+
+ it("waits for the locale change to fully apply before returning", async () => {
+ await putOptions({ locale: "en" }).expect(204);
+ expect(i18next.language).toBe("en");
+
+ await putOptions({ locale: "fr" }).expect(204);
+ expect(i18next.language).toBe("fr");
+ });
+
+ it("updates a single option via the :name/:value route", async () => {
+ await agent
+ .put("/api/options/mainFontSize/123")
+ .set("x-csrf-token", csrfToken)
+ .expect(204);
+
+ expect(optionService.getOption("mainFontSize")).toBe("123");
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.ts
index 2aef6e4e0a..ed3b4b07c3 100644
--- a/packages/trilium-core/src/routes/api/options.ts
+++ b/packages/trilium-core/src/routes/api/options.ts
@@ -8,6 +8,7 @@ import { changeLanguage } from "../../services/i18n.js";
import { getLog } from "../../services/log.js";
import optionService from "../../services/options.js";
import searchService from "../../services/search/services/search.js";
+import { getSql } from "../../services/sql/index.js";
import { ValidationError } from "../../errors.js";
interface UserTheme {
@@ -155,13 +156,19 @@ async function updateOption(req: Request<{ name: string; value: string }>) {
}
async function updateOptions(req: Request) {
- for (const optionName in req.body) {
- if (!update(optionName, req.body[optionName])) {
- // this should be improved
- // it should return 400 instead of current 500, but at least it now rollbacks transaction
- throw new Error(`Option '${optionName}' is not allowed to be changed`);
+ // The route is registered with asyncApiRoute (no automatic transaction wrapping) because the
+ // synchronous sql.transactional() cannot await promises — the transaction would commit at the
+ // first await and changeLanguage() would run outside it. Wrap the option-setting loop manually
+ // so a failure mid-batch still rolls back earlier options in the same request.
+ getSql().transactional(() => {
+ for (const optionName in req.body) {
+ if (!update(optionName, req.body[optionName])) {
+ // this should be improved
+ // it should return 400 instead of current 500, but at least it now rollbacks transaction
+ throw new Error(`Option '${optionName}' is not allowed to be changed`);
+ }
}
- }
+ });
if ("locale" in req.body) {
await changeLanguage(req.body["locale"]);
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 02bcc3fb92..18acaa9671 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -61,8 +61,8 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
apiRoute(GET, "/api/options", optionsApiRoute.getOptions);
// FIXME: possibly change to sending value in the body to avoid host of HTTP server issues with slashes
- apiRoute(PUT, "/api/options/:name/:value", optionsApiRoute.updateOption);
- apiRoute(PUT, "/api/options", optionsApiRoute.updateOptions);
+ asyncApiRoute(PUT, "/api/options/:name/:value", optionsApiRoute.updateOption);
+ asyncApiRoute(PUT, "/api/options", optionsApiRoute.updateOptions);
apiRoute(GET, "/api/options/user-themes", optionsApiRoute.getUserThemes);
apiRoute(PST, "/api/notes/:noteId/convert-to-attachment", notesApiRoute.convertNoteToAttachment);