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:
parent
f1b8d9b8d5
commit
433f3e2760
@ -46,7 +46,7 @@ test('should await other actions on lock', async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('should handle lock timeout', async () => {
|
test('should handle lock timeout', async () => {
|
||||||
const timeoutMs = 1;
|
const timeoutMs = 10;
|
||||||
let loggedError = '';
|
let loggedError = '';
|
||||||
const lock = withDbLock(getDbConfig() as IDBOption, {
|
const lock = withDbLock(getDbConfig() as IDBOption, {
|
||||||
lockKey: 1,
|
lockKey: 1,
|
||||||
@ -58,9 +58,7 @@ test('should handle lock timeout', async () => {
|
|||||||
} as unknown as Logger,
|
} as unknown as Logger,
|
||||||
});
|
});
|
||||||
|
|
||||||
// the query should fail because of the timeout. This one is a fallback when timeout
|
const asyncAction = () => ms(100);
|
||||||
// was not triggered in the integration test
|
|
||||||
const asyncAction = () => Promise.reject(new Error('Query read timeout'));
|
|
||||||
|
|
||||||
await expect(lock(asyncAction)()).rejects.toStrictEqual(
|
await expect(lock(asyncAction)()).rejects.toStrictEqual(
|
||||||
new Error('Query read timeout'),
|
new Error('Query read timeout'),
|
||||||
|
@ -3,7 +3,7 @@ import { IDBOption } from '../types';
|
|||||||
import { Logger } from '../logger';
|
import { Logger } from '../logger';
|
||||||
|
|
||||||
export const defaultLockKey = 479341;
|
export const defaultLockKey = 479341;
|
||||||
export const defaultTimeout = 5000;
|
export const defaultTimeout = 30 * 60000;
|
||||||
|
|
||||||
interface IDbLockOptions {
|
interface IDbLockOptions {
|
||||||
timeout: number;
|
timeout: number;
|
||||||
@ -23,13 +23,19 @@ export const withDbLock =
|
|||||||
async (...args: A): Promise<R> => {
|
async (...args: A): Promise<R> => {
|
||||||
const client = new Client({
|
const client = new Client({
|
||||||
...dbConfig,
|
...dbConfig,
|
||||||
query_timeout: config.timeout,
|
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
// wait to obtain a lock
|
// wait to obtain a lock
|
||||||
await client.query('SELECT pg_advisory_lock($1)', [config.lockKey]);
|
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;
|
return result;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
config.logger.error(`Locking error: ${e.message}`);
|
config.logger.error(`Locking error: ${e.message}`);
|
||||||
|
Loading…
Reference in New Issue
Block a user