feat: 完善后台导入日志权限与备份恢复
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
import { existsSync, rmSync } from 'fs';
|
||||
import { BackupStatus } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { BackupService } from './backup.service';
|
||||
|
||||
@Injectable()
|
||||
export class BackupRetentionService {
|
||||
private readonly logger = new Logger(BackupRetentionService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly settings: SettingsService,
|
||||
private readonly backups: BackupService,
|
||||
) {}
|
||||
|
||||
@Cron(CronExpression.EVERY_DAY_AT_2AM)
|
||||
async scheduledBackup(): Promise<void> {
|
||||
const enabled = (await this.settings.get('backupEnabled')) === 'true';
|
||||
if (!enabled) return;
|
||||
const schedule = (await this.settings.get('backupSchedule')) || 'daily';
|
||||
if (schedule === 'weekly' && new Date().getDay() !== 1) return;
|
||||
|
||||
const admin = await this.prisma.sysUser.findFirst({
|
||||
where: { role: 'SUPER_ADMIN', status: 'ACTIVE' },
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
if (!admin) return;
|
||||
await this.backups.createBackup(
|
||||
{ id: admin.id, username: admin.username, role: admin.role, realName: admin.realName ?? undefined },
|
||||
'SCHEDULED',
|
||||
);
|
||||
await this.cleanup();
|
||||
}
|
||||
|
||||
async cleanup(): Promise<void> {
|
||||
const days = Number((await this.settings.get('backupRetentionDays')) ?? 30);
|
||||
const count = Number((await this.settings.get('backupRetentionCount')) ?? 10);
|
||||
const cutoff = days > 0 ? new Date(Date.now() - days * 24 * 60 * 60 * 1000) : null;
|
||||
const old = await this.prisma.backupRecord.findMany({
|
||||
where: {
|
||||
mode: { in: ['BACKUP', 'SCHEDULED'] },
|
||||
status: BackupStatus.SUCCESS,
|
||||
...(cutoff ? { createdAt: { lt: cutoff } } : {}),
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
const all = await this.prisma.backupRecord.findMany({
|
||||
where: { mode: { in: ['BACKUP', 'SCHEDULED'] }, status: BackupStatus.SUCCESS },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
const overflow = count > 0 ? all.slice(count) : [];
|
||||
const ids = new Set([...old, ...overflow].map((r) => r.id));
|
||||
for (const id of ids) {
|
||||
const record = [...old, ...overflow].find((r) => r.id === id);
|
||||
if (record?.filePath && existsSync(record.filePath)) rmSync(record.filePath, { force: true });
|
||||
await this.prisma.backupRecord.delete({ where: { id } });
|
||||
}
|
||||
if (ids.size) this.logger.log(`已清理备份 ${ids.size} 个`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Body, Controller, Delete, Get, Param, Post, Query, Res, UploadedFile, UseInterceptors } from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Response } from 'express';
|
||||
import { MAX_FILE_SIZE, RoleType } from '@artveris/shared';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
||||
import { BackupService } from './backup.service';
|
||||
import { QueryBackupDto, RestoreCommitDto } from './dto/backup.dto';
|
||||
|
||||
@ApiTags('备份与恢复')
|
||||
@ApiBearerAuth()
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@Controller('backups')
|
||||
export class BackupController {
|
||||
constructor(private readonly backups: BackupService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: '备份记录列表' })
|
||||
list(@Query() query: QueryBackupDto) {
|
||||
return this.backups.list(query);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: '创建备份' })
|
||||
create(@CurrentUser() user: AuthUser) {
|
||||
return this.backups.createBackup(user);
|
||||
}
|
||||
|
||||
@Get(':id/download')
|
||||
@ApiOperation({ summary: '下载备份包' })
|
||||
download(@Param('id') id: string, @Res() res: Response) {
|
||||
return this.backups.download(id, res);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: '删除备份记录与文件' })
|
||||
remove(@Param('id') id: string) {
|
||||
return this.backups.remove(id);
|
||||
}
|
||||
|
||||
@Post('restore/preview')
|
||||
@ApiOperation({ summary: '上传备份包并预校验' })
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE * 10 } }))
|
||||
restorePreview(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) {
|
||||
return this.backups.previewRestore(file, user);
|
||||
}
|
||||
|
||||
@Post('restore/commit')
|
||||
@ApiOperation({ summary: '确认整库覆盖恢复' })
|
||||
restoreCommit(@Body() dto: RestoreCommitDto, @CurrentUser() user: AuthUser) {
|
||||
return this.backups.commitRestore(dto.restoreId, user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { BackupController } from './backup.controller';
|
||||
import { BackupRetentionService } from './backup-retention.service';
|
||||
import { BackupService } from './backup.service';
|
||||
|
||||
@Module({
|
||||
controllers: [BackupController],
|
||||
providers: [BackupService, BackupRetentionService],
|
||||
exports: [BackupService],
|
||||
})
|
||||
export class BackupModule {}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
|
||||
export class QueryBackupDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '状态' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '类型 BACKUP / RESTORE' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
mode?: string;
|
||||
}
|
||||
|
||||
export class RestoreCommitDto {
|
||||
@ApiPropertyOptional({ description: '恢复预校验记录 ID' })
|
||||
@IsString()
|
||||
restoreId!: string;
|
||||
}
|
||||
Reference in New Issue
Block a user