feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job. - One naming rule (FrameNaming) for import, upload and Reorganize. - Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder. - Writers refuse a folder another program moved or gave to another sequence. - Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules. - Phase 3 docs and translations merged; strings in all 38 languages. 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 #12.
This commit is contained in:
1 parent
9aa818ed47
commit
7e4a3b481d
416 files changed
+15304
-1572
No files matched your search
@@ -294,6 +294,10 @@ dialog.dialog p { margin: 0; color: var(--text-muted); }
|
||||
#toasts { position: fixed; inset-inline-end: 24px; bottom: 24px; display: grid; gap: 8px; z-index: 10; }
|
||||
.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); }
|
||||
/* A toast with an action (Open job, Reorganize…): the message, then its link or button at the inline end. */
|
||||
.toast.with-action { display: flex; align-items: center; gap: 12px; }
|
||||
.toast.with-action > span { flex: 1 1 auto; min-width: 0; }
|
||||
.toast.with-action > .btn { flex: none; }
|
||||
|
||||
/* Directional glyphs (icons.js) point along the reading direction; inside a left-to-right island (photos, time) they do not turn. */
|
||||
svg.directional:dir(rtl) { transform: scaleX(-1); }
|
||||
@@ -422,6 +426,35 @@ dialog.upload.dragging .drop { border-color: var(--accent); background: var(--ac
|
||||
.upload-total { display: flex; align-items: center; gap: 12px; font-size: 12px; }
|
||||
.upload-total .progress-cell { flex: 1 1 0; }
|
||||
|
||||
/* Reorganize dialog (owner review 2, R7, reorganize.js): a switch and a field per template, the dry run's totals and its
|
||||
steps (title, folder and renamed files, the old value struck through above the new one); paths stay left to right. */
|
||||
dialog.dialog.reorganize { width: 960px; }
|
||||
.reorg-fields { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 14px; align-items: center; }
|
||||
.reorg-fields .field-error { grid-column: 2; color: var(--error); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.reorg-fields .field-error:empty { display: none; }
|
||||
.reorg-totals { min-height: 18px; color: var(--text-muted); }
|
||||
.reorg-preview { max-height: 46vh; overflow: auto; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--bg); }
|
||||
.reorg-preview:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.reorg-preview.stale .table { opacity: .55; }
|
||||
.table.reorg { grid-template-columns: minmax(120px, 1fr) minmax(160px, 1.3fr) minmax(160px, 1.3fr); font-size: 12px; }
|
||||
.table.reorg .thead { position: sticky; top: 0; z-index: 1; padding: 8px 12px; background: var(--bg); }
|
||||
.table.reorg .row { min-height: 0; padding: 8px 12px; align-items: start; }
|
||||
.table.reorg .row:hover { background: none; }
|
||||
.table.reorg .row:last-child { border-bottom: 0; }
|
||||
.table.reorg .pill { align-self: flex-start; margin-block-start: 4px; }
|
||||
.change { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.change .was { color: var(--text-muted); text-decoration: line-through; }
|
||||
.path { font-family: var(--mono); overflow-wrap: anywhere; }
|
||||
.reorg-samples, .reorg-kept { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 2px; }
|
||||
.reorg-samples { color: var(--text-muted); }
|
||||
.reorg-kept { color: var(--warning); }
|
||||
.reorg-preview .table-foot { padding: 8px 12px; border-top: 1px solid var(--stroke); }
|
||||
/* Narrow windows: each step's cells one under the other; the column names stay for screen readers. */
|
||||
@media (max-width: 700px) {
|
||||
.table.reorg { grid-template-columns: minmax(0, 1fr); }
|
||||
.table.reorg .thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
}
|
||||
|
||||
/* 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; }
|
||||
|
||||
@@ -74,6 +74,12 @@ export function detailText(entry) {
|
||||
const [count, size] = details.split(" · ");
|
||||
return /^\d+$/.test(count) && /^\d+$/.test(size ?? "") ? `${plural("Admin.Trash.EntryCount", Number(count))} · ${formatBytes(Number(size))}` : details;
|
||||
}
|
||||
// Owner review 2, R7: "sequences · files · folder template · file template · title template", a template empty when kept.
|
||||
case "archive_reorganized": {
|
||||
const [sequences, files, ...templates] = details.split(" · ");
|
||||
if (!/^\d+$/.test(sequences) || !/^\d+$/.test(files ?? "")) return details;
|
||||
return [plural("Admin.Library.Count", Number(sequences)), plural("Admin.Reorganize.FilesRenamed", Number(files)), ...templates.filter(Boolean)].join(" · ");
|
||||
}
|
||||
default:
|
||||
return details;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics, and the way to the
|
||||
// archive's trash (the Library's trash view, owner review 2, R6).
|
||||
// archive's trash (the Library's trash view, owner review 2, R6). New folder or file templates apply to new sequences; the
|
||||
// toast of their save offers Reorganize (R7) to apply them to the sequences already in the archive.
|
||||
import { t, plural, applyStrings } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, bar, storageTip, writeVolumeLine, columns, toast, errorText, emptyState, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js";
|
||||
import { openReorganize } from "../reorganize.js";
|
||||
|
||||
const PROXY_SIZES = [-1, 1280, 1920, 2560, 3840, 0];
|
||||
const ACTIONS = ["scan", "rebuild", "verify", "maintenance"];
|
||||
@@ -71,6 +73,7 @@ export async function render(root, { api, setMeta }) {
|
||||
e.preventDefault();
|
||||
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
|
||||
const data = new FormData(form);
|
||||
const before = settings;
|
||||
try {
|
||||
settings = await api.put("/api/v1/archive/settings", {
|
||||
...settings,
|
||||
@@ -86,11 +89,13 @@ export async function render(root, { api, setMeta }) {
|
||||
form.querySelectorAll("option").forEach((option) => {
|
||||
option.defaultSelected = option.selected;
|
||||
});
|
||||
toast(t("Admin.Common.Saved"));
|
||||
savedToast(before, settings);
|
||||
} catch (err) {
|
||||
// Errors name the field in details; the field gets the error border and the message as its tooltip.
|
||||
const field = err.details && form.elements[err.details];
|
||||
const message = field ? invalidText(field) : errorText(err);
|
||||
// Errors name the field in details, a template followed by the rule it breaks ("fileTemplate:extension"); the field
|
||||
// gets the error border and the message as its tooltip: for a broken rule the server's, which says why.
|
||||
const [name, rule] = String(err.details ?? "").split(":");
|
||||
const field = name && form.elements[name];
|
||||
const message = field ? (rule && err.message ? err.message : invalidText(field)) : errorText(err);
|
||||
if (field) {
|
||||
markInvalid(field, message);
|
||||
field.focus();
|
||||
@@ -98,6 +103,28 @@ export async function render(root, { api, setMeta }) {
|
||||
toast(message, true);
|
||||
}
|
||||
});
|
||||
/**
|
||||
* Saved; when the folder or file template changed and the archive has sequences, the toast offers Reorganize for all of
|
||||
* them with the saved templates, the changed ones switched on.
|
||||
*/
|
||||
function savedToast(before, saved) {
|
||||
const changed = [["folder", "folderTemplate"], ["file", "fileTemplate"]].filter(([, field]) => before[field] !== saved[field]).map(([part]) => part);
|
||||
if (changed.length === 0 || stats.sequences === 0) {
|
||||
toast(t("Admin.Common.Saved"));
|
||||
return;
|
||||
}
|
||||
toast(t("Admin.Common.Saved"), false, {
|
||||
label: t("Admin.Reorganize.Offer"),
|
||||
tip: t("Admin.Reorganize.Offer.Tip"),
|
||||
run: () => openReorganize({
|
||||
api,
|
||||
target: { all: true },
|
||||
templates: { folderTemplate: saved.folderTemplate, fileTemplate: saved.fileTemplate, titleTemplate: saved.titleTemplate ?? "" },
|
||||
use: changed,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
root.querySelectorAll("[data-action]").forEach((button) => button.addEventListener("click", async () => {
|
||||
button.disabled = true;
|
||||
try {
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
// Library (owner review 2, R6; BRIEF §14.8): the panel browses, views and deletes sequences and photos and runs mass
|
||||
// operations on them, but never edits a video (no settings, no render). #/library lists the sequences with filters in the
|
||||
// address, #/library?id=<sequence> opens one (library/sequence.js), #/library?view=trash the archive's trash (library/trash.js).
|
||||
// Reorganize (R7) applies new folder, file and title templates to the selection (reorganize.js).
|
||||
import { t, plural, applyStrings } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, toast, errorText, confirmDialog, formDialog, markInvalid, emptyState, routeParams, redraw } from "../ui.js";
|
||||
import { icons } from "../icons.js";
|
||||
import { BULK_LIMIT, factsLine, captureText, cameraLabel, statusChips, lazyImage, watchImages, Selection, selectableGrid, chunks, saveFile, sequencesCsv, today, tagList, coverUrl, listed, JOB_ENDED } from "./library/shared.js";
|
||||
import { renderSequence } from "./library/sequence.js";
|
||||
import { renderTrash } from "./library/trash.js";
|
||||
import { openReorganize } from "../reorganize.js";
|
||||
|
||||
const VIEW_KEY = "chronos.admin.library.view";
|
||||
const PAGE = 100;
|
||||
@@ -256,8 +258,7 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
|
||||
if (rows.length === 0) {
|
||||
itemsHost.removeAttribute("role");
|
||||
itemsHost.removeAttribute("aria-multiselectable");
|
||||
const filtered = FILTERS.some((f) => f !== "sort" && filters[f]);
|
||||
itemsHost.innerHTML = filtered
|
||||
itemsHost.innerHTML = isFiltered()
|
||||
? emptyState("Admin.Library.NoMatch", `<button class="btn small" id="clear" data-i18n="Admin.Library.ClearFilters" data-i18n-title="Admin.Library.ClearFilters.Tip"></button>`)
|
||||
: emptyState("Admin.Library.Empty", `<button class="btn small" id="scan" data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`);
|
||||
applyStrings(itemsHost);
|
||||
@@ -343,6 +344,7 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
|
||||
<strong class="nowrap" role="status">${escapeHtml(plural("Admin.Library.Selected", selection.size))}</strong>${selectAll}
|
||||
<span class="spacer"></span>
|
||||
${JOBS.map(job).join("")}
|
||||
<button class="btn small" id="mass-reorganize" data-mass="reorganize" data-i18n="Admin.Reorganize.Action" data-i18n-title="Admin.Reorganize.Action.Tip"></button>
|
||||
<button class="btn small" id="mass-retag" data-mass="retag" data-i18n="Admin.Library.Retag" data-i18n-title="Admin.Library.Retag.Tip"></button>
|
||||
<button class="btn small" id="mass-csv" data-mass="csv" data-i18n="Admin.Library.ExportCsv" data-i18n-title="Admin.Library.ExportCsv.Tip"></button>
|
||||
<button class="btn small destructive" id="mass-delete" data-mass="delete" data-i18n="Admin.Library.Delete" data-i18n-title="Admin.Library.Delete.Tip"></button>
|
||||
@@ -362,6 +364,8 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
|
||||
}
|
||||
if (action === "all") return selectAll();
|
||||
if (action === "csv") return exportCsv();
|
||||
// A modal dialog: the button stays enabled, so the focus comes back to it when the dialog closes.
|
||||
if (action === "reorganize") return reorganize();
|
||||
button.disabled = true;
|
||||
try {
|
||||
if (action === "job") await queueJobs(button.dataset.kind);
|
||||
@@ -415,6 +419,28 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
|
||||
toast([done, skipped > 0 ? plural("Admin.Library.Skipped", skipped) : "", failure ?? ""].filter(Boolean).join(" · "), failure !== null);
|
||||
}
|
||||
|
||||
/** Whether a filter narrows the list (the sort order does not). */
|
||||
function isFiltered() {
|
||||
return FILTERS.some((f) => f !== "sort" && filters[f]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reorganize (owner review 2, R7) of the selected sequences: their ids, at most a bulk request's thousand (one plan,
|
||||
* one job). Beyond that, every sequence of the archive, but only while the selection is exactly what Select all
|
||||
* fetched without a filter and the archive has not grown since: a sequence unticked or added later is never included.
|
||||
*/
|
||||
async function reorganize() {
|
||||
const ids = [...selection.ids];
|
||||
const everything = ids.length > BULK_LIMIT && matching !== null && !isFiltered() && total === matching.length &&
|
||||
ids.length === matching.length && matching.every((s) => selection.has(s.id));
|
||||
if (!everything && ids.length > BULK_LIMIT) {
|
||||
toast(t("Admin.Reorganize.TooMany", formatNumber(BULK_LIMIT)), true);
|
||||
return;
|
||||
}
|
||||
const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle]));
|
||||
await openReorganize({ api, target: everything ? { all: true } : { sequenceIds: ids }, names });
|
||||
}
|
||||
|
||||
async function retag() {
|
||||
const datalist = facets.tags.map((f) => `<option value="${attr(f.value)}"></option>`).join("");
|
||||
const data = await formDialog({
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
// Reorganize dialog of the admin panel (owner review 2, R7; BRIEF §12.5, §14.8): folder, file and title templates applied
|
||||
// to sequences already in the archive, the Library's selection or every sequence. Each change of a template asks the
|
||||
// server for a dry run (nothing is touched) and the table shows what every sequence becomes, in the order the changes
|
||||
// apply. Apply confirms that very plan by its fingerprint, and the server runs it as a job (kind "move") that moves and
|
||||
// renames the originals, never overwriting or deleting one (only photos whose SHA-256 is known get new names).
|
||||
import { t, plural, applyStrings } from "./i18n.js";
|
||||
import { escapeHtml, attr, formatNumber, toast, errorText, confirmDialog, markInvalid, clearInvalid } from "./ui.js";
|
||||
|
||||
const ENDPOINT = "/api/v1/archive/reorganize";
|
||||
/** Wait after the last keystroke before the dry run, and the steps the table draws at a time. */
|
||||
const PLAN_DELAY = 400;
|
||||
const PAGE = 200;
|
||||
/** The parts a Reorganize changes: the template's request field, its switch and its field, with their strings. */
|
||||
const PARTS = [
|
||||
{ key: "folder", field: "folderTemplate", label: "Admin.Reorganize.Folders", use: "Admin.Reorganize.Folders.Tip", tip: "Admin.Reorganize.FolderTemplate.Tip" },
|
||||
{ key: "file", field: "fileTemplate", label: "Admin.Reorganize.Files", use: "Admin.Reorganize.Files.Tip", tip: "Admin.Reorganize.FileTemplate.Tip" },
|
||||
{ key: "title", field: "titleTemplate", label: "Admin.Reorganize.Titles", use: "Admin.Reorganize.Titles.Tip", tip: "Admin.Reorganize.TitleTemplate.Tip" },
|
||||
];
|
||||
|
||||
let dialogs = 0;
|
||||
|
||||
/**
|
||||
* Opens the Reorganize dialog. target is { all: true } (every sequence of the archive) or { sequenceIds } (at most a
|
||||
* bulk request's thousand); names maps sequence ids to the titles the page shows. templates ({ folderTemplate,
|
||||
* fileTemplate, titleTemplate }) fills the fields, else the archive's settings do; use lists the parts switched on
|
||||
* ("folder", "file", "title"), else those with a template. Resolves when the dialog closes: the queued job, or null.
|
||||
*/
|
||||
export function openReorganize({ api, target, names = new Map(), templates = null, use = null } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const id = `reorganize-${++dialogs}`;
|
||||
/** The last dry run, with key: the request it answers. */
|
||||
let plan = null;
|
||||
let shown = PAGE;
|
||||
let timer = null;
|
||||
let planning = false;
|
||||
let again = false;
|
||||
let loaded = false;
|
||||
let busy = false;
|
||||
let queued = null;
|
||||
/** A message the next plan shows (why the plan was made again). */
|
||||
let notice = "";
|
||||
const title = target.all ? t("Admin.Reorganize.TitleAll") : plural("Admin.Reorganize.Title", target.sequenceIds.length);
|
||||
|
||||
const dialog = document.createElement("dialog");
|
||||
dialog.className = "dialog reorganize";
|
||||
dialog.setAttribute("aria-labelledby", `${id}-title`);
|
||||
dialog.innerHTML = `
|
||||
<form novalidate>
|
||||
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
|
||||
<div class="reorg-fields">${PARTS.map((p) => `
|
||||
<label class="check"><input type="checkbox" data-part="${p.key}" disabled title="${attr(t(p.use))}"><span>${escapeHtml(t(p.label))}</span></label>
|
||||
<input class="input mono" name="${p.field}" dir="ltr" spellcheck="false" autocomplete="off" disabled
|
||||
aria-label="${attr(t(p.label))}" aria-describedby="${id}-${p.key}-error" title="${attr(t(p.tip))}">
|
||||
<span class="field-error" id="${id}-${p.key}-error" data-error="${p.key}"></span>`).join("")}
|
||||
</div>
|
||||
<div class="reorg-totals" role="status"></div>
|
||||
<div class="reorg-preview" role="region" tabindex="0" aria-label="${attr(t("Admin.Reorganize.Preview"))}" title="${attr(t("Admin.Reorganize.Preview.Tip"))}" hidden>
|
||||
<div class="table reorg" role="table" aria-label="${attr(t("Admin.Reorganize.Preview"))}">
|
||||
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Reorganize.Column.Sequence"></span>
|
||||
<span role="columnheader" data-i18n="Admin.Reorganize.Column.Folder"></span><span role="columnheader" data-i18n="Admin.Reorganize.Column.Files"></span></div>
|
||||
<div role="rowgroup" class="reorg-rows"></div>
|
||||
</div>
|
||||
<div class="table-foot" hidden><span class="muted reorg-shown"></span><span class="spacer"></span>
|
||||
<button class="btn small" type="button" data-act="more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>
|
||||
</div>
|
||||
<div class="error" role="alert"></div>
|
||||
<div class="buttons">
|
||||
<button class="btn" type="button" data-act="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Reorganize.Cancel.Tip"></button>
|
||||
<button class="btn primary" type="button" data-act="apply" disabled data-i18n="Admin.Reorganize.Apply" data-i18n-title="Admin.Reorganize.Apply.Tip"></button>
|
||||
</div>
|
||||
</form>`;
|
||||
document.body.appendChild(dialog);
|
||||
applyStrings(dialog);
|
||||
const form = dialog.querySelector("form");
|
||||
const totals = dialog.querySelector(".reorg-totals");
|
||||
const preview = dialog.querySelector(".reorg-preview");
|
||||
const rows = dialog.querySelector(".reorg-rows");
|
||||
const foot = dialog.querySelector(".table-foot");
|
||||
const shownText = dialog.querySelector(".reorg-shown");
|
||||
const errorLine = dialog.querySelector(".error");
|
||||
const closeButton = dialog.querySelector('[data-act="close"]');
|
||||
const applyButton = dialog.querySelector('[data-act="apply"]');
|
||||
const check = (p) => dialog.querySelector(`[data-part="${p.key}"]`);
|
||||
const input = (p) => form.elements[p.field];
|
||||
const errorHost = (p) => dialog.querySelector(`[data-error="${p.key}"]`);
|
||||
|
||||
for (const p of PARTS) {
|
||||
check(p).addEventListener("change", () => {
|
||||
clearField(p);
|
||||
showError("");
|
||||
drawButtons();
|
||||
// A part switched on without a template: its field is where the next step is.
|
||||
if (check(p).checked && input(p).value.trim() === "") {
|
||||
input(p).focus();
|
||||
clearTimeout(timer);
|
||||
preview.classList.add("stale");
|
||||
return;
|
||||
}
|
||||
schedule(0);
|
||||
});
|
||||
input(p).addEventListener("input", () => {
|
||||
clearField(p);
|
||||
showError("");
|
||||
schedule(PLAN_DELAY);
|
||||
});
|
||||
}
|
||||
// Enter in a template plans at once (a form of several fields without a submit button never submits on Enter);
|
||||
// only the Apply button changes anything.
|
||||
form.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter" || e.isComposing || !(e.target instanceof HTMLInputElement) || e.target.type === "checkbox") return;
|
||||
e.preventDefault();
|
||||
if (loaded && !busy) schedule(0);
|
||||
});
|
||||
form.addEventListener("submit", (e) => e.preventDefault());
|
||||
closeButton.addEventListener("click", () => {
|
||||
if (!busy) dialog.close();
|
||||
});
|
||||
applyButton.addEventListener("click", apply);
|
||||
dialog.querySelector('[data-act="more"]').addEventListener("click", () => {
|
||||
shown += PAGE;
|
||||
drawRows();
|
||||
if (foot.hidden) preview.focus();
|
||||
});
|
||||
// Esc closes, except while the change is being sent.
|
||||
dialog.addEventListener("cancel", (e) => {
|
||||
if (busy) e.preventDefault();
|
||||
});
|
||||
const signedOut = () => dialog.close();
|
||||
window.addEventListener("chronos:signed-out", signedOut);
|
||||
dialog.addEventListener("close", () => {
|
||||
clearTimeout(timer);
|
||||
window.removeEventListener("chronos:signed-out", signedOut);
|
||||
dialog.remove();
|
||||
resolve(queued);
|
||||
});
|
||||
dialog.showModal();
|
||||
start();
|
||||
|
||||
/** The templates to start from: given, or the archive's settings (and its title template when it has one). */
|
||||
async function start() {
|
||||
let values = templates;
|
||||
if (!values) {
|
||||
try {
|
||||
const settings = await api.get("/api/v1/archive/settings");
|
||||
values = { folderTemplate: settings.folderTemplate, fileTemplate: settings.fileTemplate, titleTemplate: settings.titleTemplate ?? "" };
|
||||
} catch (err) {
|
||||
showError(errorText(err));
|
||||
values = {};
|
||||
}
|
||||
}
|
||||
if (!dialog.open) return;
|
||||
const on = new Set(use ?? PARTS.filter((p) => String(values[p.field] ?? "").trim() !== "").map((p) => p.key));
|
||||
for (const p of PARTS) {
|
||||
input(p).value = values[p.field] ?? "";
|
||||
check(p).checked = on.has(p.key);
|
||||
}
|
||||
loaded = true;
|
||||
drawButtons();
|
||||
(PARTS.map(input).find((field) => !field.disabled) ?? check(PARTS[0])).focus();
|
||||
schedule(0);
|
||||
}
|
||||
|
||||
/** The request the fields make (without dryRun); null when no part is switched on. */
|
||||
function request() {
|
||||
const body = target.all ? { all: true } : { all: false, sequenceIds: target.sequenceIds };
|
||||
let any = false;
|
||||
for (const p of PARTS) {
|
||||
if (!check(p).checked) continue;
|
||||
body[p.field] = input(p).value.trim();
|
||||
any = true;
|
||||
}
|
||||
return any ? body : null;
|
||||
}
|
||||
|
||||
function keyNow() {
|
||||
return JSON.stringify(request());
|
||||
}
|
||||
|
||||
/** Plans again after delay ms; what the table shows until then no longer matches the fields. */
|
||||
function schedule(delay) {
|
||||
clearTimeout(timer);
|
||||
preview.classList.add("stale");
|
||||
drawButtons();
|
||||
timer = setTimeout(runPlan, delay);
|
||||
}
|
||||
|
||||
/** One dry run at a time: a change made while one is answered plans again right after it. */
|
||||
async function runPlan() {
|
||||
if (!loaded || !dialog.open) return;
|
||||
if (planning) {
|
||||
again = true;
|
||||
return;
|
||||
}
|
||||
const body = request();
|
||||
const blank = PARTS.find((p) => check(p).checked && input(p).value.trim() === "");
|
||||
if (!body || blank) {
|
||||
plan = null;
|
||||
if (blank) fieldError(blank, t("Admin.Reorganize.Blank"));
|
||||
drawPlan();
|
||||
return;
|
||||
}
|
||||
const key = JSON.stringify(body);
|
||||
planning = true;
|
||||
totals.textContent = t("Admin.Reorganize.Planning");
|
||||
drawButtons();
|
||||
try {
|
||||
const answer = await api.post(ENDPOINT, { ...body, dryRun: true });
|
||||
if (!dialog.open) return;
|
||||
plan = { ...answer, key };
|
||||
shown = PAGE;
|
||||
PARTS.forEach(clearField);
|
||||
showError(notice);
|
||||
notice = "";
|
||||
} catch (err) {
|
||||
if (!dialog.open) return;
|
||||
plan = null;
|
||||
// A refusal of an older request is not shown: the fields changed since, and the next plan tells.
|
||||
if (key === keyNow()) showProblem(err);
|
||||
} finally {
|
||||
planning = false;
|
||||
}
|
||||
if (again) {
|
||||
again = false;
|
||||
drawPlan();
|
||||
runPlan();
|
||||
return;
|
||||
}
|
||||
drawPlan();
|
||||
}
|
||||
|
||||
function drawPlan() {
|
||||
const current = plan !== null && plan.key === keyNow();
|
||||
preview.classList.toggle("stale", !current);
|
||||
if (!request()) {
|
||||
totals.textContent = t("Admin.Reorganize.NothingChosen");
|
||||
preview.hidden = true;
|
||||
} else if (!plan) {
|
||||
totals.textContent = "";
|
||||
preview.hidden = true;
|
||||
} else if (plan.steps.length === 0) {
|
||||
totals.textContent = t("Admin.Reorganize.NothingToChange");
|
||||
preview.hidden = true;
|
||||
} else {
|
||||
totals.textContent = t("Admin.Reorganize.Totals", formatNumber(plan.sequences), formatNumber(plan.files), formatNumber(plan.kept));
|
||||
preview.hidden = false;
|
||||
drawRows();
|
||||
}
|
||||
drawButtons();
|
||||
}
|
||||
|
||||
function drawRows() {
|
||||
const steps = plan.steps;
|
||||
rows.innerHTML = steps.slice(0, shown).map(rowHtml).join("");
|
||||
foot.hidden = steps.length <= shown;
|
||||
shownText.textContent = t("Admin.Library.Shown", formatNumber(Math.min(shown, steps.length)), formatNumber(steps.length));
|
||||
}
|
||||
|
||||
/**
|
||||
* One step: the sequence's title, its folder and its renamed files, before and after, with the photos that keep their
|
||||
* names, or why the whole sequence stays as it is.
|
||||
*/
|
||||
function rowHtml(s) {
|
||||
const fromTitle = s.fromTitle ?? null;
|
||||
const toTitle = s.toTitle ?? null;
|
||||
const name = names.get(s.sequenceId) ?? toTitle ?? fromTitle ?? folderName(s.fromFolder);
|
||||
// Before reads the old state only: an untitled sequence goes by the page's name for it or its folder, never by the
|
||||
// title it is about to get.
|
||||
const before = fromTitle ?? names.get(s.sequenceId) ?? folderName(s.fromFolder);
|
||||
const sequence = fromTitle !== toTitle ? change(before, toTitle ?? before, "auto")
|
||||
: `<span class="ellipsis" dir="auto" title="${attr(name)}">${escapeHtml(name)}</span>`;
|
||||
const folder = s.fromFolder !== s.toFolder ? change(s.fromFolder || "/", s.toFolder || "/", "ltr", "path")
|
||||
: `<span class="path muted" dir="ltr" title="${attr(t("Admin.Reorganize.SameFolder.Tip"))}">${escapeHtml(s.fromFolder || "/")}</span>`;
|
||||
const carried = s.carried
|
||||
? `<span class="pill" title="${attr(t("Admin.Reorganize.Carried.Tip"))}">${escapeHtml(t("Admin.Reorganize.Carried"))}</span>` : "";
|
||||
const samples = (s.fileSamples ?? []).map((f) => `<li dir="ltr">${escapeHtml(f.from)} → ${escapeHtml(f.to)}</li>`).join("");
|
||||
const files = s.fileChanges > 0
|
||||
? `<strong class="num">${escapeHtml(formatNumber(s.fileChanges))}</strong>${samples ? `<ul class="reorg-samples path">${samples}</ul>` : ""}`
|
||||
: `<span class="muted">—</span>`;
|
||||
const kept = (s.blocked ?? []).map((b) => `<li><span aria-hidden="true">▲</span> ${escapeHtml(b.photos > 0
|
||||
? t("Admin.Reorganize.KeptPhotos", plural("Admin.Dashboard.PhotoCount", b.photos), b.message) : b.message)}</li>`).join("");
|
||||
return `<div class="row" role="row" data-key="${attr(s.sequenceId)}">
|
||||
<span role="cell" class="stack">${sequence}${carried}</span>
|
||||
<span role="cell" class="stack">${folder}</span>
|
||||
<span role="cell" class="stack">${files}${kept ? `<ul class="reorg-kept">${kept}</ul>` : ""}</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function drawButtons() {
|
||||
for (const p of PARTS) {
|
||||
check(p).disabled = busy || !loaded;
|
||||
input(p).disabled = busy || !loaded || !check(p).checked;
|
||||
}
|
||||
applyButton.disabled = busy || planning || plan === null || plan.key !== keyNow() || plan.sequences === 0;
|
||||
closeButton.disabled = busy;
|
||||
}
|
||||
|
||||
/**
|
||||
* The confirmation names what moves; the plan sent back is the one the table showed. The fields cannot change
|
||||
* meanwhile, but a dry run scheduled before may answer during it: the same plan again (same request and fingerprint)
|
||||
* is applied all the same; a different one is shown instead, and Apply waits for the user.
|
||||
*/
|
||||
async function apply() {
|
||||
if (applyButton.disabled) return;
|
||||
const chosen = plan;
|
||||
const moves = chosen.steps.filter((s) => s.fromFolder !== s.toFolder).length;
|
||||
const body = [plural("Admin.Reorganize.ConfirmSequences", chosen.sequences),
|
||||
moves > 0 ? plural("Admin.Reorganize.ConfirmFolders", moves) : "",
|
||||
chosen.files > 0 ? plural("Admin.Reorganize.ConfirmFiles", chosen.files) : ""].filter(Boolean).join(" ");
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("Admin.Reorganize.ConfirmTitle"),
|
||||
body,
|
||||
confirm: t("Admin.Reorganize.Confirm"),
|
||||
confirmTip: t("Admin.Reorganize.Confirm.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
});
|
||||
if (!confirmed || !dialog.open) return;
|
||||
if (plan !== chosen && (plan?.key !== chosen.key || plan.fingerprint !== chosen.fingerprint)) {
|
||||
// A failed dry run already says why; a new plan is on screen to be checked.
|
||||
if (plan) showError(t("Admin.Reorganize.PlanChanged"));
|
||||
return;
|
||||
}
|
||||
busy = true;
|
||||
showError("");
|
||||
drawButtons();
|
||||
try {
|
||||
const job = await api.post(ENDPOINT, { ...JSON.parse(chosen.key), dryRun: false, fingerprint: chosen.fingerprint });
|
||||
queued = job;
|
||||
busy = false;
|
||||
dialog.close();
|
||||
toast(t("Admin.Reorganize.Queued"), false,
|
||||
{ label: t("Admin.Reorganize.OpenJob"), tip: t("Admin.Reorganize.OpenJob.Tip"), href: `#/jobs?job=${encodeURIComponent(job.id)}` });
|
||||
} catch (err) {
|
||||
busy = false;
|
||||
if (!dialog.open) return;
|
||||
if (err?.code === "plan_changed") {
|
||||
// The archive changed since the dry run: the new plan is shown, and Apply waits for it.
|
||||
notice = err.message || t("Admin.Error.Unreachable");
|
||||
plan = null;
|
||||
schedule(0);
|
||||
} else {
|
||||
showProblem(err);
|
||||
}
|
||||
drawButtons();
|
||||
(applyButton.disabled ? closeButton : applyButton).focus();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A refusal on the field it names (a template, with the rule it breaks after a colon and the message saying why; or the
|
||||
* folders for a nested target), else under the table.
|
||||
*/
|
||||
function showProblem(err) {
|
||||
const part = PARTS.find((p) => p.field === String(err?.details ?? "").split(":")[0]);
|
||||
if (err?.code === "invalid_template" && part) fieldError(part, err.message);
|
||||
else if (err?.code === "nested_target") fieldError(PARTS[0], err.message, err.details);
|
||||
else if (err?.code === "not_found") showError(t("Admin.Reorganize.Gone"));
|
||||
else showError(errorText(err));
|
||||
}
|
||||
|
||||
function fieldError(part, message, path = "") {
|
||||
markInvalid(input(part), path ? `${message} ${path}` : message);
|
||||
errorHost(part).innerHTML = escapeHtml(message) + (path ? ` <span class="path" dir="ltr">${escapeHtml(path)}</span>` : "");
|
||||
}
|
||||
|
||||
function clearField(part) {
|
||||
clearInvalid(input(part));
|
||||
errorHost(part).textContent = "";
|
||||
}
|
||||
|
||||
function showError(message) {
|
||||
errorLine.textContent = message;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Old and new value, one above the other; screen readers hear which is which. */
|
||||
function change(was, now, dir, cls = "") {
|
||||
return `<span class="change ${cls}"><span class="was" dir="${dir}"><span class="sr-only">${escapeHtml(t("Admin.Reorganize.Before"))} </span>${escapeHtml(was)}</span>` +
|
||||
`<span class="now" dir="${dir}"><span class="sr-only">${escapeHtml(t("Admin.Reorganize.After"))} </span>${escapeHtml(now)}</span></span>`;
|
||||
}
|
||||
|
||||
/** The last part of a sequence folder ("2026/2026-09-28 Roof" → "2026-09-28 Roof"), its name when it has no title. */
|
||||
function folderName(folder) {
|
||||
return String(folder ?? "").split("/").filter(Boolean).pop() ?? "—";
|
||||
}
|
||||
@@ -122,25 +122,49 @@ export function emptyState(sentenceKey, button = "") {
|
||||
return `<div class="empty"><span data-i18n="${attr(sentenceKey)}"></span>${button}</div>`;
|
||||
}
|
||||
|
||||
/** Shows a toast at the bottom (inline end) for 8 s (hover pauses). */
|
||||
export function toast(message, isError = false) {
|
||||
/**
|
||||
* Shows a toast at the bottom (inline end) for 8 s, 15 s with an action (the pointer over it or the keyboard focus in it
|
||||
* pauses). action ({ label, tip, href } or { label, tip, run }) adds a link or a button after the message, which closes
|
||||
* the toast.
|
||||
*/
|
||||
export function toast(message, isError = false, action = null) {
|
||||
const host = document.getElementById("toasts") ?? document.body.appendChild(Object.assign(document.createElement("div"), { id: "toasts" }));
|
||||
const item = document.createElement("div");
|
||||
item.className = `toast${isError ? " error" : ""}`;
|
||||
item.className = `toast${isError ? " error" : ""}${action ? " with-action" : ""}`;
|
||||
item.setAttribute("role", isError ? "alert" : "status");
|
||||
item.textContent = message;
|
||||
item.appendChild(Object.assign(document.createElement("span"), { textContent: message }));
|
||||
if (action) {
|
||||
const control = document.createElement(action.href ? "a" : "button");
|
||||
control.className = "btn small";
|
||||
if (action.href) control.href = action.href;
|
||||
else control.type = "button";
|
||||
control.textContent = action.label;
|
||||
control.title = action.tip;
|
||||
control.addEventListener("click", () => {
|
||||
item.remove();
|
||||
action.run?.();
|
||||
});
|
||||
item.appendChild(control);
|
||||
}
|
||||
host.appendChild(item);
|
||||
let remaining = 8000;
|
||||
let remaining = action ? 15000 : 8000;
|
||||
let started = Date.now();
|
||||
let timer = setTimeout(() => item.remove(), remaining);
|
||||
item.addEventListener("mouseenter", () => {
|
||||
let held = 0;
|
||||
const pause = () => {
|
||||
if (held++ > 0) return;
|
||||
clearTimeout(timer);
|
||||
remaining -= Date.now() - started;
|
||||
});
|
||||
item.addEventListener("mouseleave", () => {
|
||||
};
|
||||
const resume = () => {
|
||||
if (--held > 0) return;
|
||||
started = Date.now();
|
||||
timer = setTimeout(() => item.remove(), remaining);
|
||||
});
|
||||
timer = setTimeout(() => item.remove(), Math.max(remaining, 2000));
|
||||
};
|
||||
item.addEventListener("mouseenter", pause);
|
||||
item.addEventListener("mouseleave", resume);
|
||||
item.addEventListener("focusin", pause);
|
||||
item.addEventListener("focusout", resume);
|
||||
}
|
||||
|
||||
let dialogs = 0;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Data;
|
||||
@@ -13,12 +14,16 @@ using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary><c>/api/v1/archive</c> (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics.</summary>
|
||||
/// <summary>
|
||||
/// <c>/api/v1/archive</c> (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics, and
|
||||
/// Reorganize (owner review 2, R7): new templates applied to sequences already in the archive.
|
||||
/// </summary>
|
||||
public static class ArchiveEndpoints
|
||||
{
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive);
|
||||
archive.MapPost("/reorganize", ReorganizeAsync);
|
||||
// The form saves every field: it starts from what archive.json holds now, also a desktop's change since the last poll.
|
||||
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));
|
||||
@@ -65,21 +70,28 @@ public static class ArchiveEndpoints
|
||||
|
||||
/// <summary>
|
||||
/// Writes the name, templates and proxy policy into the archive's <c>archive.json</c> through the archive engine (so a
|
||||
/// restart and the proxy jobs see them), then into the index. 503 <c>archive_offline</c> while the archive cannot be
|
||||
/// written; 409 <c>archive_busy</c> while another process holds its settings; 409 <c>archive_manifest</c> when its
|
||||
/// archive.json is damaged, written by a newer Chronos or of another archive; 409 <c>archive_policy</c> when it holds a
|
||||
/// thumbnail or proxy setting this API cannot set and Chronos cannot use (details: <c>thumbnailPolicy</c> or
|
||||
/// <c>proxyPolicy</c>, the property to correct in the file). Nothing is written.
|
||||
/// restart and the proxy jobs see them), then into the index. 400 <c>bad_request</c> (details <c>name</c>,
|
||||
/// <c>proxyLongEdge</c>), 400 <c>invalid_template</c> (<see cref="InvalidTemplate"/>: <c>folderTemplate</c> or
|
||||
/// <c>fileTemplate</c>, with the rule it breaks; only a template the request changes is held to the rules, so one
|
||||
/// archive.json holds from before them never fails a save of the other fields); 503 <c>archive_offline</c> while the
|
||||
/// archive cannot be written; 409 <c>archive_busy</c> while another process holds its settings; 409
|
||||
/// <c>archive_manifest</c> when its archive.json is damaged, written by a newer Chronos or of another archive; 409
|
||||
/// <c>archive_policy</c> when it holds a thumbnail or proxy setting this API cannot set and Chronos cannot use (details:
|
||||
/// <c>thumbnailPolicy</c> or <c>proxyPolicy</c>, the property to correct in the file). Nothing is written.
|
||||
/// </summary>
|
||||
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, ArchiveSettingsDto request, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, AuditLog audit)
|
||||
{
|
||||
var name = request.Name?.Trim();
|
||||
if (string.IsNullOrEmpty(name) || name.Length > ArchiveSettings.MaxNameLength) return ApiErrors.BadRequest(context, "bad_request", "name");
|
||||
foreach (var (field, template) in new[] { ("folderTemplate", request.FolderTemplate), ("fileTemplate", request.FileTemplate) })
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(template) || !PathTemplate.Parse(template).IsValid) return ApiErrors.BadRequest(context, "invalid_template", field);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(request.FolderTemplate)) return ApiErrors.BadRequest(context, "invalid_template", "folderTemplate");
|
||||
if (string.IsNullOrWhiteSpace(request.FileTemplate)) return ApiErrors.BadRequest(context, "invalid_template", "fileTemplate");
|
||||
// The rules Reorganize checks (a folder scans never enter, a lost extension or names that repeat) hold a template the
|
||||
// request changes, as the engine does: one archive.json holds already, saved before them, never fails another save.
|
||||
var templates = new LayoutTemplates { Folder = request.FolderTemplate, File = request.FileTemplate };
|
||||
var stored = new LayoutTemplates { Folder = archive.Current.FolderTemplate, File = archive.Current.FileTemplate };
|
||||
if (new ArchiveSettings(name, templates, new ProxyPolicy(), new ThumbnailPolicy()).CheckTemplates(stored) is { } problem)
|
||||
return InvalidTemplate(context, problem);
|
||||
if (!ProxyPolicy.IsValidLongEdge(request.ProxyLongEdge)) return ApiErrors.BadRequest(context, "bad_request", "proxyLongEdge");
|
||||
|
||||
var engine = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
|
||||
@@ -101,6 +113,11 @@ public static class ArchiveEndpoints
|
||||
{
|
||||
return ApiErrors.Conflict(context, "archive_manifest");
|
||||
}
|
||||
catch (TemplateRuleException ex)
|
||||
{
|
||||
// archive.json held other templates than the index (a desktop's edit since): the request's breaks a rule for it.
|
||||
return InvalidTemplate(context, new TemplateProblem(ex.ParamName!, ex.Rule));
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
// The request's fields were checked above: what fails is a value read from archive.json (a thumbnail size, or a
|
||||
@@ -122,6 +139,117 @@ public static class ArchiveEndpoints
|
||||
return Results.Json(Settings(updated), ProtocolJson.Default.ArchiveSettingsDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize: folder, file and title templates applied to <c>sequenceIds</c> or, with <c>all</c>, to every sequence of the
|
||||
/// archive (BRIEF §12.5). With <c>dryRun</c> the plan, nothing touched: per sequence its folder and title before and after,
|
||||
/// the photos renamed with the first of them, and the photos that keep their names and why, or why the whole sequence
|
||||
/// stays as it is. Otherwise the request carries
|
||||
/// that plan's fingerprint and the server queues a <c>move</c> job (202) that applies exactly that plan, refused when the
|
||||
/// archive changed before it ran. 400 <c>bad_request</c> (details <c>sequenceIds</c>: neither or both of them, none, or
|
||||
/// more than <see cref="LibraryEndpoints.MaxBulkIds"/>; <c>templates</c>: none; <c>fingerprint</c>), 400
|
||||
/// <c>invalid_template</c> (<see cref="InvalidTemplate"/>: <c>folderTemplate</c>, <c>fileTemplate</c> or
|
||||
/// <c>titleTemplate</c>, with the rule it breaks); 404
|
||||
/// <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>nested_target</c> (details: the folder that would lie
|
||||
/// inside a sequence's folder), <c>plan_changed</c> (details: the fingerprint now), <c>job_unavailable</c>; 503
|
||||
/// <c>archive_offline</c>, <c>plan_dropped</c> (the plan was stopped: past its time, let go for newer ones, or the server
|
||||
/// stopping). Audited; the job tells each sequence it changes as <c>sequenceChanged</c> (<c>reorganized</c>)
|
||||
/// once that sequence's step is journaled (a step that failed half-way, once its folder moved and its index rows followed; a plan the server
|
||||
/// completes as it starts, no one: no client is connected yet). Photos a sequence receives between the dry run and the
|
||||
/// confirmation under the names the plan leaves them keep the fingerprint as it was. A dry run's plan is made apart from
|
||||
/// the request, a few at once and each for a limited time, and kept a few minutes, a refusal too, while what it reads
|
||||
/// from the index stays as it was (<see cref="ReorganizePlanCache"/>; the sequences' rows, and how many photos of those
|
||||
/// planned are hashed): the same dry run again (also after the first was cut off), and its confirmation, take it instead
|
||||
/// of planning again. So <c>plan_changed</c> answers a change the index has, photos a verify hashed among them; one made
|
||||
/// on disk alone since the dry run (a folder made by hand, a desktop writing to a shared archive before a scan) is found
|
||||
/// by the job, which then fails and changes nothing.
|
||||
/// </summary>
|
||||
private static async Task<IResult> ReorganizeAsync(HttpContext context, Caller caller, ReorganizeRequest request, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, ReorganizePlanCache plans)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (request.All == (request.SequenceIds is not null) || request.SequenceIds is { Count: 0 or > LibraryEndpoints.MaxBulkIds })
|
||||
return ApiErrors.BadRequest(context, "bad_request", "sequenceIds");
|
||||
var templates = new RenameTemplates(request.FolderTemplate, request.FileTemplate, request.TitleTemplate);
|
||||
if (templates.IsEmpty) return ApiErrors.BadRequest(context, "bad_request", "templates");
|
||||
if (templates.Check() is { } problem) return InvalidTemplate(context, problem);
|
||||
if (!request.DryRun && string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
|
||||
if (ArchiveService.GetAvailability(archive.Current) != ArchiveAvailability.Online)
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
||||
var sequences = request.All ? null : request.SequenceIds;
|
||||
// Stamped before planning: a change committed while the plan is made gives the next request another key.
|
||||
var key = ReorganizePlanCache.Key.Of(archive.Id, await db.Sequences.GetStampAsync(archive.Id, sequences, ct), sequences, templates);
|
||||
RenamePlan plan;
|
||||
try
|
||||
{
|
||||
// Made whatever becomes of this request, until the cache stops it: the same request again takes it.
|
||||
plan = await plans.GetOrPlanAsync(key, stop => LibraryEndpoints.Engine(archives, db).PlanReorganizeAsync(archive.Id, sequences, templates, stop), ct);
|
||||
}
|
||||
catch (NestedRenameException ex)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "nested_target", ex.Target);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
// Stopped: past its time (a read that hangs), let go for newer plans, or the server stopping.
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "plan_dropped");
|
||||
}
|
||||
var fingerprint = plan.Fingerprint();
|
||||
if (request.DryRun) return Results.Json(Plan(context, plan, fingerprint), ProtocolJson.Default.ReorganizePlanDto);
|
||||
if (!string.Equals(fingerprint, request.Fingerprint, StringComparison.Ordinal)) return ApiErrors.Conflict(context, "plan_changed", fingerprint);
|
||||
if (!host.CanRun(JobKind.Move)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.Move));
|
||||
var job = await host.Engine.EnqueueAsync(ArchiveJobs.Reorganize(archive.Current, plan, templates), caller.Id, ct);
|
||||
plans.Forget(key);
|
||||
await audit.WriteAsync(caller, context, "archive_reorganized", "job", job.Id.ToString(),
|
||||
$"{plan.Steps.Count(s => s.Changes)} · {plan.Steps.Sum(s => s.FileChanges)} · {templates.Folder} · {templates.File} · {templates.Title}");
|
||||
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 400 <c>invalid_template</c> for a template that cannot be used. The details name its field (<c>fileTemplate</c>); when
|
||||
/// it parses but breaks a rule of the archive's templates (<see cref="TemplateRules"/>), the rule follows after a colon
|
||||
/// (<c>folderTemplate:reserved_folder</c>, <c>fileTemplate:file_separator</c>, <c>fileTemplate:extension</c>,
|
||||
/// <c>fileTemplate:not_unique</c>) and the message says why in the request's language, as the desktop's fields do
|
||||
/// (<c>Errors.Template.<Rule></c>); otherwise the message is that the template is not valid.
|
||||
/// </summary>
|
||||
private static IResult InvalidTemplate(HttpContext context, TemplateProblem problem)
|
||||
{
|
||||
if (problem.Rule is not { } rule) return ApiErrors.BadRequest(context, "invalid_template", problem.Field);
|
||||
var message = Loc.Get("Errors.Template." + rule, RequestCulture.Of(context)) ?? ApiErrors.Message(context, "invalid_template");
|
||||
var wire = string.Concat(rule.Select((c, i) => char.IsUpper(c) ? (i > 0 ? "_" : string.Empty) + char.ToLowerInvariant(c) : c.ToString()));
|
||||
return Results.Json(new ApiError("invalid_template", message, $"{problem.Field}:{wire}"), ProtocolJson.Default.ApiError,
|
||||
statusCode: StatusCodes.Status400BadRequest);
|
||||
}
|
||||
|
||||
/// <summary>The dry run as the API answers it, with each reason something stays as it is in the request's language.</summary>
|
||||
private static ReorganizePlanDto Plan(HttpContext context, RenamePlan plan, string fingerprint)
|
||||
{
|
||||
var culture = RequestCulture.Of(context);
|
||||
return new ReorganizePlanDto(
|
||||
[.. plan.Steps.Select(s => new ReorganizeStepDto(s.SequenceId, s.FromFolder, s.ToFolder, s.FromTitle, s.ToTitle, s.Carried, s.FramesVersion,
|
||||
s.FileChanges, [.. s.FileSamples.Select(f => new ReorganizeFileDto(f.From, f.To))],
|
||||
[.. s.Blocked.Select(b => new ReorganizeBlockedDto(Wire(b.Reason), b.Frames, Loc.Get("Archive.Reorganize.Blocked." + b.Reason, culture) ?? Wire(b.Reason)))]))],
|
||||
plan.Steps.Count(s => s.Changes),
|
||||
plan.Steps.Sum(s => s.FileChanges),
|
||||
plan.Steps.Sum(s => s.Blocked.Sum(b => b.Frames)),
|
||||
fingerprint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wire name of a reason something stays as it is: photos that keep their names (<c>in_place</c>, <c>unhashed</c>,
|
||||
/// <c>missing</c>), or the whole sequence (<c>unreadable</c>).
|
||||
/// </summary>
|
||||
public static string Wire(RenameBlock reason) => reason switch
|
||||
{
|
||||
RenameBlock.InPlace => "in_place",
|
||||
RenameBlock.Unhashed => "unhashed",
|
||||
RenameBlock.Missing => "missing",
|
||||
_ => "unreadable",
|
||||
};
|
||||
|
||||
private static async Task<IResult> EnqueueAsync(HttpContext context, Caller caller, ServerArchive archive, JobEngineHost host, AuditLog audit, JobKind kind)
|
||||
{
|
||||
if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind));
|
||||
|
||||
@@ -63,7 +63,8 @@ public static class FileEndpoints
|
||||
/// (<see cref="ServerProxies"/>); the sequence's thumbnails, proxy state and light analysis follow as background jobs.
|
||||
/// 204; 413 <c>too_large</c>; 422 <c>proxy_not_wanted</c> (the server decodes that original itself, or it is missing or
|
||||
/// damaged), <c>invalid_proxy</c>, <c>proxy_mismatch</c> or <c>proxy_too_small</c>, which concern that proxy only; 409
|
||||
/// <c>proxies_disabled</c>, which concerns them all; 503 <c>archive_offline</c>.
|
||||
/// <c>proxies_disabled</c>, which concerns them all; 503 <c>archive_offline</c>, or <c>sequence_busy</c> while another writer
|
||||
/// holds the sequence (a Reorganize moving its folder) for longer than the lease wait.
|
||||
/// </summary>
|
||||
private static async Task<IResult> StoreProxyAsync(HttpContext context, Guid id, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, SequenceJobs follow)
|
||||
@@ -83,14 +84,20 @@ public static class FileEndpoints
|
||||
ProxyStoreResult result;
|
||||
try
|
||||
{
|
||||
result = images.StoreProxy(archive.Current, sequence, frame, body.ToArray());
|
||||
result = await images.StoreProxyAsync(archive.Current, sequence, frame, body.ToArray(), ct);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "sequence_busy");
|
||||
}
|
||||
switch (result)
|
||||
{
|
||||
case ProxyStoreResult.Gone:
|
||||
return ApiErrors.NotFound(context, "frame");
|
||||
case ProxyStoreResult.Disabled:
|
||||
return ApiErrors.Conflict(context, "proxies_disabled");
|
||||
case ProxyStoreResult.Invalid:
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize's dry runs kept a short while (owner review 2, R7): the same dry run asked again, and the confirmation that
|
||||
/// follows it, take the plan made then instead of reading every sidecar and photo folder of the selection again (with
|
||||
/// <c>all</c>, of the whole archive), while what the plan reads from the index is as it was then
|
||||
/// (<see cref="SequenceRepository.GetStampAsync"/>) and for at most <see cref="Lifetime"/> once made. A refusal (a folder
|
||||
/// inside a sequence's, a sequence not in the archive) follows from the same reads, so it is kept as a plan is; a failure
|
||||
/// is not. A plan is made apart from the request that asked for it, once for every request of the same key: a request cut
|
||||
/// off meanwhile (a proxy's timeout) leaves it to be made, and the same request again waits for it or takes it. At most
|
||||
/// <see cref="Concurrency"/> plans are made at once; one still being made past <see cref="PlanTimeout"/>, let go for newer
|
||||
/// ones (<see cref="Capacity"/>), or when the server stops, is stopped, and whoever waits for it is told it was dropped
|
||||
/// (<see cref="OperationCanceledException"/>). A change made on disk alone, which the index does not have, is not seen by a
|
||||
/// kept plan: the <c>move</c> job plans again and refuses a plan that no longer matches the archive, so nothing changes
|
||||
/// that the dry run did not show.
|
||||
/// </summary>
|
||||
public sealed class ReorganizePlanCache : IDisposable
|
||||
{
|
||||
/// <summary>How long a plan is kept once made; then its timer lets it go.</summary>
|
||||
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>
|
||||
/// Plans kept or being made at most (each holds a step for every sequence it changes or carries, or whose photos keep
|
||||
/// their names). One more lets go the kept plan asked for first; with none kept, the plan being made asked for first,
|
||||
/// which stops.
|
||||
/// </summary>
|
||||
public const int Capacity = 8;
|
||||
|
||||
/// <summary>Plans made at once at most; the others wait for their turn.</summary>
|
||||
public const int Concurrency = 2;
|
||||
|
||||
/// <summary>
|
||||
/// How long a plan may take, from when it was asked (its wait for a turn included): then it stops. A read that hangs
|
||||
/// still holds its turn until it returns.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan PlanTimeout = TimeSpan.FromMinutes(15);
|
||||
|
||||
private readonly TimeProvider _time;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<Key, Entry> _plans = [];
|
||||
private readonly SemaphoreSlim _turns = new(Concurrency);
|
||||
private readonly CancellationTokenRegistration _stopping;
|
||||
private long _order;
|
||||
|
||||
/// <param name="lifetime">The host, whose stopping stops the plans being made.</param>
|
||||
public ReorganizePlanCache(TimeProvider time, IHostApplicationLifetime? lifetime = null)
|
||||
{
|
||||
_time = time;
|
||||
if (lifetime is not null) _stopping = lifetime.ApplicationStopping.Register(Clear);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a plan is kept by: the archive, the stamp of what it reads from the index, the sequences (all of them, or the ids
|
||||
/// in the order given, which decides the folder that gets " (2)") and the templates.
|
||||
/// </summary>
|
||||
public readonly record struct Key(Guid ArchiveId, string Stamp, string Sequences, RenameTemplates Templates)
|
||||
{
|
||||
/// <param name="sequenceIds">The sequences of the request; null for every sequence of the archive.</param>
|
||||
public static Key Of(Guid archiveId, string stamp, IReadOnlyList<Guid>? sequenceIds, RenameTemplates templates) =>
|
||||
new(archiveId, stamp, sequenceIds is null ? "*" : string.Join(',', sequenceIds.Select(id => id.ToString("N"))), templates);
|
||||
}
|
||||
|
||||
/// <summary>Plans kept or being made now.</summary>
|
||||
internal int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _plans.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plan kept for <paramref name="key"/>, the one being made for it, or the one <paramref name="plan"/> starts making
|
||||
/// now, apart from the caller, then kept; <paramref name="plan"/> stops when its token is cancelled. A refusal
|
||||
/// (<see cref="NestedRenameException"/>, <see cref="ArgumentException"/>) is kept as a plan is; a failure is passed to
|
||||
/// every caller waiting for it and not kept, and so is a plan stopped (<see cref="OperationCanceledException"/>).
|
||||
/// <paramref name="cancellationToken"/> stops the wait only: the plan is still made, and kept.
|
||||
/// </summary>
|
||||
public Task<RenamePlan> GetOrPlanAsync(Key key, Func<CancellationToken, Task<RenamePlan>> plan, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
Entry? entry;
|
||||
bool start;
|
||||
lock (_gate)
|
||||
{
|
||||
// Never past its lifetime, whatever its timer.
|
||||
if (_plans.TryGetValue(key, out entry) && entry.Made is { } made && _time.GetUtcNow() - made >= Lifetime) Remove(key);
|
||||
start = !_plans.TryGetValue(key, out entry);
|
||||
if (start)
|
||||
{
|
||||
if (_plans.Count >= Capacity) Remove(_plans.MinBy(p => (p.Value.Made is null, p.Value.Order)).Key);
|
||||
var asked = new Entry(++_order);
|
||||
asked.Deadline = _time.CreateTimer(_ => TimeOut(key, asked), null, PlanTimeout, Timeout.InfiniteTimeSpan);
|
||||
_plans[key] = entry = asked;
|
||||
}
|
||||
}
|
||||
if (start) _ = MakeAsync(key, entry!, plan);
|
||||
return entry!.Plan.Task.WaitAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Forgets the plan kept for <paramref name="key"/>: its job is queued, and what the job changes gives the index another stamp.</summary>
|
||||
public void Forget(Key key)
|
||||
{
|
||||
lock (_gate) Remove(key);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stopping.Dispose();
|
||||
Clear();
|
||||
}
|
||||
|
||||
/// <summary>Lets every plan go; those being made stop.</summary>
|
||||
private void Clear()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
foreach (var key in _plans.Keys.ToList()) Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task MakeAsync(Key key, Entry entry, Func<CancellationToken, Task<RenamePlan>> plan)
|
||||
{
|
||||
var stop = entry.Stop.Token;
|
||||
RenamePlan? made = null;
|
||||
Exception? refused = null;
|
||||
try
|
||||
{
|
||||
await _turns.WaitAsync(stop).ConfigureAwait(false);
|
||||
var making = Task.Run(() => plan(stop), CancellationToken.None);
|
||||
// The turn ends with the work, also when no one waits for it any more (a read that hangs).
|
||||
_ = making.ContinueWith(t =>
|
||||
{
|
||||
_ = t.Exception;
|
||||
_turns.Release();
|
||||
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
|
||||
made = await making.WaitAsync(stop).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is NestedRenameException || ex.GetType() == typeof(ArgumentException))
|
||||
{
|
||||
// A folder inside a sequence's, a sequence not in the archive: what the key holds decides it, as it does a plan.
|
||||
refused = ex;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// A failure, or the plan stopped (past its time, let go, the server stopping): the next request plans again.
|
||||
lock (_gate)
|
||||
{
|
||||
if (_plans.GetValueOrDefault(key) == entry) Remove(key);
|
||||
}
|
||||
if (ex is OperationCanceledException canceled) entry.Plan.SetCanceled(canceled.CancellationToken);
|
||||
else entry.Plan.SetException(ex);
|
||||
// Observed here: a request cut off before it ended no longer waits for it.
|
||||
_ = entry.Plan.Task.Exception;
|
||||
return;
|
||||
}
|
||||
lock (_gate)
|
||||
{
|
||||
if (_plans.GetValueOrDefault(key) == entry)
|
||||
{
|
||||
entry.Made = _time.GetUtcNow();
|
||||
entry.Deadline?.Dispose();
|
||||
entry.Expiry = _time.CreateTimer(_ => Expire(key, entry), null, Lifetime, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
}
|
||||
if (refused is null)
|
||||
{
|
||||
entry.Plan.SetResult(made!);
|
||||
return;
|
||||
}
|
||||
entry.Plan.SetException(refused);
|
||||
_ = entry.Plan.Task.Exception;
|
||||
}
|
||||
|
||||
/// <summary>A plan still being made at <see cref="PlanTimeout"/> stops.</summary>
|
||||
private void TimeOut(Key key, Entry entry)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
// Made as its deadline fired: kept for its lifetime.
|
||||
if (_plans.GetValueOrDefault(key) == entry && entry.Made is null) Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private void Expire(Key key, Entry entry)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_plans.GetValueOrDefault(key) == entry) Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private void Remove(Key key)
|
||||
{
|
||||
if (!_plans.Remove(key, out var entry)) return;
|
||||
entry.Deadline?.Dispose();
|
||||
entry.Expiry?.Dispose();
|
||||
// Stopped outside this lock: the wait for it ends on the thread pool.
|
||||
if (entry.Made is null) _ = entry.Stop.CancelAsync();
|
||||
}
|
||||
|
||||
/// <summary>A plan being made (<see cref="Made"/> null) or kept, and the order it was asked in.</summary>
|
||||
private sealed class Entry(long order)
|
||||
{
|
||||
public long Order { get; } = order;
|
||||
|
||||
public TaskCompletionSource<RenamePlan> Plan { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
/// <summary>Stops the plan while it is made; a source with no timer and no parent, so nothing to release.</summary>
|
||||
public CancellationTokenSource Stop { get; } = new();
|
||||
|
||||
public DateTimeOffset? Made { get; set; }
|
||||
|
||||
/// <summary>Stops the plan at <see cref="PlanTimeout"/> while it is made.</summary>
|
||||
public ITimer? Deadline { get; set; }
|
||||
|
||||
/// <summary>Lets the plan go at <see cref="Lifetime"/> once made.</summary>
|
||||
public ITimer? Expiry { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -142,6 +142,7 @@ public static class ServerHost
|
||||
services.AddSingleton<RenderStore>();
|
||||
services.AddSingleton<RenderUploads>();
|
||||
services.AddSingleton<SequenceJobs>();
|
||||
services.AddSingleton<ReorganizePlanCache>();
|
||||
services.AddSingleton<RenderNodeService>();
|
||||
services.AddSingleton<JobEngineHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Jobs;
|
||||
@@ -175,7 +176,16 @@ public sealed class RenderNodeService(
|
||||
if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome<RenderDto>.Fail(422, "hash_mismatch");
|
||||
var output = JsonSerializer.Deserialize(upload.RenderJson, ProtocolJson.Default.RenderResultRequest)!;
|
||||
var sequence = await db.Sequences.GetAsync(job.TargetIds[0], cancellationToken);
|
||||
var render = sequence is null ? null : await renders.CommitAsync(sequence, staged, output, node.ClientName, cancellationToken);
|
||||
Render? render;
|
||||
try
|
||||
{
|
||||
render = sequence is null ? null : await renders.CommitAsync(sequence, staged, output, node.ClientName, cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is LeaseUnavailableException or ArchiveOfflineException or FolderMovedException)
|
||||
{
|
||||
// The node keeps the job and completes again.
|
||||
return await uploads.ReceiveAgainAsync<RenderDto>(upload, staged, ex);
|
||||
}
|
||||
if (render is null)
|
||||
{
|
||||
UploadStore.TryDelete(staged);
|
||||
|
||||
@@ -3,14 +3,17 @@ using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and
|
||||
/// 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
|
||||
/// orphans reports, index backups and clean-ups with the server's own steps, the <see cref="ICleanupStep"/>s in DI, and Reorganize's
|
||||
/// <c>move</c> jobs, which tell connected clients of the sequences they change); 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).
|
||||
@@ -25,9 +28,17 @@ public static class ArchiveModule
|
||||
services.AddSingleton(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<ServerOptions>();
|
||||
var db = sp.GetRequiredService<ChronosDatabase>();
|
||||
var events = sp.GetRequiredService<EventHub>();
|
||||
// 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
|
||||
return new ArchiveService(db, new ArchiveServiceOptions
|
||||
{
|
||||
// A Reorganize tells connected clients of every sequence it changed (BRIEF §14.3).
|
||||
SequenceChanged = async (id, change, ct) =>
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
|
||||
},
|
||||
Decoder = DecoderFactory.CreateServer(),
|
||||
Owner = Owner,
|
||||
ImagesAfterScan = true,
|
||||
|
||||
@@ -1,47 +1,64 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>Files a verified render output under the sequence's <c>exports/</c> folder (BRIEF §7) and records it.</summary>
|
||||
public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeProvider time)
|
||||
/// <param name="archives">The archive engine whose sequence lease the filing takes; one of its own when none is registered.</param>
|
||||
public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeProvider time, ArchiveService? archives = null)
|
||||
{
|
||||
private readonly ArchiveService _archives = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
|
||||
|
||||
/// <summary>
|
||||
/// Moves <paramref name="stagedFile"/> (on the archive volume) to <c><sequence folder>/exports/</c>, never
|
||||
/// replacing an existing export, and inserts the render row. Null when the sequence has no folder in the archive yet.
|
||||
/// replacing an existing export, and inserts the render row, both under the sequence's lease with its folder as the
|
||||
/// index has it then: a Reorganize may have moved it since <paramref name="sequence"/> was read, and moves the row's
|
||||
/// path along when it moves it later. Null when the sequence left the index or has no folder in the archive yet; nothing
|
||||
/// is moved then.
|
||||
/// </summary>
|
||||
/// <exception cref="FolderMovedException">The sequence is not in the folder the index has (another index moved it, and
|
||||
/// maybe another sequence into that folder): nothing is moved, and the filing can be done again once this index's next
|
||||
/// scan found the folder.</exception>
|
||||
public Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, CancellationToken cancellationToken) =>
|
||||
CommitAsync(sequence, stagedFile, output, producedBy, Guid.CreateVersion7(), cancellationToken);
|
||||
|
||||
/// <summary>As above, keeping <paramref name="id"/>: a render a client sends keeps the id it has on that client.</summary>
|
||||
public async Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, Guid id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sequence.Folder) || ArchivePathGuard.Resolve(archive.Root, sequence.Folder.TrimEnd('/') + "/exports") is not { } exports)
|
||||
return null;
|
||||
Directory.CreateDirectory(exports);
|
||||
var target = Unique(exports, output.FileName);
|
||||
File.Move(stagedFile, target);
|
||||
var render = new Render
|
||||
/// <exception cref="FolderMovedException">The sequence is not in the folder the index has.</exception>
|
||||
public Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, Guid id,
|
||||
CancellationToken cancellationToken) =>
|
||||
_archives.UnderLeaseAsync(sequence, async row =>
|
||||
{
|
||||
Id = id,
|
||||
SequenceId = sequence.Id,
|
||||
PresetName = output.PresetName,
|
||||
OutputPath = LongPath.ToPortableRelative(archive.Root, target),
|
||||
Codec = output.Codec,
|
||||
Width = output.Width,
|
||||
Height = output.Height,
|
||||
Fps = output.Fps,
|
||||
DurationSeconds = output.DurationSeconds,
|
||||
Bytes = output.Size,
|
||||
Created = time.GetUtcNow(),
|
||||
ProducedBy = producedBy,
|
||||
};
|
||||
await db.Renders.InsertAsync(render, cancellationToken);
|
||||
return render;
|
||||
}
|
||||
if (row is null || string.IsNullOrEmpty(row.Folder) || ArchivePathGuard.Resolve(archive.Root, row.Folder.TrimEnd('/') + "/exports") is not { } exports)
|
||||
return null;
|
||||
// A folder another index moved is found by this index's next scan; until then nothing is filed, so it is not created
|
||||
// again, nor filed among the exports of another sequence that index moved into it since.
|
||||
if (!SequenceFolders.Holds(new ArchivePaths(archive.Root).Sequence(row.Folder), row.Id)) throw new FolderMovedException();
|
||||
Directory.CreateDirectory(exports);
|
||||
var target = Unique(exports, output.FileName);
|
||||
File.Move(stagedFile, target);
|
||||
var render = new Render
|
||||
{
|
||||
Id = id,
|
||||
SequenceId = row.Id,
|
||||
PresetName = output.PresetName,
|
||||
OutputPath = LongPath.ToPortableRelative(archive.Root, target),
|
||||
Codec = output.Codec,
|
||||
Width = output.Width,
|
||||
Height = output.Height,
|
||||
Fps = output.Fps,
|
||||
DurationSeconds = output.DurationSeconds,
|
||||
Bytes = output.Size,
|
||||
Created = time.GetUtcNow(),
|
||||
ProducedBy = producedBy,
|
||||
};
|
||||
await db.Renders.InsertAsync(render, cancellationToken);
|
||||
return (Render?)render;
|
||||
}, cancellationToken);
|
||||
|
||||
private static string Unique(string folder, string fileName)
|
||||
{
|
||||
@@ -52,3 +69,9 @@ public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeP
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sequence is not in the folder the index has (another index of the archive moved it): nothing was filed into it, and
|
||||
/// this index's next scan finds the folder, after which the filing can be done again.
|
||||
/// </summary>
|
||||
public sealed class FolderMovedException() : IOException(Loc.L("Errors.Archive.FolderMoved"));
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Protocol;
|
||||
@@ -87,8 +89,16 @@ public sealed class RenderUploads(
|
||||
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken);
|
||||
var result = new RenderResultRequest(output.FileName, output.Size, output.Sha256, output.PresetName, output.Codec, output.Width, output.Height, output.Fps,
|
||||
output.DurationSeconds);
|
||||
var render = sequence is null ? null : await renders.CommitAsync(sequence, staged, result, output.ProducedBy ?? caller.ClientName ?? caller.User.Username,
|
||||
output.RenderId, cancellationToken);
|
||||
Render? render;
|
||||
try
|
||||
{
|
||||
render = sequence is null ? null : await renders.CommitAsync(sequence, staged, result, output.ProducedBy ?? caller.ClientName ?? caller.User.Username,
|
||||
output.RenderId, cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is LeaseUnavailableException or ArchiveOfflineException or FolderMovedException)
|
||||
{
|
||||
return await uploads.ReceiveAgainAsync<RenderDto>(upload, staged, ex);
|
||||
}
|
||||
if (render is null)
|
||||
{
|
||||
UploadStore.TryDelete(staged);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Repositories;
|
||||
@@ -303,6 +304,27 @@ public sealed class UploadService(
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A verified upload whose filing was refused before anything moved, for a reason that passes: its sequence held by
|
||||
/// another writer past the lease wait (503 <c>sequence_busy</c>), the archive offline or read-only (503
|
||||
/// <c>archive_offline</c>), or the sequence's folder not where the index has it until this index's next scan (503
|
||||
/// <c>folder_moved</c>, <see cref="FolderMovedException"/>). The staged copy goes and the upload receives again with its
|
||||
/// part file, so the client completes it again, as it does after any 503.
|
||||
/// </summary>
|
||||
public async Task<Outcome<T>> ReceiveAgainAsync<T>(Upload upload, string staged, Exception refusal)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(upload);
|
||||
logger.LogWarning("Upload {Upload} ({File}) not filed for now: {Reason}", upload.Id, upload.FileName, refusal.Message);
|
||||
UploadStore.TryDelete(staged);
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Receiving, cancellationToken: CancellationToken.None);
|
||||
return Fail<T>(503, refusal switch
|
||||
{
|
||||
ArchiveOfflineException => "archive_offline",
|
||||
FolderMovedException => "folder_moved",
|
||||
_ => "sequence_busy",
|
||||
});
|
||||
}
|
||||
|
||||
private async Task FailAsync(Upload upload)
|
||||
{
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Failed, cancellationToken: CancellationToken.None);
|
||||
|
||||
Reference in new issue
Block a user