hippofish/packages/backend/src/misc/app-lock.ts

50 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-01-13 05:40:33 +01:00
import { redisClient } from "../db/redis.js";
2023-09-02 03:44:05 +02:00
import { Mutex } from "redis-semaphore";
2019-09-09 15:46:45 +02:00
/**
* Retry delay (ms) for lock acquisition
*/
const retryDelay = 100;
/**
* Get AP Object lock
* @param uri AP object ID
* @param timeout Lock timeout (ms), The timeout releases previous lock.
* @returns Unlock function
*/
2023-09-02 21:22:13 +02:00
export async function getApLock(
uri: string,
timeout = 30 * 1000,
): Promise<Mutex> {
2023-09-02 03:44:05 +02:00
const lock = new Mutex(redisClient, `ap-object:${uri}`, {
lockTimeout: timeout,
retryInterval: retryDelay,
});
await lock.acquire();
2023-09-02 21:22:13 +02:00
return lock;
2019-09-09 15:46:45 +02:00
}
2023-09-02 03:44:05 +02:00
export async function getFetchInstanceMetadataLock(
2023-01-13 05:40:33 +01:00
host: string,
timeout = 30 * 1000,
2023-09-02 21:22:13 +02:00
): Promise<Mutex> {
2023-09-02 03:44:05 +02:00
const lock = new Mutex(redisClient, `instance:${host}`, {
lockTimeout: timeout,
retryInterval: retryDelay,
});
await lock.acquire();
2023-09-02 21:22:13 +02:00
return lock;
}
2023-09-02 21:22:13 +02:00
export async function getChartInsertLock(
lockKey: string,
timeout = 30 * 1000,
): Promise<Mutex> {
2023-09-02 03:44:05 +02:00
const lock = new Mutex(redisClient, `chart-insert:${lockKey}`, {
lockTimeout: timeout,
retryInterval: retryDelay,
});
await lock.acquire();
2023-09-02 21:22:13 +02:00
return lock;
}