Files
energy_dist/dist/app/common/service/lock.service.js
T
2026-04-21 22:34:39 +08:00

130 lines
5.1 KiB
JavaScript

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var DistributedLockService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DistributedLockService = void 0;
const common_1 = require("@nestjs/common");
const crypto_1 = require("crypto");
const redis_service_1 = require("./redis.service");
let DistributedLockService = DistributedLockService_1 = class DistributedLockService {
redisService;
logger = new common_1.Logger(DistributedLockService_1.name);
LOCK_PREFIX = 'distributed_lock:';
constructor(redisService) {
this.redisService = redisService;
}
async acquireLock(resource, options = {}) {
const { ttl = 10000, retryDelay = 100, maxRetries = 10 } = options;
const lockKey = `${this.LOCK_PREFIX}${resource}`;
const identifier = (0, crypto_1.randomUUID)();
let retries = 0;
while (retries < maxRetries) {
try {
const result = await this.redisService.client.set(lockKey, identifier, 'PX', ttl, 'NX');
if (result === 'OK') {
return { success: true, identifier };
}
}
catch (err) {
this.logger.error(`Redis error acquiring lock: ${resource}`, err);
return { success: false };
}
if (retries < maxRetries - 1) {
await this.delay(retryDelay);
}
retries++;
}
return { success: false };
}
async releaseLock(resource, identifier) {
try {
const lockKey = `${this.LOCK_PREFIX}${resource}`;
const luaScript = `
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
`;
const result = await this.redisService.client.eval(luaScript, 1, lockKey, identifier);
return result === 1;
}
catch (err) {
this.logger.warn(`Failed to release lock: ${resource}`, err);
return false;
}
}
async renewLock(resource, identifier, ttl) {
try {
const lockKey = `${this.LOCK_PREFIX}${resource}`;
const luaScript = `
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("PEXPIRE", KEYS[1], ARGV[2])
else
return 0
end
`;
const result = await this.redisService.client.eval(luaScript, 1, lockKey, identifier, ttl.toString());
return result === 1;
}
catch {
return false;
}
}
async withLock(resource, task, options = {}) {
const { ttl = 10000, timeout = 0 } = options;
const lockResult = await this.acquireLock(resource, options);
if (!lockResult.success) {
if (options.fallback) {
return options.fallback(0);
}
throw new Error(`Failed to acquire lock for resource: ${resource}`);
}
const identifier = lockResult.identifier;
const renewInterval = Math.floor(ttl / 3);
const renewTimer = setInterval(() => {
this.renewLock(resource, identifier, ttl).catch(() => { });
}, renewInterval);
let result;
try {
if (timeout > 0) {
result = await Promise.race([
task(),
new Promise((_, reject) => setTimeout(() => reject(new Error(`Lock task timed out: ${resource}`)), timeout)),
]);
}
else {
result = await task();
}
return result;
}
finally {
if (renewTimer) {
clearInterval(renewTimer);
renewTimer.unref?.();
}
await this.releaseLock(resource, identifier);
}
}
delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
};
exports.DistributedLockService = DistributedLockService;
exports.DistributedLockService = DistributedLockService = DistributedLockService_1 = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, common_1.Inject)(redis_service_1.RedisService)),
__metadata("design:paramtypes", [redis_service_1.RedisService])
], DistributedLockService);
//# sourceMappingURL=lock.service.js.map