import { Injectable, Logger } from '@nestjs/common'; import { Interval } from '@nestjs/schedule'; import { ArtworkStatus, AuditStatus, BlockchainProof, Prisma, ProofStatus, TraceCodeStatus } from '@prisma/client'; import { randomBytes, randomUUID } from 'crypto'; import { DEFAULT_CERTIFICATE_TEXT_TEMPLATE, ErrorCode, renderCertificateText, TRACE_CODE_PATTERN } from '@artveris/shared'; import { BusinessException } from '../common/exceptions/business.exception'; import { PrismaService } from '../prisma/prisma.service'; import { SettingsService } from '../settings/settings.service'; import { DepositEnvironment, DepositProvider, DepositRejected, presentStoredCertificate } from './deposit.provider'; interface CertificateRequest { version: 1; environment: DepositEnvironment; appId: string; address: string; operateId: string; text: string; } const ACTIVE_STATES = ['PENDING', 'SUBMITTING', 'WAITING', 'CHECKING']; const MAX_CHECKS = 8; const UNREACHABLE_MESSAGE = '暂时联系不上存证服务,证书没有生成。'; function depositUnreachable(error: unknown) { const texts: string[] = []; let current: unknown = error; for (let depth = 0; depth < 3 && current instanceof Error; depth += 1) { texts.push(current.message); const code = (current as { code?: unknown }).code; if (typeof code === 'string') texts.push(code); current = (current as { cause?: unknown }).cause; } return /ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ECONNRESET/.test(texts.join(' ')); } @Injectable() export class DepositCertificateService { private readonly logger = new Logger(DepositCertificateService.name); private running = false; constructor(private readonly prisma: PrismaService, private readonly settings: SettingsService) {} private async eligible(shortCode: string) { if (!TRACE_CODE_PATTERN.test(shortCode)) throw new BusinessException(ErrorCode.NOT_FOUND, '追溯码不可用', 404); const code = await this.prisma.traceCode.findUnique({ where: { shortCode }, include: { artwork: { include: { template: { include: { fields: true } } } }, proofs: true }, }); const proof = code?.proofs[0]; if (!code || code.status !== TraceCodeStatus.ACTIVE || code.artwork.deletedAt || code.artwork.status !== ArtworkStatus.ACTIVE || code.artwork.auditStatus !== AuditStatus.APPROVED || !proof || proof.status !== ProofStatus.ONCHAIN || !proof.txHash || proof.chainName !== '天河链') { throw new BusinessException(ErrorCode.NOT_FOUND, '当前实物暂不支持出证', 404); } return { code, proof }; } private async view(proof: BlockchainProof, artist?: string | null) { const request = proof.certificateRequest as unknown as CertificateRequest | null; const certificate = request && proof.certificateState === 'READY' ? presentStoredCertificate(proof.certificateUrl, request.environment, request.address, request.text, await this.settings.get('certificateAuthorMode'), artist) : null; const status = proof.certificateState === 'READY' && !certificate ? 'FAILED' : proof.certificateState; return { status, generatedAt: proof.certificateGeneratedAt, certificate: certificate && request ? { ...certificate, environment: request.environment } : certificate, message: status === 'READY' ? null : proof.certificateError, }; } /** No remote calls, writes, activation, or query-count changes. */ async status(shortCode: string) { const { code, proof } = await this.eligible(shortCode); return this.view(proof, code.artwork.artist); } async request(shortCode: string) { const { code, proof } = await this.eligible(shortCode); if (proof.certificateState === 'READY') return this.view(proof, code.artwork.artist); const settings = await this.settings.getAllRaw(); const retryUnreachable = proof.certificateState === 'FAILED' && !proof.certificateUrl && proof.certificateError === UNREACHABLE_MESSAGE; if (proof.certificateState !== 'NONE' && !retryUnreachable) { // An uncertain submission is never submitted again. User action only resumes queries. if (proof.certificateState === 'UNKNOWN' && (!proof.certificateNextCheck || proof.certificateNextCheck <= new Date())) { await this.prisma.blockchainProof.updateMany({ where: { id: proof.id, certificateState: 'UNKNOWN', certificateNextCheck: { lte: new Date() } }, data: { certificateState: 'WAITING', certificateAttempts: 0, certificateNextCheck: new Date() }, }); } return this.view((await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } })), code.artwork.artist); } const environment = settings.tianheEnv as DepositEnvironment; if (settings.blockchainDriver !== 'tianhe' || !['test', 'production'].includes(environment) || !settings.tianheAppId || !settings.tianheAppKey || !/^0x[0-9a-f]{40}$/i.test(settings.tianheWalletAddress || '')) { throw new BusinessException(ErrorCode.BAD_REQUEST, '平台存证配置尚未就绪'); } const now = new Date(); // “版本”是作品模板的动态字段;按显示名查键,不能假定数据库键叫version。 const versionField = code.artwork.template?.fields.find(field => field.label.trim() === '版本'); const dynamic = code.artwork.dynamicFields as Record | null; const versionValue = versionField ? dynamic?.[versionField.fieldKey] : undefined; let text: string; try { text = renderCertificateText(settings.certificateTextTemplate ?? DEFAULT_CERTIFICATE_TEXT_TEMPLATE, { '作品名称': code.artwork.title, '版本': typeof versionValue === 'string' || typeof versionValue === 'number' ? String(versionValue) : '', '追溯码': code.shortCode, '档案编号': code.artwork.archiveNo || '', '作者': code.artwork.artist || '', }); } catch { throw new BusinessException(ErrorCode.BAD_REQUEST, '证书文本模板配置无效,请联系平台管理员'); } if (!text || text.length > 2000) throw new BusinessException(ErrorCode.BAD_REQUEST, '证书文本为空或过长,请检查模板及作品字段'); const request: CertificateRequest = { version: 1, environment, appId: settings.tianheAppId, address: settings.tianheWalletAddress, operateId: `avc${randomBytes(8).toString('hex')}`, // 冻结首次申请时渲染出的文本,模板变化不会改变已提交或已生成证书。 text, }; // A single conditional write claims this item; concurrent callers cannot // replace the winner's frozen evidence or operation id. No daily quota. await this.prisma.blockchainProof.updateMany({ where: { id: proof.id, certificateState: retryUnreachable ? 'FAILED' : 'NONE', status: ProofStatus.ONCHAIN }, data: { certificateState: 'PENDING', certificateRequest: request as unknown as Prisma.InputJsonObject, certificateError: null, certificateRequestedAt: now, certificateNextCheck: now, }, }); return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }), code.artwork.artist); } /** Persistent DB-backed work: only explicit requests enter PENDING. Restart-safe. */ @Interval(5000) async tick() { if (this.running) return; this.running = true; try { const now = new Date(); const rows = await this.prisma.blockchainProof.findMany({ where: { certificateState: { in: ACTIVE_STATES }, certificateNextCheck: { lte: now }, OR: [{ certificateLeaseUntil: null }, { certificateLeaseUntil: { lt: now } }] }, orderBy: { certificateRequestedAt: 'asc' }, take: 5, }); for (const row of rows) await this.process(row); } catch { this.logger.warn('Certificate worker unavailable; persisted requests will be checked again'); } finally { this.running = false; } } async process(row: BlockchainProof) { const now = new Date(); const token = randomUUID(); const submit = row.certificateState === 'PENDING'; const claimed = await this.prisma.blockchainProof.updateMany({ where: { id: row.id, certificateState: row.certificateState, certificateAttempts: row.certificateAttempts, certificateNextCheck: { lte: now }, OR: [{ certificateLeaseUntil: null }, { certificateLeaseUntil: { lt: now } }] }, data: { certificateState: submit ? 'SUBMITTING' : 'CHECKING', certificateLeaseToken: token, certificateLeaseUntil: new Date(now.getTime() + 120_000) }, }); if (!claimed.count) return; const finish = (data: Prisma.BlockchainProofUpdateManyMutationInput) => this.prisma.blockchainProof.updateMany({ where: { id: row.id, certificateLeaseToken: token }, data: { ...data, certificateLeaseUntil: null, certificateLeaseToken: null }, }); const attempts = row.certificateAttempts + 1; let accepted = false; try { const request = row.certificateRequest as unknown as CertificateRequest; const settings = await this.settings.getAllRaw(); if (!request || request.version !== 1 || settings.blockchainDriver !== 'tianhe' || settings.tianheEnv !== request.environment || settings.tianheAppId !== request.appId || settings.tianheWalletAddress !== request.address || !settings.tianheAppKey) { await finish({ certificateState: 'UNKNOWN', certificateError: '存证环境或钱包已变更,请恢复原配置后继续查询', certificateNextCheck: now }); return; } const provider = new DepositProvider(request.environment, request.appId, settings.tianheAppKey); if (submit) { const current = await this.prisma.traceCode.findUnique({ where: { id: row.traceCodeId }, select: { shortCode: true } }); try { await this.eligible(current?.shortCode || ''); } catch { await finish({ certificateState: 'FAILED', certificateError: '实物当前状态不允许出证', certificateNextCheck: null }); return; } await provider.submit(request.address, request.operateId, request.text); accepted = true; await finish({ certificateState: 'WAITING', certificateError: null, certificateNextCheck: new Date(Date.now() + 5000) }); return; } // A crashed/timed-out SUBMITTING job also comes here, never back to submit(). const result = await provider.query(request.address, request.operateId); const exists = result?.operateId === request.operateId && (Boolean(result?.createTime) || Boolean(result?.txHash)); const url = exists ? await provider.certificate(request.address, request.operateId, request.text) : null; if (url) { await finish({ certificateState: 'READY', certificateUrl: url, certificateGeneratedAt: new Date(), certificateError: null, certificateNextCheck: null, certificateAttempts: attempts }); return; } await finish({ certificateState: attempts >= MAX_CHECKS ? 'UNKNOWN' : 'WAITING', certificateAttempts: attempts, certificateError: '证书尚未就绪,后续仅查询原存证', certificateNextCheck: new Date(Date.now() + 30_000) }); } catch (error) { const rejected = submit && !accepted && error instanceof DepositRejected; const unreachable = submit && !accepted && depositUnreachable(error); await finish({ certificateState: rejected || unreachable ? 'FAILED' : attempts >= MAX_CHECKS ? 'UNKNOWN' : 'WAITING', certificateAttempts: attempts, certificateError: rejected ? '存证提交被拒绝,请联系平台管理员' : unreachable ? UNREACHABLE_MESSAGE : '远端结果暂未确认,后续仅查询原存证', certificateNextCheck: rejected || unreachable ? null : new Date(Date.now() + 30_000), }); } } }