Files
mtusi2026lab4/src/storage/s3.service.ts
T

93 lines
2.5 KiB
TypeScript

import {
DeleteObjectCommand,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3';
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { createReadStream, readFileSync } from 'fs';
import { ApiError } from '../common/filters/api-error';
const CONNECT_TIMEOUT_MS = 1000;
const IDLE_TIMEOUT_MS = 5000;
const OPERATION_TIMEOUT_MS = 20000;
export interface StoredFile {
key: string;
path: string;
size: number;
contentType: string;
sha256: string;
}
@Injectable()
export class S3Service implements OnModuleDestroy {
private readonly logger = new Logger('S3Service');
private readonly client: S3Client;
private readonly bucket = process.env.S3_BUCKET ?? 'messenger-attachments';
constructor() {
this.client = new S3Client({
endpoint: process.env.S3_ENDPOINT ?? 'http://s3:9000',
region: process.env.S3_REGION ?? 'us-east-1',
forcePathStyle: true,
maxAttempts: 1,
credentials: {
accessKeyId: readSecret('S3_ACCESS_KEY_ID'),
secretAccessKey: readSecret('S3_SECRET_ACCESS_KEY'),
},
requestHandler: {
connectionTimeout: CONNECT_TIMEOUT_MS,
requestTimeout: IDLE_TIMEOUT_MS,
},
});
}
async putFile(file: StoredFile): Promise<void> {
await this.guard(`put ${file.key}`, () =>
this.client.send(
new PutObjectCommand({
Bucket: this.bucket,
Key: file.key,
Body: createReadStream(file.path),
ContentLength: file.size,
ContentType: file.contentType,
ChecksumSHA256: Buffer.from(file.sha256, 'hex').toString('base64'),
}),
{ abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) },
),
);
}
async delete(key: string): Promise<void> {
await this.guard(`delete ${key}`, () =>
this.client.send(
new DeleteObjectCommand({ Bucket: this.bucket, Key: key }),
{ abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) },
),
);
}
onModuleDestroy(): void {
this.client.destroy();
}
private async guard<T>(action: string, run: () => Promise<T>): Promise<T> {
try {
return await run();
} catch (error) {
const reason = error instanceof Error ? error.name : 'unknown error';
this.logger.error(`${action} failed: ${reason}`);
throw new ApiError('unavailable', 'object storage unavailable');
}
}
}
function readSecret(name: string): string {
const file = process.env[`${name}_FILE`];
const value = file ? readFileSync(file, 'utf8').trim() : process.env[name];
if (!value) {
throw new Error(`${name}_FILE or ${name} must be set`);
}
return value;
}