docstore.js: claim() for once-across-copies actions (same file as Downline Banners)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-13 10:35:15 -06:00
parent f29f6d1407
commit e98a6ebcd8
+8 -1
View File
@@ -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 };