chore: support standard S3 environment variables and external storage providers like RustFS

This commit is contained in:
Erik
2026-03-07 20:07:22 -03:00
parent 570536132b
commit a76e0ebfc0

View File

@@ -1,22 +1,27 @@
import { S3Client, HeadBucketCommand, CreateBucketCommand, PutBucketPolicyCommand, PutObjectCommand, DeleteObjectCommand, GetObjectCommand, ListObjectsV2Command } from '@aws-sdk/client-s3'; import { S3Client, HeadBucketCommand, CreateBucketCommand, PutBucketPolicyCommand, PutObjectCommand, DeleteObjectCommand, GetObjectCommand, ListObjectsV2Command } from '@aws-sdk/client-s3';
const endpointHost = process.env.MINIO_ENDPOINT || 'localhost'; // Prioriza as novas variáveis S3_*, mas mantém MINIO_* para compatibilidade
const port = Number.parseInt(process.env.MINIO_PORT || '9000', 10); const endpointHost = process.env.S3_ENDPOINT || process.env.MINIO_ENDPOINT || 'localhost';
const useSSL = process.env.MINIO_USE_SSL === 'true'; const port = Number.parseInt(process.env.S3_PORT || process.env.MINIO_PORT || '9000', 10);
const useSSL = (process.env.S3_USE_SSL || process.env.MINIO_USE_SSL) === 'true';
const protocol = useSSL ? 'https' : 'http'; const protocol = useSSL ? 'https' : 'http';
const endpointUrl = `${protocol}://${endpointHost}:${port}`;
console.log(`[MinIO] Configurando cliente: ${endpointHost}:${port} (SSL: ${useSSL})`); // Para S3 externos (como RustFS), o endpointUrl pode não precisar da porta se for padrão (80/443)
const endpointUrl = (port === 80 || port === 443)
? `${protocol}://${endpointHost}`
: `${protocol}://${endpointHost}:${port}`;
export const bucketName = process.env.MINIO_BUCKET_NAME || 'occto-images'; console.log(`[S3/MinIO] Configurando cliente: ${endpointUrl} (SSL: ${useSSL})`);
export const bucketName = process.env.S3_BUCKET_NAME || process.env.MINIO_BUCKET_NAME || 'occto-images';
export const s3Client = new S3Client({ export const s3Client = new S3Client({
region: 'us-east-1', region: 'us-east-1',
endpoint: endpointUrl, endpoint: endpointUrl,
forcePathStyle: true, forcePathStyle: true,
credentials: { credentials: {
accessKeyId: process.env.MINIO_ACCESS_KEY || 'admin', accessKeyId: process.env.S3_ACCESS_KEY || process.env.MINIO_ACCESS_KEY || 'admin',
secretAccessKey: process.env.MINIO_SECRET_KEY || 'adminpassword', secretAccessKey: process.env.S3_SECRET_KEY || process.env.MINIO_SECRET_KEY || 'adminpassword',
}, },
}); });
@@ -42,6 +47,7 @@ export const minioClient = {
} catch (error: unknown) { } catch (error: unknown) {
const err = error as { $metadata?: { httpStatusCode?: number } }; const err = error as { $metadata?: { httpStatusCode?: number } };
if (err?.$metadata?.httpStatusCode === 404) return false; if (err?.$metadata?.httpStatusCode === 404) return false;
if (err?.$metadata?.httpStatusCode === 403) return true; // Sem permissão para HeadBucket, mas pode existir
if (err?.$metadata?.httpStatusCode === 301) return true; // Bucket existe mas outra região if (err?.$metadata?.httpStatusCode === 301) return true; // Bucket existe mas outra região
throw error; throw error;
} }
@@ -60,7 +66,11 @@ export const minioClient = {
}, },
async setBucketPolicy(bucket: string, policy: string) { async setBucketPolicy(bucket: string, policy: string) {
try {
await s3Client.send(new PutBucketPolicyCommand({ Bucket: bucket, Policy: policy })); await s3Client.send(new PutBucketPolicyCommand({ Bucket: bucket, Policy: policy }));
} catch (error) {
console.warn('Aviso: Não foi possível definir a política do bucket. Verifique as permissões do seu provedor S3.', error);
}
}, },
async putObject(bucket: string, key: string, body: Buffer | Uint8Array | string, size?: number, metadata?: MetadataMap) { async putObject(bucket: string, key: string, body: Buffer | Uint8Array | string, size?: number, metadata?: MetadataMap) {
@@ -96,6 +106,7 @@ export async function ensureBucketExists() {
try { try {
const exists = await minioClient.bucketExists(bucketName); const exists = await minioClient.bucketExists(bucketName);
if (!exists) { if (!exists) {
console.log(`Tentando criar o bucket ${bucketName}...`);
await minioClient.makeBucket(bucketName); await minioClient.makeBucket(bucketName);
const policy = { const policy = {
@@ -114,6 +125,6 @@ export async function ensureBucketExists() {
console.log(`Bucket ${bucketName} criado e política pública aplicada.`); console.log(`Bucket ${bucketName} criado e política pública aplicada.`);
} }
} catch (error) { } catch (error) {
console.error('Erro ao garantir existência do bucket MinIO:', error); console.error('Erro ao garantir existência do bucket S3:', error);
} }
} }