diff --git a/.env.example b/.env.example index 6f6ceb78..0b2d8a83 100644 --- a/.env.example +++ b/.env.example @@ -159,6 +159,9 @@ MCP_USER_EMAIL="" # E2E_ALLOWED_PORTS 与 E2E_NETWORK_LOG 由启动器传给测试进程,用于限制和记录运行时外连。 # E2E_REPORT_DIR 在 CI 中由启动器写入,供后续步骤上传测试报告。 +# AI 用量明细(AiCompletion)保留天数,默认 180;只清理过期明细,不影响 AiUsage/AiDailyUsage 额度与汇总统计。 +# AI_COMPLETION_RETENTION_DAYS=180 + # 匿名遥测:设为 true 时强制关闭本地记录、错误回报与外发(演示站、内网合规场景),优先级最高。 # 详见 doc/TELEMETRY_DESIGN.md。 TELEMETRY_DISABLED="false" diff --git a/src/__tests__/unit/ai-completion-cleanup.test.ts b/src/__tests__/unit/ai-completion-cleanup.test.ts new file mode 100644 index 00000000..c7d14c2f --- /dev/null +++ b/src/__tests__/unit/ai-completion-cleanup.test.ts @@ -0,0 +1,141 @@ +// @vitest-environment node +/** + * AiCompletion 保留期清理(真实 SQLite):只删过期明细,不影响 AiUsage/AiDailyUsage, + * 保留天数可由环境变量覆盖;定时清理启动一分钟后执行并转为 6 小时周期。 + */ +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { PrismaClient } from '@prisma/client'; +import type { Prisma } from '@prisma/client'; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ prisma: undefined as PrismaClient | undefined })); + +vi.mock('@/lib/prisma', () => ({ get prisma() { return mocks.prisma; } })); +vi.mock('@/lib/logger', () => ({ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }) })); + +import { + DEFAULT_AI_COMPLETION_RETENTION_DAYS, + aiCompletionRetentionDays, + purgeAiCompletions, + startAiCompletionCleanupScheduler, +} from '@/lib/ai/completion-cleanup'; + +const DAY = 24 * 60 * 60 * 1000; + +let database: PrismaClient; +let directory: string; + +beforeAll(async () => { + // 只使用系统临时数据库,不接触开发或生产数据 + directory = mkdtempSync(join(tmpdir(), 'wrong-notebook-ai-completion-cleanup-test-')); + const url = `file:${join(directory, 'test.db')}`; + execFileSync(process.execPath, [resolve('node_modules/prisma/build/index.js'), 'migrate', 'deploy'], { + env: { ...process.env, DATABASE_URL: url }, + stdio: 'pipe', + }); + database = new PrismaClient({ datasources: { db: { url } } }); + await database.$queryRaw`PRAGMA journal_mode = WAL`; + await database.$queryRaw`PRAGMA busy_timeout = 30000`; + mocks.prisma = database; +}, 120000); + +beforeEach(async () => { + await database.aiCompletion.deleteMany(); + await database.aiUsage.deleteMany(); + await database.aiDailyUsage.deleteMany(); + await database.user.deleteMany(); + await database.user.createMany({ data: [ + { id: 'user-1', email: 'cleanup@example.com', password: 'test-only' }, + { id: 'user-2', email: 'other@example.com', password: 'test-only' }, + ] }); +}, 30000); + +afterAll(async () => { + await database?.$disconnect(); + if (directory) rmSync(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); +}); + +/** 建一条用量明细;createdAt 由调用方按 now 计算 */ +function completion(id: string, createdAt: Date, overrides: Partial = {}): Prisma.AiCompletionUncheckedCreateInput { + return { id, userId: 'user-1', kind: 'analyze', task: 'analyze', provider: 'openai', durationMs: 10, status: 'succeeded', createdAt, ...overrides }; +} + +describe('AI 用量明细保留期清理', () => { + it('超过保留期的明细被删除,保留期内与未设置 createdAt 的明细保留', async () => { + const now = new Date(); + const old = new Date(now.getTime() - 200 * DAY); + const recent = new Date(now.getTime() - 2 * DAY); + await database.aiCompletion.createMany({ data: [ + completion('old', old), + completion('recent', recent), + completion('other-user-old', old, { userId: 'user-2' }), + ] }); + + expect(await purgeAiCompletions(now, 'user-1')).toBe(1); + const remaining = await database.aiCompletion.findMany({ select: { id: true }, orderBy: { id: 'asc' } }); + expect(remaining.map((row) => row.id)).toEqual(['other-user-old', 'recent']); + }); + + it('不给 userId 时清理所有用户,不影响 AiUsage 与 AiDailyUsage 汇总', async () => { + const now = new Date(); + const old = new Date(now.getTime() - 200 * DAY); + await database.aiCompletion.createMany({ data: [ + completion('u1-old', old), + completion('u2-old', old, { userId: 'user-2' }), + completion('u2-recent', new Date(now.getTime() - DAY), { userId: 'user-2' }), + ] }); + await database.aiUsage.createMany({ data: [ + { id: 'usage-old', userId: 'user-1', kind: 'analyze', createdAt: old }, + { id: 'usage-new', userId: 'user-1', kind: 'practice', createdAt: new Date(now.getTime() - DAY) }, + ] }); + await database.aiDailyUsage.create({ data: { id: 'daily-old', userId: 'user-1', day: old.toISOString(), count: 12 } }); + + expect(await purgeAiCompletions(now)).toBe(2); + expect(await database.aiCompletion.findMany({ select: { id: true } })).toEqual([{ id: 'u2-recent' }]); + expect(await database.aiUsage.count()).toBe(2); + expect((await database.aiDailyUsage.findUnique({ where: { id: 'daily-old' } }))?.count).toBe(12); + }); + + it('保留天数由 AI_COMPLETION_RETENTION_DAYS 覆盖,非法值回退默认', () => { + vi.stubEnv('AI_COMPLETION_RETENTION_DAYS', ''); + expect(aiCompletionRetentionDays()).toBe(DEFAULT_AI_COMPLETION_RETENTION_DAYS); + vi.stubEnv('AI_COMPLETION_RETENTION_DAYS', 'abc'); + expect(aiCompletionRetentionDays()).toBe(DEFAULT_AI_COMPLETION_RETENTION_DAYS); + vi.stubEnv('AI_COMPLETION_RETENTION_DAYS', '30'); + expect(aiCompletionRetentionDays()).toBe(30); + vi.stubEnv('AI_COMPLETION_RETENTION_DAYS', '99999'); + expect(aiCompletionRetentionDays()).toBe(3650); + vi.unstubAllEnvs(); + }); +}); + +describe('定时清理', () => { + /** 启动调度器前重置全局标记,避免与其他用例共用状态 */ + function freshScheduler() { + const globalState = globalThis as { __aiCompletionCleanupStarted?: boolean }; + globalState.__aiCompletionCleanupStarted = false; + } + + it('启动一分钟后清理一次,之后每 6 小时一次,且重复启动不叠加定时器', async () => { + vi.useFakeTimers(); + try { + freshScheduler(); + const old = new Date(Date.now() - 200 * DAY); + await database.aiCompletion.create({ data: completion('scheduled-old', old) }); + startAiCompletionCleanupScheduler(); + startAiCompletionCleanupScheduler(); + expect(vi.getTimerCount()).toBe(1); + expect(await database.aiCompletion.count()).toBe(1); + await vi.advanceTimersByTimeAsync(60 * 1000); + expect(vi.getTimerCount()).toBe(1); + await vi.waitFor(async () => { expect(await database.aiCompletion.count()).toBe(0); }); + await vi.advanceTimersByTimeAsync(6 * 60 * 60 * 1000); + expect(vi.getTimerCount()).toBe(1); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/src/instrumentation.ts b/src/instrumentation.ts index f417422d..94f45495 100644 --- a/src/instrumentation.ts +++ b/src/instrumentation.ts @@ -17,6 +17,10 @@ export async function register() { const { startImportCleanupScheduler } = await import('./lib/import/import-cleanup'); startImportCleanupScheduler(); + // AI 用量明细:按保留期定期清理,避免长期运行后 SQLite 无限增长 + const { startAiCompletionCleanupScheduler } = await import('./lib/ai/completion-cleanup'); + startAiCompletionCleanupScheduler(); + // 全新安装还没有管理员时,在启动日志中打印一次性初始化链接 const { announceSetupLink } = await import('./lib/initialization'); await announceSetupLink(); diff --git a/src/lib/ai/completion-cleanup.ts b/src/lib/ai/completion-cleanup.ts new file mode 100644 index 00000000..e0c7a386 --- /dev/null +++ b/src/lib/ai/completion-cleanup.ts @@ -0,0 +1,70 @@ +/** + * AI 用量明细(AiCompletion)的保留期清理。 + * + * AiCompletion 每次 AI 调用写入一条 token 用量记录,长期运行的 NAS/桌面实例会持续增长。 + * 默认保留 180 天,只删除过期明细,不影响 AiUsage / AiDailyUsage 的额度与汇总统计。 + * 清理不依赖用户打开任何页面:服务启动后先清理一次,之后每 6 小时一次。 + */ + +import "server-only"; + +import { serializeWrite } from "@/lib/db-write-queue"; +import { createLogger } from "@/lib/logger"; +import { prisma } from "@/lib/prisma"; + +const logger = createLogger('ai:completion-cleanup'); + +const DAY_MS = 24 * 60 * 60 * 1000; +/** 默认保留天数:覆盖年度统计所需的历史明细 */ +export const DEFAULT_AI_COMPLETION_RETENTION_DAYS = 180; +/** 环境变量允许的最大保留天数,避免误填极端值导致永不清理 */ +const MAX_RETENTION_DAYS = 3650; +/** 定时清理间隔:6 小时,与导入任务、遥测清理一致 */ +const PURGE_INTERVAL_MS = 6 * 60 * 60 * 1000; +/** 启动后先等一分钟,避开启动时的迁移与初始化 */ +const FIRST_PURGE_DELAY_MS = 60 * 1000; + +const scheduler = globalThis as typeof globalThis & { __aiCompletionCleanupStarted?: boolean }; + +/** 读取 AI_COMPLETION_RETENTION_DAYS;未设置或非法时用默认值,超出范围时收敛到边界 */ +export function aiCompletionRetentionDays(): number { + const raw = process.env.AI_COMPLETION_RETENTION_DAYS?.trim(); + if (!raw) return DEFAULT_AI_COMPLETION_RETENTION_DAYS; + const days = Number(raw); + if (!Number.isFinite(days) || days <= 0) return DEFAULT_AI_COMPLETION_RETENTION_DAYS; + return Math.min(Math.floor(days), MAX_RETENTION_DAYS); +} + +/** + * 删除超过保留期的 AiCompletion 明细。 + * userId 为空时清理所有用户(定时任务);给出时只清理该用户。 + * 经写入队列串行执行,避免与业务写入争用 SQLite 写锁。 + */ +export async function purgeAiCompletions(now = new Date(), userId?: string): Promise { + const cutoff = new Date(now.getTime() - aiCompletionRetentionDays() * DAY_MS); + const scope = userId ? { userId } : {}; + try { + const result = await serializeWrite(() => prisma.aiCompletion.deleteMany({ + where: { ...scope, createdAt: { lt: cutoff } }, + })); + return result.count; + } catch (error) { + logger.warn({ error, userId }, 'Failed to purge expired AI completions'); + return 0; + } +} + +/** 常驻进程中启动 AiCompletion 的定期清理:启动一分钟后清理一次,之后每 6 小时一次 */ +export function startAiCompletionCleanupScheduler(): void { + if (scheduler.__aiCompletionCleanupStarted) return; + scheduler.__aiCompletionCleanupStarted = true; + const purge = () => { + void purgeAiCompletions().then((count) => { + if (count > 0) logger.info({ count }, 'Purged expired AI completions'); + }).catch(() => undefined); + }; + setTimeout(() => { + purge(); + setInterval(purge, PURGE_INTERVAL_MS).unref(); + }, FIRST_PURGE_DELAY_MS).unref(); +}