1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-02-23 00:22:19 +01:00

feat: promise timeout on lock (#5108)

This commit is contained in:
Mateusz Kwasniewski 2023-10-20 12:10:18 +02:00 committed by GitHub
parent f1b8d9b8d5
commit 433f3e2760
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 7 deletions

View File

@ -46,7 +46,7 @@ test('should await other actions on lock', async () => {
});
test('should handle lock timeout', async () => {
const timeoutMs = 1;
const timeoutMs = 10;
let loggedError = '';
const lock = withDbLock(getDbConfig() as IDBOption, {
lockKey: 1,
@ -58,9 +58,7 @@ test('should handle lock timeout', async () => {
} as unknown as Logger,
});
// the query should fail because of the timeout. This one is a fallback when timeout
// was not triggered in the integration test
const asyncAction = () => Promise.reject(new Error('Query read timeout'));
const asyncAction = () => ms(100);
await expect(lock(asyncAction)()).rejects.toStrictEqual(
new Error('Query read timeout'),

View File

@ -3,7 +3,7 @@ import { IDBOption } from '../types';
import { Logger } from '../logger';
export const defaultLockKey = 479341;
export const defaultTimeout = 5000;
export const defaultTimeout = 30 * 60000;
interface IDbLockOptions {
timeout: number;
@ -23,13 +23,19 @@ export const withDbLock =
async (...args: A): Promise<R> => {
const client = new Client({
...dbConfig,
query_timeout: config.timeout,
});
try {
await client.connect();
// wait to obtain a lock
await client.query('SELECT pg_advisory_lock($1)', [config.lockKey]);
const result = await fn(...args);
const promise = fn(...args);
const timeoutPromise = new Promise((_, reject) =>
setTimeout(
() => reject(new Error('Query read timeout')),
config.timeout,
),
);
const result = (await Promise.race([promise, timeoutPromise])) as R;
return result;
} catch (e) {
config.logger.error(`Locking error: ${e.message}`);