feat: 完善安装部署与数字溯源码
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { createHmac, randomBytes } from 'crypto';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { SHORT_CODE_LENGTH } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
const TRACE_CODE_SALT_KEY = 'traceCodeSalt';
|
||||
const MAX_DAILY_SEQUENCE = 1_000_000;
|
||||
const FEISTEL_ROUNDS = 4;
|
||||
|
||||
interface SequenceRange {
|
||||
dateKey: string;
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TraceCodeGeneratorService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async ensureSalt(): Promise<string> {
|
||||
const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
|
||||
if (existing?.value) return existing.value;
|
||||
const salt = randomBytes(32).toString('hex');
|
||||
try {
|
||||
await this.prisma.systemSetting.create({ data: { key: TRACE_CODE_SALT_KEY, value: salt } });
|
||||
return salt;
|
||||
} catch (e) {
|
||||
if (this.isUniqueError(e)) {
|
||||
const row = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
|
||||
if (row?.value) return row.value;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async generate(count: number): Promise<string[]> {
|
||||
const salt = await this.ensureSalt();
|
||||
const range = await this.allocateRange(count);
|
||||
return Array.from({ length: range.end - range.start + 1 }, (_, index) =>
|
||||
this.formatCode(this.permute6(range.start + index, salt, range.dateKey), range.dateKey),
|
||||
);
|
||||
}
|
||||
|
||||
private async allocateRange(count: number): Promise<SequenceRange> {
|
||||
const dateKey = this.shanghaiDateKey();
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
try {
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
await tx.traceCodeDailySequence.upsert({
|
||||
where: { dateKey },
|
||||
update: {},
|
||||
create: { dateKey, nextSeq: 0 },
|
||||
});
|
||||
const row = await tx.traceCodeDailySequence.update({
|
||||
where: { dateKey },
|
||||
data: { nextSeq: { increment: count } },
|
||||
});
|
||||
const start = row.nextSeq - count;
|
||||
const end = row.nextSeq - 1;
|
||||
if (end >= MAX_DAILY_SEQUENCE) {
|
||||
throw new Error('trace.code.dailyLimitExceeded');
|
||||
}
|
||||
return { dateKey, start, end };
|
||||
});
|
||||
} catch (e) {
|
||||
if (!this.isUniqueError(e) || attempt === 2) throw e;
|
||||
}
|
||||
}
|
||||
throw new Error('trace.code.sequenceAllocationFailed');
|
||||
}
|
||||
|
||||
private shanghaiDateKey(date = new Date()): string {
|
||||
const parts = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: '2-digit',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).formatToParts(date);
|
||||
const get = (type: string) => parts.find((part) => part.type === type)?.value.padStart(2, '0') ?? '00';
|
||||
return `${get('year')}${get('month')}${get('day')}`;
|
||||
}
|
||||
|
||||
private permute6(seq: number, salt: string, dateKey: string): string {
|
||||
let left = Math.floor(seq / 1000);
|
||||
let right = seq % 1000;
|
||||
const keys = this.roundKeys(salt, dateKey);
|
||||
for (let round = 0; round < FEISTEL_ROUNDS; round += 1) {
|
||||
const nextLeft = right;
|
||||
const f = (right * keys[round].mul + keys[round].add) % 1000;
|
||||
right = (left + f) % 1000;
|
||||
left = nextLeft;
|
||||
}
|
||||
return `${left.toString().padStart(3, '0')}${right.toString().padStart(3, '0')}`;
|
||||
}
|
||||
|
||||
private roundKeys(salt: string, dateKey: string): Array<{ mul: number; add: number }> {
|
||||
const digest = createHmac('sha256', salt).update(`trace-code:${dateKey}`).digest();
|
||||
return Array.from({ length: FEISTEL_ROUNDS }, (_, index) => {
|
||||
const rawMul = digest.readUInt16BE(index * 4) % 1000;
|
||||
return {
|
||||
mul: rawMul % 2 === 0 ? rawMul + 1 : rawMul,
|
||||
add: digest.readUInt16BE(index * 4 + 2) % 1000,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private formatCode(scrambled: string, dateKey: string): string {
|
||||
const code = `${scrambled.slice(0, 2)}${dateKey.slice(0, 2)}${scrambled[2]}${dateKey.slice(2, 4)}${scrambled[3]}${dateKey.slice(4, 6)}${scrambled.slice(4)}`;
|
||||
if (code.length !== SHORT_CODE_LENGTH || !/^\d{12}$/.test(code)) {
|
||||
throw new Error('trace.code.invalidGeneratedCode');
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
private isUniqueError(error: unknown): boolean {
|
||||
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user