From 96d6281e3e60c93310932b476f69a51e3525bf54 Mon Sep 17 00:00:00 2001 From: martbost Date: Mon, 16 Nov 2026 04:46:28 -0600 Subject: [PATCH] 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 --- .gitignore | 1 + Dockerfile | 5 +- README.md | 3 +- chatbot.js | 7 +- docstore.js | 210 ++++++++++++++++++++++++++++++++++++++++++++++ package-lock.json | 133 +++++++++++++++++++++++++++++ package.json | 2 +- server.js | 36 ++++++-- 8 files changed, 383 insertions(+), 14 deletions(-) create mode 100644 docstore.js diff --git a/.gitignore b/.gitignore index c2658d7..902b281 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ node_modules/ +data/ diff --git a/Dockerfile b/Dockerfile index ffe4b7e..92470a1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,10 +1,11 @@ FROM node:20-alpine WORKDIR /app -COPY package.json package-lock.json server.js layout.js blog.js programs.js netsites.js chatbot.js chatcore.js kb.js netkb.js ./ +COPY package.json package-lock.json server.js layout.js blog.js programs.js netsites.js chatbot.js chatcore.js kb.js netkb.js docstore.js ./ RUN npm ci --omit=dev --no-audit --no-fund COPY content/ ./content/ COPY public/ ./public/ -ENV NODE_ENV=production PORT=80 +ENV NODE_ENV=production PORT=80 DATA_DIR=/app/data +RUN mkdir -p /app/data EXPOSE 80 HEALTHCHECK --interval=30s --timeout=5s --start-period=10s CMD wget -qO- http://127.0.0.1/health || exit 1 CMD ["node", "server.js"] diff --git a/README.md b/README.md index f1e44c9..9a26cd5 100644 --- a/README.md +++ b/README.md @@ -8,4 +8,5 @@ stackpol.com: every POL payout across the network, stacked. Live app since 2026- - programs.js: program registry (keys match the indexer); game blurbs are InstantAdPay's own. - mockup/: the Oct design mockup (artifact https://claude.ai/artifact/1mN4dCYUcbw7EHicCdejM3). - Standing rule (Marty 2026-11-15): every rebuilt network site is added here when it goes live: a programs.js entry, its /earn/ page (automatic from the entry, plus public/img/.jpg 800x420) and an indexer source for its member payouts (house/company wallets excluded). ViralAdBlitz, 5xYourTeam and DownlineHydra added 2026-11-15. -- Site assistant (2026-11-15): chat widget on every page (`public/assets/chat.js` + `chat.css`, loaded from layout.js). `chatbot.js` holds what it knows (CANNED + FACTS from this repo); `chatcore.js`, `kb.js` (memory only here: no database, no volume) and `netkb.js` (the shared network knowledge on the hub, signed as `HUB_SITE=stackpol` with `HUB_SECRET`) are the same files as the rebuilt sites. OpenRouter key: Coolify env `OPENROUTER_API_KEY`. No admin KB editing on Stack POL. Test: `node qa/chatbot.test.mjs`. +- Site assistant (2026-11-15): chat widget on every page (`public/assets/chat.js` + `chat.css`, loaded from layout.js). `chatbot.js` holds what it knows (CANNED + FACTS from this repo); `chatcore.js`, `kb.js` (kb.json is a MySQL document, see Storage) and `netkb.js` (the shared network knowledge on the hub, signed as `HUB_SITE=stackpol` with `HUB_SECRET`) are the same files as the rebuilt sites. OpenRouter key: Coolify env `OPENROUTER_API_KEY`. No admin KB editing on Stack POL. Test: `node qa/chatbot.test.mjs`. +- Storage (Marty 2026-11-16: "they should live in the database"): MySQL, Coolify `stackpol-mysql` yw404lxgfkbb5n9s3pxu1hxk (db `stackpol`, binlog expiry 3 h persisted, in core's hourly dumps). App env `DOCSTORE_URL`; `docstore.js` (same file as LinkSpin, skips unchanged writes) keeps the data documents of DATA_DIR (/app/data, no volume) in table `docs`: `stack-index.json` (the last indexer snapshot minus `at`), `stack-index-at.json` ({at}), `kb.json` (chatbot entries), `netkb-cache.json` (network knowledge cache). Loaded before the server listens, so a deploy serves the last totals at once. The ingest API is unchanged. Without DOCSTORE_URL (local only) they are plain files in DATA_DIR. diff --git a/chatbot.js b/chatbot.js index a946347..708719f 100644 --- a/chatbot.js +++ b/chatbot.js @@ -1,7 +1,8 @@ // Stack POL's site assistant (Marty 2026-11-15): what it knows. The engine is chatcore.js (the same on every rebuilt site); // retrieval also covers the other network sites through the hub (netkb.js), this site's entries first. -// Stack POL has no database and no data volume: its own entries live in memory (seeded from this file at boot), and the -// OpenRouter key comes from the OPENROUTER_API_KEY env (a Coolify secret). No admin knowledge-base editing here. +// Storage (2026-11-16): kb.json and netkb-cache.json are MySQL documents through docstore.js (DOCSTORE_URL, stackpol-mysql), so +// the entries and the cached network set survive a deploy. The OpenRouter key comes from the OPENROUTER_API_KEY env (a Coolify +// secret). No admin knowledge-base editing here. // // Every fact below was checked against this repo on KNOWLEDGE_DATE: server.js (the on-page FAQ, the pages, /api/totals, member // stacks only when switched on), programs.js (the programs and their kinds), README.md (the indexer refreshes every 5 minutes; @@ -66,7 +67,7 @@ const FACTS = () => [ const SITE = { id: 'stackpol', hubSite: 'stackpol', netId: 'stackpol', name: 'Stack POL', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE, - dataDir: null, canned: CANNED, faq: FAQ, facts: FACTS, + dataDir: process.env.DATA_DIR || require('path').join(__dirname, 'data'), canned: CANNED, faq: FAQ, facts: FACTS, intro: 'You are the assistant on Stack POL (' + URL_ + '), the network\'s payout tracker: it adds up every POL payout across the network\'s sites and games, each one checkable on Polygon. Most questions about how to earn belong to a specific program: answer from that program\'s entries and link to it.', quickTopics: ['What is Stack POL?', 'How do I get my own page?', 'What is ViralAdBlitz?', 'How does Downline Banners pay?'] }; diff --git a/docstore.js b/docstore.js new file mode 100644 index 0000000..93a07f5 --- /dev/null +++ b/docstore.js @@ -0,0 +1,210 @@ +// Database-backed data documents (Marty 2026-11-13, standing rule: "everything database-driven ... files only for early +// prototyping"). Every *.json / *.jsonl data document under DATA_DIR that a module reads or writes with the fs *Sync calls lives +// in MySQL instead of on the volume: table `docs` (name = path relative to DATA_DIR, body LONGTEXT, updated_at). The modules keep +// their code; install() routes their fs calls on those paths to an in-memory copy that init() loads from MySQL at boot, and every +// change is written through to MySQL (coalesced per document, newest body wins, in order, retried until it lands). +// +// One writer at a time: init() claims the `docs_writer` row; an older app copy still running during a deploy finds the row taken +// and stops writing (logged), so it can never put stale data over the new copy's (the 2026-11-13 rotator.json loss). +// First boot: a document missing from MySQL is imported from its file, and the file is renamed .imported- (kept, not +// read again). Files the volume keeps on purpose: KEEP (rebuildable caches, uploads, images, the geo database, queues read by +// listing a folder). The SAME file ships in InstantAdPay and LinkSpin. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +const KEEP_FILES = new Set(['chain-index.json']); // a rebuildable cache of the blockchain +const KEEP_DIRS = ['uploads', 'geo', 'refuel-pending', 'backups', 'marks', 'kits', 'kitimg']; // binary files, or folders read by listing +const O = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, renameSync: fs.renameSync, + unlinkSync: fs.unlinkSync, statSync: fs.statSync, appendFileSync: fs.appendFileSync }; + +let ROOT = null, pool = null, ME = crypto.randomBytes(8).toString('hex'), ready = false, writer = true; +const cache = new Map(); // name -> { body: string, at: ms } +const pending = new Map(); // name -> body string | null (delete) +const stored = new Map(); // name -> body as last read from or written to MySQL: an unchanged save is not rewritten (2026-11-15: whole-document rewrites filled core with 115 GB of binlogs) +let flushing = false, timer = null; +const stats = { writes: 0, deletes: 0, refused: 0, errors: 0, imported: 0, lastError: null }; + +function nameOf(p) { + if (!ROOT || typeof p !== 'string' || !/\.jsonl?$/i.test(p)) return null; + const abs = path.resolve(p); if (!abs.startsWith(ROOT + path.sep)) return null; + const rel = abs.slice(ROOT.length + 1).split(path.sep).join('/'); + if (KEEP_FILES.has(rel) || KEEP_DIRS.some(d => rel === d || rel.startsWith(d + '/'))) return null; + return rel; +} +const enoent = p => { const e = new Error("ENOENT: no such file or directory, open '" + p + "'"); e.code = 'ENOENT'; e.errno = -2; e.path = p; return e; }; +const enc = o => (typeof o === 'string' ? o : o && o.encoding) || null; + +function put(name, body) { + cache.set(name, { body, at: Date.now() }); + if (stored.get(name) === body) { pending.delete(name); return; } // same as what MySQL already holds: nothing to write + pending.set(name, body); kick(); +} +function drop(name) { cache.delete(name); pending.set(name, null); kick(); } +function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(() => {}); }, 300); } + +async function flush() { + if (!pool || flushing || !pending.size) return; + flushing = true; + try { + for (const [name, body] of [...pending]) { + if (pending.get(name) !== body) continue; // replaced while we were busy: the newer body goes next round + if (!writer) { pending.delete(name); stats.refused++; continue; } + const c = await pool.getConnection(); + try { + await c.beginTransaction(); + const [[w]] = await c.query('SELECT owner FROM docs_writer WHERE id = 1 FOR UPDATE'); + if (!w || w.owner !== ME) { await c.rollback(); writer = false; pending.delete(name); stats.refused++; console.error('docstore: another app copy took over writing; this copy stops writing'); continue; } + if (body === null) { await c.query('DELETE FROM docs WHERE name = ?', [name]); stats.deletes++; } + else { await c.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), updated_at = VALUES(updated_at)', [name, body, Date.now()]); stats.writes++; } + await c.commit(); + if (body === null) stored.delete(name); else stored.set(name, body); + if (pending.get(name) === body) pending.delete(name); + } catch (e) { try { await c.rollback(); } catch (x) {} stats.errors++; stats.lastError = String(e.message).slice(0, 200); console.error('docstore write', name, e.message); } + finally { c.release(); } + } + } finally { flushing = false; if (pending.size) setTimeout(() => flush().catch(() => {}), 1000); } +} + +// Route the fs *Sync calls on data documents. Installed before any module runs; until init() the documents read from disk. +function install(dataDir) { + if (ROOT) return; ROOT = path.resolve(dataDir); + fs.readFileSync = function (p, o) { + if (!ready && process.env.DOCSTORE_URL && nameOf(p)) console.error('docstore: read before init', p, new Error().stack.split('\n')[2]); + const n = ready ? nameOf(p) : null; if (!n) return O.readFileSync.apply(fs, arguments); + const d = cache.get(n); if (!d) throw enoent(p); + return enc(o) ? d.body : Buffer.from(d.body, 'utf8'); + }; + fs.existsSync = function (p) { const n = ready ? nameOf(p) : null; return n ? cache.has(n) : O.existsSync.apply(fs, arguments); }; + fs.writeFileSync = function (p, data, o) { + const n = ready ? nameOf(p) : null; if (!n) return O.writeFileSync.apply(fs, arguments); + const flag = o && typeof o === 'object' ? o.flag : null; + const s = Buffer.isBuffer(data) ? data.toString('utf8') : String(data); + put(n, flag && flag[0] === 'a' ? ((cache.get(n) || {}).body || '') + s : s); + }; + fs.appendFileSync = function (p, data) { + const n = ready ? nameOf(p) : null; if (!n) return O.appendFileSync.apply(fs, arguments); + put(n, ((cache.get(n) || {}).body || '') + (Buffer.isBuffer(data) ? data.toString('utf8') : String(data))); + }; + fs.renameSync = function (a, b) { + const nb = ready ? nameOf(b) : null; const na = ready ? nameOf(a) : null; + if (!nb && !na) return O.renameSync.apply(fs, arguments); + let body; + if (na) { const d = cache.get(na); if (!d) throw enoent(a); body = d.body; drop(na); } + else { body = O.readFileSync.call(fs, a, 'utf8'); try { O.unlinkSync.call(fs, a); } catch (e) {} } + if (nb) put(nb, body); else O.writeFileSync.call(fs, b, body); + }; + fs.unlinkSync = function (p) { const n = ready ? nameOf(p) : null; if (!n) return O.unlinkSync.apply(fs, arguments); if (!cache.has(n)) throw enoent(p); drop(n); }; + fs.statSync = function (p, o) { + const n = ready ? nameOf(p) : null; if (!n) return O.statSync.apply(fs, arguments); + const d = cache.get(n); if (!d) { if (o && o.throwIfNoEntry === false) return undefined; throw enoent(p); } + const size = Buffer.byteLength(d.body, 'utf8'); const t = new Date(d.at); + return { size, mtimeMs: d.at, mtime: t, ctime: t, birthtime: t, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false }; + }; +} + +// Connect, claim writing, load every document, import files MySQL does not have yet. Throws if MySQL is unreachable: the app +// must not run on an empty copy. +async function init(opts) { + const url = String(process.env.DOCSTORE_URL || '').trim(); + if (!url) { console.log('docstore: no DOCSTORE_URL, documents stay files (prototype mode)'); return false; } + const mysql = require('mysql2/promise'); + pool = mysql.createPool({ uri: url, connectionLimit: 6, charset: 'utf8mb4' }); + await pool.query('CREATE TABLE IF NOT EXISTS docs (name VARCHAR(190) PRIMARY KEY, body LONGTEXT NOT NULL, updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'); + await pool.query('CREATE TABLE IF NOT EXISTS docs_writer (id TINYINT PRIMARY KEY, owner VARCHAR(40) NOT NULL, at BIGINT NOT NULL) ENGINE=InnoDB'); + await pool.query('INSERT INTO docs_writer (id, owner, at) VALUES (1, ?, ?) ON DUPLICATE KEY UPDATE owner = VALUES(owner), at = VALUES(at)', [ME, Date.now()]); + const [rows] = await pool.query('SELECT name, body, updated_at FROM docs'); + for (const r of rows) { cache.set(r.name, { body: r.body, at: Number(r.updated_at) }); stored.set(r.name, r.body); } + for (const sp of (opts && opts.splits) || []) await openSplit(sp); + // first boot for any document: import its file, then set the file aside + const stamp = new Date().toISOString().slice(0, 10); + const walk = dir => { let out = []; let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) {} for (const e of ents) { const p = path.join(dir, e.name); if (e.isDirectory()) out = out.concat(walk(p)); else out.push(p); } return out; }; + for (const p of walk(ROOT)) { + const n = nameOf(p); if (!n || cache.has(n)) continue; + const body = O.readFileSync.call(fs, p, 'utf8'); + if (/\.json$/i.test(n) && body.trim()) { try { JSON.parse(body); } catch (e) { throw new Error('docstore: ' + n + ' is not valid JSON; fix or move it before switching to MySQL'); } } + await pool.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name = name', [n, body, Date.now()]); + const [[got]] = await pool.query('SELECT body FROM docs WHERE name = ?', [n]); + cache.set(n, { body: got.body, at: Date.now() }); stats.imported++; + O.renameSync.call(fs, p, p + '.imported-' + stamp); + } + for (const sp of (opts && opts.splits) || []) await migrateSplit(sp); + ready = true; + console.log('docstore: MySQL documents ready,', cache.size, 'documents,', stats.imported, 'imported from files this boot'); + const shut = () => { flush().catch(() => {}).finally(() => {}); }; + process.once('beforeExit', shut); + return true; +} +// ---- row tables: an ever-growing array (spin-link clicks) is one row per item, never a rewrite of the whole document ---- +// spec { doc: 'rotator.json', field: 'hits', table: 'rot_hits', key: 'id', ts: 'ts' }. rows(table) gives the loaded items (oldest +// first); the module inserts / deletes rows itself and saves its document WITHOUT the field. +const ROWS = new Map(); const rowQ = []; let rowBusy = false; +async function openSplit(sp) { + await pool.query('CREATE TABLE IF NOT EXISTS `' + sp.table + '` (id VARCHAR(64) PRIMARY KEY, ts BIGINT NOT NULL, body MEDIUMTEXT NOT NULL, KEY ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'); + const [r] = await pool.query('SELECT body FROM `' + sp.table + '` ORDER BY ts, id'); + ROWS.set(sp.table, r.map(x => JSON.parse(x.body))); +} +async function insertMany(table, items, key, ts) { + for (let i = 0; i < items.length; i += 500) { + const part = items.slice(i, i + 500); + await pool.query('INSERT INTO `' + table + '` (id, ts, body) VALUES ? ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [part.map(x => [String(x[key]), Number(x[ts]) || 0, JSON.stringify(x)])]); + } +} +// first boot: the array still inside the document moves to its table, then the document is saved without it +async function migrateSplit(sp) { + const d = cache.get(sp.doc); if (!d) return; + let obj; try { obj = JSON.parse(d.body); } catch (e) { return; } + const arr = Array.isArray(obj[sp.field]) ? obj[sp.field] : null; if (!arr || !arr.length) return; + await insertMany(sp.table, arr, sp.key, sp.ts); + const [[{ n }]] = await pool.query('SELECT COUNT(*) n FROM `' + sp.table + '`'); + if (n < arr.length) throw new Error('docstore: ' + sp.table + ' holds ' + n + ' rows after moving ' + arr.length + '; stopping before the document is changed'); + const seen = new Set((ROWS.get(sp.table) || []).map(x => String(x[sp.key]))); const merged = (ROWS.get(sp.table) || []).concat(arr.filter(x => !seen.has(String(x[sp.key])))); + merged.sort((a, b) => (Number(a[sp.ts]) || 0) - (Number(b[sp.ts]) || 0)); ROWS.set(sp.table, merged); + obj[sp.field] = []; const body = JSON.stringify(obj); + await pool.query('UPDATE docs SET body = ?, updated_at = ? WHERE name = ?', [body, Date.now(), sp.doc]); cache.set(sp.doc, { body, at: Date.now() }); + console.log('docstore:', arr.length, sp.field, 'moved from', sp.doc, 'to table', sp.table); +} +function rows(table) { return ROWS.get(table) || null; } +function rowOp(op) { if (!pool || !writer) return; rowQ.push(op); if (!rowBusy) runRows(); } +async function runRows() { + rowBusy = true; + try { + while (rowQ.length && writer) { + const op = rowQ[0]; + try { + if (op.del) await pool.query('DELETE FROM `' + op.table + '` WHERE id IN (?)', [op.ids]); + else await pool.query('INSERT INTO `' + op.table + '` (id, ts, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [op.id, op.ts, op.body]); + rowQ.shift(); + } catch (e) { stats.errors++; stats.lastError = String(e.message).slice(0, 200); await new Promise(r => setTimeout(r, 1000)); } + } + } finally { rowBusy = false; } +} +const rowPut = (table, id, ts, obj) => rowOp({ table, id: String(id), ts: Number(ts) || 0, body: JSON.stringify(obj) }); +const rowDel = (table, ids) => { const list = [...ids].map(String); for (let i = 0; i < list.length; i += 1000) rowOp({ table, del: true, ids: list.slice(i, i + 1000) }); }; +function isOn() { return ready && !!pool; } +// once across app copies (two run side by side during a deploy): true for the first caller of a key, false after. Without MySQL: true. +async function claim(key) { + if (!pool) return true; + await pool.query('CREATE TABLE IF NOT EXISTS doc_claims (k VARCHAR(190) PRIMARY KEY, at BIGINT NOT NULL) ENGINE=InnoDB'); + const [r] = await pool.query('INSERT IGNORE INTO doc_claims (k, at) VALUES (?, ?)', [String(key).slice(0, 190), Date.now()]); + return r.affectedRows === 1; +} + +// SIGTERM during a deploy: write what is pending, then exit +async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } } +function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); } +const names = () => [...cache.keys()]; // every document name (the member erase walks them all, 2026-11-15) +// member erase (2026-11-15): count or delete the rows of a row table whose JSON body has `field` (e.g. '$.r') in `values`. Waits +// for queued row writes first, so a click queued before the erase cannot land after it. +async function rowsWhere(table, field, values, del) { + if (!pool || !values.length) return 0; + for (let i = 0; i < 100 && (rowQ.length || rowBusy); i++) await new Promise(r => setTimeout(r, 100)); + const vals = values.map(String); const where = 'CAST(JSON_UNQUOTE(JSON_EXTRACT(body, ?)) AS CHAR) IN (?)'; + if (!del) { const [[r]] = await pool.query('SELECT COUNT(*) n FROM `' + table + '` WHERE ' + where, [field, vals]); return Number(r.n); } + if (!writer) return 0; + const [r] = await pool.query('DELETE FROM `' + table + '` WHERE ' + where, [field, vals]); + const mem = ROWS.get(table); if (mem) { const k = field.replace(/^\$\./, ''); ROWS.set(table, mem.filter(x => !vals.includes(String(x[k])))); } + return Number(r.affectedRows || 0); +} +module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim, names, rowsWhere }; diff --git a/package-lock.json b/package-lock.json index 5a83777..10ac02d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,9 +8,20 @@ "name": "stackpol", "version": "1.0.0", "dependencies": { + "mysql2": "3.24.6", "qrcode": "1.5.4" } }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "license": "MIT", + "peer": true, + "dependencies": { + "undici-types": "~8.9.0" + } + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -35,6 +46,15 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -107,6 +127,15 @@ "node": ">=8" } }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -116,6 +145,22 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -125,6 +170,12 @@ "node": ">=8" } }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "license": "MIT" + }, "node_modules/locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", @@ -137,6 +188,60 @@ "node": ">=8" } }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/lru.min": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.5.tgz", + "integrity": "sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, + "node_modules/mysql2": { + "version": "3.24.6", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.6.tgz", + "integrity": "sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==", + "license": "MIT", + "dependencies": { + "aws-ssl-profiles": "^1.1.2", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.3", + "long": "^5.3.2", + "lru.min": "^1.1.4", + "named-placeholders": "^1.1.6", + "sql-escaper": "^1.5.1" + }, + "engines": { + "node": ">= 8.0" + }, + "peerDependencies": { + "@types/node": ">= 8" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", + "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", + "license": "MIT", + "dependencies": { + "lru.min": "^1.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/p-limit": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", @@ -223,12 +328,33 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "license": "ISC" }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, "node_modules/set-blocking": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", "license": "ISC" }, + "node_modules/sql-escaper": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.7.0.tgz", + "integrity": "sha512-ZgP6E9SPnhrhWXxd8+nLKPot3Euzyo3Rpxe6EFAYz2Ffaq9Xg2SH+6d4yJi7vsQDHaQlhzQ1phAopgE6+a1UCQ==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=2.0.0", + "node": ">=12.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" + } + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -255,6 +381,13 @@ "node": ">=8" } }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "license": "MIT", + "peer": true + }, "node_modules/which-module": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", diff --git a/package.json b/package.json index b1cde2a..abcda5a 100644 --- a/package.json +++ b/package.json @@ -1 +1 @@ -{ "name": "stackpol", "version": "1.0.0", "private": true, "main": "server.js", "scripts": { "start": "node server.js" }, "dependencies": { "qrcode": "1.5.4" } } +{"name":"stackpol","version":"1.0.0","private":true,"main":"server.js","scripts":{"start":"node server.js"},"dependencies":{"mysql2":"3.24.6","qrcode":"1.5.4"}} \ No newline at end of file diff --git a/server.js b/server.js index f0f3c1e..17c4d1e 100644 --- a/server.js +++ b/server.js @@ -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 /, 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); });