Skip to content

Build your personal knowledge base with Trilium Notes

chore(core): replace async-mutex with a shared Mutex

Elian Doran92f4c4b5b9cd
diff --git a/apps/client/src/components/tab_manager.ts b/apps/client/src/components/tab_manager.ts
index 01a73bdf2f..cabb64e575 100644
--- a/apps/client/src/components/tab_manager.ts
+++ b/apps/client/src/components/tab_manager.ts
@@ -1,3 +1,5 @@
+import { Mutex } from "@triliumnext/commons";
+
import Component from "./component.js";
import SpacedUpdate from "../services/spaced_update.js";
import server from "../services/server.js";
@@ -6,7 +8,6 @@ import froca from "../services/froca.js";
import treeService from "../services/tree.js";
import NoteContext from "./note_context.js";
import appContext from "./app_context.js";
-import Mutex from "../utils/mutex.js";
import linkService from "../services/link.js";
import { partitionPinnedFirst } from "../services/tab_pinning.js";
import type { EventData, NoteCommandData } from "./app_context.js";
@@ -581,7 +582,7 @@ export default class TabManager extends Component {
async removeNoteContext(ntxId: string | null): Promise<boolean> {
// removing note context is an async process which can take some time, if users presses CTRL-W quickly, two
// close events could interleave which would then lead to attempting to activate already removed context.
- return await this.mutex.runExclusively(async (): Promise<boolean> => {
+ return await this.mutex.runExclusive(async (): Promise<boolean> => {
let noteContextToRemove;
try {
@@ -902,7 +903,7 @@ export default class TabManager extends Component {
}
async reopenLastTabCommand() {
- const closeLastEmptyTab: NoteContext | undefined = await this.mutex.runExclusively(async () => {
+ const closeLastEmptyTab: NoteContext | undefined = await this.mutex.runExclusive(async () => {
let closeLastEmptyTab
if (this.recentlyClosedTabs.length === 0) {
return closeLastEmptyTab;
diff --git a/apps/client/src/utils/mutex.spec.ts b/apps/client/src/utils/mutex.spec.ts
deleted file mode 100644
index 2fb6028a04..0000000000
--- a/apps/client/src/utils/mutex.spec.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import Mutex from "./mutex";
-
-describe("Mutex", () => {
- it("runExclusively returns the callback's resolved value", async () => {
- const mutex = new Mutex();
- const result = await mutex.runExclusively(async () => 42);
- expect(result).toBe(42);
- });
-
- it("serializes overlapping runExclusively calls in order", async () => {
- const mutex = new Mutex();
- const events: string[] = [];
-
- let releaseFirst: () => void = () => {};
- const allowFirstToFinish = new Promise<void>((resolve) => (releaseFirst = resolve));
-
- let signalFirstStarted: () => void = () => {};
- const firstStarted = new Promise<void>((resolve) => (signalFirstStarted = resolve));
-
- const first = mutex.runExclusively(async () => {
- events.push("first-start");
- signalFirstStarted();
- // Hold the lock until the test allows it to finish.
- await allowFirstToFinish;
- events.push("first-end");
- });
-
- const second = mutex.runExclusively(async () => {
- events.push("second-start");
- events.push("second-end");
- });
-
- // The first has the lock; the second must be waiting behind it.
- await firstStarted;
- expect(events).toEqual(["first-start"]);
-
- releaseFirst();
- await Promise.all([first, second]);
-
- expect(events).toEqual(["first-start", "first-end", "second-start", "second-end"]);
- });
-
- it("releases the lock even when the callback throws", async () => {
- const mutex = new Mutex();
-
- await expect(
- mutex.runExclusively(async () => {
- throw new Error("boom");
- })
- ).rejects.toThrow("boom");
-
- // The mutex must have released, so a subsequent call proceeds normally.
- const result = await mutex.runExclusively(async () => "recovered");
- expect(result).toBe("recovered");
- });
-
- it("lock() resolves to an unlock function that gates the next lock", async () => {
- const mutex = new Mutex();
-
- const unlockFirst = await mutex.lock();
- let secondAcquired = false;
- const secondLock = mutex.lock().then((unlock) => {
- secondAcquired = true;
- return unlock;
- });
-
- await Promise.resolve();
- expect(secondAcquired).toBe(false);
-
- unlockFirst();
- const unlockSecond = await secondLock;
- expect(secondAcquired).toBe(true);
- unlockSecond();
- });
-});
diff --git a/apps/client/src/utils/mutex.ts b/apps/client/src/utils/mutex.ts
deleted file mode 100644
index fb98ce4b60..0000000000
--- a/apps/client/src/utils/mutex.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-export default class Mutex {
- private current: Promise<void>;
-
- constructor() {
- this.current = Promise.resolve();
- }
-
- lock() {
- let resolveFun: () => void;
- const subPromise = new Promise<void>((resolve) => (resolveFun = () => resolve()));
- // Caller gets a promise that resolves when the current outstanding lock resolves
- const newPromise = this.current.then(() => resolveFun);
- // Don't allow the next request until the new promise is done
- this.current = subPromise;
- // Return the new promise
- return newPromise;
- }
-
- async runExclusively<T>(cb: () => Promise<T>) {
- const unlock = await this.lock();
-
- try {
- return await cb();
- } finally {
- unlock();
- }
- }
-}
diff --git a/apps/server/src/services/chunked_upload.ts b/apps/server/src/services/chunked_upload.ts
index c843613e18..6f1bf355db 100644
--- a/apps/server/src/services/chunked_upload.ts
+++ b/apps/server/src/services/chunked_upload.ts
@@ -1,5 +1,5 @@
+import { Mutex } from "@triliumnext/commons";
import { ConflictError, GoneError, type HttpError, NotFoundError, utils as coreUtils, ValidationError } from "@triliumnext/core";
-import { Mutex } from "async-mutex";
import type { Request } from "express";
import { createWriteStream } from "fs";
import fsp from "fs/promises";
diff --git a/packages/commons/src/lib/utils.spec.ts b/packages/commons/src/lib/utils.spec.ts
index ac89ee5ecf..e663d64542 100644
--- a/packages/commons/src/lib/utils.spec.ts
+++ b/packages/commons/src/lib/utils.spec.ts
@@ -1,4 +1,4 @@
-import { deferred, escapeHtml, fnv1a, formatLogMessage } from "./utils.js";
+import { deferred, escapeHtml, fnv1a, formatLogMessage, Mutex } from "./utils.js";
import { describe, expect, it } from "vitest";
describe("#deferred", () => {
@@ -112,3 +112,51 @@ describe("#escapeHtml", () => {
expect(escapeHtml("")).toBe("");
});
});
+
+describe("Mutex", () => {
+ it("returns the callback's value, synchronous or not", async () => {
+ const mutex = new Mutex();
+ expect(await mutex.runExclusive(async () => 42)).toBe(42);
+ expect(await mutex.runExclusive(() => "sync")).toBe("sync");
+ });
+
+ it("runs overlapping callers one after another, in call order", async () => {
+ const mutex = new Mutex();
+ const events: string[] = [];
+ const allowFirstToFinish = deferred<void>();
+ const firstStarted = deferred<void>();
+
+ const first = mutex.runExclusive(async () => {
+ events.push("first-start");
+ firstStarted.resolve();
+ await allowFirstToFinish;
+ events.push("first-end");
+ });
+ const second = mutex.runExclusive(() => {
+ events.push("second");
+ });
+ const third = mutex.runExclusive(() => {
+ events.push("third");
+ });
+
+ await firstStarted;
+ expect(events).toEqual(["first-start"]);
+
+ allowFirstToFinish.resolve();
+ await Promise.all([first, second, third]);
+ expect(events).toEqual(["first-start", "first-end", "second", "third"]);
+ });
+
+ it("releases the lock when a callback throws or rejects", async () => {
+ const mutex = new Mutex();
+
+ await expect(mutex.runExclusive(async () => {
+ throw new Error("rejected");
+ })).rejects.toThrow("rejected");
+ await expect(mutex.runExclusive(() => {
+ throw new Error("thrown");
+ })).rejects.toThrow("thrown");
+
+ expect(await mutex.runExclusive(() => "recovered")).toBe("recovered");
+ });
+});
diff --git a/packages/commons/src/lib/utils.ts b/packages/commons/src/lib/utils.ts
index 4494d55b9d..5e2fb54cff 100644
--- a/packages/commons/src/lib/utils.ts
+++ b/packages/commons/src/lib/utils.ts
@@ -61,6 +61,17 @@ export function deferred<T>(): DeferredPromise<T> {
})();
}
+/** Runs callbacks one at a time, in the order `runExclusive()` was called. */
+export class Mutex {
+ private tail: Promise<unknown> = Promise.resolve();
+
+ runExclusive<T>(callback: () => T | PromiseLike<T>): Promise<T> {
+ const result = this.tail.then(() => callback());
+ this.tail = result.catch(() => undefined);
+ return result;
+ }
+}
+
/**
* Hashes a string with FNV-1a, returning the digest as an unsigned 32-bit number.
*
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.json
index 69e12cad8d..81c138f779 100644
--- a/packages/trilium-core/package.json
+++ b/packages/trilium-core/package.json
@@ -20,7 +20,6 @@
"@triliumnext/share-theme": "workspace:*",
"@triliumnext/turndown-plugin-gfm": "workspace:*",
"ai": "7.0.153",
- "async-mutex": "0.5.0",
"chardet": "2.2.0",
"color": "5.0.3",
"ejs": "7.0.2",
diff --git a/packages/trilium-core/src/services/sync_mutex.ts b/packages/trilium-core/src/services/sync_mutex.ts
index e900117705..135685401e 100644
--- a/packages/trilium-core/src/services/sync_mutex.ts
+++ b/packages/trilium-core/src/services/sync_mutex.ts
@@ -3,17 +3,12 @@
* (like consistency checks) can use this mutex to make sure sync isn't currently running.
*/
-import { Mutex } from "async-mutex";
-const instance = new Mutex();
+import { Mutex } from "@triliumnext/commons";
-async function doExclusively<T>(func: () => T) {
- const releaseMutex = await instance.acquire();
+const instance = new Mutex();
- try {
- return await func();
- } finally {
- releaseMutex();
- }
+function doExclusively<T>(func: () => T | PromiseLike<T>) {
+ return instance.runExclusive(func);
}
export default {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 443ceff1c0..e5bb61e94f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1474,9 +1474,6 @@ importers:
ai:
specifier: 7.0.153
version: 7.0.153([email protected])
- async-mutex:
- specifier: 0.5.0
- version: 0.5.0
chardet:
specifier: 2.2.0
version: 2.2.0
@@ -5819,9 +5816,6 @@ packages:
resolution: {integrity: sha512-Az2ZTpuytrtqENulXwO3GGv1Bztugx6TT37NIo7imr/Qo0gsYiGtSdBa2B6fsXhTpVZDNfu1Qn3pk531e3q+nQ==}
- resolution: {integrity: sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==}
-
resolution: {integrity: sha512-nSVgobk4rv61R9PUSDtYt7mPVB2olxNR5RWJcAsH676/ef11bUZwvu7+RGYrYauVdDPcO519v68wRhXQtxsV9w==}
@@ -17285,10 +17279,6 @@ snapshots:
- dependencies:
- tslib: 2.8.1
-
optional: true