BlueGit

timfa filemanager

Files

filemanager / server / restart-scheduler.js

restart-scheduler.js

Add scheduled restart backend
timfa Tim Falken · pushed by timfa · 5 months ago
9e526bef History
restart-scheduler.js 5.4 KiB Download Raw
1'use strict';
2
3const { loadConfig } = require('./config');
4const { getDb } = require('./db');
5const { SESSION_IDLE_TIMEOUT_MS } = require('./auth');
6
7const SCHEDULER_INTERVAL_MS = 60 * 1000;
8
9const CADENCE_DAYS = {
10 daily: 1,
11 every3days: 3,
12 weekly: 7,
13 biweekly: 14,
14};
15
16let schedulerTimer = null;
17let shutdownForRestartFn = null;
18let state = {
19 startedAt: null,
20 lastTickAt: null,
21 nextDueAt: null,
22 pendingSinceAt: null,
23 lastShutdownAt: null,
24 lastDecision: 'idle',
25 lastError: null,
26 configKey: null,
27 underSystemd: false,
28};
29
30function nowMs ()
31{
32 return Date.now();
33}
34
35function parseTimeToUtcParts (value)
36{
37 const match = String(value || '').trim().match(/^([01]\d|2[0-3]):([0-5]\d)$/);
38 if (!match) return null;
39
40 return {
41 hour: Number.parseInt(match[1], 10),
42 minute: Number.parseInt(match[2], 10),
43 };
44}
45
46function addCadence (date, cadence)
47{
48 const next = new Date(date.getTime());
49 if (cadence === 'monthly')
50 {
51 next.setUTCMonth(next.getUTCMonth() + 1);
52 return next;
53 }
54
55 const days = CADENCE_DAYS[cadence] || 1;
56 next.setUTCDate(next.getUTCDate() + days);
57 return next;
58}
59
60function buildScheduleConfig (config)
61{
62 const scheduled = config && config.scheduledRestart && typeof config.scheduledRestart === 'object'
63 ? config.scheduledRestart
64 : {};
65
66 return {
67 enabled: !!scheduled.enabled,
68 cadence: String(scheduled.cadence || 'daily'),
69 time: String(scheduled.time || '04:00'),
70 };
71}
72
73function configKeyFor (underSystemd, cfg)
74{
75 return JSON.stringify({
76 underSystemd: !!underSystemd,
77 enabled: !!cfg.enabled,
78 cadence: cfg.cadence,
79 time: cfg.time,
80 });
81}
82
83function computeInitialDueAt (schedule, now)
84{
85 const parts = parseTimeToUtcParts(schedule.time);
86 if (!parts) return null;
87
88 const current = new Date(now);
89 const due = new Date(now);
90 due.setUTCHours(parts.hour, parts.minute, 0, 0);
91
92 if (due.getTime() <= current.getTime())
93 {
94 return addCadence(due, schedule.cadence).getTime();
95 }
96
97 return due.getTime();
98}
99
100function advanceDueAt (currentDueAt, schedule)
101{
102 const due = new Date(Number(currentDueAt) || nowMs());
103 return addCadence(due, schedule.cadence).getTime();
104}
105
106function noLoggedInClientsForIdleWindow (now)
107{
108 const db = getDb();
109 const row = db.prepare(
110 `SELECT MAX(last_seen_at) AS lastSeenAt
111 FROM auth_sessions
112 WHERE revoked_at IS NULL`,
113 ).get();
114
115 const lastSeenAt = Number(row && row.lastSeenAt || 0);
116 if (!Number.isFinite(lastSeenAt) || lastSeenAt <= 0) return true;
117 return now - lastSeenAt >= SESSION_IDLE_TIMEOUT_MS;
118}
119
120function resetPendingState ()
121{
122 state.pendingSinceAt = null;
123}
124
125function applyConfigState (underSystemd, schedule, now)
126{
127 const nextKey = configKeyFor(underSystemd, schedule);
128 if (state.configKey === nextKey) return;
129
130 state.configKey = nextKey;
131 state.underSystemd = !!underSystemd;
132 state.lastError = null;
133 resetPendingState();
134
135 if (!underSystemd || !schedule.enabled)
136 {
137 state.nextDueAt = null;
138 state.lastDecision = underSystemd ? 'disabled' : 'not-systemd';
139 return;
140 }
141
142 state.nextDueAt = computeInitialDueAt(schedule, now);
143 state.lastDecision = 'scheduled';
144}
145
146function tick ()
147{
148 const now = nowMs();
149 state.lastTickAt = now;
150
151 const underSystemd = !!process.env.INVOCATION_ID;
152 const schedule = buildScheduleConfig(loadConfig());
153 applyConfigState(underSystemd, schedule, now);
154
155 if (!underSystemd || !schedule.enabled || !Number.isFinite(state.nextDueAt)) return;
156
157 if (now < state.nextDueAt)
158 {
159 state.lastDecision = 'waiting-next-window';
160 return;
161 }
162
163 if (!state.pendingSinceAt) state.pendingSinceAt = now;
164
165 if (!noLoggedInClientsForIdleWindow(now))
166 {
167 state.lastDecision = 'waiting-for-idle-clients';
168 return;
169 }
170
171 state.lastDecision = 'triggering-restart';
172 state.lastShutdownAt = now;
173 state.nextDueAt = advanceDueAt(state.nextDueAt, schedule);
174 resetPendingState();
175
176 if (typeof shutdownForRestartFn === 'function')
177 {
178 shutdownForRestartFn();
179 }
180}
181
182function startRestartScheduler (opts = {})
183{
184 shutdownForRestartFn = typeof opts.shutdownForRestart === 'function' ? opts.shutdownForRestart : null;
185 if (schedulerTimer) return;
186
187 state.startedAt = nowMs();
188 state.lastError = null;
189
190 try
191 {
192 tick();
193 } catch (err)
194 {
195 state.lastError = err && err.message ? String(err.message) : String(err);
196 }
197
198 schedulerTimer = setInterval(() =>
199 {
200 try
201 {
202 tick();
203 } catch (err)
204 {
205 state.lastError = err && err.message ? String(err.message) : String(err);
206 }
207 }, SCHEDULER_INTERVAL_MS);
208
209 if (schedulerTimer && typeof schedulerTimer.unref === 'function') schedulerTimer.unref();
210}
211
212function stopRestartScheduler ()
213{
214 if (!schedulerTimer) return;
215 clearInterval(schedulerTimer);
216 schedulerTimer = null;
217}
218
219function getRestartSchedulerSnapshot ()
220{
221 const schedule = buildScheduleConfig(loadConfig());
222
223 return {
224 running: !!schedulerTimer,
225 startedAt: state.startedAt,
226 lastTickAt: state.lastTickAt,
227 nextDueAt: state.nextDueAt,
228 pendingSinceAt: state.pendingSinceAt,
229 lastShutdownAt: state.lastShutdownAt,
230 lastDecision: state.lastDecision,
231 lastError: state.lastError,
232 underSystemd: !!process.env.INVOCATION_ID,
233 config: {
234 enabled: schedule.enabled,
235 cadence: schedule.cadence,
236 time: schedule.time,
237 },
238 intervalMs: SCHEDULER_INTERVAL_MS,
239 };
240}
241
242module.exports = {
243 startRestartScheduler,
244 stopRestartScheduler,
245 getRestartSchedulerSnapshot,
246};