feat: add attachment download and message attachment links

This commit is contained in:
2026-11-05 15:23:15 +03:00
parent fa0211eecb
commit f523cad721
10 changed files with 486 additions and 17 deletions
+33 -1
View File
@@ -1,10 +1,12 @@
import {
DeleteObjectCommand,
GetObjectCommand,
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;
@@ -23,10 +25,11 @@ export interface StoredFile {
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() {
this.client = new S3Client({
const config = {
endpoint: process.env.S3_ENDPOINT ?? 'http://s3:9000',
region: process.env.S3_REGION ?? 'us-east-1',
forcePathStyle: true,
@@ -35,11 +38,18 @@ export class S3Service implements OnModuleDestroy {
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> {
@@ -58,6 +68,27 @@ export class S3Service implements OnModuleDestroy {
);
}
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 delete(key: string): Promise<void> {
await this.guard(`delete ${key}`, () =>
this.client.send(
@@ -69,6 +100,7 @@ export class S3Service implements OnModuleDestroy {
onModuleDestroy(): void {
this.client.destroy();
this.streamClient.destroy();
}
private async guard<T>(action: string, run: () => Promise<T>): Promise<T> {