feat: owner review 2 phase 1: :latest, Unraid array space, Settings with About, whole-folder import (#9)
CI / Build and test (push) Successful in 5m11s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 8m57s
CI / PostgreSQL 16 integration (push) Successful in 3m10s
CI / PostgreSQL 17 integration (push) Successful in 3m30s
CI / Docker image (push) Successful in 49s
Release / Server image (push) Successful in 1m4s
CI / Build and test (push) Successful in 5m11s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 8m57s
CI / PostgreSQL 16 integration (push) Successful in 3m10s
CI / PostgreSQL 17 integration (push) Successful in 3m30s
CI / Docker image (push) Successful in 49s
Release / Server image (push) Successful in 1m4s
- :latest follows the highest stable release, or the highest pre-release while none is stable (Chronos.Tools release-channels); bad tags are refused before anything is built. - Unraid: CHRONOS_SPACE_PATH and the template's Array view show the array's free space; the write volume (cache) is shown apart; completions check the archive volume (507). - Settings is a gear, docked at the foot of the admin sidebar; About is the last part of Settings on the desktop and the panel. - Import > Folder > Whole folder: one sequence per format (desktop only). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #9.
This commit is contained in:
1 parent
5acdf146c7
commit
1f089888e8
320 files changed
+3030
-927
No files matched your search
@@ -61,8 +61,11 @@ h2 { font-size: 14px; font-weight: 600; }
|
||||
.brand strong { display: block; font-size: 14px; }
|
||||
.brand span { display: block; font-size: 11px; color: var(--text-muted); }
|
||||
.brand.large img { width: 40px; height: 40px; }
|
||||
.brand.large h2 { font-size: 18px; }
|
||||
.nav { display: grid; gap: 2px; }
|
||||
.brand.large strong { font-size: 18px; }
|
||||
/* The menu fills the sidebar: its pages from the top, Settings docked at its foot above the account (owner review 2). */
|
||||
.nav { flex: 1 0 auto; display: flex; flex-direction: column; gap: 2px; }
|
||||
.nav-group { display: grid; gap: 2px; }
|
||||
.nav-group.bottom { margin-block: auto 8px; padding-block-start: 8px; }
|
||||
.nav a { display: flex; align-items: center; gap: 10px; height: 36px; padding: 0 10px; border-radius: var(--radius); color: var(--text); text-decoration: none; }
|
||||
.nav a:hover { background: var(--card-hover); color: var(--text); }
|
||||
.nav a[aria-current="page"] { background: var(--accent-selected); color: var(--accent); font-weight: 600; }
|
||||
@@ -77,6 +80,12 @@ h2 { font-size: 14px; font-weight: 600; }
|
||||
.nav a { position: relative; }
|
||||
/* Exactly the widths the narrow layout below leaves (fractional widths at 125 % scaling included). */
|
||||
@media not all and (max-width: 900px) {
|
||||
/* Short windows: the pages above scroll, so Settings and the account stay docked in view; the whole sidebar scrolls
|
||||
only when even those do not fit. The padding keeps the links' focus rings inside the scrolling list. */
|
||||
.sidebar, .nav-group:not(.bottom) { overflow-y: auto; scrollbar-width: thin; }
|
||||
.sidebar { overflow-x: hidden; }
|
||||
/* At least one whole link stays visible (36 px plus the padding); below that the sidebar itself scrolls. */
|
||||
.nav-group:not(.bottom) { flex: 1 1 0; min-height: 44px; align-content: start; padding: 4px; margin: -4px; }
|
||||
.shell.collapsed { grid-template-columns: 56px minmax(0, 1fr); }
|
||||
.shell.collapsed .sidebar { padding-inline: 8px; }
|
||||
.shell.collapsed .sidebar-toggle { align-self: center; margin-inline-start: 0; }
|
||||
@@ -264,7 +273,10 @@ dialog.dialog p { margin: 0; color: var(--text-muted); }
|
||||
.toast { width: 420px; max-width: calc(100vw - 48px); padding: 12px 14px; color: var(--text); background: var(--card); border: 1px solid var(--stroke); border-inline-start: 3px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px var(--shadow); }
|
||||
.toast.error { border-inline-start-color: var(--error); }
|
||||
|
||||
/* About */
|
||||
/* About: the last group of Settings (owner review 2); #/about scrolls to it below the sticky header and focuses its heading. */
|
||||
.about { scroll-margin-block-start: 84px; }
|
||||
.about h2:focus { outline: none; }
|
||||
.about .brand { padding: 0; }
|
||||
.about dl { display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 8px 16px; margin: 0; }
|
||||
.about dt { color: var(--text-muted); }
|
||||
.about dd { margin: 0; overflow-wrap: anywhere; }
|
||||
@@ -291,7 +303,9 @@ dialog.dialog p { margin: 0; color: var(--text-muted); }
|
||||
.sidebar { flex-direction: row; overflow-x: auto; padding: 8px; position: static; height: auto; border-bottom: 1px solid var(--stroke); }
|
||||
.main { border-inline-start: 0; }
|
||||
.sidebar .brand, .sidebar .user, .sidebar-toggle { display: none; }
|
||||
.nav { display: flex; gap: 4px; }
|
||||
.nav { flex-direction: row; gap: 4px; }
|
||||
.nav-group { display: flex; gap: 4px; }
|
||||
.nav-group.bottom { margin: 0; margin-inline-start: auto; padding: 0; }
|
||||
.nav a > span:not(.badge) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.header { position: static; flex-wrap: wrap; padding-block: 10px; }
|
||||
.tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
|
||||
@@ -5,7 +5,12 @@ import { icons } from "./icons.js";
|
||||
import { escapeHtml, attr, errorText, nativeName, formatNumber, fitColumns } from "./ui.js";
|
||||
|
||||
const app = document.getElementById("app");
|
||||
const pages = ["dashboard", "users", "archive", "jobs", "settings", "logs", "about"];
|
||||
// The menu: its pages from the top, then the ones docked at its foot above the account (owner review 2).
|
||||
const topPages = ["dashboard", "users", "archive", "jobs", "logs"];
|
||||
const bottomPages = ["settings"];
|
||||
const pages = [...topPages, ...bottomPages];
|
||||
/** Routes of old bookmarks and where they open now: About is the last group of Settings (owner review 2). */
|
||||
const MOVED = { about: "settings?group=about" };
|
||||
const THEME_KEY = "chronos.admin.theme";
|
||||
const SIDEBAR_KEY = "chronos.admin.sidebar";
|
||||
/** The narrow layout of admin.css, where the menu is the top bar and does not collapse. */
|
||||
@@ -43,7 +48,12 @@ async function start() {
|
||||
}
|
||||
|
||||
function currentPage() {
|
||||
const p = location.hash.replace(/^#\/?/, "").split("?")[0];
|
||||
let p = location.hash.replace(/^#\/?/, "").split("?")[0];
|
||||
if (Object.hasOwn(MOVED, p)) {
|
||||
// The address shows the new route; replaceState fires no hashchange.
|
||||
history.replaceState(null, "", `#/${MOVED[p]}`);
|
||||
p = MOVED[p].split("?")[0];
|
||||
}
|
||||
return pages.includes(p) ? p : "dashboard";
|
||||
}
|
||||
|
||||
@@ -136,7 +146,7 @@ function renderPasswordChange() {
|
||||
}
|
||||
|
||||
function renderShell(page, focus) {
|
||||
const nav = pages.map((p) => `
|
||||
const links = (group) => group.map((p) => `
|
||||
<a href="#/${p}" ${p === page ? 'aria-current="page"' : ""} data-i18n-title="Admin.Nav.${cap(p)}.Tip">${icons[p]}<span data-i18n="Admin.Nav.${cap(p)}"></span>
|
||||
<span class="sr-only" id="badge-text-${p}"></span><span class="badge" id="badge-${p}" aria-hidden="true" hidden></span></a>`).join("");
|
||||
const user = api.user();
|
||||
@@ -146,7 +156,7 @@ function renderShell(page, focus) {
|
||||
<aside class="sidebar">
|
||||
<button class="btn icon sidebar-toggle" id="sidebar-toggle">${icons.menu}</button>
|
||||
${brand()}
|
||||
<nav class="nav">${nav}</nav>
|
||||
<nav class="nav"><div class="nav-group">${links(topPages)}</div><div class="nav-group bottom">${links(bottomPages)}</div></nav>
|
||||
<div class="user">
|
||||
<div class="avatar" aria-hidden="true">${escapeHtml(user.username.slice(0, 1).toUpperCase())}</div>
|
||||
<div class="who"><strong class="ellipsis" dir="auto" title="${attr(user.username)}">${escapeHtml(user.username)}</strong><span data-i18n="Admin.Role.Admin"></span></div>
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
// Generated from branding/ui-icons/icons.py (same 16-px set as the desktop apps).
|
||||
// Generated by branding/ui-icons/icons.py (same 16-px set as the desktop apps). Do not edit by hand.
|
||||
export const icons = {
|
||||
dashboard: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
users: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5 5 A3 3 0 1 0 11 5 A3 3 0 1 0 5 5 Z M2.5 14 A5.5 5.5 0 0 1 13.5 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
archive: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 4.5 H14 V13.5 H2 Z M2 2 H14 V4.5 H2 Z M6 8 H10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
jobs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 8 H13 M3 4 H13 M3 12 H9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
settings: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5.8 8 A2.2 2.2 0 1 0 10.2 8 A2.2 2.2 0 1 0 5.8 8 Z M8 1.5 V3.5 M8 12.5 V14.5 M1.5 8 H3.5 M12.5 8 H14.5 M3.4 3.4 L4.8 4.8 M11.2 11.2 L12.6 12.6 M3.4 12.6 L4.8 11.2 M11.2 4.8 L12.6 3.4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
settings: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M7.15 3.48 L7.4 1.53 A6.5 6.5 0 0 1 8.6 1.53 L8.85 3.48 A4.6 4.6 0 0 1 10.6 4.2 L12.15 3 A6.5 6.5 0 0 1 13 3.85 L11.8 5.4 A4.6 4.6 0 0 1 12.52 7.15 L14.47 7.4 A6.5 6.5 0 0 1 14.47 8.6 L12.52 8.85 A4.6 4.6 0 0 1 11.8 10.6 L13 12.15 A6.5 6.5 0 0 1 12.15 13 L10.6 11.8 A4.6 4.6 0 0 1 8.85 12.52 L8.6 14.47 A6.5 6.5 0 0 1 7.4 14.47 L7.15 12.52 A4.6 4.6 0 0 1 5.4 11.8 L3.85 13 A6.5 6.5 0 0 1 3 12.15 L4.2 10.6 A4.6 4.6 0 0 1 3.48 8.85 L1.53 8.6 A6.5 6.5 0 0 1 1.53 7.4 L3.48 7.15 A4.6 4.6 0 0 1 4.2 5.4 L3 3.85 A6.5 6.5 0 0 1 3.85 3 L5.4 4.2 A4.6 4.6 0 0 1 7.15 3.48 Z M6.3 8 A1.7 1.7 0 1 0 9.7 8 A1.7 1.7 0 1 0 6.3 8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
logs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
about: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M8 7 V11 M8 4.8 V5.2" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
menu: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 4 H13.5 M2.5 8 H13.5 M2.5 12 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
power: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 V7.5 M11.54 4.59 A5.5 5.5 0 1 1 4.46 4.59" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
moon: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.5 1.8 A6.5 6.5 0 1 0 14.2 11.2 A5.5 5.5 0 0 1 9.5 1.8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
// About: version, API, database, uptime and the certificate fingerprint clients are asked to trust.
|
||||
import { applyStrings } from "../i18n.js";
|
||||
import { escapeHtml, formatDuration, fingerprint } from "../ui.js";
|
||||
|
||||
export async function render(root, { api, info, setMeta }) {
|
||||
setMeta("");
|
||||
const dashboard = await api.get("/api/v1/server/dashboard").catch(() => null);
|
||||
const rows = [
|
||||
["Admin.About.Name", `<span dir="auto">${escapeHtml(info?.name ?? "—")}</span>`],
|
||||
["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 dir="ltr">${escapeHtml(dashboard?.database ?? "—")}</span>`],
|
||||
["Admin.About.Uptime", escapeHtml(dashboard ? formatDuration(dashboard.uptimeSeconds) : "—")],
|
||||
["Admin.About.Fingerprint", fingerprint(info?.tlsFingerprint)],
|
||||
];
|
||||
root.innerHTML = `
|
||||
<section class="panel about" aria-labelledby="about-title">
|
||||
<div class="brand large"><img src="favicon.svg" alt=""><h2 id="about-title" data-i18n="Admin.About.Title"></h2></div>
|
||||
<dl>${rows.map(([key, value]) => `<dt data-i18n="${key}"></dt><dd>${value}</dd>`).join("")}</dl>
|
||||
</section>`;
|
||||
applyStrings(root);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics.
|
||||
import { t, plural, applyStrings } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, bar, columns, toast, errorText, emptyState, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, bar, storageTip, writeVolumeLine, columns, toast, errorText, emptyState, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js";
|
||||
|
||||
const PROXY_SIZES = [-1, 1280, 1920, 2560, 3840, 0];
|
||||
const ACTIONS = ["scan", "rebuild", "verify", "maintenance"];
|
||||
@@ -15,7 +15,9 @@ export async function render(root, { api, setMeta }) {
|
||||
return;
|
||||
}
|
||||
setMeta(settings.rootPath, { ltr: true });
|
||||
// The space volume's figures (the space path when the server has one), the write volume apart when it differs.
|
||||
const used = stats.capacityBytes > 0 ? (stats.capacityBytes - stats.freeBytes) / stats.capacityBytes : 0;
|
||||
const spaceTip = attr(storageTip(stats));
|
||||
const sizes = PROXY_SIZES.includes(settings.proxyLongEdge) ? PROXY_SIZES : [settings.proxyLongEdge, ...PROXY_SIZES];
|
||||
const proxyOptions = sizes.map((size) => `<option value="${size}" ${size === settings.proxyLongEdge ? "selected" : ""}>${escapeHtml(proxyLabel(size))}</option>`).join("");
|
||||
const statsTable = (rows, labelId) => rows.length === 0 ? "" : `<div class="table compact stats" role="table" aria-labelledby="${labelId}"><div role="rowgroup">${rows.map((r) =>
|
||||
@@ -28,8 +30,8 @@ export async function render(root, { api, setMeta }) {
|
||||
<span class="sub">${escapeHtml(`${plural("Admin.Dashboard.PhotoCount", stats.photos)} · ${plural("Admin.Dashboard.CameraCount", stats.cameras)}`)}</span></section>
|
||||
<section class="panel tile" aria-labelledby="tile-originals"><h2 class="label" id="tile-originals" data-i18n="Admin.Archive.Originals"></h2><span class="value">${escapeHtml(formatBytes(stats.bytes))}</span>
|
||||
<span class="sub num">${escapeHtml(stats.firstYear ? `${stats.firstYear}–${stats.lastYear}` : "—")}</span></section>
|
||||
<section class="panel tile" aria-labelledby="tile-storage"><h2 class="label" id="tile-storage" data-i18n="Admin.Dashboard.Storage"></h2><span class="value">${escapeHtml(formatBytes(stats.freeBytes))}<small data-i18n="Admin.Archive.FreeShort"></small></span>
|
||||
${bar(used)}<span class="sub">${escapeHtml(t("Admin.Dashboard.Of", formatBytes(stats.capacityBytes)))}</span></section>
|
||||
<section class="panel tile" aria-labelledby="tile-storage"><h2 class="label" id="tile-storage" data-i18n="Admin.Dashboard.Storage"></h2><span class="value" title="${spaceTip}">${escapeHtml(formatBytes(stats.freeBytes))}<small data-i18n="Admin.Archive.FreeShort"></small></span>
|
||||
${bar(used)}<span class="sub" title="${spaceTip}">${escapeHtml(t("Admin.Dashboard.Of", formatBytes(stats.capacityBytes)))}</span>${writeVolumeLine(stats)}</section>
|
||||
<section class="panel tile" aria-labelledby="tile-health"><h2 class="label" id="tile-health" data-i18n="Admin.Archive.Health"></h2><span class="value num">${formatNumber(stats.unverifiedSequences)}<small>${escapeHtml(plural("Admin.Archive.UnverifiedUnit", stats.unverifiedSequences))}</small></span>
|
||||
<span class="sub">${escapeHtml(plural("Admin.Dashboard.WithoutProxies", stats.sequencesWithoutProxies))}</span></section>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Dashboard (mockup Admin.html, BRIEF §14.8): storage, archive, jobs, render nodes, charts, activity, active jobs.
|
||||
import { t, plural, applyStrings, culture } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw, fitColumns, PROXY_WARNING } from "../ui.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, storageTip, writeVolumeLine, columns, toast, errorText, emptyState, redraw, fitColumns, PROXY_WARNING } from "../ui.js";
|
||||
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js";
|
||||
import { activityText } from "../audit.js";
|
||||
|
||||
@@ -30,8 +30,10 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
|
||||
t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff")));
|
||||
actions.innerHTML = d.proxyWarning ? PROXY_WARNING : "";
|
||||
applyStrings(actions);
|
||||
// The space volume's figures (the space path when the server has one), the write volume apart when it differs.
|
||||
const a = d.archive;
|
||||
const used = a.capacityBytes > 0 ? (a.capacityBytes - a.freeBytes) / a.capacityBytes : 0;
|
||||
const spaceTip = attr(storageTip(a));
|
||||
const online = d.nodes.filter((n) => n.state !== "offline");
|
||||
const uploads = lastThirtyDays(d.uploads);
|
||||
const totalUploads = uploads.reduce((s, u) => s + u.value, 0);
|
||||
@@ -41,9 +43,10 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
|
||||
<div class="tiles">
|
||||
<section class="panel tile" aria-labelledby="tile-storage">
|
||||
<h2 class="label" id="tile-storage" data-i18n="Admin.Dashboard.Storage"></h2>
|
||||
<span class="value">${escapeHtml(formatBytes(a.capacityBytes - a.freeBytes))}<small>${escapeHtml(t("Admin.Dashboard.Of", formatBytes(a.capacityBytes)))}</small></span>
|
||||
<span class="value" title="${spaceTip}">${escapeHtml(formatBytes(a.capacityBytes - a.freeBytes))}<small>${escapeHtml(t("Admin.Dashboard.Of", formatBytes(a.capacityBytes)))}</small></span>
|
||||
${bar(used)}
|
||||
<span class="sub">${escapeHtml(t("Admin.Dashboard.Free", formatBytes(a.freeBytes)))} · ${escapeHtml(t("Admin.Dashboard.Originals", formatBytes(a.bytes)))}</span>
|
||||
<span class="sub" title="${spaceTip}">${escapeHtml(t("Admin.Dashboard.Free", formatBytes(a.freeBytes)))} · ${escapeHtml(t("Admin.Dashboard.Originals", formatBytes(a.bytes)))}</span>
|
||||
${writeVolumeLine(a)}
|
||||
</section>
|
||||
<section class="panel tile" aria-labelledby="tile-archive">
|
||||
<h2 class="label" id="tile-archive" data-i18n="Admin.Dashboard.Archive"></h2>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention. 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.
|
||||
// (owner review 1): the parallelism (photos at once) and the priority queue apply at once. 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, markInvalid, clearInvalid, invalidText, escapeReverts, PROXY_WARNING } from "../ui.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, PROXY_WARNING } from "../ui.js";
|
||||
import { kindLabel } from "../jobs.js";
|
||||
|
||||
/** Setting → environment variable that can fix it (BRIEF §14.9). */
|
||||
@@ -20,6 +21,10 @@ 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");
|
||||
@@ -78,7 +83,8 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
${number("uploadRetentionHours", settings.uploadRetentionHours, 'min="1" max="8760"')}
|
||||
${number("jobHistoryDays", settings.jobHistoryDays, 'min="1" max="3650"')}
|
||||
</section>
|
||||
</form>`;
|
||||
</form>
|
||||
${about()}`;
|
||||
applyStrings(root);
|
||||
const form = root.querySelector("form");
|
||||
escapeReverts(form);
|
||||
@@ -89,6 +95,33 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
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";
|
||||
@@ -143,6 +176,19 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
@@ -56,6 +56,23 @@ export function bar(fraction, muted = false) {
|
||||
`<rect class="track" width="100" height="6" rx="3"/><rect class="fill" width="${width}" height="6" rx="3"/></svg>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tooltip of a storage tile's figures (archive stats): the volume they measure and its file system; on an Unraid share
|
||||
* without a space volume, that they are the share's primary storage.
|
||||
*/
|
||||
export function storageTip(stats) {
|
||||
const lines = [stats.usesSpacePath ? t("Admin.Dashboard.SpaceVolume.Tip") : t("Admin.Dashboard.Storage.Tip")];
|
||||
if (stats.fileSystem) lines.push(t("Admin.Dashboard.FileSystem", stats.fileSystem));
|
||||
if (stats.fileSystem === "fuse.shfs" && !stats.usesSpacePath) lines.push(t("Admin.Dashboard.UnraidShare.Tip"));
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/** The write volume's free space as one more line of a storage tile, when the stats have it apart; "" otherwise. */
|
||||
export function writeVolumeLine(stats) {
|
||||
if (stats.writeFreeBytes == null) return "";
|
||||
return `<span class="sub" title="${attr(t("Admin.Dashboard.WriteVolume.Tip"))}">${escapeHtml(t("Admin.Dashboard.WriteVolume", formatBytes(stats.writeFreeBytes)))}</span>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Column chart named by label: values with labels under the bars and, when given, the value above each bar. Bars use
|
||||
* the accent colour, or the sun colour for upload activity. With edgeLabels the first and last labels align with the
|
||||
|
||||
@@ -40,7 +40,7 @@ public static class AdminEndpoints
|
||||
}
|
||||
|
||||
private static async Task<IResult> DashboardAsync(HttpContext context, ChronosDatabase db, ServerArchive archive, ServerOptions options, ServerState state,
|
||||
TimeProvider time)
|
||||
TimeProvider time, VolumeSpace volumes)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
var now = time.GetUtcNow();
|
||||
@@ -61,7 +61,7 @@ public static class AdminEndpoints
|
||||
options.TlsMode.ToString().ToLowerInvariant(),
|
||||
options.Discovery,
|
||||
users.Count,
|
||||
await ArchiveEndpoints.StatsAsync(db, archive, ct),
|
||||
await ArchiveEndpoints.StatsAsync(db, archive, volumes, ct),
|
||||
new JobCountsDto(counts.Queued, counts.Running, counts.Paused, counts.DoneSince, counts.FailedSince),
|
||||
options.Parallelism,
|
||||
options.PriorityQueue,
|
||||
|
||||
@@ -23,37 +23,31 @@ public static class ArchiveEndpoints
|
||||
archive.MapGet("/settings", async (HttpContext c, ServerArchive a, ChronosDatabase db, [FromServices] ArchiveService? archives) =>
|
||||
Results.Json(Settings(archives is null ? a.Current : await a.RefreshAsync(archives, db, c.RequestAborted)), ProtocolJson.Default.ArchiveSettingsDto));
|
||||
archive.MapPut("/settings", UpdateAsync);
|
||||
archive.MapGet("/stats", async (HttpContext c, ChronosDatabase db, ServerArchive a) =>
|
||||
Results.Json(await StatsAsync(db, a, c.RequestAborted), ProtocolJson.Default.ArchiveStatsDto));
|
||||
archive.MapGet("/stats", async (HttpContext c, ChronosDatabase db, ServerArchive a, VolumeSpace volumes) =>
|
||||
Results.Json(await StatsAsync(db, a, volumes, c.RequestAborted), ProtocolJson.Default.ArchiveStatsDto));
|
||||
foreach (var (path, kind) in new[] { ("scan", JobKind.Scan), ("rebuild", JobKind.Rebuild), ("verify", JobKind.Verify), ("maintenance", JobKind.Maintenance) })
|
||||
{
|
||||
archive.MapPost("/" + path, (HttpContext c, Caller caller, ServerArchive a, JobEngineHost host, AuditLog audit) => EnqueueAsync(c, caller, a, host, audit, kind));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Totals, distributions, free space and health of the archive (also shown on the dashboard).</summary>
|
||||
public static async Task<ArchiveStatsDto> StatsAsync(ChronosDatabase db, ServerArchive archive, CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// Totals, distributions, free space and health of the archive (also shown on the dashboard). The free space is the
|
||||
/// space volume's (<see cref="VolumeSpace.Report"/>), with the archive's own volume apart when they differ; an offline
|
||||
/// volume reports no figures (0).
|
||||
/// </summary>
|
||||
public static async Task<ArchiveStatsDto> StatsAsync(ChronosDatabase db, ServerArchive archive, VolumeSpace volumes, CancellationToken cancellationToken)
|
||||
{
|
||||
var stats = await db.Sequences.GetStatsAsync(archive.Id, cancellationToken);
|
||||
var withoutProxies = await db.Sequences.CountAsync(
|
||||
new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = SequenceStatus.ProxiesBuilt }, cancellationToken);
|
||||
long free = 0, capacity = 0;
|
||||
try
|
||||
{
|
||||
var drive = new DriveInfo(archive.Root);
|
||||
free = drive.AvailableFreeSpace;
|
||||
capacity = drive.TotalSize;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)
|
||||
{
|
||||
// An offline archive volume reports no space figures.
|
||||
}
|
||||
var storage = volumes.Report(archive.Root);
|
||||
return new ArchiveStatsDto(
|
||||
stats.Sequences,
|
||||
stats.Photos,
|
||||
stats.Bytes,
|
||||
free,
|
||||
capacity,
|
||||
storage.Space?.FreeBytes ?? 0,
|
||||
storage.Space?.TotalBytes ?? 0,
|
||||
stats.ByCamera.Count(c => c.Model is not null),
|
||||
stats.ByYear.Count > 0 ? stats.ByYear[0].Year : null,
|
||||
stats.ByYear.Count > 0 ? stats.ByYear[^1].Year : null,
|
||||
@@ -62,7 +56,11 @@ public static class ArchiveEndpoints
|
||||
[.. stats.ByCamera.Select(c => new KeyValueCount(string.Join(' ', new[] { c.Make, c.Model }.Where(v => !string.IsNullOrEmpty(v))), c.Photos, c.Bytes))],
|
||||
[.. stats.ByFormat.Select(f => new KeyValueCount(f.Format.ToString().ToLowerInvariant(), f.Photos, f.Bytes))],
|
||||
withoutProxies,
|
||||
stats.Health.Unverified);
|
||||
stats.Health.Unverified,
|
||||
storage.Write?.FreeBytes,
|
||||
storage.Write?.TotalBytes,
|
||||
storage.FileSystem,
|
||||
storage.FromSpacePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -8,6 +8,7 @@ using Chronos.Data.Processing;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
@@ -25,11 +26,11 @@ public static class DiagnosticsEndpoints
|
||||
api.MapGet("/server/diagnostics", DownloadAsync).Requires(Permissions.ManageArchive);
|
||||
|
||||
private static async Task<IResult> DownloadAsync(HttpContext context, Caller caller, ChronosDatabase db, ServerOptions options, ServerState state,
|
||||
AuditLog audit, TimeProvider time, IServiceProvider services)
|
||||
AuditLog audit, TimeProvider time, VolumeSpace volumes, IServiceProvider services)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
var failures = (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct)).Items;
|
||||
var report = Report(options, state, time);
|
||||
var report = Report(options, state, time, volumes);
|
||||
var settings = JsonSerializer.Serialize(options, ServerOptionsJson.Default.ServerOptions);
|
||||
var encoders = Encoders(services.GetService<ProcessingService>());
|
||||
|
||||
@@ -64,7 +65,7 @@ public static class DiagnosticsEndpoints
|
||||
return Results.File(file, "application/zip", name);
|
||||
}
|
||||
|
||||
private static string Report(ServerOptions options, ServerState state, TimeProvider time)
|
||||
private static string Report(ServerOptions options, ServerState state, TimeProvider time, VolumeSpace volumes)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Chronos Server {SystemEndpoints.Version} ({options.ServerName})");
|
||||
@@ -76,8 +77,11 @@ public static class DiagnosticsEndpoints
|
||||
sb.AppendLine("SQLite compile options: " + string.Join(' ', Chronos.Data.Sqlite.SqliteDatabase.CompileOptions));
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"TLS {options.TlsMode} {state.TlsFingerprint}");
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Jobs one at a time, parallelism {options.Parallelism}, priority queue {(options.PriorityQueue ? "on" : "off")}");
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Archive {options.ArchivePath} ({Space(options.ArchivePath)})");
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Data {options.DataPath} ({Space(options.DataPath)})");
|
||||
// The archive's volume is where uploads are written; the space path, when set, is what the admin panel shows.
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Archive {options.ArchivePath} ({Space(volumes, options.ArchivePath)})");
|
||||
if (!string.IsNullOrWhiteSpace(options.SpacePath))
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Space {options.SpacePath} ({Space(volumes, options.SpacePath)})");
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Data {options.DataPath} ({Space(volumes, options.DataPath)})");
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Container {File.Exists("/.dockerenv")}");
|
||||
sb.AppendLine("Set by environment: " + string.Join(", ", options.Locked));
|
||||
return sb.ToString();
|
||||
@@ -98,19 +102,15 @@ public static class DiagnosticsEndpoints
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string Space(string path)
|
||||
/// <summary>"120 GB free of 500 GB, fuse.shfs mounted at /archive from shfs" (the mount on Linux only; "…, NTFS" elsewhere).</summary>
|
||||
private static string Space(VolumeSpace volumes, string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(path)) return "missing";
|
||||
var full = Path.GetFullPath(path);
|
||||
// Windows wants a drive root; Unix accepts any directory and reports the volume it is mounted on.
|
||||
var drive = new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(full)! : full);
|
||||
return string.Create(CultureInfo.InvariantCulture, $"{drive.AvailableFreeSpace / (1L << 30)} GB free of {drive.TotalSize / (1L << 30)} GB");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
|
||||
{
|
||||
return "free space unknown";
|
||||
}
|
||||
if (!Directory.Exists(path)) return "missing";
|
||||
var figures = volumes.Measure(path) is { } v
|
||||
? string.Create(CultureInfo.InvariantCulture, $"{v.FreeBytes / (1L << 30)} GB free of {v.TotalBytes / (1L << 30)} GB")
|
||||
: "free space unknown";
|
||||
var mount = VolumeSpace.MountOf(path);
|
||||
var fileSystem = mount?.FileSystem ?? VolumeSpace.FileSystemOf(path) ?? "file system unknown";
|
||||
return mount is null ? $"{figures}, {fileSystem}" : $"{figures}, {fileSystem} mounted at {mount.MountPoint} from {mount.Source}";
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ public sealed class ServerOptions
|
||||
[
|
||||
("CHRONOS_SERVER_NAME", nameof(ServerName), (o, v) => o.ServerName = v),
|
||||
("CHRONOS_ARCHIVE_PATH", nameof(ArchivePath), (o, v) => o.ArchivePath = v),
|
||||
("CHRONOS_SPACE_PATH", nameof(SpacePath), (o, v) => o.SpacePath = v),
|
||||
("CHRONOS_ADMIN_USER", nameof(AdminUser), (o, v) => o.AdminUser = v),
|
||||
("CHRONOS_ADMIN_PASSWORD", nameof(AdminPassword), (o, v) => o.AdminPassword = v),
|
||||
("CHRONOS_DB", nameof(Database), (o, v) => o.ApplyDatabase(v)),
|
||||
@@ -80,6 +81,16 @@ public sealed class ServerOptions
|
||||
|
||||
public string ServerName { get; set; } = "Chronos Server";
|
||||
public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\ChronosArchive" : "/archive";
|
||||
|
||||
/// <summary>
|
||||
/// A folder whose volume's free space the admin panel shows instead of the archive's (owner review 2, R2; key
|
||||
/// <c>SpacePath</c>, variable <c>CHRONOS_SPACE_PATH</c>). On Unraid the archive is a user share, which reports its
|
||||
/// primary storage (often the cache) while the mover sends the photos to the array: the template maps the share's
|
||||
/// array view (<c>/mnt/user0/<share></c>) read-only to <c>/space</c>. Empty: the archive's volume; a folder that
|
||||
/// cannot be measured falls back to it with one warning. Uploads always check the archive's own volume.
|
||||
/// </summary>
|
||||
public string? SpacePath { get; set; }
|
||||
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Chronos Server") : "/data";
|
||||
public string? AdminUser { get; set; }
|
||||
public string? AdminPassword { get; set; }
|
||||
|
||||
@@ -37,6 +37,8 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
CHRONOS_DB (postgres | sqlite | connection string) CHRONOS_DB_HOST CHRONOS_DB_PORT CHRONOS_DB_NAME CHRONOS_DB_USER
|
||||
CHRONOS_DB_PASSWORD CHRONOS_DB_SSLMODE CHRONOS_HTTP_PORT CHRONOS_HTTPS_PORT CHRONOS_TLS_MODE (auto | pem | proxy)
|
||||
CHRONOS_TLS_CERT CHRONOS_TLS_KEY CHRONOS_LANG
|
||||
CHRONOS_SPACE_PATH folder whose volume's free space the admin panel shows (default: the archive's); on
|
||||
Unraid the share's array view (/mnt/user0/<share>) mapped read-only to /space
|
||||
CHRONOS_PARALLELISM photos the running job processes at once (jobs run one at a time; default: half the
|
||||
cores); CHRONOS_WORKERS, its former name, still sets it
|
||||
CHRONOS_PRIORITY_QUEUE a job of a higher level pauses the running one, which resumes afterwards (true | false)
|
||||
|
||||
@@ -88,6 +88,8 @@ public static class ServerHost
|
||||
+ "they could put a link in place of a folder and redirect the files the server moves. Let only those accounts change it (others may read it).",
|
||||
options.ArchivePath);
|
||||
}
|
||||
// A space path that cannot be measured is warned about at start, not first when someone opens the dashboard.
|
||||
if (!string.IsNullOrWhiteSpace(options.SpacePath)) app.Services.GetRequiredService<VolumeSpace>().Report(archive.Root);
|
||||
if (options.FormerWorkersVariable)
|
||||
{
|
||||
app.Logger.LogWarning("CHRONOS_WORKERS is the former name of CHRONOS_PARALLELISM: jobs now run one at a time, and the value is how many "
|
||||
@@ -112,6 +114,8 @@ public static class ServerHost
|
||||
services.AddSingleton(database);
|
||||
services.AddSingleton(archive);
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
// Tests register their own first, to simulate a full volume.
|
||||
services.TryAddSingleton<VolumeSpace>();
|
||||
services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
|
||||
services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = true);
|
||||
services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
|
||||
|
||||
@@ -30,6 +30,7 @@ public sealed class RenderNodeService(
|
||||
RenderStore renders,
|
||||
JobEngineHost jobs,
|
||||
EventHub events,
|
||||
VolumeSpace volumes,
|
||||
TimeProvider time)
|
||||
{
|
||||
public const string Idle = "idle";
|
||||
@@ -135,7 +136,8 @@ public sealed class RenderNodeService(
|
||||
if (await db.Uploads.FindByJobAsync(jobId, cancellationToken) is { State: UploadState.Receiving } open && open.Sha256 == sha && open.Size == request.Size
|
||||
&& store.Exists(open.Id))
|
||||
return Started(open);
|
||||
if (UploadRules.FreeBytes(options.UploadsPath) is { } free && free < request.Size) return Outcome<StartUploadResponse>.Fail(507, "insufficient_storage");
|
||||
if (volumes.Measure(options.UploadsPath) is { } uploadVolume && uploadVolume.FreeBytes < request.Size)
|
||||
return Outcome<StartUploadResponse>.Fail(507, "insufficient_storage");
|
||||
|
||||
var now = time.GetUtcNow();
|
||||
var upload = await db.Uploads.CreateAsync(new Upload
|
||||
@@ -166,6 +168,7 @@ public sealed class RenderNodeService(
|
||||
if (upload is not { State: UploadState.Receiving } || upload.RenderJson is null) return Outcome<RenderDto>.Fail(409, "upload_state");
|
||||
if (!upload.IsComplete)
|
||||
return Outcome<RenderDto>.Fail(409, "incomplete", (upload.ChunkCount - upload.ReceivedCount).ToString(CultureInfo.InvariantCulture));
|
||||
if (!uploads.ArchiveHasRoom(upload)) return Outcome<RenderDto>.Fail(507, "insufficient_storage");
|
||||
if (!await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Receiving, UploadState.Committing, cancellationToken: cancellationToken))
|
||||
return Outcome<RenderDto>.Fail(409, "upload_state");
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ public sealed class RenderUploads(
|
||||
UploadStore store,
|
||||
RenderStore renders,
|
||||
EventHub events,
|
||||
VolumeSpace volumes,
|
||||
TimeProvider time)
|
||||
{
|
||||
public async Task<Outcome<StartUploadResponse>> StartAsync(Caller caller, Guid sequenceId, RenderUploadRequest request, CancellationToken cancellationToken)
|
||||
@@ -46,7 +47,8 @@ public sealed class RenderUploads(
|
||||
if (await db.Uploads.FindReceivingAsync(caller.Id, sha, cancellationToken) is { } open && open.SequenceId == sequenceId && open.Size == request.Size
|
||||
&& Read(open)?.RenderId == request.RenderId && store.Exists(open.Id))
|
||||
return Started(open);
|
||||
if (UploadRules.FreeBytes(options.UploadsPath) is { } free && free < request.Size) return Outcome<StartUploadResponse>.Fail(507, "insufficient_storage");
|
||||
if (volumes.Measure(options.UploadsPath) is { } uploadVolume && uploadVolume.FreeBytes < request.Size)
|
||||
return Outcome<StartUploadResponse>.Fail(507, "insufficient_storage");
|
||||
|
||||
var now = time.GetUtcNow();
|
||||
var upload = await db.Uploads.CreateAsync(new Upload
|
||||
@@ -77,6 +79,7 @@ public sealed class RenderUploads(
|
||||
if (upload.State != UploadState.Receiving) return Outcome<RenderDto>.Fail(409, "upload_state");
|
||||
if (!upload.IsComplete)
|
||||
return Outcome<RenderDto>.Fail(409, "incomplete", (upload.ChunkCount - upload.ReceivedCount).ToString(CultureInfo.InvariantCulture));
|
||||
if (!uploads.ArchiveHasRoom(upload)) return Outcome<RenderDto>.Fail(507, "insufficient_storage");
|
||||
if (!await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Receiving, UploadState.Committing, cancellationToken: cancellationToken))
|
||||
return Outcome<RenderDto>.Fail(409, "upload_state");
|
||||
|
||||
|
||||
@@ -66,17 +66,4 @@ public static class UploadRules
|
||||
|
||||
/// <summary>The session key an upload without a sequence is grouped by: the client's, or one per user.</summary>
|
||||
public static string SessionKeyOf(string? sessionKey, Guid userId) => sessionKey ?? "user-" + userId.ToString("N");
|
||||
|
||||
/// <summary>Free bytes on the volume holding <paramref name="path"/>, or null when the platform cannot tell.</summary>
|
||||
public static long? FreeBytes(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new DriveInfo(Path.GetFullPath(path)).AvailableFreeSpace;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,10 @@ namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Chunked, resumable, hash-verified frame uploads (BRIEF §14.4): start (short-circuit on a known SHA-256 held by an
|
||||
/// intact frame, resume an unfinished upload, quota and disk checks), idempotent chunks, and completion that stages the
|
||||
/// file on the archive volume, verifies its hash and hands it to <see cref="IArchiveIngest"/>, which repairs a missing or
|
||||
/// damaged frame of that content (no quota is charged for a repair: the archive already counts those bytes).
|
||||
/// intact frame, resume an unfinished upload, quota and disk checks), idempotent chunks, and completion that checks the
|
||||
/// archive volume's free space, stages the file there, verifies its hash and hands it to <see cref="IArchiveIngest"/>,
|
||||
/// which repairs a missing or damaged frame of that content (no quota is charged for a repair: the archive already
|
||||
/// counts those bytes).
|
||||
/// </summary>
|
||||
public sealed class UploadService(
|
||||
ChronosDatabase db,
|
||||
@@ -29,11 +30,12 @@ public sealed class UploadService(
|
||||
IArchiveIngest ingest,
|
||||
SequenceJobs sequenceJobs,
|
||||
EventHub events,
|
||||
VolumeSpace volumes,
|
||||
IHostApplicationLifetime lifetime,
|
||||
TimeProvider time,
|
||||
ILogger<UploadService> logger)
|
||||
{
|
||||
/// <summary>Space kept free on the upload volume beyond the announced size.</summary>
|
||||
/// <summary>Space kept free on the upload and archive volumes beyond an upload's size.</summary>
|
||||
private const long DiskReserve = 64L * 1024 * 1024;
|
||||
|
||||
/// <summary>Card events one account may publish per minute: progress once a second leaves room for every start and end.</summary>
|
||||
@@ -74,7 +76,7 @@ public sealed class UploadService(
|
||||
if (caller.User.UsedBytes + pending + request.Size > caller.User.QuotaBytes)
|
||||
return Fail<StartUploadResponse>(403, "quota_exceeded", caller.User.QuotaBytes.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
if (UploadRules.FreeBytes(options.UploadsPath) is { } free && free < request.Size + DiskReserve)
|
||||
if (volumes.Measure(options.UploadsPath) is { } uploadVolume && uploadVolume.FreeBytes < request.Size + DiskReserve)
|
||||
return Fail<StartUploadResponse>(507, "insufficient_storage");
|
||||
|
||||
var now = time.GetUtcNow();
|
||||
@@ -165,6 +167,7 @@ public sealed class UploadService(
|
||||
if (upload.State != UploadState.Receiving) return Fail<CompleteUploadResponse>(409, "upload_state");
|
||||
if (!upload.IsComplete)
|
||||
return Fail<CompleteUploadResponse>(409, "incomplete", (upload.ChunkCount - upload.ReceivedCount).ToString(CultureInfo.InvariantCulture));
|
||||
if (!ArchiveHasRoom(upload)) return Fail<CompleteUploadResponse>(507, "insufficient_storage");
|
||||
if (!await db.Uploads.TryTransitionAsync(id, UploadState.Receiving, UploadState.Committing, cancellationToken: stopping))
|
||||
return Fail<CompleteUploadResponse>(409, "upload_state");
|
||||
|
||||
@@ -240,9 +243,24 @@ public sealed class UploadService(
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The archive volume has room for <paramref name="upload"/> and the reserve: completing it copies the file into the
|
||||
/// staging folder there (<see cref="StageVerifiedAsync"/>). Checked before the upload leaves the receiving state, so a
|
||||
/// refused completion (507) can be repeated once there is room. A volume that cannot be measured refuses nothing.
|
||||
/// </summary>
|
||||
public bool ArchiveHasRoom(Upload upload)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(upload);
|
||||
if (volumes.Measure(archive.Root) is not { } volume || volume.FreeBytes >= upload.Size + DiskReserve) return true;
|
||||
logger.LogWarning("The archive volume {Archive} has {Free} bytes free: upload {Upload} ({File}, {Size} bytes) waits for room",
|
||||
archive.Root, volume.FreeBytes, upload.Id, upload.FileName, upload.Size);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a fully received upload to the archive staging folder and checks its SHA-256. On a mismatch the upload
|
||||
/// fails, its files are deleted and null is returned; the client starts over.
|
||||
/// fails, its files are deleted and null is returned; the client starts over. Callers check
|
||||
/// <see cref="ArchiveHasRoom"/> first.
|
||||
/// </summary>
|
||||
public async Task<string?> StageVerifiedAsync(Upload upload, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
using System.Text;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>Free and total bytes of a volume.</summary>
|
||||
public sealed record VolumeFigures(long FreeBytes, long TotalBytes);
|
||||
|
||||
/// <summary>One mount of <c>/proc/self/mountinfo</c>: its mount point, filesystem type (<c>fuse.shfs</c>) and source.</summary>
|
||||
public sealed record MountEntry(string MountPoint, string FileSystem, string Source);
|
||||
|
||||
/// <summary>
|
||||
/// The archive's storage as the admin panel shows it: the space volume's figures (<see cref="ServerOptions.SpacePath"/>
|
||||
/// when set and measurable, else the archive root) and filesystem, plus the archive root's own figures (the write
|
||||
/// volume) when a space path is in use and they differ.
|
||||
/// </summary>
|
||||
public sealed record StorageReport(VolumeFigures? Space, string? FileSystem, bool FromSpacePath, VolumeFigures? Write);
|
||||
|
||||
/// <summary>
|
||||
/// Free space of the server's folders (owner review 2, R2). The archive root is where uploads are staged and filed; on
|
||||
/// Unraid it is a user share (FUSE <c>shfs</c>) that reports the share's primary storage, often the cache, while the
|
||||
/// mover sends the photos to the array. <see cref="ServerOptions.SpacePath"/> names a folder whose volume the admin panel
|
||||
/// shows instead (the share seen on the array only). Tests replace <see cref="Measure"/> to simulate a full volume.
|
||||
/// </summary>
|
||||
public class VolumeSpace(ServerOptions options, ILogger<VolumeSpace> logger)
|
||||
{
|
||||
/// <summary>Two reads of one volume a moment apart differ by what was written in between.</summary>
|
||||
private const long SameVolumeSlack = 64L * 1024 * 1024;
|
||||
|
||||
private const string MountInfo = "/proc/self/mountinfo";
|
||||
|
||||
/// <summary>1 while the space path cannot be measured: it is warned about once, not at every request.</summary>
|
||||
private int _spaceUnavailable;
|
||||
|
||||
/// <summary>Free and total bytes of the volume holding <paramref name="path"/>; null when the folder is missing or the platform cannot tell.</summary>
|
||||
public virtual VolumeFigures? Measure(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(path)) return null;
|
||||
var drive = Drive(path);
|
||||
return new VolumeFigures(drive.AvailableFreeSpace, drive.TotalSize);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The storage figures of the archive at <paramref name="archiveRoot"/>: of the space path when one is set and can be
|
||||
/// measured, else of the archive root (a space path that cannot be measured is logged once, until it can again).
|
||||
/// </summary>
|
||||
public StorageReport Report(string archiveRoot)
|
||||
{
|
||||
var write = Measure(archiveRoot);
|
||||
var spacePath = options.SpacePath;
|
||||
if (string.IsNullOrWhiteSpace(spacePath)) return new StorageReport(write, FileSystemOf(archiveRoot), FromSpacePath: false, Write: null);
|
||||
if (Measure(spacePath) is not { } space)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _spaceUnavailable, 1) == 0)
|
||||
{
|
||||
logger.LogWarning("The space path {SpacePath} (CHRONOS_SPACE_PATH) is missing or cannot be measured: the admin panel shows the free space "
|
||||
+ "of the archive {Archive} instead. Map the folder into the container, or clear the setting.", spacePath, archiveRoot);
|
||||
}
|
||||
return new StorageReport(write, FileSystemOf(archiveRoot), FromSpacePath: false, Write: null);
|
||||
}
|
||||
if (Interlocked.Exchange(ref _spaceUnavailable, 0) == 1) logger.LogInformation("The space path {SpacePath} can be measured again", spacePath);
|
||||
var differs = write is not null && (write.TotalBytes != space.TotalBytes || Math.Abs(write.FreeBytes - space.FreeBytes) > SameVolumeSlack);
|
||||
return new StorageReport(space, FileSystemOf(spacePath), FromSpacePath: true, differs ? write : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The type of the filesystem holding the folder <paramref name="path"/>: on Linux the mount's type (an Unraid user
|
||||
/// share is <c>fuse.shfs</c>, which the kernel's own figures call only FUSE), elsewhere what the system reports
|
||||
/// (NTFS). Null when the folder is missing or the type unknown.
|
||||
/// </summary>
|
||||
public static string? FileSystemOf(string path)
|
||||
{
|
||||
if (!Directory.Exists(path)) return null;
|
||||
if (MountOf(path) is { } mount) return mount.FileSystem;
|
||||
try
|
||||
{
|
||||
return Drive(path).DriveFormat;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The mount holding the folder <paramref name="path"/>, read from <c>/proc/self/mountinfo</c>; null off Linux, when
|
||||
/// the folder is missing or the file cannot be read.
|
||||
/// </summary>
|
||||
public static MountEntry? MountOf(string path)
|
||||
{
|
||||
if (!OperatingSystem.IsLinux() || !Directory.Exists(path)) return null;
|
||||
try
|
||||
{
|
||||
return FindMount(File.ReadAllText(MountInfo), Path.GetFullPath(path));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The mount of <paramref name="mountInfo"/> (the text of <c>/proc/self/mountinfo</c>) that holds the absolute
|
||||
/// <paramref name="path"/>: the longest mount point that is the path or one of its parent folders and, of mounts
|
||||
/// stacked on that point, the last listed (the one on top). Null when no line covers it.
|
||||
/// </summary>
|
||||
public static MountEntry? FindMount(string mountInfo, string path)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mountInfo);
|
||||
ArgumentNullException.ThrowIfNull(path);
|
||||
var target = path.TrimEnd('/');
|
||||
if (target.Length == 0) target = "/";
|
||||
MountEntry? best = null;
|
||||
foreach (var line in mountInfo.Split('\n'))
|
||||
{
|
||||
if (ParseMountLine(line) is not { } entry || !Covers(entry.MountPoint, target)) continue;
|
||||
if (best is null || entry.MountPoint.Length >= best.MountPoint.Length) best = entry;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One mountinfo line (proc(5)): <c>id parent major:minor root mount-point options [optional fields…] - type source
|
||||
/// super-options</c>, where fields write a space, tab, newline or backslash as an octal escape (<c>\040</c>). Null when
|
||||
/// the line has another shape.
|
||||
/// </summary>
|
||||
public static MountEntry? ParseMountLine(string line)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(line);
|
||||
var fields = line.TrimEnd('\r').Split(' ');
|
||||
if (fields.Length < 9) return null;
|
||||
// The optional fields (none or more, "shared:5 master:1") end at a lone "-".
|
||||
var separator = Array.IndexOf(fields, "-", 6);
|
||||
if (separator < 0 || separator + 2 >= fields.Length) return null;
|
||||
var mountPoint = Unescape(fields[4]);
|
||||
if (!mountPoint.StartsWith('/')) return null;
|
||||
return new MountEntry(mountPoint, Unescape(fields[separator + 1]), Unescape(fields[separator + 2]));
|
||||
}
|
||||
|
||||
/// <summary>Windows wants a drive root; Unix accepts any folder and reports the filesystem it is on.</summary>
|
||||
private static DriveInfo Drive(string path)
|
||||
{
|
||||
var full = Path.GetFullPath(path);
|
||||
return new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(full)! : full);
|
||||
}
|
||||
|
||||
/// <summary><paramref name="mountPoint"/> is <paramref name="path"/> or one of its parent folders.</summary>
|
||||
private static bool Covers(string mountPoint, string path) =>
|
||||
mountPoint == "/"
|
||||
? path.StartsWith('/')
|
||||
: path.StartsWith(mountPoint, StringComparison.Ordinal) && (path.Length == mountPoint.Length || path[mountPoint.Length] == '/');
|
||||
|
||||
/// <summary>Decodes the kernel's <c>\ooo</c> escapes (it escapes only ASCII characters).</summary>
|
||||
private static string Unescape(string field)
|
||||
{
|
||||
if (!field.Contains('\\', StringComparison.Ordinal)) return field;
|
||||
var sb = new StringBuilder(field.Length);
|
||||
for (var i = 0; i < field.Length; i++)
|
||||
{
|
||||
if (field[i] == '\\' && i + 3 < field.Length && IsOctal(field[i + 1]) && IsOctal(field[i + 2]) && IsOctal(field[i + 3]))
|
||||
{
|
||||
sb.Append((char)(((field[i + 1] - '0') * 64) + ((field[i + 2] - '0') * 8) + (field[i + 3] - '0')));
|
||||
i += 3;
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append(field[i]);
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static bool IsOctal(char c) => c is >= '0' and <= '7';
|
||||
}
|
||||
Reference in new issue
Block a user