Files
mtusi2026lab6/app/src/storage/object-storage.ts
T
ilya.tyunin 6889e77ab4 lab6: базовый коммит из lab5 (0790599)
Перенесено дерево lab5 целиком: NestJS-приложение (API + worker,
RabbitMQ, outbox, S3), Dockerfile, compose.yaml, infra/{haproxy,minio,
rabbitmq}, стендовые скрипты, scripts/lab4, scripts/lab5,
evidence/lab4, evidence/lab5 и contracts/extensions.openapi.json.

Задание lab6 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,
examples,observability}, tests, compose.example.yaml, infra/otel,
.github/pull_request_template.md.

Адаптации при переносе:
- docker-проект mtusi-lab5 -> mtusi-lab6 и тег образа
  mtusi-messenger:lab6 (compose.yaml, scripts/stop-one.sh, .env.example,
  infra/README.md), чтобы тома и контейнеры не пересекались с lab5;
- Makefile: цели lab5 сохранены целиком (skeleton lab6 не отличается
  от skeleton lab5);
- .env.example: переменные приложения и стенда lab5 + блок lab6
  (OTEL_*) из skeleton.
2026-11-09 16:44:21 +03:00

234 lines
6.3 KiB
TypeScript

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<AppConfig>) {
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<void> {
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<void> {
await this.putStream(
key,
Readable.from([data]),
data.length,
contentType,
signal,
);
}
async getStream(
key: string,
signal?: AbortSignal,
): Promise<Readable | null> {
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<void> {
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<string> {
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();
}
}