From fc8ccd80fdd5b9fb7acb8cd0809a8a56acde9b1b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 25 Oct 2026 22:58:59 -0400 Subject: [PATCH] chore: Replace redlock with a single-node Redis lock (#14212) * chore: Replace redlock with a single-node Redis lock * fix: Handle lost SET replies, late replies and stalled extensions in MutexLock --- package.json | 1 - server/queues/tasks/ValidateSSOAccessTask.ts | 4 +- server/utils/MutexLock.test.ts | 269 ++++++++++++++ server/utils/MutexLock.ts | 365 +++++++++++++++---- server/utils/__mocks__/MutexLock.ts | 20 +- yarn.lock | 17 - 6 files changed, 570 insertions(+), 106 deletions(-) create mode 100644 server/utils/MutexLock.test.ts diff --git a/package.json b/package.json index 05f380c6fc..13ded3529b 100644 --- a/package.json +++ b/package.json @@ -231,7 +231,6 @@ "react-use-measure": "^2.1.7", "react-window": "^2.3.4", "react-zoom-pan-pinch": "^3.7.0", - "redlock": "^5.0.0-beta2", "reflect-metadata": "^0.2.2", "refractor": "^5.0.0", "resolve-path": "^1.4.0", diff --git a/server/queues/tasks/ValidateSSOAccessTask.ts b/server/queues/tasks/ValidateSSOAccessTask.ts index 31413ec3ec..0b3ab44f68 100644 --- a/server/queues/tasks/ValidateSSOAccessTask.ts +++ b/server/queues/tasks/ValidateSSOAccessTask.ts @@ -50,9 +50,7 @@ export default class ValidateSSOAccessTask extends BaseTask { }) ); - if (signal.aborted) { - throw signal.error; - } + signal.throwIfAborted(); if (validity.some((isValid) => isValid)) { // Re-sync group memberships from each provider that was just diff --git a/server/utils/MutexLock.test.ts b/server/utils/MutexLock.test.ts new file mode 100644 index 0000000000..76913122a8 --- /dev/null +++ b/server/utils/MutexLock.test.ts @@ -0,0 +1,269 @@ +import { sleep } from "@shared/utils/timers"; +import Redis from "@server/storage/redis"; +import type * as MutexLockModule from "./MutexLock"; + +const { MutexLock } = + await vi.importActual("./MutexLock"); + +const noRetry = { retry: { retryCount: 0 } }; + +/** + * Make the next SET apply in Redis and then reject, as when the reply is lost. + */ +function rejectAfterSet() { + const client = Redis.defaultClient; + const set = client.set.bind(client); + return vi + .spyOn(client, "set") + .mockImplementationOnce(async (...args: Parameters) => { + await set(...args); + throw new Error("Connection lost"); + }); +} + +/** + * Make the next SET apply in Redis and then reply after a delay. + * + * @param ms The delay in milliseconds. + */ +function delaySetReply(ms: number) { + const client = Redis.defaultClient; + const set = client.set.bind(client); + return vi + .spyOn(client, "set") + .mockImplementationOnce(async (...args: Parameters) => { + const result = await set(...args); + await sleep(ms); + return result; + }); +} + +describe("MutexLock", () => { + beforeEach(async () => { + await Redis.defaultClient.flushdb(); + }); + + describe("acquire", () => { + it("should set the key with an expiry", async () => { + const lock = await MutexLock.acquire("test:lock", 1000); + + expect(await Redis.defaultClient.get("test:lock")).toEqual(lock.value); + expect(await Redis.defaultClient.pttl("test:lock")).toBeGreaterThan(0); + expect(lock.expiration).toBeGreaterThan(Date.now()); + }); + + it("should throw when the lock is held elsewhere", async () => { + await MutexLock.acquire("test:lock", 1000); + + await expect( + MutexLock.acquire("test:lock", 1000, noRetry) + ).rejects.toThrow(); + }); + + it("should retry until the lock is released", async () => { + const first = await MutexLock.acquire("test:lock", 1000); + setTimeout(() => void MutexLock.release(first), 50); + + const second = await MutexLock.acquire("test:lock", 1000, { + retry: { retryCount: 10, retryDelay: 20, retryJitter: 0 }, + }); + + expect(await Redis.defaultClient.get("test:lock")).toEqual(second.value); + }); + + it("should retry after a Redis error", async () => { + const spy = vi + .spyOn(Redis.defaultClient, "set") + .mockRejectedValueOnce(new Error("READONLY")); + + const lock = await MutexLock.acquire("test:lock", 1000, { + retry: { retryCount: 1, retryDelay: 10, retryJitter: 0 }, + }); + spy.mockRestore(); + + expect(await Redis.defaultClient.get("test:lock")).toEqual(lock.value); + }); + + it("should throw the Redis error when all attempts fail", async () => { + const spy = vi + .spyOn(Redis.defaultClient, "set") + .mockRejectedValue(new Error("READONLY")); + + await expect( + MutexLock.acquire("test:lock", 1000, { + retry: { retryCount: 1, retryDelay: 10, retryJitter: 0 }, + }) + ).rejects.toThrow("READONLY"); + spy.mockRestore(); + }); + + it("should recover its own lock after a SET reply is lost", async () => { + const spy = rejectAfterSet(); + + const lock = await MutexLock.acquire("test:lock", 1000, { + retry: { retryCount: 1, retryDelay: 10, retryJitter: 0 }, + }); + spy.mockRestore(); + + expect(await Redis.defaultClient.get("test:lock")).toEqual(lock.value); + }); + + it("should discard its own lock when giving up after a lost reply", async () => { + const spy = rejectAfterSet(); + + await expect( + MutexLock.acquire("test:lock", 1000, noRetry) + ).rejects.toThrow("Connection lost"); + spy.mockRestore(); + + expect(await Redis.defaultClient.get("test:lock")).toBeNull(); + }); + + it("should not return a lock that expired before the reply", async () => { + const spy = delaySetReply(150); + + await expect( + MutexLock.acquire("test:lock", 100, noRetry) + ).rejects.toThrow(); + spy.mockRestore(); + }); + }); + + describe("release", () => { + it("should delete the key", async () => { + const lock = await MutexLock.acquire("test:lock", 1000); + + expect(await MutexLock.release(lock)).toEqual(true); + expect(await Redis.defaultClient.get("test:lock")).toBeNull(); + }); + + it("should not delete a lock owned by another holder", async () => { + const lock = await MutexLock.acquire("test:lock", 1000); + await Redis.defaultClient.set("test:lock", "other"); + + expect(await MutexLock.release(lock)).toEqual(false); + expect(await Redis.defaultClient.get("test:lock")).toEqual("other"); + }); + }); + + describe("using", () => { + it("should hold the lock while the routine runs", async () => { + const result = await MutexLock.using("test:lock", 1000, async () => { + await expect( + MutexLock.acquire("test:lock", 1000, noRetry) + ).rejects.toThrow(); + return "done"; + }); + + expect(result).toEqual("done"); + expect(await Redis.defaultClient.get("test:lock")).toBeNull(); + }); + + it("should release the lock when the routine throws", async () => { + await expect( + MutexLock.using("test:lock", 1000, async () => { + throw new Error("failed"); + }) + ).rejects.toThrow("failed"); + + expect(await Redis.defaultClient.get("test:lock")).toBeNull(); + }); + + it("should extend the lock past its initial duration", async () => { + await MutexLock.using("test:lock", 200, async (signal) => { + await new Promise((resolve) => setTimeout(resolve, 500)); + + expect(signal.aborted).toEqual(false); + expect(await Redis.defaultClient.get("test:lock")).not.toBeNull(); + }); + }); + + it("should extend the lock in time when acquisition is slow", async () => { + const spy = delaySetReply(600); + + await MutexLock.using("test:lock", 1000, async () => { + spy.mockRestore(); + await sleep(500); + + await expect( + MutexLock.acquire("test:lock", 1000, noRetry) + ).rejects.toThrow(); + }); + }); + + it("should abort the signal when an extension stays pending past expiry", async () => { + const client = Redis.defaultClient; + + await MutexLock.using("test:lock", 200, async (signal) => { + const spy = vi.spyOn(client, "eval").mockImplementation(async () => { + await sleep(300); + return 1; + }); + await sleep(250); + spy.mockRestore(); + + expect(signal.aborted).toEqual(true); + expect(() => signal.throwIfAborted()).toThrow("expired"); + }); + }); + + it("should abort the signal when the lock is lost", async () => { + await MutexLock.using("test:lock", 200, async (signal) => { + await Redis.defaultClient.set("test:lock", "other"); + await new Promise((resolve) => setTimeout(resolve, 200)); + + expect(signal.aborted).toEqual(true); + expect(() => signal.throwIfAborted()).toThrow("was lost"); + }); + + expect(await Redis.defaultClient.get("test:lock")).toEqual("other"); + }); + }); + + describe("tryUsing", () => { + it("should run the routine when the lock is free", async () => { + const result = await MutexLock.tryUsing( + "test:lock", + 1000, + async () => "done" + ); + + expect(result).toEqual("done"); + expect(await Redis.defaultClient.get("test:lock")).toBeNull(); + }); + + it("should skip the routine when the lock is held elsewhere", async () => { + await MutexLock.acquire("test:lock", 1000); + const routine = vi.fn(); + + const result = await MutexLock.tryUsing("test:lock", 1000, routine); + + expect(result).toBeUndefined(); + expect(routine).not.toHaveBeenCalled(); + }); + + it("should skip the routine when the reply arrives after expiry", async () => { + const spy = delaySetReply(150); + const routine = vi.fn(); + + const result = await MutexLock.tryUsing("test:lock", 100, routine); + spy.mockRestore(); + + expect(result).toBeUndefined(); + expect(routine).not.toHaveBeenCalled(); + }); + + it("should discard its own lock when the SET reply is lost", async () => { + const spy = rejectAfterSet(); + const routine = vi.fn(); + + await expect( + MutexLock.tryUsing("test:lock", 1000, routine) + ).rejects.toThrow("Connection lost"); + spy.mockRestore(); + + expect(routine).not.toHaveBeenCalled(); + expect(await Redis.defaultClient.get("test:lock")).toBeNull(); + }); + }); +}); diff --git a/server/utils/MutexLock.ts b/server/utils/MutexLock.ts index c3df41c86b..597b7c9909 100644 --- a/server/utils/MutexLock.ts +++ b/server/utils/MutexLock.ts @@ -1,21 +1,43 @@ -import Redlock, { - ExecutionError, - ResourceLockedError, - type Lock, - type RedlockAbortSignal, - type Settings, -} from "redlock"; +import { randomBytes } from "node:crypto"; import { toError } from "@shared/utils/error"; +import { sleep } from "@shared/utils/timers"; import Redis from "@server/storage/redis"; import Logger from "@server/logging/Logger"; import { ShutdownHelper, ShutdownOrder } from "./ShutdownHelper"; -type AcquireOptions = { +/** + * A lock held on a single resource. + */ +export interface Lock { + /** The Redis key that holds the lock. */ + resource: string; + /** A random token that identifies this holder of the lock. */ + value: string; + /** The time the lock expires, in milliseconds since the epoch. */ + expiration: number; + /** The key of the shutdown handler that releases the lock, if any. */ + shutdownKey?: string; +} + +/** + * Settings that control how acquisition is retried while the lock is held + * elsewhere. + */ +export interface RetrySettings { + /** The number of retries after the first attempt. */ + retryCount: number; + /** The base delay between attempts in milliseconds. */ + retryDelay: number; + /** The maximum random amount added to or removed from the delay. */ + retryJitter: number; +} + +interface AcquireOptions { /** Whether a lock should be automatically released on server shutdown */ releaseOnShutdown?: boolean; /** Overrides the default retry settings for this acquisition. */ - retry?: Partial; -}; + retry?: Partial; +} /** * A distributed mutex lock backed by Redis, for coordinating exclusive access @@ -31,63 +53,85 @@ export class MutexLock { /** Default expiry time for acquiring lock in milliseconds. */ public static defaultLockTimeout = 4000; + /** Default retry settings, waiting up to roughly two minutes. */ + public static defaultRetrySettings: RetrySettings = { + retryCount: 120, + retryDelay: 1000, + retryJitter: 100, + }; + /** * Retry settings for short-lived cache locks, bounded to roughly the lock * TTL. Contenders re-check the cache after acquiring, so a longer window only * adds latency and retains memory during cache-miss storms. */ - public static cacheRetrySettings: Partial = { + public static cacheRetrySettings: Partial = { retryCount: 15, retryDelay: 250, }; - /** - * Returns the redlock instance - */ - public static get lock(): Redlock { - if (!this.redlock) { - this.redlock = new Redlock([Redis.defaultClient], { - retryJitter: 100, - retryCount: 120, - retryDelay: 1000, - }); - this.redlock.on("error", (err) => { - if (err instanceof ResourceLockedError) { - // Expected during lock contention retries, not an error. - return; - } else if (err instanceof ExecutionError) { - Logger.warn("Failed to extend Redlock lock", { - message: err.message, - }); - } else { - Logger.error("Unexpected Redlock error", err); - } - }); - } - - return this.redlock; - } - /** * Acquire a Mutex lock * * @param resource The resource to lock * @param timeout The duration to acquire the lock for if not released in milliseconds + * @param options Options for the acquisition. * @returns A promise that resolves a to a Lock + * @throws If the lock cannot be acquired after all retries. */ public static async acquire( resource: string, timeout: number, options?: AcquireOptions - ) { - const lock = await this.lock.acquire([resource], timeout, options?.retry); - if (options?.releaseOnShutdown) { - const key = `lock:${resource}`; - // @ts-expect-error Attach resource for use in shutdown - lock._key = key; - ShutdownHelper.add(key, ShutdownOrder.last, lock.release.bind(lock)); + ): Promise { + const settings = { ...this.defaultRetrySettings, ...options?.retry }; + const value = this.token(); + let lastError: Error | undefined; + let ambiguous = false; + + for (let attempt = 0; attempt <= settings.retryCount; attempt++) { + if (attempt > 0) { + await sleep( + Math.max( + 0, + settings.retryDelay + + Math.floor((Math.random() * 2 - 1) * settings.retryJitter) + ) + ); + } + + let lock: Lock | undefined; + try { + lock = await this.attempt(resource, value, timeout, ambiguous); + lastError = undefined; + } catch (err) { + // Temporary Redis errors, such as READONLY during failover, are retried. + // The SET can still have been applied, so later attempts check for it. + lastError = toError(err); + ambiguous = true; + } + if (!lock) { + continue; + } + + if (options?.releaseOnShutdown) { + lock.shutdownKey = `lock:${resource}`; + ShutdownHelper.add(lock.shutdownKey, ShutdownOrder.last, () => + this.del(lock) + ); + } + return lock; } - return lock; + + if (ambiguous) { + await this.discard(resource, value); + } + throw ( + lastError ?? + new Error( + `Could not acquire lock on ${resource} after ${settings.retryCount + 1} attempts` + ) + ); } /** @@ -104,9 +148,10 @@ export class MutexLock { public static async using( resource: string, timeout: number, - routine: (signal: RedlockAbortSignal) => Promise + routine: (signal: AbortSignal) => Promise ): Promise { - return this.lock.using([resource], timeout, routine); + const lock = await this.acquire(resource, timeout); + return this.runWithLock(lock, timeout, routine); } /** @@ -123,21 +168,20 @@ export class MutexLock { public static async tryUsing( resource: string, timeout: number, - routine: (signal: RedlockAbortSignal) => Promise + routine: (signal: AbortSignal) => Promise ): Promise { + const value = this.token(); + let lock: Lock | undefined; try { - return await this.lock.using( - [resource], - timeout, - { retryCount: 0 }, - routine - ); + lock = await this.attempt(resource, value, timeout, false); } catch (err) { - if (err instanceof ExecutionError || err instanceof ResourceLockedError) { - return undefined; - } + await this.discard(resource, value); throw err; } + if (!lock) { + return undefined; + } + return this.runWithLock(lock, timeout, routine); } /** @@ -150,22 +194,205 @@ export class MutexLock { */ public static async release(lock: Lock): Promise { try { - if (lock && lock.expiration > new Date().getTime()) { - await lock.release(); - return true; - } - return false; + return await this.del(lock); } catch (err) { - Logger.warn("Failed to release Redlock lock", toError(err)); + Logger.warn("Failed to release lock", toError(err)); return false; } finally { - // @ts-expect-error Attach resource for use in shutdown - const key = lock._key; - if (key) { - ShutdownHelper.remove(key); + if (lock.shutdownKey) { + ShutdownHelper.remove(lock.shutdownKey); } } } - private static redlock: Redlock; + /** + * Run a routine while extending the lock before it expires, and release the + * lock when the routine settles. + * + * @param lock The acquired lock. + * @param timeout The lock duration in milliseconds. + * @param routine The routine to run. + * @returns The routine's return value. + */ + private static async runWithLock( + lock: Lock, + timeout: number, + routine: (signal: AbortSignal) => Promise + ): Promise { + const controller = new AbortController(); + let timer: NodeJS.Timeout | undefined; + let watchdog: NodeJS.Timeout | undefined; + let extension: Promise | undefined; + + // Abort when the lock expires, even if an extension is still pending. + const watch = () => { + clearTimeout(watchdog); + watchdog = setTimeout( + () => controller.abort(new Error(`Lock on ${lock.resource} expired`)), + Math.max(lock.expiration - Date.now(), 0) + ); + }; + + // Extend when half of the lock duration remains, measured from the expiry. + const schedule = () => { + const delay = lock.expiration - Date.now() - Math.floor(timeout / 2); + timer = setTimeout(() => (extension = extend()), Math.max(delay, 0)); + }; + + const extend = async () => { + try { + if (await this.pexpire(lock, timeout)) { + if (!controller.signal.aborted) { + watch(); + schedule(); + } + return; + } + controller.abort(new Error(`Lock on ${lock.resource} was lost`)); + } catch (err) { + if (lock.expiration - Date.now() > this.extensionRetryDelay) { + timer = setTimeout( + () => (extension = extend()), + this.extensionRetryDelay + ); + return; + } + controller.abort(toError(err)); + } + }; + + watch(); + schedule(); + + try { + return await routine(controller.signal); + } finally { + clearTimeout(timer); + await extension; + clearTimeout(timer); + clearTimeout(watchdog); + await this.release(lock); + } + } + + /** + * Make a single attempt to acquire the lock. + * + * @param resource The resource to lock. + * @param value The token that identifies this holder. + * @param timeout The lock duration in milliseconds. + * @param ambiguous Whether an earlier attempt with this token failed after + * the SET may have been applied. + * @returns The lock, or undefined if it is held elsewhere or expired before + * the reply arrived. + */ + private static async attempt( + resource: string, + value: string, + timeout: number, + ambiguous: boolean + ): Promise { + const lock: Lock = { + resource, + value, + expiration: Date.now() + timeout, + }; + const result = await Redis.defaultClient.set( + resource, + value, + "PX", + timeout, + "NX" + ); + const acquired = + result === "OK" || (ambiguous && (await this.pexpire(lock, timeout))); + if (!acquired) { + return undefined; + } + if (Date.now() >= lock.expiration) { + await this.discard(resource, value); + return undefined; + } + return lock; + } + + /** + * Delete a lock that this holder may own, ignoring errors. + * + * @param resource The resource that was locked. + * @param value The token that identifies this holder. + */ + private static async discard(resource: string, value: string) { + try { + await this.del({ resource, value, expiration: 0 }); + } catch (err) { + Logger.warn("Failed to discard lock", toError(err)); + } + } + + /** + * Generate a random token that identifies a holder of a lock. + * + * @returns The token. + */ + private static token() { + return randomBytes(16).toString("hex"); + } + + /** + * Extend the lock if this holder still owns it. + * + * @param lock The lock to extend. + * @param timeout The new lock duration in milliseconds. + * @returns true if the lock was extended. + */ + private static async pexpire(lock: Lock, timeout: number): Promise { + const expiration = Date.now() + timeout; + const result = await Redis.defaultClient.eval( + this.extendScript, + 1, + lock.resource, + lock.value, + timeout + ); + if (result !== 1) { + return false; + } + lock.expiration = expiration; + return true; + } + + /** + * Delete the lock if this holder still owns it. + * + * @param lock The lock to delete. + * @returns true if the lock was deleted. + */ + private static async del(lock: Lock): Promise { + const result = await Redis.defaultClient.eval( + this.releaseScript, + 1, + lock.resource, + lock.value + ); + lock.expiration = 0; + return result === 1; + } + + /** Delay before retrying an extension that failed with an error. */ + private static extensionRetryDelay = 250; + + private static releaseScript = ` + if redis.call("get", KEYS[1]) == ARGV[1] then + return redis.call("del", KEYS[1]) + end + return 0 + `; + + private static extendScript = ` + if redis.call("get", KEYS[1]) == ARGV[1] then + return redis.call("pexpire", KEYS[1], ARGV[2]) + end + return 0 + `; } diff --git a/server/utils/__mocks__/MutexLock.ts b/server/utils/__mocks__/MutexLock.ts index de99b6a047..d2c566f459 100644 --- a/server/utils/__mocks__/MutexLock.ts +++ b/server/utils/__mocks__/MutexLock.ts @@ -19,8 +19,8 @@ export class MutexLock { ( _resource: string, _timeout: number, - routine: (signal: { aborted: boolean }) => unknown - ) => routine({ aborted: false }) + routine: (signal: AbortSignal) => unknown + ) => routine(new AbortController().signal) ); /** @@ -30,24 +30,12 @@ export class MutexLock { ( _resource: string, _timeout: number, - routine: (signal: { aborted: boolean }) => unknown - ) => routine({ aborted: false }) + routine: (signal: AbortSignal) => unknown + ) => routine(new AbortController().signal) ); /** * Releases a mock lock. */ public static release = vi.fn().mockResolvedValue(true); - - /** - * Returns the mock redlock instance - */ - public static get lock() { - return { - acquire: vi.fn().mockResolvedValue({ - release: vi.fn().mockResolvedValue(true), - expiration: Date.now() + 10000, - }), - }; - } } diff --git a/yarn.lock b/yarn.lock index 5b508491b2..61d9a69b0d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -13529,13 +13529,6 @@ __metadata: languageName: node linkType: hard -"node-abort-controller@npm:^3.0.1": - version: 3.1.1 - resolution: "node-abort-controller@npm:3.1.1" - checksum: 10c0/f7ad0e7a8e33809d4f3a0d1d65036a711c39e9d23e0319d80ebe076b9a3b4432b4d6b86a7fab65521de3f6872ffed36fc35d1327487c48eb88c517803403eda3 - languageName: node - linkType: hard - "node-addon-api@npm:^6.1.0": version: 6.1.0 resolution: "node-addon-api@npm:6.1.0" @@ -14166,7 +14159,6 @@ __metadata: react-use-measure: "npm:^2.1.7" react-window: "npm:^2.3.4" react-zoom-pan-pinch: "npm:^3.7.0" - redlock: "npm:^5.0.0-beta2" reflect-metadata: "npm:^0.2.2" refractor: "npm:^5.0.0" resolve-path: "npm:^1.4.0" @@ -15858,15 +15850,6 @@ __metadata: languageName: node linkType: hard -"redlock@npm:^5.0.0-beta2": - version: 5.0.0-beta2 - resolution: "redlock@npm:5.0.0-beta2" - dependencies: - node-abort-controller: "npm:^3.0.1" - checksum: 10c0/3a845b34d2a91869a21a3a4ab37011053d7374212b3aba0fe2be0f21980e49a23cef5958c1af29691df7e1d88435c07dea32c6729d281a97a123102185d69532 - languageName: node - linkType: hard - "reflect-metadata@npm:^0.2.2": version: 0.2.2 resolution: "reflect-metadata@npm:0.2.2"