import { ConflictException, Injectable } from '@nestjs/common'; import { AuthUser } from '../../common/current-user.decorator'; import { RedisService } from '../redis/redis.service'; import { AlarmsService } from '../alarms/alarms.service'; @Injectable() export class AlarmIngestionService { constructor( private readonly redisService: RedisService, private readonly alarmsService: AlarmsService, ) {} async receive(user: AuthUser, dto: any) { const idempotentKey = `alarm:ingestion:${user.sub}:${dto.sourceAlarmId}`; const redis = this.redisService.client; await redis.connect().catch(() => undefined); const created = await redis.set(idempotentKey, '1', 'EX', 3600, 'NX'); if (!created) { throw new ConflictException('重复报警已忽略'); } try { return await this.alarmsService.createFromIngestion(user, dto); } catch (e) { await redis.del(idempotentKey).catch(() => undefined); throw e; } } }