342 lines
13 KiB
TypeScript
342 lines
13 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { Response } from 'express';
|
|
import AdmZip from 'adm-zip';
|
|
import dayjs from 'dayjs';
|
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
|
|
import { dirname, isAbsolute, join, relative, resolve } from 'path';
|
|
import { Prisma } from '@prisma/client';
|
|
import { BackupStatus, ErrorCode } from '@artveris/shared';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
import { BusinessException } from '../common/exceptions/business.exception';
|
|
import { buildPage } from '../common/utils/pagination.util';
|
|
import { buildOrderBy } from '../common/utils/sort.util';
|
|
import { AuthUser } from '../common/decorators/current-user.decorator';
|
|
import { QueryBackupDto } from './dto/backup.dto';
|
|
import { SettingsService } from '../settings/settings.service';
|
|
import { StorageService } from '../storage/storage.service';
|
|
|
|
const MODELS = [
|
|
'sysUser',
|
|
'template',
|
|
'templateField',
|
|
'artwork',
|
|
'artworkRevision',
|
|
'traceNode',
|
|
'certificate',
|
|
'traceCodeGroup',
|
|
'batch',
|
|
'traceCode',
|
|
'traceCodeDailySequence',
|
|
'blockchainProof',
|
|
'queryLog',
|
|
'job',
|
|
'systemSetting',
|
|
'operationLog',
|
|
'outboundImportSession',
|
|
'outboundImportRow',
|
|
] as const;
|
|
|
|
const DELETE_ORDER = [...MODELS].reverse();
|
|
const EXCLUDED_PRISMA_MODELS = new Set(['BackupRecord']);
|
|
const PRISMA_MODEL_BY_DELEGATE: Record<(typeof MODELS)[number], string> = {
|
|
sysUser: 'SysUser',
|
|
template: 'Template',
|
|
templateField: 'TemplateField',
|
|
artwork: 'Artwork',
|
|
artworkRevision: 'ArtworkRevision',
|
|
traceNode: 'TraceNode',
|
|
certificate: 'Certificate',
|
|
traceCodeGroup: 'TraceCodeGroup',
|
|
batch: 'Batch',
|
|
traceCode: 'TraceCode',
|
|
traceCodeDailySequence: 'TraceCodeDailySequence',
|
|
blockchainProof: 'BlockchainProof',
|
|
queryLog: 'QueryLog',
|
|
job: 'Job',
|
|
systemSetting: 'SystemSetting',
|
|
operationLog: 'OperationLog',
|
|
outboundImportSession: 'OutboundImportSession',
|
|
outboundImportRow: 'OutboundImportRow',
|
|
};
|
|
const DATE_KEYS = new Set([
|
|
'lastLoginAt',
|
|
'createdAt',
|
|
'updatedAt',
|
|
'deletedAt',
|
|
'auditedAt',
|
|
'submittedAt',
|
|
'reviewedAt',
|
|
'occurredAt',
|
|
'issuedAt',
|
|
'outTime',
|
|
'firstActivatedAt',
|
|
'lastQueriedAt',
|
|
'onchainAt',
|
|
'queriedAt',
|
|
'expiresAt',
|
|
'committedAt',
|
|
]);
|
|
|
|
function jsonReplacer(_key: string, value: unknown) {
|
|
if (typeof value === 'bigint') return { __bigint: value.toString() };
|
|
return value;
|
|
}
|
|
|
|
function reviveRow(row: Record<string, any>): Record<string, any> {
|
|
const out: Record<string, any> = {};
|
|
for (const [key, value] of Object.entries(row)) {
|
|
if (value && typeof value === 'object' && '__bigint' in value) {
|
|
out[key] = BigInt(String(value.__bigint));
|
|
} else if (DATE_KEYS.has(key) && typeof value === 'string') {
|
|
out[key] = new Date(value);
|
|
} else {
|
|
out[key] = value;
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function isSafeZipPath(path: string): boolean {
|
|
return !path.includes('\\') && !path.includes('..') && !path.startsWith('/') && !/^[a-z]:/i.test(path);
|
|
}
|
|
|
|
function isSameOrChildPath(parent: string, child: string): boolean {
|
|
const rel = relative(resolve(parent), resolve(child));
|
|
return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
|
|
}
|
|
|
|
@Injectable()
|
|
export class BackupService {
|
|
private readonly storageRoot: string;
|
|
private readonly backupRoot: string;
|
|
|
|
constructor(
|
|
private readonly prisma: PrismaService,
|
|
private readonly config: ConfigService,
|
|
private readonly settings: SettingsService,
|
|
private readonly storage: StorageService,
|
|
) {
|
|
this.storageRoot = resolve(this.config.get<string>('storage.localDir') || './storage');
|
|
this.backupRoot = resolve(process.env.BACKUP_DIR || join(dirname(this.storageRoot), 'backups'));
|
|
mkdirSync(this.backupRoot, { recursive: true });
|
|
}
|
|
|
|
async list(query: QueryBackupDto) {
|
|
const where: any = {};
|
|
if (query.status) where.status = query.status;
|
|
if (query.mode) where.mode = query.mode;
|
|
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt'] as const, { createdAt: 'desc' });
|
|
const [list, total] = await this.prisma.$transaction([
|
|
this.prisma.backupRecord.findMany({ where, orderBy, skip: query.skip, take: query.take }),
|
|
this.prisma.backupRecord.count({ where }),
|
|
]);
|
|
return buildPage(list, total, query.page, query.pageSize);
|
|
}
|
|
|
|
async createBackup(user: AuthUser, mode = 'BACKUP') {
|
|
this.assertModelCoverage();
|
|
const stamp = dayjs().format('YYYYMMDDHHmmss');
|
|
const fileName = `artveris-${mode.toLowerCase()}-${stamp}.zip`;
|
|
const filePath = join(this.backupRoot, fileName);
|
|
const record = await this.prisma.backupRecord.create({
|
|
data: { fileName, filePath, status: BackupStatus.PROCESSING, mode, createdBy: user.id },
|
|
});
|
|
try {
|
|
const db = await this.dumpDatabase();
|
|
const zip = new AdmZip();
|
|
const fileList = await this.addStorageFiles(zip);
|
|
const manifest = {
|
|
app: 'artveris',
|
|
version: '0.1.0',
|
|
createdAt: new Date().toISOString(),
|
|
mode,
|
|
models: Object.fromEntries(Object.entries(db).map(([key, rows]) => [key, (rows as unknown[]).length])),
|
|
files: fileList,
|
|
};
|
|
zip.addFile('manifest.json', Buffer.from(JSON.stringify(manifest, null, 2), 'utf8'));
|
|
zip.addFile('database.json', Buffer.from(JSON.stringify(db, jsonReplacer), 'utf8'));
|
|
writeFileSync(filePath, zip.toBuffer());
|
|
const size = BigInt(statSync(filePath).size);
|
|
return this.prisma.backupRecord.update({
|
|
where: { id: record.id },
|
|
data: { status: BackupStatus.SUCCESS, size, manifest: manifest as any },
|
|
});
|
|
} catch (e) {
|
|
await this.prisma.backupRecord.update({
|
|
where: { id: record.id },
|
|
data: { status: BackupStatus.FAILED, error: (e as Error).message },
|
|
});
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
async download(id: string, res: Response) {
|
|
const record = await this.prisma.backupRecord.findUnique({ where: { id } });
|
|
if (!record || record.status !== BackupStatus.SUCCESS || !existsSync(record.filePath)) {
|
|
throw new BusinessException(ErrorCode.NOT_FOUND, '备份文件不存在', 404);
|
|
}
|
|
res.setHeader('Content-Type', 'application/zip');
|
|
res.setHeader('Content-Disposition', `attachment; filename="${record.fileName}"`);
|
|
res.end(readFileSync(record.filePath));
|
|
}
|
|
|
|
async remove(id: string) {
|
|
const record = await this.prisma.backupRecord.findUnique({ where: { id } });
|
|
if (!record) throw new BusinessException(ErrorCode.NOT_FOUND, '备份记录不存在', 404);
|
|
if (existsSync(record.filePath)) rmSync(record.filePath, { force: true });
|
|
await this.prisma.backupRecord.delete({ where: { id } });
|
|
return { success: true };
|
|
}
|
|
|
|
async previewRestore(file: Express.Multer.File, user: AuthUser) {
|
|
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传备份 ZIP 文件');
|
|
const zip = new AdmZip(file.buffer);
|
|
const manifestEntry = zip.getEntry('manifest.json');
|
|
const dbEntry = zip.getEntry('database.json');
|
|
if (!manifestEntry || !dbEntry) throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包缺少 manifest.json 或 database.json');
|
|
const manifest = JSON.parse(manifestEntry.getData().toString('utf8'));
|
|
if (manifest.app !== 'artveris') throw new BusinessException(ErrorCode.BAD_REQUEST, '不是 Artveris 备份包');
|
|
|
|
const fileName = `restore-${dayjs().format('YYYYMMDDHHmmss')}.zip`;
|
|
const filePath = join(this.backupRoot, fileName);
|
|
writeFileSync(filePath, file.buffer);
|
|
const record = await this.prisma.backupRecord.create({
|
|
data: {
|
|
fileName,
|
|
filePath,
|
|
size: BigInt(file.buffer.length),
|
|
status: BackupStatus.PENDING,
|
|
mode: 'RESTORE',
|
|
manifest,
|
|
createdBy: user.id,
|
|
},
|
|
});
|
|
return { restoreId: record.id, manifest };
|
|
}
|
|
|
|
async commitRestore(restoreId: string, user: AuthUser) {
|
|
const record = await this.prisma.backupRecord.findUnique({ where: { id: restoreId } });
|
|
if (!record || record.mode !== 'RESTORE' || !existsSync(record.filePath)) {
|
|
throw new BusinessException(ErrorCode.NOT_FOUND, '恢复记录不存在', 404);
|
|
}
|
|
await this.prisma.backupRecord.update({ where: { id: restoreId }, data: { status: BackupStatus.PROCESSING } });
|
|
const snapshot = await this.createBackup(user, 'AUTO_BEFORE_RESTORE');
|
|
try {
|
|
const zip = new AdmZip(readFileSync(record.filePath));
|
|
await this.restoreDatabase(zip);
|
|
await this.restoreStorage(zip);
|
|
return this.prisma.backupRecord.update({
|
|
where: { id: restoreId },
|
|
data: { status: BackupStatus.SUCCESS, error: null },
|
|
});
|
|
} catch (e) {
|
|
await this.prisma.backupRecord.update({
|
|
where: { id: restoreId },
|
|
data: { status: BackupStatus.FAILED, error: `${(e as Error).message};恢复前快照:${snapshot.fileName}` },
|
|
});
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
private async dumpDatabase() {
|
|
const db: Record<string, unknown[]> = {};
|
|
for (const model of MODELS) {
|
|
db[model] = model === 'systemSetting' ? await this.dumpEffectiveSettings() : await (this.prisma as any)[model].findMany();
|
|
}
|
|
return db;
|
|
}
|
|
|
|
private assertModelCoverage(): void {
|
|
const expected = new Set<string>(Object.values(Prisma.ModelName).filter((model) => !EXCLUDED_PRISMA_MODELS.has(model)));
|
|
const covered = new Set<string>(Object.values(PRISMA_MODEL_BY_DELEGATE));
|
|
const missing = [...expected].filter((model) => !covered.has(model));
|
|
const stale = [...covered].filter((model) => !expected.has(model));
|
|
if (missing.length || stale.length) {
|
|
throw new Error(`备份模型清单不完整:missing=${missing.join(',') || '-'}; stale=${stale.join(',') || '-'}`);
|
|
}
|
|
}
|
|
|
|
private async dumpEffectiveSettings() {
|
|
const rows = await this.prisma.systemSetting.findMany();
|
|
const byKey = new Map(rows.map((row) => [row.key, row]));
|
|
const all = await this.settings.getAllRaw();
|
|
let nextId = rows.reduce((max, row) => Math.max(max, row.id), 0) + 1;
|
|
const now = new Date();
|
|
for (const [key, value] of Object.entries(all)) {
|
|
if (!byKey.has(key)) {
|
|
byKey.set(key, { id: nextId++, key, value: String(value), updatedAt: now });
|
|
}
|
|
}
|
|
return [...byKey.values()];
|
|
}
|
|
|
|
private async addStorageFiles(zip: AdmZip) {
|
|
const files: string[] = [];
|
|
const storageKeys = await this.storage.listKeys();
|
|
if (storageKeys.length) {
|
|
for (const key of storageKeys) {
|
|
if (!isSafeZipPath(key)) continue;
|
|
files.push(key);
|
|
zip.addFile(`storage/${key}`, await this.storage.read(key));
|
|
}
|
|
return files;
|
|
}
|
|
if (!existsSync(this.storageRoot)) return files;
|
|
const walk = (dir: string) => {
|
|
for (const name of readdirSync(dir)) {
|
|
const full = join(dir, name);
|
|
const st = statSync(full);
|
|
if (isSameOrChildPath(this.backupRoot, full)) continue;
|
|
if (st.isDirectory()) {
|
|
walk(full);
|
|
} else {
|
|
const rel = relative(this.storageRoot, full).replace(/\\/g, '/');
|
|
if (!isSafeZipPath(rel)) continue;
|
|
files.push(rel);
|
|
zip.addFile(`storage/${rel}`, readFileSync(full));
|
|
}
|
|
}
|
|
};
|
|
walk(this.storageRoot);
|
|
return files;
|
|
}
|
|
|
|
private async restoreDatabase(zip: AdmZip) {
|
|
const entry = zip.getEntry('database.json');
|
|
if (!entry) throw new Error('备份包缺少 database.json');
|
|
const db = JSON.parse(entry.getData().toString('utf8'));
|
|
await this.prisma.$transaction(async (tx) => {
|
|
for (const model of DELETE_ORDER) {
|
|
await (tx as any)[model].deleteMany();
|
|
}
|
|
for (const model of MODELS) {
|
|
const rows = Array.isArray(db[model]) ? db[model].map(reviveRow) : [];
|
|
if (rows.length) await (tx as any)[model].createMany({ data: rows });
|
|
}
|
|
}, { timeout: 120000 });
|
|
}
|
|
|
|
private async restoreStorage(zip: AdmZip) {
|
|
const currentKeys = await this.storage.listKeys();
|
|
if (currentKeys.length) {
|
|
for (const key of currentKeys) {
|
|
if (!key.startsWith('.health/')) await this.storage.remove(key);
|
|
}
|
|
} else {
|
|
mkdirSync(this.storageRoot, { recursive: true });
|
|
for (const name of readdirSync(this.storageRoot)) {
|
|
const full = join(this.storageRoot, name);
|
|
if (isSameOrChildPath(this.backupRoot, full)) continue;
|
|
rmSync(full, { recursive: true, force: true });
|
|
}
|
|
}
|
|
for (const entry of zip.getEntries()) {
|
|
if (entry.isDirectory || !entry.entryName.startsWith('storage/')) continue;
|
|
const rel = entry.entryName.slice('storage/'.length);
|
|
if (!isSafeZipPath(rel)) throw new Error(`备份包包含不安全文件路径:${entry.entryName}`);
|
|
await this.storage.putKey(rel, entry.getData());
|
|
}
|
|
}
|
|
}
|