diff --git a/docstore.js b/docstore.js index 0bc07e4..c3cdbda 100644 --- a/docstore.js +++ b/docstore.js @@ -22,6 +22,7 @@ const O = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, exis 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 }; @@ -35,7 +36,11 @@ function nameOf(p) { 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 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); } @@ -54,6 +59,7 @@ async function flush() { 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(); } @@ -109,7 +115,7 @@ async function init(opts) { 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 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); diff --git a/qa/docstore-skip.test.cjs b/qa/docstore-skip.test.cjs new file mode 100644 index 0000000..83f68b2 --- /dev/null +++ b/qa/docstore-skip.test.cjs @@ -0,0 +1,41 @@ +// docstore: a save whose body equals what MySQL already holds is not rewritten (2026-11-15: whole-document rewrites on +// every save filled core with 115 GB of binlogs). Runs against a fake mysql2 pool, no database needed. +'use strict'; +const path = require('path'), fs = require('fs'), os = require('os'); +const rows = new Map([['links.json', '{"a":1}']]); let writes = 0; +const conn = { + beginTransaction: async () => {}, commit: async () => {}, rollback: async () => {}, release() {}, + query: async (sql, args) => { + if (/SELECT owner FROM docs_writer/.test(sql)) return [[{ owner: global.__ME }]]; + if (/^INSERT INTO docs \(name, body, updated_at\) VALUES \(\?, \?, \?\) ON DUPLICATE KEY UPDATE body/.test(sql)) { writes++; rows.set(args[0], args[1]); return [{}]; } + if (/^DELETE FROM docs/.test(sql)) { rows.delete(args[0]); return [{}]; } + return [[]]; + }, +}; +const pool = { + getConnection: async () => conn, + query: async (sql, args) => { + if (/INSERT INTO docs_writer/.test(sql)) { global.__ME = args[0]; return [{}]; } + if (/SELECT name, body, updated_at FROM docs/.test(sql)) return [[...rows].map(([name, body]) => ({ name, body, updated_at: 1 }))]; + return [[]]; + }, +}; +require.cache[require.resolve('mysql2/promise')] = { id: 'mysql2/promise', filename: require.resolve('mysql2/promise'), loaded: true, exports: { createPool: () => pool } }; +const ds = require('../docstore'); +let fails = 0; const ok = (c, m) => { console.log((c ? 'PASS ' : 'FAIL ') + m); if (!c) fails++; }; +(async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ds-')); + process.env.DOCSTORE_URL = 'mysql://fake/x'; + ds.install(dir); await ds.init(); + const f = path.join(dir, 'links.json'); + fs.writeFileSync(f, '{"a":1}'); await ds.drain(2000); + ok(writes === 0, 'saving the same body MySQL already has writes nothing (' + writes + ' writes)'); + fs.writeFileSync(f, '{"a":2}'); await ds.drain(2000); + ok(writes === 1 && rows.get('links.json') === '{"a":2}', 'a changed body is written once'); + fs.writeFileSync(f, '{"a":2}'); await ds.drain(2000); + ok(writes === 1, 'saving it again unchanged writes nothing'); + ok(fs.readFileSync(f, 'utf8') === '{"a":2}', 'reads still return the latest body'); + fs.writeFileSync(f, '{"a":3}'); fs.writeFileSync(f, '{"a":2}'); await ds.drain(2000); + ok(rows.get('links.json') === '{"a":2}', 'a change undone before the flush leaves MySQL on the right body'); + console.log(fails ? fails + ' FAILED' : 'all passed'); process.exit(fails ? 1 : 0); +})().catch(e => { console.error(e); process.exit(1); });