import { getPool } from "../../db/index.js"; // Lockless: concurrent cold misses may both compute, last writer wins. export async function getCached(userId, tag, ttlMs, compute) { let client = await getPool(); try { const hit = ( await client.query( `SELECT data FROM cache WHERE user_id = $1 AND tag = $2 AND updated_ts > NOW() - ($3 * interval '1 millisecond')`, [userId, tag, ttlMs], ) ).rows[0]; if (hit) return hit.data; } finally { await client.release(); } const data = await compute(); client = await getPool(); try { await client.query( `INSERT INTO cache (user_id, tag, data) VALUES ($1, $2, $3::jsonb) ON CONFLICT (user_id, tag) DO UPDATE SET data = EXCLUDED.data, updated_ts = NOW()`, [userId, tag, data], ); } finally { await client.release(); } return data; }