/** * Periodically prunes `candle_predict_candles` using admin settings: * - age window (`candle_predict_retention_days`) * - per-interval cap (`candle_predict_retention_keep_last`) * Either rule with value `0` is disabled. When both are set, both run. */ import * as settingsRepository from '../repositories/settingsRepository'; import * as candlePredictRepository from '../repositories/candlePredictRepository'; const PURGE_INTERVAL_MS = 15 * 60 * 1000; const MAX_BATCHES_PER_RUN = 20; const DAY_MS = 24 * 60 * 60 * 1000; let started = false; export type CandleRetentionPlan = { cutoffOpenMs: number | null; keepLast: number | null; }; /** Pure plan from settings — used by the job and unit tests. */ export function resolveCandleRetentionPlan(input: { retentionDays: number; keepLast: number; nowMs?: number; }): CandleRetentionPlan { const days = Number.isFinite(input.retentionDays) ? Math.floor(input.retentionDays) : 0; const keepLast = Number.isFinite(input.keepLast) ? Math.floor(input.keepLast) : 0; const nowMs = input.nowMs ?? Date.now(); return { cutoffOpenMs: days > 0 ? nowMs - days * DAY_MS : null, keepLast: keepLast > 0 ? keepLast : null, }; } export async function purgeExpiredCandles(): Promise<{ byAge: number; byCount: number }> { const settings = await settingsRepository.getSettings(); const plan = resolveCandleRetentionPlan({ retentionDays: settings.candle_predict_retention_days, keepLast: settings.candle_predict_retention_keep_last, }); let byAge = 0; let byCount = 0; if (plan.cutoffOpenMs != null) { for (let i = 0; i < MAX_BATCHES_PER_RUN; i += 1) { const batch = await candlePredictRepository.deleteCandlesOlderThanOpenMs(plan.cutoffOpenMs); byAge += batch; if (batch === 0) break; } } if (plan.keepLast != null) { for (let i = 0; i < MAX_BATCHES_PER_RUN; i += 1) { const batch = await candlePredictRepository.deleteCandlesBeyondKeepLastPerInterval( plan.keepLast ); byCount += batch; if (batch === 0) break; } } if (byAge > 0 || byCount > 0) { console.log( `[candle-retention] purged ${byAge} by age` + (plan.cutoffOpenMs != null ? ` (>${settings.candle_predict_retention_days}d)` : '') + `, ${byCount} by keep-last` + (plan.keepLast != null ? ` (keep ${plan.keepLast}/interval)` : '') ); } return { byAge, byCount }; } export function startCandleRetentionJob(): void { if (started) return; started = true; const run = async () => { try { await purgeExpiredCandles(); } catch (e) { console.error('[candle-retention] purge failed:', e); } setTimeout(run, PURGE_INTERVAL_MS); }; setTimeout(run, 45_000); }