forked from unimatrix/web
Start eligible quest-chain successors after committed claims
This commit is contained in:
parent
b406b337db
commit
ca5acc79b2
2 changed files with 106 additions and 9 deletions
|
|
@ -62,7 +62,7 @@ export function createGameQuestsAPI(db,settings,{personal=null,pol=null,starter=
|
|||
if(questChannel(quest.executionRequirements)==='website')return json({message:'Complete this website quest in your online mission journal.'},409);
|
||||
const result=input.action==='start'?await runtime.quests.start(actor,{definitionId:quest.id}):await runtime.quests.claim(actor,{definitionId:quest.id,revision:input.revision,requestId:input.requestId});
|
||||
if(input.action==='claim')await runtime.quests.processCompletions?.({accountId:actor.id});
|
||||
return json({ok:true,keyId:result.keyId||result.id,replayed:!!result.replayed,created:!!result.created});
|
||||
return json({ok:true,keyId:result.keyId||result.id,replayed:!!result.replayed,created:!!result.created,...(result.autoNext?{autoNext:result.autoNext,nextQuestId:result.autoNext.nextQuestId}:{})});
|
||||
}catch(error){const safe=/^(Quest |Repeatable quest cooldown|Current player identity|Current POL season|Current Personal season|Verified|A matching)/.test(error.message||'');return json({message:safe?error.message:'The quest action was not confirmed. Refresh the journal before retrying.'},409);}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,34 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au
|
|||
const types=new Map(definitions.map(d=>[d.id,d])),metrics=new Set(definitions.map(d=>d.metric));
|
||||
if(types.size!==definitions.length)throw TypeError('Duplicate quest definitions');
|
||||
const definition=id=>{const d=types.get(id);if(!d)throw Error('Unknown quest definition');return d;};
|
||||
const successors=d=>definitions.filter(next=>next.season===d.season&&next.branch===d.branch&&((next.requires||[]).includes(d.id)||(next.requiresAny||[]).includes(d.id)));
|
||||
const nextPurpose=id=>'quest-next:'+digest([id]).slice(0,21);
|
||||
// This runs after reward commit: issuing another key must never nest a key transaction.
|
||||
async function processNextQuests({accountId=null,parentId=null,actor=null}={}){
|
||||
if(accountId!==null&&!uuid(accountId))throw TypeError('Invalid completion account');
|
||||
const args=[],where=["state='queued'",parentId?'purpose=?':"purpose LIKE 'quest-next:%'"];
|
||||
if(parentId)args.push(nextPurpose(parentId));if(accountId){where.push('account_id=?');args.push(accountId);}
|
||||
const jobs=await db.query('SELECT * FROM jarvis_progression_outbox WHERE '+where.join(' AND ')+' ORDER BY created_at,id LIMIT 20',args);
|
||||
const result={started:0,failed:0,pending:false,nextQuestId:null,choices:[]};
|
||||
for(const job of jobs)try{
|
||||
const current=actor?.id===job.account_id?actor:await resolvePlayer(job.account_id);if(!current)throw Error('Player unavailable');
|
||||
const parent=definition(JSON.parse(job.payload_json).definitionId),view=await service.list(current);
|
||||
if(parent.season!==job.season_id||view.season?.id!==job.season_id){await db.query("UPDATE jarvis_progression_outbox SET state='completed' WHERE id=? AND state='queued'",[job.id]);continue;}
|
||||
const done=new Set(view.quests.filter(q=>q.state==='claimed').map(q=>q.id));if(!done.has(parent.id))throw Error('Quest predecessor is not claimed');
|
||||
const children=successors(parent).filter(d=>!done.has(d.id)),existing=children.map(d=>view.quests.find(q=>q.id===d.id)).filter(q=>q?.keyId);
|
||||
let finish=false;
|
||||
if(existing.length){result.nextQuestId=existing.length===1?existing[0].id:null;result.choices=existing.length>1?existing.map(q=>q.id):[];finish=true;}
|
||||
else{
|
||||
const eligible=children.filter(d=>questPrerequisites(d,done)&&view.quests.find(q=>q.id===d.id)?.canStart);
|
||||
if(eligible.length===1){const next=eligible[0],key=await service.start(current,{definitionId:next.id});result.started+=key.created?1:0;result.nextQuestId=next.id;finish=true;}
|
||||
else if(eligible.length>1){result.choices=eligible.map(d=>d.id);finish=true;}
|
||||
else if(!children.length)finish=true;
|
||||
else result.pending=true;
|
||||
}
|
||||
if(finish)await db.query("UPDATE jarvis_progression_outbox SET state='completed' WHERE id=? AND state='queued'",[job.id]);
|
||||
}catch{result.failed++;result.pending=true;}
|
||||
return result;
|
||||
}
|
||||
async function player(actor,store=db){if(!uuid(actor?.id)||!await authorizePlayer(actor,store))throw Error('Current player identity required');}
|
||||
async function claimed(store,id,season){return new Set((await store.query('SELECT s.definition_id FROM jarvis_quest_states s JOIN jarvis_quest_claims c ON c.key_id=s.key_id WHERE s.account_id=? AND s.season_id=? AND s.definition_id IN ('+placeholders+')',[id,season,...ids])).map(r=>r.definition_id));}
|
||||
async function questCooldown(store,accountId,d){
|
||||
|
|
@ -87,9 +115,9 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au
|
|||
async claim(actor,{definitionId,requestId,revision}){
|
||||
if(!uuid(requestId)||!Number.isSafeInteger(revision)||revision<1)throw TypeError('Review the current quest reward');
|
||||
await player(actor);const d=definition(definitionId),grant=await service.start(actor,{definitionId}),prior=await read(db,'SELECT request_id,account_id FROM jarvis_quest_claims WHERE key_id=?',[grant.id]);
|
||||
if(prior){if(prior.account_id!==actor.id)throw Error('Quest claim unavailable');return {keyId:grant.id,replayed:true};}
|
||||
if(prior){if(prior.account_id!==actor.id)throw Error('Quest claim unavailable');let autoNext;try{autoNext=await processNextQuests({accountId:actor.id,parentId:d.id,actor});}catch{autoNext={started:0,failed:1,pending:true,nextQuestId:null,choices:[]};}return {keyId:grant.id,replayed:true,autoNext,nextQuestId:autoNext.nextQuestId};}
|
||||
const key=(await keys.list(actor.id)).find(k=>k.id===grant.id);if(!key?.code)throw Error('Quest instrument is unavailable');
|
||||
return keys.consume({accountId:actor.id,keyType:'quest',code:key.code,targetId:actor.id,requestId,apply:async(tx,{keyId,scopeId})=>{
|
||||
const result=await keys.consume({accountId:actor.id,keyType:'quest',code:key.code,targetId:actor.id,requestId,apply:async(tx,{keyId,scopeId})=>{
|
||||
await player(actor,tx);const state=await lockXPAccount(tx,actor.id,clock()),season=await readActiveXPSeason(tx,clock(),d.season),e=await eligibility(tx,actor.id,d,season,state);
|
||||
if(!await authorizeClaim(actor,d,tx,{eligibility:e,season,state})||scopeId!==d.season+':'+d.id||!e.ready)throw Error('Quest objective is not complete');
|
||||
if(!(await questCooldown(tx,actor.id,d)).available)throw Error('Repeatable quest cooldown is active');
|
||||
|
|
@ -101,7 +129,10 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au
|
|||
await saveXPAccount(tx,actor.id,creditXP(state,xp,{capXP:cap(season)}),season,keyId,'quest-claimed',{definitionId:d.id,xp,reason:e.reason,...(award.basis?{awardBasis:award.basis}:{})},clock());
|
||||
await tx.query("UPDATE jarvis_quest_states SET state='claimed',completed_at=COALESCE(completed_at,?) WHERE key_id=?",[clock(),keyId]);
|
||||
if(Object.keys(reward).length)await tx.query("INSERT INTO jarvis_quest_reward_jobs(key_id,account_id,season_id,payload_json,state,created_at) VALUES(?,?,?,?,'queued',?)",[keyId,actor.id,season.season_id,JSON.stringify(reward),clock()]);
|
||||
if(successors(d).length)await tx.query("INSERT INTO jarvis_progression_outbox(id,account_id,season_id,purpose,payload_json,state,created_at) VALUES(?,?,?,?,?,'queued',?) ON DUPLICATE KEY UPDATE purpose=VALUES(purpose)",[deterministicId('quest-next:'+actor.id+':'+d.season+':'+d.id),actor.id,d.season,nextPurpose(d.id),JSON.stringify({definitionId:d.id}),clock()]);
|
||||
}});
|
||||
let autoNext;try{autoNext=await processNextQuests({accountId:actor.id,parentId:d.id,actor});}catch{autoNext={started:0,failed:1,pending:true,nextQuestId:null,choices:[]};}
|
||||
return {...result,autoNext,nextQuestId:autoNext.nextQuestId};
|
||||
},
|
||||
async completeMandatory(actor){
|
||||
await player(actor);const view=await service.list(actor);if(view.state!=='active')throw Error('No active quest season');
|
||||
|
|
@ -124,6 +155,7 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au
|
|||
if(accountId!==null&&!uuid(accountId))throw TypeError('Invalid completion account');
|
||||
const jobs=await db.query("SELECT * FROM jarvis_progression_outbox WHERE purpose='mandatory-completion' AND state='queued'"+(accountId?' AND account_id=?':'')+' ORDER BY created_at,id LIMIT 20',accountId?[accountId]:[]);let completed=0,failed=0;
|
||||
for(const job of jobs)try{const actor=await resolvePlayer(job.account_id);if(!actor)throw Error('Player unavailable');const view=await service.list(actor);if(view.season?.id!==job.season_id)throw Error('Season is no longer active');await service.completeMandatory(actor);await db.query("UPDATE jarvis_progression_outbox SET state='completed' WHERE id=? AND state='queued'",[job.id]);completed++;}catch{failed++;}
|
||||
const next=await processNextQuests({accountId});failed+=next.failed;
|
||||
return {completed,failed};
|
||||
}
|
||||
};
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff