diff --git a/website/node/imperial-raid-orders.mjs b/website/node/imperial-raid-orders.mjs index 61d0f4fb..2ff02086 100644 --- a/website/node/imperial-raid-orders.mjs +++ b/website/node/imperial-raid-orders.mjs @@ -32,6 +32,14 @@ export function createImperialRaidOrders(db,{resolveActor,resolveContext,charge, return work(tx); });} const order=(tx,id)=>tx.first('SELECT * FROM jarvis_imperial_raid_orders WHERE id=? FOR UPDATE',[id]); + async function pollOrders(store,server,{candidate=null,lock=false}={}){ + const rows=await store.query("SELECT accepted_json FROM jarvis_imperial_raid_orders WHERE state IN ('accepted','warning','started') ORDER BY created_at,id LIMIT 501"+(lock?' FOR UPDATE':'')); + if(rows.length>500)fail('The active raid register requires reconciliation.'); + const orders=rows.map(r=>parse(r.accepted_json)).filter(p=>p?.server===server);if(candidate)orders.push(candidate); + const response={ok:true,schema:1,orders}; + if(orders.length>100||Buffer.byteLength(JSON.stringify(response),'utf8')>262144)fail('This server’s raid delivery register is full. Resolve existing raids before another paid order.'); + return response; + } async function bind(tx,input){ const actor=await resolveActor(tx,input.uuid,{lock:true});if(!actor?.id)fail('Link an active personal Minecraft account first.',403); const row=await order(tx,input.requestId),hash=imperialRaidInputHash(input); @@ -109,6 +117,9 @@ export function createImperialRaidOrders(db,{resolveActor,resolveContext,charge, }catch(error){if(!error.status)throw error;return rejectPrepared(tx,row,error.message);} // Do not catch posting failures inside this transaction: a timeout, partial // write or failed key insert must roll EVERYTHING back, leaving the same intent. + // Reserve actual native delivery capacity BEFORE any debit. Both UUID fields + // below have the exact final serialized size; no silent page/truncation. + await pollOrders(tx,input.server,{candidate:{...p,receiptKeyId:p.preflightNonce,bankOrderId:p.id,acceptedAt:now},lock:true}); const receipt=await charge(tx,{...p,actorId:row.actor_id}); if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(receipt?.receiptKeyId||'')||receipt.bankOrderId!==row.id)throw Error('Original atomic paid raid receipt required'); const resultOrder={...p,receiptKeyId:receipt.receiptKeyId,bankOrderId:receipt.bankOrderId,acceptedAt:now}; @@ -161,9 +172,7 @@ export function createImperialRaidOrders(db,{resolveActor,resolveContext,charge, return {ok:true,schema:1,context:{actorUuid:input.uuid,orderingClanId:input.orderingClanId,targetClanId:input.targetClanId,orderingClanName:c.orderingClanName,targetClanName:c.targetClanName,server:input.server,accounts:q.accounts,uniqueSourceAccountId:q.accounts.length===1?String(q.accounts[0].id):null,feeMinor:q.feeMinor,currency:'DM',chainId:q.chainId,retaliationLevel:q.level,home:c.home,policy:publicPolicy()}}; } if(input.action==='poll'){ - const rows=await db.query("SELECT accepted_json FROM jarvis_imperial_raid_orders WHERE state IN ('accepted','warning','started') ORDER BY created_at,id LIMIT 501"); - if(rows.length>500)fail('The active raid register requires reconciliation.'); - return {ok:true,schema:1,orders:rows.map(r=>parse(r.accepted_json)).filter(p=>p?.server===input.server)}; + return pollOrders(db,input.server); } return locked(async tx=>{ if(input.action==='prepare')return prepare(tx,input); diff --git a/website/tests/imperial-raid-orders.test.mjs b/website/tests/imperial-raid-orders.test.mjs index 6e7da44d..76bd0307 100644 --- a/website/tests/imperial-raid-orders.test.mjs +++ b/website/tests/imperial-raid-orders.test.mjs @@ -77,3 +77,21 @@ test('a third retaliation that never starts cancels escalation before queuing it 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();} +});