misskey-awawa/packages/backend/src/core/AppLockService.ts

41 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-09-17 18:27:08 +00:00
import { promisify } from 'node:util';
import { Inject, Injectable } from '@nestjs/common';
import redisLock from 'redis-lock';
import Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
/**
* Retry delay (ms) for lock acquisition
*/
const retryDelay = 100;
@Injectable()
export class AppLockService {
2022-09-18 18:11:50 +00:00
private lock: (key: string, timeout?: number) => Promise<() => void>;
2022-09-17 18:27:08 +00:00
constructor(
@Inject(DI.redis)
private redisClient: Redis.Redis,
) {
2022-09-18 18:11:50 +00:00
this.lock = promisify(redisLock(this.redisClient, retryDelay));
2022-09-17 18:27:08 +00:00
}
/**
* Get AP Object lock
* @param uri AP object ID
* @param timeout Lock timeout (ms), The timeout releases previous lock.
* @returns Unlock function
*/
public getApLock(uri: string, timeout = 30 * 1000): Promise<() => void> {
2022-09-18 18:11:50 +00:00
return this.lock(`ap-object:${uri}`, timeout);
2022-09-17 18:27:08 +00:00
}
public getFetchInstanceMetadataLock(host: string, timeout = 30 * 1000): Promise<() => void> {
2022-09-18 18:11:50 +00:00
return this.lock(`instance:${host}`, timeout);
2022-09-17 18:27:08 +00:00
}
public getChartInsertLock(lockKey: string, timeout = 30 * 1000): Promise<() => void> {
2022-09-18 18:11:50 +00:00
return this.lock(`chart-insert:${lockKey}`, timeout);
2022-09-17 18:27:08 +00:00
}
}