From 2c84b2100fbe8aba2c78edf68dad6dc4a60802d2 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 24 Nov 2026 19:51:15 -0500 Subject: [PATCH] fix: Stream attachments in document exports and stop on disconnect (#14697) * fix: Stream attachments in single document exports and stop on disconnect Single document and revision exports read every attachment into memory before building the zip, and kept running after the client had gone. Repeated exports of a document with large attachments ran web dynos out of memory. - Stream attachments into the zip with a shared AttachmentHelper.addToArchive - Abort export work when the client connection closes - Read only images that will be inlined, with a 1MB total inline limit * fix: Destroy streams opened after abort, treat missing local files as absent --- .../models/helpers/AttachmentHelper.test.ts | 114 +++++++++++++++++ server/models/helpers/AttachmentHelper.ts | 70 ++++++++++- server/models/helpers/HTMLHelper.test.ts | 23 ++++ server/models/helpers/HTMLHelper.ts | 27 +++- server/queues/tasks/ExportDocumentTreeTask.ts | 14 ++- server/queues/tasks/ExportJSONTask.ts | 3 +- server/queues/tasks/ExportTask.ts | 45 ------- server/routes/api/documents/documents.test.ts | 115 +++++++++++++++++- server/routes/api/documents/documents.ts | 55 ++++++--- server/routes/api/revisions/revisions.test.ts | 9 +- server/routes/api/revisions/revisions.ts | 15 ++- server/storage/files/LocalStorage.test.ts | 9 ++ server/storage/files/LocalStorage.ts | 5 +- server/test/support.ts | 2 +- server/utils/koa.test.ts | 74 +++++++++++ server/utils/koa.ts | 38 +++++- 16 files changed, 524 insertions(+), 94 deletions(-) create mode 100644 server/utils/koa.test.ts diff --git a/server/models/helpers/AttachmentHelper.test.ts b/server/models/helpers/AttachmentHelper.test.ts index 20e0322f28..7dc356cde5 100644 --- a/server/models/helpers/AttachmentHelper.test.ts +++ b/server/models/helpers/AttachmentHelper.test.ts @@ -1,5 +1,10 @@ +import { Readable } from "node:stream"; +import { ZipFile } from "yazl"; import { AttachmentPreset } from "@shared/types"; import env from "@server/env"; +import FileStorage from "@server/storage/files"; +import { buildAttachment } from "@server/test/factories"; +import ZipHelper from "@server/utils/ZipHelper"; import AttachmentHelper from "./AttachmentHelper"; describe("AttachmentHelper", () => { @@ -67,4 +72,113 @@ describe("AttachmentHelper", () => { expect(key).toEqual("uploads/456/123/test/one.png"); }); }); + + describe("addToArchive", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("should stream the attachment into the archive", async () => { + const attachment = await buildAttachment(); + vi.spyOn(FileStorage, "getFileStream").mockImplementation(async () => + Readable.from([Buffer.from("image-data")]) + ); + vi.spyOn(FileStorage, "getFileBuffer"); + + const zip = new ZipFile(); + const chunks: Buffer[] = []; + zip.outputStream.on("data", (chunk: Buffer) => chunks.push(chunk)); + const finished = new Promise((resolve) => + zip.outputStream.on("end", resolve) + ); + + AttachmentHelper.addToArchive(zip, attachment, "image.png"); + zip.end(); + await finished; + + const entries: Record = {}; + await ZipHelper.walk(Buffer.concat(chunks), async (entry) => { + entries[entry.fileName] = (await entry.readBuffer(1024)).toString(); + }); + + expect(entries).toEqual({ "image.png": "image-data" }); + expect(FileStorage.getFileBuffer).not.toHaveBeenCalled(); + }); + + it("should destroy the storage stream when the signal aborts", async () => { + const attachment = await buildAttachment(); + const stream = new Readable({ read() {} }); + const getFileStream = vi + .spyOn(FileStorage, "getFileStream") + .mockResolvedValue(stream); + + const zip = new ZipFile(); + zip.outputStream.resume(); + const controller = new AbortController(); + + AttachmentHelper.addToArchive( + zip, + attachment, + "image.png", + controller.signal + ); + zip.end(); + await vi.waitFor(() => expect(getFileStream).toHaveBeenCalled()); + await new Promise((resolve) => setImmediate(resolve)); + + controller.abort(); + expect(stream.destroyed).toBe(true); + }); + + it("should destroy the storage stream when the signal aborts while it opens", async () => { + const attachment = await buildAttachment(); + const stream = new Readable({ read() {} }); + const controller = new AbortController(); + vi.spyOn(FileStorage, "getFileStream").mockImplementation(async () => { + controller.abort(); + return stream; + }); + + const zip = new ZipFile(); + const finished = new Promise((resolve) => + zip.outputStream.on("end", resolve) + ); + zip.outputStream.resume(); + + AttachmentHelper.addToArchive( + zip, + attachment, + "image.png", + controller.signal + ); + zip.end(); + await finished; + + expect(stream.destroyed).toBe(true); + }); + + it("should not read from storage when the signal has already aborted", async () => { + const attachment = await buildAttachment(); + const getFileStream = vi.spyOn(FileStorage, "getFileStream"); + + const zip = new ZipFile(); + const finished = new Promise((resolve) => + zip.outputStream.on("end", resolve) + ); + zip.outputStream.resume(); + const controller = new AbortController(); + controller.abort(); + + AttachmentHelper.addToArchive( + zip, + attachment, + "image.png", + controller.signal + ); + zip.end(); + await finished; + + expect(getFileStream).not.toHaveBeenCalled(); + }); + }); }); diff --git a/server/models/helpers/AttachmentHelper.ts b/server/models/helpers/AttachmentHelper.ts index ee073c0d41..4d3834bdbf 100644 --- a/server/models/helpers/AttachmentHelper.ts +++ b/server/models/helpers/AttachmentHelper.ts @@ -1,6 +1,8 @@ +import { Readable } from "node:stream"; import { addHours } from "date-fns"; +import type { ZipFile } from "yazl"; import { AttachmentPreset } from "@shared/types"; -import { errToString } from "@shared/utils/error"; +import { errToString, toError } from "@shared/utils/error"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import type Attachment from "@server/models/Attachment"; @@ -138,4 +140,70 @@ export default class AttachmentHelper { return Buffer.from(""); } } + + /** + * Add an attachment to an archive. The contents are streamed from storage + * when the archive writes the entry, so the file is never held in memory. + * + * A read that fails, or stops part way through, fails the archive, because a + * truncated archive looks complete. An attachment that is missing from + * storage is written as an empty entry, so that one missing file does not + * make the export impossible. + * + * @param zip The archive to add the attachment to. + * @param attachment The attachment to add. + * @param pathInZip The path of the attachment in the archive. + * @param signal An optional signal that stops the read when aborted. + */ + static addToArchive( + zip: ZipFile, + attachment: Attachment, + pathInZip: string, + signal?: AbortSignal + ) { + zip.addReadStreamLazy( + pathInZip, + { mtime: attachment.updatedAt }, + (callback) => { + if (signal?.aborted) { + return callback(null, Readable.from([])); + } + + attachment.stream.then( + (stream) => { + if (!stream) { + Logger.warn(`Attachment is missing from storage`, { + attachmentId: attachment.id, + teamId: attachment.teamId, + }); + return callback(null, Readable.from([])); + } + + // The client can disconnect while the stream is being opened. + if (signal?.aborted) { + if (stream instanceof Readable) { + stream.destroy(); + } + return callback(null, Readable.from([])); + } + + // yazl ignores errors on input streams, so forward them to fail the + // archive; otherwise the entry never ends and the output hangs open. + stream.on("error", (err) => zip.emit("error", toError(err))); + + if (signal && stream instanceof Readable) { + const handleAbort = () => stream.destroy(); + signal.addEventListener("abort", handleAbort, { once: true }); + stream.once("close", () => + signal.removeEventListener("abort", handleAbort) + ); + } + + return callback(null, stream); + }, + (err) => callback(toError(err), Readable.from([])) + ); + } + ); + } } diff --git a/server/models/helpers/HTMLHelper.test.ts b/server/models/helpers/HTMLHelper.test.ts index 6cef09666d..3838173944 100644 --- a/server/models/helpers/HTMLHelper.test.ts +++ b/server/models/helpers/HTMLHelper.test.ts @@ -78,6 +78,29 @@ describe("HTMLHelper", () => { expect(result).toBeNull(); }); + it("should not inline images past the total size limit", () => { + const html = `

`; + + expect( + HTMLHelper.inlineImage( + html, + redirectUrl, + "image/png", + buffer, + HTMLHelper.maxTotalInlineImageSize - buffer.length + ) + ).not.toBeNull(); + expect( + HTMLHelper.inlineImage( + html, + redirectUrl, + "image/png", + buffer, + HTMLHelper.maxTotalInlineImageSize - buffer.length + 1 + ) + ).toBeNull(); + }); + it("should not inline an empty buffer", () => { const html = `

`; const result = HTMLHelper.inlineImage( diff --git a/server/models/helpers/HTMLHelper.ts b/server/models/helpers/HTMLHelper.ts index a2ecae7578..86a31709b2 100644 --- a/server/models/helpers/HTMLHelper.ts +++ b/server/models/helpers/HTMLHelper.ts @@ -12,6 +12,12 @@ export default class HTMLHelper { */ public static readonly maxInlineImageSize = 100 * 1024; + /** + * The maximum total size, in bytes, of the images inlined into one exported + * HTML document. Images after this limit are kept as external files. + */ + public static readonly maxTotalInlineImageSize = 1024 * 1024; + /** * Inline a small image into exported HTML as a base64 data URI in place of * its redirect URL. Images are only inlined when they are small and @@ -22,16 +28,25 @@ export default class HTMLHelper { * @param redirectUrl The redirect URL of the image within the HTML. * @param contentType The content type of the image, e.g. "image/png". * @param buffer The contents of the image. + * @param inlinedSize The total size, in bytes, of the images already inlined + * into this document. * @returns The updated HTML if the image was inlined, otherwise null. */ public static inlineImage( html: string, redirectUrl: string, contentType: string | null | undefined, - buffer: Buffer + buffer: Buffer, + inlinedSize = 0 ): string | null { if ( - !HTMLHelper.canInlineImage(html, redirectUrl, contentType, buffer.length) + !HTMLHelper.canInlineImage( + html, + redirectUrl, + contentType, + buffer.length, + inlinedSize + ) ) { return null; } @@ -51,13 +66,16 @@ export default class HTMLHelper { * @param redirectUrl The redirect URL of the image within the HTML. * @param contentType The content type of the image, e.g. "image/png". * @param size The size of the image in bytes. + * @param inlinedSize The total size, in bytes, of the images already inlined + * into this document. * @returns True if the image is a candidate for inlining. */ public static canInlineImage( html: string, redirectUrl: string, contentType: string | null | undefined, - size: number + size: number, + inlinedSize = 0 ): boolean { if (!contentType?.startsWith("image/")) { return false; @@ -65,6 +83,9 @@ export default class HTMLHelper { if (size === 0 || size > HTMLHelper.maxInlineImageSize) { return false; } + if (inlinedSize + size > HTMLHelper.maxTotalInlineImageSize) { + return false; + } const pattern = new RegExp(escapeRegExp(redirectUrl), "g"); return (html.match(pattern)?.length ?? 0) === 1; diff --git a/server/queues/tasks/ExportDocumentTreeTask.ts b/server/queues/tasks/ExportDocumentTreeTask.ts index 04c584e13e..5d9d75be5f 100644 --- a/server/queues/tasks/ExportDocumentTreeTask.ts +++ b/server/queues/tasks/ExportDocumentTreeTask.ts @@ -9,6 +9,7 @@ import type { Collection } from "@server/models"; import Attachment from "@server/models/Attachment"; import Document from "@server/models/Document"; import Team from "@server/models/Team"; +import AttachmentHelper from "@server/models/helpers/AttachmentHelper"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import HTMLHelper from "@server/models/helpers/HTMLHelper"; import OKFHelper from "@server/models/helpers/OKFHelper"; @@ -108,6 +109,7 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { ? path.join(pathInZip, TextBundleHelper.textFileName) : pathInZip; const usedAssetNames = new Set(); + let inlinedSize = 0; // Add any referenced attachments to the zip file and replace the // reference in the document with the path to the attachment in the zip @@ -140,7 +142,9 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { text, attachment.redirectUrl, attachment.contentType, - attachment.size + // BIGINT columns are returned as strings. + Number(attachment.size), + inlinedSize ) ) { let buffer: Buffer | undefined; @@ -159,11 +163,13 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { text, attachment.redirectUrl, attachment.contentType, - buffer + buffer, + inlinedSize ) : null; - if (inlined !== null) { + if (buffer && inlined !== null) { text = inlined; + inlinedSize += buffer.length; continue; } } @@ -174,7 +180,7 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { ? TextBundleHelper.assetPath(attachment.name, usedAssetNames) : attachment.key; - this.addAttachmentToArchive( + AttachmentHelper.addToArchive( zip, attachment, isTextBundle diff --git a/server/queues/tasks/ExportJSONTask.ts b/server/queues/tasks/ExportJSONTask.ts index 443d717303..8fecd094ae 100644 --- a/server/queues/tasks/ExportJSONTask.ts +++ b/server/queues/tasks/ExportJSONTask.ts @@ -4,6 +4,7 @@ import type { NavigationNode } from "@shared/types"; import env from "@server/env"; import type { Collection, FileOperation } from "@server/models"; import { Attachment, Document } from "@server/models"; +import AttachmentHelper from "@server/models/helpers/AttachmentHelper"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import { presentAttachment, presentCollection } from "@server/presenters"; @@ -87,7 +88,7 @@ export default class ExportJSONTask extends ExportTask { const addAttachments = (attachments: Attachment[]) => { for (const attachment of attachments) { - this.addAttachmentToArchive(zip, attachment, attachment.key); + AttachmentHelper.addToArchive(zip, attachment, attachment.key); output.attachments[attachment.id] = { ...omit(presentAttachment(attachment), "url"), diff --git a/server/queues/tasks/ExportTask.ts b/server/queues/tasks/ExportTask.ts index 7c130a33c4..7322d63b0d 100644 --- a/server/queues/tasks/ExportTask.ts +++ b/server/queues/tasks/ExportTask.ts @@ -1,9 +1,7 @@ -import { Readable } from "node:stream"; import fs from "fs-extra"; import { truncate } from "es-toolkit/compat"; import { Op } from "sequelize"; import type { WhereOptions } from "sequelize"; -import type { ZipFile } from "yazl"; import { toError } from "@shared/utils/error"; import type { NavigationNode } from "@shared/types"; import { FileOperationState, NotificationEventType } from "@shared/types"; @@ -215,49 +213,6 @@ export default abstract class ExportTask extends BaseTask { includeAttachments: boolean ): Promise; - /** - * Add an attachment to the archive, streaming its contents from storage as - * the archive is written so that the file is never held in memory whole. - * - * A read that fails, or is interrupted part way through, fails the export — - * a silently truncated archive is worse than none, as it looks complete. - * An attachment that is simply absent from storage is written as an empty - * entry, since a row outliving its file must not make export impossible. - * - * @param zip The archive to add the attachment to - * @param attachment The attachment to add - * @param pathInZip The path to store the attachment at within the archive - */ - protected addAttachmentToArchive( - zip: ZipFile, - attachment: Attachment, - pathInZip: string - ) { - zip.addReadStreamLazy( - pathInZip, - { mtime: attachment.updatedAt }, - (callback) => { - attachment.stream.then( - (stream) => { - if (!stream) { - Logger.warn(`Attachment is missing from storage`, { - attachmentId: attachment.id, - teamId: attachment.teamId, - }); - return callback(null, Readable.from([])); - } - - // yazl does not watch the streams it is handed, so an interrupted - // read would otherwise stall the archive rather than fail it. - stream.on("error", (err) => zip.emit("error", toError(err))); - return callback(null, stream); - }, - (err) => callback(toError(err), Readable.from([])) - ); - } - ); - } - /** * Notify the user that requested the export, in the app and by email. A * failure is logged and does not change the result of the export. diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 99d11e0309..72ba15dfcc 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -1,3 +1,4 @@ +import { Readable } from "node:stream"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { faker } from "@faker-js/faker"; @@ -33,6 +34,7 @@ import { } from "@server/models"; import { RelationshipType } from "@server/models/Relationship"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; +import HTMLHelper from "@server/models/helpers/HTMLHelper"; import DocumentImportTask from "@server/queues/tasks/DocumentImportTask"; import FileStorage from "@server/storage/files"; import { @@ -746,8 +748,8 @@ describe("#documents.export", () => { teamId: user.teamId, text: `![image](${attachment.redirectUrl})`, }); - vi.spyOn(FileStorage, "getFileBuffer").mockResolvedValue( - Buffer.from("image-data") + vi.spyOn(FileStorage, "getFileStream").mockImplementation(async () => + Readable.from([Buffer.from("image-data")]) ); const res = await server.post("/api/documents.export", user, { @@ -773,6 +775,111 @@ describe("#documents.export", () => { expect(entries["export-test.md"]).not.toContain(attachment.redirectUrl); }); + it("should inline small images and stream other attachments for HTML", async () => { + const user = await buildUser(); + const small = await buildAttachment({ + teamId: user.teamId, + userId: user.id, + contentType: "image/png", + size: 10, + }); + const large = await buildAttachment({ + teamId: user.teamId, + userId: user.id, + contentType: "image/png", + size: HTMLHelper.maxInlineImageSize + 1, + }); + const document = await buildDocument({ + title: "Export Test", + userId: user.id, + teamId: user.teamId, + text: `![small](${small.redirectUrl})\n\n![large](${large.redirectUrl})`, + }); + const getFileBuffer = vi + .spyOn(FileStorage, "getFileBuffer") + .mockResolvedValue(Buffer.from("small-data")); + vi.spyOn(FileStorage, "getFileStream").mockImplementation(async () => + Readable.from([Buffer.from("large-data")]) + ); + + const res = await server.post("/api/documents.export", user, { + body: { + id: document.id, + }, + headers: { + accept: "text/html", + }, + }); + + expect(res.status).toEqual(200); + expect(res.headers.get("content-type")).toEqual("application/zip"); + + const location = `attachments/${large.id}.png`; + const entries = await readZipResponse(res); + expect(Object.keys(entries).sort()).toEqual([location, "export-test.html"]); + expect(entries[location]).toEqual("large-data"); + expect(entries["export-test.html"]).toContain( + Buffer.from("small-data").toString("base64") + ); + expect(entries["export-test.html"]).not.toContain(small.redirectUrl); + + // Only the image that is inlined is read into memory. + expect(getFileBuffer).toHaveBeenCalledTimes(1); + expect(getFileBuffer).toHaveBeenCalledWith(small.key); + }); + + it("should stop inlining images at the total size limit for HTML", async () => { + const user = await buildUser(); + const count = + Math.floor( + HTMLHelper.maxTotalInlineImageSize / HTMLHelper.maxInlineImageSize + ) + 1; + const images = []; + for (let i = 0; i < count; i++) { + images.push( + await buildAttachment({ + teamId: user.teamId, + userId: user.id, + contentType: "image/png", + size: HTMLHelper.maxInlineImageSize, + }) + ); + } + const document = await buildDocument({ + title: "Export Test", + userId: user.id, + teamId: user.teamId, + text: images + .map((image) => `![image](${image.redirectUrl})`) + .join("\n\n"), + }); + const getFileBuffer = vi + .spyOn(FileStorage, "getFileBuffer") + .mockResolvedValue(Buffer.alloc(HTMLHelper.maxInlineImageSize)); + vi.spyOn(FileStorage, "getFileStream").mockImplementation(async () => + Readable.from([Buffer.from("image-data")]) + ); + + const res = await server.post("/api/documents.export", user, { + body: { + id: document.id, + }, + headers: { + accept: "text/html", + }, + }); + + expect(res.status).toEqual(200); + + // The last image does not fit in the limit, so it is streamed into the zip. + const entries = await readZipResponse(res); + const external = Object.keys(entries).filter((name) => + name.startsWith("attachments/") + ); + expect(external).toHaveLength(1); + expect(getFileBuffer).toHaveBeenCalledTimes(count - 1); + }); + it("should stream a textpack when TextBundle is requested", async () => { const user = await buildUser(); const attachment = await buildAttachment( @@ -785,8 +892,8 @@ describe("#documents.export", () => { teamId: user.teamId, text: `![image](${attachment.redirectUrl})`, }); - vi.spyOn(FileStorage, "getFileBuffer").mockResolvedValue( - Buffer.from("image-data") + vi.spyOn(FileStorage, "getFileStream").mockImplementation(async () => + Readable.from([Buffer.from("image-data")]) ); const res = await server.post("/api/documents.export", user, { diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index ae10b936e1..1bdc14343f 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -101,7 +101,7 @@ import type { Context } from "@server/types"; import { toHookContext } from "@server/context"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { convertBareUrlsToEmbedMarkdown } from "@server/utils/embeds"; -import { streamZipResponse } from "@server/utils/koa"; +import { getClientAbortSignal, streamZipResponse } from "@server/utils/koa"; import { QueryHelper } from "@server/storage/QueryHelper"; import { getTeamFromContext } from "@server/utils/passport"; import pagination, { paginateQuery } from "../middlewares/pagination"; @@ -1039,28 +1039,44 @@ router.post( }) : []; - // Read attachments and, when exporting HTML, inline small images that are - // referenced a single time as base64 data URIs. Any remaining attachments - // are bundled alongside the document in a zip. - const externalAttachments: { attachment: Attachment; buffer: Buffer }[] = - []; + // When exporting HTML, inline small images that are referenced a single + // time as base64 data URIs. Only these are read into memory; the other + // attachments are streamed into a zip with the document. + const signal = getClientAbortSignal(ctx.res); + const externalAttachments: Attachment[] = []; + let inlinedSize = 0; for (const attachment of attachments) { - const buffer = await AttachmentHelper.readBuffer(attachment); + if (signal.aborted) { + return; + } - if (contentType === "text/html") { + if ( + contentType === "text/html" && + HTMLHelper.canInlineImage( + content, + attachment.redirectUrl, + attachment.contentType, + // BIGINT columns are returned as strings. + Number(attachment.size), + inlinedSize + ) + ) { + const buffer = await AttachmentHelper.readBuffer(attachment); const inlined = HTMLHelper.inlineImage( content, attachment.redirectUrl, attachment.contentType, - buffer + buffer, + inlinedSize ); if (inlined !== null) { content = inlined; + inlinedSize += buffer.length; continue; } } - externalAttachments.push({ attachment, buffer }); + externalAttachments.push(attachment); } if (isTextBundle) { @@ -1070,15 +1086,18 @@ router.post( streamZipResponse( ctx, `${fileName}.${TextBundleHelper.packExtension}`, - (zip) => { - for (const { attachment, buffer } of externalAttachments) { + (zip, zipSignal) => { + for (const attachment of externalAttachments) { const reference = TextBundleHelper.assetPath( attachment.name, usedAssetNames ); - zip.addBuffer(buffer, path.join(root, reference), { - mtime: attachment.updatedAt, - }); + AttachmentHelper.addToArchive( + zip, + attachment, + path.join(root, reference), + zipSignal + ); content = content.replace( new RegExp(escapeRegExp(attachment.redirectUrl), "g"), @@ -1115,13 +1134,13 @@ router.post( return; } - streamZipResponse(ctx, `${fileName}.zip`, (zip) => { - for (const { attachment, buffer } of externalAttachments) { + streamZipResponse(ctx, `${fileName}.zip`, (zip, zipSignal) => { + for (const attachment of externalAttachments) { const location = path.join( "attachments", `${attachment.id}.${mime.extension(attachment.contentType)}` ); - zip.addBuffer(buffer, location, { mtime: attachment.updatedAt }); + AttachmentHelper.addToArchive(zip, attachment, location, zipSignal); content = content.replace( new RegExp(escapeRegExp(attachment.redirectUrl), "g"), diff --git a/server/routes/api/revisions/revisions.test.ts b/server/routes/api/revisions/revisions.test.ts index 1381e74e7e..ccd5acddd4 100644 --- a/server/routes/api/revisions/revisions.test.ts +++ b/server/routes/api/revisions/revisions.test.ts @@ -1,3 +1,4 @@ +import { Readable } from "node:stream"; import { DocumentPermission, ExportContentType, @@ -344,8 +345,8 @@ describe("#revisions.export", () => { createContext({ user }), document ); - vi.spyOn(FileStorage, "getFileBuffer").mockResolvedValue( - Buffer.from("image-data") + vi.spyOn(FileStorage, "getFileStream").mockImplementation(async () => + Readable.from([Buffer.from("image-data")]) ); const res = await server.post("/api/revisions.export", user, { @@ -387,8 +388,8 @@ describe("#revisions.export", () => { createContext({ user }), document ); - vi.spyOn(FileStorage, "getFileBuffer").mockResolvedValue( - Buffer.from("image-data") + vi.spyOn(FileStorage, "getFileStream").mockImplementation(async () => + Readable.from([Buffer.from("image-data")]) ); const res = await server.post("/api/revisions.export", user, { diff --git a/server/routes/api/revisions/revisions.ts b/server/routes/api/revisions/revisions.ts index 4795ff284f..337698c78b 100644 --- a/server/routes/api/revisions/revisions.ts +++ b/server/routes/api/revisions/revisions.ts @@ -207,16 +207,17 @@ router.post( streamZipResponse( ctx, `${fileName}.${TextBundleHelper.packExtension}`, - async (zip) => { + (zip, signal) => { for (const attachment of attachments) { const reference = TextBundleHelper.assetPath( attachment.name, usedAssetNames ); - zip.addBuffer( - await AttachmentHelper.readBuffer(attachment), + AttachmentHelper.addToArchive( + zip, + attachment, path.join(root, reference), - { mtime: attachment.updatedAt } + signal ); content = content.replace( @@ -252,15 +253,13 @@ router.post( return; } - streamZipResponse(ctx, `${fileName}.zip`, async (zip) => { + streamZipResponse(ctx, `${fileName}.zip`, (zip, signal) => { for (const attachment of attachments) { const location = path.join( "attachments", `${attachment.id}.${mime.extension(attachment.contentType)}` ); - zip.addBuffer(await AttachmentHelper.readBuffer(attachment), location, { - mtime: attachment.updatedAt, - }); + AttachmentHelper.addToArchive(zip, attachment, location, signal); content = content.replace( new RegExp(escapeRegExp(attachment.redirectUrl), "g"), diff --git a/server/storage/files/LocalStorage.test.ts b/server/storage/files/LocalStorage.test.ts index 6df0301bdb..84f07e4bea 100644 --- a/server/storage/files/LocalStorage.test.ts +++ b/server/storage/files/LocalStorage.test.ts @@ -73,4 +73,13 @@ describe("LocalStorage", () => { expect(remaining).toBeLessThanOrEqual(Hour.seconds); }); }); + + describe("getFileStream", () => { + it("should return null for a file that does not exist", async () => { + const storage = new LocalStorage(); + await expect( + storage.getFileStream("uploads/missing/file.png") + ).resolves.toBeNull(); + }); + }); }); diff --git a/server/storage/files/LocalStorage.ts b/server/storage/files/LocalStorage.ts index 452fab8685..d40e5096fa 100644 --- a/server/storage/files/LocalStorage.ts +++ b/server/storage/files/LocalStorage.ts @@ -10,7 +10,7 @@ import JWT from "jsonwebtoken"; import safeResolvePath from "resolve-path"; import { toError } from "@shared/utils/error"; import env from "@server/env"; -import { InternalError, ValidationError } from "@server/errors"; +import { ValidationError } from "@server/errors"; import Logger from "@server/logging/Logger"; import { getTokenFromCookie } from "@server/utils/csrf"; import BaseStorage from "./BaseStorage"; @@ -145,7 +145,8 @@ export default class LocalStorage extends BaseStorage { const filePath = this.getFilePath(key); const exists = await fs.pathExists(filePath); if (!exists) { - throw InternalError(`File not found at ${key}`); + Logger.info("utils", "File not found in local storage", { key }); + return null; } if (range) { diff --git a/server/test/support.ts b/server/test/support.ts index fb5bfded1f..3ff8b867a1 100644 --- a/server/test/support.ts +++ b/server/test/support.ts @@ -157,7 +157,7 @@ export async function readZipResponse( const entries: Record = {}; await ZipHelper.walk(filePath, async (entry) => { entries[entry.fileName] = ( - await entry.readBuffer(1024 * 1024) + await entry.readBuffer(4 * 1024 * 1024) ).toString(); }); return entries; diff --git a/server/utils/koa.test.ts b/server/utils/koa.test.ts new file mode 100644 index 0000000000..d77f8f7707 --- /dev/null +++ b/server/utils/koa.test.ts @@ -0,0 +1,74 @@ +import http from "node:http"; +import { getClientAbortSignal } from "./koa"; + +/** + * Start a server that gives the signal of each request to the handler. + * + * @param handle Called with the response and its signal for each request. + * @returns The server and its port. + */ +async function startServer( + handle: (res: http.ServerResponse, signal: AbortSignal) => void +) { + const server = http.createServer((_req, res) => { + handle(res, getClientAbortSignal(res)); + }); + await new Promise((resolve) => server.listen(0, resolve)); + const address = server.address(); + if (!address || typeof address === "string") { + throw new Error("Server is not listening on a port"); + } + return { server, port: address.port }; +} + +describe("getClientAbortSignal", () => { + it("should abort when the connection closes before the response is sent", async () => { + let handleSignal: (signal: AbortSignal) => void = () => {}; + const received = new Promise((resolve) => { + handleSignal = resolve; + }); + const { server, port } = await startServer((_res, signal) => { + handleSignal(signal); + }); + server.setTimeout(50); + + const req = http.request({ port, method: "POST" }); + req.on("error", () => {}); + req.end(); + + const signal = await received; + await new Promise((resolve) => { + if (signal.aborted) { + resolve(); + return; + } + signal.addEventListener("abort", () => resolve(), { once: true }); + }); + server.close(); + + expect(signal.aborted).toBe(true); + }); + + it("should not abort when the response is sent in full", async () => { + let signal: AbortSignal | undefined; + const { server, port } = await startServer((res, s) => { + signal = s; + res.end("ok"); + }); + + await new Promise((resolve, reject) => { + const req = http.request( + { port, method: "POST", agent: false }, + (res) => { + res.resume(); + res.on("end", resolve); + } + ); + req.on("error", reject); + req.end(); + }); + await new Promise((resolve) => server.close(() => resolve())); + + expect(signal?.aborted).toBe(false); + }); +}); diff --git a/server/utils/koa.ts b/server/utils/koa.ts index 42e11d054e..6621a099f0 100644 --- a/server/utils/koa.ts +++ b/server/utils/koa.ts @@ -1,3 +1,4 @@ +import type { ServerResponse } from "node:http"; import contentDisposition from "content-disposition"; import type formidable from "formidable"; import type { Request } from "koa"; @@ -27,6 +28,29 @@ export const getFileFromRequest = ( return isArray(file) ? file[0] : file; }; +/** + * Get a signal that aborts when the client connection closes before the + * response is sent in full, so that work for an abandoned request can stop. + * + * @param res The response of the request. + * @returns A signal that aborts when the client disconnects. + */ +export const getClientAbortSignal = (res: ServerResponse): AbortSignal => { + const controller = new AbortController(); + + if (res.destroyed && !res.writableFinished) { + controller.abort(); + return controller.signal; + } + + res.once("close", () => { + if (!res.writableFinished) { + controller.abort(); + } + }); + return controller.signal; +}; + /** * Stream a freshly-built zip archive as the response body. The supplied * `build` callback receives a yazl ZipFile to populate with entries; the @@ -35,14 +59,16 @@ export const getFileFromRequest = ( * * @param ctx The koa context to write the response to. * @param fileName The filename to advertise in the Content-Disposition header. - * @param build Callback that adds entries to the provided ZipFile. + * @param build Callback that adds entries to the provided ZipFile, and + * receives a signal that aborts when the client disconnects. */ export const streamZipResponse = ( ctx: AppContext, fileName: string, - build: (zip: ZipFile) => void | Promise + build: (zip: ZipFile, signal: AbortSignal) => void | Promise ): void => { const zip = new ZipFile(); + const signal = getClientAbortSignal(ctx.res); ctx.set("Content-Type", "application/zip"); ctx.set( @@ -50,17 +76,23 @@ export const streamZipResponse = ( contentDisposition(fileName, { type: "attachment" }) ); + let failed = false; const handleError = (err: Error) => { + if (failed) { + return; + } + failed = true; ctx.app.emit("error", err, ctx); ctx.res.destroy(err); }; + zip.on("error", handleError); zip.outputStream.on("error", handleError); ctx.body = zip.outputStream; void (async () => { try { - await build(zip); + await build(zip, signal); zip.end(); } catch (err) { handleError(err instanceof Error ? err : new Error(String(err)));