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:
1 parent
e5508e7e69
commit
75daab7275
66 files changed
+1985
-290
No files matched your search
@@ -216,6 +216,34 @@ public sealed class JobRepository
|
||||
_db.ListAsync($"SELECT {Columns} FROM jobs WHERE schedule_id = $1 ORDER BY created DESC, id DESC LIMIT $2",
|
||||
[scheduleId, Cursor.ClampLimit(limit)], Map, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The jobs the schedule <paramref name="scheduleId"/> queued, newest first, a page at a time (the runs a schedule's
|
||||
/// row lists in the admin panel); <paramref name="cursor"/> continues after the previous page.
|
||||
/// </summary>
|
||||
public Task<Page<Job>> PageByScheduleAsync(Guid scheduleId, int limit = 20, string? cursor = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var p = new SqlParameters();
|
||||
var where = $"schedule_id = {p.Add(scheduleId)}";
|
||||
if (cursor is not null)
|
||||
{
|
||||
var (value, id) = Cursor.Decode("schedule-runs", cursor);
|
||||
where += " AND " + Cursor.After("created", "id", descending: true, value, id, p.Add);
|
||||
}
|
||||
var take = Cursor.ClampLimit(limit);
|
||||
var sql = $"SELECT {Columns} FROM jobs WHERE {where} ORDER BY created DESC, id DESC LIMIT {p.Add(take + 1)}";
|
||||
return _db.RunAsync(async session =>
|
||||
{
|
||||
var jobs = await session.QueryListAsync(sql, p.ToArray(), Map, cancellationToken).ConfigureAwait(false);
|
||||
string? next = null;
|
||||
if (jobs.Count > take)
|
||||
{
|
||||
jobs.RemoveAt(take);
|
||||
next = Cursor.Encode("schedule-runs", jobs[^1].Created, jobs[^1].Id);
|
||||
}
|
||||
return new Page<Job>(jobs, next);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Claims one specific queued job for <paramref name="nodeId"/> (render nodes pick by capability); null when another
|
||||
/// claimer was faster or the job is no longer queued.
|
||||
|
||||
@@ -3,8 +3,9 @@ namespace Chronos.Protocol;
|
||||
/// <summary>
|
||||
/// <c>GET/PUT /api/v1/server/settings</c> (admin): the editable part of the server configuration. Settings named in
|
||||
/// <see cref="Locked"/> come from environment variables and cannot be changed here; <see cref="RestartRequired"/> says
|
||||
/// that saved values (ports, TLS, chunk size, job history) wait for a restart. <see cref="ProxyWarning"/> is set in
|
||||
/// responses when TLS mode is proxy and the request did not come through a trusted proxy over HTTPS (ignored when saving).
|
||||
/// that saved values (ports, TLS, chunk size) wait for a restart; <see cref="JobHistoryDays"/> is what the housekeeping
|
||||
/// schedule is reset to (owner review 2, R10). <see cref="ProxyWarning"/> is set in responses when TLS mode is proxy and
|
||||
/// the request did not come through a trusted proxy over HTTPS (ignored when saving).
|
||||
/// <see cref="Parallelism"/> is how many photos the running job processes at once (jobs run one at a time), and
|
||||
/// <see cref="PriorityQueue"/> with <see cref="JobPriorities"/> the priority queue (owner review 1); both apply at once, as
|
||||
/// do <see cref="Logs"/> (owner review 2, R11; a request without them keeps them as they are).
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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&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)),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/schedules</c> (owner review 2, R10; ManageArchive): the server's scheduled jobs, its system schedules
|
||||
/// included, with the actions it can run and its time zone; create, edit (<c>PUT</c> or <c>PATCH</c>, the fields given),
|
||||
/// delete (409 <c>schedule_system</c> for a system schedule), run now (409 <c>schedule_pending</c> while its last job is
|
||||
/// queued, running or paused), reset a system schedule (409 <c>schedule_no_defaults</c> otherwise) and the jobs a schedule
|
||||
/// queued, newest first. An invalid field is 400 <c>invalid_schedule</c> with its name as details (<c>name</c>,
|
||||
/// <c>recurrence</c>, <c>parameters.percent</c>…); an age limit an environment variable fixes is 409 <c>setting_locked</c>.
|
||||
/// Every change is audited.
|
||||
/// </summary>
|
||||
public static class ScheduleEndpoints
|
||||
{
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var schedules = api.MapGroup("/schedules").Requires(Permissions.ManageArchive);
|
||||
schedules.MapGet("", async (HttpContext context, SchedulerHost host) =>
|
||||
Results.Json(await host.Scheduler.ListAsync(context.RequestAborted), ProtocolJson.Default.SchedulesDto));
|
||||
schedules.MapPost("", CreateAsync);
|
||||
schedules.MapGet("/{id:guid}", async (HttpContext context, Guid id, SchedulerHost host) =>
|
||||
await host.Scheduler.GetAsync(id, context.RequestAborted) is { } schedule
|
||||
? Results.Json(schedule, ProtocolJson.Default.ScheduleDto)
|
||||
: ApiErrors.NotFound(context, "schedule"));
|
||||
schedules.MapPut("/{id:guid}", UpdateAsync);
|
||||
schedules.MapPatch("/{id:guid}", UpdateAsync);
|
||||
schedules.MapDelete("/{id:guid}", DeleteAsync);
|
||||
schedules.MapPost("/{id:guid}/run", RunAsync);
|
||||
schedules.MapPost("/{id:guid}/reset", ResetAsync);
|
||||
schedules.MapGet("/{id:guid}/runs", RunsAsync);
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateScheduleRequest request, SchedulerHost host, AuditLog audit)
|
||||
{
|
||||
var result = await host.Scheduler.CreateAsync(request, caller.Id, context.RequestAborted);
|
||||
if (result.Problem is { } problem) return ApiErrors.BadRequest(context, "invalid_schedule", problem, problem);
|
||||
var schedule = result.Schedule!;
|
||||
await audit.WriteAsync(caller, context, "schedule_created", "schedule", schedule.Id.ToString(), Describe(schedule));
|
||||
return Results.Json(schedule, ProtocolJson.Default.ScheduleDto, statusCode: StatusCodes.Status201Created);
|
||||
}
|
||||
|
||||
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateScheduleRequest request, SchedulerHost host, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await host.Scheduler.GetAsync(id, ct) is not { } current) return ApiErrors.NotFound(context, "schedule");
|
||||
// Parameters are replaced as a whole: a missing age limit would fall back to the action's default.
|
||||
if (host.Host.LockedAgeOf(current.SystemKey) is { } locked && request.Parameters is { } parameters
|
||||
&& ScheduleActions.Normalize(current.Action, parameters).OlderThanDays != locked.Days)
|
||||
return ApiErrors.Conflict(context, "setting_locked", locked.Setting);
|
||||
var result = await host.Scheduler.UpdateAsync(id, request, ct);
|
||||
if (result.NotFound) return ApiErrors.NotFound(context, "schedule");
|
||||
if (result.Problem is { } problem) return ApiErrors.BadRequest(context, "invalid_schedule", problem, problem);
|
||||
var schedule = result.Schedule!;
|
||||
await audit.WriteAsync(caller, context, "schedule_updated", "schedule", id.ToString(), Describe(schedule));
|
||||
return Results.Json(schedule, ProtocolJson.Default.ScheduleDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, SchedulerHost host, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
var current = await host.Scheduler.GetAsync(id, ct);
|
||||
switch (await host.Scheduler.DeleteAsync(id, ct))
|
||||
{
|
||||
case ScheduleDeleteOutcome.System:
|
||||
return ApiErrors.Conflict(context, "schedule_system");
|
||||
case ScheduleDeleteOutcome.NotFound:
|
||||
return ApiErrors.NotFound(context, "schedule");
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "schedule_deleted", "schedule", id.ToString(), current is null ? null : Describe(current));
|
||||
return Results.NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Runs the schedule now, as its next run would (also a disabled one), unless its last job has not ended.</summary>
|
||||
private static async Task<IResult> RunAsync(HttpContext context, Caller caller, Guid id, SchedulerHost host, ChronosDatabase db, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await host.Scheduler.GetAsync(id, ct) is not { } schedule) return ApiErrors.NotFound(context, "schedule");
|
||||
if (schedule.LastJobId is { } last && await db.Jobs.GetAsync(last, ct) is { State: JobState.Queued or JobState.Running or JobState.Paused })
|
||||
return ApiErrors.Conflict(context, "schedule_pending", last.ToString());
|
||||
if (await host.Scheduler.RunNowAsync(id, caller.Id, ct) is not { } run) return ApiErrors.NotFound(context, "schedule");
|
||||
await audit.WriteAsync(caller, context, "schedule_run", "schedule", id.ToString(), $"{run.Schedule.Name} · {run.Outcome}");
|
||||
return Results.Json(run, ProtocolJson.Default.ScheduleRunDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> ResetAsync(HttpContext context, Caller caller, Guid id, SchedulerHost host, AuditLog audit)
|
||||
{
|
||||
var result = await host.Scheduler.ResetAsync(id, context.RequestAborted);
|
||||
if (result.NotFound) return ApiErrors.NotFound(context, "schedule");
|
||||
if (result.Problem is not null) return ApiErrors.Conflict(context, "schedule_no_defaults");
|
||||
var schedule = result.Schedule!;
|
||||
await audit.WriteAsync(caller, context, "schedule_reset", "schedule", id.ToString(), Describe(schedule));
|
||||
return Results.Json(schedule, ProtocolJson.Default.ScheduleDto);
|
||||
}
|
||||
|
||||
/// <summary>The jobs the schedule queued, newest first; <c>cursor</c> continues a page.</summary>
|
||||
private static async Task<IResult> RunsAsync(HttpContext context, Guid id, SchedulerHost host, ChronosDatabase db, string? cursor, int? limit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await host.Scheduler.GetAsync(id, ct) is null) return ApiErrors.NotFound(context, "schedule");
|
||||
var page = await db.Jobs.PageByScheduleAsync(id, limit ?? 20, string.IsNullOrEmpty(cursor) ? null : cursor, ct);
|
||||
return Results.Json(new Page<JobDto>([.. page.Items.Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto);
|
||||
}
|
||||
|
||||
/// <summary>The audit details of a schedule: its name, action and recurrence (<c>Archive scan · scan · every:10m</c>), and "off" while disabled.</summary>
|
||||
private static string Describe(ScheduleDto schedule)
|
||||
{
|
||||
var recurrence = ScheduleMapping.FromDto(schedule.Recurrence)?.Format() ?? schedule.Recurrence.Kind;
|
||||
return $"{schedule.Name} · {schedule.Action} · {recurrence}{(schedule.Enabled ? string.Empty : " · off")}";
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Server.Hosting;
|
||||
using LogFileOptions = Chronos.Core.Diagnostics.LogFileOptions;
|
||||
using LogRotation = Chronos.Core.Diagnostics.LogRotation;
|
||||
@@ -75,7 +76,7 @@ public sealed class ServerOptions
|
||||
("CHRONOS_LOG_MAX_FILE_MB", nameof(LogMaxFileMb), (o, v) => o.LogMaxFileMb = Int("CHRONOS_LOG_MAX_FILE_MB", v)),
|
||||
("CHRONOS_LOG_MAX_TOTAL_MB", nameof(LogMaxTotalMb), (o, v) => o.LogMaxTotalMb = Int("CHRONOS_LOG_MAX_TOTAL_MB", v)),
|
||||
("CHRONOS_LOG_ROTATION", nameof(LogRotation), (o, v) => o.LogRotation = ServerLogging.ParseRotation("CHRONOS_LOG_ROTATION", v)),
|
||||
("CHRONOS_AUDIT_RETENTION_DAYS", nameof(AuditRetentionDays), (o, v) => o.AuditRetentionDays = Int("CHRONOS_AUDIT_RETENTION_DAYS", v)),
|
||||
(AuditRetentionVariable, nameof(AuditRetentionDays), (o, v) => o.AuditRetentionDays = Int(AuditRetentionVariable, v)),
|
||||
("CHRONOS_DIAGNOSTICS_LOG_MB", nameof(DiagnosticsLogMb), (o, v) => o.DiagnosticsLogMb = Int("CHRONOS_DIAGNOSTICS_LOG_MB", v)),
|
||||
];
|
||||
|
||||
@@ -199,14 +200,31 @@ public sealed class ServerOptions
|
||||
/// <summary>One log file per UTC day or per hour.</summary>
|
||||
public LogRotation LogRotation { get; set; } = LogRotation.Daily;
|
||||
|
||||
/// <summary>Days audit entries are kept (the scheduler's housekeeping deletes older ones); 0 = forever.</summary>
|
||||
public int AuditRetentionDays { get; set; }
|
||||
|
||||
/// <summary>MB kept from the end of each log file in the diagnostics zip.</summary>
|
||||
public int DiagnosticsLogMb { get; set; } = (int)(Chronos.Core.Diagnostics.DiagnosticsArchive.DefaultLogTailBytes / LogFileOptions.BytesPerMb);
|
||||
public long MaxUploadBytes { get; set; } = 2L * 1024 * 1024 * 1024;
|
||||
public int ChunkSizeBytes { get; set; } = 8 * 1024 * 1024;
|
||||
|
||||
/// <summary>
|
||||
/// Days of job history the <c>housekeeping</c> system schedule keeps when it is created or reset (owner review 2, R10);
|
||||
/// afterwards the schedule's own value applies (admin panel › Jobs › Scheduled).
|
||||
/// </summary>
|
||||
public int JobHistoryDays { get; set; } = 90;
|
||||
|
||||
/// <summary>The environment variable that fixes <see cref="AuditRetentionDays"/>.</summary>
|
||||
public const string AuditRetentionVariable = "CHRONOS_AUDIT_RETENTION_DAYS";
|
||||
|
||||
/// <summary>Most days <see cref="AuditRetentionDays"/> accepts: the most a schedule's age limit takes (ten years).</summary>
|
||||
public const int MaxAuditRetentionDays = ScheduleActions.MaxDays;
|
||||
|
||||
/// <summary>
|
||||
/// Days of audit log the <c>audit-cleanup</c> system schedule keeps (owner review 2, R10, R11); 0, the default, keeps
|
||||
/// it all. It is that schedule's age limit: saving it in Settings › Logs sets the schedule's parameter, and Reset
|
||||
/// goes back to it. Set by <c>CHRONOS_AUDIT_RETENTION_DAYS</c>, it is applied to the schedule at every start and cannot
|
||||
/// be changed in the panel or on the schedule.
|
||||
/// </summary>
|
||||
public int AuditRetentionDays { get; set; }
|
||||
|
||||
public int TokenLifetimeDays { get; set; } = 30;
|
||||
|
||||
/// <summary>Uploads untouched for this long are abandoned: their partial files are deleted.</summary>
|
||||
@@ -226,7 +244,7 @@ public sealed class ServerOptions
|
||||
/// <summary>Chunk uploads one user may run at the same time; more are answered 429.</summary>
|
||||
public int ConcurrentChunksPerUser { get; set; } = 8;
|
||||
|
||||
/// <summary>Settings fixed by environment variables (names of the properties above).</summary>
|
||||
/// <summary>Settings fixed by environment variables (names of the properties above); tests set it directly.</summary>
|
||||
[JsonIgnore]
|
||||
public IReadOnlyCollection<string> Locked { get; internal set; } = [];
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@ namespace Chronos.Server.Configuration;
|
||||
/// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes <c>/data/server.json</c> (only the
|
||||
/// edited keys; secrets and environment values are never written) and applies what can change while running, the
|
||||
/// parallelism and the priority queue included (owner review 1), and the log settings through <see cref="ServerLogging"/>
|
||||
/// (owner review 2, R11); ports, TLS, chunk size and job history wait for a restart.
|
||||
/// (owner review 2, R11); ports, TLS and chunk size wait for a restart. Job history is what the housekeeping system
|
||||
/// schedule is reset to (owner review 2, R10): the schedule's own value applies.
|
||||
/// </summary>
|
||||
public sealed class ServerSettingsStore(ServerOptions options, ServerLogging logging)
|
||||
{
|
||||
@@ -62,6 +63,7 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
options.MaxUploadBytes = request.MaxUploadBytes;
|
||||
options.TokenLifetimeDays = request.TokenLifetimeDays;
|
||||
options.UploadRetentionHours = request.UploadRetentionHours;
|
||||
options.JobHistoryDays = request.JobHistoryDays;
|
||||
options.Parallelism = request.Parallelism;
|
||||
options.PriorityQueue = request.PriorityQueue;
|
||||
options.JobPriorities = JobPriorityQueue.Changed(Levels(request.JobPriorities));
|
||||
@@ -78,7 +80,7 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
var restart = request.HttpPort != options.HttpPort || request.HttpsPort != options.HttpsPort
|
||||
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||
|| request.TlsCert != options.TlsCert || request.TlsKey != options.TlsKey
|
||||
|| request.ChunkSizeBytes != options.ChunkSizeBytes || request.JobHistoryDays != options.JobHistoryDays;
|
||||
|| request.ChunkSizeBytes != options.ChunkSizeBytes;
|
||||
_saved = request with
|
||||
{
|
||||
ServerName = request.ServerName.Trim(),
|
||||
|
||||
@@ -49,7 +49,7 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
CHRONOS_LOG_MAX_FILE_MB size at which a log file continues in a numbered one (default 50; 0: no limit)
|
||||
CHRONOS_LOG_MAX_TOTAL_MB size of all log files; beyond it the oldest are deleted (default 1024; 0: no limit)
|
||||
CHRONOS_LOG_ROTATION a new log file every day or every hour, UTC (daily | hourly; default daily)
|
||||
CHRONOS_AUDIT_RETENTION_DAYS days audit entries are kept (default 0: forever)
|
||||
CHRONOS_AUDIT_RETENTION_DAYS days of audit log the audit-cleanup schedule keeps (default 0: forever)
|
||||
CHRONOS_DIAGNOSTICS_LOG_MB MB from the end of each log file in the diagnostics zip (default 4)
|
||||
CHRONOS_DISCOVERY LAN beacon (true | false); in a container it needs host networking
|
||||
CHRONOS_PUBLIC_HTTP_PORT, CHRONOS_PUBLIC_HTTPS_PORT
|
||||
@@ -58,7 +58,7 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
CHRONOS_TRUSTED_PROXIES proxy mode: addresses or networks (CIDR) whose X-Forwarded-* headers count
|
||||
(default: loopback only; list a proxy in another container or on another machine)
|
||||
|
||||
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (local time zone)
|
||||
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (time zone of the schedules)
|
||||
""";
|
||||
|
||||
public static ServerCommandLine Parse(IReadOnlyList<string> args)
|
||||
|
||||
@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Configuration;
|
||||
@@ -144,10 +145,16 @@ public static class ServerHost
|
||||
services.AddSingleton<RenderNodeService>();
|
||||
services.AddSingleton<JobEngineHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
|
||||
// After the engine's host: the scheduler queues on its engine, starts after it and stops before it (owner review 2, R10).
|
||||
services.AddSingleton<ServerScheduleHost>();
|
||||
services.AddSingleton<SchedulerHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<SchedulerHost>());
|
||||
services.AddSingleton<RenderNodeMonitor>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<RenderNodeMonitor>());
|
||||
// Recovers interrupted commits at start; its sweep is the clean-up step of the upload-cleanup schedule.
|
||||
services.AddSingleton<UploadMaintenance>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>());
|
||||
services.AddSingleton<ICleanupStep, UploadCleanupStep>();
|
||||
services.AddSingleton<DiscoveryBeaconService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>());
|
||||
}
|
||||
@@ -169,6 +176,7 @@ public static class ServerHost
|
||||
FileEndpoints.Map(api);
|
||||
UploadEndpoints.Map(api);
|
||||
JobEndpoints.Map(api);
|
||||
ScheduleEndpoints.Map(api);
|
||||
NodeEndpoints.Map(api);
|
||||
ArchiveEndpoints.Map(api);
|
||||
AdminEndpoints.Map(api);
|
||||
|
||||
@@ -18,12 +18,12 @@ public sealed class ServerLogging
|
||||
public const int MaxRetentionDays = 3650;
|
||||
public const int MaxFileMb = 10 * 1024;
|
||||
public const int MaxTotalMb = 1024 * 1024;
|
||||
public const int MaxAuditRetentionDays = 36500;
|
||||
public const int MaxAuditRetentionDays = ServerOptions.MaxAuditRetentionDays;
|
||||
public const int MaxDiagnosticsLogMb = 1024;
|
||||
|
||||
/// <summary>The ranges <see cref="Problem"/> checks, for the start-up error.</summary>
|
||||
public const string Ranges = "log retention 1 to 3650 days, log file 0 to 10240 MB, logs total 0 to 1048576 MB and not below the log file, "
|
||||
+ "audit retention 0 to 36500 days, diagnostics logs 1 to 1024 MB";
|
||||
+ "audit retention 0 to 3650 days, diagnostics logs 1 to 1024 MB";
|
||||
|
||||
/// <summary>The levels the settings accept, least severe first; their wire names are lower case (<c>information</c>).</summary>
|
||||
public static IReadOnlyList<MsLogLevel> Levels { get; } =
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Server.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Hosts the server's <see cref="Scheduler"/> (owner review 2, R10) on the <see cref="JobEngineHost"/>'s engine with the
|
||||
/// <see cref="ServerScheduleHost"/>: registered after the engine's host, so it starts after it and stops before it. At start
|
||||
/// it seeds the system schedules and settles missed runs (<see cref="Scheduler.StartAsync"/>), applies the age limits that
|
||||
/// environment variables fix (<see cref="ServerScheduleHost.LockedAgeOf"/>), and runs the archive scan once in the
|
||||
/// background, as the former polling did, so the photos of an adopted folder are indexed without waiting for its first
|
||||
/// interval (only while that schedule is enabled).
|
||||
/// </summary>
|
||||
public sealed class SchedulerHost : IHostedService
|
||||
{
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly ILogger<SchedulerHost> _logger;
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private Task _startScan = Task.CompletedTask;
|
||||
private int _stopped;
|
||||
|
||||
public SchedulerHost(ChronosDatabase db, JobEngineHost jobs, ServerScheduleHost host, TimeProvider time, ILogger<SchedulerHost> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(jobs);
|
||||
_db = db;
|
||||
_logger = logger;
|
||||
Host = host;
|
||||
Scheduler = new Scheduler(db, jobs.Engine, new SchedulerOptions { Time = time });
|
||||
}
|
||||
|
||||
public Scheduler Scheduler { get; }
|
||||
|
||||
public ServerScheduleHost Host { get; }
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var started = Scheduler.Options.Time.GetUtcNow();
|
||||
await Scheduler.StartAsync(Host, cancellationToken);
|
||||
await ApplyLockedAgesAsync(cancellationToken);
|
||||
var stopping = _stopping.Token;
|
||||
_startScan = Task.Run(() => ScanAtStartAsync(started, stopping), CancellationToken.None);
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _stopped, 1) == 1) return;
|
||||
await _stopping.CancelAsync();
|
||||
await _startScan;
|
||||
await Scheduler.DisposeAsync();
|
||||
_stopping.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the age limits environment variables fix into their system schedules (also enabling one that has a limit now,
|
||||
/// or disabling it at 0, which keeps everything); a schedule already holding the value is left as the user set it.
|
||||
/// </summary>
|
||||
private async Task ApplyLockedAgesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var system in Host.SystemSchedules)
|
||||
{
|
||||
if (Host.LockedAgeOf(system.SystemKey) is not { } locked) continue;
|
||||
if (await _db.Schedules.GetBySystemKeyAsync(system.SystemKey, cancellationToken) is not { } row) continue;
|
||||
var parameters = ScheduleMapping.Parameters(row);
|
||||
if (parameters.OlderThanDays == locked.Days) continue;
|
||||
var result = await Scheduler.UpdateAsync(row.Id, new UpdateScheduleRequest(Parameters: parameters with { OlderThanDays = locked.Days }, Enabled: locked.Days > 0),
|
||||
cancellationToken);
|
||||
if (result.Problem is { } problem) _logger.LogWarning("{Variable} could not be applied to the {Schedule} schedule ({Problem})", locked.Variable, row.Name, problem);
|
||||
else _logger.LogInformation("{Variable} sets the {Schedule} schedule to {Days} day(s)", locked.Variable, row.Name, locked.Days);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The archive scan's run at start, unless the first pass already fired it or it is disabled.</summary>
|
||||
private async Task ScanAtStartAsync(DateTimeOffset started, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (await _db.Schedules.GetBySystemKeyAsync(ServerScheduleHost.ArchiveScan, cancellationToken) is not { Enabled: true } scan || scan.LastRun >= started) return;
|
||||
await Scheduler.RunNowAsync(scan.Id, null, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "The archive scan at start could not be queued; its schedule queues the next one");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Jobs;
|
||||
|
||||
/// <summary>An age limit an environment variable fixes for a system schedule: the setting it comes from, the variable and the days.</summary>
|
||||
public sealed record LockedAge(string Setting, string Variable, int Days);
|
||||
|
||||
/// <summary>
|
||||
/// What the server tells its <see cref="Scheduler"/> (owner review 2, R10): the container's time zone (TZ), the archive it
|
||||
/// serves with the settings another writer put into archive.json (refreshed at every run, as the former polling did), the
|
||||
/// server's own clean-up steps, and its system schedules, which stand for every timer it ran out of sight before: the
|
||||
/// archive scan every 10 minutes (no catch-up), the uploads sweep every 30 minutes, the nightly copy of an SQLite index,
|
||||
/// the job history and the audit log retentions. They are seeded from <see cref="ServerOptions"/> once (the user's edits
|
||||
/// stay) and reset to the options as they are then.
|
||||
/// </summary>
|
||||
public sealed class ServerScheduleHost : IScheduleHost
|
||||
{
|
||||
public const string ArchiveScan = "archive-scan";
|
||||
public const string UploadCleanup = "upload-cleanup";
|
||||
public const string IndexBackup = "index-backup";
|
||||
public const string Housekeeping = "housekeeping";
|
||||
public const string AuditCleanup = "audit-cleanup";
|
||||
|
||||
/// <summary>Minutes between two archive scans (the desktop's rhythm, as the polling had).</summary>
|
||||
public const int ScanMinutes = 10;
|
||||
|
||||
/// <summary>Minutes between two sweeps of abandoned uploads (as the upload maintenance had).</summary>
|
||||
public const int UploadSweepMinutes = 30;
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly ServerOptions _options;
|
||||
private readonly ServerArchive _archive;
|
||||
private readonly ArchiveService? _archives;
|
||||
private readonly ILogger<ServerScheduleHost> _logger;
|
||||
|
||||
public ServerScheduleHost(ChronosDatabase db, ServerOptions options, ServerArchive archive, IServiceProvider services, ILogger<ServerScheduleHost> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
_db = db;
|
||||
_options = options;
|
||||
_archive = archive;
|
||||
_logger = logger;
|
||||
// Without the archive module (tests with a fake ingest) nothing refreshes archive.json and no clean-up step exists.
|
||||
_archives = services.GetService<ArchiveService>();
|
||||
CleanupSteps = _archives is null ? [] : [.. _archives.CleanupSteps.Select(s => s.Name)];
|
||||
TimeZone = ResolveTimeZone(Environment.GetEnvironmentVariable("TZ"), logger);
|
||||
}
|
||||
|
||||
public TimeZoneInfo TimeZone { get; }
|
||||
|
||||
public IReadOnlyList<string> CleanupSteps { get; }
|
||||
|
||||
/// <summary>Built from the options as they are now, so a reset follows a changed <see cref="ServerOptions.AuditRetentionDays"/>.</summary>
|
||||
public IReadOnlyList<SystemSchedule> SystemSchedules
|
||||
{
|
||||
get
|
||||
{
|
||||
var nightly = (Backup: new TimeOnly(3, 0), History: new TimeOnly(4, 0), Audit: new TimeOnly(4, 30));
|
||||
var list = new List<SystemSchedule>
|
||||
{
|
||||
// A missed scan is not caught up: the next one comes within minutes and SchedulerHost scans once at start.
|
||||
new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes, RecurrenceUnit.Minutes), CatchUp: false),
|
||||
new(UploadCleanup, "Upload clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Interval(UploadSweepMinutes, RecurrenceUnit.Minutes),
|
||||
new ScheduleParametersDto(OlderThanDays: UploadMaintenance.FinishedRetentionDays, Steps: [UploadCleanupStep.StepName])),
|
||||
};
|
||||
// PostgreSQL is backed up with its own tools (BRIEF §6.2): no schedule that could never run.
|
||||
if (DatabaseBackups.Unavailable(_db) is null)
|
||||
{
|
||||
list.Add(new(IndexBackup, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.DailyAt(nightly.Backup),
|
||||
new ScheduleParametersDto(Keep: DatabaseBackups.Keep)));
|
||||
}
|
||||
list.Add(new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.History),
|
||||
new ScheduleParametersDto(OlderThanDays: _options.JobHistoryDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory])));
|
||||
var audit = _options.AuditRetentionDays;
|
||||
list.Add(new(AuditCleanup, "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.Audit),
|
||||
new ScheduleParametersDto(OlderThanDays: audit, Steps: [Chronos.Data.Housekeeping.CleanupSteps.Audit]), Enabled: audit > 0));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The served archive, after taking the settings another writer sharing it (a desktop) put into its archive.json, as
|
||||
/// the former polling did before each scan; while it is offline, or the file cannot be read, as the index has it.
|
||||
/// </summary>
|
||||
public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var current = _archive.Current;
|
||||
if (_archives is null || ArchiveService.GetAvailability(current) == ArchiveAvailability.Offline) return current;
|
||||
try
|
||||
{
|
||||
return await _archive.RefreshAsync(_archives, _db, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "The settings in the archive's archive.json could not be read; schedules use those of the index");
|
||||
return _archive.Current;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The server runs every action it has a handler for; the scheduler finds the rest out itself.</summary>
|
||||
public string? Unavailable(string action) => null;
|
||||
|
||||
/// <summary>
|
||||
/// The age limit of the system schedule <paramref name="systemKey"/> that an environment variable fixes
|
||||
/// (<c>CHRONOS_AUDIT_RETENTION_DAYS</c> for <see cref="AuditCleanup"/>); null when the schedule's own value applies.
|
||||
/// </summary>
|
||||
public LockedAge? LockedAgeOf(string? systemKey) =>
|
||||
systemKey == AuditCleanup && _options.Locked.Contains(nameof(ServerOptions.AuditRetentionDays))
|
||||
? new LockedAge(nameof(ServerOptions.AuditRetentionDays), ServerOptions.AuditRetentionVariable, _options.AuditRetentionDays)
|
||||
: null;
|
||||
|
||||
/// <summary>
|
||||
/// The zone of schedule times: the process's local zone (TZ in a container), by its IANA id where the platform maps it
|
||||
/// (the admin panel formats times with it); UTC, with a warning, when TZ names a zone this system does not know (no
|
||||
/// tzdata in the image).
|
||||
/// </summary>
|
||||
public static TimeZoneInfo ResolveTimeZone(string? tz, ILogger logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
var name = tz?.Trim().TrimStart(':');
|
||||
// TZ may also be a path to a zone file, which the runtime reads itself.
|
||||
if (!string.IsNullOrEmpty(name) && !Path.IsPathRooted(name) && !OperatingSystem.IsWindows() && !TimeZoneInfo.TryFindSystemTimeZoneById(name, out _))
|
||||
{
|
||||
logger.LogWarning("TZ is {Zone}, a time zone this system does not know (is tzdata installed?): schedules run in UTC", name);
|
||||
return TimeZoneInfo.Utc;
|
||||
}
|
||||
var local = TimeZoneInfo.Local;
|
||||
if (!local.HasIanaId && TimeZoneInfo.TryConvertWindowsIdToIanaId(local.Id, out var iana) && TimeZoneInfo.TryFindSystemTimeZoneById(iana, out var zone))
|
||||
return zone;
|
||||
return local;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
@@ -8,10 +9,11 @@ namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and
|
||||
/// thumbnails, its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance) and the periodic
|
||||
/// incremental scan (<see cref="ArchivePolling"/>); a scan queues thumbnails and proxies of what it indexes, as an upload
|
||||
/// does. Decoding is managed only (BRIEF §4.2). The daily backup of an SQLite index runs with it
|
||||
/// (<see cref="DatabaseBackupService"/>).
|
||||
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance, the duplicates and
|
||||
/// orphans reports, index backups and clean-ups with the server's own steps, the <see cref="ICleanupStep"/>s in DI); a scan
|
||||
/// queues thumbnails and proxies of what it indexes, as an upload does. Decoding is managed only (BRIEF §4.2). Recurring
|
||||
/// work (the periodic scan, the nightly backup of an SQLite index, clean-ups) is queued by the server's system schedules
|
||||
/// (<see cref="Jobs.ServerScheduleHost"/>, owner review 2, R10).
|
||||
/// </summary>
|
||||
public static class ArchiveModule
|
||||
{
|
||||
@@ -24,14 +26,19 @@ public static class ArchiveModule
|
||||
{
|
||||
var options = sp.GetRequiredService<ServerOptions>();
|
||||
// Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1).
|
||||
return new ArchiveService(sp.GetRequiredService<ChronosDatabase>(),
|
||||
new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = Owner, ImagesAfterScan = true, Parallelism = () => options.Parallelism });
|
||||
return new ArchiveService(sp.GetRequiredService<ChronosDatabase>(), new ArchiveServiceOptions
|
||||
{
|
||||
Decoder = DecoderFactory.CreateServer(),
|
||||
Owner = Owner,
|
||||
ImagesAfterScan = true,
|
||||
Parallelism = () => options.Parallelism,
|
||||
CleanupSteps = [.. sp.GetServices<ICleanupStep>()],
|
||||
// Next to the index in the data folder, where the daily backups always went.
|
||||
BackupDirectory = Path.Combine(options.DataPath, DatabaseBackups.DirectoryName),
|
||||
});
|
||||
});
|
||||
services.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<ArchiveService>().Ingest);
|
||||
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ArchiveService>());
|
||||
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
|
||||
services.AddHostedService<DatabaseBackupService>();
|
||||
services.AddSingleton<ArchivePolling>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<ArchivePolling>());
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Server.Jobs;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Polls the archive (BRIEF §7: by modification time and size, no file-system watchers): an incremental scan at start
|
||||
/// and every <see cref="Interval"/> while the archive is online, so photos already in an adopted folder and sequences
|
||||
/// another writer adds (a desktop sharing the archive, files copied in by hand) are indexed without an administrator's
|
||||
/// rescan. Settings such a writer changed in archive.json reach the index first, so uploads and the admin panel follow
|
||||
/// them. A scan or rebuild of the archive that is waiting, running or paused is not queued again.
|
||||
/// </summary>
|
||||
public sealed class ArchivePolling(ChronosDatabase db, ServerArchive archive, ArchiveService archives, JobEngineHost jobs, TimeProvider time,
|
||||
ILogger<ArchivePolling> logger)
|
||||
: BackgroundService
|
||||
{
|
||||
/// <summary>The desktop's rhythm (it polls its archive the same way).</summary>
|
||||
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(10);
|
||||
|
||||
private static readonly JobState[] Pending = [JobState.Queued, JobState.Running, JobState.Paused];
|
||||
|
||||
/// <summary>Queues an incremental scan of an online archive unless one is pending; returns it, or null when none was queued.</summary>
|
||||
public async Task<Job?> PollAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!jobs.CanRun(JobKind.Scan)) return null;
|
||||
var current = archive.Current;
|
||||
if (ArchiveService.GetAvailability(current) != ArchiveAvailability.Online) return null;
|
||||
current = await archive.RefreshAsync(archives, db, cancellationToken);
|
||||
foreach (var kind in new[] { JobKind.Scan, JobKind.Rebuild })
|
||||
{
|
||||
foreach (var state in Pending)
|
||||
{
|
||||
if ((await db.Jobs.ListAsync(state, kind, 50, null, cancellationToken)).Items.Any(j => j.TargetIds.Contains(current.Id))) return null;
|
||||
}
|
||||
}
|
||||
var scan = ArchiveJobs.Scan(current);
|
||||
// Behind what users asked for (BRIEF §14.6).
|
||||
return await jobs.Engine.EnqueueAsync(scan.Kind, scan.Targets, scan.Label, scan.ParametersJson, JobPriority.Background,
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
await PollAsync(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "The archive could not be polled");
|
||||
}
|
||||
try
|
||||
{
|
||||
await Task.Delay(Interval, time, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using Chronos.Data;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// The daily <c>VACUUM INTO</c> copy of the index of a Windows server on SQLite (BRIEF §6.2: nightly, kept ×3) into
|
||||
/// <c>{DataPath}/backups</c>. A server on PostgreSQL is backed up with PostgreSQL's own tools; this service then does nothing.
|
||||
/// </summary>
|
||||
public sealed class DatabaseBackupService(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger<DatabaseBackupService> logger) : BackgroundService
|
||||
{
|
||||
/// <summary>Folder of the copies.</summary>
|
||||
public string Directory => Path.Combine(options.DataPath, "backups");
|
||||
|
||||
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (db.Dialect != Dialect.Sqlite) return Task.CompletedTask;
|
||||
logger.LogInformation("Daily index backups go to {Directory}", Directory);
|
||||
return DatabaseBackups.RunDailyAsync(db, Directory, time, stoppingToken);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,28 @@
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>What one sweep of <see cref="UploadMaintenance.SweepAsync"/> removed.</summary>
|
||||
public sealed record UploadSweep(int Expired, int Files, int Records, int Tokens);
|
||||
|
||||
/// <summary>
|
||||
/// Upload housekeeping (BRIEF §14.4): at start, uploads a crash left half-committed are settled; then every half hour
|
||||
/// abandoned uploads expire, orphaned partial and staging files are removed, old upload records and dead tokens purged.
|
||||
/// Upload housekeeping (BRIEF §14.4): at start, uploads a crash left half-committed are settled; the sweep (abandoned
|
||||
/// uploads expire, orphaned partial and staging files are removed, old upload records and dead tokens purged) is the
|
||||
/// <see cref="UploadCleanupStep"/> of the <c>upload-cleanup</c> system schedule (owner review 2, R10), no longer a timer.
|
||||
/// </summary>
|
||||
public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options, ServerArchive archive, UploadStore store, TimeProvider time,
|
||||
ILogger<UploadMaintenance> logger)
|
||||
: BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(30);
|
||||
private static readonly TimeSpan FinishedRetention = TimeSpan.FromDays(90);
|
||||
/// <summary>Days a finished upload's record is kept unless the schedule says otherwise.</summary>
|
||||
public const int FinishedRetentionDays = 90;
|
||||
|
||||
private static readonly TimeSpan StagingRetention = TimeSpan.FromDays(1);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
@@ -27,22 +35,6 @@ public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options,
|
||||
{
|
||||
logger.LogError(ex, "Upload recovery failed");
|
||||
}
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await SweepAsync(stoppingToken);
|
||||
await Task.Delay(Interval, time, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Upload cleanup failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -77,7 +69,12 @@ public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options,
|
||||
return UploadRules.StandIn(archive.Root, copies, target);
|
||||
}
|
||||
|
||||
public async Task SweepAsync(CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// Expires uploads untouched for <see cref="ServerOptions.UploadRetentionHours"/>, deletes partial files no upload
|
||||
/// receives into and this server's staging files older than a day, purges the records of uploads finished more than
|
||||
/// <paramref name="finishedDays"/> days ago (0 keeps them) and expired tokens. Safe to run at any time.
|
||||
/// </summary>
|
||||
public async Task<UploadSweep> SweepAsync(int finishedDays = FinishedRetentionDays, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = time.GetUtcNow();
|
||||
var abandonedBefore = now - TimeSpan.FromHours(options.UploadRetentionHours);
|
||||
@@ -92,23 +89,49 @@ public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options,
|
||||
var active = new HashSet<Guid>();
|
||||
foreach (var state in new[] { UploadState.Receiving, UploadState.Committing })
|
||||
active.UnionWith((await db.Uploads.ListByStateAsync(state, cancellationToken)).Select(u => u.Id));
|
||||
var files = 0;
|
||||
foreach (var (id, _) in store.List().ToList())
|
||||
{
|
||||
if (!active.Contains(id)) store.Delete(id);
|
||||
if (active.Contains(id)) continue;
|
||||
store.Delete(id);
|
||||
if (!store.Exists(id)) files++;
|
||||
}
|
||||
if (Directory.Exists(options.StagingPath))
|
||||
{
|
||||
// Only this server's staging files (named by upload id) are touched; clients may share the archive.
|
||||
foreach (var file in new DirectoryInfo(options.StagingPath).EnumerateFiles())
|
||||
{
|
||||
if (Guid.TryParseExact(Path.GetFileNameWithoutExtension(file.Name), "N", out var id) && !active.Contains(id)
|
||||
&& file.LastWriteTimeUtc < now.UtcDateTime - StagingRetention)
|
||||
UploadStore.TryDelete(file.FullName);
|
||||
if (!Guid.TryParseExact(Path.GetFileNameWithoutExtension(file.Name), "N", out var id) || active.Contains(id)
|
||||
|| file.LastWriteTimeUtc >= now.UtcDateTime - StagingRetention)
|
||||
continue;
|
||||
UploadStore.TryDelete(file.FullName);
|
||||
if (!File.Exists(file.FullName)) files++;
|
||||
}
|
||||
}
|
||||
|
||||
await db.Uploads.PurgeFinishedAsync(now - FinishedRetention, cancellationToken);
|
||||
await db.Tokens.PurgeAsync(now, cancellationToken);
|
||||
var records = finishedDays > 0 ? await db.Uploads.PurgeFinishedAsync(now - TimeSpan.FromDays(finishedDays), cancellationToken) : 0;
|
||||
var tokens = await db.Tokens.PurgeAsync(now, cancellationToken);
|
||||
if (expired > 0) logger.LogInformation("Expired {Count} abandoned upload(s)", expired);
|
||||
return new UploadSweep(expired, files, records, tokens);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server's own clean-up step <c>uploads</c> (owner review 2, R10): <see cref="UploadMaintenance.SweepAsync"/>, with the
|
||||
/// clean-up's age limit as the days finished upload records are kept. It deletes only what uploads left behind, never a
|
||||
/// photo of the archive.
|
||||
/// </summary>
|
||||
public sealed class UploadCleanupStep(UploadMaintenance maintenance) : ICleanupStep
|
||||
{
|
||||
public const string StepName = "uploads";
|
||||
|
||||
public string Name => StepName;
|
||||
|
||||
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
var sweep = await maintenance.SweepAsync(parameters.OlderThanDays, context.Cancellation).ConfigureAwait(false);
|
||||
return Loc.L("Server.Log.UploadsSwept", sweep.Expired, sweep.Files, sweep.Records, sweep.Tokens);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user