import path from "node:path"; import { isDeployedEnv } from "@/config/env"; import { LocalPrivateStorage } from "./local"; import { createSupabaseStorage } from "./supabase"; import type { ObjectStorage } from "./memory"; let singleton: ObjectStorage | null = null; let singletonKey: string | null = null; /** * Armazenamento reutilizado pelo processo. O cliente Supabase mantém pool * de conexões HTTP: criar um por requisição desperdiça soquete. */ export function createStorage(): ObjectStorage { const url = process.env.NEXT_PUBLIC_SUPABASE_URL; const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; const bucket = process.env.SUPABASE_STORAGE_BUCKET; const key = `${url ?? ""}|${bucket ?? ""}|${serviceKey ? "svc" : "nosvc"}`; if (singleton && singletonKey === key) return singleton; if (url && serviceKey && bucket) { singletonKey = key; singleton = createSupabaseStorage(url, serviceKey, bucket); return singleton; } if (isDeployedEnv()) { throw new Error( "Armazenamento privado não configurado. Defina NEXT_PUBLIC_SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY e SUPABASE_STORAGE_BUCKET.", ); } singletonKey = key; singleton = new LocalPrivateStorage(path.join(process.cwd(), ".data", "storage")); return singleton; } /** Usado em testes para não vazar estado entre casos. */ export function resetStorage(): void { singleton = null; singletonKey = null; } export type { ObjectStorage };