// 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, its next // run, its last result (every time in the server's time zone) 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, 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"]; /** The unit letters of an interval's server code (every:10m). */ const UNIT_CODES = { m: "minutes", h: "hours", d: "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): the setting, * its variable and the steps the limit deletes with (ServerScheduleHost.AgedSteps). */ const LOCKED_AGES = { "audit-cleanup": { setting: "AuditRetentionDays", variable: "CHRONOS_AUDIT_RETENTION_DAYS", steps: ["audit"] } }; /** 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: 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 ?? ""; } } /** * The recurrence a server code describes (ScheduleRecurrence.Format: every:10m, daily:03:00, weekly:mon,thu@02:30, * monthly:1@04:00), in the API's shape for recurrenceText; null for anything else. */ export function parseRecurrence(code) { const match = /^(every|daily|weekly|monthly):(.+)$/.exec(String(code ?? "")); if (!match) return null; const [, kind, rest] = match; const isTime = (s) => /^\d{2}:\d{2}$/.test(s ?? ""); if (kind === "every") { const every = /^(\d+)([mhd])$/.exec(rest); return every ? { kind, every: Number(every[1]), unit: UNIT_CODES[every[2]] } : null; } if (kind === "daily") return isTime(rest) ? { kind, time: rest } : null; const [what, time] = rest.split("@"); if (!isTime(time)) return null; if (kind === "weekly") { const days = what.split(","); return days.every((d) => DAYS.includes(d)) ? { kind, days, time } : null; } return /^\d+$/.test(what) ? { kind, dayOfMonth: Number(what), time } : null; } 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 = ``; applyStrings(actions); actions.querySelector("#new").addEventListener("click", () => openForm(null)); root.innerHTML = `
`; 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 ?? []; // A schedule deleted meanwhile (here or by another administrator), or the one a job of the Queue tab links to after // its deletion, is simply not shown: its runs are not asked for. for (const id of expanded) { if (!find(id)) forget(id); } if (focusSchedule && !find(focusSchedule)) focusSchedule = null; // 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])); // One schedule's runs that cannot be read (deleted since the list) close it; the table is drawn all the same. await Promise.all([...expanded].map((id) => loadRuns(id).catch(() => forget(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("") || `
${emptyState("Admin.Schedules.Empty", ``)}
`; 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); } /** * What an environment variable fixes on the system schedule whose age limit is * (LOCKED_AGES), with the attributes of its fixed controls; null when nothing is fixed. While the * limit deletes (more than 0 days) its switch and the steps it deletes with are fixed too (ScheduleEndpoints.ChangesLocked). */ function ageLock(systemKey, days) { const age = LOCKED_AGES[systemKey]; if (!age || !locked.some((l) => l.toLowerCase() === age.setting.toLowerCase())) return null; return { ...age, deletes: days > 0, attrs: `disabled title="${attr(t("Admin.Settings.Locked.Tip", age.variable))}"` }; } /** Closes a schedule's runs and drops them. */ function forget(id) { expanded.delete(id); runs.delete(id); } function rowHtml(s) { const name = scheduleName(s); const button = (act, key, extra = "") => ``; const buttons = button("run", "Run") + button("edit", "Edit") + (s.systemKey ? button("reset", "Reset") : button("delete", "Delete", " destructive")); const when = recurrenceText(s.recurrence); const lock = ageLock(s.systemKey, s.parameters?.olderThanDays ?? 0); return `
${s.systemKey ? `` : ""} ${escapeHtml(actionLabel(s.action))} ${escapeHtml(when)} ${escapeHtml(s.enabled ? zonedTime(s.nextRun, zone) : t("Admin.Schedules.Off"))} ${lastResult(s)} ${buttons}
${expanded.has(s.id) ? `
${runsHtml(s)}
` : ""}`; } /** 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 ``; const when = ` · ${escapeHtml(zonedShort(s.lastRun, zone))}`; const tip = `${outcomeTip(s.lastOutcome)} · ${zonedDateTime(s.lastRun, zone)}`; const job = s.lastOutcome === "queued" ? lastJobs.get(s.lastJobId) : null; if (job) return `${stateCell(job.state)}${when}`; const failed = String(s.lastOutcome).startsWith("failed:"); return `${escapeHtml(outcomeLabel(s.lastOutcome))}${when}`; } function runsHtml(s) { const page = runs.get(s.id); if (!page) return ""; if (page.items.length === 0) { return emptyState("Admin.Schedules.NoRuns", ``); } return `
${page.items.map((j) => `
${escapeHtml(kindLabel(j.kind))}${stateCell(j.state)} ${escapeHtml(zonedDateTime(j.created, zone))}
`).join("")} ${page.cursor ? `` : ""}
`; } async function toggle(id) { if (expanded.delete(id)) { draw(); return; } expanded.add(id); try { await loadRuns(id); } catch (err) { forget(id); 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}`); forget(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 lock = editing ? ageLock(schedule.systemKey, schedule.parameters?.olderThanDays ?? 0) : null; const actionOptions = (editing && !available.some((a) => a.name === schedule.action) ? [{ name: schedule.action, available: false }] : available).map((a) => ``).join(""); openSide(`

`); 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, schedule); } }); (form.querySelector("input:not([disabled]), select:not([disabled])"))?.focus(); } /** The fields of the recurrence's kind, filled from (values of the other kinds are kept for a switch back). */ function drawRecurrence(form, r) { const host = form.querySelector("#recurrence"); const time = ``; switch (r.kind) { case "every": host.innerHTML = ``; break; case "weekly": host.innerHTML = `
${DAYS.map((d) => ``).join("")}
${time}`; break; case "monthly": host.innerHTML = `${time}`; break; default: host.innerHTML = time; } applyStrings(host); } /** The parameters reads, filled from . */ function drawParameters(form, action, p, systemKey) { const host = form.querySelector("#parameters"); const lock = ageLock(systemKey, p.olderThanDays ?? 0); host.innerHTML = (PARAMETERS[action] ?? []).map((name) => { const key = `Admin.Schedules.Param.${PARAM_KEYS[`${action}.${name}`]}`; if (name === "steps") { const tip = (step) => lock?.deletes && lock.steps.includes(step) ? lock.attrs : `title="${attr(stepTip(step))}"`; return `
${steps.map((step) => ``).join("")}
`; } if (name in NUMBERS) { const fixed = name === "olderThanDays" && lock ? lock.attrs : `data-i18n-title="${key}.Tip"`; return ``; } return ``; }).join(""); applyStrings(host); } /** * An API failure on the side form of (null for a new one): the field it concerns gets the error * border, the message and the focus; a toast announces it. */ function fieldError(form, err, schedule) { const field = err.code === "setting_locked" ? lockedField(form, schedule) : fieldOf(form, 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 changed or ran (also a run that queued nothing, or an edit by another administrator), or a job it queued // changed state (the Last result column); the burst of one pass is read once. if (e.type === "jobState" || e.type === "scheduleChanged") { 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 . */ 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 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 (recurrence, parameters.percent…) 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; } /** * The form field a setting_locked refusal concerns, in the server's order (ScheduleEndpoints.ChangesLocked): the * switch turned off while the limit deletes, the age limit changed, a step the limit deletes with unticked; else the age limit. */ function lockedField(form, schedule) { const el = form.elements; const days = schedule?.parameters?.olderThanDays ?? 0; if (days > 0 && !el.enabled.checked) return el.enabled; if (el.olderThanDays && Number(el.olderThanDays.value) !== days) return el.olderThanDays; const step = days > 0 ? (LOCKED_AGES[schedule?.systemKey]?.steps ?? []).map((s) => el[`step-${s}`]).find((box) => box && !box.checked) : null; return step ?? el.olderThanDays ?? 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, as every time of this tab is ("Times in …": schedule times are its wall-clock * times); in the browser's when the zone is unknown here. */ function zoned(iso, zone, options) { const date = new Date(iso); try { return new Intl.DateTimeFormat(culture(), { ...options, timeZone: zone }).format(date); } catch { return new Intl.DateTimeFormat(culture(), options).format(date); } } function zonedTime(iso, zone) { return iso ? zoned(iso, zone, { dateStyle: "short", timeStyle: "short" }) : "—"; } function zonedDateTime(iso, zone) { return iso ? zoned(iso, zone, { dateStyle: "short", timeStyle: "medium" }) : "—"; } /** Like formatTime in the server's time zone: the time when the instant falls on today there, else the date. */ function zonedShort(iso, zone) { if (!iso) return "—"; const day = (instant) => zoned(instant, zone, { dateStyle: "short" }); return zoned(iso, zone, day(iso) === day(Date.now()) ? { timeStyle: "short" } : { dateStyle: "medium" }); } /** "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); }