// Prepaid login-slot queue (Marty, 2026-10-23: "they need to pay for the slot now to get a place in line"). // Unit test on ads.js directly: a throwaway DATA_DIR, the JSON store (no DATABASE_URL), a fake chain (free members, so // every credit is engine-side), no server, no mail, no network. Checks: // 6 slots filled; a 7th buy is refused unless it reserves; two reservations pay now (balances drop, credit activity); // places and estimated start dates; a reservation never serves; free edit while queued; owner cannot resume it; // one slot expires -> two app copies (child processes on the same DATA_DIR, the deploy overlap) promote at the same // moment -> the first reservation starts exactly once, one notice; the stale copy adopts it and never re-promotes; // cancel the second -> full refund, once; a paused slot frees its place to the line and cannot resume while the line // holds the slots; raising the slot count lets it back in. // node qa/loginqueue.test.cjs 'use strict'; const assert = require('assert'); const fs = require('fs'); const os = require('os'); const path = require('path'); const { spawn } = require('child_process'); for (const k of ['DATABASE_URL', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'OUTBOUND', 'ENGINE_KEY']) delete process.env[k]; const SITE = path.join(__dirname, '..'); const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'lq-unit-')); const ads = require(path.join(SITE, 'ads.js')); const chain = { creditBalance: async () => 0 }; let passed = 0, failed = 0; const results = []; async function t(name, fn) { try { await fn(); passed++; results.push('ok ' + name); } catch (e) { failed++; results.push('FAIL ' + name + '\n ' + String(e && e.stack || e).split('\n').slice(0, 4).join('\n ')); } } const DAY = 86400000; const em = n => n.toLowerCase() + '@lq.test'; const owners = ['f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'A', 'B', 'C', 'D']; const earned = {}; for (const o of owners) earned[em(o)] = { balance: 3000, grade: 3000, welcomed: true }; // credited purchased credits fs.writeFileSync(path.join(DATA, 'earned.json'), JSON.stringify(earned)); const login = (name, extra) => Object.assign({ type: 'login', name, targetUrl: 'https://example.com/' + encodeURIComponent(name), budget: 1000 }, extra || {}); const grade = async o => (await ads.earnedSplit(em(o))).grade; const notes = []; // one more app copy on the same volume (what a deploy overlap is): load ads.js fresh, wait for a shared start moment, // run the promotion, report what it promoted and what it notified function copy(startAt, tag) { const code = ` const path = require('path'); const fs = require('fs'); const ads = require(${JSON.stringify(path.join(SITE, 'ads.js'))}); ads.init({ dataDir: ${JSON.stringify(DATA)}, chain: { creditBalance: async () => 0 } }); const told = []; ads.setLoginQueueNotifier(async c => { told.push(c.id); }); const go = async () => { const out = await ads.promoteLoginQueue(); process.stdout.write(JSON.stringify({ tag: ${JSON.stringify(tag)}, promoted: out.map(c => c.id), told })); }; setTimeout(go, Math.max(0, ${startAt} - Date.now()));`; return new Promise((resolve, reject) => { const env = Object.assign({}, process.env); delete env.DATABASE_URL; const p = spawn(process.execPath, ['-e', code], { cwd: SITE, env }); let out = '', err = ''; p.stdout.on('data', d => out += d); p.stderr.on('data', d => err += d); p.on('close', c => { try { resolve(JSON.parse(out.slice(out.lastIndexOf('{"tag"')))); } catch (e) { reject(new Error('copy ' + tag + ' exit ' + c + ': ' + out + err)); } }); }); } (async () => { ads.init({ dataDir: DATA, chain }); ads.setRates({ loginSlotsMax: 6 }); ads.setLoginQueueNotifier(async (c, info) => { notes.push({ id: c.id, info }); }); const F = {}, Q = {}; await t('estimate math: live end dates, open places start now, each place ahead takes a full run', () => { const now = 1e12; const e6 = [1, 2, 3, 4, 5, 6].map(d => now + d * DAY); assert.deepStrictEqual(ads._estimateStarts(e6, 6, 2, now, 30), [now + DAY, now + 2 * DAY]); assert.deepStrictEqual(ads._estimateStarts(e6.slice(0, 5), 6, 2, now, 30), [now, now + DAY]); // one open place: now assert.deepStrictEqual(ads._estimateStarts([now + DAY], 1, 3, now, 30), [now + DAY, now + 31 * DAY, now + 61 * DAY]); assert.deepStrictEqual(ads._estimateStarts([Infinity], 1, 1, now, 30), [null]); // legacy slot with no end: no estimate }); await t('six member slots fill; slots read full', async () => { for (let i = 1; i <= 6; i++) { const r = await ads.createCampaign(em('f' + i), 0, login('fill' + i), []); assert.ok(r.ok, JSON.stringify(r)); assert.strictEqual(r.campaign.status, 'active'); F[i] = r.campaign.id; (await ads.campaignById(F[i])).expires = Date.now() + i * DAY; // staggered ends: slot i frees on day i } const ls = await ads.loginSlots(); assert.deepStrictEqual([ls.max, ls.used, ls.queued, ls.free], [6, 6, 0, 0]); }); await t('a 7th buy is refused with the reserve offer, and nothing is charged', async () => { const r = await ads.createCampaign(em('A'), 0, login('A slot'), []); assert.ok(r.error && r.full && r.canReserve, JSON.stringify(r)); assert.ok(/reserve the next slot/i.test(r.error) && !/—/.test(r.error), r.error); assert.strictEqual(await grade('A'), 3000); }); await t('two reservations pay now: queued, places 1 and 2, balances down 1000 each, credit activity written', async () => { const a = await ads.createCampaign(em('A'), 0, login('A slot', { reserve: true }), []); const b = await ads.createCampaign(em('B'), 0, login('B slot', { reserve: true }), []); assert.ok(a.ok && b.ok, JSON.stringify([a, b])); Q.A = a.campaign.id; Q.B = b.campaign.id; assert.strictEqual(a.campaign.status, 'queued'); assert.strictEqual(b.campaign.status, 'queued'); assert.strictEqual(a.campaign.place, 1); assert.strictEqual(b.campaign.place, 2); assert.strictEqual(a.campaign.expires, null, 'no 30-day clock while queued'); assert.strictEqual(await grade('A'), 2000); assert.strictEqual(await grade('B'), 2000); const la = await ads.creditLog(em('A')), lb = await ads.creditLog(em('B')); assert.strictEqual(la[0].reason, 'Login slot reserved (queue #1)'); assert.strictEqual(la[0].delta, -1000); assert.strictEqual(lb[0].reason, 'Login slot reserved (queue #2)'); const ls = await ads.loginSlots(); assert.deepStrictEqual([ls.used, ls.queued, ls.free], [6, 2, 0]); }); await t('places and estimated starts: #1 when slot 1 ends, #2 when slot 2 ends, Central-time date labels', async () => { const q = await ads.loginQueue(); assert.deepStrictEqual(q.map(x => [x.id, x.place]), [[Q.A, 1], [Q.B, 2]]); const e1 = (await ads.campaignById(F[1])).expires, e2 = (await ads.campaignById(F[2])).expires; assert.strictEqual(q[0].estStart, e1); assert.strictEqual(q[1].estStart, e2); assert.ok(/^[A-Z][a-z]{2} \d{1,2}, \d{4}$/.test(q[0].estStartCt), q[0].estStartCt); const mine = await ads.myLoginQueue(em('B')); assert.strictEqual(mine.length, 1); assert.strictEqual(mine[0].place, 2); const nx = await ads.loginNext(); assert.strictEqual(nx.place, 3); assert.strictEqual(nx.estStart, (await ads.campaignById(F[3])).expires); }); await t('a reservation never serves', async () => { for (let i = 0; i < 60; i++) { const s = await ads.serve('login', {}); assert.ok(s && ![Q.A, Q.B].includes(s.id), 'served ' + (s && s.id)); } }); await t('edits while queued are free and keep the free correction; owner cannot pause/resume a reservation', async () => { const r = await ads.editCampaign(em('A'), Q.A, { targetUrl: 'https://example.com/A-new' }, { fee: 100, ids: [] }); assert.ok(r.ok, JSON.stringify(r)); assert.strictEqual(r.fee, 0); assert.strictEqual(r.campaign.edits, 0); const r2 = await ads.editCampaign(em('A'), Q.A, { name: 'A slot renamed' }, { fee: 100, ids: [] }); assert.ok(r2.ok && r2.fee === 0 && r2.campaign.edits === 0, JSON.stringify(r2)); assert.strictEqual(await grade('A'), 2000); for (const st of ['active', 'paused']) { const s = await ads.setStatus(em('A'), Q.A, st); assert.ok(s.error && /in line/.test(s.error), JSON.stringify(s)); } assert.strictEqual((await ads.campaignById(Q.A)).status, 'queued'); }); await t('slot 1 expires; two app copies promote at the same moment: #1 starts exactly once, one notice', async () => { (await ads.campaignById(F[1])).expires = Date.now() - 1000; await ads.click(F[1]); // any write: the store on disk now has slot 1 ended (the copies read the disk) const at = Date.now() + 700; const [x, y] = await Promise.all([copy(at, 'x'), copy(at, 'y')]); const all = x.promoted.concat(y.promoted), told = x.told.concat(y.told); assert.deepStrictEqual(all, [Q.A], JSON.stringify([x, y])); assert.deepStrictEqual(told, [Q.A], 'one notice: ' + JSON.stringify([x, y])); const L = JSON.parse(fs.readFileSync(path.join(DATA, 'login-queue.json'), 'utf8')); assert.deepStrictEqual(Object.keys(L.promoted), [String(Q.A)]); assert.ok(!fs.existsSync(path.join(DATA, 'login-queue.lock')), 'lock released'); }); await t('the stale copy (this process still had #1 queued) adopts the start and promotes nothing; again: nothing', async () => { const before = notes.length; const p1 = await ads.promoteLoginQueue(), p2 = await ads.promoteLoginQueue(); assert.deepStrictEqual(p1, []); assert.deepStrictEqual(p2, []); assert.strictEqual(notes.length, before, 'no second notice'); const a = await ads.campaignById(Q.A); assert.strictEqual(a.status, 'active'); assert.ok(Math.abs(a.expires - (a.promotedAt + 30 * DAY)) < 5, 'runs 30 days from its start'); assert.ok(a.promotedAt > Date.now() - 60000); assert.strictEqual((await ads.campaignById(Q.B)).status, 'queued'); // six live again: B waits const ls = await ads.loginSlots(); assert.deepStrictEqual([ls.used, ls.queued], [6, 1]); assert.strictEqual((await ads.loginQueue())[0].place, 1, 'B moved up to #1'); assert.strictEqual(await grade('A'), 2000, 'promotion charges nothing more'); }); await t('cancel the second before start: full refund, once; it cannot be resumed or edited after', async () => { const r = await ads.cancelLoginReservation(em('B'), Q.B); assert.ok(r.ok, JSON.stringify(r)); assert.strictEqual(r.refunded, 1000); assert.strictEqual(await grade('B'), 3000); assert.strictEqual((await ads.creditLog(em('B')))[0].reason, 'Login slot reservation cancelled: refund'); assert.strictEqual((await ads.creditLog(em('B')))[0].delta, 1000); const again = await ads.cancelLoginReservation(em('B'), Q.B); assert.ok(again.error, JSON.stringify(again)); assert.strictEqual(await grade('B'), 3000, 'no double refund'); assert.ok((await ads.setStatus(em('B'), Q.B, 'active')).error); assert.ok((await ads.editCampaign(em('B'), Q.B, { name: 'x' }, { fee: 0 })).error); assert.ok((await ads.cancelLoginReservation(em('A'), Q.A)).error, 'a started slot is not refundable'); assert.ok((await ads.cancelLoginReservation(em('C'), Q.B)).error, 'not your reservation'); }); await t('a paused slot frees its place to the line, and cannot resume while the line holds the slots', async () => { const c = await ads.createCampaign(em('C'), 0, login('C slot', { reserve: true }), []); assert.strictEqual(c.campaign.status, 'queued'); Q.C = c.campaign.id; const p = await ads.setStatus(em('f2'), F[2], 'paused'); assert.ok(p.ok, JSON.stringify(p)); assert.strictEqual((await ads.campaignById(Q.C)).status, 'active', 'C took the paused slot'); const d = await ads.createCampaign(em('D'), 0, login('D slot', { reserve: true }), []); assert.strictEqual(d.campaign.status, 'queued'); Q.D = d.campaign.id; const r1 = await ads.setStatus(em('f2'), F[2], 'active'); assert.ok(r1.error && /reservation/.test(r1.error), JSON.stringify(r1)); ads.setRates({ loginSlotsMax: 7 }); // one more place, but D is waiting: D gets it, f2 still waits const r2 = await ads.setStatus(em('f2'), F[2], 'active'); assert.ok(r2.error, JSON.stringify(r2)); assert.strictEqual((await ads.campaignById(Q.D)).status, 'active', 'the line goes first'); ads.setRates({ loginSlotsMax: 8 }); // now a place is open with nobody waiting const r3 = await ads.setStatus(em('f2'), F[2], 'active'); assert.ok(r3.ok, JSON.stringify(r3)); const ls = await ads.loginSlots(); assert.deepStrictEqual([ls.used, ls.queued, ls.free], [8, 0, 0]); }); await t('admin cancel refunds any owner in full', async () => { ads.setRates({ loginSlotsMax: 8 }); const e = await ads.createCampaign(em('A'), 0, login('A second', { reserve: true }), []); assert.strictEqual(e.campaign.status, 'queued'); assert.strictEqual(await grade('A'), 1000); const r = await ads.cancelLoginReservation(null, e.campaign.id, { admin: true }); assert.ok(r.ok && r.refunded === 1000, JSON.stringify(r)); assert.strictEqual(await grade('A'), 2000); assert.ok(/by the admin/.test((await ads.creditLog(em('A')))[0].reason)); }); await t('no notice went out for anything but the promotions; the promotion notice carries the run', () => { assert.deepStrictEqual(notes.map(n => n.id), [Q.C, Q.D]); // A's notice came from the other app copy assert.strictEqual(notes[0].info.days, 30); assert.ok(notes[0].info.endsCt); }); console.log(results.join('\n')); console.log('\n' + passed + ' passed, ' + failed + ' failed (data dir ' + DATA + ')'); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} process.exit(failed ? 1 : 0); })().catch(e => { console.error(e); process.exit(1); });