Skip to content

Build your personal knowledge base with Trilium Notes

fix(core): don't demand a note that an image upload may outlive (closes #10823)

Elian Doran1812e26b6e67
diff --git a/packages/trilium-core/src/services/image.spec.ts b/packages/trilium-core/src/services/image.spec.ts
index e82f804561..e1efc71490 100644
--- a/packages/trilium-core/src/services/image.spec.ts
+++ b/packages/trilium-core/src/services/image.spec.ts
@@ -6,6 +6,7 @@ import { getContext } from "./context.js";
import imageService from "./image.js";
import { getImageProvider } from "./image_provider.js";
import type { ProcessedImage } from "./image_provider.js";
+import noteService from "./notes.js";
import protectedSessionService from "./protected_session.js";
/**
@@ -164,6 +165,68 @@ describe("image service (real DB)", () => {
).toThrow();
});
+ it("post-processes the note five seconds later, and lets it go quietly once deleted", () => {
+ const postProcessSpy = vi.spyOn(noteService, "asyncPostProcessContent").mockResolvedValue(undefined);
+ stubProcessImage({ ext: "png" });
+ vi.useFakeTimers();
+
+ try {
+ const survivor = createTargetNote();
+ getContext().init(() =>
+ imageService.saveImageToAttachment(survivor.noteId, fakeBuffer, "kept.png", false)
+ );
+
+ const doomed = createTargetNote();
+ getContext().init(() =>
+ imageService.saveImageToAttachment(doomed.noteId, fakeBuffer, "raced.png", false)
+ );
+ // The window is wide enough to lose the note to a delete — the user's own, or one
+ // arriving over sync — which is what made this a routine crash rather than a rare one.
+ getContext().init(() => doomed.deleteNote());
+
+ expect(() => vi.advanceTimersByTime(5000)).not.toThrow();
+
+ // The surviving note is still post-processed, so the guard skips the deleted note only.
+ expect(postProcessSpy).toHaveBeenCalledTimes(1);
+ expect(postProcessSpy.mock.calls[0][0].noteId).toBe(survivor.noteId);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("drops the processed image when its attachment no longer exists", async () => {
+ const host = createTargetNote();
+ let resolveProcessing: ((processed: ProcessedImage) => void) | undefined;
+ vi.spyOn(getImageProvider(), "processImage").mockReturnValue(
+ new Promise<ProcessedImage>((resolve) => { resolveProcessing = resolve; })
+ );
+
+ const att = getContext().init(() =>
+ imageService.saveImageToAttachment(host.noteId, fakeBuffer, "outlived.png", false)
+ );
+
+ // Nothing awaits the processing chain, so a throw inside it never reaches an assertion — it
+ // escapes as an unhandled rejection, which Node promotes to the same fatal uncaught
+ // exception. Watch for it directly, or this test would pass with the guard removed.
+ const rejections: unknown[] = [];
+ const captureRejection = (reason: unknown) => rejections.push(reason);
+ process.on("unhandledRejection", captureRejection);
+
+ try {
+ // Deleting the note marks its attachments deleted, so the in-flight processing resolves
+ // with nowhere to write its result.
+ getContext().init(() => host.deleteNote());
+ resolveProcessing?.({ buffer: fakeBuffer, format: { ext: "png", mime: "image/png" } });
+ await flushAsync();
+ } finally {
+ process.off("unhandledRejection", captureRejection);
+ }
+
+ // The attachment really is gone, so the guard — not a lucky lookup — is what was exercised.
+ expect(becca.getAttachment(att.attachmentId ?? "")).toBeFalsy();
+ expect(rejections).toEqual([]);
+ });
+
it("updates the attachment mime/content and appends a missing extension asynchronously", async () => {
const host = createTargetNote();
stubProcessImage({ ext: "jpg" });
diff --git a/packages/trilium-core/src/services/image.ts b/packages/trilium-core/src/services/image.ts
index 1560d78522..f9a910f774 100644
--- a/packages/trilium-core/src/services/image.ts
+++ b/packages/trilium-core/src/services/image.ts
@@ -192,7 +192,7 @@ function saveImageToAttachment(
const fileName = sanitizeFilename(originalName);
const note = becca.getNoteOrThrow(noteId);
- let attachment = note.saveAttachment({
+ const attachment = note.saveAttachment({
role: "image",
mime: "unknown",
title: fileName
@@ -202,7 +202,18 @@ function saveImageToAttachment(
setTimeout(() => {
getContext().init(() => {
getSql().transactional(() => {
- const note = becca.getNoteOrThrow(noteId);
+ // Looked up again rather than captured, and without asserting it is still there: five
+ // seconds is ample time for the note to be deleted, whether by the user or by an incoming
+ // sync change, and a note that no longer exists simply has nothing left to post-process.
+ // Demanding it exist turned that ordinary race into a process-level throw, which — coming
+ // from a timer, with no request to fail and no caller to catch it — took the whole
+ // application down (#10823).
+ const note = becca.getNote(noteId);
+
+ if (!note) {
+ return;
+ }
+
noteService.asyncPostProcessContent(note, note.getContent());
});
});
@@ -216,16 +227,25 @@ function saveImageToAttachment(
if (!attachmentId) {
throw new Error("Missing attachment ID.");
}
- attachment = becca.getAttachmentOrThrow(attachmentId);
- attachment.mime = getImageMimeFromExtension(format.ext);
+ // Deleting a note marks its attachments deleted too, and image processing can easily
+ // outlast the note it belongs to — in which case there is nothing left to write the
+ // result into. Same race as the post-processing timer above; here it would surface as an
+ // unhandled rejection instead of a throw.
+ const savedAttachment = becca.getAttachment(attachmentId);
+
+ if (!savedAttachment) {
+ return;
+ }
+
+ savedAttachment.mime = getImageMimeFromExtension(format.ext);
if (!originalName.includes(".")) {
originalName += `.${format.ext}`;
- attachment.title = sanitizeFilename(originalName);
+ savedAttachment.title = sanitizeFilename(originalName);
}
- attachment.setContent(buffer, { forceSave: true });
+ savedAttachment.setContent(buffer, { forceSave: true });
});
});
}), attachmentId ?? "", `attachment '${attachmentId}'`);