feat(admin): upload photos from the web panel

Owner review 2, R3: the panel can add photos to an existing or a new
sequence without the desktop app. upload.js is a dialog the library pages
open (openUpload({ api, sequence, onDone })): file picker or drag and drop
(folders are counted and left out: whole-folder import stays on the
desktop), per-photo state, a total bar, Cancel that deletes the started
uploads, and a leave-page guard while sending. Each photo is hashed in a
same-origin module worker with an in-house incremental SHA-256 (8 MiB
reads; crypto.subtle cannot hash in pieces), which runs the FIPS 180-4
known answers and a crypto.subtle cross-check before its first hash and
refuses to hash on any mismatch; the server verifies the hash again.
Chunks go through api.putBytes with the session's CSRF header, two files
and two chunks at a time, retrying no answer, 429 and 503; quota, space
and permission refusals stop the run with the server's message, and a
photo deleted from the sequence shows as deleted before.

server/info now lists the photo extensions the archive files, so the
dialog offers and sends only those. The CSP already allows the worker
(worker-src falls back to script-src 'self'); tests pin that, the module
walk follows the worker, and a browser-shaped upload runs end to end
through the cookie session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c64c60ab8bb41c102182e284177ac04a56bf1058)
This commit is contained in:
Alby96 committed 2026-10-27 10:52:40 +01:00
1 parent aa1d4913a3
commit 0e52bf0e1b
12 files changed
+1315 -15

No files matched your search

+693
View File
@@ -0,0 +1,693 @@
// Upload dialog of the admin panel (owner review 2, R3; BRIEF §14.4, §14.8): photos from this computer into an existing
// or a new sequence, chosen with the file picker or dropped on the dialog. Folders are not taken: importing a whole folder
// stays a feature of the desktop app. Each photo is hashed in a module worker (hash-worker.js, which self-tests its
// SHA-256 first and refuses to hash when a check fails), started, sent in the chunks the server does not have yet and
// completed; the server verifies the hash again before it files the photo.
import { ApiFailure } from "./api.js";
import { t, plural, applyStrings, culture } from "./i18n.js";
import { escapeHtml, attr, bar, formatBytes, formatNumber, errorText } from "./ui.js";
import { icons } from "./icons.js";
/** Photos sent at once, and chunks in flight for each: four requests, half of what the server takes from one account. */
const FILES_AT_ONCE = 2;
const CHUNKS_AT_ONCE = 2;
/** Retries of a call that failed for a passing reason (no answer, 429, 503), after 1, 2 and 4 seconds. */
const RETRIES = 3;
const SEARCH_DELAY = 250;
const LIST_LIMIT = 50;
/** States of a photo already on the server: a later run leaves it alone. */
const FINISHED = new Set(["done", "exists", "deleted"]);
/** States of a photo a run is sending. */
const ACTIVE = new Set(["hashing", "starting", "uploading", "verifying"]);
/** A failure of the hash worker: kind self_test (its SHA-256 failed a check), worker (it did not run), read or stopped. */
class HashError extends Error {
constructor(kind, detail = "") {
super(`${kind} ${detail}`.trim());
this.kind = kind;
}
}
let dialogs = 0;
/**
* Opens the upload dialog. With sequence ({ id, title } or a SequenceDto) the photos go into it; without, the dialog
* lets the user pick an existing sequence or name a new one. onDone() runs after every run that changed the library
* (photos uploaded or a sequence created), so the page can refresh. Resolves when the dialog closes.
*/
export function openUpload({ api, sequence, onDone } = {}) {
return new Promise((resolve) => {
const id = `upload-${++dialogs}`;
let target = sequence?.id ? { id: sequence.id, title: sequence.displayTitle ?? sequence.title ?? "" } : null;
let extensions = null;
let maxBytes = 0;
let running = false;
let controller = null;
let broken = null;
let hasher = null;
let searchTimer = null;
let searchToken = 0;
let frame = 0;
const items = [];
const skipped = { folders: 0, formats: 0, size: 0 };
const titles = new Map();
const dialog = document.createElement("dialog");
dialog.className = "dialog upload";
dialog.setAttribute("aria-labelledby", `${id}-title`);
dialog.innerHTML = `
<form novalidate>
<h2 id="${id}-title" data-i18n="Admin.Upload.Title"></h2>
<div class="upload-target" id="${id}-target"></div>
<div class="drop">
<button class="btn" type="button" data-act="add" data-i18n="Admin.Upload.Add" data-i18n-title="Admin.Upload.Add.Tip"></button>
<span data-i18n="Admin.Upload.Drop"></span>
<input type="file" multiple hidden tabindex="-1">
</div>
<div class="chips upload-notes" hidden></div>
<ul class="upload-files" aria-label="${attr(t("Admin.Upload.Photos"))}" hidden></ul>
<div class="upload-total" hidden></div>
<div class="error" role="alert"></div>
<div class="buttons">
<button class="btn" type="button" data-act="close" data-i18n="Admin.Upload.Close" data-i18n-title="Admin.Upload.Close.Tip"></button>
<button class="btn primary" type="submit" data-act="start" data-i18n="Admin.Upload.Start" data-i18n-title="Admin.Upload.Start.Tip"></button>
</div>
</form>`;
document.body.appendChild(dialog);
applyStrings(dialog);
const form = dialog.querySelector("form");
const targetHost = dialog.querySelector(`#${id}-target`);
const input = dialog.querySelector('input[type="file"]');
const addButton = dialog.querySelector('[data-act="add"]');
const closeButton = dialog.querySelector('[data-act="close"]');
const startButton = dialog.querySelector('[data-act="start"]');
const notes = dialog.querySelector(".upload-notes");
const list = dialog.querySelector(".upload-files");
const total = dialog.querySelector(".upload-total");
const errorLine = dialog.querySelector(".error");
drawTarget();
drawButtons();
addButton.addEventListener("click", () => input.click());
input.addEventListener("change", () => {
take([...input.files], 0);
input.value = "";
});
form.addEventListener("submit", (e) => {
e.preventDefault();
run();
});
closeButton.addEventListener("click", () => {
if (running) cancel();
else dialog.close();
});
list.addEventListener("click", (e) => {
const button = e.target.closest('[data-act="remove"]');
if (!button || running) return;
const index = items.findIndex((i) => i.key === button.closest("[data-key]").dataset.key);
if (index < 0) return;
const [item] = items.splice(index, 1);
const next = item.row.nextElementSibling ?? item.row.previousElementSibling;
item.row.remove();
(next?.querySelector('[data-act="remove"]:not([hidden])') ?? addButton).focus();
drawList();
});
// Drops: photos are taken, folders only counted (BRIEF §14.8: no folder upload on the web).
const hasFiles = (e) => [...(e.dataTransfer?.types ?? [])].includes("Files");
dialog.addEventListener("dragover", (e) => {
if (!hasFiles(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = running || extensions === null ? "none" : "copy";
dialog.classList.add("dragging");
});
dialog.addEventListener("dragleave", (e) => {
if (!dialog.contains(e.relatedTarget)) dialog.classList.remove("dragging");
});
dialog.addEventListener("drop", (e) => {
if (!hasFiles(e)) return;
e.preventDefault();
dialog.classList.remove("dragging");
if (running || extensions === null) return;
const { files, folders } = dropped(e.dataTransfer);
take(files, folders);
});
// Esc closes only while nothing is being sent; Cancel stops a run.
dialog.addEventListener("cancel", (e) => {
if (running) e.preventDefault();
});
// Leaving the page while photos are sent asks first (returnValue for browsers before preventDefault counted).
const guard = (e) => {
e.preventDefault();
e.returnValue = true;
};
const signedOut = () => {
controller?.abort();
dialog.close();
};
window.addEventListener("chronos:signed-out", signedOut);
dialog.addEventListener("close", () => {
controller?.abort();
hasher?.stop();
clearTimeout(searchTimer);
cancelAnimationFrame(frame);
window.removeEventListener("beforeunload", guard);
window.removeEventListener("chronos:signed-out", signedOut);
dialog.remove();
resolve();
});
dialog.showModal();
targetHost.querySelector('input[type="search"]')?.focus();
const firstFocus = document.activeElement;
// The photo extensions and the size limit the server announces: only those are offered and sent.
api.get("/api/v1/server/info").then((info) => {
extensions = new Set((info?.extensions ?? []).map((e) => String(e).toLowerCase()));
maxBytes = info?.limits?.maxUploadBytes ?? 0;
input.accept = [...extensions].map((e) => `.${e}`).join(",");
drawButtons();
// Into a given sequence the first step is adding photos, once the button can be used.
if (target && document.activeElement === firstFocus) addButton.focus();
}).catch((err) => showError(errorText(err)));
/** The target: fixed (given, or chosen when the first run started), else the choice of an existing or a new sequence. */
function drawTarget() {
if (target) {
targetHost.innerHTML = `<div class="field-label"><span data-i18n="Admin.Upload.Target"></span>
<strong class="ellipsis" dir="auto" title="${attr(target.title)}">${escapeHtml(target.title)}</strong></div>`;
applyStrings(targetHost);
return;
}
targetHost.innerHTML = `
<fieldset class="upload-choice"><legend data-i18n="Admin.Upload.Target"></legend>
<label class="check"><input type="radio" name="mode" value="existing" checked data-i18n-title="Admin.Upload.Existing.Tip"><span data-i18n="Admin.Upload.Existing"></span></label>
<label class="check"><input type="radio" name="mode" value="new" data-i18n-title="Admin.Upload.New.Tip"><span data-i18n="Admin.Upload.New"></span></label>
</fieldset>
<div class="upload-existing">
<input class="input" type="search" name="q" autocomplete="off" dir="auto" aria-label="${attr(t("Admin.Upload.Search"))}"
data-i18n-placeholder="Admin.Upload.Search" data-i18n-title="Admin.Upload.Search.Tip">
<select class="input list" name="sequence" size="5" aria-label="${attr(t("Admin.Upload.Sequences"))}" data-i18n-title="Admin.Upload.Sequences.Tip"></select>
</div>
<label class="upload-new" hidden><span data-i18n="Admin.Upload.NewTitle"></span>
<input class="input" name="title" maxlength="200" autocomplete="off" dir="auto" data-i18n-title="Admin.Upload.NewTitle.Tip"></label>`;
applyStrings(targetHost);
const existing = targetHost.querySelector(".upload-existing");
const fresh = targetHost.querySelector(".upload-new");
targetHost.querySelectorAll('input[name="mode"]').forEach((radio) => radio.addEventListener("change", () => {
const isNew = form.elements.mode.value === "new";
existing.hidden = isNew;
fresh.hidden = !isNew;
showError("");
}));
const search = targetHost.querySelector('input[name="q"]');
search.addEventListener("input", () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => loadSequences(search.value.trim()), SEARCH_DELAY);
});
// Enter in the search box picks nothing and sends nothing.
search.addEventListener("keydown", (e) => {
if (e.key === "Enter") e.preventDefault();
});
targetHost.querySelector("select").addEventListener("change", () => showError(""));
loadSequences("");
}
async function loadSequences(q) {
const token = ++searchToken;
const query = new URLSearchParams({ limit: String(LIST_LIMIT) });
if (q) query.set("q", q);
let page;
try {
page = await api.get(`/api/v1/sequences?${query}`);
} catch (err) {
if (token === searchToken) showError(errorText(err));
return;
}
const select = targetHost.querySelector("select");
if (token !== searchToken || !select) return;
const chosen = select.value;
for (const s of page.items) titles.set(s.id, s.displayTitle);
select.innerHTML = page.items.map((s) => `<option value="${attr(s.id)}" dir="auto" ${s.id === chosen ? "selected" : ""}>` +
`${escapeHtml(s.displayTitle)} · ${escapeHtml(plural("Admin.Upload.PhotoCount", s.frameCount))}</option>`).join("") ||
`<option disabled>${escapeHtml(t("Admin.Upload.NoMatch"))}</option>`;
}
/** Adds picked or dropped files: photos once each; folders, other files and files above the limit are counted. */
function take(files, folders) {
skipped.folders += folders;
for (const file of files) {
const dot = file.name.lastIndexOf(".");
const extension = dot < 0 ? "" : file.name.slice(dot + 1).toLowerCase();
if (file.size === 0 || !extensions?.has(extension)) {
skipped.formats++;
continue;
}
if (maxBytes > 0 && file.size > maxBytes) {
skipped.size++;
continue;
}
const key = `${file.name}\u0000${file.size}\u0000${file.lastModified}`;
if (items.some((i) => i.key === key)) continue;
const item = { key, file, state: "waiting", hashed: 0, sent: 0, uploadId: null, message: "", row: null };
item.row = document.createElement("li");
item.row.className = "upload-file";
item.row.dataset.key = key;
item.row.innerHTML = `<span class="name ellipsis" dir="auto" title="${attr(file.name)}">${escapeHtml(file.name)}</span>
<span class="size num muted">${escapeHtml(formatBytes(file.size))}</span><span class="status"></span>
<button class="btn icon small subtle" type="button" data-act="remove" title="${attr(t("Admin.Upload.Remove.Tip"))}"
aria-label="${attr(t("Admin.Upload.Remove", file.name))}">${icons.close}</button>`;
list.appendChild(item.row);
items.push(item);
drawItem(item);
}
drawNotes();
drawList();
}
function drawNotes() {
const chip = (count, key, tip) => count === 0 ? "" : `<span class="chip warn" title="${attr(tip)}">${escapeHtml(t(key, formatNumber(count)))}</span>`;
notes.innerHTML = chip(skipped.folders, "Admin.Upload.Skipped.Folders", t("Admin.Upload.Skipped.Folders.Tip")) +
chip(skipped.formats, "Admin.Upload.Skipped.Formats", t("Admin.Upload.Skipped.Formats.Tip")) +
chip(skipped.size, "Admin.Upload.Skipped.Size", t("Admin.Upload.Skipped.Size.Tip", formatBytes(maxBytes)));
notes.hidden = notes.innerHTML === "";
}
function drawList() {
list.hidden = items.length === 0;
drawTotal();
drawButtons();
}
/** One photo's row: its state, a bar while it is hashed or sent, and the reason of a failure as the tooltip. */
function drawItem(item) {
const status = item.row.querySelector(".status");
const percent = (fraction) => new Intl.NumberFormat(culture(), { style: "percent", maximumFractionDigits: 0 }).format(fraction);
let text;
let tip = "";
let tone = "queued";
let fraction = null;
switch (item.state) {
case "hashing":
text = t("Admin.Upload.State.Hashing", percent(item.hashed));
fraction = item.hashed;
tone = "running";
break;
case "starting":
text = t("Admin.Upload.State.Starting");
tone = "running";
break;
case "uploading":
fraction = item.file.size > 0 ? item.sent / item.file.size : 1;
text = t("Admin.Upload.State.Uploading", percent(fraction));
tone = "running";
break;
case "verifying":
text = t("Admin.Upload.State.Verifying");
tone = "running";
break;
case "done":
text = t("Admin.Upload.State.Done");
tip = t("Admin.Upload.State.Done.Tip");
tone = "done";
break;
case "exists":
text = t("Admin.Upload.State.Exists");
tip = t("Admin.Upload.State.Exists.Tip");
tone = "done";
break;
case "deleted":
text = t("Admin.Upload.State.Deleted");
tip = t("Admin.Upload.State.Deleted.Tip");
tone = "paused";
break;
case "failed":
text = t("Admin.Upload.State.Failed");
tip = item.message;
tone = "failed";
break;
case "cancelled":
text = t("Admin.Upload.State.Cancelled");
tone = "cancelled";
break;
case "notSent":
text = t("Admin.Upload.State.NotSent");
tip = t("Admin.Upload.State.NotSent.Tip");
tone = "cancelled";
break;
default:
text = t("Admin.Upload.State.Waiting");
}
status.innerHTML = (fraction === null ? "" : bar(fraction)) +
`<span class="state ${tone} ellipsis"${tip ? ` title="${attr(tip)}"` : ""}>${escapeHtml(text)}</span>`;
item.row.querySelector('[data-act="remove"]').hidden = !removable(item);
}
/** A photo comes off the list only between runs, and only while it is not on the server. */
function removable(item) {
return !running && !FINISHED.has(item.state) && !ACTIVE.has(item.state);
}
/** Progress redraws at most once a frame: the worker reports every 8 MiB, chunks finish four at a time. */
function update(item) {
item.dirty = true;
if (frame) return;
frame = requestAnimationFrame(() => {
frame = 0;
for (const i of items) {
if (!i.dirty) continue;
i.dirty = false;
drawItem(i);
}
drawTotal();
});
}
function setState(item, state, message = "") {
item.state = state;
item.message = message;
drawItem(item);
drawTotal();
}
function drawTotal() {
total.hidden = items.length === 0;
if (items.length === 0) return;
let bytes = 0;
let done = 0;
let sent = 0;
let failed = 0;
for (const item of items) {
bytes += item.file.size;
if (FINISHED.has(item.state)) {
done++;
sent += item.file.size;
} else if (item.state === "uploading" || item.state === "verifying") {
sent += item.sent;
} else if (item.state === "failed") {
failed++;
}
}
const text = `${t("Admin.Upload.Count", formatNumber(done), formatNumber(items.length))} · ${t("Admin.Upload.Bytes", formatBytes(sent), formatBytes(bytes))}`;
total.innerHTML = `<div class="progress-cell">${bar(bytes > 0 ? sent / bytes : 0)}<span class="num" title="${attr(text)}">${escapeHtml(text)}</span></div>` +
(failed > 0 ? `<span class="state failed nowrap">${escapeHtml(t("Admin.Upload.Failed", formatNumber(failed)))}</span>` : "");
}
function drawButtons() {
const pending = items.some((i) => !FINISHED.has(i.state));
startButton.disabled = running || !pending || broken !== null || extensions === null;
addButton.disabled = running || extensions === null;
closeButton.textContent = t(running ? "Admin.Upload.Cancel" : "Admin.Upload.Close");
closeButton.title = t(running ? "Admin.Upload.Cancel.Tip" : "Admin.Upload.Close.Tip");
for (const item of items) item.row.querySelector('[data-act="remove"]').hidden = !removable(item);
targetHost.querySelectorAll("input, select").forEach((field) => {
field.disabled = running;
});
}
function showError(text) {
errorLine.textContent = text;
}
/** Sends every photo not on the server yet, two at a time; a quota, space or permission refusal stops the rest. */
async function run() {
if (running) return;
const todo = items.filter((i) => !FINISHED.has(i.state));
if (todo.length === 0 || extensions === null) return;
if (broken) return showError(broken);
showError("");
running = true;
controller = new AbortController();
const signal = controller.signal;
window.addEventListener("beforeunload", guard);
drawButtons();
let changed = false;
try {
const into = await resolveTarget();
if (!into) return;
changed = into.created;
if (signal.aborted) return;
todo.forEach((i) => setState(i, "waiting"));
let next = 0;
let stop = null;
const lane = async () => {
while (stop === null && !signal.aborted && next < todo.length) {
const item = todo[next++];
try {
changed = (await send(item, into.id, signal)) || changed;
} catch (err) {
// A completion cut short may still have filed the photo: the page refreshes to find out.
if (item.state === "verifying") changed = true;
if (signal.aborted) {
setState(item, "cancelled");
continue;
}
setState(item, "failed", messageOf(err));
if (stops(err)) stop = err;
}
}
};
await Promise.all(Array.from({ length: FILES_AT_ONCE }, lane));
if (signal.aborted) {
await discard(todo);
todo.filter((i) => i.state === "waiting").forEach((i) => setState(i, "cancelled"));
} else if (stop !== null) {
if (stop instanceof HashError) broken = messageOf(stop);
showError(messageOf(stop));
todo.filter((i) => i.state === "waiting").forEach((i) => setState(i, "notSent"));
}
} finally {
running = false;
controller = null;
window.removeEventListener("beforeunload", guard);
todo.filter((i) => ACTIVE.has(i.state)).forEach((i) => setState(i, "cancelled"));
drawButtons();
drawTotal();
if (changed) onDone?.();
}
}
/** Stops the run: requests are aborted, the hash worker stopped and the server's unfinished uploads discarded. */
function cancel() {
controller?.abort();
hasher?.stop();
hasher = null;
}
/** DELETE of the uploads a cancelled run started and did not complete, so the server frees their space now. */
async function discard(todo) {
await Promise.all(todo.filter((i) => i.uploadId !== null && !FINISHED.has(i.state)).map(async (item) => {
try {
await api.del(`/api/v1/uploads/${item.uploadId}`);
} catch {
// Committed meanwhile, or already gone: nothing left to free.
}
item.uploadId = null;
}));
}
/**
* The sequence the run fills: the fixed one, the one picked, or a new one created now; from then on it is the
* dialog's fixed target, also when the run was cancelled meanwhile. Null (with the reason shown) when there is none.
*/
async function resolveTarget() {
if (target) return { id: target.id, created: false };
const mode = form.elements.mode.value;
if (mode === "existing") {
const select = targetHost.querySelector("select");
if (!select.value) {
showError(t("Admin.Upload.PickFirst"));
select.focus();
return null;
}
target = { id: select.value, title: titles.get(select.value) ?? "" };
drawTarget();
return { id: target.id, created: false };
}
const title = form.elements.title.value.trim();
try {
// Not retried: a lost answer must not create the sequence twice.
const created = await api.post("/api/v1/sequences", { title: title || null, cameraHint: null });
target = { id: created.id, title: created.displayTitle };
} catch (err) {
showError(errorText(err));
return null;
}
drawTarget();
return { id: target.id, created: true };
}
/**
* One photo: hashed, started (the server may already have it, or have had it before it was deleted), the missing
* chunks sent two at a time, completed. True when the library changed.
*/
async function send(item, sequenceId, signal) {
const file = item.file;
item.hashed = 0;
setState(item, "hashing");
hasher ??= createHasher();
const sha256 = await hasher.hash(file, (done, size) => {
item.hashed = size > 0 ? done / size : 1;
update(item);
});
if (signal.aborted) throw signal.reason;
setState(item, "starting");
const start = await retry(() => api.post("/api/v1/uploads", {
sequenceId, fileName: file.name, size: file.size, sha256, capturedAt: null, sessionKey: null,
}), signal);
if (start.alreadyExists) {
// No frame: the photo was deleted from this sequence; a restore from the trash brings it back (R6).
setState(item, start.frameId ? "exists" : "deleted");
return false;
}
item.uploadId = start.uploadId;
const chunk = start.chunkSize;
const count = Math.ceil(file.size / chunk);
const received = new Set(start.received ?? []);
const length = (index) => Math.min(chunk, file.size - index * chunk);
item.sent = [...received].reduce((sum, index) => sum + length(index), 0);
const missing = [];
for (let index = 0; index < count; index++) if (!received.has(index)) missing.push(index);
setState(item, "uploading");
let cursor = 0;
let failure = null;
const lane = async () => {
while (failure === null && cursor < missing.length) {
const index = missing[cursor++];
const blob = file.slice(index * chunk, index * chunk + length(index));
try {
await retry(() => api.putBytes(`/api/v1/uploads/${item.uploadId}/chunks/${index}`, blob, signal), signal);
} catch (err) {
failure ??= err;
return;
}
item.sent += blob.size;
update(item);
}
};
await Promise.all(Array.from({ length: Math.min(CHUNKS_AT_ONCE, missing.length) }, lane));
if (failure !== null) throw failure;
setState(item, "verifying");
await retry(() => api.post(`/api/v1/uploads/${item.uploadId}/complete`), signal);
item.uploadId = null;
setState(item, "done");
return true;
}
});
}
/** What dropped: the files, and how many folders were left out (the entries API tells them apart where it exists). */
function dropped(transfer) {
const files = [];
let folders = 0;
const entries = [...(transfer.items ?? [])].filter((i) => i.kind === "file");
if (entries.length > 0) {
for (const item of entries) {
if (item.webkitGetAsEntry?.()?.isDirectory) {
folders++;
continue;
}
const file = item.getAsFile();
if (file) files.push(file);
}
} else {
files.push(...(transfer.files ?? []));
}
return { files, folders };
}
/** Refusals that would refuse the next photos as well: quota, space, permission, a target gone, a broken hash. */
function stops(err) {
if (err instanceof HashError) return err.kind === "self_test" || err.kind === "worker";
if (!(err instanceof ApiFailure)) return false;
return err.status === 401 || err.status === 403 || err.status === 507 || (err.status === 404 && err.details === "sequence");
}
function messageOf(err) {
if (err instanceof HashError) {
if (err.kind === "self_test") return t("Admin.Upload.SelfTestFailed");
if (err.kind === "read") return t("Admin.Upload.ReadFailed");
return t("Admin.Upload.HashFailed");
}
return errorText(err);
}
/** Calls again after 1, 2 and 4 seconds when the server was not reached, was busy (429) or unavailable (503). */
async function retry(call, signal) {
for (let attempt = 0; ; attempt++) {
try {
return await call();
} catch (err) {
const passing = err instanceof ApiFailure && (err.status === 0 || err.status === 429 || err.status === 503);
if (signal.aborted || !passing || attempt >= RETRIES) throw err;
await sleep(1000 * 2 ** attempt, signal);
}
}
}
function sleep(ms, signal) {
return new Promise((resolve, reject) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener("abort", () => {
clearTimeout(timer);
reject(signal.reason);
}, { once: true });
});
}
/**
* The hash worker behind a promise per file. A worker that fails to load or run rejects every request (worker); its
* refusal after a failed self-test is self_test. stop() ends the worker and rejects what it still had (stopped).
*/
function createHasher() {
let worker = null;
let failure = null;
let next = 0;
const pending = new Map();
const fail = (error) => {
for (const request of pending.values()) request.reject(error);
pending.clear();
};
const start = () => {
try {
worker = new Worker(new URL("./hash-worker.js", import.meta.url), { type: "module" });
} catch (err) {
failure = new HashError("worker", String(err?.name ?? err));
return;
}
worker.addEventListener("message", (e) => {
const message = e.data ?? {};
const request = pending.get(message.id);
if (!request) return;
if (message.type === "progress") {
request.progress(message.done, message.total);
return;
}
pending.delete(message.id);
if (message.type === "done" && /^[0-9a-f]{64}$/.test(message.sha256 ?? "")) request.resolve(message.sha256);
else request.reject(new HashError(message.reason === "self_test" ? "self_test" : message.reason === "read" ? "read" : "worker", message.detail));
});
worker.addEventListener("error", (e) => {
e.preventDefault();
failure = new HashError("worker", e.message ?? "");
fail(failure);
});
};
return {
hash(file, progress) {
if (!worker && !failure) start();
if (failure) return Promise.reject(failure);
return new Promise((resolve, reject) => {
const id = ++next;
pending.set(id, { resolve, reject, progress });
worker.postMessage({ id, file });
});
},
stop() {
worker?.terminate();
worker = null;
fail(new HashError("stopped"));
},
};
}