feat: 实现存储抽象、任务队列与区块链/归属地 Mock 适配

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-28 15:53:39 +08:00
co-authored by Cursor
parent 9368574cf7
commit 6e5c767a53
17 changed files with 425 additions and 0 deletions
+1
View File
@@ -51,4 +51,5 @@
- 阶段 1(后端基础设施)已完成:`apps/api` NestJS 工程;Prisma 全量建模并迁移(init),生成客户端;全局统一响应拦截器/异常过滤器/校验管道/BigInt 序列化;ConfigModule 读根 `.env`(dotenv-cli 供 Prisma CLI 用 `dotenv -e ../../.env`);静态目录 `/uploads`;Swagger 在 `/api/docs`。已验证启动、DB 连接、health/app-info 正常。
- 踩坑:pnpm 10 默认禁用原生构建脚本,已在根 `pnpm.onlyBuiltDependencies` 放行 prisma/sharp 等;Prisma migrate 需 shadow db 权限,开发库已对 `artveris` 用户授予全部权限;nanoid 固定 ^3(CJS);`tsconfig.json` 的 include 仅 `src`(含 prisma 会让 tsc 改变 rootDir 导致 dist/main.js 路径错位)。
- 阶段 2(鉴权与用户)已完成:JWT 登录(bcryptjs)、全局 JwtAuthGuard + RolesGuard(`@Public`/`@Roles` 元数据,SUPER_ADMIN 全通)、用户 CRUD(仅超管)、改密、`auth/profile`;种子超管 `admin/Admin@12345` 与系统默认设置。已用 PowerShell 验证登录/鉴权/RBAC/401。
- 阶段 3(平台能力)已完成:StorageService 抽象(LocalDriver 默认 + OssDriver 基于 @aws-sdk/client-s3 S3 兼容,env `STORAGE_DRIVER`/`CDN_BASE_URL` 切换,getUrl 返回绝对地址);`POST /api/upload`(按 image/video/file 校验类型与大小);QueueModule(BullMQ 连 Redis)+ JobsModule(Job 表进度,`GET /api/jobs`、`/jobs/:id`);BlockchainModule(AttestationProvider 接口 + MockProvider 拟真返回 + TianheProvider 占位,`hashData` 摘要);GeoModule(Mock 归属地)+ UA 解析工具。已验证上传→静态访问→jobs 列表。
+12
View File
@@ -5,6 +5,12 @@ import { PrismaModule } from './prisma/prisma.module';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
import { UserModule } from './user/user.module';
import { StorageModule } from './storage/storage.module';
import { UploadModule } from './upload/upload.module';
import { QueueModule } from './queue/queue.module';
import { JobsModule } from './jobs/jobs.module';
import { BlockchainModule } from './blockchain/blockchain.module';
import { GeoModule } from './geo/geo.module';
@Module({
imports: [
@@ -14,8 +20,14 @@ import { UserModule } from './user/user.module';
envFilePath: ['../../.env', '.env'],
}),
PrismaModule,
StorageModule,
QueueModule,
JobsModule,
BlockchainModule,
GeoModule,
AuthModule,
UserModule,
UploadModule,
],
controllers: [AppController],
})
@@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { BlockchainService } from './blockchain.service';
@Global()
@Module({
providers: [BlockchainService],
exports: [BlockchainService],
})
export class BlockchainModule {}
@@ -0,0 +1,36 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createHash } from 'crypto';
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
import { MockProvider } from './mock.provider';
import { TianheProvider } from './tianhe.provider';
@Injectable()
export class BlockchainService {
private readonly logger = new Logger(BlockchainService.name);
private readonly provider: AttestationProvider;
constructor(private readonly config: ConfigService) {
const driver = this.config.get<string>('blockchain.driver');
if (driver === 'tianhe') {
this.provider = new TianheProvider({
baseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || '',
appId: this.config.get<string>('blockchain.tianhe.appId') || '',
appKey: this.config.get<string>('blockchain.tianhe.appKey') || '',
});
} else {
this.provider = new MockProvider();
}
this.logger.log(`区块链存证驱动:${this.provider.name}`);
}
// 计算任意业务数据的稳定摘要哈希
hashData(data: unknown): string {
const json = JSON.stringify(data);
return '0x' + createHash('sha256').update(json).digest('hex');
}
attest(payload: AttestPayload): Promise<AttestResult> {
return this.provider.attest(payload);
}
}
@@ -0,0 +1,22 @@
export interface AttestPayload {
// 业务数据摘要(对作品/证书/出库/节点等关键数据计算的哈希)
dataHash: string;
// 附带的可读元信息(仅用于存证记录,可选)
meta?: Record<string, unknown>;
}
export interface AttestResult {
dataHash: string;
txHash: string;
blockHash: string;
blockHeight: number;
chainName: string;
explorerUrl: string;
onchainAt: Date;
raw: Record<string, unknown>;
}
export interface AttestationProvider {
readonly name: string;
attest(payload: AttestPayload): Promise<AttestResult>;
}
+33
View File
@@ -0,0 +1,33 @@
import { createHash, randomBytes } from 'crypto';
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
// 模拟区块链存证:返回结构与真实链一致的拟真数据,便于联调与前端展示。
// 真实接入(天河链)确认后,仅需切换 BLOCKCHAIN_DRIVER=tianhe 即可替换。
export class MockProvider implements AttestationProvider {
readonly name = 'mock-chain';
async attest(payload: AttestPayload): Promise<AttestResult> {
// 模拟网络与出块耗时
await new Promise((r) => setTimeout(r, 200));
const txHash = '0x' + randomBytes(32).toString('hex');
const blockHash =
'0x' + createHash('sha256').update(txHash).digest('hex');
const blockHeight = 8_000_000 + Math.floor(Math.random() * 2_000_000);
const onchainAt = new Date();
return {
dataHash: payload.dataHash,
txHash,
blockHash,
blockHeight,
chainName: 'MockChain',
explorerUrl: `https://mock-explorer.local/tx/${txHash}`,
onchainAt,
raw: {
provider: this.name,
code: 0,
message: 'success',
data: { txHash, blockHash, blockHeight, dataHash: payload.dataHash },
},
};
}
}
@@ -0,0 +1,28 @@
import { Logger } from '@nestjs/common';
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
export interface TianheOptions {
baseUrl: string;
appId: string;
appKey: string;
}
// 天河链存证适配器(接入细节待确认,预留对接)。
// 已知:纯存证接口 POST /api/v2/nfr/upload,appId/appKey 直接鉴权;
// 待确认:完整返回字段、存证查询链接、是否需注册托管钱包等。
// 确认后在 attest() 内补全真实请求与字段映射即可,对上层 BlockchainService 透明。
export class TianheProvider implements AttestationProvider {
readonly name = 'tianhe';
private readonly logger = new Logger(TianheProvider.name);
constructor(private readonly opts: TianheOptions) {}
async attest(_payload: AttestPayload): Promise<AttestResult> {
if (!this.opts.appId || !this.opts.appKey || !this.opts.baseUrl) {
throw new Error('天河链未配置(TIANHE_APP_ID/APP_KEY/BASE_URL),请在 .env 配置后再启用 BLOCKCHAIN_DRIVER=tianhe');
}
// TODO: 待天河链接入细节确认后实现真实存证请求与返回字段映射。
this.logger.warn('天河链真实接入尚未实现,请先使用 BLOCKCHAIN_DRIVER=mock');
throw new Error('天河链真实接入待确认,请暂用 BLOCKCHAIN_DRIVER=mock');
}
}
+35
View File
@@ -0,0 +1,35 @@
export interface DeviceInfo {
deviceType: string; // Mobile | Tablet | PC
os: string;
}
// 轻量 User-Agent 解析,用于查询日志风控统计。
export function parseUserAgent(ua?: string): DeviceInfo {
if (!ua) return { deviceType: 'Unknown', os: 'Unknown' };
const s = ua.toLowerCase();
let deviceType = 'PC';
if (/ipad|tablet/.test(s)) deviceType = 'Tablet';
else if (/mobile|android|iphone|ipod|micromessenger/.test(s)) deviceType = 'Mobile';
let os = 'Unknown';
if (/windows/.test(s)) os = 'Windows';
else if (/iphone|ipad|ipod|ios/.test(s)) os = 'iOS';
else if (/android/.test(s)) os = 'Android';
else if (/mac os|macintosh/.test(s)) os = 'macOS';
else if (/linux/.test(s)) os = 'Linux';
return { deviceType, os };
}
// 从请求中提取真实客户端 IP(兼容反向代理)。
export function extractIp(headers: Record<string, unknown>, fallback?: string): string {
const xff = headers['x-forwarded-for'];
if (typeof xff === 'string' && xff.length > 0) {
return xff.split(',')[0].trim();
}
const real = headers['x-real-ip'];
if (typeof real === 'string' && real.length > 0) {
return real;
}
return (fallback || '').replace('::ffff:', '') || 'unknown';
}
+9
View File
@@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { GeoService } from './geo.service';
@Global()
@Module({
providers: [GeoService],
exports: [GeoService],
})
export class GeoModule {}
+31
View File
@@ -0,0 +1,31 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
// IP 归属地解析。默认 Mock(本地/内网返回占位),预留接入真实 GeoIP 服务。
@Injectable()
export class GeoService {
constructor(private readonly config: ConfigService) {}
resolveRegion(ip?: string): string {
if (!ip || ip === 'unknown') return '未知';
if (this.isLocal(ip)) return '本地/内网';
// driver=mock:真实 GeoIP 未接入,返回占位。切换真实库后在此实现。
const driver = this.config.get<string>('geo.driver');
if (driver === 'mock') {
return '未知地区';
}
return '未知地区';
}
private isLocal(ip: string): boolean {
const clean = ip.replace('::ffff:', '');
return (
clean === '127.0.0.1' ||
clean === '::1' ||
clean === 'localhost' ||
clean.startsWith('10.') ||
clean.startsWith('192.168.') ||
/^172\.(1[6-9]|2\d|3[0-1])\./.test(clean)
);
}
}
+16
View File
@@ -0,0 +1,16 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsOptional } from 'class-validator';
import { JobStatus, JobType } from '@artveris/shared';
import { PaginationDto } from '../../common/dto/pagination.dto';
export class QueryJobDto extends PaginationDto {
@ApiPropertyOptional({ enum: JobType })
@IsOptional()
@IsEnum(JobType)
type?: JobType;
@ApiPropertyOptional({ enum: JobStatus })
@IsOptional()
@IsEnum(JobStatus)
status?: JobStatus;
}
+23
View File
@@ -0,0 +1,23 @@
import { Controller, Get, Param, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { JobsService } from './jobs.service';
import { QueryJobDto } from './dto/query-job.dto';
@ApiTags('异步任务')
@ApiBearerAuth()
@Controller('jobs')
export class JobsController {
constructor(private readonly jobsService: JobsService) {}
@Get()
@ApiOperation({ summary: '任务列表' })
list(@Query() query: QueryJobDto) {
return this.jobsService.list(query);
}
@Get(':id')
@ApiOperation({ summary: '任务进度详情' })
get(@Param('id') id: string) {
return this.jobsService.get(id);
}
}
+11
View File
@@ -0,0 +1,11 @@
import { Global, Module } from '@nestjs/common';
import { JobsService } from './jobs.service';
import { JobsController } from './jobs.controller';
@Global()
@Module({
controllers: [JobsController],
providers: [JobsService],
exports: [JobsService],
})
export class JobsModule {}
+63
View File
@@ -0,0 +1,63 @@
import { Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { ErrorCode, JobStatus, JobType } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { buildPage } from '../common/utils/pagination.util';
import { QueryJobDto } from './dto/query-job.dto';
@Injectable()
export class JobsService {
constructor(private readonly prisma: PrismaService) {}
create(type: JobType, total: number, createdBy?: number, payload?: Prisma.InputJsonValue) {
return this.prisma.job.create({
data: { type, total, createdBy, payload, status: JobStatus.PENDING },
});
}
start(id: string) {
return this.prisma.job.update({ where: { id }, data: { status: JobStatus.PROCESSING } });
}
progress(id: string, successCount: number, failCount: number) {
return this.prisma.job.update({ where: { id }, data: { successCount, failCount } });
}
finish(
id: string,
data: {
status: JobStatus;
successCount?: number;
failCount?: number;
resultFileUrl?: string | null;
error?: string | null;
},
) {
return this.prisma.job.update({ where: { id }, data });
}
async get(id: string) {
const job = await this.prisma.job.findUnique({ where: { id } });
if (!job) {
throw new BusinessException(ErrorCode.JOB_NOT_FOUND, '任务不存在', 404);
}
return job;
}
async list(query: QueryJobDto) {
const where: Prisma.JobWhereInput = {};
if (query.type) where.type = query.type;
if (query.status) where.status = query.status;
const [list, total] = await this.prisma.$transaction([
this.prisma.job.findMany({
where,
orderBy: { createdAt: 'desc' },
skip: query.skip,
take: query.take,
}),
this.prisma.job.count({ where }),
]);
return buildPage(list, total, query.page, query.pageSize);
}
}
+26
View File
@@ -0,0 +1,26 @@
import { Global, Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { ConfigService } from '@nestjs/config';
@Global()
@Module({
imports: [
BullModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
connection: {
host: config.get<string>('redis.host'),
port: config.get<number>('redis.port'),
password: config.get<string>('redis.password') || undefined,
},
defaultJobOptions: {
removeOnComplete: 100,
removeOnFail: 200,
attempts: 1,
},
}),
}),
],
exports: [BullModule],
})
export class QueueModule {}
+63
View File
@@ -0,0 +1,63 @@
import {
Controller,
Post,
Query,
UploadedFile,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger';
import {
ALLOWED_DOC_TYPES,
ALLOWED_IMAGE_TYPES,
ALLOWED_VIDEO_TYPES,
ErrorCode,
MAX_FILE_SIZE,
MAX_IMAGE_SIZE,
MAX_VIDEO_SIZE,
} from '@artveris/shared';
import { StorageService } from '../storage/storage.service';
import { BusinessException } from '../common/exceptions/business.exception';
type UploadType = 'image' | 'video' | 'file';
const RULES: Record<UploadType, { types: string[]; max: number; label: string }> = {
image: { types: ALLOWED_IMAGE_TYPES, max: MAX_IMAGE_SIZE, label: '图片' },
video: { types: ALLOWED_VIDEO_TYPES, max: MAX_VIDEO_SIZE, label: '视频' },
file: { types: ALLOWED_DOC_TYPES, max: MAX_FILE_SIZE, label: '文件' },
};
@ApiTags('文件上传')
@ApiBearerAuth()
@Controller('upload')
export class UploadController {
constructor(private readonly storage: StorageService) {}
@Post()
@ApiOperation({ summary: '上传文件(图片/视频/文档)' })
@ApiConsumes('multipart/form-data')
@ApiQuery({ name: 'type', enum: ['image', 'video', 'file'], required: false })
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_VIDEO_SIZE } }))
async upload(
@UploadedFile() file: Express.Multer.File,
@Query('type') type: UploadType = 'image',
) {
if (!file) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '请选择要上传的文件');
}
const rule = RULES[type] ?? RULES.image;
if (!rule.types.includes(file.mimetype)) {
throw new BusinessException(
ErrorCode.FILE_TYPE_NOT_ALLOWED,
`不支持的${rule.label}类型:${file.mimetype}`,
);
}
if (file.size > rule.max) {
throw new BusinessException(
ErrorCode.FILE_TOO_LARGE,
`${rule.label}超出大小限制(${Math.round(rule.max / 1024 / 1024)}MB)`,
);
}
return this.storage.save(file.buffer, file.originalname, file.mimetype);
}
}
+7
View File
@@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { UploadController } from './upload.controller';
@Module({
controllers: [UploadController],
})
export class UploadModule {}