// VBB data. One document (vbb.json) holds the loop, the queue, members, sessions and daily counters; three growing // collections are row tables when the app runs on MySQL (docstore splits): banners, the cycle reward ledger and the // verified visits. Without DOCSTORE_URL (local prototype 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 = 'vbb.json'; const SPLITS = [ { doc: DOC, field: 'banners', table: 'vbb_banners', key: 'id', ts: 'createdAt' }, { doc: DOC, field: 'ledger', table: 'vbb_ledger', key: 'id', ts: 'at' }, { doc: DOC, field: 'visits', table: 'vbb_visits', key: 'id', ts: 'at' } ]; const TABLE = Object.fromEntries(SPLITS.map(s => [s.field, s])); let S = null, saveT = null, rowMode = false; const byId = new Map(); // banner id -> banner 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: { banner: 0, ledger: 0, visit: 0 }, loop: [], queue: [], progress: 0, totals: { shifts: 0, cycles: 0, visits: 0, posts: 0, views: 0 }, daily: {}, members: {}, sessions: {}, banners: [], ledger: [], visits: [] }, S || {}); rowMode = docstore.isOn(); if (rowMode) for (const sp of SPLITS) S[sp.field] = (docstore.rows(sp.table) || []).slice(); byId.clear(); for (const b of S.banners) byId.set(b.id, b); 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; // a row in a growing collection changed: one row write on MySQL, the document on files 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; } // week key = the Central-time date of that week's Monday function ctWeek(ts) { 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; const d = new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) - back)); return d.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()] || {}; } // ---- banners ---- function banner(id) { return byId.get(Number(id)) || null; } function addBanner(b) { b.id = nextId('banner'); b.createdAt = Date.now(); S.banners.push(b); byId.set(b.id, b); putRow('banners', b); return b; } function saveBanner(b) { putRow('banners', b); } function bannersOf(addr) { const a = String(addr).toLowerCase(); return S.banners.filter(b => b.owner === a); } // ---- ledger (cycle rewards: recorded only in v1, no crediting yet) ---- function addLedger(e) { e.id = 'c' + nextId('ledger'); e.at = Date.now(); S.ledger.push(e); putRow('ledger', e); return e; } function ledger() { return S.ledger; } // ---- verified visits ---- function addVisit(v) { v.id = 'v' + nextId('visit'); v.at = v.at || Date.now(); S.visits.push(v); putRow('visits', v); return v; } function visits() { return S.visits; } // keep 15 days: the 24-hour check and this week's + last week's leaderboards function pruneVisits() { const cut = Date.now() - 15 * 86400000; const old = S.visits.filter(v => v.at < cut).map(v => v.id); dropRows('visits', old); return old.length; } // ---- 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(), credits: 0, freeDay: null, via: null }); 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, banner, addBanner, saveBanner, bannersOf, addLedger, ledger, addVisit, visits, pruneVisits, member, upsertMember, memberByName, members, mintSession, session, dropSession, endSessions, SESSION_TTL };