fix: 出证连接失败时停止查询并允许重试

This commit is contained in:
Nixevol
2026-11-15 13:56:44 +08:00
parent e17ebe53df
commit 72e99daa7b
6 changed files with 51 additions and 13 deletions
@@ -50,6 +50,19 @@ describe('Consumer certificate lifecycle', () => {
await service.process(row);
expect(submit).not.toHaveBeenCalled();
});
it('a refused connection on submit fails instead of querying an unsent deposit', async () => {
const { service, row, prisma } = fixture();
const cause = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:443'), { code: 'ECONNREFUSED' });
const failure = new TypeError('fetch failed');
(failure as { cause?: unknown }).cause = cause;
jest.spyOn(DepositProvider.prototype, 'submit').mockRejectedValue(failure);
await service.process(row);
expect(prisma.blockchainProof.updateMany.mock.calls[1][0].data).toMatchObject({
certificateState: 'FAILED',
certificateError: '暂时联系不上存证服务,证书没有生成。',
certificateNextCheck: null,
});
});
it('a submission timeout changes to query-only, preserving the exact operation id', async () => {
const { service, row, prisma } = fixture();
const submit = jest.spyOn(DepositProvider.prototype, 'submit').mockRejectedValue(new Error('timeout'));
@@ -19,6 +19,19 @@ interface CertificateRequest {
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 {
@@ -46,10 +59,12 @@ export class DepositCertificateService {
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: proof.certificateState === 'READY' && !certificate ? 'FAILED' : proof.certificateState,
status,
generatedAt: proof.certificateGeneratedAt,
certificate: certificate && request ? { ...certificate, environment: request.environment } : certificate,
message: status === 'READY' ? null : proof.certificateError,
};
}
@@ -63,7 +78,8 @@ export class DepositCertificateService {
const { code, proof } = await this.eligible(shortCode);
if (proof.certificateState === 'READY') return this.view(proof, code.artwork.artist);
const settings = await this.settings.getAllRaw();
if (proof.certificateState !== 'NONE') {
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({
@@ -103,10 +119,10 @@ export class DepositCertificateService {
// 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: 'NONE', status: ProofStatus.ONCHAIN },
where: { id: proof.id, certificateState: retryUnreachable ? 'FAILED' : 'NONE', status: ProofStatus.ONCHAIN },
data: {
certificateState: 'PENDING', certificateRequest: request as unknown as Prisma.InputJsonObject,
certificateRequestedAt: now, certificateNextCheck: now,
certificateError: null, certificateRequestedAt: now, certificateNextCheck: now,
},
});
return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }), code.artwork.artist);
@@ -184,9 +200,13 @@ export class DepositCertificateService {
certificateNextCheck: new Date(Date.now() + 30_000) });
} catch (error) {
const rejected = submit && !accepted && error instanceof DepositRejected;
await finish({ certificateState: rejected ? 'FAILED' : attempts >= MAX_CHECKS ? 'UNKNOWN' : 'WAITING',
certificateAttempts: attempts, certificateError: rejected ? '存证提交被拒绝,请联系平台管理员' : '远端结果暂未确认,后续仅查询原存证',
certificateNextCheck: new Date(Date.now() + 30_000) });
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),
});
}
}
}
+1
View File
@@ -77,6 +77,7 @@ export interface TraceCertificateResult {
status: 'NONE' | 'PENDING' | 'SUBMITTING' | 'CHECKING' | 'WAITING' | 'READY' | 'UNKNOWN' | 'FAILED';
generatedAt: string | null;
certificate: TraceCertificateRecord | null;
message?: string | null;
}
export function requestTraceCertificate(shortCode: string): Promise<TraceCertificateResult> {
return instance.post(`/public/trace/${encodeURIComponent(shortCode)}/certificate`, {}, { timeout: 90_000 }) as unknown as Promise<TraceCertificateResult>;
+1 -1
View File
@@ -89,7 +89,7 @@
"certificatePreview": "预览模式不生成证书。",
"certificateRequestFailed": "暂时无法生成证书,请稍后再试或联系平台。",
"certificateCheckAgain": "重新查询",
"certificateFailed": "存证申请未成功,请联系平台处理。",
"certificateFailed": "暂时联系不上存证服务,证书没有生成。",
"certificateUnavailable": "暂时无法查询证书,请稍后重试。",
"certificateRetrieving": "正在调取存证数据",
"certificateAcquiring": "获取存证证书",
+8 -4
View File
@@ -8,7 +8,7 @@
<p v-if="preview" class="subpage-note">{{ t('chain.certificatePreview') }}</p>
<template v-else>
<p v-if="certificateError" class="subpage-note" role="alert">{{ certificateError }}</p>
<button v-if="certificateError && retryable" type="button" class="subpage-action" @click="load">
<button v-if="certificateError && retryable" type="button" class="subpage-action" @click="load(true)">
{{ t('chain.certificateCheckAgain') }}
</button>
<template v-else-if="certificateRecord">
@@ -103,7 +103,11 @@ async function showCertificateResult(result: TraceCertificateResult, run: number
measure();
return;
}
if (result.status === 'FAILED') return failCertificate('chain.certificateFailed', false);
if (result.status === 'FAILED') {
certificateError.value = result.message || t('chain.certificateFailed');
retryable.value = true;
return;
}
if (result.status === 'UNKNOWN') return failCertificate('chain.certificateDelayed');
if (result.status === 'NONE') return failCertificate('chain.certificateUnavailable');
certificatePhase.value = 1;
@@ -113,7 +117,7 @@ async function showCertificateResult(result: TraceCertificateResult, run: number
catch { if (run === certificateRun) failCertificate('chain.certificateUnavailable'); }
}, 5000);
}
async function load() {
async function load(retry = false) {
if (preview) return;
certificateRun += 1;
if (certificateTimer) clearTimeout(certificateTimer);
@@ -127,7 +131,7 @@ async function load() {
const cached = await fetchTraceCertificate(code);
if (run !== certificateRun) return;
certificatePhase.value = 1;
const result = cached.status === 'NONE' || cached.status === 'UNKNOWN'
const result = retry || cached.status === 'NONE' || cached.status === 'UNKNOWN'
? await requestTraceCertificate(code) : cached;
showCertificateResult(result, run);
} catch {
+1 -1
View File
@@ -8,7 +8,7 @@
扫码页区块链模块底部左侧为“查看存证”、右侧靠右为“查看证书”,均不显示箭头。仅明确 ONCHAIN 且有交易哈希的天河链实物显示证书按钮,未上链或处理中均不显示。仅已激活、正常、已审核通过的实物可申请。普通页面打开、刷新与证书状态 GET 都不会提交存证;后台预览模式按钮禁用,不产生付费副作用。
「查看存证」和「查看证书」都进入本平台独立页面,不使用弹窗,手机上按屏幕宽度缩放,证书内部排版不改。证书页底部按天河链说明区展示区块链 ID、SHA256 和下载按钮,说明用悬停提示;哈希只显示文字,不跳转到天河链。证书页文案依次为“正在调取存证数据”“获取存证证书”“正在整理存证证书”。先读取已保存的证书字段,已生成的马上显示。没有时才 POST 申请,并短时间查询几次;仍未完成就停止转圈并提示稍后再查,不再空转数分钟。证书按天河链证书页的版式在浏览器中绘制,下载也由浏览器生成 PNG。之后只读本地。交易详情里的 Gas、发送方和日志在第一次查到前留空,查全后写入本地,之后不再请求天河链。离开页面只停止当前等待,后台已提交任务继续完成。再次进入直接读取数据库已有记录,不重复生成。公开接口不返回天河链网址,客户页面也不能跳转到天河链。
「查看存证」和「查看证书」都进入本平台独立页面,不使用弹窗,手机上按屏幕宽度缩放,证书内部排版不改。证书页底部按天河链说明区展示区块链 ID、SHA256 和下载按钮,说明用悬停提示;哈希只显示文字,不跳转到天河链。证书页文案依次为“正在调取存证数据”“获取存证证书”“正在整理存证证书”。先读取已保存的证书字段,已生成的马上显示。没有时才 POST 申请,并短时间查询几次;仍未完成就停止转圈并提示稍后再查,不再空转数分钟。提交在收到任何响应前就连接失败时,记为未生成并可以重试;请求发出后超时则只查询原操作号,避免重复付费。证书按天河链证书页的版式在浏览器中绘制,下载也由浏览器生成 PNG。之后只读本地。交易详情里的 Gas、发送方和日志在第一次查到前留空,查全后写入本地,之后不再请求天河链。离开页面只停止当前等待,后台已提交任务继续完成。再次进入直接读取数据库已有记录,不重复生成。公开接口不返回天河链网址,客户页面也不能跳转到天河链。
新证书首次点击时按系统设置 `certificateTextTemplate` 渲染并冻结正文,默认 `{{作品名称}} {{版本}}`,例如“十二生肖莲花手工杯 一个装”。设置入口为“系统设置 → 区块链 → 证书文本模板”,帮助按钮点击后才弹出字段说明。支持 `{{作品名称}}`、`{{版本}}`、`{{追溯码}}`、`{{档案编号}}`、`{{作者}}`,可自由排序、重复使用并插入普通文本或换行。版本按作品模板中显示名为“版本”的字段取值,当前数据键为 `size`,不能硬编码成 `version`。