feat: 完善后台导入日志权限与备份恢复
This commit is contained in:
@@ -0,0 +1,260 @@
|
||||
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, join, relative, resolve } from 'path';
|
||||
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 { AuthUser } from '../common/decorators/current-user.decorator';
|
||||
import { QueryBackupDto } from './dto/backup.dto';
|
||||
|
||||
const MODELS = [
|
||||
'sysUser',
|
||||
'template',
|
||||
'templateField',
|
||||
'artwork',
|
||||
'traceNode',
|
||||
'certificate',
|
||||
'traceCodeGroup',
|
||||
'batch',
|
||||
'traceCode',
|
||||
'blockchainProof',
|
||||
'queryLog',
|
||||
'job',
|
||||
'systemSetting',
|
||||
'operationLog',
|
||||
'outboundImportSession',
|
||||
'outboundImportRow',
|
||||
] as const;
|
||||
|
||||
const DELETE_ORDER = [...MODELS].reverse();
|
||||
const DATE_KEYS = new Set([
|
||||
'lastLoginAt',
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'deletedAt',
|
||||
'auditedAt',
|
||||
'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);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class BackupService {
|
||||
private readonly storageRoot: string;
|
||||
private readonly backupRoot: string;
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly config: ConfigService,
|
||||
) {
|
||||
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 [list, total] = await this.prisma.$transaction([
|
||||
this.prisma.backupRecord.findMany({ where, orderBy: { createdAt: 'desc' }, 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') {
|
||||
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 = 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);
|
||||
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] = await (this.prisma as any)[model].findMany();
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
private addStorageFiles(zip: AdmZip) {
|
||||
const files: string[] = [];
|
||||
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 (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 restoreStorage(zip: AdmZip) {
|
||||
if (existsSync(this.storageRoot)) rmSync(this.storageRoot, { recursive: true, force: true });
|
||||
mkdirSync(this.storageRoot, { recursive: 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}`);
|
||||
const full = join(this.storageRoot, rel);
|
||||
mkdirSync(dirname(full), { recursive: true });
|
||||
writeFileSync(full, entry.getData());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user