import { pool } from '../db'; /** 每批条数:过期集不大时一次即可;积压时靠次日继续。 */ export const OPERATION_LOG_PURGE_BATCH_SIZE = 5000; /** 每租户每轮上限,避免撑破调度锁 14 分钟 TTL。 */ export const OPERATION_LOG_PURGE_MAX_BATCHES = 20; export type OperationLogRetention = | { enabled: false } | { enabled: true; mode: 'calendar_month' } | { enabled: true; mode: 'days'; days: number }; /** * 未配 OPERATION_LOG_RETENTION_DAYS:自然月(对齐「9/10 清 8/10 前」)。 * 正整数:按天(常用 31)。 * 0 或非法:关闭。 */ export function resolveOperationLogRetention(): OperationLogRetention { const raw = process.env.OPERATION_LOG_RETENTION_DAYS; if (raw == null || String(raw).trim() === '') { return { enabled: true, mode: 'calendar_month' }; } const n = Number(raw); if (!Number.isFinite(n) || n <= 0) { return { enabled: false }; } return { enabled: true, mode: 'days', days: Math.min(Math.floor(n), 3650) }; } async function deleteOneBatch(retention: Extract): Promise { if (retention.mode === 'calendar_month') { const result = await pool.query( `DELETE FROM operation_logs WHERE id IN ( SELECT id FROM operation_logs WHERE created_at < NOW() - INTERVAL '1 month' ORDER BY created_at LIMIT $1 )`, [OPERATION_LOG_PURGE_BATCH_SIZE] ); return result.rowCount ?? 0; } const result = await pool.query( `DELETE FROM operation_logs WHERE id IN ( SELECT id FROM operation_logs WHERE created_at < NOW() - ($2::int * INTERVAL '1 day') ORDER BY created_at LIMIT $1 )`, [OPERATION_LOG_PURGE_BATCH_SIZE, retention.days] ); return result.rowCount ?? 0; } /** 当前 tenant schema 分批删过期 operation_logs。不碰 inventory_logs。 */ export async function purgeExpiredOperationLogsForCurrentTenant(): Promise<{ deleted: number; more: boolean; skipped: boolean; }> { const retention = resolveOperationLogRetention(); if (!retention.enabled) { return { deleted: 0, more: false, skipped: true }; } let deleted = 0; let more = false; for (let i = 0; i < OPERATION_LOG_PURGE_MAX_BATCHES; i += 1) { const n = await deleteOneBatch(retention); deleted += n; if (n < OPERATION_LOG_PURGE_BATCH_SIZE) { more = false; break; } more = i === OPERATION_LOG_PURGE_MAX_BATCHES - 1; } return { deleted, more, skipped: false }; }