import { InjectQueue } from '@nestjs/bullmq'; import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; import { Interval } from '@nestjs/schedule'; import { JobItemStatus, JobStatus, JobType, Prisma } from '@prisma/client'; import { Queue } from 'bullmq'; import { QUEUE_NAMES } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; const STALE_MS = 5 * 60_000; @Injectable() export class BatchOutboundRecoveryService implements OnModuleInit { private readonly logger = new Logger(BatchOutboundRecoveryService.name); private recovering = false; constructor( private readonly prisma: PrismaService, @InjectQueue(QUEUE_NAMES.BATCH_OUTBOUND) private readonly queue: Queue, ) {} async onModuleInit(): Promise { await this.recoverPending(); } @Interval(60_000) async recoverPending(): Promise { if (this.recovering) return; this.recovering = true; try { const staleBefore = new Date(Date.now() - STALE_MS); const jobs = await this.prisma.job.findMany({ where: { type: JobType.BATCH_OUTBOUND, OR: [ { status: JobStatus.PENDING }, { status: JobStatus.PROCESSING, updatedAt: { lt: staleBefore } }, ], }, orderBy: { createdAt: 'asc' }, take: 20, }); for (const job of jobs) { const payload = job.payload && typeof job.payload === 'object' && !Array.isArray(job.payload) ? job.payload as Record : {}; if (payload.preparing === true) { await this.enqueue(job.id); continue; } if (job.status === JobStatus.PROCESSING) { await this.prisma.$transaction([ this.prisma.jobItem.updateMany({ where: { jobId: job.id, status: JobItemStatus.PROCESSING, updatedAt: { lt: staleBefore } }, data: { status: JobItemStatus.PENDING, error: null }, }), this.prisma.job.update({ where: { id: job.id }, data: { status: JobStatus.PENDING } }), ]); } await this.enqueue(job.id); } } finally { this.recovering = false; } } private async enqueue(jobId: string) { const bullId = `batch-outbound-${jobId}`; try { const existing = await this.queue.getJob(bullId); if (existing) { const state = await existing.getState(); if (state === 'failed') await existing.retry(); else if (state === 'completed') { await existing.remove(); await this.queue.add('batch-outbound', { jobId }, { jobId: bullId }); } } else { await this.queue.add('batch-outbound', { jobId }, { jobId: bullId }); } } catch (error) { this.logger.warn(`恢复批量出库任务失败:${jobId} ${(error as Error).message}`); } } }