feat: accept uploads into staging with jobs, outbox and job processor
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { Attachment, Prisma } from '@prisma/client';
|
||||
import { Attachment, AttachmentVariant, Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { mkdtemp, readdir, rm, stat } from 'fs/promises';
|
||||
import { tmpdir } from 'os';
|
||||
@@ -10,6 +10,8 @@ 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 { PIPELINE_VERSION } from '../jobs/job-message';
|
||||
import { enqueueJob } from '../jobs/job-store';
|
||||
import { S3Service } from '../storage/s3.service';
|
||||
import { assertValidImage, isSupportedContentType } from './image-validation';
|
||||
import { receiveBody } from './upload-body';
|
||||
@@ -18,7 +20,16 @@ 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']);
|
||||
const KNOWN_VARIANTS = new Set(['original', 'thumbnail', 'crop', 'optimized']);
|
||||
|
||||
export type AttachmentWithVariants = Attachment & { variants: AttachmentVariant[] };
|
||||
|
||||
export interface DownloadableContent {
|
||||
filename: string;
|
||||
contentType: string;
|
||||
sizeBytes: number;
|
||||
content: Readable;
|
||||
}
|
||||
|
||||
export interface UploadInput {
|
||||
chatId: string;
|
||||
@@ -36,6 +47,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
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 readonly tempRoot = process.env.UPLOAD_TMP_DIR ?? tmpdir();
|
||||
private activeUploads = 0;
|
||||
|
||||
constructor(
|
||||
@@ -47,7 +59,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
await this.removeStaleTempDirs();
|
||||
}
|
||||
|
||||
async upload(input: UploadInput): Promise<Attachment> {
|
||||
async upload(input: UploadInput): Promise<AttachmentWithVariants> {
|
||||
await assertChatMember(this.prisma, input.chatId, input.ownerId);
|
||||
const filename = parseFilename(input.filename);
|
||||
const contentType = parseContentType(input.contentType);
|
||||
@@ -58,7 +70,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
throw new ApiError('unavailable', 'too many concurrent uploads');
|
||||
}
|
||||
this.activeUploads++;
|
||||
const dir = await mkdtemp(join(tmpdir(), TEMP_PREFIX));
|
||||
const dir = await mkdtemp(join(this.tempRoot, TEMP_PREFIX));
|
||||
try {
|
||||
return await this.store(input, filename, contentType, join(dir, 'body'));
|
||||
} finally {
|
||||
@@ -67,7 +79,10 @@ export class AttachmentsService implements OnModuleInit {
|
||||
}
|
||||
}
|
||||
|
||||
async getVisible(attachmentId: string, userId: string): Promise<Attachment> {
|
||||
async getVisible(
|
||||
attachmentId: string,
|
||||
userId: string,
|
||||
): Promise<AttachmentWithVariants> {
|
||||
if (!isUuid(attachmentId)) {
|
||||
throw new ApiError('invalid_request', 'attachmentId must be a valid UUID');
|
||||
}
|
||||
@@ -76,6 +91,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
id: attachmentId,
|
||||
chat: { members: { some: { userId } } },
|
||||
},
|
||||
include: { variants: { where: { pipelineVersion: PIPELINE_VERSION } } },
|
||||
});
|
||||
if (!row) {
|
||||
throw new ApiError('not_found', 'attachment not found');
|
||||
@@ -87,10 +103,30 @@ export class AttachmentsService implements OnModuleInit {
|
||||
attachmentId: string,
|
||||
userId: string,
|
||||
variant: unknown,
|
||||
): Promise<{ attachment: Attachment; content: Readable }> {
|
||||
): Promise<DownloadableContent> {
|
||||
const attachment = await this.getVisible(attachmentId, userId);
|
||||
assertOriginalVariant(variant);
|
||||
return { attachment, content: await this.s3.getStream(attachment.objectKey) };
|
||||
const name = parseVariant(variant);
|
||||
if (attachment.status !== 'ready') {
|
||||
throw new ApiError('conflict', `attachment is ${attachment.status}`);
|
||||
}
|
||||
if (name === 'original') {
|
||||
return {
|
||||
filename: attachment.filename,
|
||||
contentType: attachment.contentType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
content: await this.s3.getStream(attachment.objectKey),
|
||||
};
|
||||
}
|
||||
const stored = attachment.variants.find((v) => v.name === name);
|
||||
if (!stored) {
|
||||
throw new ApiError('not_found', 'attachment variant not found');
|
||||
}
|
||||
return {
|
||||
filename: attachment.filename,
|
||||
contentType: stored.contentType,
|
||||
sizeBytes: stored.sizeBytes,
|
||||
content: await this.s3.getStream(stored.objectKey),
|
||||
};
|
||||
}
|
||||
|
||||
private async store(
|
||||
@@ -98,7 +134,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
filename: string,
|
||||
contentType: string,
|
||||
path: string,
|
||||
): Promise<Attachment> {
|
||||
): Promise<AttachmentWithVariants> {
|
||||
if (!input.body) {
|
||||
throw new ApiError('invalid_request', 'request body must not be empty');
|
||||
}
|
||||
@@ -113,32 +149,38 @@ export class AttachmentsService implements OnModuleInit {
|
||||
}
|
||||
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 stagingKey = `staging/${id}`;
|
||||
await this.s3.putFile({ key: stagingKey, 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,
|
||||
},
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
const attachment = await tx.attachment.create({
|
||||
data: {
|
||||
id,
|
||||
chatId: input.chatId,
|
||||
ownerId: input.ownerId,
|
||||
filename,
|
||||
contentType,
|
||||
sizeBytes: size,
|
||||
sha256,
|
||||
objectKey: `attachments/${id}/original`,
|
||||
stagingKey,
|
||||
status: 'queued',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
await enqueueJob(tx, id, now);
|
||||
return { ...attachment, variants: [] };
|
||||
});
|
||||
} catch (error) {
|
||||
if (isDefiniteRejection(error)) {
|
||||
await this.s3.delete(objectKey).catch(() => {
|
||||
this.logger.warn(`compensation failed for ${objectKey}`);
|
||||
await this.s3.delete(stagingKey).catch(() => {
|
||||
this.logger.warn(`compensation failed for ${stagingKey}`);
|
||||
});
|
||||
}
|
||||
if (error instanceof Prisma.PrismaClientUnknownRequestError) {
|
||||
this.logger.error(`metadata insert failed for ${objectKey}`);
|
||||
this.logger.error(`metadata insert failed for ${stagingKey}`);
|
||||
throw new ApiError('unavailable', 'database unavailable');
|
||||
}
|
||||
throw error;
|
||||
@@ -146,7 +188,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
}
|
||||
|
||||
private async removeStaleTempDirs(): Promise<void> {
|
||||
const root = tmpdir();
|
||||
const root = this.tempRoot;
|
||||
const names = await readdir(root);
|
||||
for (const name of names.filter((n) => n.startsWith(TEMP_PREFIX))) {
|
||||
const path = join(root, name);
|
||||
@@ -158,12 +200,12 @@ export class AttachmentsService implements OnModuleInit {
|
||||
}
|
||||
}
|
||||
|
||||
function assertOriginalVariant(raw: unknown): void {
|
||||
if (raw === undefined || raw === 'original') {
|
||||
return;
|
||||
function parseVariant(raw: unknown): string {
|
||||
if (raw === undefined) {
|
||||
return 'original';
|
||||
}
|
||||
if (typeof raw === 'string' && KNOWN_VARIANTS.has(raw)) {
|
||||
throw new ApiError('not_found', 'attachment variant not found');
|
||||
return raw;
|
||||
}
|
||||
throw new ApiError('invalid_request', 'unknown attachment variant');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user