feat: accept uploads into staging with jobs, outbox and job processor

This commit is contained in:
2026-11-15 15:21:46 +03:00
parent 19dda6e286
commit f4793b50cd
18 changed files with 1657 additions and 95 deletions
+6 -6
View File
@@ -26,7 +26,7 @@ export class AttachmentsController {
constructor(private readonly attachments: AttachmentsService) {}
@Post('api/v1/chats/:chatId/attachments')
@HttpCode(201)
@HttpCode(202)
async upload(
@Param('chatId') chatId: string,
@Query('filename') filename: unknown,
@@ -61,19 +61,19 @@ export class AttachmentsController {
@CurrentUser() user: User,
@Res() reply: FastifyReply,
): Promise<void> {
const { attachment, content } = await this.attachments.openContent(
const download = await this.attachments.openContent(
attachmentId,
user.id,
variant,
);
await reply
.header('content-type', attachment.contentType)
.header('content-length', attachment.sizeBytes)
.header('content-type', download.contentType)
.header('content-length', download.sizeBytes)
.header('x-content-type-options', 'nosniff')
.header(
'content-disposition',
`inline; filename*=UTF-8''${encodeURIComponent(attachment.filename)}`,
`inline; filename*=UTF-8''${encodeURIComponent(download.filename)}`,
)
.send(content);
.send(download.content);
}
}
+74 -32
View File
@@ -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');
}
+30 -8
View File
@@ -1,4 +1,15 @@
import { Attachment } from '@prisma/client';
import { Attachment, AttachmentVariant } from '@prisma/client';
const VARIANT_ORDER = ['thumbnail', 'crop', 'optimized'];
export interface VariantResponse {
name: string;
content_type: string;
size_bytes: number;
width: number;
height: number;
sha256: string;
}
export interface AttachmentResponse {
id: string;
@@ -8,14 +19,18 @@ export interface AttachmentResponse {
content_type: string;
size_bytes: number;
sha256: string;
status: 'ready';
variants: never[];
error_code: null;
status: string;
variants: VariantResponse[];
error_code: string | null;
created_at: string;
updated_at: string;
}
export function toAttachmentResponse(row: Attachment): AttachmentResponse {
export function toAttachmentResponse(
row: Attachment & { variants: AttachmentVariant[] },
): AttachmentResponse {
const variants = row.status === 'ready' ? [...row.variants] : [];
variants.sort((a, b) => VARIANT_ORDER.indexOf(a.name) - VARIANT_ORDER.indexOf(b.name));
return {
id: row.id,
chat_id: row.chatId,
@@ -24,9 +39,16 @@ export function toAttachmentResponse(row: Attachment): AttachmentResponse {
content_type: row.contentType,
size_bytes: row.sizeBytes,
sha256: row.sha256,
status: 'ready',
variants: [],
error_code: null,
status: row.status,
variants: variants.map((variant) => ({
name: variant.name,
content_type: variant.contentType,
size_bytes: variant.sizeBytes,
width: variant.width,
height: variant.height,
sha256: variant.sha256,
})),
error_code: row.errorCode,
created_at: row.createdAt.toISOString(),
updated_at: row.updatedAt.toISOString(),
};
+75 -10
View File
@@ -2,10 +2,14 @@ import { PrismaClient } from '@prisma/client';
import { S3Service } from '../storage/s3.service';
const MAX_REPORTED_KEYS = 20;
const DEFAULT_PREFIXES = ['attachments/', 'staging/'];
type ReconcilePrisma = Pick<PrismaClient, 'attachment' | 'attachmentVariant'>;
export interface ReconcileOptions {
apply: boolean;
graceMs: number;
stagingRetentionMs?: number;
prefix?: string;
now?: Date;
pageSize?: number;
@@ -14,6 +18,7 @@ export interface ReconcileOptions {
export interface ReconcileReport {
mode: 'apply' | 'dry-run';
grace_seconds: number;
staging_expired: number;
scanned: number;
fresh_skipped: number;
referenced: number;
@@ -25,7 +30,7 @@ export interface ReconcileReport {
}
export async function reconcile(
prisma: Pick<PrismaClient, 'attachment'>,
prisma: ReconcilePrisma,
s3: S3Service,
options: ReconcileOptions,
): Promise<ReconcileReport> {
@@ -34,6 +39,7 @@ export async function reconcile(
const report: ReconcileReport = {
mode: options.apply ? 'apply' : 'dry-run',
grace_seconds: options.graceMs / 1000,
staging_expired: 0,
scanned: 0,
fresh_skipped: 0,
referenced: 0,
@@ -43,22 +49,83 @@ export async function reconcile(
orphan_keys: [],
duration_ms: 0,
};
if (options.stagingRetentionMs !== undefined) {
report.staging_expired = await expireFailedStaging(
prisma,
s3,
(options.now ?? new Date()).getTime() - options.stagingRetentionMs,
options.apply,
);
}
for (const prefix of options.prefix ? [options.prefix] : DEFAULT_PREFIXES) {
await reconcilePrefix(prisma, s3, prefix, cutoff, options, report);
}
report.duration_ms = Date.now() - started;
return report;
}
async function expireFailedStaging(
prisma: ReconcilePrisma,
s3: S3Service,
before: number,
apply: boolean,
): Promise<number> {
const rows = await prisma.attachment.findMany({
where: {
status: 'failed',
stagingKey: { not: null },
updatedAt: { lt: new Date(before) },
},
select: { id: true, stagingKey: true },
take: 500,
});
if (!apply) {
return rows.length;
}
let expired = 0;
for (const row of rows) {
try {
await s3.delete(row.stagingKey!);
await prisma.attachment.update({
where: { id: row.id },
data: { stagingKey: null },
});
expired++;
} catch {
continue;
}
}
return expired;
}
async function reconcilePrefix(
prisma: ReconcilePrisma,
s3: S3Service,
prefix: string,
cutoff: number,
options: ReconcileOptions,
report: ReconcileReport,
): Promise<void> {
let token: string | undefined;
do {
const page = await s3.listObjects(
options.prefix ?? 'attachments/',
options.pageSize ?? 500,
token,
);
const page = await s3.listObjects(prefix, options.pageSize ?? 500, token);
token = page.nextToken;
report.scanned += page.objects.length;
const old = page.objects.filter((object) => object.lastModified.getTime() < cutoff);
report.fresh_skipped += page.objects.length - old.length;
const keys = old.map((object) => object.key);
const rows = await prisma.attachment.findMany({
where: { objectKey: { in: old.map((object) => object.key) } },
where: { OR: [{ objectKey: { in: keys } }, { stagingKey: { in: keys } }] },
select: { objectKey: true, stagingKey: true },
});
const variants = await prisma.attachmentVariant.findMany({
where: { objectKey: { in: keys } },
select: { objectKey: true },
});
const known = new Set(rows.map((row) => row.objectKey));
const known = new Set([
...rows.flatMap((row) => [row.objectKey, row.stagingKey]),
...variants.map((row) => row.objectKey),
]);
for (const { key } of old) {
if (known.has(key)) {
report.referenced++;
@@ -76,6 +143,4 @@ export async function reconcile(
}
}
} while (token);
report.duration_ms = Date.now() - started;
return report;
}