Speed (same fixes as InstantAdPay): catalog reads in parallel + stale-while-revalidate /api/catalog, positions read side by side, member reads cached 15 s (cleared on every new chain event)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-20 05:21:48 -05:00
parent a9994e708d
commit 693a539503
2 changed files with 29 additions and 18 deletions
+18 -9
View File
@@ -138,7 +138,16 @@ async function memberIdByAccount(addr) {
}
async function memberCount() { return toNum(word(await call(SEL.memberCount), 0)); }
async function productCount() { return toNum(word(await call(SEL.productCount), 0)); }
// member reads are cached 15 s (2026-10-20): dashboards ask for the same members many times a minute and every read is
// an RPC round trip; sponsor never changes and a buyer count up to 15 s old is fine for display
const memberCache = new Map();
async function member(id) {
const hit = memberCache.get(Number(id)); if (hit && Date.now() - hit.at < 15000) return hit.v;
const v = await memberRead(id); memberCache.set(Number(id), { at: Date.now(), v });
if (memberCache.size > 5000) memberCache.clear();
return v;
}
async function memberRead(id) {
const r = await call(SEL.members, [id]);
return { account: toAddr(word(r, 0)), sponsorId: toNum(word(r, 1)), buyerCount: toNum(word(r, 2)),
activated: toNum(word(r, 3)) === 1, countedAsBuyer: toNum(word(r, 4)) === 1 };
@@ -151,15 +160,15 @@ async function product(id) {
async function quoteWei(id) { try { return toBig(word(await call(SEL.quoteWei, [id]), 0)); } catch (e) { return null; } }
async function creditBalance(id, type) { return Number(toBig(word(await call(SEL.creditBalance, [id, type || 0]), 0))); }
async function catalog() {
// products and quotes are read side by side, not one after another (2026-10-20, same fix as InstantAdPay)
const n = await productCount();
const out = [];
for (let i = 1; i <= n; i++) {
const p = await product(i);
if (!p.exists || !p.active) continue;
const q = await quoteWei(i);
out.push(Object.assign(p, { costWei: q === null ? null : q.toString() }));
}
return out;
const ids = Array.from({ length: n }, (_, k) => k + 1);
const rows = await Promise.all(ids.map(async i => {
const [p, q] = await Promise.all([product(i), quoteWei(i)]);
if (!p.exists || !p.active) return null;
return Object.assign(p, { costWei: q === null ? null : q.toString() });
}));
return rows.filter(Boolean);
}
// ---- event decode ----
@@ -231,7 +240,7 @@ async function tail() {
const ev = decodeLog(lg);
if (!ev) continue;
ev.ts = Date.now(); // indexed-at time: powers honest time-series charts
state.events.push(ev);
state.events.push(ev); memberCache.clear(); // a new chain event can change any member: drop the 15 s read cache
tally(ev);
if (onEvent) { try { onEvent(ev); } catch (e) { console.error('chain onEvent', e.message); } }
}