From 856522552f2bb504bb5ff06bf3a05b3c288fcb5d Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Thu, 3 Sep 2026 15:33:22 +0800 Subject: [PATCH] chore: enforce operation log retention policy --- .../docs/workflow/生产部署入口说明.md | 10 ++ furniture-3d-system/package.json | 2 + .../migration.sql | 4 + furniture-3d-system/prisma/schema.prisma | 1 + .../scripts/cleanup-operation-logs.ts | 106 +++++++++++++++++ .../install-operation-log-retention-timer.sh | 101 +++++++++++++++++ .../operation-log-retention.repository.ts | 64 +++++++++++ .../operation-log-retention.service.test.ts | 76 +++++++++++++ .../operation-log-retention.service.ts | 107 ++++++++++++++++++ 9 files changed, 471 insertions(+) create mode 100644 furniture-3d-system/prisma/migrations/20260903190000_add_operation_log_retention_index/migration.sql create mode 100644 furniture-3d-system/scripts/cleanup-operation-logs.ts create mode 100644 furniture-3d-system/scripts/install-operation-log-retention-timer.sh create mode 100644 furniture-3d-system/src/server/repositories/operation-log-retention.repository.ts create mode 100644 furniture-3d-system/src/server/services/operation-log-retention.service.test.ts create mode 100644 furniture-3d-system/src/server/services/operation-log-retention.service.ts diff --git a/furniture-3d-system/docs/workflow/生产部署入口说明.md b/furniture-3d-system/docs/workflow/生产部署入口说明.md index 7b908f17..413b2e35 100644 --- a/furniture-3d-system/docs/workflow/生产部署入口说明.md +++ b/furniture-3d-system/docs/workflow/生产部署入口说明.md @@ -50,6 +50,16 @@ - 准确度回测:`npm run backtest:bom-cost-reference -- --sample-size=30`,只读最新成功镜像,不访问上游;样本限制 20 至 50 个,任一可比较 SKU 超过固定 10% 误差门槛即失败。 - 迁移、真实同步、安装/启用定时器和生产回测都必须另行获得生产操作授权;部署代码本身不代表这些动作已经执行。 +## 操作日志保留策略 + +- 清理脚本:`npm run db:cleanup-operation-logs` 默认只做 dry-run;只有显式传入 `--apply --confirm=cleanup-operation-logs` 才会删除数据。 +- 自动清理范围严格限定为 `OperationLog` 中 `SYSTEM + SUPPLY_CHAIN_PRODUCT_ARCHIVE + details.kind=UPDATED + SUCCESS` 且创建时间早于 30 天的字段变更。 +- 用户操作、商品档案导入、失败/重试日志及其他业务范围日志至少保留 365 天;本次策略不自动删除超过 365 天的审计日志。 +- 生产安装入口:`furniture-3d-system/scripts/install-operation-log-retention-timer.sh`。 +- 生产 systemd 名称:`furniture-operation-log-retention.service` / `furniture-operation-log-retention.timer`,默认每天中国标准时间 `04:30` 执行,附带最多 10 分钟随机延迟。 +- 安装脚本会在 `/opt/furniture-3d-system-prod/shared/operation-log-retention.env` 保存权限为 `600` 的数据库身份门禁和非敏感参数;身份未填写或保留天数不是 30 天时拒绝启用。 +- 首次启用前必须先在生产执行 dry-run,核对候选数量、数据库身份和 systemd 落点;生产安装、首次 `--apply` 和后续代码部署均需另行获得授权。 + ## 明确排除 - `192.168.58.20` 不是当前 `furniture-3d-system` 的生产部署目标。 diff --git a/furniture-3d-system/package.json b/furniture-3d-system/package.json index a3e55f2b..48bcb428 100644 --- a/furniture-3d-system/package.json +++ b/furniture-3d-system/package.json @@ -31,6 +31,8 @@ "db:verify-master-data:production-readonly": "node scripts/verify-master-data-foundation.js --read-only-quality --summary-output .master-data-audits/foundation-production-readonly-current.summary.json --summary-stdout", "db:cleanup-master-data": "node scripts/apply-master-data-cleanup-plan.js", "db:cleanup-master-data:validate": "node scripts/apply-master-data-cleanup-plan.js --validate-plan", + "db:cleanup-operation-logs": "tsx scripts/cleanup-operation-logs.ts", + "db:cleanup-operation-logs:apply": "tsx scripts/cleanup-operation-logs.ts --apply --confirm=cleanup-operation-logs", "db:export-product-category-review": "node scripts/export-non-integrated-product-category-review.js", "db:build-product-category-cleanup-plan": "node scripts/build-non-integrated-product-category-cleanup-plan.js", "db:match-jst-product-category-cleanup-plan": "node scripts/match-jst-product-category-cleanup-plan.js", diff --git a/furniture-3d-system/prisma/migrations/20260903190000_add_operation_log_retention_index/migration.sql b/furniture-3d-system/prisma/migrations/20260903190000_add_operation_log_retention_index/migration.sql new file mode 100644 index 00000000..7d9722c7 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20260903190000_add_operation_log_retention_index/migration.sql @@ -0,0 +1,4 @@ +-- Supports the bounded retention scan for system-generated product archive +-- field-change logs without changing the audit data itself. +CREATE INDEX "OperationLog_retention_scope_createdAt_idx" +ON "OperationLog"("workspaceCategory", "source", "status", "createdAt"); diff --git a/furniture-3d-system/prisma/schema.prisma b/furniture-3d-system/prisma/schema.prisma index 8618c4a9..39535777 100644 --- a/furniture-3d-system/prisma/schema.prisma +++ b/furniture-3d-system/prisma/schema.prisma @@ -3192,6 +3192,7 @@ model OperationLog { @@index([actorId, createdAt]) @@index([productSpu, createdAt]) @@index([productId, createdAt]) + @@index([workspaceCategory, source, status, createdAt], map: "OperationLog_retention_scope_createdAt_idx") } // 家具系统发往统一通知中心的本地审计副本。 diff --git a/furniture-3d-system/scripts/cleanup-operation-logs.ts b/furniture-3d-system/scripts/cleanup-operation-logs.ts new file mode 100644 index 00000000..7939cb71 --- /dev/null +++ b/furniture-3d-system/scripts/cleanup-operation-logs.ts @@ -0,0 +1,106 @@ +import { loadEnvConfig } from '@next/env' + +loadEnvConfig(process.cwd()) + +const CONFIRM_TOKEN = 'cleanup-operation-logs' +const DEFAULT_RETENTION_DAYS = 30 +const DEFAULT_BATCH_SIZE = 1000 + +function readArgument(name: string) { + const prefix = `--${name}=` + return ( + process.argv + .slice(2) + .find((argument) => argument.startsWith(prefix)) + ?.slice(prefix.length) ?? '' + ) +} + +function databaseIdentity(databaseUrl: string) { + const parsed = new URL(databaseUrl) + return [ + parsed.protocol.replace(/:$/, ''), + decodeURIComponent(parsed.username || ''), + parsed.hostname, + parsed.port || '', + parsed.pathname.replace(/^\//, ''), + parsed.searchParams.get('schema') ?? '', + ].join('|') +} + +function readPositiveInteger(name: string, fallback: number, max: number) { + const value = Number(readArgument(name) || fallback) + if (!Number.isSafeInteger(value) || value < 1 || value > max) { + throw new Error(`--${name} must be an integer between 1 and ${max}.`) + } + return value +} + +async function main() { + const databaseUrl = process.env.DATABASE_URL?.trim() ?? '' + if (!databaseUrl) throw new Error('DATABASE_URL is required.') + + const retentionDays = readPositiveInteger( + 'retention-days', + Number(process.env.OPERATION_LOG_SYSTEM_FIELD_RETENTION_DAYS || DEFAULT_RETENTION_DAYS), + 365, + ) + if (retentionDays !== DEFAULT_RETENTION_DAYS) { + throw new Error( + `The approved system field-change retention is ${DEFAULT_RETENTION_DAYS} days; do not override it in production.`, + ) + } + + const batchSize = readPositiveInteger( + 'batch-size', + Number(process.env.OPERATION_LOG_CLEANUP_BATCH_SIZE || DEFAULT_BATCH_SIZE), + 5000, + ) + const apply = process.argv.includes('--apply') + if (apply && readArgument('confirm') !== CONFIRM_TOKEN) { + throw new Error(`Pass --confirm=${CONFIRM_TOKEN} when using --apply.`) + } + + const actualDatabaseIdentity = databaseIdentity(databaseUrl) + if ( + apply && + readArgument('expected-database-identity') !== actualDatabaseIdentity + ) { + throw new Error( + `Pass --expected-database-identity=${actualDatabaseIdentity} when using --apply.`, + ) + } + + const [{ prisma }, { operationLogRetentionService }] = await Promise.all([ + import('../src/lib/prisma'), + import('../src/server/services/operation-log-retention.service'), + ]) + + try { + const result = await operationLogRetentionService.cleanup({ + now: new Date(), + batchSize, + apply, + }) + console.log( + JSON.stringify( + { + ...result, + cutoff: result.cutoff.toISOString(), + databaseIdentity: apply ? actualDatabaseIdentity : undefined, + }, + null, + 2, + ), + ) + } finally { + await prisma.$disconnect() + } +} + +void main().catch((error) => { + console.error(error instanceof Error ? error.message : String(error)) + process.exitCode = 1 +}) + +export { databaseIdentity, readArgument, readPositiveInteger } diff --git a/furniture-3d-system/scripts/install-operation-log-retention-timer.sh b/furniture-3d-system/scripts/install-operation-log-retention-timer.sh new file mode 100644 index 00000000..793fdb82 --- /dev/null +++ b/furniture-3d-system/scripts/install-operation-log-retention-timer.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +set -euo pipefail + +BASE="${FURNITURE_PROD_BASE:-/opt/furniture-3d-system-prod}" +SERVICE_NAME="${OPERATION_LOG_RETENTION_SERVICE_NAME:-furniture-operation-log-retention}" +APP_ROOT="$BASE/current/furniture-3d-system" +SHARED="$BASE/shared" +APP_ENV="$SHARED/.env" +RETENTION_ENV="$SHARED/operation-log-retention.env" +SERVICE_FILE="/etc/systemd/system/$SERVICE_NAME.service" +TIMER_FILE="/etc/systemd/system/$SERVICE_NAME.timer" +RETENTION_CALENDAR="${OPERATION_LOG_RETENTION_CALENDAR:-*-*-* 04:30:00 Asia/Shanghai}" +RANDOMIZED_DELAY_SEC="${OPERATION_LOG_RETENTION_RANDOMIZED_DELAY_SEC:-10min}" +CONFIRM_TOKEN="cleanup-operation-logs" + +if [ "$(id -u)" -ne 0 ]; then + echo "This installer must run as root." >&2 + exit 1 +fi + +if [ ! -d "$APP_ROOT" ]; then + echo "Missing app root: $APP_ROOT" >&2 + exit 1 +fi + +if [ ! -f "$APP_ENV" ]; then + echo "Missing app env: $APP_ENV" >&2 + exit 1 +fi + +mkdir -p "$SHARED" +if [ ! -f "$RETENTION_ENV" ]; then + umask 077 + cat >"$RETENTION_ENV" <<'EOF' +# Operation log retention controls. Do not commit secrets to Git. +# Must match the production DATABASE_URL identity before enabling the timer. +OPERATION_LOG_EXPECTED_DATABASE_IDENTITY= +OPERATION_LOG_SYSTEM_FIELD_RETENTION_DAYS=30 +OPERATION_LOG_CLEANUP_BATCH_SIZE=1000 +EOF + echo "Created env template: $RETENTION_ENV" +fi + +chmod 600 "$RETENTION_ENV" + +if ! grep -Eq '^OPERATION_LOG_EXPECTED_DATABASE_IDENTITY=.+$' "$RETENTION_ENV"; then + echo "Missing OPERATION_LOG_EXPECTED_DATABASE_IDENTITY in $RETENTION_ENV; timer was not installed." >&2 + exit 2 +fi + +if ! grep -Eq '^DATABASE_URL=.+$' "$APP_ENV"; then + echo "Missing DATABASE_URL in $APP_ENV; timer was not installed." >&2 + exit 2 +fi + +if ! grep -Eq '^OPERATION_LOG_SYSTEM_FIELD_RETENTION_DAYS=30$' "$RETENTION_ENV"; then + echo "OPERATION_LOG_SYSTEM_FIELD_RETENTION_DAYS must be 30; timer was not installed." >&2 + exit 2 +fi + +if command -v systemd-analyze >/dev/null 2>&1; then + systemd-analyze calendar "$RETENTION_CALENDAR" >/dev/null +fi + +cat >"$SERVICE_FILE" <"$TIMER_FILE" < + findEligibleIds(input: { + cutoff: Date + batchSize: number + }): Promise + deleteByIds(ids: string[]): Promise +} + +class OperationLogRetentionRepositoryClass + implements OperationLogRetentionRepository +{ + async countEligible(cutoff: Date) { + return prisma.operationLog.count({ + where: buildOperationLogRetentionWhere(cutoff), + }) + } + + async findEligibleIds(input: { cutoff: Date; batchSize: number }) { + const rows = await prisma.operationLog.findMany({ + where: buildOperationLogRetentionWhere(input.cutoff), + orderBy: [{ createdAt: 'asc' }, { id: 'asc' }], + take: input.batchSize, + select: { id: true }, + }) + return rows.map((row) => row.id) + } + + async deleteByIds(ids: string[]) { + if (ids.length === 0) return 0 + const result = await prisma.operationLog.deleteMany({ + where: { id: { in: ids } }, + }) + return result.count + } +} + +export const operationLogRetentionRepository = + new OperationLogRetentionRepositoryClass() + +export { OperationLogRetentionRepositoryClass } diff --git a/furniture-3d-system/src/server/services/operation-log-retention.service.test.ts b/furniture-3d-system/src/server/services/operation-log-retention.service.test.ts new file mode 100644 index 00000000..99234345 --- /dev/null +++ b/furniture-3d-system/src/server/services/operation-log-retention.service.test.ts @@ -0,0 +1,76 @@ +import { + AUDIT_LOG_MIN_RETENTION_DAYS, + DEFAULT_OPERATION_LOG_CLEANUP_BATCH_SIZE, + OperationLogRetentionService, + SYSTEM_FIELD_CHANGE_RETENTION_DAYS, + getOperationLogRetentionCutoff, + getOperationLogRetentionPolicy, +} from './operation-log-retention.service' + +describe('operation log retention service', () => { + it('uses the approved 30-day cutoff and exposes the protected audit policy', () => { + const now = new Date('2026-09-03T00:00:00.000Z') + + expect(getOperationLogRetentionCutoff(now)).toEqual( + new Date('2026-08-04T00:00:00.000Z'), + ) + expect(getOperationLogRetentionPolicy()).toEqual( + expect.objectContaining({ + systemFieldChangeRetentionDays: SYSTEM_FIELD_CHANGE_RETENTION_DAYS, + auditLogMinimumRetentionDays: AUDIT_LOG_MIN_RETENTION_DAYS, + }), + ) + }) + + it('keeps dry-run read-only', async () => { + const repository = { + countEligible: jest.fn().mockResolvedValue(12), + findEligibleIds: jest.fn(), + deleteByIds: jest.fn(), + } + const service = new OperationLogRetentionService(repository) + + const result = await service.cleanup({ + now: new Date('2026-09-03T00:00:00.000Z'), + }) + + expect(result.mode).toBe('dry-run') + expect(result.candidates).toBe(12) + expect(result.deleted).toBe(0) + expect(result.batchSize).toBe(DEFAULT_OPERATION_LOG_CLEANUP_BATCH_SIZE) + expect(repository.findEligibleIds).not.toHaveBeenCalled() + expect(repository.deleteByIds).not.toHaveBeenCalled() + }) + + it('deletes only in bounded batches when apply is explicit', async () => { + const repository = { + countEligible: jest.fn().mockResolvedValue(3), + findEligibleIds: jest + .fn() + .mockResolvedValueOnce(['log-1', 'log-2']) + .mockResolvedValueOnce(['log-3']) + .mockResolvedValueOnce([]), + deleteByIds: jest + .fn() + .mockResolvedValueOnce(2) + .mockResolvedValueOnce(1), + } + const service = new OperationLogRetentionService(repository) + + const result = await service.cleanup({ + now: new Date('2026-09-03T00:00:00.000Z'), + batchSize: 2, + apply: true, + }) + + expect(result.mode).toBe('apply') + expect(result.candidates).toBe(3) + expect(result.deleted).toBe(3) + expect(repository.findEligibleIds).toHaveBeenNthCalledWith(1, { + cutoff: new Date('2026-08-04T00:00:00.000Z'), + batchSize: 2, + }) + expect(repository.deleteByIds).toHaveBeenNthCalledWith(1, ['log-1', 'log-2']) + expect(repository.deleteByIds).toHaveBeenNthCalledWith(2, ['log-3']) + }) +}) diff --git a/furniture-3d-system/src/server/services/operation-log-retention.service.ts b/furniture-3d-system/src/server/services/operation-log-retention.service.ts new file mode 100644 index 00000000..75d7340a --- /dev/null +++ b/furniture-3d-system/src/server/services/operation-log-retention.service.ts @@ -0,0 +1,107 @@ +import { + operationLogRetentionRepository, + type OperationLogRetentionRepository, +} from '@/server/repositories/operation-log-retention.repository' + +export const SYSTEM_FIELD_CHANGE_RETENTION_DAYS = 30 +export const AUDIT_LOG_MIN_RETENTION_DAYS = 365 +export const DEFAULT_OPERATION_LOG_CLEANUP_BATCH_SIZE = 1000 + +const DAY_MS = 24 * 60 * 60 * 1000 + +export type OperationLogRetentionPolicy = { + systemFieldChangeRetentionDays: number + auditLogMinimumRetentionDays: number + protectedCategories: readonly string[] +} + +export type OperationLogCleanupResult = { + mode: 'dry-run' | 'apply' + cutoff: Date + candidates: number + deleted: number + batchSize: number + policy: OperationLogRetentionPolicy +} + +export function getOperationLogRetentionCutoff( + now = new Date(), + retentionDays = SYSTEM_FIELD_CHANGE_RETENTION_DAYS, +) { + if (!Number.isSafeInteger(retentionDays) || retentionDays < 1) { + throw new Error('retentionDays must be a positive integer.') + } + return new Date(now.getTime() - retentionDays * DAY_MS) +} + +export function getOperationLogRetentionPolicy(): OperationLogRetentionPolicy { + return { + systemFieldChangeRetentionDays: SYSTEM_FIELD_CHANGE_RETENTION_DAYS, + auditLogMinimumRetentionDays: AUDIT_LOG_MIN_RETENTION_DAYS, + protectedCategories: [ + 'user operations', + 'import records', + 'failed/retry logs', + 'non-product-archive logs', + ], + } +} + +class OperationLogRetentionService { + constructor( + private readonly repository: OperationLogRetentionRepository = + operationLogRetentionRepository, + ) {} + + async cleanup(input: { + now?: Date + batchSize?: number + apply?: boolean + }): Promise { + const batchSize = normalizeBatchSize(input.batchSize) + const cutoff = getOperationLogRetentionCutoff(input.now) + const candidates = await this.repository.countEligible(cutoff) + const mode = input.apply ? 'apply' : 'dry-run' + + if (!input.apply || candidates === 0) { + return { + mode, + cutoff, + candidates, + deleted: 0, + batchSize, + policy: getOperationLogRetentionPolicy(), + } + } + + let deleted = 0 + while (true) { + const ids = await this.repository.findEligibleIds({ cutoff, batchSize }) + if (ids.length === 0) break + const deletedInBatch = await this.repository.deleteByIds(ids) + if (deletedInBatch === 0) break + deleted += deletedInBatch + } + + return { + mode, + cutoff, + candidates, + deleted, + batchSize, + policy: getOperationLogRetentionPolicy(), + } + } +} + +function normalizeBatchSize(value?: number) { + const batchSize = value ?? DEFAULT_OPERATION_LOG_CLEANUP_BATCH_SIZE + if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 5000) { + throw new Error('batchSize must be an integer between 1 and 5000.') + } + return batchSize +} + +export const operationLogRetentionService = new OperationLogRetentionService() + +export { OperationLogRetentionService }