mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-06 17:08:10 +00:00
feat: add cron scheduling mode for image update checks (#1460)
* feat: add cron scheduling mode for image update checks Adds a cron scheduling mode alongside the existing fixed-interval dropdown in Settings > Automation > Image update checks. Users can now set a 5-field cron expression (e.g. "0 3 * * 1") for precise time-of-day scheduling of registry polls. - Backend: ImageUpdateService gains mode/cronExpression fields and cron-based nextDelayMs() using the existing cron-parser dependency. PUT /api/image-updates/interval extended with transactional writes and server-authoritative cron validation matching the Scheduled Operations contract. Nicknames like @daily are supported. - Frontend: UpdatesSection gains a SegmentedControl toggle and cron text input with cronstrue-powered live description. The frontend does advisory validation only; backend 400s are surfaced inline. SettingsPrimaryButton used for explicit "Save schedule" action. - No cron jitter (the user chose a specific time). Interval mode keeps existing ±10% jitter. - Tests: 15 new backend tests covering valid cron, invalid cron, 6-field rejection, nickname support, backward compat, runtime fallback, and transactional writes. - Docs: auto-update-policies.mdx, alerts-notifications.mdx, and openapi.yaml updated with new scheduling mode. * fix: add mode and cronExpression to UpdatesSection test fixtures The existing tests failed because the mock status object was missing the new required fields (mode, cronExpression) added with cron scheduling support. Without them, status.mode was undefined, causing uiMode to never match 'interval' and the Select combobox to not render. * fix: prevent SegmentedControl from stretching full-width in SettingsField The flex-col container defaults items to align-self: stretch, making the Interval/Cron toggle bar span the full card width. Add self-start so it sizes to its content.
This commit is contained in:
@@ -988,3 +988,111 @@ services:
|
||||
expect(checkedImages).not.toContain('someapp:v2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ImageUpdateService cron scheduling', () => {
|
||||
beforeEach(() => {
|
||||
(ImageUpdateService as any).instance = undefined;
|
||||
mockGetGlobalSettings.mockReturnValue({ developer_mode: '0' });
|
||||
});
|
||||
|
||||
it('getStatus returns mode and cronExpression fields', () => {
|
||||
const service = ImageUpdateService.getInstance();
|
||||
// Before start/configureFromSettings, defaults apply.
|
||||
mockGetGlobalSettings.mockReturnValue({ developer_mode: '0' });
|
||||
service.configureFromSettings();
|
||||
const status = service.getStatus();
|
||||
expect(status.mode).toBe('interval');
|
||||
expect(status.cronExpression).toBeNull();
|
||||
});
|
||||
|
||||
it('configureFromSettings sets cron mode with valid expression', () => {
|
||||
mockGetGlobalSettings.mockReturnValue({
|
||||
developer_mode: '0',
|
||||
image_update_check_mode: 'cron',
|
||||
image_update_check_cron: '0 3 * * 1',
|
||||
image_update_check_interval_minutes: '120',
|
||||
});
|
||||
const service = ImageUpdateService.getInstance();
|
||||
service.configureFromSettings();
|
||||
const status = service.getStatus();
|
||||
expect(status.mode).toBe('cron');
|
||||
expect(status.cronExpression).toBe('0 3 * * 1');
|
||||
});
|
||||
|
||||
it('configureFromSettings falls back to interval on invalid cron', () => {
|
||||
mockGetGlobalSettings.mockReturnValue({
|
||||
developer_mode: '0',
|
||||
image_update_check_mode: 'cron',
|
||||
image_update_check_cron: 'not a cron expression',
|
||||
image_update_check_interval_minutes: '120',
|
||||
});
|
||||
const service = ImageUpdateService.getInstance();
|
||||
service.configureFromSettings();
|
||||
const status = service.getStatus();
|
||||
expect(status.mode).toBe('interval');
|
||||
expect(status.cronExpression).toBeNull();
|
||||
});
|
||||
|
||||
it('configureFromSettings falls back to interval when cron mode has empty expression', () => {
|
||||
mockGetGlobalSettings.mockReturnValue({
|
||||
developer_mode: '0',
|
||||
image_update_check_mode: 'cron',
|
||||
image_update_check_cron: '',
|
||||
image_update_check_interval_minutes: '120',
|
||||
});
|
||||
const service = ImageUpdateService.getInstance();
|
||||
service.configureFromSettings();
|
||||
const status = service.getStatus();
|
||||
expect(status.mode).toBe('interval');
|
||||
expect(status.cronExpression).toBeNull();
|
||||
});
|
||||
|
||||
it('configureFromSettings accepts cron nicknames like @daily', () => {
|
||||
mockGetGlobalSettings.mockReturnValue({
|
||||
developer_mode: '0',
|
||||
image_update_check_mode: 'cron',
|
||||
image_update_check_cron: '@daily',
|
||||
image_update_check_interval_minutes: '120',
|
||||
});
|
||||
const service = ImageUpdateService.getInstance();
|
||||
service.configureFromSettings();
|
||||
const status = service.getStatus();
|
||||
expect(status.mode).toBe('cron');
|
||||
expect(status.cronExpression).toBe('@daily');
|
||||
});
|
||||
|
||||
it('nextDelayMs computes a positive delay for a valid cron expression', () => {
|
||||
mockGetGlobalSettings.mockReturnValue({
|
||||
developer_mode: '0',
|
||||
image_update_check_mode: 'cron',
|
||||
image_update_check_cron: '0 3 * * 1',
|
||||
image_update_check_interval_minutes: '120',
|
||||
});
|
||||
const service = ImageUpdateService.getInstance();
|
||||
service.configureFromSettings();
|
||||
// nextDelayMs is private; access it to verify it does not throw and returns
|
||||
// a positive number (next Monday at 03:00 is in the future).
|
||||
const delay = (service as any).nextDelayMs();
|
||||
expect(typeof delay).toBe('number');
|
||||
expect(delay).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('nextDelayMs falls back to interval on runtime parse failure', () => {
|
||||
// Set up cron mode, then corrupt the expression at runtime before nextDelayMs.
|
||||
mockGetGlobalSettings.mockReturnValue({
|
||||
developer_mode: '0',
|
||||
image_update_check_mode: 'cron',
|
||||
image_update_check_cron: '0 3 * * 1',
|
||||
image_update_check_interval_minutes: '120',
|
||||
});
|
||||
const service = ImageUpdateService.getInstance();
|
||||
service.configureFromSettings();
|
||||
// Corrupt the expression directly on the private field.
|
||||
(service as any).cronExpression = '0 0 31 2 *'; // Feb 31 — invalid
|
||||
const delay = (service as any).nextDelayMs();
|
||||
// Should fall back to interval mode after the parse error.
|
||||
expect(service.getStatus().mode).toBe('interval');
|
||||
expect(typeof delay).toBe('number');
|
||||
expect(delay).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -122,6 +122,94 @@ describe('PUT /api/image-updates/interval', () => {
|
||||
const statusRes = await request(app).get('/api/image-updates/status').set('Cookie', adminCookie);
|
||||
expect(statusRes.body.intervalMinutes).toBe(30);
|
||||
});
|
||||
|
||||
// ── Cron mode ──────────────────────────────────────────────────────────
|
||||
|
||||
it('persists a valid cron expression and returns the enriched status', async () => {
|
||||
const res = await request(app).put('/api/image-updates/interval')
|
||||
.set('Cookie', adminCookie)
|
||||
.send({ minutes: 120, mode: 'cron', cron: '0 3 * * 1' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.mode).toBe('cron');
|
||||
expect(res.body.cronExpression).toBe('0 3 * * 1');
|
||||
const settings = DatabaseService.getInstance().getGlobalSettings();
|
||||
expect(settings.image_update_check_mode).toBe('cron');
|
||||
expect(settings.image_update_check_cron).toBe('0 3 * * 1');
|
||||
});
|
||||
|
||||
it('accepts a cron nickname like @daily', async () => {
|
||||
const res = await request(app).put('/api/image-updates/interval')
|
||||
.set('Cookie', adminCookie)
|
||||
.send({ minutes: 120, mode: 'cron', cron: '@daily' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.mode).toBe('cron');
|
||||
expect(res.body.cronExpression).toBe('@daily');
|
||||
});
|
||||
|
||||
it('rejects a 6-field cron expression', async () => {
|
||||
const res = await request(app).put('/api/image-updates/interval')
|
||||
.set('Cookie', adminCookie)
|
||||
.send({ minutes: 120, mode: 'cron', cron: '0 0 3 * * 1' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toMatch(/5 fields/);
|
||||
});
|
||||
|
||||
it('rejects a blank cron expression when mode is cron', async () => {
|
||||
const res = await request(app).put('/api/image-updates/interval')
|
||||
.set('Cookie', adminCookie)
|
||||
.send({ minutes: 120, mode: 'cron', cron: ' ' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects an invalid cron expression (backend-authoritative)', async () => {
|
||||
const res = await request(app).put('/api/image-updates/interval')
|
||||
.set('Cookie', adminCookie)
|
||||
.send({ minutes: 120, mode: 'cron', cron: '0 0 31 2 *' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toMatch(/Invalid cron/);
|
||||
});
|
||||
|
||||
it('rejects cron mode without a cron field', async () => {
|
||||
const res = await request(app).put('/api/image-updates/interval')
|
||||
.set('Cookie', adminCookie)
|
||||
.send({ minutes: 120, mode: 'cron' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toMatch(/Cron expression/);
|
||||
});
|
||||
|
||||
it('clears cron when switching back to interval mode', async () => {
|
||||
// First set cron mode.
|
||||
await request(app).put('/api/image-updates/interval')
|
||||
.set('Cookie', adminCookie)
|
||||
.send({ minutes: 120, mode: 'cron', cron: '0 3 * * 1' });
|
||||
// Then switch to interval.
|
||||
const res = await request(app).put('/api/image-updates/interval')
|
||||
.set('Cookie', adminCookie)
|
||||
.send({ minutes: 60, mode: 'interval' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.mode).toBe('interval');
|
||||
expect(res.body.cronExpression).toBeNull();
|
||||
const settings = DatabaseService.getInstance().getGlobalSettings();
|
||||
expect(settings.image_update_check_mode).toBe('interval');
|
||||
expect(settings.image_update_check_cron).toBe('');
|
||||
});
|
||||
|
||||
it('old-client { minutes } only does not change mode (backward compat)', async () => {
|
||||
// First set cron mode.
|
||||
await request(app).put('/api/image-updates/interval')
|
||||
.set('Cookie', adminCookie)
|
||||
.send({ minutes: 120, mode: 'cron', cron: '0 3 * * 1' });
|
||||
// Then send old-client payload.
|
||||
const res = await request(app).put('/api/image-updates/interval')
|
||||
.set('Cookie', adminCookie)
|
||||
.send({ minutes: 30 });
|
||||
expect(res.status).toBe(200);
|
||||
// Mode and cron are unchanged.
|
||||
expect(res.body.mode).toBe('cron');
|
||||
expect(res.body.cronExpression).toBe('0 3 * * 1');
|
||||
// Interval was updated (the fallback value).
|
||||
expect(res.body.intervalMinutes).toBe(30);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/image-updates/fleet', () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Router, type Request, type Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import DockerController from '../services/DockerController';
|
||||
import { DatabaseService } from '../services/DatabaseService';
|
||||
import { NodeRegistry } from '../services/NodeRegistry';
|
||||
@@ -55,10 +56,33 @@ imageUpdatesRouter.get('/status', authMiddleware, (_req: Request, res: Response)
|
||||
res.json(ImageUpdateService.getInstance().getStatus());
|
||||
});
|
||||
|
||||
/**
|
||||
* Validate a cron expression using the same contract as Scheduled Operations:
|
||||
* non-empty, reject 6+ fields, parse with CronExpressionParser, and prove
|
||||
* .next() can produce a future fire time. Nicknames like @daily are accepted.
|
||||
*/
|
||||
function validateImageCheckCron(cron: unknown): string | null {
|
||||
if (typeof cron !== 'string' || !cron.trim()) {
|
||||
return 'Cron expression is required.';
|
||||
}
|
||||
if (cron.trim().split(/\s+/).length >= 6) {
|
||||
return 'Cron expression must use 5 fields (minute hour day month weekday). The seconds field is not supported.';
|
||||
}
|
||||
try {
|
||||
const expr = CronExpressionParser.parse(cron);
|
||||
expr.next(); // prove the expression can produce a next fire time
|
||||
} catch {
|
||||
return 'Invalid cron expression.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Min/max mirror ImageUpdateService's clamp; the service is the authority and
|
||||
// re-clamps on read, so this is the user-facing validation boundary.
|
||||
const IntervalPatchSchema = z.object({
|
||||
minutes: z.coerce.number().int().min(15).max(1440),
|
||||
mode: z.enum(['interval', 'cron']).optional(),
|
||||
cron: z.string().optional(),
|
||||
});
|
||||
|
||||
imageUpdatesRouter.put('/interval', authMiddleware, (req: Request, res: Response): void => {
|
||||
@@ -68,8 +92,33 @@ imageUpdatesRouter.put('/interval', authMiddleware, (req: Request, res: Response
|
||||
res.status(400).json({ error: 'minutes must be an integer between 15 and 1440' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate cron expression when mode is 'cron'.
|
||||
if (parsed.data.mode === 'cron') {
|
||||
const cronError = validateImageCheckCron(parsed.data.cron);
|
||||
if (cronError) {
|
||||
res.status(400).json({ error: cronError });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
DatabaseService.getInstance().updateGlobalSetting('image_update_check_interval_minutes', String(parsed.data.minutes));
|
||||
const db = DatabaseService.getInstance();
|
||||
const writeSettings = db.getDb().transaction((entries: [string, string][]) => {
|
||||
for (const [k, v] of entries) db.updateGlobalSetting(k, v);
|
||||
});
|
||||
const entries: [string, string][] = [
|
||||
['image_update_check_interval_minutes', String(parsed.data.minutes)],
|
||||
];
|
||||
if (parsed.data.mode !== undefined) {
|
||||
entries.push(['image_update_check_mode', parsed.data.mode]);
|
||||
}
|
||||
if (parsed.data.mode === 'cron' && parsed.data.cron !== undefined) {
|
||||
entries.push(['image_update_check_cron', parsed.data.cron]);
|
||||
} else if (parsed.data.mode === 'interval') {
|
||||
entries.push(['image_update_check_cron', '']); // clear stale cron
|
||||
}
|
||||
writeSettings(entries);
|
||||
// Reschedule the live timer so the new cadence takes effect without a restart.
|
||||
ImageUpdateService.getInstance().restartPolling();
|
||||
res.json(ImageUpdateService.getInstance().getStatus());
|
||||
|
||||
@@ -1585,6 +1585,8 @@ export class DatabaseService {
|
||||
stmt.run('health_gate_enabled', '1');
|
||||
stmt.run('health_gate_window_seconds', '90');
|
||||
stmt.run('image_update_check_interval_minutes', '120');
|
||||
stmt.run('image_update_check_mode', 'interval');
|
||||
stmt.run('image_update_check_cron', '');
|
||||
stmt.run('env_block_deploy_on_missing_required', '0');
|
||||
|
||||
// Seed the default local node if none exists
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import path from 'path';
|
||||
import YAML from 'yaml';
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import DockerController from './DockerController';
|
||||
import { DatabaseService } from './DatabaseService';
|
||||
import { FileSystemService } from './FileSystemService';
|
||||
@@ -27,6 +28,8 @@ export interface ImageCheckResult {
|
||||
* remaining time (0 when a manual refresh is allowed). `lastCheckedAt` /
|
||||
* `nextCheckAt` are epoch-ms or null ("never checked" / "not scheduled");
|
||||
* `nextCheckAt` is meaningless while `checking` is true.
|
||||
* `mode` is the active scheduling mode; `cronExpression` is the 5-field
|
||||
* expression when mode is 'cron', null otherwise or when unconfigured.
|
||||
*/
|
||||
export interface ImageUpdateStatus {
|
||||
checking: boolean;
|
||||
@@ -35,6 +38,8 @@ export interface ImageUpdateStatus {
|
||||
nextCheckAt: number | null;
|
||||
manualCooldownMinutes: number;
|
||||
manualCooldownRemainingMs: number;
|
||||
mode: 'interval' | 'cron';
|
||||
cronExpression: string | null;
|
||||
}
|
||||
|
||||
// ─── Compose file helpers ────────────────────────────────────────────────────
|
||||
@@ -162,6 +167,8 @@ export class ImageUpdateService {
|
||||
private static readonly MAX_INTERVAL_MINUTES = 1440; // 24 hours
|
||||
private static readonly DEFAULT_INTERVAL_MINUTES = 120; // 2 hours
|
||||
private static readonly INTERVAL_SETTING_KEY = 'image_update_check_interval_minutes';
|
||||
private static readonly MODE_SETTING_KEY = 'image_update_check_mode';
|
||||
private static readonly CRON_SETTING_KEY = 'image_update_check_cron';
|
||||
private static readonly JITTER_FRACTION = 0.1; // ±10% so a fleet does not poll in lockstep
|
||||
private static readonly STARTUP_DELAY_MS = 2 * 60 * 1000; // 2 min after boot
|
||||
|
||||
@@ -182,6 +189,8 @@ export class ImageUpdateService {
|
||||
// Initialized at declaration so getStatus() never reports NaN before start()
|
||||
// or configureFromSettings() has run (e.g. route tests that skip startServer).
|
||||
private intervalMs = ImageUpdateService.DEFAULT_INTERVAL_MINUTES * 60 * 1000;
|
||||
private mode: 'interval' | 'cron' = 'interval';
|
||||
private cronExpression: string | null = null;
|
||||
private static readonly MANUAL_COOLDOWN_MS = 2 * 60 * 1000; // 2 min between manual triggers
|
||||
private static readonly INTER_IMAGE_DELAY_MS = 300; // be polite to registries
|
||||
private static readonly CHECK_TIMEOUT_MS = 5 * 60 * 1000; // threshold for the "running long" skip warning
|
||||
@@ -242,10 +251,37 @@ export class ImageUpdateService {
|
||||
/**
|
||||
* Reads image_update_check_interval_minutes into intervalMs, clamped to
|
||||
* [15, 1440], falling back to the 2-hour default on a missing, blank,
|
||||
* malformed, or unreadable value.
|
||||
* malformed, or unreadable value. Also reads mode and cron expression
|
||||
* from global_settings; falls back to interval mode when cron is
|
||||
* unconfigured or unparseable.
|
||||
*/
|
||||
public configureFromSettings(): void {
|
||||
this.intervalMs = ImageUpdateService.resolveIntervalMinutes() * 60 * 1000;
|
||||
|
||||
const settings = DatabaseService.getInstance().getGlobalSettings();
|
||||
const rawMode = settings[ImageUpdateService.MODE_SETTING_KEY];
|
||||
this.mode = (rawMode === 'cron') ? 'cron' : 'interval';
|
||||
|
||||
if (this.mode === 'cron') {
|
||||
const rawCron = settings[ImageUpdateService.CRON_SETTING_KEY];
|
||||
if (typeof rawCron === 'string' && rawCron.trim()) {
|
||||
try {
|
||||
const expr = CronExpressionParser.parse(rawCron);
|
||||
expr.next(); // prove the expression can produce a next fire time
|
||||
this.cronExpression = rawCron.trim();
|
||||
} catch {
|
||||
console.warn(`[ImageUpdateService] Cron expression is invalid; falling back to interval mode. Expression: "${rawCron}"`);
|
||||
this.mode = 'interval';
|
||||
this.cronExpression = null;
|
||||
}
|
||||
} else {
|
||||
console.warn('[ImageUpdateService] Cron mode is active but no expression is set; falling back to interval mode.');
|
||||
this.mode = 'interval';
|
||||
this.cronExpression = null;
|
||||
}
|
||||
} else {
|
||||
this.cronExpression = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static resolveIntervalMinutes(): number {
|
||||
@@ -290,8 +326,31 @@ export class ImageUpdateService {
|
||||
}
|
||||
}
|
||||
|
||||
/** intervalMs with ±10% jitter so multiple nodes do not hit registries together. */
|
||||
/**
|
||||
* Compute the next check delay. In interval mode this is intervalMs with
|
||||
* ±10% jitter. In cron mode the delay is the gap between now and the next
|
||||
* cron fire time, with no jitter (the user chose a specific time). Falls
|
||||
* back to interval mode if the cron expression cannot be parsed at runtime.
|
||||
*/
|
||||
private nextDelayMs(): number {
|
||||
if (this.mode === 'cron' && this.cronExpression) {
|
||||
try {
|
||||
const expr = CronExpressionParser.parse(this.cronExpression);
|
||||
const nextFire = expr.next().toDate().getTime();
|
||||
const delay = nextFire - Date.now();
|
||||
if (delay <= 0) {
|
||||
// We just passed the fire time; retry in 30 s so the next
|
||||
// .next() call moves to the following occurrence.
|
||||
return 30_000;
|
||||
}
|
||||
return delay;
|
||||
} catch (e) {
|
||||
console.warn('[ImageUpdateService] Cron expression became invalid at runtime; falling back to interval mode:', getErrorMessage(e, String(e)));
|
||||
this.mode = 'interval';
|
||||
this.cronExpression = null;
|
||||
// Fall through to interval-based delay below.
|
||||
}
|
||||
}
|
||||
const jitter = this.intervalMs * ImageUpdateService.JITTER_FRACTION;
|
||||
return Math.round(this.intervalMs - jitter + Math.random() * 2 * jitter);
|
||||
}
|
||||
@@ -328,6 +387,8 @@ export class ImageUpdateService {
|
||||
nextCheckAt: this.nextCheckAt,
|
||||
manualCooldownMinutes: ImageUpdateService.manualCooldownMinutes,
|
||||
manualCooldownRemainingMs: this.getManualCooldownRemainingMs(),
|
||||
mode: this.mode,
|
||||
cronExpression: this.cronExpression,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user