Sponsor follow + one network holding tank + Sponsor check (Marty, 2026-10-22, approved 1-3)
Deliberate sponsor changes (tank adoption, dormant-lead rescue, release, adoption window ending, admin edit) are now recorded (sponsorfollow.json: when, how, the sponsor before, origin) and travel on the LinkSpin sync rows as sponsorSetAt/By/PrevEmail/Origin. A deliberate change from LinkSpin is applied here (a clear back to the tank included) only when the member is not bound on the InstantAdPay contract (memberId or wallet on chain), it is newer than our own deliberate change, and both sides agreed before it (or we have no sponsor). Bound, diverged and race cases change nothing and are logged. Race within 15 min: the earlier change wins on both. Ordinary bindings keep the first-platform rule. Accounts with no record behave as before; rows without the new facts hash exactly as before (no resend on deploy). Network tank: rows carry this site's own adoptions of a person; the waiting list hides someone adopted on LinkSpin, the two-adoptions limit counts both sites, the 3-day hold applies to a LinkSpin adoption too, follows close local open adoptions quietly (no chat, mail or feed post). Admin > Members > Sponsor check: shared members whose sponsor differs or is one-sided, each side's when/how, chain binding, and Use InstantAdPay's / Use LinkSpin's sponsor (applied on the other site, refused when bound there). Partner endpoints /api/partner/sponsor-facts and /api/partner/sponsor-apply (same HMAC as the registry rows). Tests: qa/sponsorfollow.test.cjs 27/27, qa/sponsorfollow-e2e.mjs 20/20 (local IAP + local LinkSpin, throwaway data), QA member walk 0 bugs. No sponsor was changed on production. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,7 @@
|
||||
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
|
||||
# bash qa/run.sh all # public + member + earn
|
||||
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
|
||||
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests and the two-server e2e (local IAP + local LinkSpin, throwaway data)
|
||||
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
|
||||
# bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it)
|
||||
# bash qa/run.sh sov-passes # Explorer/Champion tiers: store unit checks + admin buys Explorer with seeded purchased credits on a local copy (screenshots D:/tmp/sov-passes)
|
||||
@@ -35,6 +36,9 @@ if [ "$MODE" = "public" ]; then
|
||||
node qa/chatbot-sync.mjs || status=1
|
||||
elif [ "$MODE" = "member" ]; then
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
||||
elif [ "$MODE" = "sponsorfollow" ]; then
|
||||
node qa/sponsorfollow.test.cjs || status=1
|
||||
node qa/sponsorfollow-e2e.mjs || status=1
|
||||
elif [ "$MODE" = "kb" ]; then
|
||||
node qa/kb-retrieval.cjs || status=1
|
||||
node qa/kb-chat.mjs || status=1
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// End-to-end check of the sponsor follow through the REAL sync code (lssync.js -> LinkSpin /api/partner/registry and
|
||||
// iapsync.js -> InstantAdPay /api/partner/registry, the hash and registry loop guards, the Sponsor check endpoints).
|
||||
// Boots a local InstantAdPay AND a local LinkSpin, each on a throwaway data dir seeded with the same few accounts (JSON
|
||||
// stores, no DATABASE_URL, no mail key, no engine key), pointed ONLY at each other with a throwaway LS_SYNC_SECRET.
|
||||
// Nothing touches production. Needs the LinkSpin repo beside this one (LS_SITE to override).
|
||||
// node qa/sponsorfollow-e2e.mjs
|
||||
import { spawn, execSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const require = createRequire(import.meta.url);
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const IAP_SITE = path.join(HERE, '..');
|
||||
const LS_SITE = process.env.LS_SITE || path.join(IAP_SITE, '..', '..', 'linkspin', 'site');
|
||||
const SECRET = 'qa-sponsorfollow-' + 'x'.repeat(40);
|
||||
process.env.LS_SYNC_SECRET = SECRET;
|
||||
const SF = require(path.join(IAP_SITE, 'sponsorfollow.js'));
|
||||
const IAP_PORT = 8811, LS_PORT = 8812, IAP = 'http://127.0.0.1:' + IAP_PORT, LS = 'http://127.0.0.1:' + LS_PORT;
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
let pass = 0, fail = 0; const lines = [];
|
||||
const ok = (cond, name, extra) => { if (cond) { pass++; lines.push('ok ' + name); } else { fail++; lines.push('FAIL ' + name + (extra ? '\n ' + extra : '')); } };
|
||||
|
||||
const now = Date.now();
|
||||
const acct = (email, username, o) => Object.assign({ email, pass: null, sponsorRef: '', code: ('c' + username).slice(0, 7), username, address: null, created: now - 20 * 86400000, lastSeen: now - 3600000, memberId: 0 }, o || {});
|
||||
function seed(dir, list) {
|
||||
fs.mkdirSync(path.join(dir, 'uploads'), { recursive: true });
|
||||
const db = { v: 2, byEmail: {}, byAddress: {}, byCode: {}, joins: 0, positions: {} };
|
||||
for (const a of list) { db.byEmail[a.email] = a; db.byCode[a.code] = a.email; }
|
||||
fs.writeFileSync(path.join(dir, 'accounts.json'), JSON.stringify(db));
|
||||
}
|
||||
const base = () => [acct('adopter@qa.test', 'adopter', { memberId: 0 }), acct('old@qa.test', 'oldsponsor'), acct('lead1@qa.test', 'leadone'), acct('lead2@qa.test', 'leadtwo', { sponsorRef: 'oldsponsor' }), acct('lead4@qa.test', 'leadfour', { sponsorRef: 'oldsponsor' })];
|
||||
const iapDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-e2e-iap-')), lsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-e2e-ls-'));
|
||||
// lead3 is bound on InstantAdPay (memberId), lead4 joined LinkSpin under someone else (ordinary, already different)
|
||||
seed(iapDir, base().concat([acct('lead3@qa.test', 'leadthree', { memberId: 42, sponsorRef: 'oldsponsor' })]));
|
||||
seed(lsDir, base().map(a => a.email === 'lead4@qa.test' ? Object.assign(a, { sponsorRef: 'adopter' }) : a).concat([acct('lead3@qa.test', 'leadthree', { sponsorRef: 'oldsponsor' })]));
|
||||
|
||||
const env = (port, dir, extra) => Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, ADMIN_EMAIL: 'admin@qa.test', ADMIN_PASSWORD: 'localtest', LS_SYNC_SECRET: SECRET, DATABASE_URL: '', SENDGRID_API_KEY: '', ENGINE_KEY: '', ENGINE_KEY_FILE: '' }, extra);
|
||||
for (const k of ['DATABASE_URL', 'NETWORK_DB_URL']) delete process.env[k];
|
||||
const procs = [];
|
||||
function boot(site, port, dir, extra, log) {
|
||||
const p = spawn(process.execPath, ['server.js'], { cwd: site, env: env(port, dir, extra), stdio: ['ignore', fs.openSync(log, 'w'), fs.openSync(log, 'a')] });
|
||||
procs.push(p); return p;
|
||||
}
|
||||
async function up(url) { for (let i = 0; i < 40; i++) { try { const r = await fetch(url + '/api/config', { signal: AbortSignal.timeout(2000) }); if (r.status < 500) return true; } catch (e) {} await sleep(1000); } return false; }
|
||||
const admin = async (url, pth, body, method) => { const r = await fetch(url + pth, { method: method || (body ? 'POST' : 'GET'), headers: { Authorization: 'Bearer localtest', 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined }); return r.json(); };
|
||||
const facts = async (url, email) => ((await SF.peerPost(url, '/api/partner/sponsor-facts', { emails: [email] })).rows || [])[0] || null;
|
||||
async function waitFor(fn, ms) { const t0 = Date.now(); while (Date.now() - t0 < (ms || 20000)) { try { if (await fn()) return true; } catch (e) {} await sleep(700); } return false; }
|
||||
|
||||
const OUT = path.join(IAP_SITE, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
|
||||
try {
|
||||
boot(IAP_SITE, IAP_PORT, iapDir, { LS_URL: LS }, path.join(OUT, 'sf-e2e-iap.log'));
|
||||
boot(LS_SITE, LS_PORT, lsDir, { IAP_URL: IAP, SITE_HOST: '127.0.0.1:' + LS_PORT, TANK_RESCUE: '' }, path.join(OUT, 'sf-e2e-ls.log'));
|
||||
ok(await up(IAP), 'local InstantAdPay up'); ok(await up(LS), 'local LinkSpin up');
|
||||
|
||||
// 1. a deliberate change on InstantAdPay (admin edit from the tank) follows to LinkSpin
|
||||
let r = await admin(IAP, '/api/admin/member', { email: 'lead1@qa.test', sponsorRef: 'adopter' }, 'PATCH');
|
||||
ok(!r.error, 'IAP admin sets lead1 -> @adopter', JSON.stringify(r));
|
||||
ok(await waitFor(async () => (await facts(LS, 'lead1@qa.test')).sponsorEmail === 'adopter@qa.test'), 'LinkSpin follows: lead1 under adopter');
|
||||
const l1 = await facts(LS, 'lead1@qa.test'); ok(l1 && l1.prov && l1.prov.by === 'admin' && l1.prov.origin === 'instantadpay', 'LinkSpin keeps the same record (by admin, origin instantadpay)', JSON.stringify(l1 && l1.prov));
|
||||
|
||||
// 2. a deliberate change on LinkSpin (both had @oldsponsor) follows to InstantAdPay, a clear back to the tank
|
||||
r = await admin(LS, '/api/admin/member', { email: 'lead2@qa.test', sponsorRef: '' }, 'PATCH');
|
||||
ok(!r.error, 'LinkSpin admin clears lead2 to the tank', JSON.stringify(r));
|
||||
ok(await waitFor(async () => (await facts(IAP, 'lead2@qa.test')).sponsorEmail === null), 'InstantAdPay follows the clear: lead2 in the tank');
|
||||
|
||||
// 3. bound on InstantAdPay: a LinkSpin change does not move it there; reported; resolve refuses on the bound side
|
||||
r = await admin(LS, '/api/admin/member', { email: 'lead3@qa.test', sponsorRef: 'adopter' }, 'PATCH');
|
||||
await sleep(6000);
|
||||
ok((await facts(IAP, 'lead3@qa.test')).sponsorEmail === 'old@qa.test', 'bound on InstantAdPay: sponsor there unchanged');
|
||||
|
||||
// 4. ping-pong: let both ticks run; nothing keeps bouncing
|
||||
const s1 = await admin(IAP, '/api/admin/lssync'), t1 = await admin(LS, '/api/admin/iapsync');
|
||||
await admin(IAP, '/api/admin/lssync/run', {}); await admin(LS, '/api/admin/iapsync/run', {}); await sleep(1500);
|
||||
await admin(IAP, '/api/admin/lssync/run', {}); await admin(LS, '/api/admin/iapsync/run', {}); await sleep(1500);
|
||||
const s2 = await admin(IAP, '/api/admin/lssync/run', {}), t2 = await admin(LS, '/api/admin/iapsync/run', {});
|
||||
ok(s2.sent === 0 && t2.sent === 0, 'no ping-pong: a third reconcile on each side sends 0 rows', JSON.stringify({ s1: s1.pushed, s2, t1: t1.pushed, t2 }));
|
||||
|
||||
// 5. the Sponsor check on both apps lists lead3 (bound on IAP) and lead4 (ordinary, different) and nothing else
|
||||
const rep = await admin(IAP, '/api/admin/sponsor-check'); const rep2 = await admin(LS, '/api/admin/sponsor-check');
|
||||
const emails = x => (x.rows || []).map(y => y.email).sort().join(',');
|
||||
ok(!rep.peerError && emails(rep) === 'lead3@qa.test,lead4@qa.test', 'IAP Sponsor check rows = lead3, lead4', JSON.stringify({ e: emails(rep), err: rep.peerError }));
|
||||
ok(emails(rep2) === emails(rep), 'LinkSpin Sponsor check shows the same rows');
|
||||
const r3 = (rep.rows || []).find(x => x.email === 'lead3@qa.test');
|
||||
ok(r3 && r3.iap.bound && !r3.ls.bound, 'lead3: bound on InstantAdPay, not on LinkSpin');
|
||||
ok(r3 && (r3.iap.log || []).some(l => l.action === 'bound'), 'lead3: the refused follow is in the InstantAdPay log');
|
||||
r = await admin(IAP, '/api/admin/sponsor-check/resolve', { email: 'lead3@qa.test', use: 'linkspin' });
|
||||
ok(r.error && /bound/.test(r.error), "resolve 'Use LinkSpin's sponsor' on the bound side is refused", JSON.stringify(r));
|
||||
r = await admin(LS, '/api/admin/sponsor-check/resolve', { email: 'lead3@qa.test', use: 'instantadpay' });
|
||||
ok(r.ok, "resolve from LinkSpin admin: 'Use InstantAdPay's sponsor' applies on LinkSpin", JSON.stringify(r));
|
||||
ok((await facts(LS, 'lead3@qa.test')).sponsorEmail === 'old@qa.test', 'lead3 now @oldsponsor on both');
|
||||
r = await admin(IAP, '/api/admin/sponsor-check/resolve', { email: 'lead4@qa.test', use: 'instantadpay' });
|
||||
ok(r.ok, "resolve from InstantAdPay admin: lead4 'Use InstantAdPay's sponsor' applied on LinkSpin through the partner call", JSON.stringify(r));
|
||||
await sleep(5000);
|
||||
const rep3 = await admin(IAP, '/api/admin/sponsor-check');
|
||||
ok((rep3.rows || []).length === 0, 'after both picks the Sponsor check is empty', emails(rep3));
|
||||
ok((await facts(IAP, 'lead4@qa.test')).sponsorEmail === 'old@qa.test', 'lead4 on InstantAdPay untouched by its own pick');
|
||||
|
||||
// 6. an old peer (no proto 2): rows carrying the new facts are sent again later (checked through the stored hashes)
|
||||
const st = JSON.parse(fs.readFileSync(path.join(iapDir, 'sponsorfollow.json'), 'utf8'));
|
||||
ok(st.peer && st.peer.proto === 2, 'IAP saw LinkSpin answer proto 2');
|
||||
} catch (e) { fail++; lines.push('FAIL exception ' + (e && e.stack || e)); }
|
||||
finally {
|
||||
for (const p of procs) { try { p.kill(); } catch (e) {} }
|
||||
if (process.platform === 'win32') for (const port of [IAP_PORT, LS_PORT]) { try { const o = execSync('netstat -ano | findstr :' + port, { encoding: 'utf8' }); for (const pid of new Set(o.split(/\r?\n/).map(l => l.trim().split(/\s+/).pop()).filter(x => /^\d+$/.test(x) && x !== '0'))) { try { execSync('taskkill /F /PID ' + pid, { stdio: 'ignore' }); } catch (e) {} } } catch (e) {} }
|
||||
await sleep(500);
|
||||
for (const d of [iapDir, lsDir]) { try { fs.rmSync(d, { recursive: true, force: true }); } catch (e) {} }
|
||||
}
|
||||
console.log(lines.join('\n')); console.log('\nsponsorfollow e2e: ' + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,295 @@
|
||||
// Unit tests for the sponsor follow rule + the one network holding tank (sponsorfollow.js, tank.js). The SAME file ships in
|
||||
// InstantAdPay and LinkSpin. No server, no network, no chain: two in-process "platforms" (two instances of this repo's
|
||||
// tank.js, each with its own in-memory accounts, follow store and throwaway data dir) and a mini sync that builds rows the
|
||||
// way lssync.js / iapsync.js do (rowFields + tank summary) and delivers them the way the inbound handlers do.
|
||||
// node qa/sponsorfollow.test.cjs
|
||||
'use strict';
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const SITE = path.join(__dirname, '..');
|
||||
const SF = require(path.join(SITE, 'sponsorfollow.js'));
|
||||
delete process.env.DATABASE_URL; // JSON stores only
|
||||
|
||||
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 ' + (e && e.stack || e).split('\n').slice(0, 3).join('\n ')); } }
|
||||
|
||||
// ---------- pure rule ----------
|
||||
const H = 3600000, T0 = Date.UTC(2026, 9, 22, 15, 0, 0);
|
||||
const inc = (o) => Object.assign({ sponsorEmail: 'a@x.co', at: T0, by: 'adopt', prevEmail: null, origin: 'instantadpay' }, o);
|
||||
const loc = (o) => Object.assign({ sponsorEmail: null, prov: null, bound: false }, o);
|
||||
|
||||
async function pure() {
|
||||
await t('ordinary incoming row (no sponsorSetBy) is left to the first-platform rule', () => {
|
||||
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'b@x.co' }), { sponsorEmail: 'a@x.co' }).action, 'ordinary');
|
||||
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'b@x.co' }), inc({ by: 'join' })).action, 'ordinary');
|
||||
assert.strictEqual(SF.incomingOf({ sponsorEmail: 'a@x.co', sponsorSetBy: 'join', sponsorSetAt: T0 }), null);
|
||||
});
|
||||
await t('deliberate adoption fills an empty sponsor (one network tank)', () => {
|
||||
const d = SF.decide(loc(), inc()); assert.strictEqual(d.action, 'apply'); assert.ok(d.apply);
|
||||
});
|
||||
await t('bound member never changes, even for a newer deliberate change', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', bound: true }), inc({ prevEmail: 'b@x.co' })); assert.strictEqual(d.action, 'bound'); assert.ok(!d.apply); assert.ok(d.conflict);
|
||||
assert.strictEqual(SF.decide(loc({ bound: true }), inc()).action, 'bound');
|
||||
});
|
||||
await t('newer deliberate change wins when both sides agreed before it', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'b@x.co' }), inc({ by: 'rescue', sponsorEmail: null, prevEmail: 'b@x.co' }));
|
||||
assert.strictEqual(d.action, 'apply'); assert.ok(d.apply);
|
||||
});
|
||||
await t('clear back to the tank applies (sponsorEmail null)', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'a@x.co', prov: { at: T0 - 9 * 86400000, by: 'adopt', sponsorEmail: 'a@x.co', origin: 'instantadpay' } }), inc({ by: 'expire', sponsorEmail: null, prevEmail: 'a@x.co', at: T0 }));
|
||||
assert.strictEqual(d.action, 'apply');
|
||||
});
|
||||
await t('ordinary sponsor that already differed from the sender is NOT moved (diverged, reported)', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'c@x.co' }), inc({ prevEmail: null }));
|
||||
assert.strictEqual(d.action, 'diverged'); assert.ok(!d.apply); assert.ok(d.conflict);
|
||||
});
|
||||
await t('older incoming deliberate change loses to a newer local one (stale)', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 + 2 * H, by: 'admin', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
|
||||
assert.strictEqual(d.action, 'stale'); assert.ok(!d.apply);
|
||||
});
|
||||
await t('newer incoming deliberate change beats an older local deliberate one', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 - 2 * H, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
|
||||
assert.strictEqual(d.action, 'apply');
|
||||
});
|
||||
await t('conflict window: earlier incoming wins over a later local change, flagged', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 + 60000, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
|
||||
assert.strictEqual(d.action, 'conflict-apply'); assert.ok(d.apply); assert.ok(d.conflict);
|
||||
});
|
||||
await t('conflict window: later incoming loses to an earlier local change, flagged, not applied', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 - 60000, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
|
||||
assert.strictEqual(d.action, 'conflict-keep'); assert.ok(!d.apply); assert.ok(d.conflict);
|
||||
});
|
||||
await t('two changes from the same platform minutes apart are sequential, not a race', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'a@x.co', prov: { at: T0, by: 'adopt', sponsorEmail: 'a@x.co', origin: 'instantadpay' } }), inc({ at: T0 + 60000, by: 'admin', sponsorEmail: 'z@x.co', prevEmail: 'a@x.co' }));
|
||||
assert.strictEqual(d.action, 'apply');
|
||||
});
|
||||
await t('a sender that built on our current sponsor is sequential, not a race', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 + 120000, by: 'admin', sponsorEmail: 'z@x.co', prevEmail: 'b@x.co', origin: 'instantadpay' }));
|
||||
assert.strictEqual(d.action, 'apply');
|
||||
});
|
||||
await t('same sponsor already: no-op (the ping-pong stopper)', () => {
|
||||
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'A@x.co ' }), inc()).action, 'same');
|
||||
});
|
||||
await t('a local record that no longer describes the current sponsor is ignored (later ordinary change)', () => {
|
||||
const d = SF.decide(loc({ sponsorEmail: 'w@x.co', prov: { at: T0 + H, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0, prevEmail: null }));
|
||||
assert.strictEqual(d.action, 'diverged');
|
||||
assert.strictEqual(SF.rowFields({ at: T0, by: 'adopt', sponsorEmail: 'b@x.co' }, 'w@x.co'), null);
|
||||
});
|
||||
await t('back-compat: rows without the new facts hash exactly as before (no resend on deploy)', () => {
|
||||
assert.strictEqual(SF.hashExtra({ email: 'm@x.co', sponsorEmail: 'a@x.co', tank: null }), '');
|
||||
assert.notStrictEqual(SF.hashExtra({ sponsorSetBy: 'adopt', sponsorSetAt: T0 }), '');
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- two platforms in one process ----------
|
||||
function fakeAccounts() {
|
||||
const by = new Map(); let nextId = 100;
|
||||
const pub = a => a ? Object.assign({}, a) : null;
|
||||
const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
|
||||
return {
|
||||
_by: by,
|
||||
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: T0 - 30 * 86400000, lastSeen: T0 - H }, o || {}); by.set(email, a); return pub(a); },
|
||||
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
|
||||
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
|
||||
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
|
||||
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
|
||||
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true, account: pub(a) }; },
|
||||
async listAll() { return [...by.values()].map(pub); },
|
||||
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); },
|
||||
async setMemberId(e, id) { const a = by.get(e); if (a) a.memberId = id; }
|
||||
};
|
||||
}
|
||||
function platform(name, peerName) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-' + name + '-'));
|
||||
delete require.cache[require.resolve(path.join(SITE, 'tank.js'))];
|
||||
const tank = require(path.join(SITE, 'tank.js'));
|
||||
const accounts = fakeAccounts();
|
||||
const purchases = [];
|
||||
const chain = { recentEvents: () => purchases, getConfig: () => ({}) };
|
||||
const chats = [];
|
||||
const messages = { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 };
|
||||
const store = SF.create({ dataDir: dir, platform: name });
|
||||
const bound = new Set();
|
||||
const glue = SF.glue({ store, accounts, tank: () => tank, peer: peerName,
|
||||
isBound: async a => Number(a.memberId) > 0 || bound.has(a.email) ? { bound: true, why: name + ' member #' + a.memberId } : { bound: false },
|
||||
sponsorAccount: em => accounts.byEmail(em),
|
||||
wouldCycle: async (email, sp) => { let cur = sp; for (let i = 0; cur && i < 60; i++) { if (cur.email === email) return true; cur = await accounts.sponsorOf(cur.email); } return false; } });
|
||||
tank.init({ dataDir: dir, chain, accounts, messages, mailer: null, site: 'https://' + name + '.test', follow: glue, store });
|
||||
const P = { name, dir, tank, accounts, store, glue, chats, purchases, bound, hashes: {} };
|
||||
// what the sync module would send for one account (lssync/iapsync rowFor)
|
||||
P.rowFor = async email => {
|
||||
const a = await accounts.byEmail(email); const sp = await accounts.sponsorOf(email);
|
||||
const row = { email, username: a.username, sponsorEmail: sp && sp.email !== email ? sp.email : null };
|
||||
Object.assign(row, SF.rowFields(store.get(email), row.sponsorEmail) || {});
|
||||
row.tank = (await tank.summaryFor(email)) || null;
|
||||
return row;
|
||||
};
|
||||
return P;
|
||||
}
|
||||
// deliver one row from P to Q the way the inbound handlers do (tank state first, then the follow rule)
|
||||
async function deliver(P, Q, email) {
|
||||
const row = await P.rowFor(email);
|
||||
if (Object.prototype.hasOwnProperty.call(row, 'tank')) Q.store.setRemote(email, row.tank);
|
||||
const d = await Q.glue.applyIncoming(email, row);
|
||||
return { row, d };
|
||||
}
|
||||
// a mini "both sides synced" loop: push changed rows both ways until nothing changes (with a guard against ping-pong)
|
||||
async function settle(P, Q, emails) {
|
||||
let rounds = 0, moves = 0;
|
||||
for (; rounds < 6; rounds++) {
|
||||
let changed = 0;
|
||||
for (const [X, Y] of [[P, Q], [Q, P]]) for (const e of emails) {
|
||||
const row = await X.rowFor(e); const h = JSON.stringify(row);
|
||||
if (X.hashes[e] === h) continue; X.hashes[e] = h; changed++;
|
||||
Y.store.setRemote(e, row.tank); const d = await Y.glue.applyIncoming(e, row); if (d.apply) moves++;
|
||||
}
|
||||
if (!changed) break;
|
||||
}
|
||||
return { rounds, moves };
|
||||
}
|
||||
const spOf = async (P, e) => { const s = await P.accounts.sponsorOf(e); return s ? s.email : null; };
|
||||
function people(P, Q) {
|
||||
for (const X of [P, Q]) {
|
||||
X.accounts.add('adopter@x.co', { memberId: 7, username: 'adopter' });
|
||||
X.accounts.add('other@x.co', { memberId: 8, username: 'otheradopter' });
|
||||
X.accounts.add('lead@x.co', { username: 'lead' });
|
||||
X.accounts.add('old@x.co', { username: 'oldsponsor', memberId: 9 });
|
||||
X.purchases.push({ type: 'Purchase', buyerId: 7, priceCents: 2500 }, { type: 'Purchase', buyerId: 8, priceCents: 2500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function network() {
|
||||
await t('network tank: adopting on one platform makes the person adopted on both (same adopter), notices only once', async () => {
|
||||
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||
assert.ok((await P.tank.waiting()).some(w => w.email === 'lead@x.co'));
|
||||
assert.ok((await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
|
||||
const r = await P.tank.adopt('adopter@x.co', 'lead', 'hi'); assert.ok(r.ok, JSON.stringify(r));
|
||||
const { d } = await deliver(P, Q, 'lead@x.co');
|
||||
assert.strictEqual(d.action, 'apply');
|
||||
assert.strictEqual(await spOf(Q, 'lead@x.co'), 'adopter@x.co');
|
||||
assert.ok(!(await Q.tank.waiting()).some(w => w.email === 'lead@x.co'), 'hidden on the other side');
|
||||
assert.strictEqual(P.chats.length, 1); assert.strictEqual(Q.chats.length, 0, 'no chat on the quiet side');
|
||||
const qr = await Q.tank.adopt('other@x.co', 'lead'); assert.ok(qr.error, 'cannot be adopted twice across the network');
|
||||
});
|
||||
await t('ping-pong guard: the applied change comes back as "same" and settles in one round trip', async () => {
|
||||
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||
await P.tank.adopt('adopter@x.co', 'lead');
|
||||
const s = await settle(P, Q, ['lead@x.co']);
|
||||
assert.strictEqual(s.moves, 1); assert.ok(s.rounds <= 3, 'rounds ' + s.rounds);
|
||||
const back = await Q.rowFor('lead@x.co'); const fromP = await P.rowFor('lead@x.co');
|
||||
assert.strictEqual(back.sponsorSetAt, fromP.sponsorSetAt); assert.strictEqual(back.sponsorSetOrigin, 'instantadpay');
|
||||
assert.strictEqual((await P.glue.applyIncoming('lead@x.co', back)).action, 'same');
|
||||
});
|
||||
await t('waiting list hides someone with an open adoption elsewhere even if the follow could not apply', async () => {
|
||||
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||
Q.bound.add('lead@x.co'); // say LinkSpin cannot take the change
|
||||
await P.tank.adopt('adopter@x.co', 'lead');
|
||||
const { d } = await deliver(P, Q, 'lead@x.co');
|
||||
assert.strictEqual(d.action, 'bound');
|
||||
assert.ok(!(await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
|
||||
assert.ok(Q.store.recent(5).some(x => x.action === 'bound' && x.conflict), 'logged for the report');
|
||||
});
|
||||
await t('release mirrors: releasing on the quiet side clears both and closes the open adoption as dropped', async () => {
|
||||
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
|
||||
// the 3-day commitment counts on the quiet side too
|
||||
const early = await Q.tank.release('adopter@x.co', 'lead@x.co'); assert.ok(early.error && /commitment/.test(early.error), JSON.stringify(early));
|
||||
// four days later
|
||||
const realNow = Date.now; Date.now = () => realNow() + 4 * 86400000;
|
||||
try {
|
||||
const r = await Q.tank.release('adopter@x.co', 'lead@x.co'); assert.ok(r.ok, JSON.stringify(r));
|
||||
await settle(P, Q, ['lead@x.co']);
|
||||
assert.strictEqual(await spOf(P, 'lead@x.co'), null); assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
|
||||
const pad = (await P.tank.adminView()).adoptions.find(a => a.adoptee === 'lead@x.co');
|
||||
assert.strictEqual(pad.status, 'dropped');
|
||||
assert.ok((await P.tank.waiting()).some(w => w.email === 'lead@x.co'), 'back in the tank on both');
|
||||
assert.ok((await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
|
||||
} finally { Date.now = realNow; }
|
||||
});
|
||||
await t('expiry mirrors: the adopting side ends the window and the other side follows the clear', async () => {
|
||||
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
|
||||
const realNow = Date.now; Date.now = () => realNow() + 8 * 86400000;
|
||||
try {
|
||||
const sw = await P.tank.sweep(); assert.strictEqual(sw.back, 1);
|
||||
await settle(P, Q, ['lead@x.co']);
|
||||
assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
|
||||
assert.strictEqual(Q.store.get('lead@x.co').by, 'expire');
|
||||
} finally { Date.now = realNow; }
|
||||
});
|
||||
await t('two adoptions per person count across both platforms', async () => {
|
||||
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||
const realNow = Date.now; let off = 0; Date.now = () => realNow() + off;
|
||||
try {
|
||||
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
|
||||
off = 8 * 86400000; await P.tank.sweep(); await settle(P, Q, ['lead@x.co']);
|
||||
const r2 = await Q.tank.adopt('other@x.co', 'lead'); assert.ok(r2.ok, JSON.stringify(r2)); await settle(P, Q, ['lead@x.co']);
|
||||
assert.strictEqual(await spOf(P, 'lead@x.co'), 'other@x.co');
|
||||
off = 16 * 86400000; await Q.tank.sweep(); await settle(P, Q, ['lead@x.co']);
|
||||
// adopted once on each side now: a third adoption anywhere is refused
|
||||
if (!(await P.tank.waiting()).some(w => w.email === 'lead@x.co')) { /* kept where they are after two */ }
|
||||
const r3 = await P.tank.adopt('adopter@x.co', 'lead'); assert.ok(r3.error, JSON.stringify(r3));
|
||||
} finally { Date.now = realNow; }
|
||||
});
|
||||
await t('race: both sides adopt within minutes -> the earlier adoption wins on both, the later one is a conflict', async () => {
|
||||
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||
const realNow = Date.now; let off = 0; Date.now = () => realNow() + off;
|
||||
try {
|
||||
await P.tank.adopt('adopter@x.co', 'lead');
|
||||
off = 90000; await Q.tank.adopt('other@x.co', 'lead'); // 90 s later on LinkSpin, before the sync arrived
|
||||
off = 100000;
|
||||
const a = await deliver(Q, P, 'lead@x.co'); // the later change reaches the earlier side: kept, flagged
|
||||
assert.strictEqual(a.d.action, 'conflict-keep');
|
||||
const b = await deliver(P, Q, 'lead@x.co'); // the earlier change reaches the later side: applied, flagged
|
||||
assert.strictEqual(b.d.action, 'conflict-apply');
|
||||
await settle(P, Q, ['lead@x.co']);
|
||||
assert.strictEqual(await spOf(P, 'lead@x.co'), 'adopter@x.co'); assert.strictEqual(await spOf(Q, 'lead@x.co'), 'adopter@x.co');
|
||||
const qad = (await Q.tank.adminView()).adoptions.find(x => x.adopter === 'other@x.co');
|
||||
assert.strictEqual(qad.status, 'conflict');
|
||||
assert.ok(P.store.recent(10).some(x => x.action === 'conflict-keep'));
|
||||
} finally { Date.now = realNow; }
|
||||
});
|
||||
await t('ordinary join on the other side is never overwritten by an adoption here (diverged, reported)', async () => {
|
||||
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||
await Q.accounts.setSponsorRef('lead@x.co', 'oldsponsor'); // joined LinkSpin through @oldsponsor's link
|
||||
await P.tank.adopt('adopter@x.co', 'lead');
|
||||
const { d } = await deliver(P, Q, 'lead@x.co');
|
||||
assert.strictEqual(d.action, 'diverged'); assert.strictEqual(await spOf(Q, 'lead@x.co'), 'old@x.co');
|
||||
});
|
||||
await t('rescue clears the other side when both had the same sponsor', async () => {
|
||||
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||
for (const X of [P, Q]) await X.accounts.setSponsorRef('lead@x.co', 'oldsponsor');
|
||||
await P.glue.setDeliberate('lead@x.co', '', 'rescue', 'test');
|
||||
const { d } = await deliver(P, Q, 'lead@x.co');
|
||||
assert.strictEqual(d.action, 'apply'); assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
|
||||
});
|
||||
await t('admin pick from the mismatch report applies on the unbound side and refuses on a bound one', async () => {
|
||||
const P = platform('instantadpay', 'linkspin'); P.accounts.add('m@x.co'); P.accounts.add('s@x.co', { username: 'sss' });
|
||||
const ok = await P.glue.adminApply('m@x.co', 's@x.co'); assert.ok(ok.ok, JSON.stringify(ok)); assert.strictEqual(await spOf(P, 'm@x.co'), 's@x.co');
|
||||
assert.strictEqual(P.store.get('m@x.co').by, 'admin');
|
||||
P.bound.add('m@x.co'); const no = await P.glue.adminApply('m@x.co', null); assert.ok(no.error && /bound/.test(no.error));
|
||||
assert.strictEqual(await spOf(P, 'm@x.co'), 's@x.co');
|
||||
});
|
||||
await t('mismatch report: differ / one-sided rows, matches counted', async () => {
|
||||
const r = SF.mismatches([{ email: 'a@x', sponsorEmail: 's1' }, { email: 'b@x', sponsorEmail: 's1' }, { email: 'c@x', sponsorEmail: null }, { email: 'd@x', sponsorEmail: 's2' }],
|
||||
[{ email: 'a@x', sponsorEmail: 's1' }, { email: 'b@x', sponsorEmail: 's2' }, { email: 'c@x', sponsorEmail: 's3' }, { email: 'e@x', sponsorEmail: 's4' }]);
|
||||
assert.strictEqual(r.shared, 3); assert.strictEqual(r.same, 1); assert.deepStrictEqual(r.rows.map(x => x.email + ':' + x.kind), ['b@x:differ', 'c@x:ls-only']);
|
||||
});
|
||||
await t('pending follow: retried later and settled (sponsor account arrives)', async () => {
|
||||
const Q = platform('linkspin', 'instantadpay'); Q.accounts.add('lead@x.co');
|
||||
const row = { email: 'lead@x.co', sponsorEmail: 'late@x.co', sponsorSetAt: T0, sponsorSetBy: 'adopt', sponsorPrevEmail: null, sponsorSetOrigin: 'instantadpay' };
|
||||
assert.strictEqual((await Q.glue.applyIncoming('lead@x.co', row)).action, 'pending');
|
||||
Q.accounts.add('late@x.co', { username: 'late' });
|
||||
const rr = await Q.glue.retryPending(); assert.strictEqual(rr.settled, 1);
|
||||
assert.strictEqual(await spOf(Q, 'lead@x.co'), 'late@x.co'); assert.strictEqual(Q.store.pendingFor('lead@x.co'), null);
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
await pure(); await network();
|
||||
console.log(results.join('\n'));
|
||||
console.log('\nsponsorfollow: ' + passed + ' passed, ' + failed + ' failed');
|
||||
process.exit(failed ? 1 : 0);
|
||||
})();
|
||||
Reference in New Issue
Block a user