import { DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import { NodeHttpHandler } from '@smithy/node-http-handler'; import { Injectable, Logger, ServiceUnavailableException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import http from 'node:http'; import { Readable } from 'node:stream'; import type { AppConfig } from '../config/app-config.schema.js'; export class ObjectStorageUnavailableError extends ServiceUnavailableException { constructor() { super('Object storage unavailable'); } } export type PresignPutOptions = { contentType: string; contentLength: number; checksumSha256Base64: string; expiresInSeconds: number; }; function isMissingKey(error: unknown): boolean { const candidate = error as { name?: string; $metadata?: { httpStatusCode?: number }; }; return ( candidate?.name === 'NoSuchKey' || candidate?.name === 'NotFound' || candidate?.$metadata?.httpStatusCode === 404 ); } @Injectable() export class ObjectStorage { private readonly logger = new Logger(ObjectStorage.name); private readonly bucket: string; private readonly internal: S3Client; private readonly presign: S3Client; private readonly requestTimeoutMs: number; constructor(config: ConfigService) { this.bucket = config.getOrThrow('S3_BUCKET'); this.requestTimeoutMs = config.getOrThrow('S3_REQUEST_TIMEOUT_MS'); const common = { region: config.getOrThrow('S3_REGION'), forcePathStyle: true, credentials: { accessKeyId: config.getOrThrow('S3_ACCESS_KEY_ID'), secretAccessKey: config.getOrThrow('S3_SECRET_ACCESS_KEY'), }, // Поток нельзя повторить: повтор — решение клиента API. maxAttempts: 1, requestChecksumCalculation: 'WHEN_REQUIRED' as const, responseChecksumValidation: 'WHEN_REQUIRED' as const, // requestTimeout bounds a request until its response arrives and, // with throwOnRequestTimeout, actually fails it (otherwise smithy // only logs a warning); socketTimeout bounds a stalled body read. // A hung S3 therefore costs at most S3_REQUEST_TIMEOUT_MS per call. requestHandler: new NodeHttpHandler({ connectionTimeout: config.getOrThrow('S3_CONNECT_TIMEOUT_MS'), requestTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'), throwOnRequestTimeout: true, socketTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'), httpAgent: new http.Agent({ keepAlive: true, maxSockets: 64 }), }), }; this.internal = new S3Client({ ...common, endpoint: config.getOrThrow('S3_ENDPOINT'), }); // Сеть не использует: только подпись URL для клиента. this.presign = new S3Client({ ...common, endpoint: config.getOrThrow('S3_PUBLIC_ENDPOINT'), }); } objectKey(attachmentId: string): string { return `attachments/${attachmentId}/original`; } stagingKey(attachmentId: string): string { return `staging/${attachmentId}/original`; } variantKey( attachmentId: string, pipelineVersion: number, variant: 'thumbnail' | 'crop' | 'optimized', extension: 'jpg' | 'webp', attempt = 1, ): string { // The attempt suffix makes a stale worker's write harmless: the DB // points at the key of the attempt that won the lease fence. return `attachments/${attachmentId}/v${pipelineVersion}/${variant}-a${attempt}.${extension}`; } async putStream( key: string, body: Readable, contentLength: number, contentType: string, signal?: AbortSignal, ): Promise { try { await this.internal.send( new PutObjectCommand({ Bucket: this.bucket, Key: key, Body: body, ContentLength: contentLength, ContentType: contentType, }), // The upload deadline (UPLOAD_TIMEOUT_MS, via `signal`) bounds the // PUT: it lasts as long as the client sends, not S3_REQUEST_TIMEOUT_MS. // A worker buffer has no client deadline, so it uses the SDK timeout. signal ? { abortSignal: signal, requestTimeout: 0 } : { requestTimeout: this.requestTimeoutMs }, ); } catch (error) { throw this.fail('put', error); } } async putBuffer( key: string, data: Buffer, contentType: string, signal?: AbortSignal, ): Promise { await this.putStream( key, Readable.from([data]), data.length, contentType, signal, ); } async getStream( key: string, signal?: AbortSignal, ): Promise { try { const result = await this.internal.send( new GetObjectCommand({ Bucket: this.bucket, Key: key }), { abortSignal: signal }, ); return result.Body as Readable; } catch (error) { if (isMissingKey(error)) return null; throw this.fail('get', error); } } async head(key: string): Promise<{ size: number; checksumSha256?: string; etag?: string; lastModified?: Date; } | null> { try { const result = await this.internal.send( new HeadObjectCommand({ Bucket: this.bucket, Key: key, ChecksumMode: 'ENABLED', }), ); return { size: Number(result.ContentLength ?? 0), checksumSha256: result.ChecksumSHA256, etag: result.ETag, lastModified: result.LastModified, }; } catch (error) { if (isMissingKey(error)) return null; throw this.fail('head', error); } } async delete(key: string): Promise { try { await this.internal.send( new DeleteObjectCommand({ Bucket: this.bucket, Key: key }), ); } catch (error) { if (isMissingKey(error)) return; throw this.fail('delete', error); } } async presignPut(key: string, options: PresignPutOptions): Promise { return getSignedUrl( this.presign, new PutObjectCommand({ Bucket: this.bucket, Key: key, ContentType: options.contentType, ContentLength: options.contentLength, ChecksumSHA256: options.checksumSha256Base64, }), { expiresIn: options.expiresInSeconds, signableHeaders: new Set([ 'content-type', 'content-length', 'x-amz-checksum-sha256', ]), unhoistableHeaders: new Set(['x-amz-checksum-sha256']), }, ); } private fail(operation: string, error: unknown): Error { const name = (error as { name?: string })?.name ?? 'UnknownError'; this.logger.warn(`S3 ${operation} failed: ${name}`); return new ObjectStorageUnavailableError(); } }