Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
core/image compression: performance improvements
Adorian Doran4cbe9a7d16eb
diff --git a/apps/server/src/services/image_codec.ts b/apps/server/src/services/image_codec.tsindex 7063cf5047..d2c7bc04a0 100644--- a/apps/server/src/services/image_codec.ts+++ b/apps/server/src/services/image_codec.ts@@ -20,8 +20,13 @@ import isSvg from "is-svg";import { Jimp } from "jimp";import * as UPNG from "upng-js";-/** Where a line the codec wants written goes. Dropped by default, since nothing here needs it. */-export type CodecLog = (message: string) => void;+/**+ * Where a line the codec wants written goes. Dropped by default, since nothing here needs it.+ *+ * `detail` marks a line that is worth having while investigating and not worth having otherwise —+ * one per image, which over a run is most of a log. The host decides what to do with that.+ */+export type CodecLog = (message: string, detail?: boolean) => void;const IGNORE_LOG: CodecLog = () => {};@@ -46,19 +51,23 @@ const COMPRESSIBLE_EXTENSIONS = new Set<string>(IMAGE_COMPRESSIBLE_FORMATS);export const DECODE_MEMORY_MB = 1024;/**- * What a decode is taken to want, per pixel of the image.+ * What a decode is taken to want, per pixel of the image — the most it might, not the usual.** jpeg-js counts every allocation it makes and credits none of them back, so what it weighs against* its budget is the sum of all of them: the coefficient blocks it holds per component (4 bytes a* pixel each), the per-component planes (1 each), the interleaved component data (1 a component)- * and the RGBA bitmap at the end (4). For an ordinary photograph, whose chroma planes are stored at- * a quarter resolution, that comes to about 15.+ * and the RGBA bitmap at the end (4). A photograph whose chroma is stored at quarter resolution+ * comes to about 15; one stored without any subsampling — which is what jimp itself writes — comes+ * to 22. This is the second figure, rounded up.*- * Rounded up from there, so the ceiling below sits inside the budget rather than exactly on it. An- * image stored without chroma subsampling wants nearer 22 and can still exceed the budget while- * under this ceiling; that decode fails as it always did, reported against the one image.+ * Taking the usual case instead was a mistake worth recording. This governs two things: how many+ * decodes a caller will run at once, and how large an image is refused rather than attempted. Under-+ * counting made a sixty-megapixel image look like it would fit a gigabyte, so it was admitted,+ * reserved almost the whole budget, held every other image behind it for as long as the decode+ * took, and then had a fair chance of exceeding the decoder's own ceiling and failing anyway. A run+ * that stops dead on one enormous image is a far worse outcome than one that declines to touch it.*/-const DECODE_BYTES_PER_PIXEL = 16;+const DECODE_BYTES_PER_PIXEL = 24;export type CompressionPlan =| { verdict: "skip"; reason: ImageCompressionSkipReason }@@ -381,7 +390,10 @@ export async function compressImageBytes(result = await image.getBuffer("image/png");}- log(`Compressing image of ${buffer.byteLength} bytes took ${Date.now() - start}ms`);+ // The pixels, not just the bytes: a well-compressed photograph can be a tenth the size of a+ // plain one and ten times the work, and without this the log gives no way to tell the two apart.+ log(`Compressing image of ${buffer.byteLength} bytes (${width}x${height}, `+ + `${(width * height / 1e6).toFixed(1)} MP) took ${Date.now() - start}ms`, true);if (result.byteLength >= buffer.byteLength) {// A small or already well-compressed image can grow; the original stays.diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.tsindex 512f4c63fe..d34dbd55f4 100644--- a/apps/server/src/services/image_provider.ts+++ b/apps/server/src/services/image_provider.ts@@ -23,8 +23,19 @@ import {planFromBytes} from "./image_codec.js";-/** Lines the codec produced, written where the rest of the server's logging goes. */-const toBackendLog = (message: string) => getLog().info(message);+/**+ * Lines the codec produced, written where the rest of the server's logging goes.+ *+ * Per-image detail is dropped unless it was asked for. The backend log is a note the client reads,+ * and re-reads as it grows: a line an image over several hundred images is most of that file, and+ * serving it back is work this process does instead of compressing. Set+ * `TRILIUM_IMAGE_WORKER_DEBUG` to keep them.+ */+const toBackendLog = (message: string, detail?: boolean) => {+ if (!detail || process.env.TRILIUM_IMAGE_WORKER_DEBUG) {+ getLog().info(message);+ }+};async function shrinkImage(buffer: Uint8Array, originalName: string): Promise<Uint8Array> {let jpegQuality = optionService.getOptionInt("imageJpegQuality", 0);@@ -124,22 +135,24 @@ export const serverImageProvider: ImageProvider = {: { decodeCost: decodeCostOf(plan.declared) };},+ /**+ * Compresses off-thread where there are threads to do it on, and here where there are not.+ *+ * The distinction matters more than it looks. "No workers at all" is a property of the+ * installation — nothing was found to run, or nothing would start — and doing the work here is+ * then the only way to do it, exactly as before there were workers. "A worker failed on this+ * image" is a different thing entirely, and answering it by decoding here is a cure worse than+ * the illness: a decode does not yield, so the thread that serves the application stops serving+ * it for as long as it takes, several times over if several workers are failing. That is the+ * application freezing in order to save one image.+ *+ * So a failed worker fails its image. The run carries on, the image is reported untouched, and+ * running the tool again picks it up — none of which requires the application to stop.+ */async compressImage(buffer: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionOutcome> {- try {- const offThread = await compressInWorker(buffer, request, DECODE_MEMORY_MB);-- if (offThread) {- return offThread;- }- } catch (e: unknown) {- // The image is not given up on because a thread was: the work is perfectly possible- // here, only slower and in the way. Said per image, since a worker dying mid-run is a- // different matter from there being no workers at all — which is said once, by the pool.- getLog().info(- `Image Compression Tool: a worker failed (${(e as Error).message}); compressing here instead.`);- }+ const offThread = await compressInWorker(buffer, request, DECODE_MEMORY_MB);- return compressImageBytes(buffer, request, toBackendLog);+ return offThread ?? compressImageBytes(buffer, request, toBackendLog);},compressionConcurrencydiff --git a/apps/server/src/services/image_worker.ts b/apps/server/src/services/image_worker.tsindex 1942ee0b4e..d471d6806e 100644--- a/apps/server/src/services/image_worker.ts+++ b/apps/server/src/services/image_worker.ts@@ -11,7 +11,8 @@*/import type { ImageCompressionOutcome, ImageCompressionRequest } from "@triliumnext/core/src/services/image_provider.js";-import { parentPort } from "node:worker_threads";+import { getHeapStatistics } from "node:v8";+import { parentPort, threadId } from "node:worker_threads";import { compressImageBytes } from "./image_codec.js";@@ -24,6 +25,11 @@ export interface ImageWorkerRequest {budgetMb: number;}+/** A line the worker wants written as it happens, rather than when — or if — it finishes. */+export interface ImageWorkerTrace {+ trace: string;+}+export interface ImageWorkerResponse {id: number;outcome?: ImageCompressionOutcome;@@ -35,13 +41,66 @@ export interface ImageWorkerResponse {/* v8 ignore start -- runs only inside a worker thread, where the harness does not follow. What itdoes is exercised through the codec directly; what is left here is the message plumbing. */++/**+ * Traced on the worker's own output rather than through the reply.+ *+ * The reply is no use for diagnosing a thread that is not answering, which is the failure worth+ * tracing: whatever it would have carried is exactly what never arrives. This goes to the parent's+ * stdout as it happens, so a thread that stops can be seen stopping and where.+ */+/**+ * Sends a line to the thread that has a logger, and prints it besides.+ *+ * Sent rather than only printed because a packaged desktop app has nowhere to show a thread's+ * stdout, and the backend log is where someone looking into a run is actually reading.+ */+const announce = (message: string) => {+ console.log(`[image worker ${threadId}] ${message}`);+ parentPort?.postMessage({ trace: `worker ${threadId}: ${message}` } satisfies ImageWorkerTrace);+};++/** The per-image commentary, which would be a line an image without the asking. */+const trace = (message: string) => {+ if (process.env.TRILIUM_IMAGE_WORKER_DEBUG) {+ announce(message);+ }+};++// Announced whether or not anyone asked for tracing: one line per thread, and the one that answers+// why a run is slow rather than broken. A thread whose old space is smaller than the decode it is+// handed does not fail — it collects, over and over, taking several times longer while looking+// perfectly healthy. What V8 actually granted is the only place that shows.+announce(`loaded and listening; heap limit ${Math.round(getHeapStatistics().heap_size_limit / 1024 / 1024)} MB`);+parentPort?.on("message", (message: ImageWorkerRequest) => {const logs: string[] = [];+ const started = Date.now();++ trace(`received image #${message.id}, ${message.buffer.byteLength} bytes, budget ${message.budgetMb} MB`);- compressImageBytes(message.buffer, message.request, (line) => logs.push(line), message.budgetMb)+ compressImageBytes(+ message.buffer,+ message.request,+ // Detail is carried back only when it was asked for; the caller would drop it anyway, and+ // it would otherwise travel between threads an image at a time for nothing.+ (line, detail) => {+ if (!detail || process.env.TRILIUM_IMAGE_WORKER_DEBUG) {+ logs.push(line);+ }+ },+ message.budgetMb+ ).then(- (outcome) => reply({ id: message.id, outcome, logs }),- (error: unknown) => reply({ id: message.id, error: describe(error), logs })+ (outcome) => {+ trace(`image #${message.id} ${outcome.compressed ? "compressed" : `skipped (${outcome.reason})`}`+ + ` in ${Date.now() - started}ms; replying`);+ reply({ id: message.id, outcome, logs });+ },+ (error: unknown) => {+ trace(`image #${message.id} failed in ${Date.now() - started}ms: ${describe(error)}`);+ reply({ id: message.id, error: describe(error), logs });+ });});diff --git a/apps/server/src/services/image_worker_pool.ts b/apps/server/src/services/image_worker_pool.tsindex 4afc485123..18330dc977 100644--- a/apps/server/src/services/image_worker_pool.ts+++ b/apps/server/src/services/image_worker_pool.ts@@ -23,27 +23,32 @@ import { availableParallelism } from "node:os";import { join } from "node:path";import { Worker } from "node:worker_threads";-import type { ImageWorkerRequest, ImageWorkerResponse } from "./image_worker.js";+import type { ImageWorkerRequest, ImageWorkerResponse, ImageWorkerTrace } from "./image_worker.js";/*** How many images may be compressed at once, or 1 where they cannot be compressed off-thread at* all — which is the same answer as "do it here", and is what the caller schedules against.*- * One per core. The thread this frees up needs very little while they work — it hands out images,- * takes the results and writes them — so holding a core back for it would leave one idle through- * the whole run for the sake of the part that is already waiting.+ * Capped low, and deliberately not scaled to the machine. Decoding a photograph is bound by memory+ * bandwidth at least as much as by processor: past a handful of them the decoders are queueing for+ * the same bus, and adding more buys contention rather than throughput. Measured on a 24-thread+ * machine, letting it run one per core left a 380 KB image taking 10.7 seconds where a 4.9 MB one+ * had taken 2.9 seconds earlier in the same run — and starting a further thread, 24ms of work at+ * the outset, took 2.3 seconds by then.*- * This is a ceiling rather than a promise: what actually runs at once is whatever the memory budget- * admits, so on a machine with many cores and images to match, the budget is the binding constraint- * and this never comes into it.+ * It stays a ceiling rather than a promise: what actually runs at once is whatever the memory budget+ * admits, which on large images is fewer still.*- * `availableParallelism` rather than the raw core count: it follows the affinity the process was- * given, so a container pinned to two cores is answered as two.+ * `availableParallelism` rather than the raw core count, for the machines below the cap: it follows+ * the affinity the process was given, so a container pinned to two cores is answered as two.*/export function compressionConcurrency(): number {- return workerEntry() ? Math.max(1, availableParallelism()) : 1;+ return workerEntry() ? Math.max(1, Math.min(MAX_WORKERS, availableParallelism())) : 1;}+/** Where decoding stops going faster for being given more threads; see above for the measurement. */+const MAX_WORKERS = 4;+/*** Compresses one image in a worker, or answers `null` if there is no worker to do it in — which the* caller reads as "then do it yourself" rather than as a failure of the image.@@ -88,23 +93,65 @@ export async function compressInWorker(// Nothing has ever come back from a worker here, so this is not one thread having died but// this installation being unable to run them — an environment whose loader cannot read the- // entry point, say. Trying again per image would fail a thousand times over.+ // entry point, say. Answered as "there are no workers", which is the truth of it: this image+ // and every one after it is compressed by the caller, exactly as before there were threads.if (!everSucceeded) {- disable(`they do not work here (${firstLine(e)})`);+ return disable(`they do not work here (${firstLine(e)})`);}+ // Workers do work here, and one of them failed on this image. Raised rather than answered+ // with a fallback: doing it on the calling thread instead would stop the application for the+ // length of a decode, and doing that for each of several failing workers is how a run takes+ // the whole application down with it. The image is reported untouched and the run goes on.throw e;}}-/** Stops the pool between runs, so an idle Trilium is not holding threads it is not using. */+/**+ * Stops the workers that are not doing anything, so a Trilium that has finished compressing is not+ * still holding them.+ *+ * A thread does not release what it decoded when it goes quiet — its isolate keeps the last image+ * it worked on until something there collects it, and several idle threads each sitting on a+ * decoded photograph is memory the rest of the application would rather have. Terminating them+ * gives it back outright.+ *+ * Only the free ones: a busy worker is not in the pool to be found here, and is left to finish.+ */export function shutdownImageWorkers() {- idle.forEach((pooled) => void pooled.worker.terminate());+ started -= idle.length;+ idle.forEach((pooled) => {+ pooled.stopped = true;+ void pooled.worker.terminate();+ });idle.length = 0;}+/**+ * How long the pool waits, having been given nothing to do, before letting its threads go.+ *+ * Long enough that the images of one run do not pay to start a thread each, short enough that a run+ * which has finished stops costing anything soon after. Nothing schedules a run, so any wait at all+ * is only ever bridging the gap between two images.+ */+const IDLE_SHUTDOWN_MS = 30 * 1000;++let idleTimer: NodeJS.Timeout | undefined;++/** Restarted whenever a worker comes free, so the countdown only ever runs on a quiet pool. */+function scheduleShutdown() {+ clearTimeout(idleTimer);+ idleTimer = setTimeout(shutdownImageWorkers, IDLE_SHUTDOWN_MS);+ // Never a reason for this to be what holds the process open.+ idleTimer.unref();+}+interface PooledWorker {worker: Worker;+ /** Captured while it is alive: a thread reports its id as -1 once it has gone. */+ threadId: number;+ /** Set when we stopped it ourselves, so its exit is not reported as something going wrong. */+ stopped?: boolean;pending?: (response: ImageWorkerResponse) => void;failed?: (error: unknown) => void;}@@ -153,6 +200,8 @@ function release(worker: PooledWorker) {}idle.push(worker);+ // Nothing was waiting for it, so this may well have been the last image of a run.+ scheduleShutdown();}/**@@ -164,10 +213,35 @@ function release(worker: PooledWorker) {*/function retire(worker: PooledWorker) {started--;+ worker.stopped = true;void worker.worker.terminate();waiting.shift()?.(null);}+/**+ * The heap a worker is given: sized to the work, and neither inherited nor unbounded.+ *+ * Both directions matter, which is why this is a fixed figure rather than a floor.+ *+ * Too small and a decode does not fail, it collects — over and over, taking several times longer+ * while looking perfectly healthy. A thread started by Electron's main process inherits a heap set+ * for running an application, not for decoding photographs.+ *+ * Too large is the subtler half. V8 collects lazily against its ceiling, so a thread allowed four+ * gigabytes will happily accumulate several before it bothers, and four such threads can put a+ * machine into paging — where the symptom is not the compression slowing down but everything else+ * stopping, the process that hosts them included.+ *+ * This is what one decode actually needs: the memory budget a single image may claim, and room to+ * work around it. A worker only ever holds one image at a time, so it never needs more.+ */+function workerLimits() {+ return { maxOldGenerationSizeMb: WORKER_HEAP_MB };+}++/** Room for the largest decode the budget will admit, and the working set around it. */+const WORKER_HEAP_MB = 2048;+function spawn(): PooledWorker | null {const entry = workerEntry();@@ -179,12 +253,46 @@ function spawn(): PooledWorker | null {}try {- const pooled: PooledWorker = { worker: new Worker(entry.file, { execArgv: entry.execArgv }) };-- pooled.worker.on("message", (response: ImageWorkerResponse) => pooled.pending?.(response));+ const startedAt = Date.now();+ const limits = workerLimits();+ const worker = new Worker(entry.file, { execArgv: entry.execArgv, resourceLimits: limits });+ // Read now rather than in the handlers: a thread that has exited reports its id as -1, which+ // is the one moment the id is worth having.+ const pooled: PooledWorker = { worker, threadId: worker.threadId };++ // Rare enough to say out loud without asking: a handful of lines per process, and the ones+ // that answer "did a thread ever start, and did it stay up" — which is the whole question+ // when a run stops making progress.+ getLog().info(`Image Compression Tool: starting a worker with a `+ + `${limits.maxOldGenerationSizeMb} MB heap from ${entry.file}`);+ pooled.worker.on("online",+ () => getLog().info(`Image Compression Tool: worker ${pooled.threadId} online in ${Date.now() - startedAt}ms`));++ pooled.worker.on("message", (response: ImageWorkerResponse | ImageWorkerTrace) => {+ // Traces arrive while the image is still being worked on, so they are written straight+ // out rather than waited for; only the answer settles the request.+ if ("trace" in response) {+ getLog().info(`Image Compression Tool: ${response.trace}`);++ return;+ }++ pooled.pending?.(response);+ });// A worker that dies takes its in-flight image with it; the image is failed, not the run.- pooled.worker.on("error", (error) => pooled.failed?.(error));- pooled.worker.on("exit", () => pooled.failed?.(new Error("Image worker exited.")));+ pooled.worker.on("error", (error) => {+ getLog().info(`Image Compression Tool: worker ${pooled.threadId} errored: ${firstLine(error)}`);+ pooled.failed?.(error);+ });+ pooled.worker.on("exit", (code) => {+ // A thread we stopped ourselves exits with a failure code too, so saying so plainly is+ // the difference between "this is the pool tidying up" and "something died mid-image".+ getLog().info(pooled.stopped+ ? `Image Compression Tool: worker ${pooled.threadId} stopped`+ : `Image Compression Tool: worker ${pooled.threadId} exited unexpectedly with code ${code}`+ + `${pooled.pending ? " while working on an image" : " while idle"}`);+ pooled.failed?.(new Error(`Image worker exited with code ${code}.`));+ });pooled.worker.unref();return pooled;@@ -221,16 +329,25 @@ function send(budgetMb: number): Promise<ImageWorkerResponse> {const message: ImageWorkerRequest = { id: ++lastRequestId, buffer, request, budgetMb };+ const sentAt = Date.now();++ trace(`sending image #${message.id} (${buffer.byteLength} bytes) to worker ${worker.threadId}`+ + ` — ${started} started, ${idle.length} idle, ${waiting.length} waiting`);return new Promise<ImageWorkerResponse>((resolve, reject) => {// A thread that took an image and went quiet would otherwise hold the run open with nothing// to show for it. Generous, because a large decode legitimately takes minutes; expiring is// treated as the worker having failed, and the image is compressed here instead.- const expiry = setTimeout(- () => reject(new Error("Image worker did not answer in time.")), WORKER_REPLY_TIMEOUT_MS);+ const expiry = setTimeout(() => {+ getLog().info(+ `Image Compression Tool: worker ${worker.threadId} did not answer for image `+ + `#${message.id} within ${WORKER_REPLY_TIMEOUT_MS}ms; giving up on it`);+ reject(new Error("Image worker did not answer in time."));+ }, WORKER_REPLY_TIMEOUT_MS);worker.pending = (response) => {clearTimeout(expiry);+ trace(`worker ${worker.threadId} answered image #${message.id} in ${Date.now() - sentAt}ms`);resolve(response);};worker.failed = (error) => {@@ -246,7 +363,31 @@ function send(});}-const WORKER_REPLY_TIMEOUT_MS = 5 * 60 * 1000;+/**+ * How long a worker is given to answer before it is written off.+ *+ * Deliberately far longer than any decode should take, because the cost of being wrong in this+ * direction is small and the cost of being wrong in the other is not. Two minutes looked generous+ * against images that decode in seconds — until an image near the size ceiling, sharing the memory+ * bus with three others, legitimately took longer than that. Killing it did not save any time: the+ * work fell back onto the thread serving the application, blocked it for twenty seconds, and made+ * the next worker time out in turn.+ *+ * So this is for a thread that has genuinely stopped, not for one that is taking a while. A run+ * meets that at most once per worker, and the images are not waiting on anything else meanwhile.+ */+const WORKER_REPLY_TIMEOUT_MS = 15 * 60 * 1000;++/**+ * Per-image tracing, off unless asked for: a cleanup over a large tree would otherwise write two+ * lines per image into the log a user reads. Set `TRILIUM_IMAGE_WORKER_DEBUG` to follow a run image+ * by image; the worker reads the same variable and traces its own side to stdout.+ */+function trace(message: string) {+ if (process.env.TRILIUM_IMAGE_WORKER_DEBUG) {+ getLog().info(`Image Compression Tool: ${message}`);+ }+}let lastRequestId = 0;diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex baa04d15be..94de2d1b70 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -18,6 +18,7 @@ import BAttachment from "../becca/entities/battachment.js";import type BNote from "../becca/entities/bnote.js";import { NotFoundError, ValidationError } from "../errors.js";import { getImageProvider, type ImageCompressionRequest } from "./image_provider.js";+import { getContext } from "./context.js";import { getLog } from "./log.js";import optionService from "./options.js";import { runWithinBudget } from "./parallel_budget.js";@@ -447,18 +448,23 @@ async function compressTargets(targets: CompressionTarget[], request: ImageCompr}}+ const writes = createWriteBatch();const compressed = await runWithinBudget(- worthReading.map(({ target, cost }) => ({ cost, run: () => compressTarget(target, request) })),+ worthReading.map(({ target, cost }) => ({ cost, run: () => compressTarget(target, request, writes) })),{ totalBytes: COMPRESSION_BUDGET_BYTES, maxConcurrent: concurrency });+ // Nothing should be left — every write either filled a group or waited out its own timer — but+ // saying so costs nothing and a run must not end holding work it has not committed.+ writes.flush();+// Back into the order they were visited in, which is the order they are reported in — the// schedule above is free to have run them in any other.worthReading.forEach(({ at }, index) => {items[at] = compressed[index];});- return summarize(items);+ return logRunEnd(summarize(items));}/**@@ -488,6 +494,102 @@ function logRunStart(imageCount: number, concurrency: number) {getLog().info(`Image Compression Tool: started operation over ${images} ${how}.`);}+/**+ * Commits the run's writes in groups instead of one at a time.+ *+ * Every compressed image is a new blob written, an old one — often several megabytes — deleted, a+ * row updated and a change recorded. On its own that is a small transaction; eight hundred of them+ * back to back is gigabytes of pages through the write-ahead log, a commit and a flush each, and+ * the checkpoints that follow. None of that stops the process, which is what makes it confusing to+ * watch: the application keeps answering while the database it shares stops being available to+ * anything else, the note holding the log included.+ *+ * Grouping them changes none of the writing and almost all of the committing.+ *+ * Flushed when the group is full *or* when one has been waiting: without the second, the last few+ * images of a run would sit in a batch that never fills, and the run waits on them — which is a+ * deadlock rather than a delay.+ */+function createWriteBatch() {+ const pending: {+ write: () => boolean;+ settle: (saved: boolean) => void;+ fail: (error: unknown) => void;+ }[] = [];+ let timer: ReturnType<typeof setTimeout> | undefined;++ function flush() {+ clearTimeout(timer);+ timer = undefined;++ const batch = pending.splice(0);++ if (batch.length === 0) {+ return;+ }++ try {+ // Each write answers for itself inside the one transaction: a single image that cannot+ // be written must not take the other twenty-four down with it, which is what letting+ // the exception out would do.+ // Given a context of its own, as every other write resumed after an asynchronous step+ // is: a flush runs from a timer, by which point the one the request was carrying is no+ // longer around it, and a transaction without one has no entity changes to record+ // against. `image.ts` does the same after its own processing completes.+ const outcomes = getContext().init(() => getSql().transactional(() => batch.map((entry) => {+ try {+ return { saved: entry.write() };+ } catch (error: unknown) {+ return { error };+ }+ })));++ batch.forEach((entry, at) => {+ const outcome = outcomes[at];++ if ("error" in outcome) {+ entry.fail(outcome.error);+ } else {+ entry.settle(outcome.saved);+ }+ });+ } catch (error: unknown) {+ // The transaction itself failed — not one write within it, but the whole thing, which+ // leaves every image in this group unanswered.+ //+ // Answering them is the entire point of catching it. A flush runs from a timer, so an+ // exception let out here goes nowhere anyone is watching, and the images waiting on it+ // wait for a promise that will never settle: the run stops, silently and permanently,+ // with its workers idle and nothing in the log to say why. Reporting the failure costs+ // those images and nothing else.+ getLog().error(`Image Compression Tool: a batch of ${batch.length} writes failed: ${error}`);+ batch.forEach((entry) => entry.fail(error));+ }+ }++ return {+ /** Queues a write and answers once it has been committed, with whatever it answered. */+ add(write: () => boolean): Promise<boolean> {+ return new Promise<boolean>((settle, fail) => {+ pending.push({ write, settle, fail });++ if (pending.length >= WRITE_BATCH_SIZE) {+ flush();+ } else if (!timer) {+ timer = setTimeout(flush, WRITE_BATCH_MS);+ }+ });+ },+ flush+ };+}++/** Enough to make the commits rare, few enough that a run is never far from having saved its work. */+const WRITE_BATCH_SIZE = 25;++/** How long a write waits for company before going on its own. */+const WRITE_BATCH_MS = 250;+/*** What is already known about a target before reading it: the finished item where its fate was* settled from the header, otherwise what its decode is expected to want.@@ -539,13 +641,18 @@ async function foreseeTarget(target: CompressionTarget, request: ImageCompressio* Reads one image in full and compresses it. Reached only for images {@link foreseeTarget} could* not settle from the header, so the reading and the decoding are both known to be worth doing.*/-async function compressTarget(target: CompressionTarget, request: ImageCompressionRequest): Promise<ImageCompressionItem> {+async function compressTarget(+ target: CompressionTarget,+ request: ImageCompressionRequest,+ writes: ReturnType<typeof createWriteBatch>+): Promise<ImageCompressionItem> {const skipped = (originalSize: number, skipReason: ImageCompressionSkipReason) =>skippedItem(target, originalSize, skipReason);// One image failing is reported as that image's own skip and nothing more: the images after it// in the same run are still worth compressing.let content: Uint8Array | undefined;+ const startedAt = Date.now();try {content = target.getContent();@@ -558,12 +665,16 @@ async function compressTarget(target: CompressionTarget, request: ImageCompressireturn skipped(content.byteLength, outcome.reason);}- // The compression itself is asynchronous, so the write is a separate transaction of its- // own rather than one held open across it. Long enough, in fact, for the image to have been- // replaced meanwhile — by another request, or by an incoming synchronisation update — and- // these bytes are a smaller copy of the picture that replacement got rid of. Nothing here- // is worth putting that back, so the newer image wins and this one is reported as skipped.- const saved = getSql().transactional(() => target.save(outcome.buffer, outcome.format.mime, sourceBlobId));+ // Queued rather than written here and now: the compression was asynchronous, so this is a+ // transaction of its own either way, and one shared with the images finishing around it+ // costs the database a fraction of what eight hundred separate commits do.+ //+ // The wait is long enough for the image to have been replaced meanwhile — by another+ // request, or by an incoming synchronisation update — and these bytes are a smaller copy of+ // the picture that replacement got rid of. Nothing here is worth putting that back, so the+ // newer image wins and this one is reported as skipped. The check happens inside the+ // transaction, whichever group it lands in.+ const saved = await writes.add(() => target.save(outcome.buffer, outcome.format.mime, sourceBlobId));if (!saved) {getLog().info(@@ -573,8 +684,14 @@ async function compressTarget(target: CompressionTarget, request: ImageCompressireturn skipped(content.byteLength, "changed");}+ // The elapsed time rides on the line that was being written anyway. Per-image timing is the+ // first thing wanted when a run is slower than it should be, and asking for it separately+ // meant either a second line an image — which is what made the log a burden — or a setting+ // nobody has turned on at the moment they need it. This covers the whole of an image's+ // handling: reading it, compressing it, and waiting for its write to be committed.getLog().info(- `Compressed ${target.entityType} '${target.entityId}' from ${content.byteLength} to ${outcome.buffer.byteLength} bytes.`+ `Compressed ${target.entityType} '${target.entityId}' from ${content.byteLength} to `+ + `${outcome.buffer.byteLength} bytes in ${Date.now() - startedAt}ms.`);return {@@ -619,6 +736,35 @@ function logFailure(target: CompressionTarget, e: unknown) {getLog().error(`Failed to compress ${target.entityType} '${target.entityId}': ${error?.stack ?? error}`);}+/**+ * Says how a run ended, which until now nothing did.+ *+ * A run that finished and a run that stopped part-way looked exactly alike in the log: images going+ * by, and then no more lines. Saying so plainly is the difference between "it is still working" and+ * "it is done" — and the tally of what was left alone is usually the answer to why so few images+ * were touched at all.+ */+function logRunEnd(response: ImageCompressionResponse): ImageCompressionResponse {+ if (response.items.length > 0) {+ const reasons = new Map<string, number>();++ response.items.filter((item) => !item.compressed).forEach((item) => {+ const reason = item.skipReason ?? "unknown";++ reasons.set(reason, (reasons.get(reason) ?? 0) + 1);+ });++ const left = [ ...reasons ].map(([ reason, count ]) => `${count} ${reason}`).join(", ");++ getLog().info(+ `Image Compression Tool: finished — ${response.compressedCount} compressed, `+ + `${response.skippedCount} left alone${left ? ` (${left})` : ""}, `+ + `${response.savedSize} bytes saved.`);+ }++ return response;+}+function summarize(items: ImageCompressionItem[]): ImageCompressionResponse {const originalSize = items.reduce((total, item) => total + item.originalSize, 0);const newSize = items.reduce((total, item) => total + item.newSize, 0);