forked from mtusi2026/mtusi2026lab5
246 lines
6.4 KiB
TypeScript
246 lines
6.4 KiB
TypeScript
import {
|
|
DeleteObjectCommand,
|
|
GetObjectCommand,
|
|
HeadBucketCommand,
|
|
ListObjectsV2Command,
|
|
PutObjectCommand,
|
|
S3Client,
|
|
} from '@aws-sdk/client-s3';
|
|
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
|
import { createReadStream, readFileSync } from 'fs';
|
|
import { Readable } from 'stream';
|
|
import { ApiError } from '../common/filters/api-error';
|
|
|
|
const CONNECT_TIMEOUT_MS = 1000;
|
|
const IDLE_TIMEOUT_MS = 5000;
|
|
const OPERATION_TIMEOUT_MS = 20000;
|
|
const HEALTH_TIMEOUT_MS = 1000;
|
|
|
|
export interface ObjectPage {
|
|
objects: { key: string; lastModified: Date }[];
|
|
nextToken?: string;
|
|
}
|
|
|
|
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 streamClient: S3Client;
|
|
private readonly bucket = process.env.S3_BUCKET ?? 'messenger-attachments';
|
|
|
|
constructor() {
|
|
const config = {
|
|
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'),
|
|
},
|
|
};
|
|
this.client = new S3Client({
|
|
...config,
|
|
requestHandler: {
|
|
connectionTimeout: CONNECT_TIMEOUT_MS,
|
|
requestTimeout: IDLE_TIMEOUT_MS,
|
|
},
|
|
});
|
|
this.streamClient = new S3Client({
|
|
...config,
|
|
requestHandler: { connectionTimeout: CONNECT_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 putBuffer(
|
|
key: string,
|
|
body: Buffer,
|
|
contentType: string,
|
|
sha256: string,
|
|
): Promise<void> {
|
|
await this.guard(`put ${key}`, () =>
|
|
this.client.send(
|
|
new PutObjectCommand({
|
|
Bucket: this.bucket,
|
|
Key: key,
|
|
Body: body,
|
|
ContentLength: body.length,
|
|
ContentType: contentType,
|
|
ChecksumSHA256: Buffer.from(sha256, 'hex').toString('base64'),
|
|
}),
|
|
{ abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) },
|
|
),
|
|
);
|
|
}
|
|
|
|
async getBuffer(key: string, maxBytes: number): Promise<Buffer> {
|
|
let body: Readable;
|
|
try {
|
|
const response = await this.client.send(
|
|
new GetObjectCommand({ Bucket: this.bucket, Key: key }),
|
|
{ abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) },
|
|
);
|
|
if ((response.ContentLength ?? 0) > maxBytes) {
|
|
throw new ObjectTooLargeError(key);
|
|
}
|
|
body = response.Body as Readable;
|
|
} catch (error) {
|
|
if (error instanceof ObjectTooLargeError) {
|
|
throw error;
|
|
}
|
|
const name = error instanceof Error ? error.name : 'unknown error';
|
|
this.logger.error(`get ${key} failed: ${name}`);
|
|
if (name === 'NoSuchKey') {
|
|
throw new ObjectMissingError(key);
|
|
}
|
|
throw new ApiError('unavailable', 'object storage unavailable');
|
|
}
|
|
const chunks: Buffer[] = [];
|
|
let size = 0;
|
|
try {
|
|
for await (const chunk of body) {
|
|
size += chunk.length;
|
|
if (size > maxBytes) {
|
|
body.destroy();
|
|
throw new ObjectTooLargeError(key);
|
|
}
|
|
chunks.push(chunk);
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof ObjectTooLargeError) {
|
|
throw error;
|
|
}
|
|
throw new ApiError('unavailable', 'object storage unavailable');
|
|
}
|
|
return Buffer.concat(chunks);
|
|
}
|
|
|
|
async getStream(key: string): Promise<Readable> {
|
|
const deadline = new AbortController();
|
|
const timer = setTimeout(() => deadline.abort(), IDLE_TIMEOUT_MS);
|
|
try {
|
|
const { Body } = await this.streamClient.send(
|
|
new GetObjectCommand({ Bucket: this.bucket, Key: key }),
|
|
{ abortSignal: deadline.signal },
|
|
);
|
|
return Body as Readable;
|
|
} catch (error) {
|
|
const name = error instanceof Error ? error.name : 'unknown error';
|
|
this.logger.error(`get ${key} failed: ${name}`);
|
|
if (name === 'NoSuchKey') {
|
|
throw new Error(`object ${key} is missing from storage`);
|
|
}
|
|
throw new ApiError('unavailable', 'object storage unavailable');
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
async isAvailable(): Promise<boolean> {
|
|
try {
|
|
await this.client.send(new HeadBucketCommand({ Bucket: this.bucket }), {
|
|
abortSignal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
|
|
});
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async listObjects(
|
|
prefix: string,
|
|
pageSize: number,
|
|
token?: string,
|
|
): Promise<ObjectPage> {
|
|
const page = await this.guard(`list ${prefix}`, () =>
|
|
this.client.send(
|
|
new ListObjectsV2Command({
|
|
Bucket: this.bucket,
|
|
Prefix: prefix,
|
|
MaxKeys: pageSize,
|
|
ContinuationToken: token,
|
|
}),
|
|
{ abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) },
|
|
),
|
|
);
|
|
return {
|
|
objects: (page.Contents ?? []).map((object) => ({
|
|
key: object.Key!,
|
|
lastModified: object.LastModified!,
|
|
})),
|
|
nextToken: page.NextContinuationToken,
|
|
};
|
|
}
|
|
|
|
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();
|
|
this.streamClient.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');
|
|
}
|
|
}
|
|
}
|
|
|
|
export class ObjectMissingError extends Error {
|
|
constructor(key: string) {
|
|
super(`object ${key} is missing from storage`);
|
|
this.name = 'ObjectMissingError';
|
|
}
|
|
}
|
|
|
|
export class ObjectTooLargeError extends Error {
|
|
constructor(key: string) {
|
|
super(`object ${key} exceeds size limit`);
|
|
this.name = 'ObjectTooLargeError';
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|