feat(server): scheduled jobs on the server and a Scheduled tab in the admin panel

Owner review 2, R10: nothing may run out of sight, so every timer the server
ran becomes a system schedule the admin panel shows and manages, and
administrators create their own.

- SchedulerHost runs the shared Scheduler on the job engine (started after
  JobEngineHost, stopped before it); ServerScheduleHost gives it the
  container's time zone (UTC with a warning when TZ is unknown), the archive
  refreshed from archive.json at every run (what ArchivePolling did), the
  clean-up steps and the system schedules: archive-scan every 10 minutes
  (no catch-up, also run once at start like the polling), upload-cleanup
  every 30 minutes, index-backup at 03:00 (SQLite only), housekeeping (job
  history) at 04:00 and audit-cleanup at 04:30.
- ArchivePolling and DatabaseBackupService are gone; UploadMaintenance only
  recovers commits at start, its sweep is the "uploads" clean-up step.
- /api/v1/schedules (ManageArchive, audited): list with actions and time
  zone, create, PUT/PATCH, delete (409 schedule_system), run now (409
  schedule_pending), reset (409 schedule_no_defaults), runs paged by cursor;
  invalid fields are 400 invalid_schedule naming the field.
- CHRONOS_AUDIT_RETENTION_DAYS (AuditRetentionDays, default 365) seeds the
  audit clean-up; set by the environment it is applied at every start and
  locked. Job history leaves Settings: it is the housekeeping schedule's age
  limit, and the setting is what a reset restores.
- Admin panel: Jobs has Queue and Scheduled tabs; schedules with when (in
  the panel's language and the server's zone), next run, last result, a
  switch, Run now, Edit, Delete or Reset, their runs linking to the jobs, and
  a side panel for the action, recurrence and parameters; job rows a
  schedule queued carry a Scheduled pill. Strings in en and it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 808ce94ae29e3bf4522cb4d40dfd76d4f8529c64)
This commit is contained in:
Alby96 committed 2026-10-27 02:25:01 +01:00
1 parent e5508e7e69
commit 75daab7275
66 files changed
+1985 -290

No files matched your search

+20
View File
@@ -223,9 +223,24 @@ svg.chart .label { fill: var(--text-muted); }
.table.nodes.fit-1 .col-owner, .table.nodes.fit-1 .col-heartbeat { display: none; }
.table.audit.fit-1 { grid-template-columns: max-content minmax(70px, .8fr) minmax(90px, max-content) minmax(100px, 2fr); }
.table.audit.fit-1 .col-from { display: none; }
/* Scheduled jobs (owner review 2, R10): name, action, when, next run, last result, switch, actions. */
.table.schedules { grid-template-columns: minmax(130px, 1.3fr) minmax(80px, max-content) minmax(110px, 1fr) max-content minmax(90px, max-content) max-content max-content; }
.table.schedules.fit-1 { grid-template-columns: minmax(130px, 1.3fr) minmax(110px, 1fr) max-content minmax(90px, max-content) max-content max-content; }
.table.schedules.fit-1 .col-action { display: none; }
.table.schedules.fit-2 { grid-template-columns: minmax(120px, 1.3fr) minmax(100px, 1fr) max-content max-content max-content; }
.table.schedules.fit-2 .col-last { display: none; }
.table-foot { display: flex; align-items: center; gap: 16px; padding: 10px 18px; font-size: 12px; }
.table-foot a { white-space: nowrap; }
.row-actions { display: flex; gap: 6px; justify-content: flex-end; }
/* A name with a pill after it (a system schedule, a job a schedule queued). */
.name-cell { display: flex; align-items: center; gap: 8px; min-width: 0; }
.pill { flex: none; display: inline-flex; align-items: center; height: 20px; padding: 0 8px; border: 1px solid var(--stroke); border-radius: 12px; font-size: 11px; color: var(--text-muted); white-space: nowrap; text-decoration: none; }
a.pill:hover { border-color: var(--accent); color: var(--accent); }
/* The runs of a schedule, under its row: kind, state, time and a link to the job. */
.runs { display: grid; grid-template-columns: minmax(0, max-content) max-content max-content max-content; gap: 6px 18px; align-items: center; padding: 10px 18px; background: var(--bg); border-top: 1px solid var(--stroke); }
.runs .run { display: contents; }
.runs .more { grid-column: 1 / -1; justify-self: start; }
.table .row.log-row .empty { background: var(--bg); border-top: 1px solid var(--stroke); }
.person { display: flex; align-items: center; gap: 10px; min-width: 0; }
.stack { display: flex; flex-direction: column; min-width: 0; }
.stack small { font-size: 11px; color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -253,6 +268,11 @@ pre.log.tall { max-height: 60vh; border-top: 0; }
.form legend { color: var(--text-muted); margin-bottom: 8px; padding: 0; }
.form h2 { font-size: 16px; }
.inline { display: flex; align-items: center; gap: 8px; }
.form-group { display: grid; gap: 12px; }
.form-group:empty { display: none; }
.days { display: flex; flex-wrap: wrap; gap: 8px 14px; }
/* Each tab of a page draws into its own body; its children lay out as the page's own. */
.tab-body { display: contents; }
.buttons { display: flex; gap: 8px; justify-content: flex-end; }
.error { color: var(--error); min-height: 18px; }
.settings { display: grid; gap: 20px; }
+13
View File
@@ -3,6 +3,7 @@
import { t, has, plural } from "./i18n.js";
import { formatBytes } from "./ui.js";
import { kindLabel, pascal } from "./jobs.js";
import { actionLabel as scheduleAction, outcomeLabel } from "./schedules.js";
export function actionLabel(action) {
const key = `Admin.Logs.Action.${pascal(action)}`;
@@ -35,6 +36,18 @@ export function detailText(entry) {
case "user_updated":
case "sequence_updated":
return details.split(", ").map(changeLabel).join(", ");
case "schedule_run": {
const [name, outcome] = splitLast(details);
return outcome === undefined ? details : `${name} · ${outcomeLabel(outcome)}`;
}
case "schedule_created":
case "schedule_updated":
case "schedule_deleted":
case "schedule_reset": {
// "name · action · recurrence[ · off]": the action in words, the name as typed (system schedules: as stored).
const [name, action, ...rest] = details.split(" · ");
return action === undefined ? details : [name, scheduleAction(action), ...rest.map((r) => r === "off" ? t("Admin.Schedules.Off") : r)].join(" · ");
}
default:
return details;
}
+59 -7
View File
@@ -1,18 +1,60 @@
// Jobs (BRIEF §14.8): queue and history with cancel/pause/resume/retry/priority, log tails, render nodes.
// Jobs (BRIEF §14.8): two tabs in the header. Queue: queue and history with cancel/pause/resume/retry/priority, log tails,
// render nodes; #/jobs?job=<id> opens that job's log. Scheduled (#/jobs?tab=schedules, owner review 2, R10): the server's
// schedules, its system ones included (schedules.js).
import { t, plural, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatTime, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, fitColumns } from "../ui.js";
import { escapeHtml, attr, formatTime, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, fitColumns, routeParams } from "../ui.js";
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders, logText } from "../jobs.js";
import { renderSchedules } from "../schedules.js";
const TABS = ["queue", "schedules"];
const FILTERS = ["all", "running", "queued", "paused", "failed", "done", "cancelled"];
const PRIORITIES = ["background", "normal", "user"];
export async function render(root, { api, setMeta, onEvent }) {
export async function render(root, context) {
const { actions, onEvent } = context;
let tab = TABS.includes(routeParams().get("tab")) ? routeParams().get("tab") : "queue";
// The open tab's event handler: the page subscribes once, a tab that was left hears nothing more.
let handler = null;
onEvent((e) => handler?.(e));
actions.innerHTML = `<div class="segmented" role="group" aria-label="${attr(t("Admin.Nav.Jobs"))}">${TABS.map((name) =>
`<button class="btn" data-tab="${name}" aria-pressed="${name === tab}" data-i18n="Admin.Jobs.Tab.${cap(name)}" data-i18n-title="Admin.Jobs.Tab.${cap(name)}.Tip"></button>`).join("")}</div>
<span class="actions" id="tab-actions"></span>`;
applyStrings(actions);
const tabActions = actions.querySelector("#tab-actions");
actions.querySelectorAll("[data-tab]").forEach((b) => b.addEventListener("click", () => {
if (b.dataset.tab === tab) return;
tab = b.dataset.tab;
actions.querySelectorAll("[data-tab]").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
history.replaceState(null, "", tab === "queue" ? "#/jobs" : "#/jobs?tab=schedules");
show();
}));
async function show() {
handler = null;
tabActions.innerHTML = "";
// Each tab draws into a body of its own, so a late answer of the tab that was left never touches the new one.
root.innerHTML = `<div class="tab-body"></div>`;
const body = root.firstElementChild;
const scoped = { ...context, actions: tabActions, onEvent: (fn) => { handler = fn; } };
if (tab === "queue") await renderQueue(body, scoped, routeParams().get("job"));
else await renderSchedules(body, scoped, routeParams().get("schedule"));
}
await show();
}
/** The Queue tab; <paramref name="focusJob"/> (a job id from a schedule's runs) is shown first with its log open. */
async function renderQueue(root, { api, setMeta, onEvent }, focusJob) {
let filter = "all";
let jobs = [];
let nodes = [];
let running = 0;
let cursor = null;
const expanded = new Set();
// The job a schedule's run links to stays first while the list does not hold it; it gets the focus once.
const pinId = focusJob;
let pinned = null;
const expanded = new Set(pinId ? [pinId] : []);
let timer = null;
root.innerHTML = `
@@ -47,6 +89,7 @@ export async function render(root, { api, setMeta, onEvent }) {
}
async function load(more = false) {
if (!root.isConnected) return;
try {
const state = filter === "all" ? "" : `&state=${filter}`;
const [page, list, active] = await Promise.all([
@@ -59,20 +102,29 @@ export async function render(root, { api, setMeta, onEvent }) {
cursor = page.nextCursor;
nodes = list;
running = active.items.length;
pinned = pinId && !jobs.some((j) => j.id === pinId) ? await api.get(`/api/v1/jobs/${pinId}`).catch(() => null) : null;
} catch (err) {
toast(errorText(err), true);
return;
}
if (!root.isConnected) return;
setMeta(`${plural("Admin.Jobs.RunningCount", running)} · ${plural("Admin.Jobs.NodesOnline", nodes.filter((n) => n.state !== "offline").length)}`);
draw();
if (focusJob) {
root.querySelector(`[data-toggle="${CSS.escape(focusJob)}"]`)?.focus();
root.querySelector(`[data-key="${CSS.escape(focusJob)}"]`)?.scrollIntoView({ block: "center" });
focusJob = null;
}
}
function draw() {
const host = root.querySelector("#rows");
const shown = pinned ? [pinned, ...jobs] : jobs;
redraw(host, () => {
host.innerHTML = jobs.map((j) => `
host.innerHTML = shown.map((j) => `
<div class="row" role="row" data-key="${attr(j.id)}">
<span role="cell"><button class="link ellipsis" data-toggle="${attr(j.id)}" aria-expanded="${expanded.has(j.id)}" aria-controls="log-${attr(j.id)}" data-i18n-title="Admin.Jobs.Log.Tip">${escapeHtml(kindLabel(j.kind))}</button></span>
<span class="name-cell" role="cell"><button class="link ellipsis" data-toggle="${attr(j.id)}" aria-expanded="${expanded.has(j.id)}" aria-controls="log-${attr(j.id)}" data-i18n-title="Admin.Jobs.Log.Tip">${escapeHtml(kindLabel(j.kind))}</button>${j.scheduleId
? `<a class="pill" href="#/jobs?tab=schedules&amp;schedule=${attr(j.scheduleId)}" data-i18n="Admin.Jobs.Scheduled" data-i18n-title="Admin.Jobs.Scheduled.Tip"></a>` : ""}</span>
<span class="ellipsis" role="cell" dir="auto" title="${attr(j.targetLabel ?? "")}">${escapeHtml(j.targetLabel ?? "")}</span>
<span class="col-node ellipsis" role="cell" dir="auto">${escapeHtml(nodeLabel(j, nodes))}</span>
<span class="progress" role="cell">${progressCell(j)}</span>
@@ -175,7 +227,7 @@ export async function render(root, { api, setMeta, onEvent }) {
onEvent((e) => {
if (e.type === "jobProgress") {
const job = jobs.find((j) => j.id === e.jobId);
const job = jobs.find((j) => j.id === e.jobId) ?? (pinned?.id === e.jobId ? pinned : null);
if (job) {
job.progressDone = e.done;
job.progressTotal = e.total;
@@ -1,8 +1,10 @@
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention, logs. Values fixed by
// environment variables are read-only here; ports, TLS, chunk size and job history apply at the next restart. Jobs run one
// at a time (owner review 1): the parallelism (photos at once) and the priority queue apply at once, as do the log levels,
// retention, size limits and rotation (owner review 2, R11). About (version, API, database, uptime) is the last group,
// read-only (owner review 2); #/about opens here on it.
// environment variables are read-only here; ports, TLS and chunk size apply at the next restart. How long job history is
// kept is a parameter of the Job history clean-up schedule (Jobs › Scheduled, owner review 2, R10); the audit retention
// saved here is the Audit log clean-up schedule's age limit. Jobs run one at a time (owner review 1): the parallelism
// (photos at once) and the priority queue apply at once, as do the log levels, retention, size limits and rotation
// (owner review 2, R11). About (version, API, database, uptime) is the last group, read-only (owner review 2); #/about
// opens here on it.
import { t, applyStrings, languages } from "../i18n.js";
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, PROXY_WARNING } from "../ui.js";
import { kindLabel } from "../jobs.js";
@@ -94,7 +96,6 @@ export async function render(root, { api, info, setMeta, actions }) {
${number("chunkSizeMib", settings.chunkSizeBytes / MIB, 'min="0.0625" max="64" step="0.0625"')}
${number("tokenLifetimeDays", settings.tokenLifetimeDays, 'min="1" max="365"')}
${number("uploadRetentionHours", settings.uploadRetentionHours, 'min="1" max="8760"')}
${number("jobHistoryDays", settings.jobHistoryDays, 'min="1" max="3650"')}
</section>
<section class="panel" aria-labelledby="logs-title">
<h2 id="logs-title" data-i18n="Admin.Settings.Logs"></h2>
@@ -104,7 +105,7 @@ export async function render(root, { api, info, setMeta, actions }) {
${number("logMaxFileMb", settings.logs.maxFileMb, 'min="0" max="10240"')}
${number("logMaxTotalMb", settings.logs.maxTotalMb, 'min="0" max="1048576"')}
${choice("logRotation", settings.logs.rotation, ROTATIONS, (r) => `Admin.Settings.Rotation.${cap(r)}`)}
${number("auditRetentionDays", settings.logs.auditRetentionDays, 'min="0" max="36500"')}
${number("auditRetentionDays", settings.logs.auditRetentionDays, 'min="0" max="3650"')}
${number("diagnosticsLogMb", settings.logs.diagnosticsLogMb, 'min="1" max="1024"')}
</section>
</form>
@@ -180,7 +181,6 @@ export async function render(root, { api, info, setMeta, actions }) {
chunkSizeBytes: Math.round(Number(data.get("chunkSizeMib")) * MIB),
tokenLifetimeDays: Number(data.get("tokenLifetimeDays")),
uploadRetentionHours: Number(data.get("uploadRetentionHours")),
jobHistoryDays: Number(data.get("jobHistoryDays")),
logs: {
fileLevel: String(value("logLevel", settings.logs.fileLevel)),
consoleLevel: String(value("consoleLogLevel", settings.logs.consoleLevel)),
+534
View File
@@ -0,0 +1,534 @@
// Scheduled jobs (owner review 2, R10): the Scheduled tab of the Jobs page (#/jobs?tab=schedules). Every schedule of the
// server, its system schedules first (the timers it runs, shown so nothing runs out of sight), with when it runs in the
// server's time zone, its next run, its last result and a switch; Run now, Edit, Delete (user schedules) and Reset
// (system schedules). A schedule's name opens its last runs, each linking to its job on the Queue tab. A side panel
// creates and edits schedules: the action (those the server cannot run are disabled, their reason in the tooltip), the
// recurrence, the action's parameters, priority, catch-up and the switch.
import { t, plural, has, applyStrings, culture } from "./i18n.js";
import { escapeHtml, attr, formatNumber, formatTime, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, focusPlace, restoreFocus, fitColumns,
markInvalid, clearInvalid, invalidText } from "./ui.js";
import { kindLabel, pascal, stateCell } from "./jobs.js";
const KINDS = ["every", "daily", "weekly", "monthly"];
const UNITS = ["minutes", "hours", "days"];
/** Day names of the API, Monday first; 1 January 2001 was a Monday. */
const DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
const PRIORITIES = ["background", "normal", "user"];
/** The parameters each action reads (ScheduleActions.Normalize), in the order the form shows them. */
const PARAMETERS = {
scan: ["force", "deep"], verify: ["olderThanDays", "percent"], thumbnails: ["force"], proxies: ["force"], analysis: ["deep"],
maintenance: ["dryRun"], backup: ["keep"], cleanup: ["steps", "olderThanDays"], duplicates: [], orphans: [],
};
/** What a new schedule of an action starts with (ScheduleActions.Defaults); absent values are false or off. */
const DEFAULTS = { verify: { olderThanDays: 30, percent: 100 }, backup: { keep: 3 }, cleanup: { steps: ["job-history"], olderThanDays: 90 } };
/** A parameter's label and tooltip by action, under Admin.Schedules.Param. */
const PARAM_KEYS = {
"scan.force": "FullScan", "scan.deep": "DeepAfterScan", "thumbnails.force": "MakeAgain", "proxies.force": "MakeAgain", "analysis.deep": "Deep",
"verify.olderThanDays": "UncheckedDays", "verify.percent": "Percent", "maintenance.dryRun": "DryRun", "backup.keep": "Keep",
"cleanup.steps": "Steps", "cleanup.olderThanDays": "OlderDays",
};
const NUMBERS = { olderThanDays: 'min="0" max="3650"', percent: 'min="1" max="100"', keep: 'min="1" max="100"' };
/** Settings an environment variable fixes for a system schedule's age limit (ServerScheduleHost.LockedAgeOf). */
const LOCKED_AGES = { "audit-cleanup": ["AuditRetentionDays", "CHRONOS_AUDIT_RETENTION_DAYS"] };
/** A schedule's name: a system schedule's in the panel's language (by its key), a user's as typed. */
export function scheduleName(schedule) {
const key = schedule.systemKey ? `Admin.Schedules.System.${pascal(schedule.systemKey)}` : null;
return key && has(key) ? t(key) : schedule.name;
}
export function actionLabel(action) {
const key = `Admin.Schedules.Action.${pascal(action)}`;
return has(key) ? t(key) : action;
}
/** "Queued", "Skipped: busy", "Failed"… for an outcome code (failed:<reason> included). */
export function outcomeLabel(outcome) {
if (String(outcome).startsWith("failed:")) return t("Admin.Schedules.Outcome.Failed");
const key = `Admin.Schedules.Outcome.${pascal(outcome ?? "")}`;
return has(key) ? t(key) : String(outcome ?? "");
}
/** What an outcome means, as one sentence (a failure with its reason). */
export function outcomeTip(outcome) {
const text = String(outcome ?? "");
if (text.startsWith("failed:")) return t("Admin.Schedules.Outcome.Failed.Tip", text.slice("failed:".length));
const key = `Admin.Schedules.Outcome.${pascal(text)}.Tip`;
return has(key) ? t(key) : text;
}
/** "Every 10 minutes", "Daily at 03:00", "Mon, Thu at 02:30", "Day 1 of each month at 04:00" in the panel's language. */
export function recurrenceText(r) {
switch (r?.kind) {
case "every": return UNITS.includes(r.unit) ? plural(`Admin.Schedules.Every.${cap(r.unit)}`, r.every) : `${r.every} ${r.unit}`;
case "daily": return t("Admin.Schedules.DailyAt", timeText(r.time));
case "weekly": return t("Admin.Schedules.WeeklyAt", dayList(r.days ?? []), timeText(r.time));
case "monthly": return t("Admin.Schedules.MonthlyAt", formatNumber(r.dayOfMonth), timeText(r.time));
default: return r?.kind ?? "";
}
}
export async function renderSchedules(root, { api, setMeta, actions, onEvent }, focusSchedule) {
let schedules = [];
let available = [];
let steps = [];
let zone = "UTC";
let locked = [];
let lastJobs = new Map();
const runs = new Map();
const expanded = new Set(focusSchedule ? [focusSchedule] : []);
let opener = null;
let timer = null;
actions.innerHTML = `<button class="btn primary" id="new" data-i18n="Admin.Schedules.New" data-i18n-title="Admin.Schedules.New.Tip"></button>`;
applyStrings(actions);
actions.querySelector("#new").addEventListener("click", () => openForm(null));
root.innerHTML = `
<div class="split">
<section class="panel flush">
<div class="table schedules" data-levels="2" role="table" aria-label="${attr(t("Admin.Jobs.Tab.Schedules"))}">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Schedules.Name"></span><span role="columnheader" class="col-action" data-i18n="Admin.Schedules.Action"></span>
<span role="columnheader" data-i18n="Admin.Schedules.When"></span><span role="columnheader" data-i18n="Admin.Schedules.NextRun"></span>
<span role="columnheader" class="col-last" data-i18n="Admin.Schedules.LastResult"></span><span role="columnheader" data-i18n="Admin.Schedules.Enabled"></span>
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div id="rows" role="rowgroup"></div>
</div>
</section>
<aside class="panel side" id="side" hidden></aside>
</div>`;
applyStrings(root);
const table = root.querySelector(".table");
const side = root.querySelector("#side");
side.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
e.preventDefault();
closeSide();
}
});
async function load() {
if (!root.isConnected) return;
try {
const [list, settings] = await Promise.all([api.get("/api/v1/schedules"), api.get("/api/v1/server/settings").catch(() => null)]);
schedules = list.items;
available = list.actions;
steps = list.steps ?? [];
zone = list.timeZone;
locked = settings?.locked ?? [];
// The state of each schedule's last job, for the Last result column (a job the history no longer has shows the outcome).
const ids = [...new Set(schedules.filter((s) => s.lastJobId && s.lastOutcome === "queued").map((s) => s.lastJobId))];
const jobs = await Promise.all(ids.map((id) => api.get(`/api/v1/jobs/${id}`).catch(() => null)));
lastJobs = new Map(jobs.filter(Boolean).map((j) => [j.id, j]));
await Promise.all([...expanded].map((id) => loadRuns(id)));
} catch (err) {
toast(errorText(err), true);
return;
}
if (!root.isConnected) return;
setMeta(`${plural("Admin.Schedules.Count", schedules.length)} · ${t("Admin.Schedules.TimeZone", zone)}`);
draw();
if (focusSchedule) {
root.querySelector(`[data-key="${CSS.escape(focusSchedule)}"]`)?.scrollIntoView({ block: "center" });
root.querySelector(`[data-toggle="${CSS.escape(focusSchedule)}"]`)?.focus();
focusSchedule = null;
}
}
/** The first page of a schedule's runs, or the next one with more. */
async function loadRuns(id, more = false) {
const known = runs.get(id);
const cursor = more && known?.cursor ? `&cursor=${encodeURIComponent(known.cursor)}` : "";
const page = await api.get(`/api/v1/schedules/${id}/runs?limit=10${cursor}`);
runs.set(id, { items: more && known ? known.items.concat(page.items) : page.items, cursor: page.nextCursor });
}
function draw() {
const host = root.querySelector("#rows");
redraw(host, () => {
host.innerHTML = schedules.map(rowHtml).join("") || `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Schedules.Empty",
`<button class="btn small" id="empty-new" data-i18n="Admin.Schedules.New" data-i18n-title="Admin.Schedules.New.Tip"></button>`)}</div></div>`;
applyStrings(host);
});
host.querySelectorAll("[data-toggle]").forEach((b) => b.addEventListener("click", () => toggle(b.dataset.toggle)));
host.querySelectorAll("[data-act]").forEach((b) => b.addEventListener("click", () => act(b.dataset.act, find(b.closest("[data-key]").dataset.key))));
host.querySelectorAll("[data-enable]").forEach((box) => box.addEventListener("change", () => setEnabled(find(box.dataset.enable), box)));
host.querySelectorAll("[data-more-runs]").forEach((b) => b.addEventListener("click", () => moreRuns(b.dataset.moreRuns)));
host.querySelectorAll("[data-run-first]").forEach((b) => b.addEventListener("click", () => act("run", find(b.dataset.runFirst))));
host.querySelector("#empty-new")?.addEventListener("click", () => openForm(null));
fitColumns(table);
}
function find(id) {
return schedules.find((s) => s.id === id);
}
function rowHtml(s) {
const name = scheduleName(s);
const button = (act, key, extra = "") => `<button class="btn small${extra}" data-act="${act}" data-i18n="Admin.Schedules.${key}" data-i18n-title="Admin.Schedules.${key}.Tip"></button>`;
const buttons = button("run", "Run") + button("edit", "Edit") + (s.systemKey ? button("reset", "Reset") : button("delete", "Delete", " destructive"));
const when = recurrenceText(s.recurrence);
return `
<div class="row${s.enabled ? "" : " dim"}" role="row" data-key="${attr(s.id)}">
<span class="name-cell" role="cell"><button class="link ellipsis" data-toggle="${attr(s.id)}" aria-expanded="${expanded.has(s.id)}" aria-controls="runs-${attr(s.id)}"
dir="auto" data-i18n-title="Admin.Schedules.Runs.Tip">${escapeHtml(name)}</button>${s.systemKey
? `<span class="pill" data-i18n="Admin.Schedules.System" data-i18n-title="Admin.Schedules.System.Tip"></span>` : ""}</span>
<span class="col-action ellipsis" role="cell" title="${attr(actionTip(s.action))}">${escapeHtml(actionLabel(s.action))}</span>
<span class="ellipsis" role="cell" title="${attr(t("Admin.Schedules.When.Tip", zone))}">${escapeHtml(when)}</span>
<span class="num nowrap" role="cell" title="${attr(t("Admin.Schedules.NextRun.Tip", zone))}">${escapeHtml(s.enabled ? zonedTime(s.nextRun, zone) : t("Admin.Schedules.Off"))}</span>
<span class="col-last ellipsis" role="cell">${lastResult(s)}</span>
<span role="cell"><input type="checkbox" role="switch" data-enable="${attr(s.id)}" ${s.enabled ? "checked" : ""}
aria-label="${attr(t("Admin.Schedules.EnabledFor", name))}" title="${attr(t("Admin.Schedules.Enabled.Tip"))}"></span>
<span class="row-actions" role="cell">${buttons}</span>
</div>
${expanded.has(s.id) ? `<div class="row log-row" role="row"><div class="wide" role="cell" id="runs-${attr(s.id)}">${runsHtml(s)}</div></div>` : ""}`;
}
/** The last result: the last job's state when the run queued one, else what the run did; when, in the tooltip's words. */
function lastResult(s) {
if (!s.lastRun) return `<span class="muted" data-i18n="Admin.Schedules.Never"></span>`;
const when = `<span class="muted"> · ${escapeHtml(formatTime(s.lastRun))}</span>`;
const tip = `${outcomeTip(s.lastOutcome)} · ${formatDateTime(s.lastRun)}`;
const job = s.lastOutcome === "queued" ? lastJobs.get(s.lastJobId) : null;
if (job) return `<span title="${attr(tip)}">${stateCell(job.state)}${when}</span>`;
const failed = String(s.lastOutcome).startsWith("failed:");
return `<span class="${failed ? "state failed" : ""}" title="${attr(tip)}">${escapeHtml(outcomeLabel(s.lastOutcome))}${when}</span>`;
}
function runsHtml(s) {
const page = runs.get(s.id);
if (!page) return "";
if (page.items.length === 0) {
return emptyState("Admin.Schedules.NoRuns", `<button class="btn small" data-run-first="${attr(s.id)}" data-i18n="Admin.Schedules.Run" data-i18n-title="Admin.Schedules.Run.Tip"></button>`);
}
return `<div class="runs" role="list" aria-label="${attr(t("Admin.Schedules.RunsOf", scheduleName(s)))}">${page.items.map((j) => `
<div class="run" role="listitem"><span class="ellipsis">${escapeHtml(kindLabel(j.kind))}</span><span>${stateCell(j.state)}</span>
<span class="muted nowrap num">${escapeHtml(formatDateTime(j.created))}</span>
<a class="btn small" href="#/jobs?job=${attr(j.id)}" data-i18n="Admin.Schedules.OpenJob" data-i18n-title="Admin.Schedules.OpenJob.Tip"></a></div>`).join("")}
${page.cursor ? `<button class="btn small more" data-more-runs="${attr(s.id)}" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button>` : ""}</div>`;
}
async function toggle(id) {
if (expanded.delete(id)) {
draw();
return;
}
expanded.add(id);
try {
await loadRuns(id);
} catch (err) {
toast(errorText(err), true);
}
draw();
}
async function moreRuns(id) {
try {
await loadRuns(id, true);
} catch (err) {
toast(errorText(err), true);
return;
}
draw();
}
async function act(action, schedule) {
if (!schedule) return;
try {
if (action === "edit") return openForm(schedule);
if (action === "run") {
const run = await api.post(`/api/v1/schedules/${schedule.id}/run`);
toast(outcomeTip(run.outcome), String(run.outcome).startsWith("failed:"));
runs.delete(schedule.id);
} else if (action === "delete") {
const confirmed = await confirmDialog({
title: t("Admin.Schedules.DeleteTitle", scheduleName(schedule)),
confirm: t("Admin.Schedules.Delete"),
confirmTip: t("Admin.Schedules.Delete.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed) return;
await api.del(`/api/v1/schedules/${schedule.id}`);
expanded.delete(schedule.id);
} else if (action === "reset") {
const confirmed = await confirmDialog({
title: t("Admin.Schedules.ResetTitle", scheduleName(schedule)),
confirm: t("Admin.Schedules.Reset"),
confirmTip: t("Admin.Schedules.Reset.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed) return;
await api.post(`/api/v1/schedules/${schedule.id}/reset`);
}
await load();
} catch (err) {
toast(errorText(err), true);
}
}
async function setEnabled(schedule, box) {
try {
await api.put(`/api/v1/schedules/${schedule.id}`, { enabled: box.checked });
await load();
} catch (err) {
box.checked = !box.checked;
toast(errorText(err), true);
}
}
/** Shows the side panel, remembering which control opened it so closing returns the keyboard there. */
function openSide(html) {
if (side.hidden) {
const scope = actions.contains(document.activeElement) ? actions : root;
opener = { scope, place: focusPlace(scope) };
}
side.hidden = false;
side.innerHTML = html;
applyStrings(side);
fitColumns(table);
side.querySelector("#close").addEventListener("click", closeSide);
}
function closeSide() {
side.hidden = true;
side.innerHTML = "";
fitColumns(table);
if (opener) restoreFocus(opener.scope, opener.place);
opener = null;
}
function openForm(schedule) {
const editing = schedule !== null;
const system = editing && Boolean(schedule.systemKey);
const first = available.find((a) => a.available)?.name ?? "scan";
const draft = { recurrence: { every: 1, unit: "hours", time: "03:00", days: ["mon"], dayOfMonth: 1, ...(schedule?.recurrence ?? { kind: "daily" }) } };
const fixed = `disabled title="${attr(t("Admin.Schedules.Fixed.Tip"))}"`;
const actionOptions = (editing && !available.some((a) => a.name === schedule.action) ? [{ name: schedule.action, available: false }] : available).map((a) =>
`<option value="${attr(a.name)}" ${a.name === (schedule?.action ?? first) ? "selected" : ""} ${a.available || a.name === schedule?.action ? "" : "disabled"}
title="${attr(a.available ? actionTip(a.name) : reasonTip(a.reason))}">${escapeHtml(actionLabel(a.name))}</option>`).join("");
openSide(`
<form class="form" novalidate>
<h2 data-i18n="${editing ? "Admin.Schedules.EditTitle" : "Admin.Schedules.New"}"></h2>
<label><span data-i18n="Admin.Schedules.Name"></span>
<input class="input" name="name" required maxlength="100" autocomplete="off" dir="auto" value="${attr(editing ? scheduleName(schedule) : "")}" ${system ? fixed : `data-i18n-title="Admin.Schedules.Name.Tip"`}></label>
<label><span data-i18n="Admin.Schedules.Action"></span>
<select class="input" name="action" ${system ? fixed : `data-i18n-title="Admin.Schedules.Action.Tip"`}>${actionOptions}</select></label>
<label><span data-i18n="Admin.Schedules.Repeat"></span>
<select class="input" name="kind" data-i18n-title="Admin.Schedules.Repeat.Tip">${KINDS.map((k) =>
`<option value="${k}" ${k === draft.recurrence.kind ? "selected" : ""}>${escapeHtml(t(`Admin.Schedules.Kind.${cap(k)}`))}</option>`).join("")}</select></label>
<div class="form-group" id="recurrence"></div>
<div class="form-group" id="parameters"></div>
<label><span data-i18n="Admin.Schedules.Priority"></span>
<select class="input" name="priority" data-i18n-title="Admin.Schedules.Priority.Tip">${PRIORITIES.map((p) =>
`<option value="${p}" ${p === (schedule?.priority ?? "background") ? "selected" : ""}>${escapeHtml(t(`Admin.Jobs.Priority.${cap(p)}`))}</option>`).join("")}</select></label>
<label class="check"><input type="checkbox" name="catchUp" ${schedule?.catchUp ?? true ? "checked" : ""} data-i18n-title="Admin.Schedules.CatchUp.Tip"><span data-i18n="Admin.Schedules.CatchUp"></span></label>
<label class="check"><input type="checkbox" name="enabled" ${schedule?.enabled ?? true ? "checked" : ""} data-i18n-title="Admin.Schedules.Enabled.Tip"><span data-i18n="Admin.Schedules.Enabled"></span></label>
<div class="buttons">
<button class="btn" type="button" id="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Common.Cancel.Tip"></button>
<button class="btn primary" type="submit" data-i18n="${editing ? "Admin.Common.Save" : "Admin.Schedules.Create"}" data-i18n-title="${editing ? "Admin.Common.Save.Tip" : "Admin.Schedules.Create.Tip"}"></button>
</div>
</form>`);
const form = side.querySelector("form");
const values = (action) => action === schedule?.action ? schedule.parameters : (DEFAULTS[action] ?? {});
drawRecurrence(form, draft.recurrence);
drawParameters(form, schedule?.action ?? first, values(schedule?.action ?? first), schedule?.systemKey);
form.elements.kind.addEventListener("change", () => {
// The fields drawn are still those of the kind chosen before.
draft.recurrence = { ...draft.recurrence, ...shownFields(form, draft.recurrence.kind), kind: form.elements.kind.value };
drawRecurrence(form, draft.recurrence);
});
form.elements.action.addEventListener("change", () => drawParameters(form, form.elements.action.value, values(form.elements.action.value), schedule?.systemKey));
form.addEventListener("submit", async (e) => {
e.preventDefault();
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const action = form.elements.action.value;
const body = {
recurrence: recurrenceOf(form),
parameters: parametersOf(form, action),
priority: form.elements.priority.value,
catchUp: form.elements.catchUp.checked,
enabled: form.elements.enabled.checked,
};
if (!system) Object.assign(body, { name: form.elements.name.value.trim(), action });
try {
if (editing) await api.put(`/api/v1/schedules/${schedule.id}`, body);
else await api.post("/api/v1/schedules", body);
closeSide();
toast(t("Admin.Common.Saved"));
await load();
} catch (err) {
fieldError(form, err);
}
});
(form.querySelector("input:not([disabled]), select:not([disabled])"))?.focus();
}
/** The fields of the recurrence's kind, filled from <paramref name="r"/> (values of the other kinds are kept for a switch back). */
function drawRecurrence(form, r) {
const host = form.querySelector("#recurrence");
const time = `<label><span data-i18n="Admin.Schedules.Time"></span>
<input class="input narrow num" type="time" name="time" required value="${attr(r.time ?? "03:00")}" title="${attr(t("Admin.Schedules.Time.Tip", zone))}"></label>`;
switch (r.kind) {
case "every":
host.innerHTML = `<label><span data-i18n="Admin.Schedules.Interval"></span><span class="inline">
<input class="input narrow num" type="number" name="every" min="1" value="${attr(r.every ?? 1)}" data-i18n-title="Admin.Schedules.Interval.Tip">
<select class="input narrow" name="unit" data-i18n-title="Admin.Schedules.Unit.Tip">${UNITS.map((u) =>
`<option value="${u}" ${u === r.unit ? "selected" : ""}>${escapeHtml(t(`Admin.Schedules.Unit.${cap(u)}`))}</option>`).join("")}</select></span></label>`;
break;
case "weekly":
host.innerHTML = `<fieldset><legend data-i18n="Admin.Schedules.Days"></legend><div class="days">${DAYS.map((d) => `<label class="check">
<input type="checkbox" name="day-${d}" ${(r.days ?? []).includes(d) ? "checked" : ""} title="${attr(t("Admin.Schedules.Day.Tip", dayName(d, "long")))}"><span>${escapeHtml(dayName(d))}</span></label>`).join("")}</div></fieldset>${time}`;
break;
case "monthly":
host.innerHTML = `<label><span data-i18n="Admin.Schedules.DayOfMonth"></span>
<input class="input narrow num" type="number" name="dayOfMonth" min="1" max="28" value="${attr(r.dayOfMonth ?? 1)}" data-i18n-title="Admin.Schedules.DayOfMonth.Tip"></label>${time}`;
break;
default:
host.innerHTML = time;
}
applyStrings(host);
}
/** The parameters <paramref name="action"/> reads, filled from <paramref name="p"/>. */
function drawParameters(form, action, p, systemKey) {
const host = form.querySelector("#parameters");
const lockedAge = LOCKED_AGES[systemKey];
const ageLocked = lockedAge && locked.some((l) => l.toLowerCase() === lockedAge[0].toLowerCase());
host.innerHTML = (PARAMETERS[action] ?? []).map((name) => {
const key = `Admin.Schedules.Param.${PARAM_KEYS[`${action}.${name}`]}`;
if (name === "steps") {
return `<fieldset><legend data-i18n="${key}"></legend>${steps.map((step) => `<label class="check">
<input type="checkbox" name="step-${attr(step)}" value="${attr(step)}" ${(p.steps ?? []).includes(step) ? "checked" : ""} title="${attr(stepTip(step))}"><span>${escapeHtml(stepLabel(step))}</span></label>`).join("")}</fieldset>`;
}
if (name in NUMBERS) {
const lock = name === "olderThanDays" && ageLocked ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", lockedAge[1]))}"` : `data-i18n-title="${key}.Tip"`;
return `<label><span data-i18n="${key}"></span><input class="input narrow num" type="number" name="${name}" ${NUMBERS[name]} value="${attr(p[name] ?? 0)}" ${lock}></label>`;
}
return `<label class="check"><input type="checkbox" name="${name}" ${p[name] ? "checked" : ""} data-i18n-title="${key}.Tip"><span data-i18n="${key}"></span></label>`;
}).join("");
applyStrings(host);
}
/** An API failure on the side form: the field it concerns gets the error border, the message and the focus; a toast announces it. */
function fieldError(form, err) {
const field = fieldOf(form, err.code === "setting_locked" ? "parameters.olderThanDays" : err.code === "invalid_schedule" ? err.details : null);
const message = field && err.code === "invalid_schedule" ? invalidText(field) : errorText(err);
if (field) {
markInvalid(field, message);
field.focus();
}
toast(message, true);
}
setMeta("");
onEvent((e) => {
// A schedule's run queues jobs; their states change the Last result column.
if (e.type === "jobState") {
clearTimeout(timer);
timer = setTimeout(load, 800);
}
});
await load();
}
/** The recurrence the form describes (RecurrenceDto). */
function recurrenceOf(form) {
const kind = form.elements.kind.value;
return { kind, ...shownFields(form, kind) };
}
/** The values of the recurrence fields the form shows for <paramref name="kind"/>. */
function shownFields(form, kind) {
const el = form.elements;
switch (kind) {
case "every": return { every: Number(el.every.value), unit: el.unit.value };
case "weekly": return { time: el.time.value, days: DAYS.filter((d) => el[`day-${d}`].checked) };
case "monthly": return { time: el.time.value, dayOfMonth: Number(el.dayOfMonth.value) };
default: return { time: el.time.value };
}
}
/** The parameters of <paramref name="action"/> the form holds (disabled fields included: an age limit an environment variable fixes). */
function parametersOf(form, action) {
const parameters = {};
for (const name of PARAMETERS[action] ?? []) {
if (name === "steps") parameters.steps = [...form.querySelectorAll('input[name^="step-"]')].filter((b) => b.checked).map((b) => b.value);
else if (name in NUMBERS) parameters[name] = Number(form.elements[name].value);
else parameters[name] = form.elements[name].checked;
}
return parameters;
}
/** The form field an invalid API field (<c>recurrence</c>, <c>parameters.percent</c>…) belongs to. */
function fieldOf(form, apiField) {
if (!apiField) return null;
const el = form.elements;
if (apiField === "recurrence") {
const kind = el.kind.value;
if (kind === "every") return el.every;
if (kind === "weekly" && !DAYS.some((d) => el[`day-${d}`].checked)) return el["day-mon"];
if (kind === "monthly" && !(Number(el.dayOfMonth.value) >= 1 && Number(el.dayOfMonth.value) <= 28)) return el.dayOfMonth;
return el.time;
}
if (apiField === "parameters.steps") return form.querySelector('input[name^="step-"]');
const name = apiField.startsWith("parameters.") ? apiField.slice("parameters.".length) : apiField;
return el[name] ?? null;
}
function actionTip(action) {
const key = `Admin.Schedules.Action.${pascal(action)}.Tip`;
return has(key) ? t(key) : action;
}
/** Why the server cannot run an action (ScheduleUnavailable codes; unknown codes read "not available here"). */
function reasonTip(reason) {
const key = `Admin.Schedules.Reason.${pascal(reason ?? "")}.Tip`;
return has(key) ? t(key) : t("Admin.Schedules.Reason.Unknown.Tip");
}
function stepLabel(step) {
const key = `Admin.Schedules.Step.${pascal(step)}`;
return has(key) ? t(key) : step;
}
function stepTip(step) {
const key = `Admin.Schedules.Step.${pascal(step)}.Tip`;
return has(key) ? t(key) : step;
}
/** An instant in the server's time zone (schedule times are its wall-clock times); in the browser's when the zone is unknown here. */
function zonedTime(iso, zone) {
if (!iso) return "—";
const options = { dateStyle: "short", timeStyle: "short" };
try {
return new Intl.DateTimeFormat(culture(), { ...options, timeZone: zone }).format(new Date(iso));
} catch {
return new Intl.DateTimeFormat(culture(), options).format(new Date(iso));
}
}
/** "03:00" as the panel's language writes a time of day. */
function timeText(hhmm) {
const [h, m] = String(hhmm ?? "").split(":").map(Number);
if (!Number.isFinite(h) || !Number.isFinite(m)) return String(hhmm ?? "");
return new Intl.DateTimeFormat(culture(), { timeStyle: "short", timeZone: "UTC" }).format(Date.UTC(2001, 0, 1, h, m));
}
function dayName(day, style = "short") {
return new Intl.DateTimeFormat(culture(), { weekday: style, timeZone: "UTC" }).format(Date.UTC(2001, 0, 1 + DAYS.indexOf(day)));
}
function dayList(days) {
const names = DAYS.filter((d) => days.includes(d)).map((d) => dayName(d));
try {
return new Intl.ListFormat(culture(), { style: "short", type: "conjunction" }).format(names);
} catch {
return names.join(", ");
}
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}