fix: 优化天河链确认策略

This commit is contained in:
Nixevol
2026-07-06 19:43:00 +08:00
parent 628a5a4465
commit 7480e4d256
9 changed files with 107 additions and 22 deletions
+1
View File
@@ -64,6 +64,7 @@ export const traceCodeApi = {
qrUrl: (id: string) => `/api/trace-codes/${id}/qrcode`,
qrBlob: (id: string) => download(`/trace-codes/${id}/qrcode`),
onchain: (id: string) => post(`/trace-codes/${id}/onchain`, {}),
confirmProof: (id: number) => post(`/blockchain-proofs/${id}/confirm`, {}),
// 分组
groups: (params?: object) => get<any[]>('/trace-code-groups', params),
createGroup: (data: { name: string; remark?: string }) => post('/trace-code-groups', data),
+48 -3
View File
@@ -263,6 +263,7 @@ const qrSrc = ref('');
const qrUrl = ref('');
let qrBlobUrl = '';
const exporting = ref(false);
const confirmingProofIds = ref<number[]>([]);
const groupModal = ref(false);
const groupForm = reactive<{ name: string }>({ name: '' });
@@ -311,7 +312,7 @@ const columns = computed<DataTableColumns<any>>(() => {
align: 'center',
render: (r) =>
r.latestAnyProof
? h(NTag, { size: 'small', type: statusType(r.latestAnyProof.status) }, { default: () => t(`common.status.${r.latestAnyProof.status}`) })
? h(NTag, { size: 'small', type: proofStatusType(r.latestAnyProof) }, { default: () => proofStatusText(r.latestAnyProof) })
: h(NText, { depth: 3 }, { default: () => t('pages.traceCode.noOnchain') }),
},
{ title: () => t('pages.traceCode.shortCode'), key: 'shortCode', width: 120, align: 'center', ellipsis: { tooltip: true } },
@@ -615,17 +616,23 @@ function batchDelete() {
}
function rowActionOptions(row: any): DropdownOption[] {
return [
const options: DropdownOption[] = [
{ label: t('pages.traceCode.changeGroup'), key: 'changeGroup', children: rowGroupOptions.value },
{ label: t('pages.traceCode.changeBatch'), key: 'batch:open' },
{ label: t('pages.traceCode.registerOutbound'), key: 'outbound:open' },
];
if (canManualConfirm(row.latestAnyProof)) {
options.push({ label: t('pages.traceCode.reconfirmOnchain'), key: 'onchain:confirm' });
}
options.push(
{ type: 'divider', key: 'divider-1' },
{
label: row.status === TraceCodeStatus.DISABLED ? t('pages.traceCode.enableOne') : t('pages.traceCode.disableOne'),
key: row.status === TraceCodeStatus.DISABLED ? 'status:enable' : 'status:disable',
},
{ label: t('common.action.delete'), key: 'delete' },
];
);
return options;
}
async function onRowAction(row: any, key: string) {
@@ -648,6 +655,11 @@ async function onRowAction(row: any, key: string) {
return;
}
if (key === 'onchain:confirm') {
await confirmProof(row.latestAnyProof);
return;
}
if (key === 'status:disable' || key === 'status:enable') {
await traceCodeApi.update(String(row.id), { disabled: key === 'status:disable' });
message.success(t('common.msg.operationSuccess'));
@@ -673,6 +685,39 @@ async function onRowAction(row: any, key: string) {
}
}
function proofRaw(proof: any) {
return proof?.rawResponse && typeof proof.rawResponse === 'object' ? proof.rawResponse : {};
}
function isUnconfirmedProof(proof: any) {
return proof?.status === 'CONFIRMING' && proofRaw(proof).confirmationManualRequired === true;
}
function proofStatusText(proof: any) {
return isUnconfirmedProof(proof) ? t('pages.traceCode.unconfirmed') : t(`common.status.${proof.status}`);
}
function proofStatusType(proof: any): 'default' | 'success' | 'warning' | 'error' | 'info' {
return isUnconfirmedProof(proof) ? 'warning' : statusType(proof?.status);
}
function canManualConfirm(proof: any) {
return Boolean(proof?.id && proof?.txHash && proof.status !== 'ONCHAIN');
}
async function confirmProof(proof: any) {
if (!canManualConfirm(proof) || confirmingProofIds.value.includes(proof.id)) return;
confirmingProofIds.value.push(proof.id);
try {
await traceCodeApi.confirmProof(proof.id);
message.success(t('pages.traceCode.confirmSubmitted'));
await load();
emit('changed');
} finally {
confirmingProofIds.value = confirmingProofIds.value.filter((id) => id !== proof.id);
}
}
function openBatchModal(row?: any) {
batchTarget.value = row || null;
batchForm.batchValue = row?.batch?.id ?? null;
+3
View File
@@ -346,6 +346,9 @@
"outRegistered": "Recorded",
"notOutbound": "Not Outbound",
"noOnchain": "Not On-chain",
"unconfirmed": "Unconfirmed",
"reconfirmOnchain": "Reconfirm",
"confirmSubmitted": "Reconfirm task submitted",
"tableFilter": "Filter",
"registerOutbound": "Record Outbound / Chain",
"enableOne": "Enable",
+3
View File
@@ -346,6 +346,9 @@
"outRegistered": "已登记",
"notOutbound": "未出库",
"noOnchain": "未上链",
"unconfirmed": "未确认",
"reconfirmOnchain": "重新确认",
"confirmSubmitted": "已提交重新确认任务",
"tableFilter": "筛选",
"registerOutbound": "登记出库/上链",
"enableOne": "启用",
@@ -78,4 +78,23 @@ export class AttestationService {
await this.queue.add('onchain', { proofId });
return { success: true };
}
async confirm(proofId: number) {
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '存证记录不存在', 404);
if (proof.status === ProofStatus.ONCHAIN) return { success: true };
if (!proof.txHash) throw new BusinessException(ErrorCode.BAD_REQUEST, '缺少交易哈希,无法重新确认');
await this.prisma.blockchainProof.update({
where: { id: proofId },
data: {
status: ProofStatus.CONFIRMING,
rawResponse: {
...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}),
manualConfirmQueuedAt: new Date().toISOString(),
},
},
});
await this.queue.add('confirm-onchain', { proofId, action: 'confirm', confirmAttempt: 1, manual: true });
return { success: true };
}
}
@@ -23,4 +23,11 @@ export class BlockchainController {
retry(@Param('id', ParseIntPipe) id: number) {
return this.attestation.retry(id);
}
@Post('blockchain-proofs/:id/confirm')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '重新查询链上确认结果' })
confirm(@Param('id', ParseIntPipe) id: number) {
return this.attestation.confirm(id);
}
}
+24 -18
View File
@@ -10,10 +10,12 @@ interface OnchainJobData {
proofId: number;
action?: 'attest' | 'confirm';
confirmAttempt?: number;
manual?: boolean;
}
const CONFIRM_DELAY_MS = 30_000;
const MAX_CONFIRM_ATTEMPTS = 20;
const FIRST_CONFIRM_DELAY_MS = 30_000;
const SECOND_CONFIRM_DELAY_MS = 60_000;
const MAX_AUTO_CONFIRM_ATTEMPTS = 2;
function requestMeta(raw: unknown): Record<string, unknown> | undefined {
if (!raw || typeof raw !== 'object') return undefined;
@@ -43,7 +45,7 @@ export class OnchainProcessor extends WorkerHost {
async process(job: Job<OnchainJobData>): Promise<void> {
if (job.data.action === 'confirm') {
await this.confirm(job.data.proofId, job.data.confirmAttempt || 1);
await this.confirm(job.data.proofId, job.data.confirmAttempt || 1, Boolean(job.data.manual));
return;
}
await this.attest(job.data.proofId);
@@ -74,7 +76,7 @@ export class OnchainProcessor extends WorkerHost {
},
});
if (result.confirmationRequired) {
await this.scheduleConfirm(proofId, 1);
await this.scheduleConfirm(proofId, 1, FIRST_CONFIRM_DELAY_MS);
this.logger.log(`存证 ${proofId} 已提交链上,等待确认`);
} else {
this.logger.log(`存证 ${proofId} 上链成功`);
@@ -96,9 +98,10 @@ export class OnchainProcessor extends WorkerHost {
}
}
private async confirm(proofId: number, attempt: number): Promise<void> {
private async confirm(proofId: number, attempt: number, manual = false): Promise<void> {
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
if (!proof || proof.status !== ProofStatus.CONFIRMING) return;
if (!proof || proof.status === ProofStatus.ONCHAIN) return;
if (proof.status !== ProofStatus.CONFIRMING && !manual) return;
if (!proof.txHash) {
await this.markConfirmFailed(proofId, proof.rawResponse, '缺少交易哈希,无法确认链上结果', attempt);
return;
@@ -130,39 +133,42 @@ export class OnchainProcessor extends WorkerHost {
return;
}
await this.recordWaiting(proofId, proof.rawResponse, result.raw, attempt);
if (attempt >= MAX_CONFIRM_ATTEMPTS) {
await this.markConfirmFailed(proofId, proof.rawResponse, '超过最大确认次数,仍未查询到链上区块信息', attempt);
await this.recordWaiting(proofId, proof.rawResponse, result.raw, attempt, manual);
if (manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS) {
this.logger.warn(`存证 ${proofId} 尚未查询到链上确认信息,等待手动重新确认`);
return;
}
await this.scheduleConfirm(proofId, attempt + 1);
await this.scheduleConfirm(proofId, attempt + 1, SECOND_CONFIRM_DELAY_MS);
} catch (e) {
const message = (e as Error).message;
if (attempt >= MAX_CONFIRM_ATTEMPTS) {
await this.markConfirmFailed(proofId, proof.rawResponse, message, attempt);
if (manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS) {
await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt, manual);
return;
}
await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt);
await this.scheduleConfirm(proofId, attempt + 1);
await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt, manual);
await this.scheduleConfirm(proofId, attempt + 1, SECOND_CONFIRM_DELAY_MS);
}
}
private scheduleConfirm(proofId: number, confirmAttempt: number) {
private scheduleConfirm(proofId: number, confirmAttempt: number, delay: number, manual = false) {
return this.queue.add(
'confirm-onchain',
{ proofId, action: 'confirm', confirmAttempt } satisfies OnchainJobData,
{ delay: CONFIRM_DELAY_MS },
{ proofId, action: 'confirm', confirmAttempt, manual } satisfies OnchainJobData,
{ delay },
);
}
private recordWaiting(proofId: number, raw: unknown, confirmation: Record<string, unknown>, attempt: number) {
private recordWaiting(proofId: number, raw: unknown, confirmation: Record<string, unknown>, attempt: number, manual: boolean) {
return this.prisma.blockchainProof.update({
where: { id: proofId },
data: {
status: ProofStatus.CONFIRMING,
rawResponse: jsonObject({
...rawObject(raw),
confirmation,
confirmationAttempts: attempt,
confirmationManualRequired: manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS,
lastConfirmMode: manual ? 'manual' : 'auto',
lastConfirmCheckedAt: new Date().toISOString(),
}),
},
@@ -39,6 +39,7 @@ function actionOf(method: string, path: string): string {
if (path.includes('/download')) return 'download';
if (path.includes('/upload')) return 'upload';
if (path.includes('/audit')) return 'audit';
if (path.includes('/blockchain-proofs') && path.includes('/confirm')) return 'onchain';
if (path.includes('/onchain')) return 'onchain';
if (path.includes('/backup')) return 'backup';
if (path.includes('/restore')) return 'restore';