fix: 移除消费者出证每日上限并保留单件防重
This commit is contained in:
@@ -807,8 +807,7 @@
|
||||
"tianheManualHint": "Enter the saved User ID and User Key. The system verifies them with TiChain before saving (for reusing the existing wallet after reinstall/migration).",
|
||||
"tianheManualUserIdPh": "e.g. artveris-platform",
|
||||
"tianheManualUserKeyPh": "The User Key you saved offline",
|
||||
"certificateEnabled": "On-demand certificates",
|
||||
"certificateDailyLimit": "Daily new certificate limit"
|
||||
"certificateEnabled": "On-demand certificates"
|
||||
},
|
||||
"profile": {
|
||||
"title": "Personal Info",
|
||||
|
||||
@@ -807,8 +807,7 @@
|
||||
"tianheManualHint": "输入已保存的 User ID 与 User Key,系统将向天河链校验后保存(用于重装/迁移后复用既有钱包)。",
|
||||
"tianheManualUserIdPh": "如 artveris-platform",
|
||||
"tianheManualUserKeyPh": "已离线保存的 User Key",
|
||||
"certificateEnabled": "扫码页按需出证",
|
||||
"certificateDailyLimit": "每日新增证书上限"
|
||||
"certificateEnabled": "扫码页按需出证"
|
||||
},
|
||||
"profile": {
|
||||
"title": "个人信息",
|
||||
|
||||
@@ -96,9 +96,6 @@
|
||||
<n-form-item :label="t('pages.settings.certificateEnabled')">
|
||||
<n-switch v-model:value="form.certificateEnabled" />
|
||||
</n-form-item>
|
||||
<n-form-item :label="t('pages.settings.certificateDailyLimit')">
|
||||
<n-input-number v-model:value="form.certificateDailyLimit" :min="0" :max="10000" :precision="0" />
|
||||
</n-form-item>
|
||||
<n-form-item :label="t('pages.settings.tianheEnv')">
|
||||
<n-select v-model:value="form.tianheEnv" :options="tianheEnvOptions" @update:value="onTianheEnvChange" />
|
||||
</n-form-item>
|
||||
@@ -324,7 +321,6 @@ const form = reactive({
|
||||
blockchainDriver: 'mock',
|
||||
tianheEnv: 'test',
|
||||
certificateEnabled: true,
|
||||
certificateDailyLimit: 100,
|
||||
tianheBaseUrl: TIANHE_TEST_URL,
|
||||
tianheAppId: '',
|
||||
tianheAppKey: '',
|
||||
@@ -371,7 +367,6 @@ async function load() {
|
||||
form.blockchainDriver = s.blockchainDriver || 'mock';
|
||||
form.tianheEnv = s.tianheEnv || 'test';
|
||||
form.certificateEnabled = s.certificateEnabled !== 'false';
|
||||
form.certificateDailyLimit = Number(s.certificateDailyLimit ?? '100');
|
||||
form.tianheBaseUrl = s.tianheBaseUrl || TIANHE_TEST_URL;
|
||||
form.tianheAppId = s.tianheAppId || '';
|
||||
form.tianheAppKey = s.tianheAppKey || '';
|
||||
@@ -562,7 +557,6 @@ async function save() {
|
||||
blockchainDriver: form.blockchainDriver,
|
||||
tianheEnv: form.tianheEnv,
|
||||
certificateEnabled: String(form.certificateEnabled),
|
||||
certificateDailyLimit: String(form.certificateDailyLimit ?? 0),
|
||||
tianheBaseUrl: form.tianheBaseUrl,
|
||||
tianheAppId: form.tianheAppId,
|
||||
tianheAppKey: form.tianheAppKey,
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Daily certificate generation is unlimited; keep the per-item idempotency state.
|
||||
DELETE FROM `system_setting` WHERE `key` IN ('certificateDailyLimit', 'certificateDailyQuota');
|
||||
@@ -2,7 +2,7 @@ import { DepositCertificateService } from './deposit-certificate.service';
|
||||
import { DepositProvider } from './deposit.provider';
|
||||
|
||||
const settings = {
|
||||
certificateEnabled: 'true', certificateDailyLimit: '100', blockchainDriver: 'tianhe',
|
||||
certificateEnabled: 'true', blockchainDriver: 'tianhe',
|
||||
tianheEnv: 'test', tianheAppId: 'app', tianheAppKey: 'key', tianheWalletAddress: '0x' + 'a'.repeat(40),
|
||||
};
|
||||
function fixture(state = 'PENDING') {
|
||||
@@ -78,16 +78,31 @@ describe('Consumer certificate lifecycle', () => {
|
||||
await expect(service.request('123456000001')).rejects.toThrow();
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it('uses an atomic NONE claim so a stale concurrent transaction cannot overwrite the request or consume quota', async () => {
|
||||
const { service, prisma } = fixture('NONE');
|
||||
const tx = {
|
||||
systemSetting: { upsert: jest.fn(), update: jest.fn() },
|
||||
$queryRaw: jest.fn().mockResolvedValue([{ value: '2026-09-20:1' }]),
|
||||
blockchainProof: { updateMany: jest.fn().mockResolvedValue({ count: 0 }) },
|
||||
};
|
||||
prisma.$transaction.mockImplementation(async callback => callback(tx));
|
||||
it('ignores obsolete daily settings and claims an item without any quota transaction', async () => {
|
||||
const { service, prisma, config } = fixture('NONE');
|
||||
config.getAllRaw.mockResolvedValue({ ...settings, certificateDailyLimit: '0', certificateDailyQuota: '2026-09-20:999999' } as any);
|
||||
await service.request('123456000001');
|
||||
expect(tx.blockchainProof.updateMany).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 1, certificateState: 'NONE', status: 'ONCHAIN' } }));
|
||||
expect(tx.systemSetting.update).not.toHaveBeenCalled();
|
||||
expect(prisma.blockchainProof.updateMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: { id: 1, certificateState: 'NONE', status: 'ONCHAIN' },
|
||||
data: expect.objectContaining({ certificateState: 'PENDING' }),
|
||||
}));
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it('concurrent first clicks preserve the winning request snapshot and operation id', async () => {
|
||||
const { service, prisma, row } = fixture('NONE');
|
||||
let writes = 0;
|
||||
prisma.blockchainProof.updateMany.mockImplementation(async ({ where, data }: any) => {
|
||||
if (row.certificateState !== where.certificateState) return { count: 0 };
|
||||
Object.assign(row, data);
|
||||
writes++;
|
||||
return { count: 1 };
|
||||
});
|
||||
const results = await Promise.all(Array.from({ length: 10 }, () => service.request('123456000001')));
|
||||
const saved = row.certificateRequest;
|
||||
expect(writes).toBe(1);
|
||||
expect(results.every(result => result.status === 'PENDING')).toBe(true);
|
||||
await service.request('123456000001');
|
||||
expect(row.certificateRequest).toBe(saved);
|
||||
expect(writes).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -91,25 +91,14 @@ export class DepositCertificateService {
|
||||
`证据记录时间:${now.toISOString()}`,
|
||||
].join(';'),
|
||||
};
|
||||
// DB quota lock survives Redis restarts and serializes initial requests across workers.
|
||||
// No credentials or network calls inside the transaction.
|
||||
await this.prisma.$transaction(async tx => {
|
||||
const quotaKey = 'certificateDailyQuota';
|
||||
await tx.systemSetting.upsert({ where: { key: quotaKey }, create: { key: quotaKey, value: '' }, update: { key: quotaKey } });
|
||||
const [quota] = await tx.$queryRaw<Array<{ value: string }>>`SELECT value FROM system_setting WHERE \`key\` = ${quotaKey} FOR UPDATE`;
|
||||
// Use a conditional write, not a snapshot read: MySQL REPEATABLE READ can
|
||||
// retain an older NONE snapshot while this transaction waited for the lock.
|
||||
const claimed = await tx.blockchainProof.updateMany({ where: { id: proof.id, certificateState: 'NONE', status: ProofStatus.ONCHAIN }, data: {
|
||||
// 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 },
|
||||
data: {
|
||||
certificateState: 'PENDING', certificateRequest: request as unknown as Prisma.InputJsonObject,
|
||||
certificateRequestedAt: now, certificateNextCheck: now,
|
||||
} });
|
||||
if (!claimed.count) return;
|
||||
const day = new Date(now.getTime() + 8 * 3600_000).toISOString().slice(0, 10);
|
||||
const [quotaDay, quotaCount] = (quota?.value || '').split(':');
|
||||
const count = quotaDay === day ? Number(quotaCount) || 0 : 0;
|
||||
const limit = Math.min(10000, Math.max(0, Number(settings.certificateDailyLimit ?? '100') || 0));
|
||||
if (count >= limit) throw new BusinessException(ErrorCode.TOO_MANY_REQUESTS, '今日证书生成数量已达上限,请稍后再试', 429);
|
||||
await tx.systemSetting.update({ where: { key: quotaKey }, data: { value: `${day}:${count + 1}` } });
|
||||
},
|
||||
});
|
||||
return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }));
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ const EDITABLE_KEYS = [
|
||||
'storageMigrationCopied',
|
||||
'blockchainDriver',
|
||||
'certificateEnabled',
|
||||
'certificateDailyLimit',
|
||||
'tianheEnv',
|
||||
'tianheBaseUrl',
|
||||
'tianheAppId',
|
||||
@@ -92,7 +91,6 @@ export class SettingsService {
|
||||
settingsEncryptionKey: this.config.get<string>('settingsEncryptionKey') || '',
|
||||
blockchainDriver: this.config.get<string>('blockchain.driver') || 'mock',
|
||||
certificateEnabled: 'true',
|
||||
certificateDailyLimit: '100',
|
||||
tianheEnv: 'test',
|
||||
tianheBaseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com',
|
||||
tianheAppId: this.config.get<string>('blockchain.tianhe.appId') || '',
|
||||
@@ -149,10 +147,6 @@ export class SettingsService {
|
||||
if (values.certificateEnabled !== undefined && !['true', 'false'].includes(String(values.certificateEnabled))) {
|
||||
throw new BadRequestException('Invalid certificate switch');
|
||||
}
|
||||
if (values.certificateDailyLimit !== undefined &&
|
||||
(!/^\d+$/.test(String(values.certificateDailyLimit)) || Number(values.certificateDailyLimit) > 10000)) {
|
||||
throw new BadRequestException('Certificate daily limit must be between 0 and 10000');
|
||||
}
|
||||
const updates: Array<{ key: string; value: string }> = [];
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (!EDITABLE_KEYS.includes(key)) continue;
|
||||
|
||||
Reference in New Issue
Block a user