import { S3Client, PutObjectCommand, GetObjectCommand } from "npm:@aws-sdk/client-s3@3"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { config, DATA_DIR } from "./config.ts"; /** * Almacenamiento de archivos (Fase 4c): expedientes cifrados, PDFs de * gafetes, logos. Antes vivían en el volumen local (panel-data) -- un * volumen local no se comparte entre réplicas ni microservicios, así que * es el mismo cuello de botella que motivó salir de SQLite, solo que en * otra capa. El contenido YA viene cifrado con AES-GCM (docs_crypto.ts) * antes de llegar aquí -- el bucket nunca ve texto plano. * * Backend real: Contabo Object Storage (S3-compatible). Si no hay * credenciales S3 configuradas (dev local sin Contabo), cae a disco local * bajo DATA_DIR -- útil para desarrollar/probar sin depender de Contabo, * pero NO es la ruta recomendada para staging/producción (ver Fase 4c del * plan: un volumen local no escala horizontalmente). */ let client: S3Client | null = null; function s3Configured(): boolean { return !!(config.s3Endpoint && config.s3Bucket && config.s3AccessKeyId && config.s3SecretAccessKey); } function getClient(): S3Client { if (!client) { client = new S3Client({ endpoint: config.s3Endpoint, region: config.s3Region, forcePathStyle: true, credentials: { accessKeyId: config.s3AccessKeyId, secretAccessKey: config.s3SecretAccessKey, }, }); } return client; } async function streamToUint8Array(body: unknown): Promise { const chunks: Uint8Array[] = []; // deno-lint-ignore no-explicit-any for await (const chunk of body as any) { chunks.push(chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk)); } const total = chunks.reduce((n, c) => n + c.length, 0); const out = new Uint8Array(total); let offset = 0; for (const c of chunks) { out.set(c, offset); offset += c.length; } return out; } export async function putObject(key: string, bytes: Uint8Array): Promise { if (s3Configured()) { await getClient().send( new PutObjectCommand({ Bucket: config.s3Bucket, Key: key, Body: bytes }), ); return; } const path = join(DATA_DIR, "local-objects", key); await mkdir(dirname(path), { recursive: true }); await writeFile(path, bytes); } export async function getObject(key: string): Promise { if (s3Configured()) { const res = await getClient().send( new GetObjectCommand({ Bucket: config.s3Bucket, Key: key }), ); return await streamToUint8Array(res.Body); } const path = join(DATA_DIR, "local-objects", key); return await readFile(path); } // --- Convenciones de key por dominio (equivalentes a los antiguos // workerDir/projectDir/companyDir + Deno.readFile/writeFile) --- export function workerDocKey(workerId: number, storageName: string): string { return `expedientes/${workerId}/${storageName}`; } export function projectDocKey(projectId: number, storageName: string): string { return `proyectos/${projectId}/${storageName}`; } export function companyDocKey(companyId: number, storageName: string): string { return `empresas/${companyId}/${storageName}`; } export function badgeJobPdfKey(jobId: number): string { return `pdfs/gafetes-${jobId}.pdf`; } export function loanReceiptPdfKey(loanId: number, weekId: number): string { return `pdfs/prestamo-${loanId}-semana-${weekId}.pdf`; } export function projectLogoKey(projectId: number, side: "left" | "right", ext: string): string { return `logos/${projectId}-${side}.${ext}`; }