| 1 | import { Injectable, Logger } from '@nestjs/common' |
| 2 | import { Cron, CronExpression } from '@nestjs/schedule' |
| 3 | import { WithLoggerContext } from '@yikart/common' |
| 4 | import { |
| 5 | AiLog, |
| 6 | AiLogChannel, |
| 7 | AiLogRepository, |
| 8 | AiLogType, |
| 9 | } from '@yikart/mongodb' |
| 10 | import { Redlock } from '@yikart/redlock' |
| 11 | import { RedlockKey } from '../../../common/enums' |
| 12 | import { AideoService } from './aideo.service' |
| 13 | |
| 14 | @Injectable() |
| 15 | export class AideoTaskStatusScheduler { |
| 16 | private readonly logger = new Logger(AideoTaskStatusScheduler.name) |
| 17 | |
| 18 | constructor( |
| 19 | private readonly aiLogRepo: AiLogRepository, |
| 20 | private readonly aideoService: AideoService, |
| 21 | ) { } |
| 22 | |
| 23 | /** |
| 24 | * 每30秒检查一次正在处理中的 Aideo 任务状态 |
| 25 | */ |
| 26 | @Cron(CronExpression.EVERY_30_SECONDS) |
| 27 | @Redlock(RedlockKey.AideoTaskStatusCheck, 60, { throwOnFailure: false }) |
| 28 | @WithLoggerContext() |
| 29 | async processAideoTaskStatus() { |
| 30 | this.logger.debug('开始检查 Aideo 任务状态') |
| 31 | |
| 32 | const generatingTasks = await this.aiLogRepo.listGeneratingByType(AiLogType.Aideo, AiLogChannel.Volcengine) |
| 33 | |
| 34 | if (generatingTasks.length === 0) { |
| 35 | return |
| 36 | } |
| 37 | |
| 38 | this.logger.debug(`找到 ${generatingTasks.length} 个正在处理中的 Aideo 任务`) |
| 39 | |
| 40 | for (const task of generatingTasks) { |
| 41 | await this.processTask(task) |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * 处理单个任务 |
| 47 | */ |
| 48 | private async processTask(task: AiLog) { |
| 49 | try { |
| 50 | await this.aideoService.processAideoTask(task) |
| 51 | } |
| 52 | catch (error) { |
| 53 | this.logger.error({ error, taskId: task.id }, '处理 Aideo 任务失败') |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 |