Skip to content

Build your personal knowledge base with Trilium Notes

core/image compression: report compression progress

Adorian Dorane2ccd8e2ca75
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 3ea9367b76..53374db2ed 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2977,6 +2977,7 @@
"compress_process_child_notes_help": "Compresses the images of every note in the subtree, not just the selected one. Beware that a child note may be a clone, in which case its images are shared with the other notes it appears in.",
"compress_cancel": "Cancel",
"compress_running": "Compressing images…",
+ "compress_running_progress": "Compressing image {{done}} of {{total}}…",
"compress_result_one": "{{count}} image processed, reducing the size from {{before}} to {{after}}.",
"compress_result_other": "{{count}} images processed, reducing the size from {{before}} to {{after}}.",
"compress_result_no_gain_one": "{{count}} image processed, but it could not be made any smaller.",
diff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsx b/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsx
index 179cf7bcf1..911bb66b33 100644
--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsx
+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsx
@@ -695,6 +695,9 @@ describe("running the compression", () => {
expect(postedUrl()).toBe("notes/n1/compress-images");
expect(postedBody()).toEqual({
+ // Names the run so its progress can be followed back over the websocket; generated per
+ // request, so only its presence is worth asserting.
+ taskId: expect.any(String),
resize: true,
maxWidthHeight: DEFAULT_MAX_WIDTH_HEIGHT,
jpegHandling: "compress",
diff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.tsx b/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.tsx
index 0fa1cc6b22..b09663b363 100644
--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.tsx
+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.tsx
@@ -99,20 +99,28 @@ function ImageCompressionDialog({ target, onFinished }: {
return;
}
- // Nothing here can say how far along it is — the images are compressed server-side and the
- // run reports only once — so a spinner rather than a bar, and nothing to cancel: the server
- // carries on whatever the client does.
- toast.showPersistent({
+ // A spinner rather than a bar, and nothing to cancel: the server carries on whatever the
+ // client does. The message is replaced as the count arrives — one toast throughout, so the
+ // wording changes in place rather than a second toast appearing beside the first.
+ const showProgress = (message: string) => toast.showPersistent({
id: IMAGE_COMPRESSION_TOAST_ID,
icon: "bx bx-loader-circle bx-spin",
- message: t("space_usage.compress_running"),
+ message,
dismissible: false
});
+ showProgress(t("space_usage.compress_running"));
+
let result: ImageCompressionResponse | null = null;
try {
- result = await runImageCompression(target, settings);
+ result = await runImageCompression(target, settings, (done, total) => {
+ // Until the run has said how many there are, the count on its own would read as a
+ // total; the wording without one says only that it is working through them.
+ showProgress(total === undefined
+ ? t("space_usage.compress_running")
+ : t("space_usage.compress_running_progress", { done, total }));
+ });
toast.showMessage(compressionResultMessage(result), COMPRESSION_DONE_TIMEOUT_MS);
} catch {
// Already reported by the request layer, and nothing here can say what the run managed
diff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_operation.ts b/apps/client/src/widgets/dialogs/image_compression/image_compression_operation.ts
index cca89a62f4..f519ea1997 100644
--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_operation.ts
+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_operation.ts
@@ -1,8 +1,9 @@
-import type { ImageCompressionResponse } from "@triliumnext/commons";
+import type { ImageCompressionResponse, WebSocketMessage } from "@triliumnext/commons";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
-import { formatSize } from "../../../services/utils";
+import { formatSize, randomString } from "../../../services/utils";
+import { subscribeToMessages, unsubscribeToMessage } from "../../../services/ws";
import type { ImageCompressionToolOptions } from "./image_compression_options";
/**
@@ -38,16 +39,26 @@ export const IMAGE_COMPRESSION_TOAST_ID = "image-compression";
*/
const COMPRESSION_TIMEOUT_MS = 60 * 60 * 1000;
-/** Compresses the target's images and reports what that did, image by image and in total. */
+/**
+ * Compresses the target's images and reports what that did, image by image and in total.
+ *
+ * `onProgress` is called as the run works through them. A subtree can hold hundreds, and the request
+ * itself says nothing until it is over — so the count comes back the other way, over the websocket,
+ * against a task named here and quoted in the request.
+ */
export function runImageCompression(
target: ImageCompressionTarget,
- options: ImageCompressionToolOptions
+ options: ImageCompressionToolOptions,
+ onProgress?: (done: number, total: number | undefined) => void
): Promise<ImageCompressionResponse> {
const url = target.type === "note"
? `notes/${target.noteId}/compress-images`
: `attachments/${target.attachmentId}/compress-image`;
+ const taskId = randomString(12);
+ const listener = onProgress && followProgress(taskId, onProgress);
return server.postWithTimeout<ImageCompressionResponse>(url, COMPRESSION_TIMEOUT_MS, {
+ taskId,
resize: options.resize,
maxWidthHeight: options.maxWidthHeight,
jpegHandling: options.jpegHandling,
@@ -57,9 +68,33 @@ export function runImageCompression(
// Left out entirely for an attachment, which has no subtree to descend into — the endpoint
// does not read it, and sending it would suggest it does.
...(target.type === "note" ? { recursive: options.processChildNotes } : {})
+ }).finally(() => {
+ if (listener) {
+ unsubscribeToMessage(listener);
+ }
});
}
+/**
+ * Watches one run's progress messages, and only that run's.
+ *
+ * Subscribed for the length of the request rather than for the length of the session: a run is
+ * started from here and is over when the request answers, so there is nothing for a listener to
+ * hear before or after. The task id is checked as well as the type — two runs can be in flight from
+ * two windows, and each should count its own.
+ */
+function followProgress(taskId: string, onProgress: (done: number, total: number | undefined) => void) {
+ const listener = (message: WebSocketMessage) => {
+ if (message.type === "taskProgressCount" && "taskId" in message && message.taskId === taskId) {
+ onProgress(message.progressCount, message.totalCount);
+ }
+ };
+
+ subscribeToMessages(listener);
+
+ return listener;
+}
+
/**
* What the run is told to have done. Every image it visited is counted, skipped ones included, so
* the count and the two sizes are all measured over the same set and read as one sentence.
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index ce24402546..b2b454ffc6 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -461,6 +461,11 @@ export interface ImageCompressionOptions {
* Only the note endpoint reads this; an attachment has no subtree to descend into.
*/
recursive?: boolean;
+ /**
+ * Names a task to report progress against, so a caller watching a long run can be told how far
+ * it has got. Left out, the run reports only when it finishes.
+ */
+ taskId?: string;
}
/**
diff --git a/packages/commons/src/lib/ws_api.ts b/packages/commons/src/lib/ws_api.ts
index e0cf91f62b..eef027eb36 100644
--- a/packages/commons/src/lib/ws_api.ts
+++ b/packages/commons/src/lib/ws_api.ts
@@ -42,7 +42,8 @@ type TaskDataDefinitions = {
shrinkImages?: boolean;
safeImport?: boolean;
} | null,
- importAttachments: null
+ importAttachments: null,
+ compressImages: null
}
type TaskResultDefinitions = {
@@ -59,6 +60,7 @@ type TaskResultDefinitions = {
parentNoteId?: string;
importedNoteId?: string
};
+ compressImages: null;
}
export type TaskType = keyof TaskDataDefinitions | keyof TaskResultDefinitions;
diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.ts
index 94de2d1b70..5321cffad4 100644
--- a/packages/trilium-core/src/services/image_compression.ts
+++ b/packages/trilium-core/src/services/image_compression.ts
@@ -23,6 +23,7 @@ import { getLog } from "./log.js";
import optionService from "./options.js";
import { runWithinBudget } from "./parallel_budget.js";
import { getSql } from "./sql/index.js";
+import TaskContext from "./task_context.js";
import { wrapStringOrBuffer } from "./utils/binary.js";
/** Quality bounds shared with the automatic shrinking, so the two cannot drift apart. */
@@ -48,7 +49,8 @@ export async function compressNoteImages(noteId: string, options?: ImageCompress
throw new NotFoundError(`Note '${noteId}' was not found.`);
}
- return compressTargets(collectNoteTargets(note, resolveRecursive(options)), resolveCompressionRequest(options));
+ return compressTargets(
+ collectNoteTargets(note, resolveRecursive(options)), resolveCompressionRequest(options), options?.taskId);
}
/** Compresses one image attachment, under exactly the rules a whole-note run would apply to it. */
@@ -63,7 +65,7 @@ export async function compressAttachmentImage(attachmentId: string, options?: Im
throw new ValidationError(`Attachment '${attachmentId}' has role '${attachment.role}', but 'image' was expected.`);
}
- return compressTargets([ attachmentTarget(attachment) ], resolveCompressionRequest(options));
+ return compressTargets([ attachmentTarget(attachment) ], resolveCompressionRequest(options), options?.taskId);
}
/**
@@ -430,8 +432,13 @@ function resolveAttachmentSkip(attachment: BAttachment): ImageCompressionSkipRea
* The passes are not an optimization of each other: the first exists because deciding should not
* cost what doing costs, the second because doing should not be allowed to cost everything at once.
*/
-async function compressTargets(targets: CompressionTarget[], request: ImageCompressionRequest): Promise<ImageCompressionResponse> {
+async function compressTargets(
+ targets: CompressionTarget[],
+ request: ImageCompressionRequest,
+ taskId?: string
+): Promise<ImageCompressionResponse> {
const concurrency = getImageProvider().compressionConcurrency();
+ const reportProgress = progressReporter(taskId, targets.length);
logRunStart(targets.length, concurrency);
@@ -443,6 +450,7 @@ async function compressTargets(targets: CompressionTarget[], request: ImageCompr
if (foreseen.item) {
items[at] = foreseen.item;
+ reportProgress();
} else {
worthReading.push({ at, target, cost: foreseen.cost });
}
@@ -450,7 +458,10 @@ async function compressTargets(targets: CompressionTarget[], request: ImageCompr
const writes = createWriteBatch();
const compressed = await runWithinBudget(
- worthReading.map(({ target, cost }) => ({ cost, run: () => compressTarget(target, request, writes) })),
+ worthReading.map(({ target, cost }) => ({
+ cost,
+ run: () => compressTarget(target, request, writes).finally(reportProgress)
+ })),
{ totalBytes: COMPRESSION_BUDGET_BYTES, maxConcurrent: concurrency }
);
@@ -467,6 +478,29 @@ async function compressTargets(targets: CompressionTarget[], request: ImageCompr
return logRunEnd(summarize(items));
}
+/**
+ * Counts images off against the total, so a run of hundreds can say how far it has got rather than
+ * only that it is going.
+ *
+ * Every image counts, whether it was compressed or settled from its header — the total is what the
+ * run set out to visit, so the two have to agree or the count would stall short of its own end. The
+ * effect is that a tree of mostly-untouched images races to a high number and then slows, which is
+ * a fair picture of what is happening.
+ *
+ * A run nobody asked to watch is not reported on: without a task to report against, this is nothing.
+ */
+function progressReporter(taskId: string | undefined, total: number): () => void {
+ if (!taskId) {
+ return () => {};
+ }
+
+ const task = TaskContext.getInstance(taskId, "compressImages", null);
+
+ task.setTotalCount(total);
+
+ return () => task.increaseProgressCount();
+}
+
/**
* The most all decodes running at once may be holding between them.
*