Files
Chronos/src/Chronos.Server/Admin/web/pages/settings.js
T
Alby96 422f33d5f3 fix(server): show the audit clean-up's real age limit and lock it before the first pass
Settings › Logs › Keep audit showed ServerOptions.AuditRetentionDays, a second
copy of the audit clean-up schedule's age limit. Edits made on Jobs › Scheduled
never reached it, so the panel could say "kept forever" while entries were
being deleted every night. Saving 0 there then changed nothing, because the
endpoint only compared against the stale option value.

- GET and PUT /server/settings now report the schedule's limit in force (0
  while the schedule is off). Saving compares against that value. A value sent
  back unchanged leaves the server.json reset default and the env lock alone. A
  new value sets the schedule and becomes the reset default.
- ApplyAgeAsync also turns the schedule on when it already holds the days but
  is off.
- CHRONOS_AUDIT_RETENTION_DAYS is now applied before the scheduler's first
  pass, through a new Scheduler.StartAsync overload with a beforeFirstPass hook.
  Before, a missed 04:30 run was caught up at start with the stale days, which
  could delete entries the variable says to keep. While the variable fixes a
  limit above 0, turning the schedule off is a 409 setting_locked.
- Corrected the comments in SchedulerHost, ServerOptions, ServerSettingsStore,
  LogSettingsDto, the header of settings.js and ARCHITECTURE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 490ed286e9f32745174b13b1963d6ec91955196b)
2026-10-27 09:56:46 +01:00

224 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 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); Keep audit shows the
// Audit log clean-up schedule's age limit (0 while it is off), and saving a new one sets it. 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";
/** Levels of the priority queue, highest first. */
const LEVELS = ["high", "normal", "low"];
/** Log levels, least severe first (the server's wire names). */
const LOG_LEVELS = ["trace", "debug", "information", "warning", "error", "critical", "none"];
const ROTATIONS = ["daily", "hourly"];
/** Settings the server names in error details whose field here has another name. */
const FIELDS = { maxuploadbytes: "maxUploadMb", chunksizebytes: "chunkSizeMib" };
const PEM_FILES = ["tlsCert", "tlsKey"];
const MB = 1e6;
const MIB = 1024 * 1024;
export async function render(root, { api, info, setMeta, actions }) {
// Only the About group's database and uptime, filled in when the dashboard answers: the form never waits for its
// archive statistics, and without them those rows keep a dash.
const status = api.get("/api/v1/server/dashboard").then((d) => ({ ...d, at: Date.now() }), () => null);
let dashboard = null;
let settings;
try {
settings = await api.get("/api/v1/server/settings");
} catch (err) {
root.innerHTML = `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
return;
}
setMeta("");
// In the header, like the other pages' main action, so toasts never cover it.
actions.innerHTML = `<button class="btn primary" type="submit" form="settings-form" data-i18n="Admin.Common.Save" data-i18n-title="Admin.Common.Save.Tip"></button>`;
applyStrings(actions);
const same = (a, b) => a.toLowerCase() === b.toLowerCase();
const locked = (name) => settings.locked.some((l) => same(l, name));
// The server names the variable that fixes each locked setting: CHRONOS_LOG_LEVEL fixes the console's level too, unless
// CHRONOS_LOG_CONSOLE_LEVEL sets its own (BRIEF §14.9).
const variable = (name) => Object.entries(settings.lockedBy ?? {}).find(([setting]) => same(setting, name))?.[1] ?? name;
const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", variable(name)))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
const field = (name, input) => `<label class="field"><span data-i18n="Admin.Settings.${cap(name)}"></span>${input}</label>`;
const number = (name, value, attrs = "") => field(name, `<input class="input narrow num" type="number" name="${name}" value="${attr(value)}" ${attrs} ${lock(name)}>`);
const text = (name, value, attrs = "dir=\"auto\"") => field(name, `<input class="input" name="${name}" value="${attr(value ?? "")}" ${attrs} ${lock(name)}>`);
// A value this page does not know stays listed, so saving the other settings never changes it.
const choice = (name, value, values, label) => field(name, `<select class="input" name="${name}" ${lock(name)}>${values.concat(values.includes(value) ? [] : [value])
.map((v) => `<option value="${attr(v)}" ${v === value ? "selected" : ""}>${escapeHtml(t(label(v)))}</option>`).join("")}</select>`);
const level = (name, value) => choice(name, value, LOG_LEVELS, (l) => `Admin.Settings.Level.${cap(l)}`);
function draw() {
root.innerHTML = `
<form class="settings" id="settings-form" novalidate>
<section class="panel" aria-labelledby="server-title">
<div class="panel-head"><h2 id="server-title" data-i18n="Admin.Settings.Server"></h2>
${settings.restartRequired ? `<span class="chip warn" data-i18n="Admin.Settings.Restart" data-i18n-title="Admin.Settings.Restart.Tip"></span>` : ""}</div>
${text("serverName", settings.serverName)}
${field("language", `<select class="input" name="language" ${lock("language")}>${languages().concat(languages().includes(settings.language) ? [] : [settings.language])
.map((code) => `<option value="${attr(code)}" ${code === settings.language ? "selected" : ""}>${escapeHtml(nativeName(code))}</option>`).join("")}</select>`)}
${field("discovery", `<span class="inline"><input type="checkbox" name="discovery" ${settings.discovery ? "checked" : ""} ${lock("discovery")}></span>`)}
</section>
<section class="panel" aria-labelledby="jobs-title">
<h2 id="jobs-title" data-i18n="Admin.Settings.Jobs"></h2>
${number("parallelism", settings.parallelism, 'min="1" max="64"')}
${field("priorityQueue", `<span class="inline"><input type="checkbox" name="priorityQueue" ${settings.priorityQueue ? "checked" : ""} ${lock("priorityQueue")}></span>`)}
<div class="priorities" ${settings.priorityQueue ? "" : "hidden"}>
${settings.jobPriorities.map((p) => `<label class="field"><span>${escapeHtml(kindLabel(p.kind))}</span>
<select class="input narrow" name="priority:${attr(p.kind)}" title="${attr(t("Admin.Settings.JobPriority.Tip", kindLabel(p.kind)))}">${LEVELS.map((l) =>
`<option value="${l}" ${l === p.level ? "selected" : ""}>${escapeHtml(t(`Admin.Settings.Priority.${cap(l)}`))}</option>`).join("")}</select></label>`).join("")}
</div>
</section>
<section class="panel" aria-labelledby="network-title">
<div class="panel-head"><h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
${settings.proxyWarning ? PROXY_WARNING : ""}</div>
${number("httpPort", settings.httpPort, 'min="1" max="65535"')}
${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')}
${field("tlsMode", `<select class="input" name="tlsMode" ${lock("tlsMode")}>${["auto", "pem", "proxy"].map((m) =>
`<option value="${m}" ${m === settings.tlsMode ? "selected" : ""}>${escapeHtml(t(`Admin.Settings.Tls.${cap(m)}`))}</option>`).join("")}</select>`)}
${text("tlsCert", settings.tlsCert, 'dir="ltr" spellcheck="false"')}
${text("tlsKey", settings.tlsKey, 'dir="ltr" spellcheck="false"')}
<div class="field"><span data-i18n="Admin.Settings.Fingerprint"></span><code data-i18n-title="Admin.Settings.Fingerprint.Tip">${fingerprint(info?.tlsFingerprint)}</code></div>
</section>
<section class="panel" aria-labelledby="limits-title">
<h2 id="limits-title" data-i18n="Admin.Settings.Limits"></h2>
${number("maxUploadMb", Math.round(settings.maxUploadBytes / MB), 'min="1"')}
${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"')}
</section>
<section class="panel" aria-labelledby="logs-title">
<h2 id="logs-title" data-i18n="Admin.Settings.Logs"></h2>
${level("logLevel", settings.logs.fileLevel)}
${level("consoleLogLevel", settings.logs.consoleLevel)}
${number("logRetentionDays", settings.logs.retentionDays, 'min="1" max="3650"')}
${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="3650"')}
${number("diagnosticsLogMb", settings.logs.diagnosticsLogMb, 'min="1" max="1024"')}
</section>
</form>
${about()}`;
applyStrings(root);
const form = root.querySelector("form");
escapeReverts(form);
form.addEventListener("submit", save);
form.elements.tlsMode.addEventListener("change", () => pemFiles(form));
pemFiles(form);
// The levels matter only while the priority queue is on.
form.elements.priorityQueue.addEventListener("change", () => { root.querySelector(".priorities").hidden = !form.elements.priorityQueue.checked; });
}
/**
* About, outside the form: nothing to save. The server name and the certificate fingerprint are left to the Server
* and Network groups above; the uptime counts on from when it was read.
*/
function about() {
const rows = [
["Admin.About.Version", `<span class="num" dir="ltr">${escapeHtml(info?.version ?? "—")}</span>`],
["Admin.About.Api", `<span class="num">${escapeHtml(info?.apiVersion ?? "—")}</span>`],
["Admin.About.Database", `<span id="about-database" dir="ltr">${escapeHtml(database())}</span>`],
["Admin.About.Uptime", `<span id="about-uptime">${escapeHtml(uptime())}</span>`],
];
return `
<section class="panel about" aria-labelledby="about-title">
<h2 id="about-title" tabindex="-1" data-i18n="Admin.Settings.About"></h2>
<div class="brand large"><img src="favicon.svg" alt=""><strong data-i18n="Admin.About.Title"></strong></div>
<dl>${rows.map(([key, value]) => `<dt data-i18n="${key}"></dt><dd>${value}</dd>`).join("")}</dl>
</section>`;
}
function database() {
return dashboard?.database ?? "—";
}
function uptime() {
return dashboard ? formatDuration(dashboard.uptimeSeconds + (Date.now() - dashboard.at) / 1000) : "—";
}
/** The certificate and key files are used only in Own certificate mode; elsewhere they are off and say so. */
function pemFiles(form) {
const pem = form.elements.tlsMode.value === "pem";
for (const name of PEM_FILES.filter((n) => !locked(n))) {
const input = form.elements[name];
clearInvalid(input);
input.disabled = !pem;
input.title = t(pem ? `Admin.Settings.${cap(name)}.Tip` : "Admin.Settings.PemOnly.Tip");
}
}
async function save(e) {
e.preventDefault();
const form = e.target;
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const data = new FormData(form);
const value = (name, fallback) => (form.elements[name]?.disabled ? fallback : data.get(name));
const request = {
...settings,
serverName: String(value("serverName", settings.serverName)).trim(),
language: String(value("language", settings.language)),
parallelism: Number(value("parallelism", settings.parallelism)),
priorityQueue: form.elements.priorityQueue.disabled ? settings.priorityQueue : form.elements.priorityQueue.checked,
jobPriorities: settings.jobPriorities.map((p) => ({ kind: p.kind, level: String(data.get(`priority:${p.kind}`) ?? p.level) })),
discovery: form.elements.discovery.disabled ? settings.discovery : form.elements.discovery.checked,
httpPort: Number(value("httpPort", settings.httpPort)),
httpsPort: Number(value("httpsPort", settings.httpsPort)),
tlsMode: String(value("tlsMode", settings.tlsMode)),
tlsCert: String(value("tlsCert", settings.tlsCert ?? "")).trim() || null,
tlsKey: String(value("tlsKey", settings.tlsKey ?? "")).trim() || null,
maxUploadBytes: Math.round(Number(data.get("maxUploadMb")) * MB),
chunkSizeBytes: Math.round(Number(data.get("chunkSizeMib")) * MIB),
tokenLifetimeDays: Number(data.get("tokenLifetimeDays")),
uploadRetentionHours: Number(data.get("uploadRetentionHours")),
logs: {
fileLevel: String(value("logLevel", settings.logs.fileLevel)),
consoleLevel: String(value("consoleLogLevel", settings.logs.consoleLevel)),
retentionDays: Number(value("logRetentionDays", settings.logs.retentionDays)),
maxFileMb: Number(value("logMaxFileMb", settings.logs.maxFileMb)),
maxTotalMb: Number(value("logMaxTotalMb", settings.logs.maxTotalMb)),
rotation: String(value("logRotation", settings.logs.rotation)),
auditRetentionDays: Number(value("auditRetentionDays", settings.logs.auditRetentionDays)),
diagnosticsLogMb: Number(value("diagnosticsLogMb", settings.logs.diagnosticsLogMb)),
},
};
try {
settings = await api.put("/api/v1/server/settings", request);
draw();
toast(t("Admin.Common.Saved"));
} catch (err) {
const key = String(err.details ?? "").toLowerCase();
const input = (FIELDS[key] && form.elements[FIELDS[key]]) || [...form.elements].find((el) => el.name && el.name.toLowerCase() === key);
let message = errorText(err);
if (input && err.code === "invalid_setting") message = PEM_FILES.includes(input.name) ? t("Admin.Settings.PemMissing") : invalidText(input);
if (input && !input.disabled) {
markInvalid(input, message);
input.focus();
}
toast(message, true);
}
}
draw();
// Once: the route drops the group, so a later redraw (a language change) leaves the focus where it is.
if (routeParams().get("group") === "about") {
history.replaceState(null, "", "#/settings");
root.querySelector(".about").scrollIntoView({ block: "start" });
root.querySelector("#about-title").focus({ preventScroll: true });
}
// Only the two rows change, so the focus and the form's edits stay; a page left meanwhile is not touched.
status.then((d) => {
dashboard = d;
if (!d || !root.isConnected) return;
root.querySelector("#about-database").textContent = database();
root.querySelector("#about-uptime").textContent = uptime();
});
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}