fix: 移除消费者出证每日上限并保留单件防重

This commit is contained in:
Nixevol
2026-09-20 01:46:19 +08:00
parent f2d24dff0d
commit 002521f5d1
8 changed files with 39 additions and 47 deletions
@@ -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;