Add scheduled restart backend
Admins can now persist a global scheduled restart policy with cadence and time. When enabled under systemd, the server waits for at least one hour of no logged-in clients before shutting down so systemd can restart it safely. The debug API now exposes maintenance row counts and cleanup/scheduler runtime snapshots for long-uptime monitoring.
@@ -11,6 +11,12 @@ const AUTH_SESSION_REVOKED_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours
11
11
const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout
12
12
13
13
let authSessionPurgeTimer = null;
14
const authSessionCleanupState = {
15
lastRunAt: null,
16
lastPurgedCount: 0,
17
lastDurationMs: 0,
18
lastError: null,
19
};
14
20
15
21
// Secret used to sign JWTs — generated fresh each server boot.
16
22
// Tokens from a previous boot are automatically invalid.
@@ -91,6 +97,27 @@ function purgeStaleSessions (opts = {})
91
97
return Number(result && result.changes || 0);
92
98
}
93
99
100
function runAuthSessionCleanupOnce ()
101
{
102
const startedAt = nowMs();
103
try
104
{
105
const purged = purgeStaleSessions();
106
authSessionCleanupState.lastRunAt = nowMs();
107
authSessionCleanupState.lastPurgedCount = Number(purged || 0);
108
authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt);
109
authSessionCleanupState.lastError = null;
110
return purged;
111
} catch (err)
112
{
113
authSessionCleanupState.lastRunAt = nowMs();
114
authSessionCleanupState.lastPurgedCount = 0;
115
authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt);
116
authSessionCleanupState.lastError = err && err.message ? String(err.message) : String(err);
117
throw err;
118
}
119
}
120
94
121
function startAuthSessionCleanupLoop ()
95
122
{
96
123
if (authSessionPurgeTimer) return;
@@ -98,7 +125,7 @@ function startAuthSessionCleanupLoop ()
98
125
// Run once immediately at startup to trim stale rows from earlier uptime.
99
126
try
100
127
{
101
purgeStaleSessions();
128
runAuthSessionCleanupOnce();
102
129
} catch
103
130
{
104
131
// Ignore purge failures and retry on the next interval.
@@ -108,7 +135,7 @@ function startAuthSessionCleanupLoop ()
108
135
{
109
136
try
110
137
{
111
purgeStaleSessions();
138
runAuthSessionCleanupOnce();
112
139
} catch
113
140
{
114
141
// Keep server healthy even if cleanup temporarily fails.
@@ -128,6 +155,20 @@ function stopAuthSessionCleanupLoop ()
128
155
authSessionPurgeTimer = null;
129
156
}
130
157
158
function getAuthSessionCleanupSnapshot ()
159
{
160
return {
161
running: !!authSessionPurgeTimer,
162
intervalMs: AUTH_SESSION_PURGE_INTERVAL_MS,
163
lastRunAt: authSessionCleanupState.lastRunAt,
164
lastPurgedCount: authSessionCleanupState.lastPurgedCount,
165
lastDurationMs: authSessionCleanupState.lastDurationMs,
166
lastError: authSessionCleanupState.lastError,
167
revokedRetentionMs: AUTH_SESSION_REVOKED_RETENTION_MS,
168
idleRetentionMs: AUTH_SESSION_IDLE_RETENTION_MS,
169
};
170
}
171
131
172
// ---------------------------------------------------------------------------
132
173
// Token creation
133
174
// ---------------------------------------------------------------------------
@@ -276,6 +317,7 @@ module.exports = {
276
317
getRegion,
277
318
revokeSession,
278
319
purgeStaleSessions,
320
getAuthSessionCleanupSnapshot,
279
321
startAuthSessionCleanupLoop,
280
322
stopAuthSessionCleanupLoop,
281
323
SESSION_IDLE_TIMEOUT_MS,
@@ -11,6 +11,12 @@ const AUTH_SESSION_REVOKED_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours11
const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout11
const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout12
12
13
let authSessionPurgeTimer = null;13
let authSessionPurgeTimer = null;14
const authSessionCleanupState = {15
lastRunAt: null,16
lastPurgedCount: 0,17
lastDurationMs: 0,18
lastError: null,19
};14
20
15
// Secret used to sign JWTs — generated fresh each server boot.21
// Secret used to sign JWTs — generated fresh each server boot.16
// Tokens from a previous boot are automatically invalid.22
// Tokens from a previous boot are automatically invalid.@@ -91,6 +97,27 @@ function purgeStaleSessions (opts = {})91
return Number(result && result.changes || 0);97
return Number(result && result.changes || 0);92
}98
}93
99
100
function runAuthSessionCleanupOnce ()101
{102
const startedAt = nowMs();103
try104
{105
const purged = purgeStaleSessions();106
authSessionCleanupState.lastRunAt = nowMs();107
authSessionCleanupState.lastPurgedCount = Number(purged || 0);108
authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt);109
authSessionCleanupState.lastError = null;110
return purged;111
} catch (err)112
{113
authSessionCleanupState.lastRunAt = nowMs();114
authSessionCleanupState.lastPurgedCount = 0;115
authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt);116
authSessionCleanupState.lastError = err && err.message ? String(err.message) : String(err);117
throw err;118
}119
}120
94
function startAuthSessionCleanupLoop ()121
function startAuthSessionCleanupLoop ()95
{122
{96
if (authSessionPurgeTimer) return;123
if (authSessionPurgeTimer) return;@@ -98,7 +125,7 @@ function startAuthSessionCleanupLoop ()98
// Run once immediately at startup to trim stale rows from earlier uptime.125
// Run once immediately at startup to trim stale rows from earlier uptime.99
try126
try100
{127
{101
purgeStaleSessions();128
runAuthSessionCleanupOnce();102
} catch129
} catch103
{130
{104
// Ignore purge failures and retry on the next interval.131
// Ignore purge failures and retry on the next interval.@@ -108,7 +135,7 @@ function startAuthSessionCleanupLoop ()108
{135
{109
try136
try110
{137
{111
purgeStaleSessions();138
runAuthSessionCleanupOnce();112
} catch139
} catch113
{140
{114
// Keep server healthy even if cleanup temporarily fails.141
// Keep server healthy even if cleanup temporarily fails.@@ -128,6 +155,20 @@ function stopAuthSessionCleanupLoop ()128
authSessionPurgeTimer = null;155
authSessionPurgeTimer = null;129
}156
}130
157
158
function getAuthSessionCleanupSnapshot ()159
{160
return {161
running: !!authSessionPurgeTimer,162
intervalMs: AUTH_SESSION_PURGE_INTERVAL_MS,163
lastRunAt: authSessionCleanupState.lastRunAt,164
lastPurgedCount: authSessionCleanupState.lastPurgedCount,165
lastDurationMs: authSessionCleanupState.lastDurationMs,166
lastError: authSessionCleanupState.lastError,167
revokedRetentionMs: AUTH_SESSION_REVOKED_RETENTION_MS,168
idleRetentionMs: AUTH_SESSION_IDLE_RETENTION_MS,169
};170
}171
131
// ---------------------------------------------------------------------------172
// ---------------------------------------------------------------------------132
// Token creation173
// Token creation133
// ---------------------------------------------------------------------------174
// ---------------------------------------------------------------------------@@ -276,6 +317,7 @@ module.exports = {276
getRegion,317
getRegion,277
revokeSession,318
revokeSession,278
purgeStaleSessions,319
purgeStaleSessions,320
getAuthSessionCleanupSnapshot,279
startAuthSessionCleanupLoop,321
startAuthSessionCleanupLoop,280
stopAuthSessionCleanupLoop,322
stopAuthSessionCleanupLoop,281
SESSION_IDLE_TIMEOUT_MS,323
SESSION_IDLE_TIMEOUT_MS,@@ -5,6 +5,26 @@ const path = require('path');
5
5
6
6
const CONFIG_PATH = path.join(__dirname, '../config.json');
7
7
8
const DEFAULT_SCHEDULED_RESTART = {
9
enabled: false,
10
cadence: 'daily',
11
time: '04:00',
12
};
13
14
function normalizeScheduledRestart (value)
15
{
16
const raw = value && typeof value === 'object' ? value : {};
17
const cadence = String(raw.cadence || '').trim().toLowerCase();
18
const allowedCadences = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']);
19
const time = String(raw.time || '').trim();
20
21
return {
22
enabled: !!raw.enabled,
23
cadence: allowedCadences.has(cadence) ? cadence : DEFAULT_SCHEDULED_RESTART.cadence,
24
time: /^([01]\d|2[0-3]):([0-5]\d)$/.test(time) ? time : DEFAULT_SCHEDULED_RESTART.time,
25
};
26
}
27
8
28
function loadConfig ()
9
29
{
10
30
try
@@ -19,10 +39,11 @@ function loadConfig ()
19
39
{
20
40
parsed.rootAliases = {};
21
41
}
42
parsed.scheduledRestart = normalizeScheduledRestart(parsed.scheduledRestart);
22
43
return parsed;
23
44
} catch
24
45
{
25
const defaults = { port: 3000, paths: [], rootAliases: {} };
46
const defaults = { port: 3000, paths: [], rootAliases: {}, scheduledRestart: { ...DEFAULT_SCHEDULED_RESTART } };
26
47
fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
27
48
return defaults;
28
49
}
@@ -5,6 +5,26 @@ const path = require('path');5
5
6
const CONFIG_PATH = path.join(__dirname, '../config.json');6
const CONFIG_PATH = path.join(__dirname, '../config.json');7
7
8
const DEFAULT_SCHEDULED_RESTART = {9
enabled: false,10
cadence: 'daily',11
time: '04:00',12
};13
14
function normalizeScheduledRestart (value)15
{16
const raw = value && typeof value === 'object' ? value : {};17
const cadence = String(raw.cadence || '').trim().toLowerCase();18
const allowedCadences = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']);19
const time = String(raw.time || '').trim();20
21
return {22
enabled: !!raw.enabled,23
cadence: allowedCadences.has(cadence) ? cadence : DEFAULT_SCHEDULED_RESTART.cadence,24
time: /^([01]\d|2[0-3]):([0-5]\d)$/.test(time) ? time : DEFAULT_SCHEDULED_RESTART.time,25
};26
}27
8
function loadConfig ()28
function loadConfig ()9
{29
{10
try30
try@@ -19,10 +39,11 @@ function loadConfig ()19
{39
{20
parsed.rootAliases = {};40
parsed.rootAliases = {};21
}41
}42
parsed.scheduledRestart = normalizeScheduledRestart(parsed.scheduledRestart);22
return parsed;43
return parsed;23
} catch44
} catch24
{45
{25
const defaults = { port: 3000, paths: [], rootAliases: {} };46
const defaults = { port: 3000, paths: [], rootAliases: {}, scheduledRestart: { ...DEFAULT_SCHEDULED_RESTART } };26
fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');47
fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');27
return defaults;48
return defaults;28
}49
}@@ -10,6 +10,7 @@ const { ensureServerKeys } = require('./crypto');
10
10
const { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth');
11
11
const { loadConfig } = require('./config');
12
12
const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');
13
const { startRestartScheduler, stopRestartScheduler } = require('./restart-scheduler');
13
14
const { logError } = require('./logger');
14
15
const authRoutes = require('./routes/auth');
15
16
const filesRoutes = require('./routes/files');
@@ -66,6 +67,7 @@ function shutdown (opts = {}, ...servers)
66
67
stopThumbnailCacheLoop();
67
68
stopAuthSessionCleanupLoop();
68
69
stopShareMaintenanceLoop();
70
stopRestartScheduler();
69
71
70
72
// Close DB first so file locks are released as early as possible.
71
73
closeDb();
@@ -127,6 +129,7 @@ function start ()
127
129
startThumbnailCacheLoop();
128
130
startAuthSessionCleanupLoop();
129
131
startShareMaintenanceLoop();
132
startRestartScheduler({ shutdownForRestart });
130
133
131
134
// Give the admin route access to the server handle for graceful shutdown.
132
135
app.set('server', httpServer);
@@ -10,6 +10,7 @@ const { ensureServerKeys } = require('./crypto');10
const { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth');10
const { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth');11
const { loadConfig } = require('./config');11
const { loadConfig } = require('./config');12
const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');12
const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');13
const { startRestartScheduler, stopRestartScheduler } = require('./restart-scheduler');13
const { logError } = require('./logger');14
const { logError } = require('./logger');14
const authRoutes = require('./routes/auth');15
const authRoutes = require('./routes/auth');15
const filesRoutes = require('./routes/files');16
const filesRoutes = require('./routes/files');@@ -66,6 +67,7 @@ function shutdown (opts = {}, ...servers)66
stopThumbnailCacheLoop();67
stopThumbnailCacheLoop();67
stopAuthSessionCleanupLoop();68
stopAuthSessionCleanupLoop();68
stopShareMaintenanceLoop();69
stopShareMaintenanceLoop();70
stopRestartScheduler();69
71
70
// Close DB first so file locks are released as early as possible.72
// Close DB first so file locks are released as early as possible.71
closeDb();73
closeDb();@@ -127,6 +129,7 @@ function start ()127
startThumbnailCacheLoop();129
startThumbnailCacheLoop();128
startAuthSessionCleanupLoop();130
startAuthSessionCleanupLoop();129
startShareMaintenanceLoop();131
startShareMaintenanceLoop();132
startRestartScheduler({ shutdownForRestart });130
133
131
// Give the admin route access to the server handle for graceful shutdown.134
// Give the admin route access to the server handle for graceful shutdown.132
app.set('server', httpServer);135
app.set('server', httpServer);@@ -0,0 +1,246 @@
1
'use strict';
2
3
const { loadConfig } = require('./config');
4
const { getDb } = require('./db');
5
const { SESSION_IDLE_TIMEOUT_MS } = require('./auth');
6
7
const SCHEDULER_INTERVAL_MS = 60 * 1000;
8
9
const CADENCE_DAYS = {
10
daily: 1,
11
every3days: 3,
12
weekly: 7,
13
biweekly: 14,
14
};
15
16
let schedulerTimer = null;
17
let shutdownForRestartFn = null;
18
let 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
30
function nowMs ()
31
{
32
return Date.now();
33
}
34
35
function 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
46
function 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
60
function 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
73
function 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
83
function 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
100
function advanceDueAt (currentDueAt, schedule)
101
{
102
const due = new Date(Number(currentDueAt) || nowMs());
103
return addCadence(due, schedule.cadence).getTime();
104
}
105
106
function 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
120
function resetPendingState ()
121
{
122
state.pendingSinceAt = null;
123
}
124
125
function 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
146
function 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
182
function 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
212
function stopRestartScheduler ()
213
{
214
if (!schedulerTimer) return;
215
clearInterval(schedulerTimer);
216
schedulerTimer = null;
217
}
218
219
function 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
242
module.exports = {
243
startRestartScheduler,
244
stopRestartScheduler,
245
getRestartSchedulerSnapshot,
246
};
@@ -0,0 +1,246 @@1
'use strict';2
3
const { loadConfig } = require('./config');4
const { getDb } = require('./db');5
const { SESSION_IDLE_TIMEOUT_MS } = require('./auth');6
7
const SCHEDULER_INTERVAL_MS = 60 * 1000;8
9
const CADENCE_DAYS = {10
daily: 1,11
every3days: 3,12
weekly: 7,13
biweekly: 14,14
};15
16
let schedulerTimer = null;17
let shutdownForRestartFn = null;18
let 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
30
function nowMs ()31
{32
return Date.now();33
}34
35
function 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
46
function 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
60
function buildScheduleConfig (config)61
{62
const scheduled = config && config.scheduledRestart && typeof config.scheduledRestart === 'object'63
? config.scheduledRestart64
: {};65
66
return {67
enabled: !!scheduled.enabled,68
cadence: String(scheduled.cadence || 'daily'),69
time: String(scheduled.time || '04:00'),70
};71
}72
73
function 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
83
function 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
100
function advanceDueAt (currentDueAt, schedule)101
{102
const due = new Date(Number(currentDueAt) || nowMs());103
return addCadence(due, schedule.cadence).getTime();104
}105
106
function noLoggedInClientsForIdleWindow (now)107
{108
const db = getDb();109
const row = db.prepare(110
`SELECT MAX(last_seen_at) AS lastSeenAt111
FROM auth_sessions112
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
120
function resetPendingState ()121
{122
state.pendingSinceAt = null;123
}124
125
function 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
146
function 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
182
function 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
try191
{192
tick();193
} catch (err)194
{195
state.lastError = err && err.message ? String(err.message) : String(err);196
}197
198
schedulerTimer = setInterval(() =>199
{200
try201
{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
212
function stopRestartScheduler ()213
{214
if (!schedulerTimer) return;215
clearInterval(schedulerTimer);216
schedulerTimer = null;217
}218
219
function 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
242
module.exports = {243
startRestartScheduler,244
stopRestartScheduler,245
getRestartSchedulerSnapshot,246
};@@ -48,6 +48,28 @@ const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
48
48
const debugRouter = require('./debug');
49
49
50
50
const BCRYPT_ROUNDS = 12;
51
const SCHEDULED_RESTART_CADENCES = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']);
52
const SCHEDULED_RESTART_TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
53
54
function normaliseScheduledRestartConfig (value, fallback = null)
55
{
56
const defaults = fallback && typeof fallback === 'object'
57
? fallback
58
: { enabled: false, cadence: 'daily', time: '04:00' };
59
const raw = value && typeof value === 'object' ? value : {};
60
61
const cadenceRaw = String(raw.cadence || defaults.cadence || '').trim().toLowerCase();
62
const cadence = SCHEDULED_RESTART_CADENCES.has(cadenceRaw) ? cadenceRaw : defaults.cadence;
63
64
const timeRaw = String(raw.time || defaults.time || '').trim();
65
const time = SCHEDULED_RESTART_TIME_RE.test(timeRaw) ? timeRaw : defaults.time;
66
67
return {
68
enabled: !!raw.enabled,
69
cadence,
70
time,
71
};
72
}
51
73
52
74
function normalizePermissions (permissions)
53
75
{
@@ -306,12 +328,14 @@ router.get('/config', (req, res) =>
306
328
{
307
329
const config = loadConfig();
308
330
const effective = getEffectivePaths(config.paths || []);
331
const scheduledRestart = normaliseScheduledRestartConfig(config.scheduledRestart);
309
332
res.json({
310
333
port: config.port || 3000,
311
334
paths: config.paths || [],
312
335
effectivePaths: effective,
313
336
userPath: config.userPath || null,
314
337
userFolderSizeLimit: config.userFolderSizeLimit || null,
338
scheduledRestart,
315
339
});
316
340
});
317
341
@@ -322,7 +346,7 @@ router.get('/config', (req, res) =>
322
346
// ---------------------------------------------------------------------------
323
347
router.put('/config', (req, res) =>
324
348
{
325
const { paths, port, userPath, userFolderSizeLimit } = req.body;
349
const { paths, port, userPath, userFolderSizeLimit, scheduledRestart } = req.body;
326
350
if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
327
351
328
352
const config = loadConfig();
@@ -357,6 +381,33 @@ router.put('/config', (req, res) =>
357
381
}
358
382
}
359
383
384
if (scheduledRestart !== undefined)
385
{
386
if (!process.env.INVOCATION_ID)
387
{
388
return res.status(400).json({ error: 'Scheduled restart requires running under systemd.' });
389
}
390
391
if (!scheduledRestart || typeof scheduledRestart !== 'object' || Array.isArray(scheduledRestart))
392
{
393
return res.status(400).json({ error: 'scheduledRestart must be an object.' });
394
}
395
396
const cadence = String(scheduledRestart.cadence || '').trim().toLowerCase();
397
if (!SCHEDULED_RESTART_CADENCES.has(cadence))
398
{
399
return res.status(400).json({ error: 'Invalid scheduled restart cadence.' });
400
}
401
402
const time = String(scheduledRestart.time || '').trim();
403
if (!SCHEDULED_RESTART_TIME_RE.test(time))
404
{
405
return res.status(400).json({ error: 'Invalid scheduled restart time. Expected HH:MM (24-hour).' });
406
}
407
408
config.scheduledRestart = normaliseScheduledRestartConfig(scheduledRestart, config.scheduledRestart);
409
}
410
360
411
try
361
412
{
362
413
saveConfig(config);
@@ -48,6 +48,28 @@ const { loadConfig, saveConfig, getEffectivePaths } = require('../config');48
const debugRouter = require('./debug');48
const debugRouter = require('./debug');49
49
50
const BCRYPT_ROUNDS = 12;50
const BCRYPT_ROUNDS = 12;51
const SCHEDULED_RESTART_CADENCES = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']);52
const SCHEDULED_RESTART_TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;53
54
function normaliseScheduledRestartConfig (value, fallback = null)55
{56
const defaults = fallback && typeof fallback === 'object'57
? fallback58
: { enabled: false, cadence: 'daily', time: '04:00' };59
const raw = value && typeof value === 'object' ? value : {};60
61
const cadenceRaw = String(raw.cadence || defaults.cadence || '').trim().toLowerCase();62
const cadence = SCHEDULED_RESTART_CADENCES.has(cadenceRaw) ? cadenceRaw : defaults.cadence;63
64
const timeRaw = String(raw.time || defaults.time || '').trim();65
const time = SCHEDULED_RESTART_TIME_RE.test(timeRaw) ? timeRaw : defaults.time;66
67
return {68
enabled: !!raw.enabled,69
cadence,70
time,71
};72
}51
73
52
function normalizePermissions (permissions)74
function normalizePermissions (permissions)53
{75
{@@ -306,12 +328,14 @@ router.get('/config', (req, res) =>306
{328
{307
const config = loadConfig();329
const config = loadConfig();308
const effective = getEffectivePaths(config.paths || []);330
const effective = getEffectivePaths(config.paths || []);331
const scheduledRestart = normaliseScheduledRestartConfig(config.scheduledRestart);309
res.json({332
res.json({310
port: config.port || 3000,333
port: config.port || 3000,311
paths: config.paths || [],334
paths: config.paths || [],312
effectivePaths: effective,335
effectivePaths: effective,313
userPath: config.userPath || null,336
userPath: config.userPath || null,314
userFolderSizeLimit: config.userFolderSizeLimit || null,337
userFolderSizeLimit: config.userFolderSizeLimit || null,338
scheduledRestart,315
});339
});316
});340
});317
341
@@ -322,7 +346,7 @@ router.get('/config', (req, res) =>322
// ---------------------------------------------------------------------------346
// ---------------------------------------------------------------------------323
router.put('/config', (req, res) =>347
router.put('/config', (req, res) =>324
{348
{325
const { paths, port, userPath, userFolderSizeLimit } = req.body;349
const { paths, port, userPath, userFolderSizeLimit, scheduledRestart } = req.body;326
if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });350
if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });327
351
328
const config = loadConfig();352
const config = loadConfig();@@ -357,6 +381,33 @@ router.put('/config', (req, res) =>357
}381
}358
}382
}359
383
384
if (scheduledRestart !== undefined)385
{386
if (!process.env.INVOCATION_ID)387
{388
return res.status(400).json({ error: 'Scheduled restart requires running under systemd.' });389
}390
391
if (!scheduledRestart || typeof scheduledRestart !== 'object' || Array.isArray(scheduledRestart))392
{393
return res.status(400).json({ error: 'scheduledRestart must be an object.' });394
}395
396
const cadence = String(scheduledRestart.cadence || '').trim().toLowerCase();397
if (!SCHEDULED_RESTART_CADENCES.has(cadence))398
{399
return res.status(400).json({ error: 'Invalid scheduled restart cadence.' });400
}401
402
const time = String(scheduledRestart.time || '').trim();403
if (!SCHEDULED_RESTART_TIME_RE.test(time))404
{405
return res.status(400).json({ error: 'Invalid scheduled restart time. Expected HH:MM (24-hour).' });406
}407
408
config.scheduledRestart = normaliseScheduledRestartConfig(scheduledRestart, config.scheduledRestart);409
}410
360
try411
try361
{412
{362
saveConfig(config);413
saveConfig(config);@@ -12,6 +12,9 @@ const { loadConfig, getEffectivePaths } = require('../config');
12
12
const { getImageSubtitleDebugSnapshot } = require('../image-subtitles');
13
13
const { getVideoStreamDebugSnapshot } = require('../video-stream');
14
14
const { getSubtitleDebugLogSnapshot } = require('../subtitle-debug-log');
15
const authModule = require('../auth');
16
const shareRoutes = require('./share');
17
const restartScheduler = require('../restart-scheduler');
15
18
16
19
const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;
17
20
@@ -199,6 +202,59 @@ function getMemorySnapshot ()
199
202
};
200
203
}
201
204
205
function getMaintenanceSnapshot ()
206
{
207
const db = getDb();
208
const now = Date.now();
209
const activeSince = now - AUTH_IDLE_TIMEOUT_MS;
210
211
const authRows = db.prepare(`
212
SELECT
213
COUNT(*) AS total,
214
SUM(CASE WHEN revoked_at IS NULL THEN 1 ELSE 0 END) AS active,
215
SUM(CASE WHEN revoked_at IS NOT NULL THEN 1 ELSE 0 END) AS revoked
216
FROM auth_sessions
217
`).get() || {};
218
219
const shareRows = db.prepare(`
220
SELECT
221
COUNT(*) AS total,
222
SUM(CASE WHEN expires_at <= ? THEN 1 ELSE 0 END) AS expired
223
FROM share_tokens
224
`).get([now]) || {};
225
226
const activeUserRows = db.prepare(
227
`SELECT COUNT(DISTINCT username) AS count
228
FROM auth_sessions
229
WHERE revoked_at IS NULL
230
AND last_seen_at >= ?`,
231
).get([activeSince]) || {};
232
233
const authCleanup = typeof authModule.getAuthSessionCleanupSnapshot === 'function'
234
? authModule.getAuthSessionCleanupSnapshot()
235
: null;
236
const shareMaintenance = typeof shareRoutes.getShareMaintenanceSnapshot === 'function'
237
? shareRoutes.getShareMaintenanceSnapshot()
238
: null;
239
const scheduledRestart = typeof restartScheduler.getRestartSchedulerSnapshot === 'function'
240
? restartScheduler.getRestartSchedulerSnapshot()
241
: null;
242
243
return {
244
rows: {
245
authSessionsTotal: Number(authRows.total || 0),
246
authSessionsActive: Number(authRows.active || 0),
247
authSessionsRevoked: Number(authRows.revoked || 0),
248
activeLoggedInUsers: Number(activeUserRows.count || 0),
249
shareTokensTotal: Number(shareRows.total || 0),
250
shareTokensExpired: Number(shareRows.expired || 0),
251
},
252
authCleanup,
253
shareMaintenance,
254
scheduledRestart,
255
};
256
}
257
202
258
router.get('/debug/stream-stats', (req, res) =>
203
259
{
204
260
const rootUsage = collectRootUsageStats();
@@ -208,6 +264,7 @@ router.get('/debug/stream-stats', (req, res) =>
208
264
const subtitleDebugLog = getSubtitleDebugLogSnapshot();
209
265
const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);
210
266
const memory = getMemorySnapshot();
267
const maintenance = getMaintenanceSnapshot();
211
268
212
269
res.json({
213
270
generatedAt: Date.now(),
@@ -218,6 +275,7 @@ router.get('/debug/stream-stats', (req, res) =>
218
275
subtitleCache,
219
276
subtitleDebugLog,
220
277
videoFiles,
278
maintenance,
221
279
});
222
280
});
223
281
@@ -12,6 +12,9 @@ const { loadConfig, getEffectivePaths } = require('../config');12
const { getImageSubtitleDebugSnapshot } = require('../image-subtitles');12
const { getImageSubtitleDebugSnapshot } = require('../image-subtitles');13
const { getVideoStreamDebugSnapshot } = require('../video-stream');13
const { getVideoStreamDebugSnapshot } = require('../video-stream');14
const { getSubtitleDebugLogSnapshot } = require('../subtitle-debug-log');14
const { getSubtitleDebugLogSnapshot } = require('../subtitle-debug-log');15
const authModule = require('../auth');16
const shareRoutes = require('./share');17
const restartScheduler = require('../restart-scheduler');15
18
16
const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;19
const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;17
20
@@ -199,6 +202,59 @@ function getMemorySnapshot ()199
};202
};200
}203
}201
204
205
function getMaintenanceSnapshot ()206
{207
const db = getDb();208
const now = Date.now();209
const activeSince = now - AUTH_IDLE_TIMEOUT_MS;210
211
const authRows = db.prepare(`212
SELECT213
COUNT(*) AS total,214
SUM(CASE WHEN revoked_at IS NULL THEN 1 ELSE 0 END) AS active,215
SUM(CASE WHEN revoked_at IS NOT NULL THEN 1 ELSE 0 END) AS revoked216
FROM auth_sessions217
`).get() || {};218
219
const shareRows = db.prepare(`220
SELECT221
COUNT(*) AS total,222
SUM(CASE WHEN expires_at <= ? THEN 1 ELSE 0 END) AS expired223
FROM share_tokens224
`).get([now]) || {};225
226
const activeUserRows = db.prepare(227
`SELECT COUNT(DISTINCT username) AS count228
FROM auth_sessions229
WHERE revoked_at IS NULL230
AND last_seen_at >= ?`,231
).get([activeSince]) || {};232
233
const authCleanup = typeof authModule.getAuthSessionCleanupSnapshot === 'function'234
? authModule.getAuthSessionCleanupSnapshot()235
: null;236
const shareMaintenance = typeof shareRoutes.getShareMaintenanceSnapshot === 'function'237
? shareRoutes.getShareMaintenanceSnapshot()238
: null;239
const scheduledRestart = typeof restartScheduler.getRestartSchedulerSnapshot === 'function'240
? restartScheduler.getRestartSchedulerSnapshot()241
: null;242
243
return {244
rows: {245
authSessionsTotal: Number(authRows.total || 0),246
authSessionsActive: Number(authRows.active || 0),247
authSessionsRevoked: Number(authRows.revoked || 0),248
activeLoggedInUsers: Number(activeUserRows.count || 0),249
shareTokensTotal: Number(shareRows.total || 0),250
shareTokensExpired: Number(shareRows.expired || 0),251
},252
authCleanup,253
shareMaintenance,254
scheduledRestart,255
};256
}257
202
router.get('/debug/stream-stats', (req, res) =>258
router.get('/debug/stream-stats', (req, res) =>203
{259
{204
const rootUsage = collectRootUsageStats();260
const rootUsage = collectRootUsageStats();@@ -208,6 +264,7 @@ router.get('/debug/stream-stats', (req, res) =>208
const subtitleDebugLog = getSubtitleDebugLogSnapshot();264
const subtitleDebugLog = getSubtitleDebugLogSnapshot();209
const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);265
const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);210
const memory = getMemorySnapshot();266
const memory = getMemorySnapshot();267
const maintenance = getMaintenanceSnapshot();211
268
212
res.json({269
res.json({213
generatedAt: Date.now(),270
generatedAt: Date.now(),@@ -218,6 +275,7 @@ router.get('/debug/stream-stats', (req, res) =>218
subtitleCache,275
subtitleCache,219
subtitleDebugLog,276
subtitleDebugLog,220
videoFiles,277
videoFiles,278
maintenance,221
});279
});222
});280
});223
281
@@ -26,6 +26,20 @@ let mockSubtitleSnapshot = {
26
26
byFile: {},
27
27
};
28
28
29
let mockRestartSchedulerSnapshot = {
30
running: true,
31
startedAt: Date.now(),
32
lastTickAt: Date.now(),
33
nextDueAt: Date.now() + 3600000,
34
pendingSinceAt: null,
35
lastShutdownAt: null,
36
lastDecision: 'waiting-next-window',
37
lastError: null,
38
underSystemd: true,
39
config: { enabled: false, cadence: 'daily', time: '04:00' },
40
intervalMs: 60000,
41
};
42
29
43
// ── child_process mock — controlled per test ──────────────────────────────────
30
44
let mockExecFileImpl = null;
31
45
jest.mock('child_process', () =>
@@ -80,6 +94,14 @@ jest.mock('../server/db', () =>
80
94
last_seen_at INTEGER NOT NULL,
81
95
revoked_at INTEGER
82
96
);
97
CREATE TABLE IF NOT EXISTS share_tokens (
98
token TEXT PRIMARY KEY,
99
file_path TEXT NOT NULL,
100
is_dir INTEGER NOT NULL DEFAULT 0,
101
created_by TEXT NOT NULL,
102
created_at INTEGER NOT NULL,
103
expires_at INTEGER NOT NULL
104
);
83
105
`);
84
106
}
85
107
return db;
@@ -95,8 +117,17 @@ jest.mock('../server/image-subtitles', () => ({
95
117
getImageSubtitleDebugSnapshot: () => mockSubtitleSnapshot,
96
118
}));
97
119
120
jest.mock('../server/restart-scheduler', () => ({
121
getRestartSchedulerSnapshot: () => mockRestartSchedulerSnapshot,
122
}));
123
98
124
// ── config mock ─────────────────────────────────────────────────────────────
99
const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null };
125
const mockConfig = {
126
port: 3000,
127
paths: ['/mnt/data', '/mnt/docs'],
128
userPath: null,
129
scheduledRestart: { enabled: false, cadence: 'daily', time: '04:00' },
130
};
100
131
jest.mock('../server/config', () => ({
101
132
loadConfig: () => ({ ...mockConfig }),
102
133
saveConfig: (c) => Object.assign(mockConfig, c),
@@ -438,6 +469,11 @@ describe('GET /api/admin/config', () =>
438
469
expect(status).toBe(200);
439
470
expect(body.port).toBe(3000);
440
471
expect(Array.isArray(body.paths)).toBe(true);
472
expect(body.scheduledRestart).toEqual(expect.objectContaining({
473
enabled: expect.any(Boolean),
474
cadence: expect.any(String),
475
time: expect.any(String),
476
}));
441
477
});
442
478
});
443
479
@@ -501,6 +537,15 @@ describe('GET /api/admin/debug/stream-stats', () =>
501
537
const { status, body } = await req('GET', '/api/admin/debug/stream-stats');
502
538
expect(status).toBe(200);
503
539
expect(Array.isArray(body.videoFiles)).toBe(true);
540
expect(body.maintenance).toEqual(expect.objectContaining({
541
rows: expect.objectContaining({
542
authSessionsTotal: expect.any(Number),
543
shareTokensTotal: expect.any(Number),
544
}),
545
scheduledRestart: expect.objectContaining({
546
intervalMs: expect.any(Number),
547
}),
548
}));
504
549
505
550
const live = body.videoFiles.find((row) => row.filePath === '/videos/live.mkv');
506
551
expect(live).toBeTruthy();
@@ -540,6 +585,60 @@ describe('PUT /api/admin/config', () =>
540
585
const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
541
586
expect(status).toBe(400);
542
587
});
588
589
test('saves scheduled restart config when running under systemd', async () =>
590
{
591
const origInvocationId = process.env.INVOCATION_ID;
592
process.env.INVOCATION_ID = 'test-invocation';
593
594
try
595
{
596
const { status, body } = await req('PUT', '/api/admin/config', {
597
paths: ['/mnt/data'],
598
scheduledRestart: {
599
enabled: true,
600
cadence: 'weekly',
601
time: '03:45',
602
},
603
});
604
expect(status).toBe(200);
605
expect(body.ok).toBe(true);
606
607
const readback = await req('GET', '/api/admin/config');
608
expect(readback.body.scheduledRestart).toEqual({
609
enabled: true,
610
cadence: 'weekly',
611
time: '03:45',
612
});
613
} finally
614
{
615
if (origInvocationId === undefined) delete process.env.INVOCATION_ID;
616
else process.env.INVOCATION_ID = origInvocationId;
617
}
618
});
619
620
test('rejects scheduled restart config when not running under systemd', async () =>
621
{
622
const origInvocationId = process.env.INVOCATION_ID;
623
delete process.env.INVOCATION_ID;
624
625
try
626
{
627
const { status } = await req('PUT', '/api/admin/config', {
628
paths: ['/mnt/data'],
629
scheduledRestart: {
630
enabled: true,
631
cadence: 'daily',
632
time: '02:15',
633
},
634
});
635
expect(status).toBe(400);
636
} finally
637
{
638
if (origInvocationId === undefined) delete process.env.INVOCATION_ID;
639
else process.env.INVOCATION_ID = origInvocationId;
640
}
641
});
543
642
});
544
643
545
644
describe('POST /api/admin/shutdown', () =>
@@ -26,6 +26,20 @@ let mockSubtitleSnapshot = {26
byFile: {},26
byFile: {},27
};27
};28
28
29
let mockRestartSchedulerSnapshot = {30
running: true,31
startedAt: Date.now(),32
lastTickAt: Date.now(),33
nextDueAt: Date.now() + 3600000,34
pendingSinceAt: null,35
lastShutdownAt: null,36
lastDecision: 'waiting-next-window',37
lastError: null,38
underSystemd: true,39
config: { enabled: false, cadence: 'daily', time: '04:00' },40
intervalMs: 60000,41
};42
29
// ── child_process mock — controlled per test ──────────────────────────────────43
// ── child_process mock — controlled per test ──────────────────────────────────30
let mockExecFileImpl = null;44
let mockExecFileImpl = null;31
jest.mock('child_process', () =>45
jest.mock('child_process', () =>@@ -80,6 +94,14 @@ jest.mock('../server/db', () =>80
last_seen_at INTEGER NOT NULL,94
last_seen_at INTEGER NOT NULL,81
revoked_at INTEGER95
revoked_at INTEGER82
);96
);97
CREATE TABLE IF NOT EXISTS share_tokens (98
token TEXT PRIMARY KEY,99
file_path TEXT NOT NULL,100
is_dir INTEGER NOT NULL DEFAULT 0,101
created_by TEXT NOT NULL,102
created_at INTEGER NOT NULL,103
expires_at INTEGER NOT NULL104
);83
`);105
`);84
}106
}85
return db;107
return db;@@ -95,8 +117,17 @@ jest.mock('../server/image-subtitles', () => ({95
getImageSubtitleDebugSnapshot: () => mockSubtitleSnapshot,117
getImageSubtitleDebugSnapshot: () => mockSubtitleSnapshot,96
}));118
}));97
119
120
jest.mock('../server/restart-scheduler', () => ({121
getRestartSchedulerSnapshot: () => mockRestartSchedulerSnapshot,122
}));123
98
// ── config mock ─────────────────────────────────────────────────────────────124
// ── config mock ─────────────────────────────────────────────────────────────99
const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null };125
const mockConfig = {126
port: 3000,127
paths: ['/mnt/data', '/mnt/docs'],128
userPath: null,129
scheduledRestart: { enabled: false, cadence: 'daily', time: '04:00' },130
};100
jest.mock('../server/config', () => ({131
jest.mock('../server/config', () => ({101
loadConfig: () => ({ ...mockConfig }),132
loadConfig: () => ({ ...mockConfig }),102
saveConfig: (c) => Object.assign(mockConfig, c),133
saveConfig: (c) => Object.assign(mockConfig, c),@@ -438,6 +469,11 @@ describe('GET /api/admin/config', () =>438
expect(status).toBe(200);469
expect(status).toBe(200);439
expect(body.port).toBe(3000);470
expect(body.port).toBe(3000);440
expect(Array.isArray(body.paths)).toBe(true);471
expect(Array.isArray(body.paths)).toBe(true);472
expect(body.scheduledRestart).toEqual(expect.objectContaining({473
enabled: expect.any(Boolean),474
cadence: expect.any(String),475
time: expect.any(String),476
}));441
});477
});442
});478
});443
479
@@ -501,6 +537,15 @@ describe('GET /api/admin/debug/stream-stats', () =>501
const { status, body } = await req('GET', '/api/admin/debug/stream-stats');537
const { status, body } = await req('GET', '/api/admin/debug/stream-stats');502
expect(status).toBe(200);538
expect(status).toBe(200);503
expect(Array.isArray(body.videoFiles)).toBe(true);539
expect(Array.isArray(body.videoFiles)).toBe(true);540
expect(body.maintenance).toEqual(expect.objectContaining({541
rows: expect.objectContaining({542
authSessionsTotal: expect.any(Number),543
shareTokensTotal: expect.any(Number),544
}),545
scheduledRestart: expect.objectContaining({546
intervalMs: expect.any(Number),547
}),548
}));504
549
505
const live = body.videoFiles.find((row) => row.filePath === '/videos/live.mkv');550
const live = body.videoFiles.find((row) => row.filePath === '/videos/live.mkv');506
expect(live).toBeTruthy();551
expect(live).toBeTruthy();@@ -540,6 +585,60 @@ describe('PUT /api/admin/config', () =>540
const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });585
const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });541
expect(status).toBe(400);586
expect(status).toBe(400);542
});587
});588
589
test('saves scheduled restart config when running under systemd', async () =>590
{591
const origInvocationId = process.env.INVOCATION_ID;592
process.env.INVOCATION_ID = 'test-invocation';593
594
try595
{596
const { status, body } = await req('PUT', '/api/admin/config', {597
paths: ['/mnt/data'],598
scheduledRestart: {599
enabled: true,600
cadence: 'weekly',601
time: '03:45',602
},603
});604
expect(status).toBe(200);605
expect(body.ok).toBe(true);606
607
const readback = await req('GET', '/api/admin/config');608
expect(readback.body.scheduledRestart).toEqual({609
enabled: true,610
cadence: 'weekly',611
time: '03:45',612
});613
} finally614
{615
if (origInvocationId === undefined) delete process.env.INVOCATION_ID;616
else process.env.INVOCATION_ID = origInvocationId;617
}618
});619
620
test('rejects scheduled restart config when not running under systemd', async () =>621
{622
const origInvocationId = process.env.INVOCATION_ID;623
delete process.env.INVOCATION_ID;624
625
try626
{627
const { status } = await req('PUT', '/api/admin/config', {628
paths: ['/mnt/data'],629
scheduledRestart: {630
enabled: true,631
cadence: 'daily',632
time: '02:15',633
},634
});635
expect(status).toBe(400);636
} finally637
{638
if (origInvocationId === undefined) delete process.env.INVOCATION_ID;639
else process.env.INVOCATION_ID = origInvocationId;640
}641
});543
});642
});544
643
545
describe('POST /api/admin/shutdown', () =>644
describe('POST /api/admin/shutdown', () =>