Skip to content

Build your personal knowledge base with Trilium Notes

core/image compression tool: fix some issues

Adorian Doran562fb6870be4
diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.ts
index 01d8a67680..df09ac5a5a 100644
--- a/apps/server/src/services/image_compression.spec.ts
+++ b/apps/server/src/services/image_compression.spec.ts
@@ -1,5 +1,6 @@
import type { ImageCompressionResponse } from "@triliumnext/commons";
import { becca, cls, getSql, options } from "@triliumnext/core";
+import { getImageProvider, initImageProvider } from "@triliumnext/core/src/services/image_provider.js";
import { createTextNote } from "@triliumnext/core/src/test/api_fixtures.js";
import { CoreApiTester } from "@triliumnext/core/src/test/api_tester.js";
import { Jimp } from "jimp";
@@ -426,6 +427,61 @@ describe("compress one attachment (POST /api/attachments/:attachmentId/compress-
});
});
+/**
+ * Re-encoding an image takes long enough — seconds, for a large one — that the image can be
+ * replaced while it is happening, by another request or by an incoming synchronisation update. What
+ * comes out of the encoder is then a smaller copy of a picture that no longer exists, and writing
+ * it would silently put the replaced image back with no revision to recover the newer one from.
+ */
+describe("an image changed mid-run", () => {
+ it("keeps a replaced attachment instead of overwriting it with the older picture", async () => {
+ const { noteId } = await createTextNote(api);
+ const attachmentId = await addAttachment(noteId, "target.png", noisyPng);
+
+ const res = await whileCompressing(
+ () => replaceAttachmentContent(attachmentId, smallPng),
+ () => api.post<ImageCompressionResponse>(`/api/attachments/${attachmentId}/compress-image`, {
+ body: { pngHandling: "jpeg" }
+ })
+ );
+
+ expect(res.body.items[0]).toMatchObject({ compressed: false, skipReason: "changed" });
+ // Still the replacement, and still a PNG: a write would have made it the JPEG it converts to.
+ expect(readAttachment(attachmentId)).toMatchObject({ size: smallPng.byteLength, mime: "image/png" });
+ });
+
+ it("keeps a replaced image note instead of overwriting it with the older picture", async () => {
+ const noteId = await createImageNote(noisyPng);
+
+ const res = await whileCompressing(
+ () => replaceNoteContent(noteId, smallPng),
+ () => api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {
+ body: { pngHandling: "jpeg" }
+ })
+ );
+
+ expect(res.body.items[0]).toMatchObject({ compressed: false, skipReason: "changed" });
+ expect(readNote(noteId)).toMatchObject({ size: smallPng.byteLength, mime: "image/png" });
+ });
+
+ it("compresses over a change that left the image alone, without reverting it", async () => {
+ const { noteId } = await createTextNote(api);
+ const attachmentId = await addAttachment(noteId, "before.png", noisyPng);
+
+ const res = await whileCompressing(
+ () => renameAttachment(attachmentId, "after.png"),
+ () => api.post<ImageCompressionResponse>(`/api/attachments/${attachmentId}/compress-image`, {
+ body: { pngHandling: "jpeg" }
+ })
+ );
+
+ // The picture itself never moved, so there is nothing to refuse — but the run must write
+ // through the attachment as it is now, not the copy of the row it started from.
+ expect(res.body.items[0]).toMatchObject({ compressed: true });
+ expect(readAttachment(attachmentId).title).toBe("after.png");
+ });
+});
+
/**
* Paints the fixture: smooth sine gradients across all three channels, giving a picture with the
* statistics of a photograph — many distinct colours, strongly correlated between neighbours.
@@ -491,6 +547,54 @@ function readAttachment(attachmentId: string): { mime: string; title: string; si
});
}
+/**
+ * Runs `interfere` at the one moment that matters — after the run has read an image, before it
+ * writes the result back — and runs `request` inside that arrangement.
+ *
+ * Standing in for the real provider is what makes the moment reachable at all: the window is real,
+ * but it is only as wide as an encoder is slow, and a test that raced it would pass by luck.
+ */
+async function whileCompressing<T>(interfere: () => void, request: () => Promise<T>): Promise<T> {
+ const real = getImageProvider();
+
+ initImageProvider({
+ getImageType: (buffer) => real.getImageType(buffer),
+ processImage: (buffer, originalName, shrink) => real.processImage(buffer, originalName, shrink),
+ compressImage: (buffer, compressionRequest) => {
+ interfere();
+ return real.compressImage(buffer, compressionRequest);
+ }
+ });
+
+ try {
+ return await request();
+ } finally {
+ initImageProvider(real);
+ }
+}
+
+/** Someone else replacing the picture — a re-upload, or a synchronisation update landing. */
+function replaceAttachmentContent(attachmentId: string, content: Uint8Array) {
+ cls.init(() => getSql().transactional(() => {
+ becca.getAttachmentOrThrow(attachmentId).setContent(content, { forceSave: true });
+ }));
+}
+
+function replaceNoteContent(noteId: string, content: Uint8Array) {
+ cls.init(() => getSql().transactional(() => {
+ becca.getNoteOrThrow(noteId).setContent(content, { forceSave: true });
+ }));
+}
+
+/** A change to the attachment that leaves its content alone, which compression must not undo. */
+function renameAttachment(attachmentId: string, title: string) {
+ cls.init(() => getSql().transactional(() => {
+ const attachment = becca.getAttachmentOrThrow(attachmentId);
+ attachment.title = title;
+ attachment.save();
+ }));
+}
+
function itemFor(response: ImageCompressionResponse, entityId: string) {
const item = response.items.find((candidate) => candidate.entityId === entityId);
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 6da0691661..1d2d53a6ee 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -483,6 +483,12 @@ export type ImageCompressionSkipReason =
| "no-gain"
/** This build has no image compression at all (the standalone/WASM runtime). */
| "unsupported-platform"
+ /**
+ * The image was replaced while it was being re-encoded — by another request, or by a
+ * synchronisation update — so the result was derived from content that no longer exists. Writing
+ * it would have put the superseded picture back; the newer one is kept instead.
+ */
+ | "changed"
/** Compression failed; the original was kept and the failure logged. */
| "error";
diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.ts
index 5cdc9641fa..b1d2a10698 100644
--- a/packages/trilium-core/src/services/image_compression.ts
+++ b/packages/trilium-core/src/services/image_compression.ts
@@ -157,7 +157,14 @@ export interface CompressionTarget {
/** Set when the target must be left alone for a reason known before reading its content. */
skip?: ImageCompressionSkipReason;
getContent(): Uint8Array;
- save(buffer: Uint8Array, mime: string): void;
+ /** Names the content {@link getContent} returns — a hash of those exact bytes. */
+ blobId(): string | undefined;
+ /**
+ * Writes the compressed image back, but only over the content it was derived from: re-encoding
+ * is slow enough for the image to be replaced meanwhile, and this result describes the picture
+ * that was there before. Answers whether the write happened.
+ */
+ save(buffer: Uint8Array, mime: string, sourceBlobId: string | undefined): boolean;
}
/**
@@ -203,25 +210,48 @@ function noteTarget(note: BNote): CompressionTarget {
mime: note.mime,
skip: note.isContentAvailable() ? undefined : "protected",
getContent: () => wrapStringOrBuffer(note.getContent()),
- save(buffer, mime) {
- note.mime = mime;
- note.save();
- note.setContent(buffer, { forceSave: true });
+ blobId: () => note.blobId,
+ save(buffer, mime, sourceBlobId) {
+ const current = becca.getNote(note.noteId);
+
+ if (!current || current.blobId !== sourceBlobId) {
+ return false;
+ }
+
+ current.mime = mime;
+ current.save();
+ current.setContent(buffer, { forceSave: true });
+
+ return true;
}
};
}
function attachmentTarget(attachment: BAttachment): CompressionTarget {
+ const attachmentId = attachment.attachmentId ?? "";
+
return {
entityType: "attachment",
- entityId: attachment.attachmentId ?? "",
+ entityId: attachmentId,
title: attachment.title,
mime: attachment.mime,
skip: resolveAttachmentSkip(attachment),
getContent: () => wrapStringOrBuffer(attachment.getContent()),
- save(buffer, mime) {
- attachment.mime = mime;
- attachment.setContent(buffer, { forceSave: true });
+ blobId: () => attachment.blobId,
+ // Written through a freshly read attachment rather than the one collected at the start of
+ // the run: that one is a detached copy of its row, and `forceSave` writes the whole row
+ // back, which would undo a title or position changed since — a subtree run is long.
+ save(buffer, mime, sourceBlobId) {
+ const current = becca.getAttachment(attachmentId);
+
+ if (!current || current.blobId !== sourceBlobId) {
+ return false;
+ }
+
+ current.mime = mime;
+ current.setContent(buffer, { forceSave: true });
+
+ return true;
}
};
}
@@ -280,6 +310,8 @@ async function compressTarget(target: CompressionTarget, request: ImageCompressi
try {
content = target.getContent();
+ // Read in the same turn as the content itself, so it names exactly the bytes just read.
+ const sourceBlobId = target.blobId();
if (target.skip) {
return skipped(content.byteLength, target.skip);
@@ -292,8 +324,19 @@ async function compressTarget(target: CompressionTarget, request: ImageCompressi
}
// The compression itself is asynchronous, so the write is a separate transaction of its
- // own rather than one held open across it.
- getSql().transactional(() => target.save(outcome.buffer, outcome.format.mime));
+ // 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));
+
+ if (!saved) {
+ getLog().info(
+ `Left ${target.entityType} '${target.entityId}' alone: its content changed while it was being compressed.`
+ );
+
+ return skipped(content.byteLength, "changed");
+ }
getLog().info(
`Compressed ${target.entityType} '${target.entityId}' from ${content.byteLength} to ${outcome.buffer.byteLength} bytes.`