Files
mtusi2026lab7/app/src/storage/object-storage.ts
T

360 lines
9.2 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 { SpanKind } from '@opentelemetry/api';
import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
Optional,
ServiceUnavailableException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import http from 'node:http';
import https from 'node:https';
import { Readable } from 'node:stream';
import type { AppConfig } from '../config/app-config.schema.js';
import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js';
import { TlsMaterialManager } from '../security/tls-material.js';
import { withChildSpan } from '../telemetry/tracing.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
);
}
function isS3AuthError(error: unknown): boolean {
const candidate = error as {
name?: string;
Code?: string;
$metadata?: { httpStatusCode?: number };
};
const code = candidate?.Code ?? candidate?.name ?? '';
return (
code === 'InvalidAccessKeyId' ||
code === 'SignatureDoesNotMatch' ||
code === 'AccessDenied' ||
code === 'ExpiredToken' ||
candidate?.$metadata?.httpStatusCode === 403
);
}
@Injectable()
export class ObjectStorage implements OnModuleDestroy {
private readonly logger = new Logger(ObjectStorage.name);
private readonly bucket: string;
private readonly endpoint: string;
private readonly publicEndpoint: string | undefined;
private readonly region: string;
private readonly connectTimeoutMs: number;
private readonly requestTimeoutMs: number;
private internal: S3Client;
private presign: S3Client | undefined;
private agent: http.Agent | https.Agent;
private readonly onTlsReload: () => void;
constructor(
private readonly config: ConfigService<AppConfig>,
@Optional() @Inject(TlsMaterialManager) private readonly tls?: TlsMaterialManager,
@Optional() @Inject(RuntimeSecretsStore) private readonly secrets?: RuntimeSecretsStore,
) {
this.bucket = config.getOrThrow('S3_BUCKET');
this.endpoint = config.getOrThrow('S3_ENDPOINT');
this.publicEndpoint =
typeof config.get === 'function'
? config.get('S3_PUBLIC_ENDPOINT')
: undefined;
this.region = config.getOrThrow('S3_REGION');
this.connectTimeoutMs = config.getOrThrow('S3_CONNECT_TIMEOUT_MS');
this.requestTimeoutMs = config.getOrThrow('S3_REQUEST_TIMEOUT_MS');
if (this.tls?.enabled && !this.endpoint.startsWith('https://')) {
throw new Error('S3_ENDPOINT must use https:// when TLS_ENABLED=true');
}
const built = this.createClients();
this.internal = built.internal;
this.presign = built.presign;
this.agent = built.agent;
this.onTlsReload = () => this.rebuildClients();
this.tls?.on('reloaded', this.onTlsReload);
}
onModuleDestroy(): void {
this.tls?.off('reloaded', this.onTlsReload);
this.internal.destroy();
this.presign?.destroy();
this.agent.destroy();
}
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 {
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,
}),
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> {
if (!this.presign) {
throw new Error(
'S3_PUBLIC_ENDPOINT is not configured for presigned uploads',
);
}
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 createClients(): {
internal: S3Client;
presign: S3Client | undefined;
agent: http.Agent | https.Agent;
} {
const useHttps = this.endpoint.startsWith('https://');
const agent = useHttps
? new https.Agent({
keepAlive: true,
maxSockets: 64,
...(this.tls?.ca ? { ca: this.tls.ca } : {}),
rejectUnauthorized: true,
minVersion: 'TLSv1.2',
})
: new http.Agent({ keepAlive: true, maxSockets: 64 });
const credentials = this.secrets
? async () => this.secrets!.getS3Credentials()
: {
accessKeyId: this.config.getOrThrow('S3_ACCESS_KEY_ID')!,
secretAccessKey: this.config.getOrThrow('S3_SECRET_ACCESS_KEY')!,
};
const common = {
region: this.region,
forcePathStyle: true,
credentials,
maxAttempts: 1,
requestChecksumCalculation: 'WHEN_REQUIRED' as const,
responseChecksumValidation: 'WHEN_REQUIRED' as const,
requestHandler: new NodeHttpHandler({
connectionTimeout: this.connectTimeoutMs,
requestTimeout: this.requestTimeoutMs,
throwOnRequestTimeout: true,
socketTimeout: this.requestTimeoutMs,
...(useHttps
? { httpsAgent: agent as https.Agent }
: { httpAgent: agent as http.Agent }),
}),
};
const internal = new S3Client({
...common,
endpoint: this.endpoint,
});
internal.middlewareStack.add(
(next, handlerContext) => async (args) => {
const operation = String(
handlerContext.commandName ?? 'Unknown',
).replace(/Command$/u, '');
return withChildSpan(
`S3.${operation}`,
SpanKind.CLIENT,
{
'rpc.system': 'aws-api',
'rpc.service': 'S3',
'rpc.method': operation,
'aws.s3.bucket': this.bucket,
},
() => next(args),
);
},
{ step: 'initialize', name: 'messengerTelemetry' },
);
const presign = this.publicEndpoint
? new S3Client({
...common,
endpoint: this.publicEndpoint,
})
: undefined;
return { internal, presign, agent };
}
private rebuildClients(): void {
try {
const next = this.createClients();
const oldInternal = this.internal;
const oldPresign = this.presign;
const oldAgent = this.agent;
this.internal = next.internal;
this.presign = next.presign;
this.agent = next.agent;
oldInternal.destroy();
oldPresign?.destroy();
oldAgent.destroy();
this.logger.log('Rebuilt S3 clients with updated TLS material');
} catch (error) {
this.logger.warn(
`S3 client rebuild failed: ${error instanceof Error ? error.name : 'unknown error'}`,
);
}
}
private fail(operation: string, error: unknown): Error {
if (isS3AuthError(error)) {
void this.secrets?.refreshNow('s3_auth_error');
}
const name = (error as { name?: string })?.name ?? 'UnknownError';
this.logger.warn(`S3 ${operation} failed: ${name}`);
return new ObjectStorageUnavailableError();
}
}