Skip to content

Build your personal knowledge base with Trilium Notes

core/setup/backup data: fix an issue

Adorian Doran090296d5fae5
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 0db575877a..43c1af6043 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -100,6 +100,8 @@ function register(app: express.Application) {
routes.buildSharedApiRoutes({
route,
asyncRoute,
+ // The server's asyncRoute never opened a transaction to begin with.
+ asyncRouteWithoutTransaction: asyncRoute,
apiRoute,
asyncApiRoute,
apiResultHandler,
diff --git a/apps/standalone/src/lightweight/browser_routes.spec.ts b/apps/standalone/src/lightweight/browser_routes.spec.ts
index bc1772c586..196d3ff9d5 100644
--- a/apps/standalone/src/lightweight/browser_routes.spec.ts
+++ b/apps/standalone/src/lightweight/browser_routes.spec.ts
@@ -1,4 +1,4 @@
-import { routes, sql_init } from "@triliumnext/core";
+import { getSql, routes, sql_init } from "@triliumnext/core";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BrowserRouter } from "./browser_router.js";
@@ -68,7 +68,7 @@ describe("route wrapper branches (via controlled handlers)", () => {
function buildRouter(): BrowserRouter {
vi.spyOn(routes, "buildSharedApiRoutes").mockImplementation((received: RouteCtx) => {
ctx = received;
- const { route, asyncRoute, apiRoute, asyncApiRoute, apiResultHandler } = received;
+ const { route, asyncRoute, asyncRouteWithoutTransaction, apiRoute, asyncApiRoute, apiResultHandler } = received;
apiRoute("get", "/t/api", (req: { originalUrl: string }) => ({ url: req.originalUrl }));
asyncApiRoute("get", "/t/asyncapi", () => ({ ok: true }));
@@ -90,6 +90,7 @@ describe("route wrapper branches (via controlled handlers)", () => {
asyncRoute("get", "/t/async-obj", [], async () => ({ z: 9 }), apiResultHandler);
asyncRoute("get", "/t/async-res", [], async (_req: unknown, res: MockRes) => { res.send("async-body"); });
asyncRoute("get", "/t/async-noresult", [], async () => ({ done: true }));
+ asyncRouteWithoutTransaction("get", "/t/async-no-tx", [], async () => ({ bare: true }), apiResultHandler);
});
return createConfiguredRouter();
}
@@ -112,6 +113,22 @@ describe("route wrapper branches (via controlled handlers)", () => {
expect(parseJson((await router.dispatch("GET", "http://localhost/t/asyncapi")).body)).toEqual({ ok: true });
});
+ it("leaves the database alone for a route that says it wants no transaction", async () => {
+ // The setup screen's erase closes the database and opens another one. A transaction opened
+ // around it belongs to a connection that is gone by the time it would be committed, and
+ // SQLite answers "cannot rollback - no transaction is active".
+ const router = buildRouter();
+ const transactional = vi.spyOn(getSql(), "transactionalAsync");
+
+ expect(parseJson((await router.dispatch("GET", "http://localhost/t/async-no-tx")).body))
+ .toEqual({ bare: true });
+ expect(transactional).not.toHaveBeenCalled();
+
+ // The ordinary async route is unchanged: it still gets one.
+ await router.dispatch("GET", "http://localhost/t/async-obj");
+ expect(transactional).toHaveBeenCalled();
+ });
+
it("formats route() results through apiResultHandler (object, tuple, undefined)", async () => {
const router = buildRouter();
expect(parseJson((await router.dispatch("GET", "http://localhost/t/r-obj")).body)).toEqual({ a: 1 });
diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.ts
index 73ab64c095..73c2dfbbb1 100644
--- a/apps/standalone/src/lightweight/browser_routes.ts
+++ b/apps/standalone/src/lightweight/browser_routes.ts
@@ -130,14 +130,15 @@ function createRoute(router: BrowserRouter) {
* transactional() wrapper, which would commit an empty transaction immediately when
* passed an async callback.
*/
-function createAsyncRoute(router: BrowserRouter) {
+function createAsyncRoute(router: BrowserRouter, { transactional = true } = {}) {
return (method: HttpMethod, path: string, _middleware: any[], handler: (req: any, res: any) => Promise<unknown>, resultHandler?: ((req: any, res: any, result: unknown) => unknown) | null) => {
router.register(method, path, (req: BrowserRequest) => {
return getContext().init(async () => {
setContextFromHeaders(req);
const expressLikeReq = toExpressLikeReq(req);
const mockRes = createMockExpressResponse();
- const result = await getSql().transactionalAsync(() => handler(expressLikeReq, mockRes));
+ const run = () => handler(expressLikeReq, mockRes);
+ const result = transactional ? await getSql().transactionalAsync(run) : await run();
// If the handler used the mock response (e.g. image routes that call res.send()),
// return it as a raw response so BrowserRouter doesn't JSON-serialize it.
@@ -276,6 +277,7 @@ export function registerRoutes(router: BrowserRouter): void {
routes.buildSharedApiRoutes({
route: createRoute(router),
asyncRoute: createAsyncRoute(router),
+ asyncRouteWithoutTransaction: createAsyncRoute(router, { transactional: false }),
apiRoute,
asyncApiRoute: createApiRoute(router, false),
apiResultHandler,
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 67d55a040f..60c83a475f 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -45,6 +45,15 @@ const GET = "get",
interface SharedApiRoutesContext {
route: any;
asyncRoute: any;
+ /**
+ * Like `asyncRoute`, minus the transaction, on every platform.
+ *
+ * `asyncRoute` is transactional in the browser and not on the server, which is fine for handlers
+ * that only read or write rows. It is not fine for the handful that close the database and open
+ * another one: the transaction they started belongs to a connection that is gone by the time it
+ * would be committed, and SQLite says so.
+ */
+ asyncRouteWithoutTransaction: any;
apiRoute: any;
asyncApiRoute: any;
checkApiAuth: any;
@@ -58,7 +67,7 @@ interface SharedApiRoutesContext {
csrfMiddleware: any;
}
-export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoute, checkApiAuth, apiResultHandler, checkApiAuthOrElectron, checkAppNotInitialized, checkCredentials, loginRateLimiter, uploadMiddlewareWithErrorHandling, importMiddlewareWithErrorHandling, csrfMiddleware }: SharedApiRoutesContext) {
+export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTransaction, apiRoute, asyncApiRoute, checkApiAuth, apiResultHandler, checkApiAuthOrElectron, checkAppNotInitialized, checkCredentials, loginRateLimiter, uploadMiddlewareWithErrorHandling, importMiddlewareWithErrorHandling, csrfMiddleware }: SharedApiRoutesContext) {
apiRoute(GET, '/api/tree', treeApiRoute.getTree);
apiRoute(PST, '/api/tree/load', treeApiRoute.load);
@@ -157,10 +166,12 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
// What becomes of the database the wizard was booted away from. Guarded like the rest of setup,
// and refused again inside on an instance that has no such database. Not transactional: the
// backup runs for minutes, and keeping the database reopens it.
- asyncRoute(PST, "/api/setup/existing/backup", [checkAppNotInitialized], setupApiRoute.backUpExisting, apiResultHandler);
- asyncRoute(GET, "/api/setup/existing/status", [checkAppNotInitialized], setupApiRoute.existingBackupStatus, apiResultHandler);
- asyncRoute(PST, "/api/setup/existing/delete", [checkAppNotInitialized], setupApiRoute.deleteExisting, apiResultHandler);
- asyncRoute(PST, "/api/setup/existing/keep", [checkAppNotInitialized], setupApiRoute.keepExisting, apiResultHandler);
+ // Without a transaction, on every platform: the backup runs for minutes with the database in
+ // use, and erasing or keeping it closes the connection any transaction would belong to.
+ asyncRouteWithoutTransaction(PST, "/api/setup/existing/backup", [checkAppNotInitialized], setupApiRoute.backUpExisting, apiResultHandler);
+ asyncRouteWithoutTransaction(GET, "/api/setup/existing/status", [checkAppNotInitialized], setupApiRoute.existingBackupStatus, apiResultHandler);
+ asyncRouteWithoutTransaction(PST, "/api/setup/existing/delete", [checkAppNotInitialized], setupApiRoute.deleteExisting, apiResultHandler);
+ asyncRouteWithoutTransaction(PST, "/api/setup/existing/keep", [checkAppNotInitialized], setupApiRoute.keepExisting, apiResultHandler);
asyncApiRoute(PST, "/api/sync/test", syncApiRoute.testSync);
asyncApiRoute(PST, "/api/sync/now", syncApiRoute.syncNow);
diff --git a/packages/trilium-core/src/test/api_tester.ts b/packages/trilium-core/src/test/api_tester.ts
index b68b7bf289..d6a0345dac 100644
--- a/packages/trilium-core/src/test/api_tester.ts
+++ b/packages/trilium-core/src/test/api_tester.ts
@@ -264,6 +264,7 @@ export class CoreApiTester {
routes.buildSharedApiRoutes({
route: buildRoute(true),
asyncRoute: buildRoute(false),
+ asyncRouteWithoutTransaction: buildRoute(false),
apiRoute,
asyncApiRoute,
apiResultHandler,