import { ConflictException, HttpException, Injectable, NotFoundException, PayloadTooLargeException, UnsupportedMediaTypeException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { randomUUID } from 'node:crypto'; import type { AppConfig } from '../config/app-config.schema.js'; import { ChatsService } from '../chats/chats.service.js'; import { JobsRepository } from '../jobs/jobs.repository.js'; import { OutboxRelay } from '../jobs/outbox-relay.service.js'; import { MetricsService } from '../metrics/metrics.service.js'; import { ObjectStorage, ObjectStorageUnavailableError, } from '../storage/object-storage.js'; import type { User } from '../users/user.js'; import { toAttachment, type Attachment, type AttachmentRow, } from './attachment.js'; import { AttachmentsRepository } from './attachments.repository.js'; import { imageRejection } from './attachments.service.js'; import type { CreateDirectUploadDto } from './dto/create-direct-upload.dto.js'; import { validateFilename } from './filename.js'; import { ImageDecoder } from './image/image-decoder.js'; import { UploadSlots } from './upload-slots.js'; import { ImageInspector, ImageRejectedError, type ImageHeader, } from './image/image-inspector.js'; export type DirectUpload = { attachment_id: string; method: 'PUT'; url: string; headers: Record; expires_at: string; }; const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']); @Injectable() export class DirectUploadsService { private readonly maxUploadBytes: number; private readonly maxPixels: number; private readonly uploadTimeoutMs: number; private readonly ttlSeconds: number; private readonly maxPending: number; private readonly pipelineVersion: number; private readonly maxAttempts: number; constructor( config: ConfigService, private readonly repository: AttachmentsRepository, private readonly jobs: JobsRepository, private readonly relay: OutboxRelay, private readonly storage: ObjectStorage, private readonly chats: ChatsService, private readonly metrics: MetricsService, private readonly decoder: ImageDecoder, private readonly slots: UploadSlots, ) { this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES'); this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS'); this.uploadTimeoutMs = config.getOrThrow('UPLOAD_TIMEOUT_MS'); this.ttlSeconds = config.getOrThrow('DIRECT_UPLOAD_URL_TTL_SECONDS'); this.maxPending = config.getOrThrow( 'DIRECT_UPLOAD_MAX_PENDING_PER_USER', ); this.pipelineVersion = config.getOrThrow('PIPELINE_VERSION'); this.maxAttempts = config.getOrThrow('JOB_MAX_ATTEMPTS'); } async init( chatId: string, user: User, dto: CreateDirectUploadDto, ): Promise { const filename = validateFilename(dto.filename); if (!MEDIA_TYPES.has(dto.content_type)) throw new UnsupportedMediaTypeException( 'content_type must be image/png or image/jpeg', ); if (dto.size_bytes > this.maxUploadBytes) throw new PayloadTooLargeException('Image is too large'); await this.chats.getForUser(chatId, user); const id = randomUUID(); const stagingKey = this.storage.stagingKey(id); const inserted = await this.repository.insertPendingLimited( { id, chatId, ownerId: user.id, filename, contentType: dto.content_type, uploadMode: 'direct', objectKey: this.storage.objectKey(id), stagingKey, sizeBytes: dto.size_bytes, sha256: dto.sha256, ttlMs: this.ttlSeconds * 1000, }, this.maxPending, ); if (!inserted) throw new HttpException( { message: 'Too many unfinished direct uploads', retryAfter: this.ttlSeconds, }, 429, ); const checksum = Buffer.from(dto.sha256, 'hex').toString('base64'); let url: string; try { url = await this.storage.presignPut(stagingKey, { contentType: dto.content_type, contentLength: dto.size_bytes, checksumSha256Base64: checksum, expiresInSeconds: this.ttlSeconds, }); } catch (error) { await this.repository.deletePending(id); throw error; } this.metrics.increment('attachments.direct.initiated'); return { attachment_id: id, method: 'PUT', url, headers: { 'Content-Type': dto.content_type, 'x-amz-checksum-sha256': checksum, }, expires_at: new Date( Date.now() + this.ttlSeconds * 1000, ).toISOString(), }; } async complete(attachmentId: string, user: User): Promise { const row = await this.repository.findForComplete( attachmentId, user.id, ); if (!row) throw new NotFoundException(); if (row.status !== 'pending') return this.describe(row); return this.slots.run(user.id, () => this.verifyAndAccept(row)); } private async describe(row: AttachmentRow): Promise { const variants = row.status === 'ready' && row.ready_pipeline_version !== null ? await this.jobs.variantsFor( row.id, row.ready_pipeline_version, ) : []; return toAttachment(row, variants); } private async verifyAndAccept(row: AttachmentRow): Promise { const size = Number(row.size_bytes); const stagingKey = row.staging_key; if (stagingKey === null) throw new ConflictException('Upload has not been received'); const expectedChecksum = Buffer.from( row.sha256 as string, 'hex', ).toString('base64'); const head = await this.storage.head(stagingKey); if (head === null) throw new ConflictException('Upload has not been received'); if (head.size !== size || head.checksumSha256 !== expectedChecksum) { await this.reject(row, stagingKey); throw new ConflictException( 'Uploaded object does not match the declaration', ); } let header: ImageHeader; try { header = await this.verifyObject(stagingKey, size); } catch (error) { if (error instanceof ImageRejectedError) { await this.reject(row, stagingKey); throw imageRejection(error); } throw error; } if (header.contentType !== row.content_type) { await this.reject(row, stagingKey); throw new UnsupportedMediaTypeException( 'Image content does not match content_type', ); } const accepted = await this.jobs.acceptUpload( row.id, { sizeBytes: size, sha256: row.sha256 as string, width: header.width, height: header.height, }, this.pipelineVersion, this.maxAttempts, ); if (!accepted) { // A parallel complete of the same upload won: answer like a repeat. const current = await this.repository.findForComplete( row.id, row.owner_id, ); if (current && current.status !== 'pending') return this.describe(current); throw new ConflictException('Upload is no longer pending'); } this.relay.kick(); this.metrics.increment('attachments.direct.completed'); return toAttachment(accepted); } /** * Reads the whole object: a correct signed checksum only proves that the * bytes are the ones the client declared, not that they form an image. The * stream goes through ImageInspector (structure, CRCs, completeness), then * the copy is fully decoded. Memory is bounded like a proxy upload. */ private async verifyObject( key: string, size: number, ): Promise { // Same deadline as a proxy upload: a slow or hung read releases its slot. const signal = AbortSignal.timeout(this.uploadTimeoutMs); const stream = await this.storage.getStream(key, signal); if (stream === null) throw new ConflictException('Upload has not been received'); const inspector = new ImageInspector(this.maxPixels); const chunks: Buffer[] = []; let read = 0; try { for await (const chunk of stream as AsyncIterable) { read += chunk.length; if (read > size) throw new ImageRejectedError( 'unsupported_media_type', 'Object is larger than declared', ); inspector.push(chunk); chunks.push(chunk); } } catch (error) { if (error instanceof ImageRejectedError) throw error; // The object stream broke mid-read (S3 outage, timeout): the image // was not judged, so this is an outage, not a client error. throw new ObjectStorageUnavailableError(); } finally { stream.destroy(); this.metrics.add('attachments.direct.verify_bytes', read); } const header = inspector.finish(); const data = Buffer.concat(chunks, read); chunks.length = 0; await this.decoder.verify(data, signal); return header; } /** * A rejected claim keeps its row (status `rejected`, original expiry) while * the signed URL may still be used: a later re-PUT would otherwise leave an * object that no row refers to. The sweeper removes both after expiry + grace. */ private async reject( row: AttachmentRow, stagingKey: string, ): Promise { // Row first: a row that is not pending any more (accepted after a parallel // complete, or claimed by the sweeper) keeps its object. if (!(await this.repository.rejectPending(row.id))) return; try { await this.storage.delete(stagingKey); } catch { // The sweeper deletes the object again after expiry. } this.metrics.increment('attachments.direct.rejected'); } }