From 950846ba4936247898ef522aa509a022b414d8c6 Mon Sep 17 00:00:00 2001 From: Ravi Kiran Date: Wed, 2 Dec 2026 13:38:35 +0530 Subject: [PATCH] Let a system job drop its finished runs and add a non-waiting lock A job definition can set discardFinishedRuns so the queue removes each run once it ends; the queue keeps every finished run by default and scans them on each schedule change. distributedLock.tryAcquireLock takes a lock only if it is free and returns null otherwise, for work that should be skipped while another run of it is going. Co-Authored-By: Claude Fable 5.2 --- .../api/src/app/helper/system-jobs/common.ts | 4 + .../helper/system-jobs/redis-system-job.ts | 11 ++- .../system-jobs/redis-system-job.test.ts | 63 +++++++++++++ .../server/shared/src/lib/distributed-lock.ts | 51 +++++++++- packages/server/shared/src/lib/memory-lock.ts | 17 ++++ .../shared/test/distributed-lock.test.ts | 94 +++++++++++++++++++ .../server/shared/test/memory-lock.test.ts | 36 +++++++ 7 files changed, 274 insertions(+), 2 deletions(-) create mode 100644 packages/server/api/test/unit/helper/system-jobs/redis-system-job.test.ts create mode 100644 packages/server/shared/test/distributed-lock.test.ts create mode 100644 packages/server/shared/test/memory-lock.test.ts diff --git a/packages/server/api/src/app/helper/system-jobs/common.ts b/packages/server/api/src/app/helper/system-jobs/common.ts index c41affd430..4e7b0ac4c6 100644 --- a/packages/server/api/src/app/helper/system-jobs/common.ts +++ b/packages/server/api/src/app/helper/system-jobs/common.ts @@ -55,6 +55,10 @@ export type SystemJobDefinition = { name: T; data: SystemJobData; jobId?: string; + // The queue keeps every finished run unless told otherwise, and each + // upsert scans them all. A job that runs often sets this so its finished + // runs are dropped. + discardFinishedRuns?: boolean; }; export type SystemJobHandler = ( diff --git a/packages/server/api/src/app/helper/system-jobs/redis-system-job.ts b/packages/server/api/src/app/helper/system-jobs/redis-system-job.ts index 67d6cd560c..061f355d22 100644 --- a/packages/server/api/src/app/helper/system-jobs/redis-system-job.ts +++ b/packages/server/api/src/app/helper/system-jobs/redis-system-job.ts @@ -94,16 +94,22 @@ const addJobToQueue = async ({ job, schedule, }: AddJobToQueueParams): Promise => { - const jobOptions = configureJobOptions({ schedule, jobId: job.jobId }); + const jobOptions = configureJobOptions({ + schedule, + jobId: job.jobId, + discardFinishedRuns: job.discardFinishedRuns, + }); await systemJobsQueue.add(job.name, job.data, jobOptions); }; const configureJobOptions = ({ schedule, jobId, + discardFinishedRuns, }: { schedule: JobSchedule; jobId?: string; + discardFinishedRuns?: boolean; }): JobsOptions => { const config: JobsOptions = {}; @@ -125,6 +131,9 @@ const configureJobOptions = ({ return { ...config, ...spreadIfDefined('jobId', jobId), + ...(discardFinishedRuns + ? { removeOnComplete: true, removeOnFail: true } + : {}), }; }; diff --git a/packages/server/api/test/unit/helper/system-jobs/redis-system-job.test.ts b/packages/server/api/test/unit/helper/system-jobs/redis-system-job.test.ts new file mode 100644 index 0000000000..976bc594ae --- /dev/null +++ b/packages/server/api/test/unit/helper/system-jobs/redis-system-job.test.ts @@ -0,0 +1,63 @@ +const mockAdd = jest.fn(); +const mockGetJobs = jest.fn(); + +jest.mock('bullmq', () => ({ + Queue: jest.fn().mockImplementation(() => ({ + add: mockAdd, + getJobs: mockGetJobs, + waitUntilReady: jest.fn().mockResolvedValue(undefined), + })), + Worker: jest.fn().mockImplementation(() => ({ + waitUntilReady: jest.fn().mockResolvedValue(undefined), + })), +})); + +jest.mock('@openops/server-shared', () => ({ + createRedisClient: jest.fn().mockReturnValue({}), + logger: { info: jest.fn(), debug: jest.fn() }, +})); + +import { SystemJobName } from '../../../../src/app/helper/system-jobs/common'; +import { redisSystemJobSchedulerService } from '../../../../src/app/helper/system-jobs/redis-system-job'; + +describe('redisSystemJobSchedulerService.upsertJob', () => { + beforeEach(async () => { + jest.clearAllMocks(); + mockGetJobs.mockResolvedValue([]); + await redisSystemJobSchedulerService.init(); + }); + + it('keeps finished runs by default', async () => { + await redisSystemJobSchedulerService.upsertJob({ + job: { name: SystemJobName.OAUTH_CLEANUP, data: {} }, + schedule: { type: 'repeated', cron: '0 * * * *' }, + }); + + expect(mockAdd).toHaveBeenCalledWith( + SystemJobName.OAUTH_CLEANUP, + {}, + { repeat: { pattern: '0 * * * *', tz: 'UTC' } }, + ); + }); + + it('has the queue drop finished runs of a job that asks for it', async () => { + await redisSystemJobSchedulerService.upsertJob({ + job: { + name: SystemJobName.OAUTH_CLEANUP, + data: {}, + discardFinishedRuns: true, + }, + schedule: { type: 'repeated', cron: '*/5 * * * *' }, + }); + + expect(mockAdd).toHaveBeenCalledWith( + SystemJobName.OAUTH_CLEANUP, + {}, + { + repeat: { pattern: '*/5 * * * *', tz: 'UTC' }, + removeOnComplete: true, + removeOnFail: true, + }, + ); + }); +}); diff --git a/packages/server/shared/src/lib/distributed-lock.ts b/packages/server/shared/src/lib/distributed-lock.ts index 2700ce27a2..75b47dd1cb 100644 --- a/packages/server/shared/src/lib/distributed-lock.ts +++ b/packages/server/shared/src/lib/distributed-lock.ts @@ -1,5 +1,5 @@ import Redis from 'ioredis'; -import RedLock from 'redlock'; +import RedLock, { ExecutionError, ResourceLockedError } from 'redlock'; import { createRedisClient } from './cache/redis-connection'; import { exceptionHandler } from './exception-handler'; import { logger } from './logger'; @@ -66,6 +66,55 @@ const acquireLock = async ({ } }; +// The lock library reports a held lock and a Redis failure with the same +// error; what tells them apart is why each Redis client voted against. +const isHeldByAnother = async (error: unknown): Promise => { + if (!(error instanceof ExecutionError)) { + return false; + } + const attempts = await Promise.all(error.attempts); + const reasons = attempts.flatMap((attempt) => [ + ...attempt.votesAgainst.values(), + ]); + return ( + reasons.length > 0 && + reasons.every((reason) => reason instanceof ResourceLockedError) + ); +}; + +const tryAcquireRedisLock = async ( + key: string, + timeout: number, +): Promise => { + try { + return await redLock.acquire([key], timeout, { retryCount: 0 }); + } catch (e) { + if (await isHeldByAnother(e)) { + return null; + } + exceptionHandler.handle(Object.assign(e as Error, { key, timeout })); + throw e; + } +}; + +// Takes the lock if it is free and returns null if it is held; it never +// waits. For work that should be skipped, not queued, while another run of +// it is going. `timeout` is how long the lock lives if it is not released. +const tryAcquireLock = async ({ + key, + timeout = 3000, +}: AcquireLockParams): Promise => { + switch (queueMode) { + case QueueMode.REDIS: + return tryAcquireRedisLock(key, timeout); + case QueueMode.MEMORY: + return memoryLock.tryAcquire(key); + default: + throw new Error(`Unknown queue mode: ${queueMode}`); + } +}; + export const distributedLock = { acquireLock, + tryAcquireLock, }; diff --git a/packages/server/shared/src/lib/memory-lock.ts b/packages/server/shared/src/lib/memory-lock.ts index 9c635ebe7a..fb39a0b8f2 100644 --- a/packages/server/shared/src/lib/memory-lock.ts +++ b/packages/server/shared/src/lib/memory-lock.ts @@ -19,6 +19,10 @@ class MutexLockWrapper { async release(): Promise { this.lock.release(); } + + isLocked(): boolean { + return this.lock.isLocked(); + } } export const memoryLock = { @@ -31,6 +35,19 @@ export const memoryLock = { await lock.acquire(); return lock; }, + // Takes the lock only if it is free; never waits. + tryAcquire: async (key: string): Promise => { + let lock = memoryLocks.get(key); + if (!lock) { + lock = new MutexLockWrapper(); + memoryLocks.set(key, lock); + } + if (lock.isLocked()) { + return null; + } + await lock.acquire(); + return lock; + }, delete: (key: string): void => { memoryLocks.delete(key); }, diff --git a/packages/server/shared/test/distributed-lock.test.ts b/packages/server/shared/test/distributed-lock.test.ts new file mode 100644 index 0000000000..87a3c26d30 --- /dev/null +++ b/packages/server/shared/test/distributed-lock.test.ts @@ -0,0 +1,94 @@ +const mockAcquire = jest.fn(); + +class MockResourceLockedError extends Error {} + +class MockExecutionError extends Error { + attempts: Promise<{ votesAgainst: Map }>[]; + + constructor(reasons: Error[]) { + super('The operation was unable to achieve a quorum.'); + this.attempts = [ + Promise.resolve({ + votesAgainst: new Map(reasons.map((reason, index) => [index, reason])), + }), + ]; + } +} + +jest.mock('redlock', () => ({ + __esModule: true, + default: jest.fn().mockImplementation(() => ({ acquire: mockAcquire })), + ExecutionError: MockExecutionError, + ResourceLockedError: MockResourceLockedError, +})); + +jest.mock('../src/lib/cache/redis-connection', () => ({ + createRedisClient: jest.fn().mockReturnValue({}), +})); + +const mockHandleException = jest.fn(); +jest.mock('../src/lib/exception-handler', () => ({ + exceptionHandler: { handle: mockHandleException }, +})); + +jest.mock('../src/lib/logger', () => ({ + logger: { debug: jest.fn(), info: jest.fn() }, +})); + +jest.mock('../src/lib/system', () => ({ + AppSystemProp: { QUEUE_MODE: 'QUEUE_MODE' }, + QueueMode: { REDIS: 'REDIS', MEMORY: 'MEMORY' }, + system: { getOrThrow: jest.fn().mockReturnValue('REDIS') }, +})); + +import { distributedLock, initializeLock } from '../src/lib/distributed-lock'; + +describe('distributedLock.tryAcquireLock (Redis)', () => { + beforeEach(() => { + jest.clearAllMocks(); + initializeLock(); + }); + + it('asks for the lock once, with no retries, and returns it', async () => { + const lock = { release: jest.fn() }; + mockAcquire.mockResolvedValue(lock); + + const result = await distributedLock.tryAcquireLock({ + key: 'job', + timeout: 5000, + }); + + expect(mockAcquire).toHaveBeenCalledWith(['job'], 5000, { retryCount: 0 }); + expect(result).toBe(lock); + }); + + it('returns null when the lock is held', async () => { + mockAcquire.mockRejectedValue( + new MockExecutionError([new MockResourceLockedError('locked')]), + ); + + const result = await distributedLock.tryAcquireLock({ key: 'job' }); + + expect(result).toBeNull(); + expect(mockHandleException).not.toHaveBeenCalled(); + }); + + it('rethrows when Redis refused the request for another reason', async () => { + const failure = new MockExecutionError([new Error('READONLY replica')]); + mockAcquire.mockRejectedValue(failure); + + await expect(distributedLock.tryAcquireLock({ key: 'job' })).rejects.toBe( + failure, + ); + expect(mockHandleException).toHaveBeenCalled(); + }); + + it('rethrows a failure that is not about the lock at all', async () => { + mockAcquire.mockRejectedValue(new Error('connection refused')); + + await expect( + distributedLock.tryAcquireLock({ key: 'job' }), + ).rejects.toThrow('connection refused'); + expect(mockHandleException).toHaveBeenCalled(); + }); +}); diff --git a/packages/server/shared/test/memory-lock.test.ts b/packages/server/shared/test/memory-lock.test.ts new file mode 100644 index 0000000000..0483ebaa01 --- /dev/null +++ b/packages/server/shared/test/memory-lock.test.ts @@ -0,0 +1,36 @@ +import { memoryLock } from '../src/lib/memory-lock'; + +describe('memoryLock.tryAcquire', () => { + it('takes a free lock', async () => { + const lock = await memoryLock.tryAcquire('try-free'); + + expect(lock).not.toBeNull(); + await lock?.release(); + }); + + it('returns null without waiting while the lock is held', async () => { + const held = await memoryLock.tryAcquire('try-held'); + + expect(await memoryLock.tryAcquire('try-held')).toBeNull(); + + await held?.release(); + }); + + it('takes the lock again once it was released', async () => { + const first = await memoryLock.tryAcquire('try-released'); + await first?.release(); + + const second = await memoryLock.tryAcquire('try-released'); + + expect(second).not.toBeNull(); + await second?.release(); + }); + + it('returns null while a waiting acquire holds the same key', async () => { + const held = await memoryLock.acquire('try-shared', 1000); + + expect(await memoryLock.tryAcquire('try-shared')).toBeNull(); + + await held.release(); + }); +});