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
client/image compression tool: fix several issues
Adorian Doran12524a98ee42
diff --git a/apps/server/src/services/image_worker_pool.spec.ts b/apps/server/src/services/image_worker_pool.spec.tsindex 04cfe81bbd..4a5d6e3b13 100644--- a/apps/server/src/services/image_worker_pool.spec.ts+++ b/apps/server/src/services/image_worker_pool.spec.ts@@ -150,6 +150,75 @@ describe("worker pool failure semantics", () => {expect(h.forked).toHaveLength(1);});+ /**+ * What happens to the images queued behind a worker, which is where the pool can do real harm.+ *+ * A caller queues only when every worker is busy, and is then past the point where it could+ * have started one for itself: from there it is answered by the pool or not at all. Not at all+ * is not a slow answer but a permanent one — an import creates each note empty and fills it in+ * when its compression returns, so a promise that never settles is a note left at zero bytes.+ */+ describe("images queued behind a busy pool", () => {+ /** Fills the pool and queues `count` more images behind it. */+ async function queueBehind(pool: typeof import("./image_worker_pool.js"), count: number) {+ h.cores = 1;++ const running = pool.compressInWorker(BYTES, REQUEST, 1024);++ await flush();++ const queued = Array.from({ length: count }, () => pool.compressInWorker(BYTES, REQUEST, 1024));++ await flush();+ // One process for all of them: the rest are waiting on it, not on one of their own.+ expect(h.forked).toHaveLength(1);++ return { running, queued };+ }++ it("answers all of them when workers are given up on, rather than leaving them waiting", async () => {+ const pool = await import("./image_worker_pool.js");+ const { running, queued } = await queueBehind(pool, 3);++ // Dead before it ever spoke, so this installation is taken to have no workers at all.+ // The one being run is answered by its own call; the queued ones are answered by+ // nothing unless giving up says so.+ h.forked[0].emit("exit", 127, null);++ await expect(running).resolves.toBeNull();+ await expect(Promise.all(queued)).resolves.toEqual([ null, null, null ]);+ });++ it("starts a replacement for one that dies, so the queue behind it moves", async () => {+ const pool = await import("./image_worker_pool.js");+ const { running, queued } = await queueBehind(pool, 1);+ const worker = h.forked[0];++ worker.emit("message", { trace: "worker 4000: loaded and listening" });+ await flush();+ // Taken down by the image it was given, having already proven workers run here.+ worker.emit("exit", 1, null);+ await expect(running).rejects.toThrow("exited with code 1");+ await flush();++ // The capacity it held is free again, and the image queued for it gets a process rather+ // than a wait with nothing left to end it.+ expect(h.forked).toHaveLength(2);++ const replacement = h.forked[1];++ replacement.emit("message", { trace: "worker 4001: loaded and listening" });+ await flush();+ replacement.emit("message", {+ id: (replacement.sent[0] as { id: number }).id,+ outcome: { compressed: false, reason: "no-gain" },+ logs: []+ });++ await expect(queued[0]).resolves.toMatchObject({ compressed: false, reason: "no-gain" });+ });+ });+it("sizes the pool to the machine's memory as well as its cores", async () => {const pool = await import("./image_worker_pool.js");diff --git a/apps/server/src/services/image_worker_pool.ts b/apps/server/src/services/image_worker_pool.tsindex 79b0233d15..b9f89c2355 100644--- a/apps/server/src/services/image_worker_pool.ts+++ b/apps/server/src/services/image_worker_pool.ts@@ -267,7 +267,32 @@ function retire(worker: PooledWorker) {started--;worker.stopped = true;worker.worker.kill();- waiting.shift()?.(null);++ const next = waiting.shift();++ if (!next) {+ return;+ }++ // The capacity this worker held is free again, and whoever is queued for it is already past+ // the point where they could have started one for themselves — they queued because the pool+ // was full, and it no longer is. Starting the replacement here is what keeps the queue moving;+ // without it a pool whose workers all died would leave everyone behind them waiting on a+ // release that can no longer come.+ //+ // Only where workers are known to run, though. If none has ever spoken, another is not going+ // to either, and starting one would make this caller wait out a second process failing to come+ // up before hearing the same answer it can be given now.+ const replacement = everSpoke ? spawn() : null;++ if (replacement) {+ started++;+ next(replacement);+ } else {+ // Nothing can be started, which `spawn` has already answered for by disabling workers+ // outright — and that answers everyone else. This one was taken off the queue first.+ next(null);+ }}/**@@ -399,9 +424,24 @@ function disable(reason: string): null {`Image Compression Tool: compressing in this process because ${reason}.`);}+ // Everyone still queued is answered, not left holding a promise for a worker that is now never+ // coming. Nothing else would ever answer them — the queue is drained by workers coming free,+ // and there are to be no more workers — so without this they wait for the life of the process,+ // and whoever is awaiting them waits with them. An image whose compression never returns is an+ // image that is never written: the note is created empty and filled in when the compression+ // answers, so a promise that never settles is a note left at nothing.+ answerEveryoneWaiting();+return null;}+/** Tells every queued caller there is no worker for it, so each one compresses its own image. */+function answerEveryoneWaiting() {+ while (waiting.length > 0) {+ waiting.shift()?.(null);+ }+}+function send(worker: PooledWorker,buffer: Uint8Array,diff --git a/apps/server/src/services/image_write_barrier.spec.ts b/apps/server/src/services/image_write_barrier.spec.tsnew file mode 100644index 0000000000..19d1e7a601--- /dev/null+++ b/apps/server/src/services/image_write_barrier.spec.ts@@ -0,0 +1,70 @@+import { becca, cls, getSql, imageService, options } from "@triliumnext/core";+import { awaitPendingImageWrites } from "@triliumnext/core/src/services/image.js";+import { CoreApiTester } from "@triliumnext/core/src/test/api_tester.js";+import { Jimp } from "jimp";+import { beforeAll, describe, expect, it } from "vitest";++/**+ * What "the import has finished" is worth.+ *+ * An image note is created at once and empty, and filled in when the compression it was handed to+ * answers — which is what stops an upload blocking on a decode. Between the two the note exists+ * holding nothing, and for a few hundred images that gap is minutes long. An import that reports+ * success in the middle of it is reporting something untrue, and a process stopped there leaves+ * those notes empty for good, since nothing anywhere records that they are owed anything.+ *+ * So the debt is written down as it is incurred, and the barrier below is what an importer waits on.+ */+let photo: Uint8Array;++beforeAll(async () => {+ CoreApiTester.build();++ // Large enough that compressing it is real work rather than something that could finish within+ // the same turn by accident — the gap this is about has to actually be open.+ const image = new Jimp({ width: 900, height: 700, color: 0x3366ccff });++ for (let x = 0; x < 900; x++) {+ for (let y = 0; y < 700; y++) {+ image.setPixelColor((((x * 7919 + y * 104729) & 0xffffff) << 8 | 0xff) >>> 0, x, y);+ }+ }++ photo = new Uint8Array(await image.getBuffer("image/png"));++ cls.init(() => {+ options.setOption("compressImages", "true");+ options.setOption("imageResize", "true");+ options.setOption("imageMaxWidthHeight", "200");+ });+}, 120000);++describe("waiting for the images an import is owed", () => {+ it("holds until every note handed over has its content, however many are in flight", async () => {+ const noteIds = cls.init(() => getSql().transactional(() =>+ // As an import does it: one call per image, none of them awaited, all still going when+ // the last returns.+ Array.from({ length: 12 }, (_, index) =>+ imageService.saveImage("root", photo, `photo${index}.png`, true).noteId)));++ // The notes exist and are empty, which is exactly the state an import used to report as+ // success — and which a restart here would make permanent.+ expect(noteIds).toHaveLength(12);+ expect(sizes(noteIds).filter((size) => size === 0).length).toBeGreaterThan(0);++ await awaitPendingImageWrites();++ // Every one of them stored, and stored smaller: 900x700 against a bound of 200.+ expect(sizes(noteIds).filter((size) => size === 0)).toEqual([]);+ sizes(noteIds).forEach((size) => expect(size).toBeLessThan(photo.byteLength));+ }, 120000);++ it("comes straight back when nothing is owed", async () => {+ await awaitPendingImageWrites();+ await expect(awaitPendingImageWrites()).resolves.toBeUndefined();+ });+});++function sizes(noteIds: string[]): number[] {+ return cls.init(() => noteIds.map((noteId) => becca.getNoteOrThrow(noteId).getContent().length));+}diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.tsindex b02b8eb7a2..9cff4e87af 100644--- a/packages/trilium-core/src/routes/api/attachments.spec.ts+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts@@ -171,6 +171,15 @@ describe("Attachments API (core)", () => {expect(res.status).toBe(200);expect(res.body.uploaded).toBe(true);expect(res.body.url).toContain("/image/");++ // The URL it just handed back has to be fetchable *now*. The editor puts it straight+ // into the document as an image source and the browser asks for it immediately, so an+ // upload that answers before the bytes are stored draws a broken image — the picture+ // shows for a moment from the local copy and is then replaced by nothing.+ const fetched = await api.get(`/${res.body.url}`);++ expect(fetched.status).toBe(200);+ expect((fetched.body as Uint8Array).length).toBeGreaterThan(0);});it("reports a missing upload when no file is present", async () => {diff --git a/packages/trilium-core/src/routes/api/attachments.ts b/packages/trilium-core/src/routes/api/attachments.tsindex 1bd926ed88..f2808d94d8 100644--- a/packages/trilium-core/src/routes/api/attachments.ts+++ b/packages/trilium-core/src/routes/api/attachments.ts@@ -47,7 +47,7 @@ function saveAttachment(req: Request<{ noteId: string }>) {note.saveAttachment({ attachmentId, role, mime, title, content }, matchBy);}-function uploadAttachment(req: FileRequest<{ noteId: string }>) {+async function uploadAttachment(req: FileRequest<{ noteId: string }>) {const { noteId } = req.params;const { file } = req;@@ -66,6 +66,13 @@ function uploadAttachment(req: FileRequest<{ noteId: string }>) {if (["image/png", "image/jpg", "image/jpeg", "image/gif", "image/webp", "image/svg+xml"].includes(file.mimetype)) {const attachment = imageService.saveImageToAttachment(noteId, buffer, file.originalname, true, true);++ // The URL below is fetched the moment this answers — the editor puts it straight into the+ // document as the source of an image. Answering before the bytes are stored hands it the+ // address of an empty attachment, which draws as a broken image and stays broken until+ // something reloads the note. So this one image is waited for; nothing else is.+ await imageService.awaitImageWrite(attachment.attachmentId);+url = `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}`;} else {const attachment = note.saveAttachment({diff --git a/packages/trilium-core/src/routes/api/image.ts b/packages/trilium-core/src/routes/api/image.tsindex 9309f5b82b..75f877c36c 100644--- a/packages/trilium-core/src/routes/api/image.ts+++ b/packages/trilium-core/src/routes/api/image.ts@@ -111,7 +111,7 @@ function returnAttachedImage(req: Request<{ attachmentId: string }>, res: Respon}}-function updateImage(req: FileRequest<{ noteId: string }>) {+async function updateImage(req: FileRequest<{ noteId: string }>) {const { noteId } = req.params;const { file } = req;@@ -140,6 +140,10 @@ function updateImage(req: FileRequest<{ noteId: string }>) {imageService.updateImage(noteId, file.buffer, file.originalname);+ // The client re-requests the image as soon as this answers, to show what it just uploaded.+ // Answering first would have it fetch the note's old content, or nothing at all.+ await imageService.awaitImageWrite(noteId);+return { uploaded: true };}diff --git a/packages/trilium-core/src/routes/api/import.ts b/packages/trilium-core/src/routes/api/import.tsindex 5b54f431ca..859a90dc70 100644--- a/packages/trilium-core/src/routes/api/import.ts+++ b/packages/trilium-core/src/routes/api/import.ts@@ -9,6 +9,7 @@ import becca_loader from "../../becca/becca_loader.js";import type BNote from "../../becca/entities/bnote.js";import { ValidationError } from "../../errors.js";import * as cls from "../../services/context.js";+import { awaitPendingImageWrites } from "../../services/image.js";import importFile from "../../services/import/dispatch.js";import singleImportService from "../../services/import/single.js";import { getLog } from "../../services/log.js";@@ -88,7 +89,7 @@ async function importNotesToBranch(req: ImportRequest<{ parentNoteId: string }>)return note.getPojo();}-function importAttachmentsToNote(req: ImportRequest<{ parentNoteId: string }>) {+async function importAttachmentsToNote(req: ImportRequest<{ parentNoteId: string }>) {const { parentNoteId } = req.params;const { taskId, last } = req.body;@@ -109,6 +110,11 @@ function importAttachmentsToNote(req: ImportRequest<{ parentNoteId: string }>) {try {singleImportService.importAttachment(taskContext, file, parentNote);+ // An imported image is stored once its compression answers, which is after the call above+ // has returned. Waited out for the same reason the note import waits: what is reported as+ // finished should be finished. (This path does not go through the import dispatcher, which+ // is where every other importer is waited on.)+ await awaitPendingImageWrites();} catch (e: unknown) {const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex d349e60fdb..57a7d60f47 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -130,7 +130,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutroute(GET, "/api/revisions/:revisionId/image/:filename", [checkApiAuthOrElectron], imageRoute.returnImageFromRevision);route(GET, "/api/attachments/:attachmentId/image/:filename", [checkApiAuthOrElectron], imageRoute.returnAttachedImage);route(GET, "/api/images/:noteId/:filename", [checkApiAuthOrElectron], imageRoute.returnImageFromNote);- route(PUT, "/api/images/:noteId", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], imageRoute.updateImage, apiResultHandler);+ asyncRoute(PUT, "/api/images/:noteId", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], imageRoute.updateImage, apiResultHandler);// Readings rather than runs: headers only, so they are cheap enough to open a dialog with.apiRoute(GET, "/api/notes/:noteId/image-info", imageRoute.getNoteImageInfo);apiRoute(GET, "/api/attachments/:attachmentId/image-info", imageRoute.getAttachmentImageInfo);@@ -140,7 +140,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutasyncApiRoute(PST, "/api/notes/:noteId/compress-images", imageRoute.compressNoteImages);apiRoute(PST, "/api/image-compression/:taskId/cancel", imageRoute.cancelImageCompression);asyncApiRoute(PST, "/api/attachments/:attachmentId/compress-image", imageRoute.compressAttachmentImage);- route(PST, "/api/notes/:noteId/attachments/upload", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], attachmentsApiRoute.uploadAttachment, apiResultHandler);+ asyncRoute(PST, "/api/notes/:noteId/attachments/upload", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], attachmentsApiRoute.uploadAttachment, apiResultHandler);// group of the services below are meant to be executed from the outsideroute(GET, "/api/setup/status", [], setupApiRoute.getStatus, apiResultHandler);@@ -163,7 +163,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout//#region Import/exportasyncRoute(PST, "/api/notes/:parentNoteId/notes-import", [checkApiAuthOrElectron, importMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importNotesToBranch, apiResultHandler);- route(PST, "/api/notes/:parentNoteId/attachments-import", [checkApiAuthOrElectron, importMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importAttachmentsToNote, apiResultHandler);+ asyncRoute(PST, "/api/notes/:parentNoteId/attachments-import", [checkApiAuthOrElectron, importMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importAttachmentsToNote, apiResultHandler);asyncRoute(GET, "/api/branches/:branchId/export/:type/:format/:taskId", [checkApiAuthOrElectron], exportRoute.exportBranch);//#endregiondiff --git a/packages/trilium-core/src/services/image.ts b/packages/trilium-core/src/services/image.tsindex e513c44598..1560d78522 100644--- a/packages/trilium-core/src/services/image.ts+++ b/packages/trilium-core/src/services/image.ts@@ -19,6 +19,83 @@ function getImageMimeFromExtension(ext: string): string {return `image/${ext === "svg" ? "svg+xml" : ext}`;}+/**+ * Image content that has been promised but not yet stored.+ *+ * Every function below writes its image in two steps: the note or attachment is created at once,+ * empty, and filled in when the compression it was handed to answers. That is what keeps an upload+ * from blocking on a decode — but between the two the entity exists holding nothing, and nothing+ * anywhere records that it is owed anything. An import of hundreds is minutes of that, and a+ * process stopped in the middle of it leaves those entities empty for good.+ *+ * So the debt is written down. {@link awaitPendingImageWrites} is what a caller waits on before+ * saying it is finished.+ */+const pendingWrites = new Set<PendingImageWrite>();++interface PendingImageWrite {+ /** The note or attachment the content is owed to, so one image can be waited for on its own. */+ entityId: string;+ stored: Promise<void>;+}++/**+ * Records one image write, and swallows its failure.+ *+ * Swallowed here rather than left to reject: the write is nobody's promise, so a rejection is an+ * unhandled one — and it would take the barrier down with it, turning one image that could not be+ * stored into an import reported as failed. The entity keeps the empty content it was created+ * with, which is what it would have had anyway, and the reason is in the log.+ */+function trackWrite(write: Promise<unknown>, entityId: string, describe: string) {+ const stored = write+ .then(() => {}, (e: unknown) => {+ getLog().error(`Failed to store image ${describe}: ${(e as Error)?.stack ?? e}`);+ })+ .finally(() => pendingWrites.delete(entry));+ const entry: PendingImageWrite = { entityId, stored };++ pendingWrites.add(entry);+}++/**+ * Waits until every image handed over so far has been stored.+ *+ * Drained rather than sampled: compressing one image can start another — an importer creates its+ * notes as it reads them — and a write begun while this was waiting on the last batch is still one+ * the caller owes. It ends when there is nothing left outstanding, which for a bounded piece of+ * work like an import is when that work is genuinely done. (A caller with an unbounded supply of+ * images would never see the set empty, which is why this is for imports and not for, say, a+ * long-lived request loop.)+ */+export async function awaitPendingImageWrites(): Promise<void> {+ while (pendingWrites.size > 0) {+ // Safe to await as a group: none of these can reject, see above.+ await Promise.all([ ...pendingWrites ].map((entry) => entry.stored));+ }+}++/**+ * Waits for the content of one image, and only that one.+ *+ * For the caller that hands a client a URL and expects it to be fetched immediately — a picture+ * pasted into the editor is requested by the browser the moment the upload answers, and an answer+ * that arrives before the bytes do is an answer to an empty attachment. That is a broken image in+ * the document, and it stays broken until something reloads it.+ *+ * One image rather than all of them, unlike {@link awaitPendingImageWrites}: a paste has no reason+ * to wait out an import that happens to be running, and would be waiting minutes if it did.+ */+export async function awaitImageWrite(entityId: string | undefined): Promise<void> {+ if (!entityId) {+ return;+ }++ await Promise.all([ ...pendingWrites ]+ .filter((entry) => entry.entityId === entityId)+ .map((entry) => entry.stored));+}+function updateImage(noteId: string, uploadBuffer: Uint8Array, originalName: string): void {getLog().info(`Updating image ${noteId}: ${originalName}`);@@ -33,7 +110,7 @@ function updateImage(noteId: string, uploadBuffer: Uint8Array, originalName: strnote.setLabel("originalFileName", originalName);// Process image asynchronously- getImageProvider().processImage(uploadBuffer, originalName, true).then(({ buffer, format }) => {+ trackWrite(getImageProvider().processImage(uploadBuffer, originalName, true).then(({ buffer, format }) => {getContext().init(() => {getSql().transactional(() => {note.mime = getImageMimeFromExtension(format.ext);@@ -41,7 +118,7 @@ function updateImage(noteId: string, uploadBuffer: Uint8Array, originalName: strnote.setContent(buffer);});});- });+ }), noteId, `note '${noteId}'`);}function saveImage(@@ -75,7 +152,7 @@ function saveImage(note.addLabel("originalFileName", originalName);// Process image asynchronously- getImageProvider().processImage(uploadBuffer, originalName, shrinkImageSwitch).then(({ buffer, format }) => {+ trackWrite(getImageProvider().processImage(uploadBuffer, originalName, shrinkImageSwitch).then(({ buffer, format }) => {getContext().init(() => {getSql().transactional(() => {note.mime = getImageMimeFromExtension(format.ext);@@ -89,7 +166,7 @@ function saveImage(note.setContent(buffer, { forceSave: true });});});- });+ }), note.noteId, `note '${note.noteId}'`);return {fileName,@@ -133,7 +210,7 @@ function saveImageToAttachment(// Process image asynchronouslyconst attachmentId = attachment.attachmentId;- getImageProvider().processImage(uploadBuffer, originalName, !!shrinkImageSwitch).then(({ buffer, format }) => {+ trackWrite(getImageProvider().processImage(uploadBuffer, originalName, !!shrinkImageSwitch).then(({ buffer, format }) => {getContext().init(() => {getSql().transactional(() => {if (!attachmentId) {@@ -151,12 +228,14 @@ function saveImageToAttachment(attachment.setContent(buffer, { forceSave: true });});});- });+ }), attachmentId ?? "", `attachment '${attachmentId}'`);return attachment;}export default {+ awaitImageWrite,+ awaitPendingImageWrites,saveImage,saveImageToAttachment,updateImagediff --git a/packages/trilium-core/src/services/import/dispatch.ts b/packages/trilium-core/src/services/import/dispatch.tsindex 1ff395a9a4..c3a52ba8ef 100644--- a/packages/trilium-core/src/services/import/dispatch.ts+++ b/packages/trilium-core/src/services/import/dispatch.ts@@ -1,4 +1,5 @@import type BNote from "../../becca/entities/bnote.js";+import { awaitPendingImageWrites } from "../image.js";import type TaskContext from "../task_context.js";import { extname } from "../utils/path.js";import type { ZipSource } from "../zip_provider.js";@@ -35,6 +36,23 @@ export interface ImportOptions {* `file.buffer` for the browser/WASM upload that has no temp file.*/export default async function importFile(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote, options: ImportOptions, format?: string): Promise<BNote | (string | number)[] | null> {+ const imported = await routeToImporter(taskContext, file, parentNote, options, format);++ // An image note is created empty and filled in when the compression it was handed to answers,+ // so an importer that has returned is not an import that has finished: its pictures may still+ // be on their way. Waited out here, in the one place every importer passes through, so that an+ // import reported as done is one the user can close the lid on — rather than one whose notes+ // fill in over the following minutes, and stay empty for good if the process stops first.+ //+ // Nothing is serialised by this. The images were all handed over as the notes were made and+ // have been compressing throughout; this only declines to call the import finished while any+ // of them is outstanding.+ await awaitPendingImageWrites();++ return imported;+}++async function routeToImporter(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote, options: ImportOptions, format?: string): Promise<BNote | (string | number)[] | null> {const extension = extname(file.originalname).toLowerCase();// Every zip-reading importer (generic + the tagged providers) reads the archive straight from the temp