diff --git a/docstore.js b/docstore.js new file mode 100644 index 0000000..c3e9359 --- /dev/null +++ b/docstore.js @@ -0,0 +1,184 @@ +// 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) +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() }); 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 (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) }); + 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; } + +// 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); } +module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn }; diff --git a/package-lock.json b/package-lock.json index 0a0d98d..de96df6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,8 @@ "name": "banner-line", "version": "0.1.0", "dependencies": { - "ethers": "^6.13.0" + "ethers": "^6.13.0", + "mysql2": "^3.11.0" }, "engines": { "node": ">=20" @@ -59,6 +60,15 @@ "integrity": "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q==", "license": "MIT" }, + "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/ethers": { "version": "6.17.0", "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.17.0.tgz", @@ -87,6 +97,112 @@ "node": ">=14.0.0" } }, + "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/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-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/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/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/sql-escaper": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.5.2.tgz", + "integrity": "sha512-6CKD38c31SENivxOADeMNLdukOnUxUcflKtzVWzace7Riv1v7cAEym5Cx9Q7gYZ3ezIJI7ZpqecQq8cqNeSSFg==", + "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/tslib": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", diff --git a/package.json b/package.json index 721d8fd..dc2dca9 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,11 @@ "dev": "node --watch server.js", "qa": "node qa/smoke.mjs" }, - "engines": { "node": ">=20" }, + "engines": { + "node": ">=20" + }, "dependencies": { - "ethers": "^6.13.0" + "ethers": "^6.13.0", + "mysql2": "^3.11.0" } } diff --git a/server.js b/server.js index 21a188c..6f05db9 100644 --- a/server.js +++ b/server.js @@ -20,11 +20,7 @@ const SEL = { buy: iface.getFunction('buy').selector, buyFor: iface.getFunction( const C = cfgMod.get(); fs.mkdirSync(path.join(C.dataDir, 'art'), { recursive: true }); -store.load(); -chain.init(); -hubreport.init({ dataDir: C.dataDir, members: () => chain.allMembers() }); -refuelspots.init({ lock: () => keeper.busy() }); keeper.setOtherBusy(() => refuelspots.busy()); -keeper.init(); +const docstore = require('./docstore'); docstore.install(C.dataDir); // data documents live in MySQL when DOCSTORE_URL is set (Marty 2026-11-13: database is the standard) const PUB = path.join(__dirname, 'public'); const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; @@ -389,6 +385,15 @@ const server = http.createServer(async (req, res) => { } }); -server.listen(C.port, () => console.log('Downline Banners on :' + C.port + ' chain ' + C.chainName + ' (' + C.chainId + ') contract ' + (C.contract || '(not set)'))); +(async () => { + await docstore.init({}); // before anything reads its data + process.on('SIGTERM', () => { docstore.drain(8000).finally(() => process.exit(0)); }); + store.load(); + chain.init(); + hubreport.init({ dataDir: C.dataDir, members: () => chain.allMembers() }); + refuelspots.init({ lock: () => keeper.busy() }); keeper.setOtherBusy(() => refuelspots.busy()); + keeper.init(); + server.listen(C.port, () => console.log('Downline Banners on :' + C.port + ' chain ' + C.chainName + ' (' + C.chainId + ') contract ' + (C.contract || '(not set)') + ' store: ' + (docstore.isOn() ? 'MySQL documents' : 'volume JSON'))); +})().catch(e => { console.error('start failed:', e.message); process.exit(1); }); process.on('SIGTERM', () => { store.flush(); process.exit(0); }); process.on('SIGINT', () => { store.flush(); process.exit(0); });