feat: 优化静态资源缓存策略
This commit is contained in:
+1
-1
@@ -28,7 +28,7 @@ coverage/
|
|||||||
unpackage/
|
unpackage/
|
||||||
|
|
||||||
# 本地文件存储(运行时上传目录)
|
# 本地文件存储(运行时上传目录)
|
||||||
storage/
|
/storage/
|
||||||
apps/api/storage/
|
apps/api/storage/
|
||||||
backups/
|
backups/
|
||||||
apps/api/backups/
|
apps/api/backups/
|
||||||
|
|||||||
@@ -183,6 +183,7 @@
|
|||||||
- 远程部署密钥持久化(2026-07-05):`deploy_remote.py` 不再让 MySQL root/业务用户、Redis、JWT 等生产密钥每次留空时重新生成;脚本会把这些密钥保存到 `.deploy/remote-secrets.json`,后续部署自动加载并作为默认值复用,避免已有 MySQL/Redis 数据卷继续使用旧密码但新 `.env` 写入新随机密码导致 `Access denied`。`mysql` 服务新增 `MYSQL_ROOT_HOST: "%"`,用于新数据卷首次初始化时允许 root 从容器网络来源登录;已有数据卷不受该变量重新初始化影响。MySQL 初始化等待改为真正执行 root `SELECT 1`,失败 60 次后明确提示检查旧数据卷/旧 root 密码。若服务器上已用错误随机密码创建了空 `artveris_mysql` 卷,开发阶段可删除该 Artveris 专属卷后重新部署;有正式数据时必须使用创建该卷时的旧密码或做数据库迁移。
|
- 远程部署密钥持久化(2026-07-05):`deploy_remote.py` 不再让 MySQL root/业务用户、Redis、JWT 等生产密钥每次留空时重新生成;脚本会把这些密钥保存到 `.deploy/remote-secrets.json`,后续部署自动加载并作为默认值复用,避免已有 MySQL/Redis 数据卷继续使用旧密码但新 `.env` 写入新随机密码导致 `Access denied`。`mysql` 服务新增 `MYSQL_ROOT_HOST: "%"`,用于新数据卷首次初始化时允许 root 从容器网络来源登录;已有数据卷不受该变量重新初始化影响。MySQL 初始化等待改为真正执行 root `SELECT 1`,失败 60 次后明确提示检查旧数据卷/旧 root 密码。若服务器上已用错误随机密码创建了空 `artveris_mysql` 卷,开发阶段可删除该 Artveris 专属卷后重新部署;有正式数据时必须使用创建该卷时的旧密码或做数据库迁移。
|
||||||
- 远程部署重置选项(2026-07-05):`deploy_remote.py` 新增交互项“是否清理线上 Artveris 旧容器/卷/网络/API镜像后重新部署”,默认 `N`;只有手动输入 `y` 才执行远程清理。清理命令先尝试当前远程目录下的 `docker compose ... down -v --remove-orphans`,再按 `com.docker.compose.project=artveris` 标签清理残留容器/卷/网络,并删除 `artveris-api:*` 镜像和旧部署文件。不会按镜像名删除通用 `mysql/redis/nginx`,避免误伤 1Panel 及其他项目;但会删除 Artveris 自己的数据卷,正式数据环境慎用。
|
- 远程部署重置选项(2026-07-05):`deploy_remote.py` 新增交互项“是否清理线上 Artveris 旧容器/卷/网络/API镜像后重新部署”,默认 `N`;只有手动输入 `y` 才执行远程清理。清理命令先尝试当前远程目录下的 `docker compose ... down -v --remove-orphans`,再按 `com.docker.compose.project=artveris` 标签清理残留容器/卷/网络,并删除 `artveris-api:*` 镜像和旧部署文件。不会按镜像名删除通用 `mysql/redis/nginx`,避免误伤 1Panel 及其他项目;但会删除 Artveris 自己的数据卷,正式数据环境慎用。
|
||||||
- 生产初始化账号(2026-07-05):生产 API 镜像启动命令从“仅 Prisma migrate 后启动服务”改为 `migrate deploy -> node prisma/seed-production.js -> node dist/main.js`。新增 `apps/api/prisma/seed-production.js`,只幂等创建 `SEED_ADMIN_USERNAME/SEED_ADMIN_PASSWORD/SEED_ADMIN_NAME` 指定的超级管理员和基础系统设置,不创建 `seed.ts` 中的示例作品/追溯码/查询日志,避免生产库为空时默认 `admin / Admin@12345` 登录失败,同时不污染正式业务数据。
|
- 生产初始化账号(2026-07-05):生产 API 镜像启动命令从“仅 Prisma migrate 后启动服务”改为 `migrate deploy -> node prisma/seed-production.js -> node dist/main.js`。新增 `apps/api/prisma/seed-production.js`,只幂等创建 `SEED_ADMIN_USERNAME/SEED_ADMIN_PASSWORD/SEED_ADMIN_NAME` 指定的超级管理员和基础系统设置,不创建 `seed.ts` 中的示例作品/追溯码/查询日志,避免生产库为空时默认 `admin / Admin@12345` 登录失败,同时不污染正式业务数据。
|
||||||
|
- 静态资源缓存与 OSS/CDN 约定(2026-07-05):上传文件现在计算 SHA-256,并将 hash 前缀写入唯一文件 key(`YYYY/MM/DD/{hash16}-{nanoid}.ext`),确保“文件变化 = 新 URL”,避免长缓存后用户看到旧文件。`StorageService.save` 返回 `hash`,本地 `/uploads` 静态服务开启 ETag/Last-Modified,并设置 `Cache-Control: public, max-age=31536000, immutable`;OSS/S3 兼容上传同样写入 `CacheControl` 与 `ContentType`。`CDN_BASE_URL` 仍作为资源公开 URL 前缀,API/作品详情接口不做强缓存,只让图片、视频、证书等静态资源走浏览器/CDN 缓存。前端后台媒体缩略图补充 `loading="lazy"`,客户端溯源页视频继续使用 `preload="metadata"`,不要在资源 URL 后拼随机参数绕过缓存。
|
||||||
|
|
||||||
## 当前代码基准与注意事项
|
## 当前代码基准与注意事项
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
@dragend="onDragEnd"
|
@dragend="onDragEnd"
|
||||||
>
|
>
|
||||||
<video v-if="isVideo(m)" class="thumb" :src="m.url" muted preload="metadata" />
|
<video v-if="isVideo(m)" class="thumb" :src="m.url" muted preload="metadata" />
|
||||||
<img v-else class="thumb" :src="m.url" :alt="m.name" />
|
<img v-else class="thumb" :src="m.url" :alt="m.name" loading="lazy" />
|
||||||
<div v-if="isVideo(m)" class="play"><n-icon :component="PlayCircleOutline" :size="26" /></div>
|
<div v-if="isVideo(m)" class="play"><n-icon :component="PlayCircleOutline" :size="26" /></div>
|
||||||
<div class="order">{{ i + 1 }}</div>
|
<div class="order">{{ i + 1 }}</div>
|
||||||
<button class="del" type="button" :title="t('common.action.delete')" @click.stop="remove(i)">×</button>
|
<button class="del" type="button" :title="t('common.action.delete')" @click.stop="remove(i)">×</button>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<div class="media-upload" :class="{ text: listType === 'text' }">
|
<div class="media-upload" :class="{ text: listType === 'text' }">
|
||||||
<div v-if="listType === 'image-card'" class="image-grid">
|
<div v-if="listType === 'image-card'" class="image-grid">
|
||||||
<div v-for="(m, i) in items" :key="m.key" class="image-item previewable" @click="preview(i)">
|
<div v-for="(m, i) in items" :key="m.key" class="image-item previewable" @click="preview(i)">
|
||||||
<img v-if="isImage(m)" class="image-thumb" :src="m.url || m.key" :alt="m.name || m.key" />
|
<img v-if="isImage(m)" class="image-thumb" :src="m.url || m.key" :alt="m.name || m.key" loading="lazy" />
|
||||||
<div v-else class="file-thumb">{{ fileExt(m) }}</div>
|
<div v-else class="file-thumb">{{ fileExt(m) }}</div>
|
||||||
<button class="remove" type="button" :title="t('common.action.delete')" @click.stop="remove(m.key)">×</button>
|
<button class="remove" type="button" :title="t('common.action.delete')" @click.stop="remove(m.key)">×</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -186,6 +186,7 @@
|
|||||||
class="node-media-image"
|
class="node-media-image"
|
||||||
:src="m.url"
|
:src="m.url"
|
||||||
:alt="m.name || n.title"
|
:alt="m.name || n.title"
|
||||||
|
loading="lazy"
|
||||||
@click="previewNodeImage(n.media, m)"
|
@click="previewNodeImage(n.media, m)"
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
@@ -214,6 +215,7 @@
|
|||||||
class="cert-preview-image"
|
class="cert-preview-image"
|
||||||
:src="c.watermarkUrl || c.originUrl"
|
:src="c.watermarkUrl || c.originUrl"
|
||||||
:alt="c.name"
|
:alt="c.name"
|
||||||
|
loading="lazy"
|
||||||
@click="previewCert(c)"
|
@click="previewCert(c)"
|
||||||
/>
|
/>
|
||||||
<div v-else class="cert-pending">{{ t('pages.artwork.watermarkPending') }}</div>
|
<div v-else class="cert-pending">{{ t('pages.artwork.watermarkPending') }}</div>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { AppModule } from './app.module';
|
|||||||
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
|
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
|
||||||
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
|
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
|
||||||
import { OperationLogInterceptor } from './operation-log/operation-log.interceptor';
|
import { OperationLogInterceptor } from './operation-log/operation-log.interceptor';
|
||||||
|
import { STATIC_ASSET_CACHE_CONTROL } from './storage/storage.service';
|
||||||
|
|
||||||
// 让 BigInt 可被 JSON 序列化为字符串,避免精度问题。
|
// 让 BigInt 可被 JSON 序列化为字符串,避免精度问题。
|
||||||
(BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () {
|
(BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () {
|
||||||
@@ -54,6 +55,13 @@ async function bootstrap(): Promise<void> {
|
|||||||
}
|
}
|
||||||
app.useStaticAssets(localDir, {
|
app.useStaticAssets(localDir, {
|
||||||
prefix: config.get<string>('storage.publicPrefix') || '/uploads',
|
prefix: config.get<string>('storage.publicPrefix') || '/uploads',
|
||||||
|
etag: true,
|
||||||
|
lastModified: true,
|
||||||
|
maxAge: '1y',
|
||||||
|
immutable: true,
|
||||||
|
setHeaders: (res) => {
|
||||||
|
res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Swagger(开发文档)
|
// Swagger(开发文档)
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { existsSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'fs';
|
||||||
|
import { dirname, relative, resolve } from 'path';
|
||||||
|
import { PutOptions, StorageDriver } from './storage.types';
|
||||||
|
|
||||||
|
export interface LocalDriverOptions {
|
||||||
|
localDir: string;
|
||||||
|
publicPrefix: string;
|
||||||
|
cdnBaseUrl: string;
|
||||||
|
baseUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 本地磁盘存储驱动(默认)。文件经 Nest 静态目录对外访问。
|
||||||
|
export class LocalDriver implements StorageDriver {
|
||||||
|
private readonly root: string;
|
||||||
|
|
||||||
|
constructor(private readonly opts: LocalDriverOptions) {
|
||||||
|
this.root = resolve(opts.localDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
private fullPath(key: string): string {
|
||||||
|
const full = resolve(this.root, key);
|
||||||
|
const rel = relative(this.root, full);
|
||||||
|
if (rel.startsWith('..') || rel === '' || rel.includes('..\\') || rel.includes('../')) {
|
||||||
|
throw new Error('Unsafe storage key');
|
||||||
|
}
|
||||||
|
return full;
|
||||||
|
}
|
||||||
|
|
||||||
|
async put(key: string, buffer: Buffer, _options?: PutOptions): Promise<void> {
|
||||||
|
const full = this.fullPath(key);
|
||||||
|
mkdirSync(dirname(full), { recursive: true });
|
||||||
|
writeFileSync(full, buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
async get(key: string): Promise<Buffer> {
|
||||||
|
return readFileSync(this.fullPath(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(key: string): Promise<void> {
|
||||||
|
const full = this.fullPath(key);
|
||||||
|
if (existsSync(full)) {
|
||||||
|
rmSync(full, { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getPublicUrl(key: string): string {
|
||||||
|
if (this.opts.cdnBaseUrl) {
|
||||||
|
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
|
||||||
|
}
|
||||||
|
return `${this.opts.baseUrl.replace(/\/$/, '')}${this.opts.publicPrefix}/${key}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import {
|
||||||
|
DeleteObjectCommand,
|
||||||
|
GetObjectCommand,
|
||||||
|
PutObjectCommand,
|
||||||
|
S3Client,
|
||||||
|
} from '@aws-sdk/client-s3';
|
||||||
|
import { PutOptions, StorageDriver } from './storage.types';
|
||||||
|
|
||||||
|
export interface OssDriverOptions {
|
||||||
|
endpoint: string;
|
||||||
|
region: string;
|
||||||
|
bucket: string;
|
||||||
|
accessKeyId: string;
|
||||||
|
accessKeySecret: string;
|
||||||
|
cdnBaseUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// S3 兼容对象存储驱动(阿里云 OSS S3 兼容端点 / MinIO 等通用)。
|
||||||
|
// 仅在 STORAGE_DRIVER=oss 时启用;凭据在 .env 配置,业务代码无需改动即可切换。
|
||||||
|
export class OssDriver implements StorageDriver {
|
||||||
|
private readonly client: S3Client;
|
||||||
|
|
||||||
|
constructor(private readonly opts: OssDriverOptions) {
|
||||||
|
this.client = new S3Client({
|
||||||
|
region: opts.region || 'us-east-1',
|
||||||
|
endpoint: opts.endpoint || undefined,
|
||||||
|
forcePathStyle: true,
|
||||||
|
credentials: {
|
||||||
|
accessKeyId: opts.accessKeyId,
|
||||||
|
secretAccessKey: opts.accessKeySecret,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async put(key: string, buffer: Buffer, options?: PutOptions): Promise<void> {
|
||||||
|
await this.client.send(
|
||||||
|
new PutObjectCommand({
|
||||||
|
Bucket: this.opts.bucket,
|
||||||
|
Key: key,
|
||||||
|
Body: buffer,
|
||||||
|
ContentType: options?.contentType,
|
||||||
|
CacheControl: options?.cacheControl,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async get(key: string): Promise<Buffer> {
|
||||||
|
const res = await this.client.send(
|
||||||
|
new GetObjectCommand({ Bucket: this.opts.bucket, Key: key }),
|
||||||
|
);
|
||||||
|
const bytes = await res.Body!.transformToByteArray();
|
||||||
|
return Buffer.from(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(key: string): Promise<void> {
|
||||||
|
await this.client.send(new DeleteObjectCommand({ Bucket: this.opts.bucket, Key: key }));
|
||||||
|
}
|
||||||
|
|
||||||
|
getPublicUrl(key: string): string {
|
||||||
|
if (this.opts.cdnBaseUrl) {
|
||||||
|
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
|
||||||
|
}
|
||||||
|
const base = (this.opts.endpoint || '').replace(/\/$/, '');
|
||||||
|
return `${base}/${this.opts.bucket}/${key}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { StorageService } from './storage.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [StorageService],
|
||||||
|
exports: [StorageService],
|
||||||
|
})
|
||||||
|
export class StorageModule {}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { createHash } from 'crypto';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import { nanoid } from 'nanoid';
|
||||||
|
import { extname } from 'path';
|
||||||
|
import { LocalDriver } from './local.driver';
|
||||||
|
import { OssDriver } from './oss.driver';
|
||||||
|
import { SavedFile, StorageDriver } from './storage.types';
|
||||||
|
|
||||||
|
export const STATIC_ASSET_CACHE_CONTROL = 'public, max-age=31536000, immutable';
|
||||||
|
|
||||||
|
const MIME_EXT: Record<string, string> = {
|
||||||
|
'image/jpeg': '.jpg',
|
||||||
|
'image/png': '.png',
|
||||||
|
'image/webp': '.webp',
|
||||||
|
'image/gif': '.gif',
|
||||||
|
'image/svg+xml': '.svg',
|
||||||
|
'video/mp4': '.mp4',
|
||||||
|
'video/webm': '.webm',
|
||||||
|
'video/quicktime': '.mov',
|
||||||
|
'application/pdf': '.pdf',
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class StorageService {
|
||||||
|
private readonly logger = new Logger(StorageService.name);
|
||||||
|
private readonly driver: StorageDriver;
|
||||||
|
|
||||||
|
constructor(private readonly config: ConfigService) {
|
||||||
|
const s = this.config.get<Record<string, any>>('storage')!;
|
||||||
|
if (s.driver === 'oss') {
|
||||||
|
this.driver = new OssDriver({
|
||||||
|
endpoint: s.oss.endpoint,
|
||||||
|
region: s.oss.region,
|
||||||
|
bucket: s.oss.bucket,
|
||||||
|
accessKeyId: s.oss.accessKeyId,
|
||||||
|
accessKeySecret: s.oss.accessKeySecret,
|
||||||
|
cdnBaseUrl: s.cdnBaseUrl,
|
||||||
|
});
|
||||||
|
this.logger.log('存储驱动:OSS/S3 兼容');
|
||||||
|
} else {
|
||||||
|
this.driver = new LocalDriver({
|
||||||
|
localDir: s.localDir,
|
||||||
|
publicPrefix: s.publicPrefix,
|
||||||
|
cdnBaseUrl: s.cdnBaseUrl,
|
||||||
|
baseUrl: this.config.get<string>('baseUrl') || 'http://localhost:3000',
|
||||||
|
});
|
||||||
|
this.logger.log('存储驱动:本地磁盘');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildHash(buffer: Buffer): string {
|
||||||
|
return createHash('sha256').update(buffer).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildKey(originalName: string, hash: string, mime?: string): string {
|
||||||
|
const ext = (mime && MIME_EXT[mime]) || extname(originalName) || '';
|
||||||
|
return `${dayjs().format('YYYY/MM/DD')}/${hash.slice(0, 16)}-${nanoid()}${ext}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async save(buffer: Buffer, originalName: string, mime?: string): Promise<SavedFile> {
|
||||||
|
const hash = this.buildHash(buffer);
|
||||||
|
const key = this.buildKey(originalName, hash, mime);
|
||||||
|
await this.driver.put(key, buffer, {
|
||||||
|
contentType: mime,
|
||||||
|
cacheControl: STATIC_ASSET_CACHE_CONTROL,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
url: this.driver.getPublicUrl(key),
|
||||||
|
name: originalName,
|
||||||
|
size: buffer.length,
|
||||||
|
mime: mime || 'application/octet-stream',
|
||||||
|
hash,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async putKey(key: string, buffer: Buffer, mime?: string): Promise<string> {
|
||||||
|
await this.driver.put(key, buffer, {
|
||||||
|
contentType: mime,
|
||||||
|
cacheControl: STATIC_ASSET_CACHE_CONTROL,
|
||||||
|
});
|
||||||
|
return this.driver.getPublicUrl(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
derivedKey(sourceKey: string, suffix: string): string {
|
||||||
|
const ext = extname(sourceKey);
|
||||||
|
const base = sourceKey.slice(0, sourceKey.length - ext.length);
|
||||||
|
return `${base}_${suffix}${ext || '.jpg'}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
getUrl(key: string): string {
|
||||||
|
return this.driver.getPublicUrl(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
read(key: string): Promise<Buffer> {
|
||||||
|
return this.driver.get(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(key: string): Promise<void> {
|
||||||
|
await this.driver.remove(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
export interface PutOptions {
|
||||||
|
contentType?: string;
|
||||||
|
cacheControl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StorageDriver {
|
||||||
|
put(key: string, buffer: Buffer, options?: PutOptions): Promise<void>;
|
||||||
|
get(key: string): Promise<Buffer>;
|
||||||
|
remove(key: string): Promise<void>;
|
||||||
|
getPublicUrl(key: string): string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SavedFile {
|
||||||
|
key: string;
|
||||||
|
url: string;
|
||||||
|
name: string;
|
||||||
|
size: number;
|
||||||
|
mime: string;
|
||||||
|
hash: string;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user