Stack POL data in MySQL (Marty 2026-11-16: payout totals wiped on every deploy)

The indexer snapshot (was /tmp/stack-index.json) and the chatbot KB (was memory)
are now MySQL documents via docstore.js (DOCSTORE_URL, Coolify stackpol-mysql),
loaded before the server listens so a deploy shows the last totals at once.
Snapshot split into stack-index.json + stack-index-at.json so a push with no new
payouts rewrites only the tiny doc (docstore skips unchanged bodies). Ingest API
unchanged. Tested on core: restart keeps totals, /programs, /earn, member pages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-16 04:46:28 -06:00
parent b6e020e025
commit 96d6281e3e
8 changed files with 383 additions and 14 deletions
+29 -7
View File
@@ -2,12 +2,18 @@
// full SEO footprint. Every POL payout across the network, stacked: a network home with live totals, one page per program,
// the public ledger (every row links to Polygonscan), opt-in member stacks at /<username>, and the blog.
// Data: tools/indexer.py on core reads every program's payout records and IAP/LinkSpin's chain index every 5 minutes and POSTs
// one JSON snapshot to /api/ingest (Bearer STACK_INGEST_KEY). Pages read that snapshot, never the chain. The last snapshot is
// kept in /tmp so a restart serves numbers at once; the next push replaces it within 5 minutes.
// one JSON snapshot to /api/ingest (Bearer STACK_INGEST_KEY). Pages read that snapshot, never the chain.
// Storage (Marty 2026-11-16: "Stack POL wipes its payout totals on every deploy; they should live in the database"): the last
// snapshot and the chatbot's knowledge base are MySQL documents through docstore.js (DOCSTORE_URL, Coolify stackpol-mysql), loaded
// at boot before the server listens, so a restart or deploy serves the last totals at once. The snapshot is two documents:
// stack-index.json (everything but `at`) and stack-index-at.json ({at}), so a push with no new payouts rewrites only the tiny one
// (docstore skips unchanged bodies; binlog stays small). Without DOCSTORE_URL (local only) they are files in DATA_DIR.
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const docstore = require('./docstore'); docstore.install(DATA_DIR); // before any module reads data
const zlib = require('zlib');
const { SITE, esc, head, tail, ZONES, spot, personalize, memberLinks, proCta } = require('./layout');
let QR = null; try { QR = require('qrcode'); } catch (e) { console.error('[stackpol] qrcode module missing: no QR on Pro pages'); }
@@ -17,9 +23,16 @@ const blog = require('./blog');
const PORT = Number(process.env.PORT) || 80;
const KEY = String(process.env.STACK_INGEST_KEY || '').trim();
const OWNER = 'martbost'; // the network pages' join links (the site owner's referral)
const SNAP = '/tmp/stack-index.json';
const SNAP = path.join(DATA_DIR, 'stack-index.json'), SNAP_AT = path.join(DATA_DIR, 'stack-index-at.json');
const PUB = path.join(__dirname, 'public');
let IDX = null; try { IDX = JSON.parse(fs.readFileSync(SNAP, 'utf8')); } catch (e) {}
let IDX = null;
function loadSnap() {
try { const j = JSON.parse(fs.readFileSync(SNAP, 'utf8')); let at = 0; try { at = Number(JSON.parse(fs.readFileSync(SNAP_AT, 'utf8')).at) || 0; } catch (e) {} j.at = at || j.at || null; IDX = j; } catch (e) { IDX = null; }
}
function saveSnap(j) {
const body = Object.assign({}, j); delete body.at;
fs.writeFileSync(SNAP, JSON.stringify(body)); fs.writeFileSync(SNAP_AT, JSON.stringify({ at: j.at }));
}
blog.load();
const fmt = n => Number(n || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
@@ -191,7 +204,7 @@ const server = http.createServer((req, res) => {
if (!KEY || req.headers.authorization !== 'Bearer ' + KEY) { res.writeHead(401); return res.end(); }
const chunks = []; let n = 0;
req.on('data', c => { n += c.length; if (n > 8e6) req.destroy(); else chunks.push(c); });
req.on('end', () => { try { const j = JSON.parse(Buffer.concat(chunks).toString('utf8')); if (!j || !j.network || !j.programs) throw new Error('shape'); j.at = j.at || Date.now(); IDX = j; fs.writeFile(SNAP, JSON.stringify(j), () => {}); send(req, res, 200, 'application/json', JSON.stringify({ ok: true, at: j.at }), 'no-store'); } catch (e) { send(req, res, 400, 'application/json', JSON.stringify({ error: e.message }), 'no-store'); } });
req.on('end', () => { try { const j = JSON.parse(Buffer.concat(chunks).toString('utf8')); if (!j || !j.network || !j.programs) throw new Error('shape'); j.at = j.at || Date.now(); IDX = j; saveSnap(j); send(req, res, 200, 'application/json', JSON.stringify({ ok: true, at: j.at }), 'no-store'); } catch (e) { send(req, res, 400, 'application/json', JSON.stringify({ error: e.message }), 'no-store'); } });
return;
}
if (p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) { chatbot.handle(req, res, p, u, { json: chatJson, readBody: chatBody, isAdmin: () => false })
@@ -227,5 +240,14 @@ const server = http.createServer((req, res) => {
return html(req, res, 404, notFound());
} catch (e) { console.error('[stackpol]', p, e); html(req, res, 500, notFound('Something went wrong on our side. Try again in a minute.'), 'no-store'); }
});
chatbot.init();
server.listen(PORT, () => console.log('Stack POL on :' + PORT + ' | snapshot ' + (IDX ? new Date(IDX.at).toISOString() : 'none yet') + ' | posts ' + blog.listPublished().length + ' | ingest ' + (KEY ? 'on' : 'OFF (no STACK_INGEST_KEY)')));
(async () => {
// MySQL first: never serve (or take a push into) an empty copy. A few tries for a database that is still starting.
for (let i = 1; ; i++) {
try { await docstore.init(); break; } catch (e) { console.error('docstore init try ' + i + ':', e.message); if (i >= 6) throw e; await new Promise(r => setTimeout(r, 5000)); }
}
process.on('SIGTERM', () => { docstore.drain(8000).finally(() => process.exit(0)); });
if (!docstore.isOn()) { try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch (e) {} }
loadSnap();
chatbot.init(); // after docstore.init: kb.json and netkb-cache.json are MySQL documents
server.listen(PORT, () => console.log('Stack POL on :' + PORT + ' | snapshot ' + (IDX && IDX.at ? new Date(IDX.at).toISOString() : 'none yet') + ' | store ' + (docstore.isOn() ? 'MySQL' : 'files in ' + DATA_DIR) + ' | posts ' + blog.listPublished().length + ' | ingest ' + (KEY ? 'on' : 'OFF (no STACK_INGEST_KEY)')));
})().catch(e => { console.error('start failed:', e.message); process.exit(1); });