// ViralAdBlitz data. One document (vab.json) holds members, sessions, Boost purchases (the chain's Purchase events with their // delivery counters), the watcher position and daily counters. Four growing collections are row tables when the app runs on // MySQL (docstore splits): text ads, verified visits, verified clicks and Boost views (the audit trail of every view counted // toward a Boost's guarantee). Without DOCSTORE_URL (local prototype + smoke tests only) everything stays in the one file, // written atomically (tmp + rename). Marty's rule (2026-11-13): MySQL is the standard; never launch on files. 'use strict'; const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const cfgMod = require('./config'); const docstore = require('./docstore'); const DOC = 'vab.json'; const SPLITS = [ { doc: DOC, field: 'ads', table: 'vab_ads', key: 'id', ts: 'createdAt' }, { doc: DOC, field: 'visits', table: 'vab_visits', key: 'id', ts: 'at' }, { doc: DOC, field: 'clicks', table: 'vab_clicks', key: 'id', ts: 'at' }, { doc: DOC, field: 'bviews', table: 'vab_bviews', key: 'id', ts: 'at' } ]; const TABLE = Object.fromEntries(SPLITS.map(s => [s.field, s])); let S = null, saveT = null, rowMode = false; const adById = new Map(), adByOwner = new Map(); const FILE = () => path.join(cfgMod.get().dataDir, DOC); function load() { try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = null; } S = Object.assign({ v: 1, seq: { ad: 0, visit: 0, click: 0, bview: 0 }, daily: {}, totals: { visits: 0, views: 0, vclicks: 0, clicks: 0, boostViews: 0 }, members: {}, sessions: {}, purchases: {}, shop: {}, ads: [], visits: [], clicks: [], bviews: [] }, S || {}); rowMode = docstore.isOn(); if (rowMode) for (const sp of SPLITS) S[sp.field] = (docstore.rows(sp.table) || []).slice(); adById.clear(); adByOwner.clear(); for (const a of S.ads) { adById.set(a.id, a); if (a.status !== 'removed') adByOwner.set(a.owner, a); } const now = Date.now(); for (const [k, s] of Object.entries(S.sessions)) if (s.expires < now) delete S.sessions[k]; } function save(now) { if (saveT && !now) return; const run = () => { saveT = null; try { const out = rowMode ? Object.assign({}, S, Object.fromEntries(SPLITS.map(sp => [sp.field, []]))) : S; const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 }); fs.renameSync(tmp, FILE()); } catch (e) { console.error('store save failed', e.message); } }; if (now) { clearTimeout(saveT); run(); } else saveT = setTimeout(run, 800); } function flush() { save(true); } const state = () => S; function putRow(field, item) { if (rowMode) { const sp = TABLE[field]; docstore.rowPut(sp.table, item[sp.key], item[sp.ts], item); } save(); } function dropRows(field, ids) { if (!ids.length) return; const set = new Set(ids); S[field] = S[field].filter(x => !set.has(x[TABLE[field].key])); if (rowMode) docstore.rowDel(TABLE[field].table, ids); save(); } function nextId(kind) { S.seq[kind] = (S.seq[kind] || 0) + 1; return S.seq[kind]; } // ---- Central time (Marty: everything on US Central) ---- const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' }); function ctDay(ts) { const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value])); return p.year + '-' + p.month + '-' + p.day; } function ctWeek(ts) { // the Central-time date of that week's Monday const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value])); const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[p.weekday] || 0; return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) - back)).toISOString().slice(0, 10); } function bump(k, n) { const day = ctDay(); const d = S.daily[day] || (S.daily[day] = {}); d[k] = (d[k] || 0) + (n || 1); save(); } function today() { return S.daily[ctDay()] || {}; } // ---- text ads (one live ad per member) ---- function ad(id) { return adById.get(Number(id)) || null; } function adOf(owner) { return adByOwner.get(String(owner || '').toLowerCase()) || null; } function addAd(a) { a.id = nextId('ad'); a.createdAt = Date.now(); a.updatedAt = a.createdAt; S.ads.push(a); adById.set(a.id, a); adByOwner.set(a.owner, a); putRow('ads', a); return a; } function saveAd(a) { a.updatedAt = Date.now(); if (a.status === 'removed') { if (adByOwner.get(a.owner) === a) adByOwner.delete(a.owner); } else adByOwner.set(a.owner, a); putRow('ads', a); } function ads() { return S.ads; } function liveAds() { return S.ads.filter(a => a.status === 'live'); } // ---- verified visits / clicks / Boost views ---- function addVisit(v) { v.id = 'v' + nextId('visit'); v.at = v.at || Date.now(); S.visits.push(v); putRow('visits', v); return v; } function addClick(c) { c.id = 'k' + nextId('click'); c.at = c.at || Date.now(); S.clicks.push(c); putRow('clicks', c); return c; } function addBview(b) { b.id = 'b' + nextId('bview'); b.at = b.at || Date.now(); S.bviews.push(b); putRow('bviews', b); return b; } const visits = () => S.visits, clicks = () => S.clicks, bviews = () => S.bviews; // visits + clicks: 15 days (the 24-hour checks, this week's + last week's board); Boost views: 120 days (the delivery audit trail) function prune() { const now = Date.now(); let n = 0; for (const [f, days] of [['visits', 15], ['clicks', 15], ['bviews', 120]]) { const cut = now - days * 86400000; const old = S[f].filter(x => x.at < cut).map(x => x.id); dropRows(f, old); n += old.length; } return n; } // ---- members ---- function member(addr) { return S.members[String(addr || '').toLowerCase()] || null; } function upsertMember(addr, patch) { const a = String(addr).toLowerCase(); const m = S.members[a] || (S.members[a] = { address: a, username: null, joinedAt: Date.now(), via: null, netOk: false }); Object.assign(m, patch || {}); m.lastSeen = Date.now(); save(); return m; } function memberByName(name) { const n = String(name || '').toLowerCase(); if (!n) return null; for (const m of Object.values(S.members)) if (m.username && m.username.toLowerCase() === n) return m; return null; } function members() { return Object.values(S.members); } // ---- sessions ---- const SESSION_TTL = 7 * 24 * 3600000; function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: address.toLowerCase(), expires: Date.now() + SESSION_TTL }; save(); return token; } function session(token) { const s = token && S.sessions[token]; return s && s.expires > Date.now() ? Object.assign({ token }, s) : null; } function dropSession(token) { delete S.sessions[token]; save(); } // network hub events (hubevents.js, 2026-11-16): end every session `match` names that was made before `before` -> how many function endSessions(match, before) { let n = 0; for (const [k, x] of Object.entries(S.sessions)) if (x.expires - SESSION_TTL <= before && match(x)) { delete S.sessions[k]; n++; } if (n) save(); return n; } module.exports = { SPLITS, load, flush, save, state, ctDay, ctWeek, bump, today, ad, adOf, addAd, saveAd, ads, liveAds, addVisit, addClick, addBview, visits, clicks, bviews, prune, member, upsertMember, memberByName, members, mintSession, session, dropSession, endSessions, SESSION_TTL };