// 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 };