import path from "path"; import { globalEnv } from "./globalEnv.js"; import BaseDiskCache from "@entity-access/server-pages/dist/cache/BaseDiskCache.js"; import { hash } from "crypto"; const tmpdir = path.join(globalEnv.tmpDir, "t-json"); export const dnsDiskCache = new BaseDiskCache({ root: tmpdir, keepTTLSeconds: 15 * 60, maxAge: 5, minAge: 1 }); export function jsonCache({ ttlSecondsFailed = (e) => 60000 as number } = {}) { return function(target, key) { const oldMethod = target[key] as (... a: any[]) => any; async function value(... a: any[]) { const cacheKey = `${target.constructor.name}/${key}/${hash("sha256", a.join(), "hex")}`; for(;;) { const r = await dnsDiskCache.getOrCreateJsonAsync<{ result?, error?, ttl? }>(cacheKey, async () => { try { return { result: await oldMethod.apply(this, a) as Promise }; } catch (error) { const errors = []; const cause = error?.cause; if (cause ) { errors.push(cause.stack ?? cause); } errors.push(error.stack ?? error); return { error: errors.join() , ttl: Date.now() + (ttlSecondsFailed(error) * 1000) }; } }); if (r.result) { return r.result; } if(r.ttl < Date.now()) { // delete error and lets retry... await dnsDiskCache.deleteAt(cacheKey); continue; } // if error is older than 1 minute... retry... throw new Error(r.error); } } const d = { value, enumerable: true, configurable: true }; Object.defineProperty(target, key, d); return d; }; }