Files
mtusi2026lab4/src/attachments/attachments.service.ts
T

199 lines
6.0 KiB
TypeScript

import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { Attachment, Prisma } from '@prisma/client';
import { randomUUID } from 'crypto';
import { mkdtemp, readdir, rm, stat } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { Readable } from 'stream';
import { assertChatMember } from '../chats/chat-access';
import { codePointLength } from '../common/dto/code-point-length.validator';
import { ApiError } from '../common/filters/api-error';
import { validate as isUuid } from '../common/uuid';
import { isDatabaseUnavailable, PrismaService } from '../db/prisma.service';
import { S3Service } from '../storage/s3.service';
import { assertValidImage, isSupportedContentType } from './image-validation';
import { receiveBody } from './upload-body';
const TEMP_PREFIX = 'messenger-upload-';
const STALE_TEMP_MS = 60 * 60 * 1000;
const MAX_FILENAME_CODE_POINTS = 255;
const FORBIDDEN_FILENAME = /[/\\\p{Cc}\p{Zl}\p{Zp}]/u;
const KNOWN_VARIANTS = new Set(['thumbnail', 'crop', 'optimized']);
export interface UploadInput {
chatId: string;
ownerId: string;
filename: unknown;
contentType: string | undefined;
contentLength: string | undefined;
body: Readable | undefined;
}
@Injectable()
export class AttachmentsService implements OnModuleInit {
private readonly logger = new Logger('AttachmentsService');
private readonly maxBytes = Number(process.env.MAX_UPLOAD_BYTES ?? 10485760);
private readonly maxPixels = Number(process.env.MAX_IMAGE_PIXELS ?? 40000000);
private readonly maxConcurrent = Number(process.env.MAX_CONCURRENT_UPLOADS ?? 16);
private readonly bodyTimeoutMs = Number(process.env.UPLOAD_BODY_TIMEOUT_MS ?? 60000);
private activeUploads = 0;
constructor(
private readonly prisma: PrismaService,
private readonly s3: S3Service,
) {}
async onModuleInit(): Promise<void> {
await this.removeStaleTempDirs();
}
async upload(input: UploadInput): Promise<Attachment> {
await assertChatMember(this.prisma, input.chatId, input.ownerId);
const filename = parseFilename(input.filename);
const contentType = parseContentType(input.contentType);
if (Number(input.contentLength) > this.maxBytes) {
throw new ApiError('payload_too_large', 'attachment exceeds size limit');
}
if (this.activeUploads >= this.maxConcurrent) {
throw new ApiError('unavailable', 'too many concurrent uploads');
}
this.activeUploads++;
const dir = await mkdtemp(join(tmpdir(), TEMP_PREFIX));
try {
return await this.store(input, filename, contentType, join(dir, 'body'));
} finally {
this.activeUploads--;
await rm(dir, { recursive: true, force: true });
}
}
async getVisible(attachmentId: string, userId: string): Promise<Attachment> {
if (!isUuid(attachmentId)) {
throw new ApiError('invalid_request', 'attachmentId must be a valid UUID');
}
const row = await this.prisma.attachment.findFirst({
where: {
id: attachmentId,
chat: { members: { some: { userId } } },
},
});
if (!row) {
throw new ApiError('not_found', 'attachment not found');
}
return row;
}
async openContent(
attachmentId: string,
userId: string,
variant: unknown,
): Promise<{ attachment: Attachment; content: Readable }> {
const attachment = await this.getVisible(attachmentId, userId);
assertOriginalVariant(variant);
return { attachment, content: await this.s3.getStream(attachment.objectKey) };
}
private async store(
input: UploadInput,
filename: string,
contentType: string,
path: string,
): Promise<Attachment> {
if (!input.body) {
throw new ApiError('invalid_request', 'request body must not be empty');
}
const { size, sha256 } = await receiveBody(
input.body,
path,
this.maxBytes,
this.bodyTimeoutMs,
);
if (size === 0) {
throw new ApiError('invalid_request', 'request body must not be empty');
}
await assertValidImage(path, size, contentType, this.maxPixels);
const id = randomUUID();
const objectKey = `attachments/${id}`;
await this.s3.putFile({ key: objectKey, path, size, contentType, sha256 });
const now = new Date();
try {
return await this.prisma.attachment.create({
data: {
id,
chatId: input.chatId,
ownerId: input.ownerId,
filename,
contentType,
sizeBytes: size,
sha256,
objectKey,
createdAt: now,
updatedAt: now,
},
});
} catch (error) {
if (isDefiniteRejection(error)) {
await this.s3.delete(objectKey).catch(() => {
this.logger.warn(`compensation failed for ${objectKey}`);
});
}
throw error;
}
}
private async removeStaleTempDirs(): Promise<void> {
const root = tmpdir();
const names = await readdir(root);
for (const name of names.filter((n) => n.startsWith(TEMP_PREFIX))) {
const path = join(root, name);
const info = await stat(path).catch(() => null);
if (info && Date.now() - info.mtimeMs > STALE_TEMP_MS) {
await rm(path, { recursive: true, force: true });
}
}
}
}
function assertOriginalVariant(raw: unknown): void {
if (raw === undefined || raw === 'original') {
return;
}
if (typeof raw === 'string' && KNOWN_VARIANTS.has(raw)) {
throw new ApiError('not_found', 'attachment variant not found');
}
throw new ApiError('invalid_request', 'unknown attachment variant');
}
function isDefiniteRejection(error: unknown): boolean {
return (
error instanceof Prisma.PrismaClientKnownRequestError &&
!isDatabaseUnavailable(error)
);
}
function parseFilename(raw: unknown): string {
if (
typeof raw !== 'string' ||
raw.trim() === '' ||
codePointLength(raw) > MAX_FILENAME_CODE_POINTS ||
FORBIDDEN_FILENAME.test(raw)
) {
throw new ApiError(
'invalid_request',
'filename must be 1-255 characters without path separators or control characters',
);
}
return raw;
}
function parseContentType(raw: string | undefined): string {
const contentType = raw?.split(';')[0].trim().toLowerCase() ?? '';
if (!isSupportedContentType(contentType)) {
throw new ApiError(
'unsupported_media_type',
'Content-Type must be image/png or image/jpeg',
);
}
return contentType;
}