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,season_id VARCHAR(8) 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)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 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); 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.query('SELECT * FROM jarvis_imperial_raid_clans WHERE clan_id=?'+(create?' FOR UPDATE':''),[id]))[0]||{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)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.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.occurredAtclock()+30000)fail('Raid acknowledgement time is invalid.'); if(input.phase==='started'){ if(input.occurredAtclock()+30000||started===null&&(input.startedAt!==0||input.activeMillis!==0)||started!==null&&(input.startedAt!==started||input.occurredAtinput.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'){ return pollOrders(db,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); }); } }); }