Files
instantadpay/tankready.js
T
martbost 52f0a5496b Holding-tank readiness on the tank cards (Marty 2026-11-18, warm-up stage 1, no email)
Each waiting lead on My line > Holding tank and Admin > Members tank card now shows how they got into the tank, a stage chip (New / Warming / Engaged / Activated / Ready, real actions only), the network heat score 0-100 with its band, and their last real action. Computed on the network hub (POST /v1/tank/readiness); tankready.js sends this site's facts (own last sign-in, wallet, entry reason from the adoption records and join data; sponsor usernames, never emails) and caches the answer. Tank list sorts hottest first by default (grace and ready-to-activate grouping unchanged), new Heat sort and "Warm or hot" filter on the tank only. Hub down = the card exactly as before. No mail, no Telegram, no sponsor moves; adoption rules, caps and the v2 batch untouched. qa/tank-readiness.test.mjs (against a local hub) added to member + tankhold. tankready.js?v=20261118rd, my.js / admin.js / site.css ?v=20261118rd. iap-qa member ALL PASSED.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:01:46 -06:00

126 lines
8.5 KiB
JavaScript

'use strict';
// Holding-tank readiness (Marty 2026-11-18, stage 1 of the tank warm-up; review page claude.ai/artifact/76vTtcB67KJNopG3KZu5ca).
// What an adopting sponsor sees on each waiting lead: how they got into the tank, how far along they are (New, Warming, Engaged,
// Activated, Ready), a 0-100 heat score with its band, and their last real action. The network hub computes it
// (POST <hub>/v1/tank/readiness, the one heat formula in network-hub lib/heat.js); this module sends the hub what only this
// site knows (its own last sign-in, a linked wallet, and the entry reason from its adoption records and join data) and keeps
// the answer in memory for the tank card.
//
// NO EMAIL, NO MESSAGE, NO SPONSOR CHANGE: read-only here; the hub stores only the entry fact. The hub down = no extras, the tank
// card works exactly as before. The same file runs on InstantAdPay and LinkSpin (deps.site names the site; copy changes to both).
const crypto = require('crypto');
const FRESH_MS = 5 * 60 * 1000; // a cached answer this young is used as is
const STALE_MS = 6 * 3600 * 1000; // an older one is still shown while a refresh runs, never past this
const DOWN_MS = 2 * 60 * 1000; // the hub failed: no new try for this long
let R = null; // deps: { site, accounts, tank, followGet(email) }
let cache = { at: 0, by: new Map() }; let busy = null; let downUntil = 0; let last = { at: 0, ok: null, n: 0, ms: 0, error: null, recorded: 0 };
const on = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_ENABLED || '')) && String(process.env.HUB_READINESS || '1') !== '0'
&& !!process.env.HUB_URL && String(process.env.HUB_SECRET || '').length >= 32 && typeof fetch === 'function';
const lc = v => String(v || '').trim().toLowerCase();
function init(deps) { R = deps; }
async function hubPost(p, body, timeout) {
const raw = JSON.stringify(body); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', process.env.HUB_SECRET).update(ts + '\n' + raw).digest('hex');
const r = await fetch(String(process.env.HUB_URL).replace(/\/+$/, '') + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': process.env.HUB_SITE || R.site, 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeout || 20000) });
let j = null; try { j = await r.json(); } catch (e) {}
if (r.status !== 200) throw new Error('hub ' + p + ' ' + r.status + (j && j.error ? ' ' + j.error : ''));
return j;
}
// ── how they got into the tank, from this site's own records ──
// adoption history (tank.historyMap: newest 6 per person: adopter, ts, status, closed, note), the sponsor-follow record (a move
// made on the other platform), and the join data. Sponsor emails never leave the site: a username, or nothing.
const ENTRY_STATUS = { rescued: 'rescued', released: 'released', dropped: 'released', expired: 'returned', unreached: 'returned' };
const LATER = new Set(['open', 'done', 'invited', 'gift', 'moved', 'conflict']); // a sponsor came after: that entry is over
const FOLLOW_BY = { rescue: 'rescued', release: 'released', expire: 'returned', expiry: 'returned' };
const IMPORTS = { btc4hits: 'BTC4Hits', faucetwave: 'FaucetWave', socialpix: 'SocialPix' };
async function nameOfEmail(email) {
if (!email || String(email).startsWith('dead:')) return null;
try { const a = await R.accounts.byEmail(lc(email)); return a && a.username ? a.username : null; } catch (e) { return null; }
}
async function localEntry(a, hist, pv) {
const rows = (hist || []).slice().sort((x, y) => (x.closed || x.ts || 0) - (y.closed || y.ts || 0));
let best = null;
for (const h of rows) {
if (ENTRY_STATUS[h.status]) {
const dead = h.status === 'rescued' && String(h.adopter || '').startsWith('dead:');
best = { reason: dead ? 'sponsor_gone' : ENTRY_STATUS[h.status], at: Number(h.status === 'rescued' || h.status === 'released' ? h.ts : (h.closed || h.ts)) || 0, adopter: h.adopter, status: h.status };
} else if (LATER.has(h.status) && best && (h.ts || 0) >= best.at) best = null;
}
// a move made on the other platform that left them with no sponsor here (sponsorfollow), when newer
if (pv && !pv.sponsorEmail && FOLLOW_BY[pv.by] && Number(pv.at) > (best ? best.at : 0)) best = { reason: FOLLOW_BY[pv.by], at: Number(pv.at), adopter: pv.prevEmail || null, site: ({ instantadpay: 'iap', linkspin: 'linkspin' })[lc(pv.origin)] || null };
if (best) {
const from = best.reason === 'sponsor_gone' ? null : await nameOfEmail(best.adopter);
const detail = {}; if (from) detail.from = from;
if (best.reason === 'sponsor_gone') detail.note = 'their sponsor link no longer leads to a member';
if (best.status === 'dropped') detail.note = 'released by the member who adopted them';
return { reason: best.reason, at: best.at, site: best.site || undefined, detail };
}
const via = lc(a.joinedVia); const ref = lc(a.joinedRef);
if (via === 'hub') return null; // made here for someone who joined elsewhere on the network: the hub knows their first door
if ((via === 'linkspin' || via === 'instantadpay' || via === 'carried') && ref !== 'btc4hits') return null; // a copy of an account from the other platform (LinkSpin: 'carried'): same, the hub knows
const leg = /^legacy:([a-z0-9]+)/.exec(ref);
if (via === 'btc4hits' || ref === 'btc4hits') return { reason: 'imported', at: Number(a.created) || 0, detail: { oldSite: 'BTC4Hits' } };
if (leg) return { reason: 'imported', at: Number(a.created) || 0, detail: { oldSite: IMPORTS[leg[1]] || leg[1] } };
const detail = {}; if (via) detail.via = via; if (ref && !/^hub:/.test(ref)) detail.ref = ref.slice(0, 80);
return { reason: 'joined', at: Number(a.created) || 0, detail };
}
// one call for the whole waiting list (a few thousand rows at most)
async function refresh() {
if (!R || !on()) return null;
if (busy) return busy;
busy = (async () => {
const t0 = Date.now();
try {
const list = await R.tank.waiting();
const hist = R.tank.historyMap ? await R.tank.historyMap() : new Map();
const accts = new Map();
const rows = [];
for (const w of list) {
const a = (await R.accounts.byEmail(w.email)) || { email: w.email, created: w.joined };
accts.set(w.email, a);
let pv = null; try { pv = R.followGet ? R.followGet(w.email) : null; } catch (e) {}
rows.push({ email: w.email, seenAt: w.lastSeen || 0, wallet: !!w.wallet, entry: await localEntry(a, hist.get(w.email), pv) || undefined });
}
const r = rows.length ? await hubPost('/v1/tank/readiness', { rows }, 30000) : { rows: [] };
const by = new Map();
for (const x of (r.rows || [])) { const src = rows[x.i]; if (src) by.set(src.email, { entry: x.entry, stage: x.stage, heat: x.heat, last: x.last, onHub: !!x.onHub }); }
cache = { at: Date.now(), by };
last = { at: Date.now(), ok: true, n: by.size, ms: Date.now() - t0, error: null, recorded: r.recorded || 0 };
return cache;
} catch (e) {
downUntil = Date.now() + DOWN_MS; last = { at: Date.now(), ok: false, n: 0, ms: Date.now() - t0, error: e.message, recorded: 0 };
console.error('tankready', e.message);
return null;
} finally { busy = null; }
})();
return busy;
}
// the readiness for these waiting rows, as rows with `rd` added. Waits for the hub only when nothing usable is cached, and then
// at most `waitMs`; otherwise answers from the cache and refreshes in the background.
async function attach(list, waitMs) {
if (!R || !on() || !Array.isArray(list)) return list;
const age = Date.now() - cache.at;
if (age > FRESH_MS && Date.now() > downUntil) {
const p = refresh();
if (age > STALE_MS && p) await Promise.race([p, new Promise(res => setTimeout(res, waitMs || 4000))]);
}
if (Date.now() - cache.at > STALE_MS) return list;
return list.map(w => { const x = cache.by.get(w.email); return x ? Object.assign({}, w, { rd: x }) : w; });
}
const status = () => Object.assign({ on: on(), cached: cache.by.size, cachedAt: cache.at || null }, last);
// counts for the report: entry reasons and stages across the cached tank
function counts() {
const reasons = {}; const stages = {}; const bands = {};
for (const x of cache.by.values()) { reasons[x.entry.reason] = (reasons[x.entry.reason] || 0) + 1; stages[x.stage] = (stages[x.stage] || 0) + 1; bands[x.heat.band] = (bands[x.heat.band] || 0) + 1; }
return { at: cache.at, n: cache.by.size, reasons, stages, bands };
}
module.exports = { init, refresh, attach, status, counts, localEntry, _reset: () => { cache = { at: 0, by: new Map() }; downUntil = 0; busy = null; } };