Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/server/api/src/app/helper/system-jobs/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ export type SystemJobDefinition<T extends SystemJobName> = {
name: T;
data: SystemJobData<T>;
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<T extends SystemJobName = SystemJobName> = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,22 @@ const addJobToQueue = async <T extends SystemJobName>({
job,
schedule,
}: AddJobToQueueParams<T>): Promise<void> => {
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 = {};

Expand All @@ -125,6 +131,9 @@ const configureJobOptions = ({
return {
...config,
...spreadIfDefined('jobId', jobId),
...(discardFinishedRuns
? { removeOnComplete: true, removeOnFail: true }
: {}),
};
};

Expand Down
Original file line number Diff line number Diff line change
@@ -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,
},
);
});
});
51 changes: 50 additions & 1 deletion packages/server/shared/src/lib/distributed-lock.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<boolean> => {
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<Lock | null> => {
try {
return await redLock.acquire([key], timeout, { retryCount: 0 });
Comment thread
ravikiranvm marked this conversation as resolved.
Resolved
} 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<Lock | null> => {
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,
};
17 changes: 17 additions & 0 deletions packages/server/shared/src/lib/memory-lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ class MutexLockWrapper {
async release(): Promise<void> {
this.lock.release();
}

isLocked(): boolean {
return this.lock.isLocked();
}
}

export const memoryLock = {
Expand All @@ -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<Lock | null> => {
let lock = memoryLocks.get(key);
if (!lock) {
lock = new MutexLockWrapper();
memoryLocks.set(key, lock);
Comment thread
ravikiranvm marked this conversation as resolved.
Resolved
}
if (lock.isLocked()) {
return null;
}
await lock.acquire();
return lock;
},
delete: (key: string): void => {
memoryLocks.delete(key);
},
Expand Down
94 changes: 94 additions & 0 deletions packages/server/shared/test/distributed-lock.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
const mockAcquire = jest.fn();

class MockResourceLockedError extends Error {}

class MockExecutionError extends Error {
attempts: Promise<{ votesAgainst: Map<unknown, Error> }>[];

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();
});
});
36 changes: 36 additions & 0 deletions packages/server/shared/test/memory-lock.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
Loading