feat: owner review 2 phase 4b: mass conversion after import (#13)
CI / Build and test (push) Failing after 3m1s
CI / PostgreSQL 16 integration (push) Skipped
CI / PostgreSQL 17 integration (push) Skipped
CI / Docker image (push) Skipped
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
Release / Build, test and publish (push) Successful in 15m31s
Release / Server image (push) Successful in 1m13s
CI / Build and test (push) Failing after 3m1s
CI / PostgreSQL 16 integration (push) Skipped
CI / PostgreSQL 17 integration (push) Skipped
CI / Docker image (push) Skipped
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
Release / Build, test and publish (push) Successful in 15m31s
Release / Server image (push) Successful in 1m13s
Convert photos already in the archive to JPEG, TIFF-16 or Linear DNG, from the panel's Library and the desktop's Archive and Library. Each run asks Replace (same frames, originals to the trash, recoverable) or New sequence. A dry run lists what converts, what is skipped and why, size before and after, and free space; the job converts exactly the confirmed photos, resumes, and commits all or nothing per sequence. A conversion never changes what Chronos reads from a photo. Replaced originals are erased only on the archive's own word that their conversion is gone. Desktop TIFFs that WIC showed black or as noise now go to the managed reader; the Edit picker no longer spins a core. 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 #13.
This commit is contained in:
1 parent
7e4a3b481d
commit
efa87f68ce
354 files changed
+24530
-843
No files matched your search
@@ -433,14 +433,15 @@ dialog.dialog.reorganize { width: 960px; }
|
||||
.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; }
|
||||
/* A dry run's table, Reorganize's and Convert's: scrolls inside the dialog, dimmed while it no longer matches the fields. */
|
||||
.reorg-preview, .plan-preview { max-height: 46vh; overflow: auto; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--bg); }
|
||||
.reorg-preview:focus-visible, .plan-preview:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.reorg-preview.stale .table, .plan-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 .thead, .table.convert .thead { position: sticky; top: 0; z-index: 1; padding: 8px 12px; background: var(--bg); }
|
||||
.table.reorg .row, .table.convert .row { min-height: 0; padding: 8px 12px; align-items: start; }
|
||||
.table.reorg .row:hover, .table.convert .row:hover { background: none; }
|
||||
.table.reorg .row:last-child, .table.convert .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; }
|
||||
@@ -448,11 +449,29 @@ dialog.dialog.reorganize { width: 960px; }
|
||||
.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); }
|
||||
.reorg-preview .table-foot, .plan-preview .table-foot { padding: 8px 12px; border-top: 1px solid var(--stroke); }
|
||||
|
||||
/* Convert dialog (owner review 2, R7, convert.js): format, JPEG quality and mode side by side (the mode never preselected),
|
||||
the dry run's totals and space line, then per sequence the photos converted, those left as they are with why (what
|
||||
blocks the whole sequence first, ▲ in the warning colour) and the size before and after. */
|
||||
dialog.dialog.convert { width: 960px; }
|
||||
.convert-fields { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 12px 32px; }
|
||||
.convert-choice { border: 0; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px 20px; }
|
||||
.convert-choice legend { color: var(--text-muted); padding: 0; margin-block-end: 8px; }
|
||||
.convert-choice[aria-invalid="true"] { outline: 2px solid var(--error); outline-offset: 4px; border-radius: var(--radius); }
|
||||
.convert-quality .input { width: 88px; }
|
||||
.convert-summary { display: grid; gap: 4px; min-height: 18px; color: var(--text-muted); }
|
||||
.convert-space.short { color: var(--error); }
|
||||
.convert-next { color: var(--text); }
|
||||
.table.convert { grid-template-columns: minmax(140px, 1.3fr) max-content minmax(160px, 1.6fr) max-content; font-size: 12px; }
|
||||
.plan-notes { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; color: var(--text-muted); }
|
||||
.plan-notes .blocked { color: var(--warning); }
|
||||
|
||||
/* 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; }
|
||||
.table.reorg, .table.convert { grid-template-columns: minmax(0, 1fr); }
|
||||
.table.reorg .thead, .table.convert .thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.table.convert .end { justify-self: start; }
|
||||
}
|
||||
|
||||
/* About: the last group of Settings (owner review 2); #/about scrolls to it below the sticky header and focuses its heading. */
|
||||
|
||||
@@ -80,6 +80,13 @@ export function detailText(entry) {
|
||||
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(" · ");
|
||||
}
|
||||
// Owner review 2, R7: "sequences · photos · target · mode", e.g. "2 · 120 · linear-dng · replace".
|
||||
case "archive_converted": {
|
||||
const [sequences, photos, target, mode] = details.split(" · ");
|
||||
if (!/^\d+$/.test(sequences) || !/^\d+$/.test(photos ?? "")) return details;
|
||||
return [plural("Admin.Library.Count", Number(sequences)), plural("Admin.Dashboard.PhotoCount", Number(photos)),
|
||||
wireLabel("Admin.Convert.Format.", target), wireLabel("Admin.Convert.Mode.", mode)].filter(Boolean).join(" · ");
|
||||
}
|
||||
default:
|
||||
return details;
|
||||
}
|
||||
@@ -107,6 +114,13 @@ function scheduleNameIn(parts) {
|
||||
return scheduleName({ systemKey, name: (systemKey ? parts.slice(1) : parts).join(" · ") });
|
||||
}
|
||||
|
||||
/** A code of the API in words by its key under prefix ("linear-dng" → Admin.Convert.Format.LinearDng); else as recorded. */
|
||||
function wireLabel(prefix, code) {
|
||||
if (!code) return "";
|
||||
const key = prefix + pascal(code);
|
||||
return has(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
function splitLast(details) {
|
||||
const at = details.lastIndexOf(" · ");
|
||||
return at < 0 ? [details] : [details.slice(0, at), details.slice(at + 3)];
|
||||
|
||||
@@ -0,0 +1,542 @@
|
||||
// Convert dialog of the admin panel (owner review 2, R7; BRIEF §12.5, §14.8): the photos of the Library's selection, or of
|
||||
// every sequence, converted to JPEG, TIFF-16 or linear DNG. What happens to the originals is chosen at every run, never
|
||||
// preselected: Replace (the converted files become the sequence's photos, the originals go to the archive's trash) or New
|
||||
// sequence (converted copies in a new sequence, the source untouched; the photos left as they are are not in it). Each
|
||||
// change asks the server for a dry run (nothing is touched) and the table shows, per sequence, what converts, what stays
|
||||
// as it is and why, and the size before and after. The server makes a dry run apart from the request and keeps it a few
|
||||
// minutes, so one that takes longer than a proxy lets a request last is asked for again until it is made. Apply confirms
|
||||
// that very plan by its fingerprint (Replace by typing a word), and the server runs it as a job (kind "convert") that
|
||||
// verifies every converted file before anything changes.
|
||||
import { t, plural, applyStrings } from "./i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatDuration, toast, errorText, confirmDialog, markInvalid, clearInvalid } from "./ui.js";
|
||||
import { listed } from "./pages/library/shared.js";
|
||||
|
||||
const ENDPOINT = "/api/v1/archive/convert";
|
||||
/** Wait after the last keystroke in Quality before the dry run, and the steps the table draws at a time. */
|
||||
const PLAN_DELAY = 400;
|
||||
const PAGE = 200;
|
||||
const DEFAULT_QUALITY = 95;
|
||||
/**
|
||||
* A dry run the server is still making: a request cut off after CUT_AFTER ms or by a proxy's timeout (502, 504, 524, or
|
||||
* no answer) is asked again after RETRY_DELAY ms, for up to PLAN_PATIENCE ms (the server stops a plan after 15 minutes);
|
||||
* one the server stopped (503 plan_dropped) DROPPED_RETRIES times more. Past SLOW_PLAN seconds the totals tell how long.
|
||||
*/
|
||||
const CUT_AFTER = 20000;
|
||||
const RETRY_DELAY = 2000;
|
||||
const PLAN_PATIENCE = 16 * 60 * 1000;
|
||||
const DROPPED_RETRIES = 1;
|
||||
const SLOW_PLAN = 10;
|
||||
/**
|
||||
* Apply confirms only the plan the server keeps, a few minutes from when it was made: the dry run is asked first (at once
|
||||
* while kept, else made again), and a plan let go between that answer and the confirmation is asked for DROPPED_CONFIRMS
|
||||
* times more.
|
||||
*/
|
||||
const DROPPED_CONFIRMS = 1;
|
||||
/** The formats, as the API names them, with their strings; linear DNG, the archival choice, is the one chosen first. */
|
||||
const TARGETS = [
|
||||
{ value: "jpeg", label: "Admin.Convert.Format.Jpeg", tip: "Admin.Convert.Format.Jpeg.Tip" },
|
||||
{ value: "tiff16", label: "Admin.Convert.Format.Tiff16", tip: "Admin.Convert.Format.Tiff16.Tip" },
|
||||
{ value: "linear-dng", label: "Admin.Convert.Format.LinearDng", tip: "Admin.Convert.Format.LinearDng.Tip" },
|
||||
];
|
||||
const ARCHIVAL = "linear-dng";
|
||||
/** What happens to the originals; no default: the person converting chooses every time. */
|
||||
const MODES = [
|
||||
{ value: "replace", label: "Admin.Convert.Mode.Replace", tip: "Admin.Convert.Mode.Replace.Tip" },
|
||||
{ value: "new-sequence", label: "Admin.Convert.Mode.NewSequence", tip: "Admin.Convert.Mode.NewSequence.Tip" },
|
||||
];
|
||||
/**
|
||||
* The mode the dry run is asked with while none is chosen, whose words say only that photos stay as they are: what
|
||||
* converts does not depend on the mode, so the table shows the plan at once; Apply waits for a choice, and New sequence
|
||||
* asks again (the fingerprint names the mode, and the rows say what the new sequence lacks), answered from the plan the
|
||||
* server keeps.
|
||||
*/
|
||||
const PREVIEW_MODE = "replace";
|
||||
|
||||
let dialogs = 0;
|
||||
|
||||
/**
|
||||
* Opens the Convert 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. Resolves when the dialog closes: the queued
|
||||
* job, or null.
|
||||
*/
|
||||
export function openConvert({ api, target, names = new Map() } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const id = `convert-${++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;
|
||||
/** Apply asks the dry run again before it confirms (checking: nothing sent yet, Close stays), then sends it (busy). */
|
||||
let checking = 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.Convert.TitleAll") : plural("Admin.Convert.Title", target.sequenceIds.length);
|
||||
const radio = (name, o, checked) => `<label class="check" title="${attr(t(o.tip))}"><input type="radio" name="${name}" value="${o.value}"
|
||||
${checked ? "checked" : ""} title="${attr(t(o.tip))}"><span>${escapeHtml(t(o.label))}</span></label>`;
|
||||
|
||||
const dialog = document.createElement("dialog");
|
||||
dialog.className = "dialog convert";
|
||||
dialog.setAttribute("aria-labelledby", `${id}-title`);
|
||||
dialog.innerHTML = `
|
||||
<form novalidate>
|
||||
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
|
||||
<div class="convert-fields">
|
||||
<fieldset class="convert-choice" data-field="target"><legend data-i18n="Admin.Convert.Format"></legend>
|
||||
${TARGETS.map((o) => radio("target", o, o.value === ARCHIVAL)).join("")}</fieldset>
|
||||
<label class="field-label convert-quality"><span data-i18n="Admin.Convert.Quality"></span>
|
||||
<input class="input narrow" name="quality" type="number" min="1" max="100" step="1" inputmode="numeric" value="${DEFAULT_QUALITY}"
|
||||
autocomplete="off" data-i18n-title="Admin.Convert.Quality.Tip"></label>
|
||||
<fieldset class="convert-choice" data-field="mode" role="radiogroup" aria-required="true"><legend data-i18n="Admin.Convert.Mode"></legend>
|
||||
${MODES.map((o) => radio("mode", o, false)).join("")}</fieldset>
|
||||
</div>
|
||||
<div class="convert-summary" role="status">
|
||||
<span class="convert-totals"></span>
|
||||
<span class="convert-space" hidden></span>
|
||||
<span class="convert-next" hidden data-i18n="Admin.Convert.ChooseMode"></span>
|
||||
</div>
|
||||
<div class="plan-preview" role="region" tabindex="0" aria-label="${attr(t("Admin.Convert.Preview"))}" title="${attr(t("Admin.Convert.Preview.Tip"))}" hidden>
|
||||
<div class="table convert" role="table" aria-label="${attr(t("Admin.Convert.Preview"))}">
|
||||
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Convert.Column.Sequence"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Convert.Column.Converted"></span>
|
||||
<span role="columnheader" class="convert-left" data-i18n="Admin.Convert.Column.Unchanged"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Convert.Column.Size"></span></div>
|
||||
<div role="rowgroup" class="convert-rows"></div>
|
||||
</div>
|
||||
<div class="table-foot" hidden><span class="muted convert-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.Convert.Cancel.Tip"></button>
|
||||
<button class="btn primary" type="button" data-act="apply" disabled data-i18n="Admin.Convert.Apply" data-i18n-title="Admin.Convert.Apply.Tip"></button>
|
||||
</div>
|
||||
</form>`;
|
||||
document.body.appendChild(dialog);
|
||||
applyStrings(dialog);
|
||||
const form = dialog.querySelector("form");
|
||||
const quality = form.elements.quality;
|
||||
const qualityField = dialog.querySelector(".convert-quality");
|
||||
const targetSet = dialog.querySelector('[data-field="target"]');
|
||||
const modeSet = dialog.querySelector('[data-field="mode"]');
|
||||
const totals = dialog.querySelector(".convert-totals");
|
||||
const space = dialog.querySelector(".convert-space");
|
||||
const next = dialog.querySelector(".convert-next");
|
||||
const preview = dialog.querySelector(".plan-preview");
|
||||
const rows = dialog.querySelector(".convert-rows");
|
||||
const leftHeader = dialog.querySelector(".convert-left");
|
||||
const foot = dialog.querySelector(".table-foot");
|
||||
const shownText = dialog.querySelector(".convert-shown");
|
||||
const errorLine = dialog.querySelector(".error");
|
||||
const closeButton = dialog.querySelector('[data-act="close"]');
|
||||
const applyButton = dialog.querySelector('[data-act="apply"]');
|
||||
|
||||
for (const set of [targetSet, modeSet]) {
|
||||
set.addEventListener("change", () => {
|
||||
clearInvalid(set);
|
||||
showError("");
|
||||
drawQuality();
|
||||
// Choosing the mode the table was planned with needs no new dry run.
|
||||
if (!planning && plan !== null && plan.key === keyNow()) drawPlan();
|
||||
else schedule(0);
|
||||
});
|
||||
}
|
||||
quality.addEventListener("input", () => {
|
||||
clearInvalid(quality);
|
||||
showError("");
|
||||
schedule(PLAN_DELAY);
|
||||
});
|
||||
// Enter in Quality plans at once; only the Apply button changes anything.
|
||||
form.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
if (!busy) schedule(0);
|
||||
});
|
||||
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();
|
||||
drawQuality();
|
||||
targetSet.querySelector("input:checked").focus();
|
||||
schedule(0);
|
||||
|
||||
/** The value of a choice's checked radio button, null while none is. */
|
||||
function chosen(set) {
|
||||
return set.querySelector("input:checked")?.value ?? null;
|
||||
}
|
||||
|
||||
/** The quality typed, a whole number from 1 to 100, else null. */
|
||||
function qualityValue() {
|
||||
const text = quality.value.trim();
|
||||
const n = Number(text);
|
||||
return /^\d+$/.test(text) && n >= 1 && n <= 100 ? n : null;
|
||||
}
|
||||
|
||||
/** The request the fields make (without dryRun); its quality only for a JPEG, its mode the preview's until one is chosen. */
|
||||
function request() {
|
||||
const body = target.all ? { all: true } : { all: false, sequenceIds: target.sequenceIds };
|
||||
const format = chosen(targetSet);
|
||||
body.target = format;
|
||||
body.quality = format === "jpeg" ? qualityValue() : null;
|
||||
body.mode = chosen(modeSet) ?? PREVIEW_MODE;
|
||||
return body;
|
||||
}
|
||||
|
||||
function keyNow() {
|
||||
return JSON.stringify(request());
|
||||
}
|
||||
|
||||
/** Quality is a JPEG's alone: hidden for the lossless formats. */
|
||||
function drawQuality() {
|
||||
qualityField.hidden = chosen(targetSet) !== "jpeg";
|
||||
}
|
||||
|
||||
/** 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 (!dialog.open) return;
|
||||
if (planning) {
|
||||
again = true;
|
||||
return;
|
||||
}
|
||||
if (chosen(targetSet) === "jpeg" && qualityValue() === null) {
|
||||
plan = null;
|
||||
fieldError(quality, t("Admin.Convert.QualityRange"));
|
||||
drawPlan();
|
||||
return;
|
||||
}
|
||||
const body = request();
|
||||
const key = JSON.stringify(body);
|
||||
planning = true;
|
||||
drawButtons();
|
||||
try {
|
||||
const answer = await waiting(() => dryRun(body, key));
|
||||
if (!dialog.open) return;
|
||||
plan = { ...answer, key };
|
||||
shown = PAGE;
|
||||
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();
|
||||
}
|
||||
|
||||
/** Runs work while the totals say it is planning and, once that is long, for how long, with why in their tooltip. */
|
||||
async function waiting(work) {
|
||||
const started = Date.now();
|
||||
const showWait = () => {
|
||||
const seconds = Math.floor((Date.now() - started) / 1000);
|
||||
totals.textContent = seconds < SLOW_PLAN ? t("Admin.Convert.Planning") : t("Admin.Convert.PlanningFor", formatDuration(seconds));
|
||||
};
|
||||
const ticking = setInterval(showWait, 1000);
|
||||
showWait();
|
||||
totals.title = t("Admin.Convert.Planning.Tip");
|
||||
try {
|
||||
return await work();
|
||||
} finally {
|
||||
clearInterval(ticking);
|
||||
totals.title = "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The dry run of body. The server makes it apart from the request and keeps it a few minutes, so a request cut off on
|
||||
* the way (a proxy's timeout) is asked again, and answered once the plan is made; a plan the server stopped (let go for
|
||||
* newer ones, past its time) is asked for once more. Gives up past PLAN_PATIENCE, or once the fields changed or the
|
||||
* dialog closed: the last failure is thrown.
|
||||
*/
|
||||
async function dryRun(body, key) {
|
||||
const started = Date.now();
|
||||
let dropped = 0;
|
||||
for (;;) {
|
||||
const sent = Date.now();
|
||||
try {
|
||||
return await api.post(ENDPOINT, { ...body, dryRun: true });
|
||||
} catch (err) {
|
||||
const retry = cutOff(err, Date.now() - sent) || (err?.code === "plan_dropped" && dropped++ < DROPPED_RETRIES);
|
||||
if (!retry || Date.now() - started > PLAN_PATIENCE || !dialog.open || key !== keyNow()) throw err;
|
||||
await new Promise((done) => setTimeout(done, RETRY_DELAY));
|
||||
if (!dialog.open || key !== keyNow()) throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawPlan() {
|
||||
const current = plan !== null && plan.key === keyNow();
|
||||
preview.classList.toggle("stale", !current);
|
||||
if (!plan) {
|
||||
totals.textContent = "";
|
||||
space.hidden = true;
|
||||
next.hidden = true;
|
||||
preview.hidden = true;
|
||||
} else {
|
||||
// New sequence's words: the photos left as they are in the sequences copied are not copied into the new sequences.
|
||||
const copies = plan.mode === "new-sequence";
|
||||
leftHeader.textContent = t(copies ? "Admin.Convert.Column.NotCopied" : "Admin.Convert.Column.Unchanged");
|
||||
totals.textContent = plan.photos === 0 ? t("Admin.Convert.NothingToConvert")
|
||||
: t(copies ? "Admin.Convert.TotalsNew" : "Admin.Convert.Totals", formatNumber(plan.sequences), formatNumber(plan.photos),
|
||||
formatNumber(copies ? leftOut(converting(plan.steps)) : plan.skipped), formatBytes(plan.bytesBefore), formatBytes(plan.bytesAfter));
|
||||
space.hidden = plan.photos === 0;
|
||||
space.textContent = plan.space.message;
|
||||
space.classList.toggle("short", !plan.space.enough);
|
||||
next.hidden = plan.photos === 0 || !plan.space.enough || chosen(modeSet) !== null;
|
||||
preview.hidden = plan.steps.length === 0;
|
||||
if (!preview.hidden) 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 sequence: its title and folder, the photos converted (or what blocks it), the photos left as they are with why,
|
||||
* and the size of those converted before and after (an estimate).
|
||||
*/
|
||||
function rowHtml(s) {
|
||||
const name = names.get(s.sequenceId) || s.title || folderName(s.folder);
|
||||
const blocked = s.blocked ?? [];
|
||||
const skipped = s.skipped ?? [];
|
||||
const converts = blocked.length === 0 && s.photos > 0;
|
||||
const count = converts ? `<strong class="num">${escapeHtml(formatNumber(s.photos))}</strong>` : `<span class="muted">—</span>`;
|
||||
// What blocks the whole sequence first, then the photos left as they are.
|
||||
const notes = [...blocked.map((b) => `<li class="blocked"><span aria-hidden="true">▲</span> ${escapeHtml(b.message)}</li>`),
|
||||
...skipped.map((k) => `<li>${escapeHtml(t("Admin.Convert.SkippedPhotos", plural("Admin.Dashboard.PhotoCount", k.photos), k.message))}</li>`)];
|
||||
const left = notes.length > 0 ? `<ul class="plan-notes">${notes.join("")}</ul>` : `<span class="muted">—</span>`;
|
||||
const size = converts
|
||||
? `<span class="num nowrap" dir="auto" title="${attr(t("Admin.Convert.Size.Tip"))}">${escapeHtml(t("Admin.Convert.SizeChange", formatBytes(s.bytesBefore), formatBytes(s.bytesAfter)))}</span>`
|
||||
: `<span class="muted">—</span>`;
|
||||
return `<div class="row${converts ? "" : " dim"}" role="row" data-key="${attr(s.sequenceId)}">
|
||||
<span role="cell" class="stack"><strong class="ellipsis" dir="auto" title="${attr(name)}">${escapeHtml(name)}</strong>
|
||||
<small class="path" dir="ltr" title="${attr(s.folder || "/")}">${escapeHtml(s.folder || "/")}</small></span>
|
||||
<span role="cell" class="end">${count}</span>
|
||||
<span role="cell">${left}</span>
|
||||
<span role="cell" class="end">${size}</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply waits for a current plan that converts something, with the space it needs, and for the mode; its tooltip says
|
||||
* which. While Apply asks the dry run again the fields and Apply wait, and Close stays: nothing was sent to convert yet.
|
||||
*/
|
||||
function drawButtons() {
|
||||
for (const field of form.querySelectorAll("input")) field.disabled = busy || checking;
|
||||
const current = plan !== null && plan.key === keyNow() && !planning;
|
||||
const mode = chosen(modeSet);
|
||||
const reason = !current ? null
|
||||
: plan.photos === 0 ? "Admin.Convert.Nothing.Tip"
|
||||
: !plan.space.enough ? "Admin.Convert.NoSpace.Tip"
|
||||
: mode === null ? "Admin.Convert.ChooseMode.Tip" : null;
|
||||
applyButton.disabled = busy || checking || !current || reason !== null;
|
||||
applyButton.title = t(reason ?? "Admin.Convert.Apply.Tip");
|
||||
closeButton.disabled = busy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace asks for a word to be typed (the originals leave the sequence for the trash); New sequence for a plain
|
||||
* confirmation that says how many photos the new sequences lack, and each sequence's count in the list. 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. The server confirms only the plan it keeps, which lives a few minutes from
|
||||
* when it was made: the dry run is asked first, answered at once while it is kept and otherwise made again while the
|
||||
* totals say so (Close stays meanwhile, nothing being sent yet); the same fingerprint is then confirmed, and a
|
||||
* different one is shown instead.
|
||||
*/
|
||||
async function apply() {
|
||||
if (applyButton.disabled) return;
|
||||
const shownPlan = plan;
|
||||
const body = JSON.parse(shownPlan.key);
|
||||
const format = targetLabel(body.target);
|
||||
const going = converting(shownPlan.steps);
|
||||
const replace = body.mode === "replace";
|
||||
const list = listed(going.map((s) => {
|
||||
const item = t("Admin.Convert.PlanItem", names.get(s.sequenceId) || s.title || folderName(s.folder),
|
||||
plural("Admin.Dashboard.PhotoCount", s.photos), t("Admin.Convert.SizeChange", formatBytes(s.bytesBefore), formatBytes(s.bytesAfter)));
|
||||
const left = leftOut([s]);
|
||||
return replace || left === 0 ? item : t("Admin.Convert.PlanItemNotCopied", item, plural("Admin.Convert.NotCopiedCount", left));
|
||||
}));
|
||||
// The photos of the sequences converted that stay as they are: their new sequences hold the converted copies alone.
|
||||
const notCopied = leftOut(going);
|
||||
const confirmed = await confirmDialog(replace ? {
|
||||
title: t("Admin.Convert.ConfirmReplaceTitle", format),
|
||||
body: plural("Admin.Convert.ConfirmReplace", shownPlan.photos, plural("Admin.Library.Count", shownPlan.sequences)),
|
||||
list,
|
||||
confirm: t("Admin.Convert.Confirm.Replace"),
|
||||
confirmTip: t("Admin.Convert.Confirm.Replace.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
typed: t("Admin.Convert.ReplaceWord"),
|
||||
typedKind: "word",
|
||||
} : {
|
||||
title: t("Admin.Convert.ConfirmNewTitle", format),
|
||||
body: [plural("Admin.Convert.ConfirmNew", shownPlan.photos), notCopied > 0 ? plural("Admin.Convert.ConfirmNewNotCopied", notCopied) : ""]
|
||||
.filter(Boolean).join(" "),
|
||||
list,
|
||||
confirm: t("Admin.Convert.Confirm.New"),
|
||||
confirmTip: t("Admin.Convert.Confirm.New.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
});
|
||||
if (!confirmed || !dialog.open) return;
|
||||
if (plan !== shownPlan && (plan?.key !== shownPlan.key || plan.fingerprint !== shownPlan.fingerprint)) {
|
||||
// A failed dry run already says why; a new plan is on screen to be checked.
|
||||
if (plan) showError(t("Admin.Convert.PlanChanged"));
|
||||
return;
|
||||
}
|
||||
showError("");
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
// The dry run first, while the totals say so: nothing is sent to convert yet, so Close stays.
|
||||
checking = true;
|
||||
drawButtons();
|
||||
let now;
|
||||
try {
|
||||
now = await waiting(() => dryRun(body, shownPlan.key));
|
||||
} catch (err) {
|
||||
// Nothing was sent to convert: the plan shown stays, and Apply asks again.
|
||||
checking = false;
|
||||
if (!dialog.open) return;
|
||||
drawPlan();
|
||||
showProblem(err);
|
||||
applyButton.focus();
|
||||
return;
|
||||
}
|
||||
checking = false;
|
||||
// Closed meanwhile: nothing is sent.
|
||||
if (!dialog.open) return;
|
||||
if (now.fingerprint !== shownPlan.fingerprint) {
|
||||
// Made again, and no longer the plan confirmed: shown, and Apply waits for the user.
|
||||
plan = { ...now, key: shownPlan.key };
|
||||
shown = PAGE;
|
||||
drawPlan();
|
||||
showError(t("Admin.Convert.PlanChanged"));
|
||||
(applyButton.disabled ? closeButton : applyButton).focus();
|
||||
return;
|
||||
}
|
||||
busy = true;
|
||||
drawButtons();
|
||||
try {
|
||||
const job = await api.post(ENDPOINT, { ...body, dryRun: false, fingerprint: shownPlan.fingerprint });
|
||||
queued = job;
|
||||
busy = false;
|
||||
dialog.close();
|
||||
toast(t("Admin.Convert.Queued"), false,
|
||||
{ label: t("Admin.Convert.OpenJob"), tip: t("Admin.Convert.OpenJob.Tip"), href: `#/jobs?job=${encodeURIComponent(job.id)}` });
|
||||
return;
|
||||
} catch (err) {
|
||||
busy = false;
|
||||
// Let go between the dry run's answer and the confirmation: asked again, as the dry run was.
|
||||
if (err?.code === "plan_dropped" && attempt < DROPPED_CONFIRMS && dialog.open) continue;
|
||||
if (!dialog.open) return;
|
||||
drawPlan();
|
||||
if (["plan_changed", "plan_dropped", "not_enough_space", "nothing_to_convert"].includes(err?.code)) {
|
||||
// The archive changed since the dry run (or a conversion of these sequences was queued meanwhile, or the volume
|
||||
// filled up, or the server let the plan go): nothing was queued; the plan is made again and shown, and Apply
|
||||
// waits for it.
|
||||
notice = err.code === "plan_changed" ? t("Admin.Convert.PlanChanged") : errorText(err);
|
||||
plan = null;
|
||||
schedule(0);
|
||||
} else if (cutOff(err, Infinity)) {
|
||||
// No answer: the job may have been queued all the same, and Apply again would queue another one.
|
||||
showError(t("Admin.Convert.NoAnswer"));
|
||||
} else {
|
||||
showProblem(err);
|
||||
}
|
||||
drawButtons();
|
||||
(applyButton.disabled ? closeButton : applyButton).focus();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The steps that convert: nothing blocks them, and they have photos to convert. */
|
||||
function converting(steps) {
|
||||
return steps.filter((s) => (s.blocked ?? []).length === 0 && s.photos > 0);
|
||||
}
|
||||
|
||||
/** The photos steps leave as they are: of a sequence New sequence copies, those its new sequence lacks. */
|
||||
function leftOut(steps) {
|
||||
return steps.reduce((sum, s) => sum + (s.skipped ?? []).reduce((photos, k) => photos + k.photos, 0), 0);
|
||||
}
|
||||
|
||||
/** A refusal on the field it names (quality, format, mode), else under the table. */
|
||||
function showProblem(err) {
|
||||
const field = err?.code === "bad_request" ? { quality, target: targetSet, mode: modeSet }[err.details] : undefined;
|
||||
if (field === quality) fieldError(quality, t("Admin.Convert.QualityRange"));
|
||||
else if (field) fieldError(field, errorText(err));
|
||||
else if (err?.code === "not_found") showError(t("Admin.Convert.Gone"));
|
||||
else showError(errorText(err));
|
||||
}
|
||||
|
||||
/** The field's error border with the message as its tooltip (DESIGN §4), and the message in the dialog's alert line. */
|
||||
function fieldError(field, message) {
|
||||
markInvalid(field, message);
|
||||
showError(message);
|
||||
}
|
||||
|
||||
function showError(message) {
|
||||
errorLine.textContent = message;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a request that failed after ms milliseconds was cut off on the way rather than answered: a proxy's timeout (504,
|
||||
* or Cloudflare's 524), or a closed connection or a 502 once it had lasted CUT_AFTER (sooner, the server is not there).
|
||||
*/
|
||||
function cutOff(err, ms) {
|
||||
return err?.status === 504 || err?.status === 524 || ((err?.status === 0 || err?.status === 502) && ms >= CUT_AFTER);
|
||||
}
|
||||
|
||||
/** A format's name in the panel's language ("jpeg" → "JPEG", "linear-dng" → "Linear DNG"). */
|
||||
function targetLabel(value) {
|
||||
const known = TARGETS.find((o) => o.value === value);
|
||||
return known ? t(known.label) : String(value ?? "");
|
||||
}
|
||||
|
||||
/** 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() ?? "—";
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
// 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).
|
||||
// Reorganize (R7) applies new folder, file and title templates to the selection (reorganize.js), Convert (R7) converts its
|
||||
// photos to JPEG, TIFF-16 or linear DNG (convert.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";
|
||||
@@ -9,6 +10,7 @@ import { BULK_LIMIT, factsLine, captureText, cameraLabel, statusChips, lazyImage
|
||||
import { renderSequence } from "./library/sequence.js";
|
||||
import { renderTrash } from "./library/trash.js";
|
||||
import { openReorganize } from "../reorganize.js";
|
||||
import { openConvert } from "../convert.js";
|
||||
|
||||
const VIEW_KEY = "chronos.admin.library.view";
|
||||
const PAGE = 100;
|
||||
@@ -345,6 +347,7 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
|
||||
<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-convert" data-mass="convert" data-i18n="Admin.Convert.Action" data-i18n-title="Admin.Convert.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>
|
||||
@@ -364,8 +367,9 @@ 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.
|
||||
// Modal dialogs: the button stays enabled, so the focus comes back to it when the dialog closes.
|
||||
if (action === "reorganize") return reorganize();
|
||||
if (action === "convert") return convert();
|
||||
button.disabled = true;
|
||||
try {
|
||||
if (action === "job") await queueJobs(button.dataset.kind);
|
||||
@@ -425,20 +429,36 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* What a plan-first mass operation (owner review 2, R7: Reorganize, Convert) works on: the selected sequences' 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. Null, with tooMany's toast, otherwise.
|
||||
*/
|
||||
async function reorganize() {
|
||||
function planTarget(tooMany) {
|
||||
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;
|
||||
toast(t(tooMany, formatNumber(BULK_LIMIT)), true);
|
||||
return null;
|
||||
}
|
||||
return everything ? { all: true } : { sequenceIds: ids };
|
||||
}
|
||||
|
||||
/** Reorganize of the selected sequences: new folder, file and title templates, with a dry run. */
|
||||
async function reorganize() {
|
||||
const target = planTarget("Admin.Reorganize.TooMany");
|
||||
if (!target) return;
|
||||
const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle]));
|
||||
await openReorganize({ api, target: everything ? { all: true } : { sequenceIds: ids }, names });
|
||||
await openReorganize({ api, target, names });
|
||||
}
|
||||
|
||||
/** Convert of the selected sequences' photos: the format and, at every run, Replace or New sequence, with a dry run. */
|
||||
async function convert() {
|
||||
const target = planTarget("Admin.Convert.TooMany");
|
||||
if (!target) return;
|
||||
const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle]));
|
||||
await openConvert({ api, target, names });
|
||||
}
|
||||
|
||||
async function retag() {
|
||||
|
||||
@@ -78,7 +78,7 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
|
||||
<span class="col-by ellipsis" role="cell" dir="auto">${escapeHtml(e.deletedBy ?? "—")}</span>
|
||||
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(e.deletedAt))}</span>
|
||||
<span class="row-actions" role="cell"><button class="btn small" data-restore="${attr(e.name)}" data-i18n="Admin.Trash.Restore"
|
||||
data-i18n-title="${e.kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : "Admin.Trash.RestorePhotos.Tip"}" ${restoring.has(e.name) ? "disabled" : ""}></button></span>
|
||||
data-i18n-title="${restoreTip(e.kind)}" ${restoring.has(e.name) ? "disabled" : ""}></button></span>
|
||||
</div>`).join("")
|
||||
|| `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Trash.IsEmpty",
|
||||
`<a class="btn small" href="${attr(back)}" data-i18n="Admin.Trash.Back" data-i18n-title="Admin.Trash.Back.Tip"></a>`)}</div></div>`;
|
||||
@@ -104,8 +104,11 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
|
||||
else draw();
|
||||
return;
|
||||
}
|
||||
// A replaced entry (owner review 2, R7) swaps back: its originals take their conversions' place, which go to the trash.
|
||||
const lines = [result.kind === "sequence" ? t("Admin.Trash.RestoredSequence", entry.title)
|
||||
: result.newSequence ? plural("Admin.Trash.RestoredNew", result.photos) : plural("Admin.Trash.RestoredPhotos", result.photos, entry.title)];
|
||||
: result.newSequence ? plural("Admin.Trash.RestoredNew", result.photos)
|
||||
: result.kind === "replaced" ? plural("Admin.Trash.RestoredOriginals", result.photos, entry.title)
|
||||
: plural("Admin.Trash.RestoredPhotos", result.photos, entry.title)];
|
||||
// The server says, in the page's language, how many photos stayed in the trash and why (one sentence per reason).
|
||||
if (result.kept.length > 0 && result.message) lines.push(result.message);
|
||||
toast(lines.join(" "), result.kept.length > 0);
|
||||
@@ -133,7 +136,10 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("Admin.Trash.EmptyTitle"),
|
||||
body: [plural("Admin.Trash.EmptyBody", plan.files, formatBytes(plan.bytes)), t("Admin.Trash.EmptyFinal")].join(" "),
|
||||
list: plan.entries.map((e) => t("Admin.Trash.PlanItem", kindLabel(e.kind), e.title, formatBytes(e.bytes))),
|
||||
// Replaced originals whose conversion was deleted since may be the last copy of their photos: the list names them
|
||||
// first, each saying so, wherever the trash lists them.
|
||||
list: [...plan.entries.filter((e) => e.conversionDeleted), ...plan.entries.filter((e) => !e.conversionDeleted)].map((e) => t("Admin.Trash.PlanItem",
|
||||
e.conversionDeleted ? `${kindLabel(e.kind)} · ${t("Admin.Trash.ConversionDeleted")}` : kindLabel(e.kind), e.title, formatBytes(e.bytes))),
|
||||
confirm: t("Admin.Trash.EmptyConfirm"),
|
||||
confirmTip: t("Admin.Trash.EmptyConfirm.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
@@ -212,6 +218,11 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
|
||||
await load();
|
||||
}
|
||||
|
||||
/** What Restore does to an entry of this kind: a sequence's folder back, photos back, or originals back in place of their conversions. */
|
||||
function restoreTip(kind) {
|
||||
return kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : kind === "replaced" ? "Admin.Trash.RestoreReplaced.Tip" : "Admin.Trash.RestorePhotos.Tip";
|
||||
}
|
||||
|
||||
function kindLabel(kind) {
|
||||
return t(kind === "sequence" ? "Admin.Trash.Kind.Sequence" : kind === "replaced" ? "Admin.Trash.Kind.Replaced" : "Admin.Trash.Kind.Photos");
|
||||
}
|
||||
@@ -48,8 +48,8 @@ public static class AdminEndpoints
|
||||
var users = await db.Users.ListAsync(ct);
|
||||
var names = users.ToDictionary(u => u.Id, u => u.Username);
|
||||
var counts = await db.Jobs.CountAsync(today, ct);
|
||||
var running = await db.Jobs.ListAsync(JobState.Running, null, 10, null, ct);
|
||||
var queued = await db.Jobs.ListAsync(JobState.Queued, null, 10, null, ct);
|
||||
var running = await db.Jobs.ListBriefAsync(JobState.Running, null, 10, null, ct);
|
||||
var queued = await db.Jobs.ListBriefAsync(JobState.Queued, null, 10, null, ct);
|
||||
var nodes = await db.RenderNodes.ListAsync(ct);
|
||||
var uploads = await db.Uploads.CommittedPerDayAsync(today.AddDays(-29), ct);
|
||||
var activity = await db.Audit.ListAsync(null, null, 12, null, ct);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Conversion;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
@@ -15,8 +17,9 @@ 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, and
|
||||
/// Reorganize (owner review 2, R7): new templates applied to sequences already in the archive.
|
||||
/// <c>/api/v1/archive</c> (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics,
|
||||
/// Reorganize (owner review 2, R7): new templates applied to sequences already in the archive, and Convert (R7): their
|
||||
/// photos converted to JPEG, TIFF-16 or linear DNG, replacing them or into new sequences.
|
||||
/// </summary>
|
||||
public static class ArchiveEndpoints
|
||||
{
|
||||
@@ -24,6 +27,7 @@ public static class ArchiveEndpoints
|
||||
{
|
||||
var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive);
|
||||
archive.MapPost("/reorganize", ReorganizeAsync);
|
||||
archive.MapPost("/convert", ConvertAsync);
|
||||
// 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));
|
||||
@@ -157,14 +161,14 @@ public static class ArchiveEndpoints
|
||||
/// 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
|
||||
/// from the index stays as it was (<see cref="PlanCache"/>; 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)
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, PlanCache plans)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (request.All == (request.SequenceIds is not null) || request.SequenceIds is { Count: 0 or > LibraryEndpoints.MaxBulkIds })
|
||||
@@ -177,7 +181,7 @@ public static class ArchiveEndpoints
|
||||
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);
|
||||
var key = ReorganizePlanKey.Of(archive.Id, await db.Sequences.GetStampAsync(archive.Id, sequences, ct), sequences, templates);
|
||||
RenamePlan plan;
|
||||
try
|
||||
{
|
||||
@@ -250,6 +254,239 @@ public static class ArchiveEndpoints
|
||||
_ => "unreadable",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Convert: the photos of <c>sequenceIds</c> or, with <c>all</c>, of every sequence of the archive, converted to
|
||||
/// <c>target</c> (<c>jpeg</c>, <c>tiff16</c>, <c>linear-dng</c>) at <c>quality</c> (JPEG, 1–100, default 95) in <c>mode</c>
|
||||
/// (<c>replace</c> or <c>new-sequence</c>; BRIEF §12.5). With <c>dryRun</c> the plan, nothing touched: per sequence the
|
||||
/// photos converted, their size and the estimate after, the photos left as they are with why in the mode's words (of a
|
||||
/// sequence <c>new-sequence</c> copies, that the new sequence lacks them; <c>convert_on_pc</c> for a format the server
|
||||
/// cannot read at full resolution), what blocks it; the totals; the space needed and free; the fingerprint. Otherwise
|
||||
/// the request carries that fingerprint and the server queues a <c>convert</c> job (202) that converts exactly the photos
|
||||
/// that plan converts, leaving as it is (and reporting) a sequence where one of them 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>target</c>, <c>quality</c>, <c>mode</c>, <c>fingerprint</c>); 404
|
||||
/// <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>plan_changed</c> (details: the fingerprint now; none
|
||||
/// when a conversion of these sequences was queued meanwhile), <c>nothing_to_convert</c>, <c>not_enough_space</c>
|
||||
/// (details: the bytes needed), <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; for a confirmation, no plan is kept for the
|
||||
/// index as it is now, let go since or the index changed: ask the dry run again, and confirm that one). Audited
|
||||
/// (<c>archive_converted</c>: sequences · photos · target · mode); the job tells each sequence it replaces the frames of
|
||||
/// as <c>sequenceChanged</c> <c>converted</c>, each new one as <c>created</c>. A dry run's plan is made apart from the
|
||||
/// request, a few at once (Reorganize's among them) 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="PlanCache"/>, <see cref="ConvertPlanKey"/>: the
|
||||
/// sequences' rows, and of the photos of those planned their formats, sizes, hashes and the flags that decide): the
|
||||
/// same dry run again (also after the first was cut off), in either mode and at any quality of a lossless target, takes
|
||||
/// it instead of planning again, and a confirmation takes only it, never planning inside its own request (a proxy could
|
||||
/// cut that off once the job is queued); the sequences jobs make busy and the free space are as they are at every
|
||||
/// request. So a confirmation answers <c>plan_dropped</c> when the index changed, and <c>plan_changed</c> when the plan
|
||||
/// kept is not the one confirmed (a job started or ended on one of its sequences since). One made on disk alone since
|
||||
/// the plan is found by the job, which plans again and converts the photos confirmed alone, each only while it holds
|
||||
/// the content confirmed, leaving the sequence as it is otherwise.
|
||||
/// </summary>
|
||||
private static async Task<IResult> ConvertAsync(HttpContext context, Caller caller, ConvertRequest request, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, PlanCache 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");
|
||||
if (TargetOf(request.Target) is not { } target) return ApiErrors.BadRequest(context, "bad_request", "target");
|
||||
var quality = request.Quality ?? ConvertOptions.DefaultQuality;
|
||||
if (quality is < 1 or > 100) return ApiErrors.BadRequest(context, "bad_request", "quality");
|
||||
if (ModeOf(request.Mode) is not { } mode) return ApiErrors.BadRequest(context, "bad_request", "mode");
|
||||
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 options = new ConvertOptions(target, quality);
|
||||
var sequences = request.All ? null : request.SequenceIds;
|
||||
var engine = LibraryEndpoints.Engine(archives, db);
|
||||
// Stamped before planning: a change committed while the plan is made gives the next request another key.
|
||||
var key = ConvertPlanKey.Of(archive.Id, await db.Sequences.GetConvertStampAsync(archive.Id, sequences, ct), sequences, options);
|
||||
ConvertPlan plan;
|
||||
try
|
||||
{
|
||||
ConvertPlan kept;
|
||||
if (request.DryRun)
|
||||
{
|
||||
// Made whatever becomes of this request, until the cache stops it: the same request again takes it, in either mode.
|
||||
kept = await plans.GetOrPlanAsync(key, stop => PlanConvertAsync(engine, archive.Current, sequences, options, stop), ct);
|
||||
}
|
||||
else if (plans.Kept(key) is { } shown)
|
||||
{
|
||||
kept = await shown;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Let go since its dry run (past its lifetime, or for newer plans): planned again inside this request, it could
|
||||
// outlast a proxy, which would cut it off after its job was queued. The client asks the dry run again.
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "plan_dropped");
|
||||
}
|
||||
// What converts is the same in either mode and at any quality of a lossless target: the request's own are set on
|
||||
// it; the sequences busy and the free space are as they are now.
|
||||
plan = Now(kept with { Options = options, Mode = mode }, await engine.Converter.BusyAsync(ct), await FreeSpaceAsync(engine, archive.Id, options, ct));
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
||||
}
|
||||
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.ConvertPlanDto);
|
||||
if (!string.Equals(fingerprint, request.Fingerprint, StringComparison.Ordinal)) return ApiErrors.Conflict(context, "plan_changed", fingerprint);
|
||||
if (plan.Frames == 0) return ApiErrors.Conflict(context, "nothing_to_convert");
|
||||
if (!plan.Space.Enough) return ApiErrors.Conflict(context, "not_enough_space", plan.Space.Required.ToString(CultureInfo.InvariantCulture));
|
||||
if (!host.CanRun(JobKind.Convert)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.Convert));
|
||||
Job? job = null;
|
||||
try
|
||||
{
|
||||
// Checked against the conversions pending and queued under one lock: two confirmations at once queue one job.
|
||||
await engine.Converter.QueueAsync(archive.Current, plan, async r => job = await host.Engine.EnqueueAsync(r, caller.Id, ct), ct);
|
||||
}
|
||||
catch (ConversionQueuedException)
|
||||
{
|
||||
// Another tab or user queued a conversion of these sequences since: the dry run now shows them busy.
|
||||
return ApiErrors.Conflict(context, "plan_changed");
|
||||
}
|
||||
plans.Forget(key);
|
||||
await audit.WriteAsync(caller, context, "archive_converted", "job", job!.Id.ToString(),
|
||||
$"{plan.Converted.Count()} · {plan.Frames} · {Wire(target)} · {Wire(mode)}");
|
||||
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A kept conversion plan as it stands now: each sequence busy or not as the jobs are now (<see cref="MassConverter.BusyAsync"/>:
|
||||
/// a kept plan never shows one busy once its job ended, nor free once a conversion of it was queued), and the space it
|
||||
/// needs for the sequences that convert then, against the free space measured now. A busy sequence is planned all the
|
||||
/// same, so its photos are those it converts once free.
|
||||
/// </summary>
|
||||
private static ConvertPlan Now(ConvertPlan plan, IReadOnlySet<Guid> busy, long? free)
|
||||
{
|
||||
var archiveBusy = busy.Contains(plan.ArchiveId);
|
||||
List<ConvertSequencePlan> sequences = [.. plan.Sequences.Select(s => s with { Blocked = Blocks(s.Blocked, archiveBusy || busy.Contains(s.SequenceId)) })];
|
||||
var estimated = sequences.Where(s => s.Converts).Sum(s => s.BytesAfter);
|
||||
return plan with { Sequences = sequences, Space = new ConvertSpace(ConvertPlanner.Required(estimated), free) };
|
||||
|
||||
// In the order a plan made now lists them: offline, busy, then what its sidecar said.
|
||||
static IReadOnlyList<ConvertBlock> Blocks(IReadOnlyList<ConvertBlock> blocked, bool held) =>
|
||||
[.. blocked.Where(b => b == ConvertBlock.Offline), .. held ? [ConvertBlock.Busy] : (ConvertBlock[])[], .. blocked.Where(b => b is not (ConvertBlock.Offline or ConvertBlock.Busy))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The conversion plan <see cref="PlanCache"/> keeps for a <see cref="ConvertPlanKey"/>, made in one mode for both (the
|
||||
/// request's is set on it, and the busy sequences and free space at every request: <see cref="Now"/>). One made while
|
||||
/// the archive's volume was away read nothing of it: it is not kept, and the request is answered <c>archive_offline</c>.
|
||||
/// </summary>
|
||||
private static async Task<ConvertPlan> PlanConvertAsync(ArchiveService engine, Archive archive, IReadOnlyList<Guid>? sequences, ConvertOptions options,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var plan = await engine.PlanConvertAsync(archive.Id, sequences, options, ConvertMode.Replace, cancellationToken);
|
||||
if (plan.Sequences.Any(s => s.Blocked.Contains(ConvertBlock.Offline))) throw new ArchiveOfflineException(archive.RootPath, ArchiveAvailability.Offline);
|
||||
return plan;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The free space of the archive's volume now, as the engine measures it for a conversion's plan and its job
|
||||
/// (<see cref="ArchiveServiceOptions.FreeSpace"/>): the plan of no sequence reads no sidecar and no photo.
|
||||
/// </summary>
|
||||
private static async Task<long?> FreeSpaceAsync(ArchiveService engine, Guid archiveId, ConvertOptions options, CancellationToken cancellationToken) =>
|
||||
(await engine.PlanConvertAsync(archiveId, [], options, ConvertMode.Replace, cancellationToken)).Space.Free;
|
||||
|
||||
/// <summary>The conversion dry run as the API answers it, each reason in the request's language and in its mode's words.</summary>
|
||||
private static ConvertPlanDto Plan(HttpContext context, ConvertPlan plan, string fingerprint)
|
||||
{
|
||||
var culture = RequestCulture.Of(context);
|
||||
var space = plan.Space;
|
||||
var spaceLine = space.Free is not { } free
|
||||
? Loc.Text("Archive.Convert.SpaceUnknown", [Size(space.Required, culture)], culture)
|
||||
: Loc.Text(space.Enough ? "Archive.Convert.Space" : "Archive.Convert.SpaceShort", [Size(space.Required, culture), Size(free, culture)], culture);
|
||||
return new ConvertPlanDto(Wire(plan.Options.Target), plan.Options.Quality, Wire(plan.Mode),
|
||||
[.. plan.Sequences.Select(s => new ConvertSequenceDto(s.SequenceId, s.Title, s.Folder, s.FramesVersion, s.Frames.Count, s.BytesBefore, s.BytesAfter,
|
||||
[.. s.Skipped.GroupBy(k => Wire(k.Reason))
|
||||
.Select(g => new ConvertSkippedDto(g.Key, g.Sum(k => k.Frames), SkipMessage(g.First().Reason, plan.Mode == ConvertMode.NewSequence && s.Converts, culture)))],
|
||||
[.. s.Blocked.Select(b => new ConvertBlockedDto(Wire(b), Loc.Get("Archive.Convert.Blocked." + b, culture) ?? Wire(b)))]))],
|
||||
plan.Converted.Count(),
|
||||
plan.Frames,
|
||||
plan.Skipped,
|
||||
plan.BytesBefore,
|
||||
plan.BytesAfter,
|
||||
new ConvertSpaceDto(space.Required, space.Free, space.Enough, spaceLine),
|
||||
fingerprint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wire name of why photos are not converted: <c>same_format</c>, <c>convert_on_pc</c> (a format the server has no
|
||||
/// full-resolution decoder for, or a file it reads only from its preview: a PC with the camera's codec may convert
|
||||
/// them), <c>undecodable</c>, <c>missing</c>, <c>unhashed</c>, <c>eight_bit</c> (a RAW this host develops at 8 bits only,
|
||||
/// for a 16-bit target), <c>color_profile</c> (a colour profile the target can neither keep nor convert to),
|
||||
/// <c>too_large</c>, <c>inaccessible</c> (a file another program held open, or that could not be opened, when the plan
|
||||
/// was made).
|
||||
/// </summary>
|
||||
public static string Wire(ConvertSkip reason) => reason switch
|
||||
{
|
||||
ConvertSkip.SameFormat => "same_format",
|
||||
ConvertSkip.NoNativeDecoder or ConvertSkip.PreviewOnly => "convert_on_pc",
|
||||
ConvertSkip.Undecodable => "undecodable",
|
||||
ConvertSkip.Missing => "missing",
|
||||
ConvertSkip.EightBit => "eight_bit",
|
||||
ConvertSkip.ColorProfile => "color_profile",
|
||||
ConvertSkip.TooLarge => "too_large",
|
||||
ConvertSkip.Inaccessible => "inaccessible",
|
||||
_ => "unhashed",
|
||||
};
|
||||
|
||||
/// <summary>Wire name of why a sequence is not converted: <c>busy</c>, <c>offline</c>, <c>unreadable</c>, <c>frames_changed</c>.</summary>
|
||||
public static string Wire(ConvertBlock reason) => reason switch
|
||||
{
|
||||
ConvertBlock.Busy => "busy",
|
||||
ConvertBlock.Offline => "offline",
|
||||
ConvertBlock.Unreadable => "unreadable",
|
||||
_ => "frames_changed",
|
||||
};
|
||||
|
||||
/// <summary>Wire name of a conversion target: <c>jpeg</c>, <c>tiff16</c>, <c>linear-dng</c>.</summary>
|
||||
public static string Wire(ConvertTarget target) => target switch
|
||||
{
|
||||
ConvertTarget.Jpeg => "jpeg",
|
||||
ConvertTarget.Tiff16 => "tiff16",
|
||||
_ => "linear-dng",
|
||||
};
|
||||
|
||||
/// <summary>Wire name of a conversion mode: <c>replace</c>, <c>new-sequence</c>.</summary>
|
||||
public static string Wire(ConvertMode mode) => mode == ConvertMode.Replace ? "replace" : "new-sequence";
|
||||
|
||||
private static ConvertTarget? TargetOf(string? text) =>
|
||||
Enum.GetValues<ConvertTarget>().Select(t => (ConvertTarget?)t).FirstOrDefault(t => string.Equals(Wire(t!.Value), text?.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static ConvertMode? ModeOf(string? text) =>
|
||||
Enum.GetValues<ConvertMode>().Select(m => (ConvertMode?)m).FirstOrDefault(m => string.Equals(Wire(m!.Value), text?.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>
|
||||
/// Why photos are not converted, in <paramref name="culture"/>: on the server, a format it cannot read says to convert on
|
||||
/// a PC. Of a sequence <see cref="ConvertMode.NewSequence"/> copies (<paramref name="copied"/>) it says that the new
|
||||
/// sequence lacks them (it holds the converted copies alone); otherwise, and of a sequence that converts nothing now (no
|
||||
/// new sequence is made of it), that they stay as they are.
|
||||
/// </summary>
|
||||
private static string SkipMessage(ConvertSkip reason, bool copied, CultureInfo culture)
|
||||
{
|
||||
var onPc = reason is ConvertSkip.NoNativeDecoder or ConvertSkip.PreviewOnly;
|
||||
var key = copied
|
||||
? onPc ? "Server.Convert.OnPcNew" : "Archive.Convert.NotCopied." + reason
|
||||
: onPc ? "Server.Convert.OnPc" : "Archive.Convert.Skipped." + reason;
|
||||
return Loc.Get(key, culture) ?? Wire(reason);
|
||||
}
|
||||
|
||||
/// <summary>A size as the dry run's space line shows it: GB from one gigabyte, MB below.</summary>
|
||||
private static string Size(long bytes, CultureInfo culture) => bytes >= 1_000_000_000
|
||||
? Loc.Text("Common.Size.GB", [(bytes / 1e9).ToString("0.#", culture)], culture)
|
||||
: Loc.Text("Common.Size.MB", [(bytes / 1e6).ToString("0.#", culture)], culture);
|
||||
|
||||
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));
|
||||
|
||||
@@ -56,7 +56,8 @@ public static class JobEndpoints
|
||||
if (!JobWire.TryParseKind(kind, out var k)) return ApiErrors.BadRequest(context, "invalid_filter", "kind");
|
||||
kindFilter = k;
|
||||
}
|
||||
var page = await db.Jobs.ListAsync(stateFilter, kindFilter, limit ?? 50, string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted);
|
||||
// A job's answer holds no parameters (a conversion's or an import's can name every sequence or file): the list reads none.
|
||||
var page = await db.Jobs.ListBriefAsync(stateFilter, kindFilter, limit ?? 50, string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted);
|
||||
return Results.Json(new Page<JobDto>([.. page.Items.Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Conversion;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// The dry runs of Reorganize and Convert 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 (the stamp its
|
||||
/// key holds: <see cref="SequenceRepository.GetStampAsync"/>, <see cref="SequenceRepository.GetConvertStampAsync"/>) 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 (<see cref="PlanKey.Refuses"/>); 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, of either kind; 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 job that applies a plan plans again and does only what the plan confirmed showed, leaving as it is what
|
||||
/// no longer matches it. A conversion's confirmation takes a kept plan only (<see cref="Kept"/>): one let go since is
|
||||
/// planned again by a dry run, apart from the request, and confirmed then.
|
||||
/// </summary>
|
||||
public sealed class PlanCache : 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, of either kind (each holds a step for every sequence it plans). 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, of either kind; 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<PlanKey, 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 PlanCache(TimeProvider time, IHostApplicationLifetime? lifetime = null)
|
||||
{
|
||||
_time = time;
|
||||
if (lifetime is not null) _stopping = lifetime.ApplicationStopping.Register(Clear);
|
||||
}
|
||||
|
||||
/// <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="PlanKey.Refuses"/>) 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 async Task<TPlan> GetOrPlanAsync<TPlan>(PlanKey<TPlan> key, Func<CancellationToken, Task<TPlan>> plan, CancellationToken cancellationToken = default)
|
||||
where TPlan : class
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
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!, async stop => await plan(stop).ConfigureAwait(false));
|
||||
// The key's kind names the plan's: what was made for it is a TPlan.
|
||||
return (TPlan)await entry!.Plan.Task.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plan kept for <paramref name="key"/> (or the refusal kept for it, which the task throws), within its lifetime; null
|
||||
/// when there is none: never made, still being made, stopped, or let go. Plans nothing: a confirmation takes the plan its
|
||||
/// dry run showed, never one made inside its own request, which a proxy may cut off once the job is queued.
|
||||
/// </summary>
|
||||
public Task<TPlan>? Kept<TPlan>(PlanKey<TPlan> key) where TPlan : class
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
Task<object> plan;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_plans.TryGetValue(key, out var entry) || entry.Made is not { } made) return null;
|
||||
if (_time.GetUtcNow() - made >= Lifetime)
|
||||
{
|
||||
Remove(key);
|
||||
return null;
|
||||
}
|
||||
plan = entry.Plan.Task;
|
||||
}
|
||||
return As(plan);
|
||||
|
||||
// The key's kind names the plan's: what was made for it is a TPlan.
|
||||
static async Task<TPlan> As(Task<object> made) => (TPlan)await made.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <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(PlanKey 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(PlanKey key, Entry entry, Func<CancellationToken, Task<object>> plan)
|
||||
{
|
||||
var stop = entry.Stop.Token;
|
||||
object? 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 not OperationCanceledException && key.Refuses(ex))
|
||||
{
|
||||
// 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(PlanKey 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(PlanKey key, Entry entry)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_plans.GetValueOrDefault(key) == entry) Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private void Remove(PlanKey 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<object> 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; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a kept plan is kept by (<see cref="PlanCache"/>): everything it is made from, by value, its kind included.</summary>
|
||||
public abstract record PlanKey
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether <paramref name="exception"/>, thrown while the plan is made, refuses the request for what the key holds (kept
|
||||
/// as a plan is: the same reads refuse it again) rather than failing it (not kept).
|
||||
/// </summary>
|
||||
public abstract bool Refuses(Exception exception);
|
||||
|
||||
/// <summary>The sequences of a request as a key holds them: <c>*</c> for every sequence, else the ids in the order given.</summary>
|
||||
protected static string Selection(IReadOnlyList<Guid>? sequenceIds) =>
|
||||
sequenceIds is null ? "*" : string.Join(',', sequenceIds.Select(id => id.ToString("N")));
|
||||
}
|
||||
|
||||
/// <summary>The key of a plan of <typeparamref name="TPlan"/>: what <see cref="PlanCache.GetOrPlanAsync"/> answers for it.</summary>
|
||||
public abstract record PlanKey<TPlan> : PlanKey where TPlan : class;
|
||||
|
||||
/// <summary>
|
||||
/// What a Reorganize plan is kept by: the archive, the stamp of what it reads from the index
|
||||
/// (<see cref="SequenceRepository.GetStampAsync"/>), the sequences (all of them, or the ids in the order given, which decides
|
||||
/// the folder that gets " (2)") and the templates. A folder inside a sequence's (<see cref="NestedRenameException"/>) or a
|
||||
/// sequence not in the archive (<see cref="ArgumentException"/>) refuses it.
|
||||
/// </summary>
|
||||
public sealed record ReorganizePlanKey(Guid ArchiveId, string Stamp, string Sequences, RenameTemplates Templates) : PlanKey<RenamePlan>
|
||||
{
|
||||
/// <param name="sequenceIds">The sequences of the request; null for every sequence of the archive.</param>
|
||||
public static ReorganizePlanKey Of(Guid archiveId, string stamp, IReadOnlyList<Guid>? sequenceIds, RenameTemplates templates) =>
|
||||
new(archiveId, stamp, Selection(sequenceIds), templates);
|
||||
|
||||
public override bool Refuses(Exception exception) => exception is NestedRenameException || exception.GetType() == typeof(ArgumentException);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a conversion plan is kept by: the archive, the stamp of what it reads from the index
|
||||
/// (<see cref="SequenceRepository.GetConvertStampAsync"/>), the sequences (all of them, or the ids in the order given) and
|
||||
/// the target with the quality that counts (<see cref="ConvertOptions.Key"/>: a lossless target's ignores it). Not the
|
||||
/// mode: what converts is the same in either, so the plan made with one serves the other (the endpoint sets the request's).
|
||||
/// Nor the jobs that make a sequence busy, nor the free space: the endpoint sets those as they are at every request.
|
||||
/// A sequence not in the archive (<see cref="ArgumentException"/>) refuses it.
|
||||
/// </summary>
|
||||
public sealed record ConvertPlanKey(Guid ArchiveId, string Stamp, string Sequences, string Options) : PlanKey<ConvertPlan>
|
||||
{
|
||||
/// <param name="sequenceIds">The sequences of the request; null for every sequence of the archive.</param>
|
||||
public static ConvertPlanKey Of(Guid archiveId, string stamp, IReadOnlyList<Guid>? sequenceIds, ConvertOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
return new(archiveId, stamp, Selection(sequenceIds), options.Key);
|
||||
}
|
||||
|
||||
public override bool Refuses(Exception exception) => exception.GetType() == typeof(ArgumentException);
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
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; }
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ public static partial class TrashEndpoints
|
||||
public static bool IsEntryName(string? name) => name is not null && EntryName().IsMatch(name);
|
||||
|
||||
public static TrashEntryDto Entry(TrashEntry e) =>
|
||||
new(e.Name, e.Kind.ToString().ToLowerInvariant(), e.SequenceId, e.Title, e.Folder, e.Frames, e.Files, e.Bytes, e.DeletedBy, e.DeletedAt);
|
||||
new(e.Name, e.Kind.ToString().ToLowerInvariant(), e.SequenceId, e.Title, e.Folder, e.Frames, e.Files, e.Bytes, e.DeletedBy, e.DeletedAt, e.ConversionDeleted);
|
||||
|
||||
/// <summary>The entries newest first with their total size (a read-only archive lists them too); 503 <c>archive_offline</c>.</summary>
|
||||
private static async Task<IResult> ListAsync(HttpContext context, ChronosDatabase db, ServerArchive archive, [FromServices] ArchiveService? archives)
|
||||
|
||||
@@ -26,7 +26,7 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs,
|
||||
JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move, JobKind.Backup, JobKind.Cleanup,
|
||||
JobKind.EmptyTrash,
|
||||
JobKind.EmptyTrash, JobKind.Convert,
|
||||
];
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
@@ -142,7 +142,7 @@ public static class ServerHost
|
||||
services.AddSingleton<RenderStore>();
|
||||
services.AddSingleton<RenderUploads>();
|
||||
services.AddSingleton<SequenceJobs>();
|
||||
services.AddSingleton<ReorganizePlanCache>();
|
||||
services.AddSingleton<PlanCache>();
|
||||
services.AddSingleton<RenderNodeService>();
|
||||
services.AddSingleton<JobEngineHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
|
||||
|
||||
@@ -12,8 +12,9 @@ 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, and Reorganize's
|
||||
/// <c>move</c> jobs, which tell connected clients of the sequences they change); a scan
|
||||
/// orphans reports, index backups and clean-ups with the server's own steps, the <see cref="ICleanupStep"/>s in DI, Reorganize's
|
||||
/// <c>move</c> jobs and the <c>convert</c> jobs, which tell connected clients of the sequences they change or make, and check
|
||||
/// their space against the space volume's free bytes, <see cref="VolumeSpace.Report"/>); 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).
|
||||
@@ -30,16 +31,21 @@ public static class ArchiveModule
|
||||
var options = sp.GetRequiredService<ServerOptions>();
|
||||
var db = sp.GetRequiredService<ChronosDatabase>();
|
||||
var events = sp.GetRequiredService<EventHub>();
|
||||
var volumes = sp.GetService<VolumeSpace>();
|
||||
// Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1).
|
||||
return new ArchiveService(db, new ArchiveServiceOptions
|
||||
{
|
||||
// A Reorganize tells connected clients of every sequence it changed (BRIEF §14.3).
|
||||
// A Reorganize or a conversion tells connected clients of every sequence it changed or made (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(),
|
||||
// Where a conversion writes (owner review 2, R7): the tighter of what the panel shows as the archive's free space
|
||||
// (R2: the space path's volume) and the volume the archive's folders are on, which takes every byte it stages
|
||||
// and files (on Unraid the cache, until the mover runs).
|
||||
FreeSpace = volumes is null ? null : volumes.WritableFree,
|
||||
Owner = Owner,
|
||||
ImagesAfterScan = true,
|
||||
Parallelism = () => options.Parallelism,
|
||||
|
||||
@@ -47,6 +47,17 @@ public class VolumeSpace(ServerOptions options, ILogger<VolumeSpace> logger)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The free bytes a write under the folder <paramref name="path"/> of the archive may count on (a conversion checks its
|
||||
/// estimate against it, owner review 2, R7): the tighter of the space volume and the volume the folder is on, which on
|
||||
/// Unraid is the cache a share writes to until the mover runs; null when neither can be measured.
|
||||
/// </summary>
|
||||
public long? WritableFree(string path)
|
||||
{
|
||||
var report = Report(path);
|
||||
return report.Space is { } space && report.Write is { } write ? Math.Min(space.FreeBytes, write.FreeBytes) : report.Space?.FreeBytes;
|
||||
}
|
||||
|
||||
/// <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).
|
||||
|
||||
Reference in new issue
Block a user