'use strict'; const { loadConfig } = require('./config'); const { getDb } = require('./db'); const { SESSION_IDLE_TIMEOUT_MS } = require('./auth'); const SCHEDULER_INTERVAL_MS = 60 * 1000; const CADENCE_DAYS = { daily: 1, every3days: 3, weekly: 7, biweekly: 14, }; let schedulerTimer = null; let shutdownForRestartFn = null; let state = { startedAt: null, lastTickAt: null, nextDueAt: null, pendingSinceAt: null, lastShutdownAt: null, lastDecision: 'idle', lastError: null, configKey: null, underSystemd: false, }; function nowMs () { return Date.now(); } function parseTimeToUtcParts (value) { const match = String(value || '').trim().match(/^([01]\d|2[0-3]):([0-5]\d)$/); if (!match) return null; return { hour: Number.parseInt(match[1], 10), minute: Number.parseInt(match[2], 10), }; } function addCadence (date, cadence) { const next = new Date(date.getTime()); if (cadence === 'monthly') { next.setUTCMonth(next.getUTCMonth() + 1); return next; } const days = CADENCE_DAYS[cadence] || 1; next.setUTCDate(next.getUTCDate() + days); return next; } function buildScheduleConfig (config) { const scheduled = config && config.scheduledRestart && typeof config.scheduledRestart === 'object' ? config.scheduledRestart : {}; return { enabled: !!scheduled.enabled, cadence: String(scheduled.cadence || 'daily'), time: String(scheduled.time || '04:00'), }; } function configKeyFor (underSystemd, cfg) { return JSON.stringify({ underSystemd: !!underSystemd, enabled: !!cfg.enabled, cadence: cfg.cadence, time: cfg.time, }); } function computeInitialDueAt (schedule, now) { const parts = parseTimeToUtcParts(schedule.time); if (!parts) return null; const current = new Date(now); const due = new Date(now); due.setUTCHours(parts.hour, parts.minute, 0, 0); if (due.getTime() <= current.getTime()) { return addCadence(due, schedule.cadence).getTime(); } return due.getTime(); } function advanceDueAt (currentDueAt, schedule) { const due = new Date(Number(currentDueAt) || nowMs()); return addCadence(due, schedule.cadence).getTime(); } function noLoggedInClientsForIdleWindow (now) { const db = getDb(); const row = db.prepare( `SELECT MAX(last_seen_at) AS lastSeenAt FROM auth_sessions WHERE revoked_at IS NULL`, ).get(); const lastSeenAt = Number(row && row.lastSeenAt || 0); if (!Number.isFinite(lastSeenAt) || lastSeenAt <= 0) return true; return now - lastSeenAt >= SESSION_IDLE_TIMEOUT_MS; } function resetPendingState () { state.pendingSinceAt = null; } function applyConfigState (underSystemd, schedule, now) { const nextKey = configKeyFor(underSystemd, schedule); if (state.configKey === nextKey) return; state.configKey = nextKey; state.underSystemd = !!underSystemd; state.lastError = null; resetPendingState(); if (!underSystemd || !schedule.enabled) { state.nextDueAt = null; state.lastDecision = underSystemd ? 'disabled' : 'not-systemd'; return; } state.nextDueAt = computeInitialDueAt(schedule, now); state.lastDecision = 'scheduled'; } function tick () { const now = nowMs(); state.lastTickAt = now; const underSystemd = !!process.env.INVOCATION_ID; const schedule = buildScheduleConfig(loadConfig()); applyConfigState(underSystemd, schedule, now); if (!underSystemd || !schedule.enabled || !Number.isFinite(state.nextDueAt)) return; if (now < state.nextDueAt) { state.lastDecision = 'waiting-next-window'; return; } if (!state.pendingSinceAt) state.pendingSinceAt = now; if (!noLoggedInClientsForIdleWindow(now)) { state.lastDecision = 'waiting-for-idle-clients'; return; } state.lastDecision = 'triggering-restart'; state.lastShutdownAt = now; state.nextDueAt = advanceDueAt(state.nextDueAt, schedule); resetPendingState(); if (typeof shutdownForRestartFn === 'function') { shutdownForRestartFn(); } } function startRestartScheduler (opts = {}) { shutdownForRestartFn = typeof opts.shutdownForRestart === 'function' ? opts.shutdownForRestart : null; if (schedulerTimer) return; state.startedAt = nowMs(); state.lastError = null; try { tick(); } catch (err) { state.lastError = err && err.message ? String(err.message) : String(err); } schedulerTimer = setInterval(() => { try { tick(); } catch (err) { state.lastError = err && err.message ? String(err.message) : String(err); } }, SCHEDULER_INTERVAL_MS); if (schedulerTimer && typeof schedulerTimer.unref === 'function') schedulerTimer.unref(); } function stopRestartScheduler () { if (!schedulerTimer) return; clearInterval(schedulerTimer); schedulerTimer = null; } function getRestartSchedulerSnapshot () { const schedule = buildScheduleConfig(loadConfig()); return { running: !!schedulerTimer, startedAt: state.startedAt, lastTickAt: state.lastTickAt, nextDueAt: state.nextDueAt, pendingSinceAt: state.pendingSinceAt, lastShutdownAt: state.lastShutdownAt, lastDecision: state.lastDecision, lastError: state.lastError, underSystemd: !!process.env.INVOCATION_ID, config: { enabled: schedule.enabled, cadence: schedule.cadence, time: schedule.time, }, intervalMs: SCHEDULER_INTERVAL_MS, }; } module.exports = { startRestartScheduler, stopRestartScheduler, getRestartSchedulerSnapshot, };