web/website/tests/imperial-raid-orders.test.mjs

97 lines
16 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import {randomUUID} from 'node:crypto';
import {BankFixture} from './postbank-fixture.mjs';
import {PostbankPayments} from '../node/postbank-payments.mjs';
import {initializeImperialRaids,createImperialRaidOrders} from '../node/imperial-raid-orders.mjs';
import {IMPERIAL_RAID_POLICY as P} from '../node/imperial-raid-protocol.mjs';
const id=n=>'00000000-0000-4000-8000-'+String(n).padStart(12,'0');
async function fixture(){
const db=new BankFixture(),query=db.query.bind(db);db.query=(sql,args=[])=>query(sql.replace(/\) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4/g,')'),args);await initializeImperialRaids(db);let now=1000000000;
await db.query("INSERT INTO pb_accounts(id,type_code,display_name,balance_minor,system_key,created_at) VALUES(1,'105','Synthetic clan A',10000000,NULL,0),(2,'999','Synthetic Tax treasury',0,'sys_tax_treasury',0),(3,'105','Synthetic clan B',10000000,NULL,0)");
await db.query('CREATE TABLE fixture_raid_keys(id TEXT PRIMARY KEY,order_id TEXT UNIQUE)');
const options={allowed:true,version:1,revision:1,failAfterPost:false,badReceipt:false};
const resolveActor=async(_tx,uuid)=>[id(1),id(8)].includes(uuid)?{id:uuid===id(1)?id(10):id(11)}:null;
const resolveContext=async(tx,input)=>{
if(!options.allowed)throw Object.assign(Error('Current clan authority changed'),{status:403});
if(input.uuid!==(input.orderingClanId===id(3)?id(1):id(8)))throw Object.assign(Error('Not this clan owner'),{status:403});
const account=await tx.first('SELECT * FROM pb_accounts WHERE id=?',[input.orderingClanId===id(3)?1:3]);
return {orderingClanName:'Ordering clan',targetClanName:'Target clan',authority:{version:options.version},home:{worldUuid:id(7),position:{x:12,y:80,z:30},claimRevision:options.revision},accounts:[{id:String(account.id),name:account.display_name,availableMinor:String(account.balance_minor-account.reserved_minor)}]};
};
const charge=async(tx,p)=>{
const source=await tx.first('SELECT * FROM pb_accounts WHERE id=?',[p.sourceAccountId]),tax=await tx.first('SELECT * FROM pb_accounts WHERE id=2');source.entity_id=id(40);
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[p.id,p.actorId,source.id,tax.id,p.inputHash,p.feeMinor,'Synthetic Imperial raid',now]);
await new PostbankPayments(db,null,{clock:()=>now}).post(tx,{id:p.id,actor_id:p.actorId,amount_minor:p.feeMinor},source,tax,false);
if(options.failAfterPost)throw Error('Injected failure after real ledger posting');
const key=randomUUID();await tx.query('INSERT INTO fixture_raid_keys VALUES(?,?)',[key,p.id]);
return {receiptKeyId:options.badReceipt?'unbound':key,bankOrderId:p.id};
};
const service=createImperialRaidOrders(db,{resolveActor,resolveContext,charge,clock:()=>now});
const intent=(reverse=false)=>({server:'arrakis',uuid:reverse?id(8):id(1),requestId:randomUUID(),orderingClanId:reverse?id(4):id(3),targetClanId:reverse?id(3):id(4),sourceAccountId:reverse?'3':'1'});
const prepare=input=>service.execute({action:'prepare',...input});
const acceptInput=p=>({action:'accept',server:p.server,orderId:p.id,eventId:randomUUID(),inputHash:p.inputHash,preflightNonce:p.preflightNonce,preflight:{...p.home,defendersOnline:0,spawnable:true,protected:false,observedAt:now}});
const accept=async input=>{const p=await prepare(input),a=acceptInput(p.order);return {p,a,result:await service.execute(a)};};
const start=async p=>{now=p.acceptedAt+P.noticeMs;return service.execute({action:'ack',server:p.server,orderId:p.id,eventId:randomUUID(),phase:'started',occurredAt:now});};
const terminal=(p,outcome='survived',activeMillis=P.durationMs)=>({action:'outcome',server:p.server,orderId:p.id,eventId:randomUUID(),outcome,startedAt:p.acceptedAt+P.noticeMs,occurredAt:now,activeMillis});
return {db,options,service,intent,prepare,acceptInput,accept,start,terminal,clock:()=>now,setTime:n=>now=n,close:()=>db.close()};
}
test('context and prepare never post a payment; a prepared original can be read unchanged',async()=>{
const f=await fixture();try{const i=f.intent(),c=await f.service.execute({action:'context',server:i.server,uuid:i.uuid,orderingClanId:i.orderingClanId,targetClanId:i.targetClanId});assert.equal(c.context.uniqueSourceAccountId,'1');const p=await f.prepare(i);assert.equal(p.state,'prepared');assert.equal(p.order.id,i.requestId);assert.deepEqual(await f.service.execute({action:'status',...i}),p);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.close();}
});
test('cancellation arriving before a delayed prepare leaves a durable unpaid tombstone',async()=>{
const f=await fixture();try{const i=f.intent(),c=await f.service.execute({action:'cancel_prepared',...i});assert.equal(c.charged,false);assert.equal(c.definitive,true);assert.deepEqual(await f.prepare(i),c);assert.deepEqual(await f.service.execute({action:'status',...i}),c);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.close();}
});
test('unknown status is not definitive, and changing original target/account/actor cannot cancel another intent',async()=>{
const f=await fixture();try{const i=f.intent();assert.equal((await f.service.execute({action:'status',...i})).definitive,false);await f.prepare(i);for(const patch of [{sourceAccountId:'3'},{targetClanId:id(9)},{uuid:id(8)}])await assert.rejects(f.service.execute({action:'cancel_prepared',...i,...patch}),e=>e.status===409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.close();}
});
test('concurrent acceptance retries use the original bank order and exactly two ledger legs',async()=>{
const f=await fixture();try{const i=f.intent(),p=await f.prepare(i),a=f.acceptInput(p.order),results=await Promise.all([1,2,3].map(()=>f.service.execute(a)));assert.deepEqual(results[0],results[1]);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,2);assert.equal((await f.db.first('SELECT COUNT(*) n FROM fixture_raid_keys')).n,1);assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=1')).b,7500000);assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=2')).b,2500000);assert.equal((await f.service.execute({action:'cancel_prepared',...i})).state,'accepted');}finally{f.close();}
});
test('cancel/accept races cannot clear a paid receipt or debit a cancelled intent',async()=>{
for(const cancelFirst of [true,false]){const f=await fixture();try{const i=f.intent(),p=await f.prepare(i),a=f.acceptInput(p.order),cancel={action:'cancel_prepared',...i};await Promise.all((cancelFirst?[cancel,a]:[a,cancel]).map(v=>f.service.execute(v)));const result=await f.service.execute({action:'status',...i});assert.equal(result.state,cancelFirst?'cancelled':'accepted');assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,cancelFirst?0:1);}finally{f.close();}}
});
test('expired preparation and changed authority/home/funds are definitive unpaid rejections',async()=>{
for(const mutation of ['expiry','authority','home','funds']){const f=await fixture();try{const i=f.intent(),p=await f.prepare(i),a=f.acceptInput(p.order);if(mutation==='expiry')f.setTime(f.clock()+P.preparedMs+1);if(mutation==='authority')f.options.allowed=false;if(mutation==='home')f.options.revision++;if(mutation==='funds')await f.db.query('UPDATE pb_accounts SET balance_minor=1 WHERE id=1');const r=await f.service.execute(a);assert.equal(r.charged,false);assert.equal(r.definitive,true);assert.equal(r.state,mutation==='expiry'?'expired':'rejected');assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.close();}}
});
test('posting/key-binding failures roll back balance, entries, key and accepted state together',async()=>{
for(const badReceipt of [false,true]){const f=await fixture();try{const i=f.intent(),p=await f.prepare(i);f.options.badReceipt=badReceipt;f.options.failAfterPost=!badReceipt;await assert.rejects(f.service.execute(f.acceptInput(p.order)));assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=1')).b,10000000);for(const table of ['pb_orders','pb_entries','fixture_raid_keys'])assert.equal((await f.db.first('SELECT COUNT(*) n FROM '+table)).n,0);assert.equal((await f.service.execute({action:'status',...i})).state,'prepared');}finally{f.close();}}
});
test('the same event ID with changed evidence conflicts without another debit',async()=>{
const f=await fixture();try{const {a}=await f.accept(f.intent());await assert.rejects(f.service.execute({...a,preflight:{...a.preflight,defendersOnline:1}}),e=>e.status===409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.close();}
});
test('an empty party or short active duration cannot create a success quest',async()=>{
const f=await fixture();try{const {result}=await f.accept(f.intent()),p=result.order;await assert.rejects(f.service.execute({...f.terminal(p),startedAt:0,activeMillis:0}),e=>e.status===409);await f.start(p);f.setTime(f.clock()+1000);await assert.rejects(f.service.execute(f.terminal(p,'survived',1000)),e=>e.status===409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_imperial_raid_jobs')).n,0);}finally{f.close();}
});
test('full survival and commander defeat queue exactly the approved Reputation result once',async()=>{
for(const outcome of ['survived','commander_defeated']){const f=await fixture();try{const {result}=await f.accept(f.intent()),p=result.order;await f.start(p);f.setTime(f.clock()+(outcome==='survived'?P.durationMs:1000));const e=f.terminal(p,outcome,outcome==='survived'?P.durationMs:1000),r=await f.service.execute(e);assert.equal(r.orderId,p.id);assert.equal(r.eventId,e.eventId);assert.deepEqual(await f.service.execute(e),r);const jobs=await f.db.query('SELECT * FROM jarvis_imperial_raid_jobs');assert.equal(jobs.length,1);assert.equal(jobs[0].kind,'quest');const payload=JSON.parse(jobs[0].payload_json);assert.equal(payload.xp,outcome==='survived'?1000:100);assert.equal(payload.personalXP,undefined);assert.equal(payload.amountMinor,undefined);await assert.rejects(f.service.execute({...e,eventId:randomUUID()}),x=>x.status===409);}finally{f.close();}}
});
test('post-accept spawn failure queues only an original-payment refund and no quest',async()=>{
const f=await fixture();try{const {result}=await f.accept(f.intent()),p=result.order,e={...f.terminal(p,'spawn_failed',0),startedAt:0},r=await f.service.execute(e);assert.equal(r.state,'neutral');assert.equal(r.refundState,'queued');assert.deepEqual(await f.service.execute(e),r);const jobs=await f.db.query('SELECT * FROM jarvis_imperial_raid_jobs');assert.equal(jobs.length,1);assert.equal(jobs[0].kind,'refund');assert.equal(JSON.parse(jobs[0].payload_json).orderId,p.id);assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=1')).b,7500000);}finally{f.close();}
});
test('third paid retaliation queues one chain-bound original-war job at25/30/35/40k fees',async()=>{
const f=await fixture();try{const orders=[];for(let n=0;n<4;n++){const {result}=await f.accept(f.intent(n%2===1)),p=result.order;orders.push(p);await f.start(p);f.setTime(f.clock()+1000);await f.service.execute(f.terminal(p,'commander_defeated',1000));}assert.deepEqual(orders.map(p=>p.feeMinor),['2500000','3000000','3500000','4000000']);assert.equal(new Set(orders.map(p=>p.chainId)).size,1);const jobs=await f.db.query("SELECT * FROM jarvis_imperial_raid_jobs WHERE kind='war'");assert.equal(jobs.length,1);assert.equal(JSON.parse(jobs[0].payload_json).chainId,orders[0].chainId);assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=2')).b,13000000);assert.equal((await f.prepare(f.intent())).state,'rejected');}finally{f.close();}
});
test('a third retaliation that never starts cancels escalation before queuing its original-fee recovery',async()=>{
const f=await fixture();try{for(let n=0;n<3;n++){const {result}=await f.accept(f.intent(n%2===1)),p=result.order;await f.start(p);f.setTime(f.clock()+1000);await f.service.execute(f.terminal(p,'commander_defeated',1000));}const {result}=await f.accept(f.intent(true)),p=result.order;assert.equal((await f.db.first("SELECT state FROM jarvis_imperial_raid_jobs WHERE order_id=? AND kind='war'",[p.id])).state,'waiting_start');await f.service.execute({...f.terminal(p,'spawn_failed',0),startedAt:0});assert.equal((await f.db.first("SELECT state FROM jarvis_imperial_raid_jobs WHERE order_id=? AND kind='war'",[p.id])).state,'cancelled');assert.equal((await f.db.first("SELECT state FROM jarvis_imperial_raid_jobs WHERE order_id=? AND kind='refund'",[p.id])).state,'queued');}finally{f.close();}
});
test('neutral interruption cannot refund an automatic war already committed for that order',async()=>{
const f=await fixture();try{const {result}=await f.accept(f.intent()),p=result.order;await f.start(p);await f.db.query('UPDATE jarvis_imperial_raid_orders SET war_campaign_id=? WHERE id=?',[id(90),p.id]);f.setTime(f.clock()+1000);const r=await f.service.execute(f.terminal(p,'interrupted',1000));assert.equal(r.refundState,'not_due');assert.equal(r.refundReason,'war_started');assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_imperial_raid_jobs')).n,0);}finally{f.close();}
});
test('native delivery capacity is reserved before charging: all100 are returned, the101st is not charged or silently omitted',async()=>{
const f=await fixture();try{
const prepared=(await f.prepare(f.intent())).order,ids=[];
for(let n=0;n<100;n++){const clone={...prepared,id:randomUUID(),requestId:randomUUID(),receiptKeyId:randomUUID(),bankOrderId:randomUUID(),acceptedAt:f.clock()};ids.push(clone.id);await f.db.query("INSERT INTO jarvis_imperial_raid_orders(id,actor_id,minecraft_uuid,input_hash,intent_json,state,accepted_json,created_at,expires_at,updated_at) VALUES(?,?,?,?,?,'accepted',?,?,?,?)",[clone.id,id(10),id(1),prepared.inputHash,'{}',JSON.stringify(clone),f.clock(),f.clock()+120000,f.clock()]);}
const poll=()=>f.service.execute({action:'poll',server:'arrakis'});assert.equal((await poll()).orders.length,100);
await assert.rejects(f.service.execute(f.acceptInput(prepared)),/register is full/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM fixture_raid_keys')).n,0);
await f.db.query('DELETE FROM jarvis_imperial_raid_orders WHERE id=?',[ids[0]]);assert.equal((await f.service.execute(f.acceptInput(prepared))).charged,true);assert.equal((await poll()).orders.length,100);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
}finally{f.close();}
});
test('UTF8 poll-size overflow requires reconciliation and refuses another debit without dropping existing orders',async()=>{
const f=await fixture();try{
const prepared=(await f.prepare(f.intent())).order,clone={...prepared,id:randomUUID(),orderingClanName:'界'.repeat(90000),acceptedAt:f.clock(),receiptKeyId:randomUUID(),bankOrderId:randomUUID()};
await f.db.query("INSERT INTO jarvis_imperial_raid_orders(id,actor_id,minecraft_uuid,input_hash,intent_json,state,accepted_json,created_at,expires_at,updated_at) VALUES(?,?,?,?,?,'accepted',?,?,?,?)",[clone.id,id(10),id(1),prepared.inputHash,'{}',JSON.stringify(clone),f.clock(),f.clock()+120000,f.clock()]);
await assert.rejects(f.service.execute({action:'poll',server:'arrakis'}),/register is full/);await assert.rejects(f.service.execute(f.acceptInput(prepared)),/register is full/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first("SELECT COUNT(*) n FROM jarvis_imperial_raid_orders WHERE state='accepted'")).n,1);
}finally{f.close();}
});