2023-07-27 14:31:52 +09:00
|
|
|
/*
|
|
|
|
* SPDX-FileCopyrightText: syuilo and other misskey contributors
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-09-18 03:27:08 +09:00
|
|
|
import { promisify } from 'node:util';
|
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
|
|
import redisLock from 'redis-lock';
|
2023-04-14 13:50:05 +09:00
|
|
|
import * as Redis from 'ioredis';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { DI } from '@/di-symbols.js';
|
2022-12-04 17:05:32 +09:00
|
|
|
import { bindThis } from '@/decorators.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Retry delay (ms) for lock acquisition
|
|
|
|
*/
|
|
|
|
const retryDelay = 100;
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class AppLockService {
|
2023-02-22 14:58:41 +09:00
|
|
|
private lock: (key: string, timeout?: number, _?: (() => Promise<void>) | undefined) => Promise<() => void>;
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
constructor(
|
|
|
|
@Inject(DI.redis)
|
|
|
|
private redisClient: Redis.Redis,
|
|
|
|
) {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.lock = promisify(redisLock(this.redisClient, retryDelay));
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get AP Object lock
|
|
|
|
* @param uri AP object ID
|
|
|
|
* @param timeout Lock timeout (ms), The timeout releases previous lock.
|
|
|
|
* @returns Unlock function
|
|
|
|
*/
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-09-18 03:27:08 +09:00
|
|
|
public getApLock(uri: string, timeout = 30 * 1000): Promise<() => void> {
|
2022-09-19 03:11:50 +09:00
|
|
|
return this.lock(`ap-object:${uri}`, timeout);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-09-18 03:27:08 +09:00
|
|
|
public getChartInsertLock(lockKey: string, timeout = 30 * 1000): Promise<() => void> {
|
2022-09-19 03:11:50 +09:00
|
|
|
return this.lock(`chart-insert:${lockKey}`, timeout);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
}
|