来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
82 lines
2.5 KiB
TypeScript
82 lines
2.5 KiB
TypeScript
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<OperationLogRetention, { enabled: true }>): Promise<number> {
|
|
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 };
|
|
}
|