Skip to content

Commit

Permalink
feat: promise timeout on lock (#5108)
Browse files Browse the repository at this point in the history
  • Loading branch information
kwasniew authored Oct 20, 2023
1 parent f1b8d9b commit 433f3e2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
6 changes: 2 additions & 4 deletions src/lib/util/db-lock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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'),
Expand Down
12 changes: 9 additions & 3 deletions src/lib/util/db-lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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}`);
Expand Down

0 comments on commit 433f3e2

Please sign in to comment.