From e98a6ebcd8d4ad399832576402f85c50950c7dd7 Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 13 Nov 2026 10:35:15 -0600 Subject: [PATCH] docstore.js: claim() for once-across-copies actions (same file as Downline Banners) Co-Authored-By: Claude Opus 5.5 --- docstore.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docstore.js b/docstore.js index c3e9359..0bc07e4 100644 --- a/docstore.js +++ b/docstore.js @@ -177,8 +177,15 @@ async function runRows() { 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); } -module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn }; +module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim };