Files
outline/server/storage/files/LocalStorage.ts
T
Tom Moor 2c84b2100f 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
2026-11-24 19:51:15 -05:00

198 lines
5.2 KiB
TypeScript

import { Blob } from "node:buffer";
import { mkdir, unlink, rmdir } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import type { PresignedPost } from "@aws-sdk/s3-presigned-post";
import fs from "fs-extra";
import invariant from "invariant";
import JWT from "jsonwebtoken";
import safeResolvePath from "resolve-path";
import { toError } from "@shared/utils/error";
import env from "@server/env";
import { ValidationError } from "@server/errors";
import Logger from "@server/logging/Logger";
import { getTokenFromCookie } from "@server/utils/csrf";
import BaseStorage from "./BaseStorage";
import { CSRF } from "@shared/constants";
import type { AppContext } from "@server/types";
export default class LocalStorage extends BaseStorage {
public async getPresignedPost(
ctx: AppContext,
key: string,
acl: string,
maxUploadSize: number,
contentType = "image"
): Promise<Partial<PresignedPost>> {
// A short-lived signature that authorizes uploading to this key only
const sig = JWT.sign({ key, type: "attachment-upload" }, env.SECRET_KEY, {
expiresIn: 3600,
});
return Promise.resolve({
url: this.getUrlForKey(key),
fields: {
key,
acl,
maxUploadSize: String(maxUploadSize),
contentType,
sig,
[CSRF.fieldName]: getTokenFromCookie(ctx) ?? "",
},
});
}
public getUploadUrl() {
return "/api/files.create";
}
public getUrlForKey(key: string): string {
return `/api/files.get?key=${key}`;
}
public store = async ({
body,
key,
}: {
body: string | fs.ReadStream | Buffer | Uint8Array | Blob;
contentLength?: number;
contentType?: string;
key: string;
acl?: string;
}) => {
const exists = await fs.pathExists(this.getFilePath(key));
if (exists) {
throw ValidationError(`File already exists at ${key}`);
}
await mkdir(this.getFilePath(path.dirname(key)), {
recursive: true,
});
let src: NodeJS.ReadableStream;
if (body instanceof fs.ReadStream) {
src = body;
} else if (body instanceof Blob) {
src = Readable.from(Buffer.from(await body.arrayBuffer()));
} else {
src = Readable.from(body);
}
const filePath = this.getFilePath(key);
// Create the file on disk first
await fs.createFile(filePath);
await pipeline(src, fs.createWriteStream(filePath));
return this.getUrlForKey(key);
};
public async deleteFile(key: string) {
const filePath = this.getFilePath(key);
try {
await unlink(filePath);
} catch (err) {
Logger.warn(`Couldn't delete ${filePath}`, { error: err });
return;
}
const directory = path.dirname(filePath);
try {
await rmdir(directory);
} catch (err) {
if (err instanceof Error && "code" in err && err.code === "ENOTEMPTY") {
return;
}
Logger.warn(`Couldn't delete directory ${directory}`, { error: err });
}
}
public getSignedUrl = async (
key: string,
expiresIn = LocalStorage.defaultSignedUrlExpires
) => {
const sig = JWT.sign(
{
key,
type: "attachment",
iat: Math.floor(
LocalStorage.getSigningDate(expiresIn).getTime() / 1000
),
},
env.SECRET_KEY,
{
expiresIn,
}
);
return Promise.resolve(`${env.URL}/api/files.get?sig=${sig}`);
};
public async getFileHandle(key: string) {
return {
path: this.getFilePath(key),
cleanup: async () => {
// no-op, as we're reading the canonical file directly
},
};
}
public async getFileStream(
key: string,
range?: { start: number; end: number }
) {
const filePath = this.getFilePath(key);
const exists = await fs.pathExists(filePath);
if (!exists) {
Logger.info("utils", "File not found in local storage", { key });
return null;
}
if (range) {
if (
typeof range.start !== "number" ||
typeof range.end !== "number" ||
range.start < 0 ||
range.end < range.start
) {
throw ValidationError("Invalid range specified");
}
}
try {
return fs.createReadStream(filePath, range);
} catch (err) {
Logger.error(`Failed to create read stream`, toError(err), { filePath });
throw ValidationError("Unable to read file");
}
}
public stat(key: string) {
return fs.stat(this.getFilePath(key));
}
public getFileExists(key: string) {
return fs.pathExists(this.getFilePath(key));
}
public moveFile(fromKey: string, toKey: string): Promise<void> {
return fs.move(this.getFilePath(fromKey), this.getFilePath(toKey));
}
private getFilePath(key: string) {
invariant(
env.FILE_STORAGE_LOCAL_ROOT_DIR,
"FILE_STORAGE_LOCAL_ROOT_DIR is required"
);
// resolve-path only rejects a path that climbs above the root, it will
// silently normalize one that moves between buckets inside it.
if (key.split(/[\\/]/).includes("..")) {
throw ValidationError(`Invalid file key ${key}`);
}
return safeResolvePath(env.FILE_STORAGE_LOCAL_ROOT_DIR, key);
}
}