forked from unimatrix/web
185 lines
17 KiB
JavaScript
185 lines
17 KiB
JavaScript
import {randomUUID} from 'node:crypto';
|
|
import {IMPERIAL_RAID_POLICY as P,validateImperialRaidInput,imperialRaidIntent,imperialRaidInputHash,imperialRaidEventHash,imperialRaidFee,unpaidRaidResponse,raidEventAcknowledgement} from './imperial-raid-protocol.mjs';
|
|
|
|
export const IMPERIAL_RAID_SCHEMA=[
|
|
`CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_guard(id INTEGER PRIMARY KEY) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_orders(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,input_hash CHAR(64) NOT NULL,intent_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,prepared_json TEXT NULL,accepted_json TEXT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,updated_at BIGINT NOT NULL,started_at BIGINT NULL,terminal_event_id CHAR(36) NULL,outcome_json TEXT NULL,war_campaign_id CHAR(36) NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_clans(clan_id CHAR(36) PRIMARY KEY,last_order_at BIGINT NULL,last_raided_at BIGINT NULL,revenge_against CHAR(36) NULL,revenge_until BIGINT NULL,revenge_level INTEGER NOT NULL DEFAULT 0,chain_id CHAR(36) NULL,active_order_id CHAR(36) NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_events(event_id CHAR(36) PRIMARY KEY,order_id CHAR(36) NOT NULL,event_hash CHAR(64) NOT NULL,response_json TEXT NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_jobs(order_id CHAR(36) NOT NULL,kind VARCHAR(16) NOT NULL,payload_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,attempted_at BIGINT NULL,completed_at BIGINT NULL,lease_token CHAR(36) NULL,lease_until BIGINT NULL,result_json TEXT NULL,PRIMARY KEY(order_id,kind)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
|
];
|
|
export const initializeImperialRaids=async db=>{for(const sql of IMPERIAL_RAID_SCHEMA)await db.query(sql);};
|
|
export async function lockImperialRaidGuard(tx){
|
|
await tx.query('INSERT INTO jarvis_imperial_raid_guard(id) VALUES(1) ON DUPLICATE KEY UPDATE id=VALUES(id)');
|
|
await tx.first('SELECT id FROM jarvis_imperial_raid_guard WHERE id=1 FOR UPDATE');
|
|
}
|
|
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
|
|
const publicPolicy=()=>Object.fromEntries(['noticeMs','durationMs','baseRaiders','perDefender','maxRaiders','minDefendersOnline'].map(k=>[k,P[k]]));
|
|
const paid=row=>!!row?.accepted_json;
|
|
const accepted=row=>({ok:true,schema:1,state:'accepted',charged:true,order:JSON.parse(row.accepted_json)});
|
|
const finalUnpaid=row=>unpaidRaidResponse(row.id,row.input_hash,row.state,row.outcome_json?JSON.parse(row.outcome_json).message:null);
|
|
const parse=value=>value?JSON.parse(value):null;
|
|
const same=(a,b)=>imperialRaidEventHash(a)===imperialRaidEventHash(b);
|
|
const selectedAccount=(quote,id)=>{const account=quote.accounts.find(a=>String(a.id)===id);if(!account)fail('Choose a currently authorised clan bank account.');if(!/^\d+$/.test(account.availableMinor)||BigInt(account.availableMinor)<BigInt(quote.feeMinor))fail('Insufficient authorised clan funds.');return account;};
|
|
|
|
// resolveActor and resolveContext read the ORIGINAL linked account, clan deed,
|
|
// Home Block and debit rights inside this transaction. charge must post the
|
|
// existing bank/key operation on the supplied transaction, never another pool.
|
|
export function createImperialRaidOrders(db,{resolveActor,resolveContext,charge,clock=Date.now,makeId=randomUUID}={}){
|
|
if(![resolveActor,resolveContext,charge].every(f=>typeof f==='function'))throw TypeError('Authoritative Imperial raid adapters required');
|
|
async function locked(work){return db.transaction(async tx=>{
|
|
await lockImperialRaidGuard(tx);
|
|
return work(tx);
|
|
});}
|
|
const order=(tx,id)=>tx.first('SELECT * FROM jarvis_imperial_raid_orders WHERE id=? FOR UPDATE',[id]);
|
|
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);
|
|
if(row&&(row.actor_id!==actor.id||row.input_hash!==hash||row.minecraft_uuid!==input.uuid))fail('This raid reference belongs to a different original intent.');
|
|
return {actor,row,hash};
|
|
}
|
|
async function insert(tx,input,actor,hash,state,prepared=null,message=null){
|
|
const now=clock();await tx.query('INSERT INTO jarvis_imperial_raid_orders(id,actor_id,minecraft_uuid,input_hash,intent_json,state,prepared_json,accepted_json,created_at,expires_at,updated_at,started_at,terminal_event_id,outcome_json) VALUES(?,?,?,?,?,?,?,NULL,?,?,?,NULL,NULL,?)',[input.requestId,actor.id,input.uuid,hash,JSON.stringify(imperialRaidIntent(input)),state,prepared?JSON.stringify(prepared):null,now,prepared?.expiresAt||now,now,message?JSON.stringify({message}):null]);
|
|
return order(tx,input.requestId);
|
|
}
|
|
async function expire(tx,row){
|
|
if(row.state==='prepared'&&Number(row.expires_at)<=clock()){
|
|
await tx.query("UPDATE jarvis_imperial_raid_orders SET state='expired',updated_at=? WHERE id=?",[clock(),row.id]);return {...row,state:'expired'};
|
|
}return row;
|
|
}
|
|
async function rejectPrepared(tx,row,message){
|
|
await tx.query("UPDATE jarvis_imperial_raid_orders SET state='rejected',outcome_json=?,updated_at=? WHERE id=?",[JSON.stringify({message}),clock(),row.id]);
|
|
return finalUnpaid({...row,state:'rejected',outcome_json:JSON.stringify({message})});
|
|
}
|
|
async function clan(tx,id,create=false){
|
|
if(create)await tx.query('INSERT INTO jarvis_imperial_raid_clans(clan_id) VALUES(?) ON DUPLICATE KEY UPDATE clan_id=VALUES(clan_id)',[id]);
|
|
return await tx.first('SELECT * FROM jarvis_imperial_raid_clans WHERE clan_id=?'+(create?' FOR UPDATE':''),[id])||{clan_id:id};
|
|
}
|
|
async function quote(tx,input,{lock=false}={}){
|
|
const context=await resolveContext(tx,input,{lock}),a=await clan(tx,input.orderingClanId,lock),b=await clan(tx,input.targetClanId,lock),now=clock();
|
|
if(input.orderingClanId===input.targetClanId)fail('Choose a rival clan.');
|
|
if(b.active_order_id)fail('This clan already has an active Imperial raid.');
|
|
const retaliation=a.revenge_against===input.targetClanId&&Number(a.revenge_until)>now,level=retaliation?Number(a.revenge_level)+1:0;
|
|
if(!retaliation&&a.last_order_at!==null&&a.last_order_at!==undefined&&now-Number(a.last_order_at)<P.ordererCooldownMs)fail('The ordering clan is still on its Imperial raid cooldown.');
|
|
if(!retaliation&&b.last_raided_at!==null&&b.last_raided_at!==undefined&&now-Number(b.last_raided_at)<P.targetCooldownMs)fail('The target clan is still protected by its raid cooldown.');
|
|
const feeMinor=imperialRaidFee(level),accounts=context.accounts||[];
|
|
return {context,a,b,level,feeMinor,chainId:retaliation?a.chain_id:null,accounts};
|
|
}
|
|
async function eventReplay(tx,input){
|
|
const prior=await tx.first('SELECT * FROM jarvis_imperial_raid_events WHERE event_id=? FOR UPDATE',[input.eventId]);
|
|
if(!prior)return null;if(prior.order_id!==input.orderId||prior.event_hash!==imperialRaidEventHash(input))fail('This raid event reference changed.');
|
|
return JSON.parse(prior.response_json);
|
|
}
|
|
async function saveEvent(tx,input,response){
|
|
await tx.query('INSERT INTO jarvis_imperial_raid_events(event_id,order_id,event_hash,response_json,created_at) VALUES(?,?,?,?,?)',[input.eventId,input.orderId,imperialRaidEventHash(input),JSON.stringify(response),clock()]);return response;
|
|
}
|
|
async function requirePaid(tx,input){
|
|
const row=await order(tx,input.orderId);if(!paid(row)||parse(row.intent_json).server!==input.server)fail('This backend has no accepted receipt for that order.');return row;
|
|
}
|
|
async function queue(tx,row,kind,payload,state='queued'){
|
|
await tx.query('INSERT INTO jarvis_imperial_raid_jobs(order_id,kind,payload_json,state,created_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE order_id=VALUES(order_id)',[row.id,kind,JSON.stringify(payload),state,clock()]);
|
|
}
|
|
async function prepare(tx,input){
|
|
const {actor,row:existing,hash}=await bind(tx,input);
|
|
if(existing){const row=await expire(tx,existing);if(paid(row))return accepted(row);if(row.state==='prepared')return {ok:true,schema:1,state:'prepared',order:parse(row.prepared_json)};return finalUnpaid(row);}
|
|
let q;
|
|
try{q=await quote(tx,input,{lock:true});selectedAccount(q,input.sourceAccountId);}
|
|
catch(error){if(!error.status)throw error;return finalUnpaid(await insert(tx,input,actor,hash,'rejected',null,error.message));}
|
|
const now=clock(),c=q.context,prepared={id:input.requestId,requestId:input.requestId,inputHash:hash,preflightNonce:makeId(),preparedAt:now,expiresAt:now+P.preparedMs,actorUuid:input.uuid,orderingClanId:input.orderingClanId,targetClanId:input.targetClanId,orderingClanName:c.orderingClanName,targetClanName:c.targetClanName,sourceAccountId:input.sourceAccountId,feeMinor:q.feeMinor,currency:'DM',server:input.server,chainId:q.chainId||makeId(),retaliationLevel:q.level,home:c.home,policy:publicPolicy()};
|
|
await insert(tx,input,actor,hash,'prepared',prepared);
|
|
// Internal authority versions stay outside the native public DTO.
|
|
await tx.query('UPDATE jarvis_imperial_raid_orders SET outcome_json=? WHERE id=?',[JSON.stringify({authority:c.authority}),input.requestId]);
|
|
return {ok:true,schema:1,state:'prepared',order:prepared};
|
|
}
|
|
async function accept(tx,input){
|
|
const row=await order(tx,input.orderId);if(!row||parse(row.intent_json).server!==input.server)fail('Prepared Imperial raid unavailable.');
|
|
const prior=await eventReplay(tx,input);if(prior)return prior;
|
|
const p=parse(row.prepared_json);if(!p||p.inputHash!==input.inputHash||p.preflightNonce!==input.preflightNonce)fail('The original prepared raid binding is required.');
|
|
if(paid(row))return saveEvent(tx,input,accepted(row));
|
|
const fresh=await expire(tx,row);if(fresh.state!=='prepared')return finalUnpaid(fresh);
|
|
const evidence=input.preflight,now=clock();
|
|
if(evidence.observedAt<now-30000||evidence.observedAt>now+10000||!same(evidence.position,p.home.position)||evidence.worldUuid!==p.home.worldUuid||evidence.claimRevision!==p.home.claimRevision) return rejectPrepared(tx,row,'The native Home Block preflight changed or expired.');
|
|
let q;
|
|
try{
|
|
const intent=parse(row.intent_json),actor=await resolveActor(tx,intent.uuid,{lock:true});if(actor?.id!==row.actor_id)fail('The original linked actor changed.',403);
|
|
q=await quote(tx,intent,{lock:true});
|
|
if(q.feeMinor!==p.feeMinor||q.level!==p.retaliationLevel||(q.chainId&&q.chainId!==p.chainId)||!same(q.context.home,p.home)||!same(q.context.authority,parse(row.outcome_json)?.authority))fail('The clan authority, fee, chain or Home Block changed.');
|
|
selectedAccount(q,p.sourceAccountId);
|
|
if(evidence.defendersOnline<P.minDefendersOnline)fail('Too few defenders are online.');
|
|
}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.
|
|
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};
|
|
await tx.query("UPDATE jarvis_imperial_raid_orders SET state='accepted',accepted_json=?,updated_at=? WHERE id=?",[JSON.stringify(resultOrder),now,row.id]);
|
|
if(q.level)await tx.query('UPDATE jarvis_imperial_raid_clans SET revenge_against=NULL,revenge_until=NULL,revenge_level=0 WHERE clan_id=?',[p.orderingClanId]);
|
|
else await tx.query('UPDATE jarvis_imperial_raid_clans SET last_order_at=? WHERE clan_id=?',[now,p.orderingClanId]);
|
|
await tx.query('UPDATE jarvis_imperial_raid_clans SET last_raided_at=?,active_order_id=?,revenge_against=?,revenge_until=?,revenge_level=?,chain_id=? WHERE clan_id=?',[now,row.id,q.level>=P.warAfter?null:p.orderingClanId,q.level>=P.warAfter?null:now+P.revengeMs,q.level>=P.warAfter?0:q.level,p.chainId,p.targetClanId]);
|
|
if(q.level===P.warAfter)await queue(tx,row,'war',{orderId:row.id,chainId:p.chainId,orderingClanId:p.orderingClanId,targetClanId:p.targetClanId},'waiting_start');
|
|
return saveEvent(tx,input,{ok:true,schema:1,state:'accepted',charged:true,order:resultOrder});
|
|
}
|
|
async function acknowledge(tx,input){
|
|
const row=await requirePaid(tx,input),prior=await eventReplay(tx,input);if(prior)return prior;
|
|
const p=parse(row.accepted_json);
|
|
if(input.occurredAt<p.acceptedAt||input.occurredAt>clock()+30000)fail('Raid acknowledgement time is invalid.');
|
|
if(input.phase==='started'){
|
|
if(input.occurredAt<p.acceptedAt+P.noticeMs)fail('The full raid warning must finish before starting.');
|
|
if(row.started_at!==null&&Number(row.started_at)!==input.occurredAt)fail('The original actual start time changed.');
|
|
if(row.terminal_event_id)fail('This raid already has a terminal outcome.');
|
|
await tx.query("UPDATE jarvis_imperial_raid_orders SET state='started',started_at=?,updated_at=? WHERE id=?",[input.occurredAt,clock(),row.id]);
|
|
await tx.query("UPDATE jarvis_imperial_raid_jobs SET state='queued' WHERE order_id=? AND kind='war' AND state='waiting_start'",[row.id]);
|
|
}else if(row.state==='accepted')await tx.query("UPDATE jarvis_imperial_raid_orders SET state='warning',updated_at=? WHERE id=?",[clock(),row.id]);
|
|
return saveEvent(tx,input,raidEventAcknowledgement(row.id,input.eventId,input.phase));
|
|
}
|
|
async function outcome(tx,input){
|
|
const row=await requirePaid(tx,input),prior=await eventReplay(tx,input);if(prior)return prior;
|
|
if(row.terminal_event_id)fail('The original terminal outcome is already recorded.');
|
|
const p=parse(row.accepted_json),started=row.started_at===null?null:Number(row.started_at),neutral=['interrupted','spawn_failed','cancelled'].includes(input.outcome);
|
|
if(input.occurredAt<p.acceptedAt||input.occurredAt>clock()+30000||started===null&&(input.startedAt!==0||input.activeMillis!==0)||started!==null&&(input.startedAt!==started||input.occurredAt<started||input.activeMillis>input.occurredAt-started+1000))fail('The original actual raid interval is required.');
|
|
if(!neutral&&started===null)fail('A real party start must be acknowledged before a combat outcome.');
|
|
if(input.outcome==='survived'&&input.activeMillis!==P.durationMs)fail('The commander must survive fifteen actual active minutes.');
|
|
if(input.outcome==='spawn_failed'&&started!==null)fail('An already started raid must use interruption, not spawn failure.');
|
|
const state=neutral?'neutral':input.outcome==='survived'?'completed':'failed';
|
|
await tx.query('UPDATE jarvis_imperial_raid_orders SET state=?,terminal_event_id=?,outcome_json=?,updated_at=? WHERE id=?',[state,input.eventId,JSON.stringify(input),clock(),row.id]);
|
|
await tx.query('UPDATE jarvis_imperial_raid_clans SET active_order_id=NULL WHERE clan_id=? AND active_order_id=?',[p.targetClanId,row.id]);
|
|
if(neutral){
|
|
if(!row.war_campaign_id){
|
|
await tx.query("UPDATE jarvis_imperial_raid_jobs SET state='cancelled' WHERE order_id=? AND kind='war' AND state IN ('waiting_start','queued','processing')",[row.id]);
|
|
await queue(tx,row,'refund',{orderId:row.id,eventId:input.eventId,outcome:input.outcome});
|
|
}
|
|
}
|
|
else await queue(tx,row,'quest',{orderId:row.id,eventId:input.eventId,actorId:row.actor_id,outcome:input.outcome,xp:state==='completed'?1000:100});
|
|
return saveEvent(tx,input,{...raidEventAcknowledgement(row.id,input.eventId,state),...(neutral?(row.war_campaign_id?{refundState:'not_due',refundReason:'war_started'}:{refundState:'queued'}):{})});
|
|
}
|
|
return Object.freeze({
|
|
async execute(value){
|
|
const input=validateImperialRaidInput(value);
|
|
if(input.action==='context'){
|
|
const actor=await resolveActor(db,input.uuid);if(!actor?.id)fail('Link an active personal Minecraft account first.',403);
|
|
const q=await quote(db,input),c=q.context;
|
|
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 locked(async tx=>{
|
|
if(input.action==='prepare')return prepare(tx,input);
|
|
if(input.action==='accept')return accept(tx,input);
|
|
if(input.action==='ack')return acknowledge(tx,input);
|
|
if(input.action==='outcome')return outcome(tx,input);
|
|
const {actor,row:old,hash}=await bind(tx,input),row=old?await expire(tx,old):null;
|
|
if(paid(row))return accepted(row);
|
|
if(input.action==='cancel_prepared'){
|
|
if(!row)return finalUnpaid(await insert(tx,input,actor,hash,'cancelled'));
|
|
if(row.state==='prepared')await tx.query("UPDATE jarvis_imperial_raid_orders SET state='cancelled',updated_at=? WHERE id=?",[clock(),row.id]);
|
|
return finalUnpaid({...row,state:row.state==='prepared'?'cancelled':row.state});
|
|
}
|
|
if(!row)return {ok:true,schema:1,orderId:input.requestId,requestId:input.requestId,inputHash:hash,state:'unknown',definitive:false};
|
|
return row.state==='prepared'?{ok:true,schema:1,state:'prepared',order:parse(row.prepared_json)}:finalUnpaid(row);
|
|
});
|
|
}
|
|
});
|
|
}
|

Staff