Files
instantadpay/qa/login-queue-sql.cjs
T
martbost 89b5969b25 Prepaid login-ad line: when all member slots are taken, members pay now to reserve the next one (Marty, 2026-10-23: "they need to pay for the slot now to get a place in line")
- ads.js: a login buy with every slot taken returns full:true and a reserve offer; with reserve:true it is charged the full slot price at once (purchased credits only, credit log 'Login slot reserved (queue #N)') and stored with status 'queued' + queuedAt, no starts/expires, never served or counted as a slot. First paid, first served.
- Promotion (promoteLoginQueue): on a slot expiring (scheduleSweep), a member pausing a slot, every new login buy, and a one-minute tick. The oldest reservation becomes active, starts now, ends in 30 days; the owner gets an on-site notice (kind 'notice') and an email unless unsubscribed.
- Deploy-overlap safety: the cap decision runs under a lease row in the new app_locks table (one conditional UPDATE takes it, an expired lease can be taken over); every start/cancel/edit is a conditional UPDATE on status='queued', so a reservation starts at most once and a cancel racing a start has exactly one winner. Live login buys and paused-slot resumes also take the lease, so the cap holds for them too.
- A freed slot goes to the line first: a paused slot resumes only while live + queued < loginSlotsMax, with a plain message saying the line is ahead.
- Cancel before the start: full refund as purchased-grade credits (credit log 'Login slot reservation cancelled: refund'), once. Edit target/image/headline before the start, free. Cancelled reservations can be archived.
- Estimated start per place from the live slots' end dates and the reservations ahead, shown in Central time and labelled an estimate.
- db.js: campaigns.queued_at BIGINT NULL, app_locks table + 'login_queue' row, all added on boot.
- server.js: loginLine in GET /api/my/campaigns, POST /api/my/campaigns/:id/cancel-reservation and /edit-reservation (safe-browsing, reach and image checks), GET /api/admin/login-queue, POST /api/admin/login-queue/:id/cancel, the promotion notice hook and the one-minute tick.
- Member UI (my.js, my.html): open slots or the line with place and estimated start on the Login ad form, the button becomes "Reserve the next slot", IAP.confirmBox before paying, In line #N + estimated start in the list, Edit and Cancel and refund. Admin (admin.js, admin.html): Login-ad line card with owner, queued at, place, estimated start, cancel + refund. Tags bumped to 20261023lq.
- chatbot.js: new canned 'login-ads' answer and the LOGIN ADS fact updated (6 slots, the paid line, cancel = full refund before start). The knowledge base seeds the new entry on boot.
- audit.js: queued/cancelled reservations are not per-day login campaigns.
- QA: qa/login-queue.cjs (JSON store end to end) and qa/login-queue-sql.cjs (SQL path guard logic against a fake SQL layer), bash qa/run.sh login-queue. qa/login-slot.mjs pattern follows the refactor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:14:57 -05:00

152 lines
12 KiB
JavaScript

// Prepaid login-ad line, MySQL code path (2026-10-23).
// node qa/login-queue-sql.cjs
// There is no MySQL on the test machine, so this swaps db.js for an in-memory fake that understands exactly the SQL the
// line uses and runs each statement atomically after a random 0-3 ms wait, so concurrent callers interleave BETWEEN
// statements the way two app copies do during a deploy overlap. That tests the guard logic of the SQL path (the
// app_locks lease and the conditional UPDATE ... WHERE status='queued'), not MySQL itself: real InnoDB locking, the
// schema migration and mysql2's affectedRows semantics are not exercised here. Unknown SQL throws, so a statement
// this fake does not model fails the test instead of passing silently. Exit 1 on failure.
'use strict';
const path = require('path');
const DAY = 86400000;
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
// ---- the fake ----
const T = { campaigns: [], locks: {}, earned: {}, log: [] }; let nextId = 1;
const wait = () => new Promise(r => setTimeout(r, Math.floor(Math.random() * 4)));
const norm = s => String(s).replace(/\s+/g, ' ').trim();
const liveRows = now => T.campaigns.filter(c => c.type === 'login' && c.status === 'active' && c.house === 0 && (c.expires == null || c.expires > now));
async function q(sql, p) {
await wait();
const s = norm(sql); p = p || [];
let m;
if (s.startsWith('INSERT IGNORE INTO app_locks')) { if (!T.locks[p[0]]) T.locks[p[0]] = { holder: null, until: 0 }; return { affectedRows: 1 }; }
if (s === 'UPDATE app_locks SET holder=?, lease_until=? WHERE name=? AND (holder IS NULL OR lease_until<?)') {
const L = T.locks[p[2]]; if (L && (L.holder === null || L.until < p[3])) { L.holder = p[0]; L.until = p[1]; return { affectedRows: 1 }; } return { affectedRows: 0 };
}
if (s === 'UPDATE app_locks SET holder=NULL, lease_until=0 WHERE name=? AND holder=?') {
const L = T.locks[p[0]]; if (L && L.holder === p[1]) { L.holder = null; L.until = 0; return { affectedRows: 1 }; } return { affectedRows: 0 };
}
if (s === "SELECT COUNT(*) n FROM campaigns WHERE type='login' AND status='active' AND house=0 AND (expires IS NULL OR expires>?)") return [{ n: liveRows(p[0]).length }];
if (s === "SELECT expires FROM campaigns WHERE type='login' AND status='active' AND house=0 AND (expires IS NULL OR expires>?)") return liveRows(p[0]).map(c => ({ expires: c.expires }));
if ((m = /^SELECT \* FROM campaigns WHERE type='login' AND status='queued' AND house=0 ORDER BY queued_at ASC, id ASC( LIMIT (\d+))?$/.exec(s))) {
const rows = T.campaigns.filter(c => c.type === 'login' && c.status === 'queued' && c.house === 0).sort((a, b) => (a.queued_at - b.queued_at) || (a.id - b.id));
return (m[2] ? rows.slice(0, Number(m[2])) : rows).map(c => Object.assign({}, c));
}
if (s === "UPDATE campaigns SET status='active', starts=?, expires=?, body=? WHERE id=? AND type='login' AND status='queued'") {
const c = T.campaigns.find(x => x.id === p[3] && x.type === 'login' && x.status === 'queued'); if (!c) return { affectedRows: 0 };
c.status = 'active'; c.starts = p[0]; c.expires = p[1]; c.body = p[2]; return { affectedRows: 1 };
}
if (s === "UPDATE campaigns SET status='cancelled' WHERE id=? AND type='login' AND status='queued'") {
const c = T.campaigns.find(x => x.id === p[0] && x.type === 'login' && x.status === 'queued'); if (!c) return { affectedRows: 0 };
c.status = 'cancelled'; return { affectedRows: 1 };
}
if (s === 'SELECT * FROM campaigns WHERE id=?') return T.campaigns.filter(c => c.id === p[0]).map(c => Object.assign({}, c));
if (s === 'SELECT * FROM campaigns WHERE owner_email=? ORDER BY id DESC') return T.campaigns.filter(c => c.owner_email === p[0]).sort((a, b) => b.id - a.id).map(c => Object.assign({}, c));
if (s === 'UPDATE campaigns SET status=? WHERE id=? AND owner_email=?') { const c = T.campaigns.find(x => x.id === p[1] && x.owner_email === p[2]); if (!c) return { affectedRows: 0 }; c.status = p[0]; return { affectedRows: 1 }; }
if (s.startsWith('INSERT INTO earned_credits (email,balance,purchase_grade,granted_welcome,updated)')) {
const e = T.earned[p[0]] = T.earned[p[0]] || { balance: 0, grade: 0 }; e.balance += p[1]; e.grade += p[2]; return { affectedRows: 1 };
}
if (s.startsWith('INSERT INTO credit_log')) { T.log.push({ email: p[0], delta: p[3], kind: p[4], note: p[5], ref: p[6] }); return { affectedRows: 1 }; }
throw new Error('fake db: unmodelled SQL: ' + s);
}
const fake = { enabled: () => true, q, init: async () => true };
const dbPath = require.resolve(path.join(__dirname, '..', 'db.js'));
require.cache[dbPath] = { id: dbPath, filename: dbPath, loaded: true, exports: fake };
const fs = require('fs'); const os = require('os');
const ads = require('../ads');
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-loginq-sql-'));
ads.init({ dataDir, chain: { creditBalance: async () => 0 } });
ads.setRates({ loginSlotsMax: 6, loginSlotCredits: 1000, loginSlotDays: 30 });
const notified = []; ads.onLoginPromoted(async c => { notified.push(c.id); });
const row = (o) => { const c = Object.assign({ id: nextId++, owner_email: 'x@qa.test', member_id: 1, house: 0, type: 'login', name: 'QA', target_url: 'https://example.com', image_url: null, title: null, body: '30', budget: 1000, spent: 1000, accrued: 0, imps: 0, clicks: 0, batch_imps: 0, status: 'active', created: Date.now(), expires: Date.now() + 10 * DAY, starts: Date.now(), queued_at: null }, o); T.campaigns.push(c); return c; };
const reset = () => { T.campaigns = []; T.locks = {}; T.earned = {}; T.log = []; notified.length = 0; };
const live = () => liveRows(Date.now()).length;
const tick = () => new Promise(r => setTimeout(r, 30));
(async () => {
// 1. one slot frees, two queued, five promoters at once: exactly one start, the oldest
for (let round = 0; round < 25; round++) {
reset();
const slots = []; for (let i = 0; i < 6; i++) slots.push(row({ owner_email: 's' + i + '@qa.test', expires: Date.now() + (i + 1) * DAY }));
const a = row({ owner_email: 'a@qa.test', status: 'queued', queued_at: 1000, expires: null, starts: null });
const b = row({ owner_email: 'b@qa.test', status: 'queued', queued_at: 2000, expires: null, starts: null });
slots[0].expires = Date.now() - 1000;
const res = await Promise.all([1, 2, 3, 4, 5].map(() => ads.promoteLoginQueue()));
await tick();
const started = res.flatMap(r => r.promoted.map(c => c.id));
const good = started.length === 1 && started[0] === a.id && a.status === 'active' && b.status === 'queued' && live() === 6 && notified.length === 1 && T.locks.login_queue.holder === null;
if (!good || round === 24) ok(good, 'round ' + (round + 1) + '/25: five concurrent promoters, one free slot -> exactly one start (the oldest), 6 live, one notice, lock released', JSON.stringify({ started, a: a.status, b: b.status, live: live(), notified, lock: T.locks.login_queue }));
if (!good) break;
}
// 2. two free slots, three queued, concurrent promoters: exactly two start, the two oldest, never over the cap
{
reset();
for (let i = 0; i < 4; i++) row({});
const q = [3000, 1000, 2000].map(t => row({ status: 'queued', queued_at: t, expires: null, starts: null }));
const res = await Promise.all([1, 2, 3].map(() => ads.promoteLoginQueue()));
const started = res.flatMap(r => r.promoted.map(c => c.id)).sort();
ok(started.length === 2 && started.join() === [q[1].id, q[2].id].sort().join() && q[0].status === 'queued' && live() === 6, 'two slots free: the two oldest start, the third waits, cap 6', JSON.stringify({ started, live: live() }));
}
// 3. a cancel racing a start: exactly one wins, the refund is paid only if the cancel won
{
let bad = 0;
for (let round = 0; round < 40; round++) {
reset();
for (let i = 0; i < 5; i++) row({});
const a = row({ owner_email: 'race@qa.test', status: 'queued', queued_at: 1, expires: null, starts: null });
const [cn, pr] = await Promise.all([ads.cancelLoginReservation('race@qa.test', a.id), ads.promoteLoginQueue()]);
const refunded = (T.earned['race@qa.test'] || { balance: 0 }).balance;
const cancelWon = !!cn.ok, startWon = pr.promoted.length === 1;
if (cancelWon === startWon || (cancelWon && (a.status !== 'cancelled' || refunded !== 1000)) || (startWon && (a.status !== 'active' || refunded !== 0))) bad++;
}
ok(bad === 0, '40 rounds of cancel vs start on the same reservation: always exactly one winner, refund only when the cancel won', bad + ' bad rounds');
}
// 4. a lease held by the other app copy: the tick backs off; an expired lease is taken over
{
reset();
for (let i = 0; i < 5; i++) row({});
const a = row({ status: 'queued', queued_at: 1, expires: null, starts: null });
T.locks.login_queue = { holder: 'other-copy', until: Date.now() + 10000 };
let r = await ads.promoteLoginQueue();
ok(r.busy === true && !r.promoted.length && a.status === 'queued' && T.locks.login_queue.holder === 'other-copy', 'lease held by the other copy: no start, the tick backs off, the lease is untouched', JSON.stringify(r));
T.locks.login_queue.until = Date.now() - 1; // that copy died holding it
r = await ads.promoteLoginQueue();
ok(r.promoted.length === 1 && a.status === 'active' && T.locks.login_queue.holder === null, 'an expired lease is taken over, the reservation starts, the lease is released', JSON.stringify({ n: r.promoted.length, lock: T.locks.login_queue }));
}
// 5. resume rule in SQL mode: a paused slot stays paused while the line is non-empty, even with a slot free
{
reset();
for (let i = 0; i < 4; i++) row({});
const p = row({ owner_email: 'pz@qa.test', status: 'paused' });
const w = row({ status: 'queued', queued_at: 1, expires: null, starts: null });
T.locks.login_queue = { holder: 'other-copy', until: Date.now() + 60000 }; // keep the line from starting w during the check
const t0 = Date.now(); let r = await ads.setStatus('pz@qa.test', p.id, 'active');
ok(r.error && /busy/.test(r.error) && p.status === 'paused' && Date.now() - t0 >= 3000, 'resume waits for the lease and gives up cleanly while another copy holds it', JSON.stringify(r));
T.locks.login_queue = { holder: null, until: 0 };
// 4 live + 1 waiting = 5 of 6: one place is open, so the paused slot may resume
r = await ads.setStatus('pz@qa.test', p.id, 'active');
ok(r.ok && p.status === 'active', '4 live + 1 waiting of 6: a place is open, the paused slot resumes', JSON.stringify(r).slice(0, 100));
p.status = 'paused'; row({}); // now 5 live + 1 waiting = 6
r = await ads.setStatus('pz@qa.test', p.id, 'active');
ok(r.error && /line goes first/.test(r.error) && p.status === 'paused', '5 live + 1 waiting of 6: resume refused, the line goes first', JSON.stringify(r));
r = await ads.setStatus(w.owner_email, w.id, 'active');
ok(r.error && /already in line/.test(r.error), 'a reservation cannot be "resumed" past the line', JSON.stringify(r));
}
// 6. cancel refunds once, at purchase grade, with the ledger line
{
reset();
const a = row({ owner_email: 'c@qa.test', status: 'queued', queued_at: 1, expires: null, starts: null, spent: 600, accrued: 400 });
const r1 = await ads.cancelLoginReservation('c@qa.test', a.id), r2 = await ads.cancelLoginReservation('c@qa.test', a.id);
const e = T.earned['c@qa.test'];
ok(r1.ok && r1.refunded === 1000 && r2.error && e.balance === 1000 && e.grade === 1000, 'cancel: 1,000 back once (spent + accrued), purchased grade; the second cancel pays nothing', JSON.stringify({ r1, r2, e }));
ok(T.log.some(l => l.delta === 1000 && /^Login slot reservation cancelled: refund/.test(l.note) && l.kind === 'refund'), 'credit_log row "Login slot reservation cancelled: refund"', JSON.stringify(T.log));
const r3 = await ads.cancelLoginReservation('someone@else.test', a.id);
ok(r3.error === 'No such reservation.', 'another member cannot cancel it or learn its state', JSON.stringify(r3));
}
fs.rmSync(dataDir, { recursive: true, force: true });
console.log(fails ? fails + ' FAILED' : 'ALL PASS');
process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); process.exit(1); });