import { S3Client, PutObjectCommand, GetObjectCommand, HeadBucketCommand, DeleteObjectCommand, } 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: S3-compatible (Cloudflare R2). Si no hay credenciales S3 * (dev local), cae a disco bajo DATA_DIR. En staging/producción el volumen * local no escala: hay que configurar S3_*. */ let client: S3Client | null = null; export function s3Configured(): boolean { return !!(config.s3Endpoint && config.s3Bucket && config.s3AccessKeyId && config.s3SecretAccessKey); } export type StoragePing = { configured: boolean; ok: boolean; backend: "s3" | "local"; }; /** HeadBucket (S3) o escritura de prueba en disco local. */ export async function pingStorage(): Promise { if (!s3Configured()) { try { await mkdir(join(DATA_DIR, "local-objects"), { recursive: true }); return { configured: false, ok: true, backend: "local" }; } catch { return { configured: false, ok: false, backend: "local" }; } } try { await getClient().send(new HeadBucketCommand({ Bucket: config.s3Bucket })); return { configured: true, ok: true, backend: "s3" }; } catch { return { configured: true, ok: false, backend: "s3" }; } } /** Put + get + delete de un objeto sonda. No dejar basura en el bucket. */ export async function probeStorageReadWrite(): Promise { const key = `_panels/connectivity-probe-${crypto.randomUUID()}`; const payload = new TextEncoder().encode("panels-connectivity-probe"); await putObject(key, payload); const got = await getObject(key); if (new TextDecoder().decode(got) !== "panels-connectivity-probe") { throw new Error("El objeto sonda no coincide con lo escrito"); } if (s3Configured()) { await getClient().send(new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key })); } } function getClient(): S3Client { if (!client) { client = new S3Client({ endpoint: config.s3Endpoint, region: config.s3Region || "auto", forcePathStyle: true, // R2 no implementa los checksums CRC32 que el SDK v3 manda por defecto. requestChecksumCalculation: "WHEN_REQUIRED", responseChecksumValidation: "WHEN_REQUIRED", 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}`; }