panels-origin/api/storage.ts
Cursor Agent 1ac04996b6
ops: generar accesos por ambiente y verificar Postgres, Redis y Contabo
Scripts create-accesses / verify-connectivity para un Postgres+Redis+bucket
por ambiente. /v1/health y el arranque de la API incluyen sonda de storage.

Co-authored-by: alberto.martinez <alberto.martinez@mrdev.mx>
2026-09-02 21:22:39 +00:00

144 lines
4.9 KiB
TypeScript

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: 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;
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<StoragePing> {
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<void> {
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,
forcePathStyle: true,
credentials: {
accessKeyId: config.s3AccessKeyId,
secretAccessKey: config.s3SecretAccessKey,
},
});
}
return client;
}
async function streamToUint8Array(body: unknown): Promise<Uint8Array> {
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<void> {
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<Uint8Array> {
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}`;
}