From 433f3e27602367e93bead655d2cae12a6bb4e457 Mon Sep 17 00:00:00 2001 From: Mateusz Kwasniewski Date: Fri, 20 Oct 2023 12:10:18 +0200 Subject: [PATCH] feat: promise timeout on lock (#5108) --- src/lib/util/db-lock.test.ts | 6 ++---- src/lib/util/db-lock.ts | 12 +++++++++--- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/lib/util/db-lock.test.ts b/src/lib/util/db-lock.test.ts index 574fafbd61..17e8bc6a84 100644 --- a/src/lib/util/db-lock.test.ts +++ b/src/lib/util/db-lock.test.ts @@ -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'), diff --git a/src/lib/util/db-lock.ts b/src/lib/util/db-lock.ts index 55562ebe54..152e4b8650 100644 --- a/src/lib/util/db-lock.ts +++ b/src/lib/util/db-lock.ts @@ -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 => { 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}`);