diff --git a/client/control.html b/client/control.html index 05f20ee..625fd9f 100644 --- a/client/control.html +++ b/client/control.html @@ -12,7 +12,7 @@

-

New world

+

New world

CHARACTER RECORD

diff --git a/client/src/content-editor.ts b/client/src/content-editor.ts index b230c31..643e4ae 100644 --- a/client/src/content-editor.ts +++ b/client/src/content-editor.ts @@ -201,7 +201,7 @@ function combatForm(kind:string){ const fields=form('Create mob','create-mob',()=>({mob:{...values.read(),model:model.value,behavior:behavior.value,attackId:attack.value,lootId:loot.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}})); fields.append(values.node,field('Model preset',model),field('Behavior',behavior),field('Attack profile',attack),field('Loot table',loot),...inputs.map(v=>field(v.label,v.input)),node('p','Health/power = base × level × (1 + world age in days × scaling). Defence is flat. Aggressive creatures pursue within the leash; guards defend their detection radius; passive creatures retaliate only when attacked. Models remain placeholders until milestone 4.5.','muted')); }else if(kind==='loot'){ - const items=[...catalog.items,...(catalog.gathering?.consumables??[]),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...['wood','ore','herb','bandage','axe','flint_and_steel','fishing_pole'].map(id=>({id,name:statLabel(id)}))]; + const items=[...catalog.items,...(catalog.gathering?.consumables??[]),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...['wood','ore','herb','bandage','escape_stone','axe','flint_and_steel','fishing_pole'].map(id=>({id,name:statLabel(id)}))]; const entries=repeat('Loot entries','Add loot entry',()=>{const group=node('div','','catalog-fields'),item=contentChoice(items),amount=number(1,1,100,'1'),chance=number(100,0,100),pool=text('',40),weight=number(1,1,10000,'1');pool.required=false;group.append(field('Item',item),field('Quantity',amount),field('Drop chance (%)',chance),field('Weighted group (blank = independent)',pool),field('Group weight',weight));return{node:group,read:()=>({item:item.value,amount:Number(amount.value),chance:Number(chance.value),group:pool.value.trim(),weight:Number(weight.value)})}},[],32); const fields=form('Create loot table','create-loot',()=>({loot:{...values.read(),entries:entries.read()}}));fields.append(values.node,entries.node,node('p','Blank groups roll independently; 100% is guaranteed. Each named group selects one entry by weight, then rolls that entry’s chance. Finisher luck affects non-guaranteed chances. New mobs leave a lootable corpse; the corpse is shared and may be looted by nearby players.','muted')); }else{ diff --git a/client/src/control.ts b/client/src/control.ts index bc2621c..188c00d 100644 --- a/client/src/control.ts +++ b/client/src/control.ts @@ -25,7 +25,7 @@ function openCommand(op: string, worldId = '', target = '', value = '') { const create = op === 'create-world', rename = op === 'rename'; $('command-title').textContent = labels[op]; $('command-context').textContent = create ? 'Deployment: GitOps / ArgoCD' : `${worldId}${target ? ` / ${target}` : ''}`; - $('world-input-label').hidden = !create; + $('world-input-label').hidden = !create; $('world-kind-label').hidden=!create; $('world-input').required = create; $('value-input-label').hidden = !create && !rename; $('value-caption').textContent = create ? 'Seed' : 'Character name'; @@ -133,7 +133,7 @@ for (const id of ['close-command','cancel-command']) $(id).onclick = () => comma $('close-character').onclick = () => characterMenu.close(); $('command-form').onsubmit = async event => { event.preventDefault(); const submit = $('submit-command'); submit.disabled = true; - const body = { ...draft, worldId: draft.op === 'create-world' ? $('world-input').value : draft.worldId, value: ['rename','create-world'].includes(draft.op) ? $('value-input').value : '', reason: $('reason-input').value, confirm: $('confirm-input').value }; + const body = { ...draft, op:draft.op==='create-world'&&$('world-kind').value==='hub'?'create-hub':draft.op, worldId: draft.op === 'create-world' ? $('world-input').value : draft.worldId, value: ['rename','create-world'].includes(draft.op) ? $('value-input').value : '', reason: $('reason-input').value, confirm: $('confirm-input').value }; try { await api('/api/control/commands', body); $('command-dialog').close(); notify('Action queued. Execution status is recorded in the audit log.'); await refresh(); } catch (e) { $('command-error').textContent = (e as Error).message; } finally { submit.disabled = false; } diff --git a/client/src/generated.ts b/client/src/generated.ts index 42e5e88..4df34d9 100644 --- a/client/src/generated.ts +++ b/client/src/generated.ts @@ -547,6 +547,7 @@ export interface WorldInfo { capacity: number; collapseInSeconds: number; id: string; + kind?: string; online: number; phase: string; radius: number; diff --git a/client/src/main.ts b/client/src/main.ts index 77089d2..b8ac077 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -1,4 +1,5 @@ import './style.css'; +import { showTravel } from './travel'; import { createIcons, Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } from 'lucide'; import { WorldView } from './world-view'; import type { Character, Chunk, Entity, Intent, Snapshot } from './generated'; @@ -8,7 +9,7 @@ import { InputActions, isEditing, type InputAction } from './input-actions'; import { hasOpenMenu, registerMenu } from './menu-focus'; type Recipe = { Inputs: Record; Outputs: Record }; -type Config = { worldId: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record; playerSpeed: number; gatherRange: number; attackRange: number }; +type Config = { worldId: string; kind: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record; playerSpeed: number; gatherRange: number; attackRange: number }; const $ = (id: string) => document.getElementById(id) as T; const visible = (id: string, show: boolean) => { $(id).hidden = !show; }; const pretty = (s: string) => s.replaceAll('_', ' ').replace(/^./, c => c.toUpperCase()); @@ -60,7 +61,7 @@ async function api(path: string, body?: unknown): Promise { } function notice(message: string) { $('notice').textContent = message; visible('notice', true); clearTimeout(noticeTimer); noticeTimer = setTimeout(() => visible('notice', false), 3500); } function send(op: string, target = '', x = 0, z = 0, slot = '') { - if (ws?.readyState !== WebSocket.OPEN || !snapshot || snapshot.self.entity.state !== 'alive') return; + if (ws?.readyState !== WebSocket.OPEN || !snapshot || !['alive','eligible'].includes(snapshot.self.entity.state)) return; const intent: Intent = { op, target, x, z, slot, seq: ++sequence }; ws.send(JSON.stringify(intent)); } @@ -104,7 +105,6 @@ function connect() { $('connection-status').textContent = 'Connected'; $('connection-dot').parentElement!.classList.remove('offline'); const state = value.self.entity.state; if (state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. Their belongings remain in this world.', false); - else if (state === 'eligible') showEnding('A passage forward.', 'The Harbinger has fallen. Your character and belongings can continue to a new world.', true); else if (value.self.remainingSeconds <= 0) showEnding('Rest until tomorrow.', 'Your daily play time is complete. Your keystone will return you to your previous location after 00:00 UTC.', false); }; ws.onclose = async () => { @@ -159,7 +159,7 @@ function minimap(s: Snapshot) { } function updateHUD(s: Snapshot) { const c = s.self, w = s.world; - visible('game-controls', true); visible('movement', c.entity.state === 'alive' && $('inventory').hidden && $('settings').hidden); + visible('game-controls', true); visible('movement', ['alive','eligible'].includes(c.entity.state) && $('inventory').hidden && $('settings').hidden); $('character-name').textContent = c.entity.name; $('character-level').textContent = `Level ${c.level || 1}`; $('character-experience').textContent = experienceText(c); @@ -179,10 +179,15 @@ function updateHUD(s: Snapshot) { $('season-clock').textContent = time(w.phase === 'gathering' ? w.bossInSeconds : w.collapseInSeconds); $('season-detail').textContent = w.phase === 'gathering' ? 'Until the Harbinger' : `${Math.round(w.safeRadius)}m of world remaining`; $('season-progress').style.width = `${w.safeRadius / w.radius * 100}%`; - visible('boss-bar', w.phase === 'cataclysm'); $('boss-health').style.width = `${w.bossHp / w.bossMaxHp * 100}%`; $('boss-count').textContent = `${Math.ceil(w.bossHp)} / ${Math.ceil(w.bossMaxHp)}`; + visible('boss-bar', w.phase === 'cataclysm' || w.phase === 'won'); $('boss-health').style.width = `${w.bossHp / w.bossMaxHp * 100}%`; $('boss-count').textContent = w.phase==='won'?'Portal at 0, 0':`${Math.ceil(w.bossHp)} / ${Math.ceil(w.bossMaxHp)}`; $('coordinates').textContent = `${Math.round(c.entity.position.x)}, ${Math.round(c.entity.position.z)}`; $('chunk-count').textContent = `${view.chunks.size} chunks`; if (!$('inventory').hidden) inventory(c); + if(w.kind==='hub'){ $('phase-label').textContent='THE HUB';$('season-clock').textContent='Permanent haven';$('season-detail').textContent='Crafting allowed · No experience gained'; } + if(w.phase==='won'){ $('season-clock').textContent='Portal open';$('season-detail').textContent='Find the victory portal at 0, 0'; } + visible('target-boss',w.kind!=='hub');$('target-boss').textContent=w.phase==='won'?'Find victory portal':'Target Harbinger';$('target-boss').setAttribute('aria-label',w.phase==='won'?'Find victory portal':'Target Harbinger'); + visible('dev-boss',config.development&&w.kind!=='hub'); + $('attack').disabled=w.kind==='hub'||w.phase==='won';$('gather').disabled=w.kind==='hub'||w.phase==='won'; selection(view.selected); minimap(s); if (s.message && s.message !== lastNotice) { notice(s.message); lastNotice = s.message; } } @@ -252,6 +257,8 @@ async function boot() { }, 50); const [loadedConfig, chunks] = await Promise.all([api('/api/config'), api('/api/preview'), view.load()]); config = loadedConfig; + const travelButton=document.createElement('button');travelButton.id='travel';travelButton.textContent='Travel';travelButton.title='World travel';$('inventory-toggle').before(travelButton); + travelButton.onclick=()=>{if(!snapshot)return;input.clear();walkTo=undefined;pendingAction=undefined;send('move');void showTravel({worldId:config.worldId,route:config.kind==='hub'?'hub':snapshot.world.phase==='won'?'portal':'escape',beforeTravel:()=>{requestedClose=true;},afterTravel:departed=>{requestedClose=departed;}});}; $('zoom').value = String(view.distance); view.addChunks(chunks); view.updateEntities(chunks.flatMap(c => c.resources)); $('connection-status').textContent = 'World online'; @@ -262,19 +269,13 @@ async function boot() { else if (me?.character) { $('arrival').close(); if (me.character.entity.state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. A fresh world is a new beginning.', false); - else if (me.character.entity.state === 'eligible') showEnding('A passage forward.', 'Your survivor passage is saved.', true); else connect(); } else { if (me?.active) { visible('join-form', false); - const link = document.createElement('a'); link.href = `/game?world=${encodeURIComponent(me.active.worldId)}`; link.className = 'command'; link.textContent = `Continue ${me.active.name} in ${me.active.worldId}`; $('passages').append(link); - } - const passages = await api<{ characterId: string; sourceWorld: string; name: string }[]>('/api/passages').catch(() => []); - for (const passage of passages.filter(p => p.sourceWorld !== config.worldId)) { - const button = document.createElement('button'); button.textContent = `Continue as ${passage.name}`; - button.onclick = async () => { try { await api('/api/join', { name: '', passage: passage.characterId }); $('arrival').close(); connect(); } catch (e) { $('arrival-error').textContent = String((e as Error).message); } }; - $('passages').append(button); + const link = document.createElement('a'); link.href = me.active.state==='transit'?'/':`/game?world=${encodeURIComponent(me.active.worldId)}`; link.className = 'command'; link.textContent = me.active.state==='transit'?'Resume travel from your account':`Continue ${me.active.name} in ${me.active.worldId}`; $('passages').append(link); } + if(config.kind==='hub'){visible('join-form',false);$('arrival-error').textContent='Enter a hub through travel from your current character. Open your account to continue.';} } $('join-form').onsubmit = async event => { event.preventDefault(); const button = $('join'); button.disabled = true; @@ -292,7 +293,7 @@ async function boot() { document.querySelectorAll(`[data-close="${id}"]`).forEach(button=>button.onclick=()=>menu.close()); } $('jump').onclick = () => input.trigger('jump'); $('attack').onclick = () => input.trigger('attack'); $('gather').onclick = () => input.trigger('gather'); $('heal').onclick = () => input.trigger('heal'); $('keystone').onclick = () => input.trigger('return'); - $('target-boss').onclick = () => { selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); }; + $('target-boss').onclick = () => { if(snapshot?.world.phase==='won'){walkTo={x:0,z:0};pendingAction=undefined;return;} selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); }; $('dev-boss').onclick = () => void api('/api/dev/boss', {}).catch(e => notice(e.message)); $('reconnect').onclick = () => location.reload(); $('new-character').onclick = () => { requestedClose = true; ws?.close(); location.reload(); }; @@ -310,7 +311,7 @@ async function boot() { view.canvas.addEventListener('pointerdown', event => { if (!snapshot || hasOpenMenu() || $('arrival').open || $('ending').open || event.button !== 0) return; const hit = view.pick(event.clientX, event.clientY); - if (hit.entity) { selection(hit.entity); action(['boss', 'sentinel','mob','player'].includes(hit.entity.kind) ? 'attack' : 'gather'); } + if (hit.entity) { if(hit.entity.kind==='portal'){$('travel').click();return;} selection(hit.entity); action(['boss', 'sentinel','mob','player'].includes(hit.entity.kind) ? 'attack' : 'gather'); } else if (hit.point) { selection(); walkTo = hit.point; pendingAction = undefined; } }); Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; }, get walkTo() { return walkTo; }, get pendingAction() { return pendingAction; }, get keys() { return input.keys; } }, configurable: true }); diff --git a/client/src/player-content.ts b/client/src/player-content.ts index cbbf6be..441e01e 100644 --- a/client/src/player-content.ts +++ b/client/src/player-content.ts @@ -21,7 +21,7 @@ export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:() for(const i of catalog.items)choice.append(new Option(`${i.name} (${i.id})`,i.id)); for(const r of catalog.gathering?.resources??[])if(r.output==='self')choice.append(new Option(r.name,r.id)); for(const i of catalog.gathering?.consumables??[])choice.append(new Option(i.name,i.id)); - for(const id of ['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage'])choice.append(new Option(statLabel(id),id)); + for(const id of ['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'])choice.append(new Option(statLabel(id),id)); notice.textContent='Items go into the bag. Equipment requirements still apply when equipping.';break; case 'remove-item': for(const i of v.items??[]){const slot=Object.entries(v.equipment??{}).find(([,id])=>id===i.id)?.[0];choice.append(new Option(`${i.name}${slot?` [${statLabel(slot)}]`:''} · ${i.id}`,i.id));} diff --git a/client/src/portal-shared.ts b/client/src/portal-shared.ts index 540717e..2859dc6 100644 --- a/client/src/portal-shared.ts +++ b/client/src/portal-shared.ts @@ -3,7 +3,7 @@ import type { Character } from './generated'; import './theme'; export type RecordCharacter = { id: string; account: string; worldId: string; name: string; state: string; character: { view: Character; bornAt: string; diedAt?: string; deathReason?: string; dailySeconds: number } }; -export type World = { id: string; phase: string; living: number; dead: number; capacity: number; createdAt: string; bossAt: string; closed: boolean; available: boolean; revision: number; catalogVersion: number }; +export type World = { id: string; kind: string; phase: string; living: number; dead: number; capacity: number; createdAt: string; bossAt: string; closed: boolean; available: boolean; revision: number; catalogVersion: number }; export type Command = { id: string; worldId: string; actor: string; op: string; target: string; value: string; reason: string; status: string; result: string; createdAt: number; completedAt: number }; export const $ = (id: string) => document.getElementById(id) as T; export const el = (tag: K, text = '', className = '') => { const node = document.createElement(tag); node.textContent = text; node.className = className; return node; }; diff --git a/client/src/site.ts b/client/src/site.ts index de705fc..b827a72 100644 --- a/client/src/site.ts +++ b/client/src/site.ts @@ -1,4 +1,5 @@ import './portal.css'; +import { showTravel } from './travel'; import { permanentTitles, progressionSummary } from './progression'; import { $, api, APIError, badge, cell, date, el, gameURL, icons, icon, table, type RecordCharacter, type World } from './portal-shared'; @@ -16,9 +17,10 @@ function renderWorlds(worlds: World[]) { const heading = el('div', '', 'world-name'); heading.append(el('h3', world.id), badge(!world.available ? 'offline' : world.phase)); const population = el('div', '', 'world-stat'); population.append(el('span', 'Living'), el('strong', `${world.living} / ${world.capacity}`)); const clock = el('div', '', 'world-stat'); clock.append(el('span', world.phase === 'gathering' ? 'Harbinger arrives' : 'Season'), el('strong', world.phase === 'gathering' ? date(world.bossAt) : world.phase === 'cataclysm' ? 'The world is collapsing' : 'Ended')); + if(world.kind==='hub'){clock.replaceChildren(el('span','Hub instance'),el('strong','Permanent haven · No XP'));} const active = account?.active; const resume = active?.worldId === world.id; - const transfer = active?.state === 'eligible' && active.worldId !== world.id && world.phase === 'gathering'; + const transfer = false; const open = world.available && (resume || (!world.closed && world.living < world.capacity && ['gathering', 'cataclysm'].includes(world.phase) && (!active || transfer))); const action = el('a', resume ? 'Continue' : transfer ? 'Use passage' : 'Enter world', `button ${open ? '' : 'disabled'}`); if (open) action.href = gameURL(world.id); else { action.setAttribute('aria-disabled', 'true'); action.title = active && !resume && !transfer ? `Living character in ${active.worldId}` : 'World unavailable for arrivals'; } @@ -33,8 +35,8 @@ function renderAccount() { if (!account) { history.append(el('p', 'Sign in to see your characters.', 'empty')); return; } if (account.active) { const r = account.active; const summary = el('div', '', 'active-life'); const title = el('div', '', 'active-life-summary'); - title.append(el('h3', r.name), el('p', `${r.worldId} / ${r.state === 'eligible' ? 'Passage earned' : `${Math.ceil(r.character.view.entity.hp)} health`}`, 'muted'), progressionSummary(r.character.view)); - const link = el('a', 'Continue journey', 'button'); link.href = gameURL(r.worldId); link.append(icon('arrow-right')); summary.append(title, link); + title.append(el('h3', r.name), el('p', `${r.state==='transit'?'Travel in progress':r.worldId} / ${r.state === 'eligible' ? 'Passage earned' : `${Math.ceil(r.character.view.entity.hp)} health`}`, 'muted'), progressionSummary(r.character.view)); + const link = el('a', r.state==='transit'?'Resume travel':'Continue journey', 'button'); link.href = r.state==='transit'?'#':gameURL(r.worldId);if(r.state==='transit')link.onclick=e=>{e.preventDefault();void showTravel();}; link.append(icon('arrow-right')); summary.append(title, link); const titles = el('section', '', 'active-titles'); titles.append(el('h3', 'Permanent titles'), permanentTitles(r.character.view.titles)); parent.append(summary, titles); } else parent.append(el('p', 'Your next life is waiting in an open world.', 'empty')); diff --git a/client/src/travel.css b/client/src/travel.css new file mode 100644 index 0000000..16f6987 --- /dev/null +++ b/client/src/travel.css @@ -0,0 +1,3 @@ +.travel-dialog{box-sizing:border-box;width:min(540px,calc(100vw - 28px));max-height:90dvh;overflow:auto;padding:26px;border:1px solid #6b8279;border-radius:16px;background:#192923;color:#e9eee6;box-shadow:0 18px 80px #0008;font:15px/1.5 system-ui,sans-serif;z-index:100} +.travel-dialog::backdrop{background:#08100bc2}.travel-dialog h2{margin:0 0 12px}.travel-dialog label{display:grid;gap:8px}.travel-dialog p{color:#c5d2c7}.travel-dialog select,.travel-dialog button{font:inherit;color:inherit;background:#2d4438;border:1px solid #65816f;border-radius:7px;padding:10px}.travel-dialog select{width:100%}.travel-dialog footer{display:flex;flex-wrap:wrap;gap:8px;margin-top:18px}.travel-dialog button{cursor:pointer}.travel-dialog button:disabled{opacity:.5;cursor:wait}.travel-dialog button:last-child{background:#44634a}.travel-dialog [role=status]{min-height:24px} +.travel-dialog footer a{align-self:center;color:#c5e8d0;padding:10px}.actions{flex-wrap:wrap;max-width:100%}.actions #travel{font-size:11px} diff --git a/client/src/travel.ts b/client/src/travel.ts new file mode 100644 index 0000000..a21f53c --- /dev/null +++ b/client/src/travel.ts @@ -0,0 +1,63 @@ +import { api, el, gameURL, type World } from './portal-shared'; +import { registerMenu } from './menu-focus'; +import './travel.css'; + +type Transfer = { id: string; source: string; sourceKind: string; destination: string; route: string; status: string; acceptedWorld: string }; +type Departure = { worldId: string; route: 'hub' | 'escape' | 'portal'; beforeTravel?: () => void; afterTravel?: (departed: boolean) => void }; +let open = false; +export async function showTravel(source?: Departure) { + if (open) return; open = true; + const dialog = el('dialog', '', 'travel-dialog'); + const heading = el('h2', 'Travel'), description = el('p'), status = el('p'); status.setAttribute('role', 'status'); + const label = el('label', 'Destination'), select = el('select'); label.append(select); + const close = el('button', 'Close'), refresh = el('button', 'Refresh destinations'), go = el('button', 'Travel'); + const account = el('a','Account'); account.href='/'; + const footer = el('footer'); footer.append(close, refresh, account, go); dialog.append(heading, description, label, status, footer); document.body.append(dialog); + let transfer: Transfer | null = null, busy = false, prepared = false; + const requestId = crypto.randomUUID(); + const menu = registerMenu(dialog, () => { dialog.close(); dialog.remove(); menu.dispose(); open = false; if (prepared && source) location.href = '/'; }); + close.onclick = menu.close; dialog.oncancel = event => { event.preventDefault(); menu.close(); }; + dialog.showModal(); menu.opened(); + async function load() { + go.disabled = true; + try { + const [pending, worlds] = await Promise.all([api('/api/travel'), api('/api/worlds')]); + transfer = pending ?? transfer; + if (!source && !transfer) { description.textContent='No journey is waiting to finish.'; status.textContent='Refresh your account to continue your character.'; return; } + const fromHub = transfer ? transfer.sourceKind === 'hub' : source?.route === 'hub'; + description.textContent = transfer ? 'Your character and belongings are saved in transit. Choose an available destination to finish your journey.' : source?.route === 'portal' ? 'Stand beside the victory portal to enter a hub. Your character, belongings and progression travel with you.' : fromHub ? 'Switch hub instances or enter a survival world. Once there, you need an escape stone or a Harbinger victory to return.' : 'Consumes one escape stone to reach a hub. Escaping does not count as surviving this world.'; + const previous = select.value || transfer?.destination; + select.replaceChildren(); + for (const w of worlds.filter(w => w.available && !w.closed && w.living < w.capacity && ['hub', 'gathering', 'cataclysm'].includes(w.phase) && (fromHub || w.kind === 'hub') && (transfer || w.id !== source?.worldId))) { + select.append(new Option(`${w.id} · ${w.kind === 'hub' ? 'Hub' : w.phase === 'cataclysm' ? 'Collapsing world' : 'Survival world'} · ${w.living}/${w.capacity}`, w.id)); + } + if ([...select.options].some(o => o.value === previous)) select.value = previous!; + go.textContent = transfer ? 'Finish travel' : source?.route === 'escape' ? 'Use escape stone & travel' : 'Travel'; + go.disabled = !select.options.length || (!source && !transfer); + status.textContent = select.options.length ? '' : 'No destination is available. Your saved character remains safe in transit if departure already completed.'; + } catch (e) { status.textContent = (e as Error).message; } + } + refresh.onclick = () => { if (!busy) void load(); }; + go.onclick = async () => { + if (busy) return; busy = true; go.disabled = refresh.disabled = close.disabled = true; select.disabled = true; + try { + source?.beforeTravel?.(); + if (!transfer) { + if (!source) throw new Error('No pending journey. Refresh your account.'); + transfer = await api(`/worlds/${source.worldId}/api/travel/prepare`, { requestId, destination: select.value, route: source.route }); + } + prepared = true; + if (transfer.status !== 'accepted') transfer = await api(`/worlds/${select.value}/api/travel/accept`, { transferId: transfer.id }); + location.href = gameURL(transfer.acceptedWorld); + } catch (e) { + // Recover either side of a lost HTTP response from durable server state. + const message = (e as Error).message; + try { + if (transfer) { const saved = await api(`/api/travel?id=${encodeURIComponent(transfer.id)}`); if (saved?.status === 'accepted') { location.href = gameURL(saved.acceptedWorld); return; } } + await load(); if (transfer) prepared = true; + } catch { /* Keep the current transfer ID available for retry. */ } + status.textContent = `${message} You can retry or return to your account to resume travel.`; + } finally { busy = false; source?.afterTravel?.(prepared); go.disabled = !select.options.length || (!source && !transfer); refresh.disabled = close.disabled = select.disabled = false; if(prepared && !dialog.isConnected) location.href='/'; } + }; + await load(); +} diff --git a/client/src/world-view.ts b/client/src/world-view.ts index 183de85..e60f51b 100644 --- a/client/src/world-view.ts +++ b/client/src/world-view.ts @@ -97,6 +97,8 @@ export class WorldView { this.scene.add(mesh); peers.parts.push(mesh); }); this.batches.set('player', peers); + const portalMesh = new T.InstancedMesh(new T.TorusGeometry(2,.22,8,40).translate(0,2.5,0),new T.MeshBasicMaterial({color:'#86ffe0'}),8); + portalMesh.count=0;portalMesh.userData.kind='portal';this.scene.add(portalMesh);this.batches.set('portal',{parts:[portalMesh],entities:[]}); const corpseMesh = new T.InstancedMesh(new T.BoxGeometry(1.1, 0.45, 2.1), new T.MeshStandardMaterial({ color: '#77766d' }), 2048); corpseMesh.count = 0; corpseMesh.userData.kind = 'corpse'; this.scene.add(corpseMesh); this.batches.set('corpse', { parts: [corpseMesh], entities: [] }); diff --git a/deploy/chart/templates/worlds.yaml b/deploy/chart/templates/worlds.yaml index 1b593ea..203cf4e 100644 --- a/deploy/chart/templates/worlds.yaml +++ b/deploy/chart/templates/worlds.yaml @@ -4,6 +4,7 @@ {{- range .Values.worlds -}} {{- if hasKey $ids .id -}}{{- fail "world IDs must be unique" -}}{{- end -}} {{- $_ := set $ids .id true -}} +{{- if not (has (default "survival" .kind) (list "survival" "hub")) -}}{{- fail "world kind must be survival or hub" -}}{{- end -}} {{- $host := default .host $root.Values.portal.host -}} {{- $directory = append $directory (dict "id" .id "url" (printf "https://%s/game?world=%s" $host .id)) -}} {{- end -}} @@ -60,6 +61,7 @@ spec: - { name: APP_ENV, value: production } - { name: LISTEN_ADDR, value: "0.0.0.0:8080" } - { name: WORLD_ID, value: {{ .id | quote }} } + - { name: WORLD_KIND, value: {{ default "survival" .kind | quote }} } - { name: WORLD_SEED, value: {{ .seed | quote }} } - { name: PUBLIC_URL, value: {{ printf "https://%s" $host | quote }} } - { name: WORLD_DIRECTORY, value: {{ $directory | toJson | quote }} } diff --git a/deploy/values-srs.yaml b/deploy/values-srs.yaml index 02b84f9..54da641 100644 --- a/deploy/values-srs.yaml +++ b/deploy/values-srs.yaml @@ -30,6 +30,14 @@ worlds: - id: world-001 seed: "734291" host: srs.aeternalisgames.com + - id: hub-001 + kind: hub + seed: "927410" + host: srs.aeternalisgames.com + - id: hub-002 + kind: hub + seed: "927411" + host: srs.aeternalisgames.com networkPolicy: enabled: true ingressNamespace: kube-system diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 894e314..2522b36 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -40,7 +40,10 @@ death and current-world boundaries describe the running implementation; see `planning/SYSTEMS-ROADMAP.md` for the future lifecycle rules and unresolved details. The milestone 1 [lifecycle and ownership contract](LIFECYCLE-OWNERSHIP.md) maps the current code to proposed states, transaction boundaries, and migration steps. -It is a specification for later milestones, not an applied schema change. +Its later lifecycle systems remain specifications. [Milestone 5](MILESTONE-5.md) +implements hub/survival kinds and durable travel escrow: source departure and +destination acceptance each commit under their own owner lease, with the account +reserved throughout transit. Hub crafting suppresses XP and retains daily usage. One Go process owns one world, with a serial simulation protected by one lock. Clients submit bounded intents. The server determines speed, terrain height, diff --git a/docs/LIFECYCLE-OWNERSHIP.md b/docs/LIFECYCLE-OWNERSHIP.md index c87cacd..1fc7fa2 100644 --- a/docs/LIFECYCLE-OWNERSHIP.md +++ b/docs/LIFECYCLE-OWNERSHIP.md @@ -6,6 +6,16 @@ protocol change is activated by this milestone. Confirmed product rules come fro Record names and transaction boundaries below are the proposed implementation contract. Open product decisions are explicitly listed at the end. +## Milestone 5 implementation status + +[Playable hub travel](MILESTONE-5.md) implements `survival`/`hub` kinds, character +transfers (`prepared -> accepted`), in-transit account reservations, hub switching, +escape stones and physical victory portals. Returning to a viable source hub is +an acceptance of the same transfer. Later resurrection, housing, cosmetics and +title-ledger migrations below remain planned. Current hub daily-time accounting +is unchanged; XP is suppressed. See the milestone document for the applied schema, +lock order, compatibility restrictions and manual checks. + ## Existing code and migration constraints | Existing boundary | Evidence | Required future change | diff --git a/docs/MILESTONE-5.md b/docs/MILESTONE-5.md new file mode 100644 index 0000000..2d04ae5 --- /dev/null +++ b/docs/MILESTONE-5.md @@ -0,0 +1,104 @@ +# Milestone 5: playable hub travel + +Implemented for manual testing. Milestone 4.5 presentation work remains pending; +the user explicitly requested proceeding with 5. Terrain depth/traversal remains +in [the environment backlog](../planning/ENVIRONMENT-BACKLOG.md). + +## Player behavior + +- **Travel** opens the destination menu. Hubs accept existing characters through + travel; new characters begin in survival worlds. +- A living, connected character can use **one escape stone** to leave a survival + world before victory. This first implementation activates instantly, requires + remaining daily time and an unsheltered character, and grants no survival credit. + The stone is spent once when departure succeeds, even if arrival needs retrying. +- Harbinger victory opens a visible portal at **0, 0**. Survivors remain able to + move/jump. Use **Find victory portal**, stand within gathering range, then click + the portal or open Travel. This route consumes no escape stone. +- From a hub, switch hub instances or enter a survival world. Survival admission + remains open during collapse until admissions close, capacity fills, or the + world is destroyed. Arrival checks these conditions again. +- If travel is interrupted, the account page offers **Resume travel**. The same + pending journey can choose another available destination; escape/victory must + finish in a hub. A journey from a hub may return to its viable source hub. +- No new allowance, character, inventory, equipment ID, title, or progression is + created by travel. Existing daily-time accounting continues in hubs. Time spent + in transit is offline time. Esc closes the focused travel menu. +- Hubs have no Harbinger, collapse, gathering nodes, mobs, combat, or XP awards. + Existing crafting consumes resources and creates items without crafting or + character XP. Discovery and the expanded professions arrive in milestone 6; + learned spells and weapon proficiency arrive in milestone 7 and must use the + same character ownership and XP-location rules. + +## Administration and deployment + +`WORLD_KIND=survival|hub` selects the instance kind; existing populated legacy +worlds default to survival. A saved typed instance cannot change kind. Only a +legacy untyped gathering instance with no characters, corpses, or end record may +initialize as a hub, supporting empty instance bootstrap during image promotion. +Never repurpose an existing played world as a hub. + +The deployment values add **hub-001** and **hub-002** for switching tests. Wait +for the new image to become ready before entering these instances. Control's +**New world** form includes an instance-type selector. Additional provisioning +requires the existing GitOps setup; its configured operator limit is unchanged. +Control refuses mob spawning, awakening the Harbinger, and ending a hub. + +Admins can grant **escape_stone** through player item controls, and select it in +loot tables. It is not automatically granted to new characters. Loot drop rates +remain authored content. The existing escape activation is provisional; channels, +charges, interrupt rules and presentation can be added later. + +## Persistence and compatibility + +`character_transfers` stores a server-generated journey ID, request nonce, +account/source/route, character payload and accepted destination. A unique pending +transfer and a registry reservation including `transit` prevent replacement or +two destinations owning the same life. + +Departure commits the item cost, source removal, registry reservation, and escrow +under the source lease/revision in one transaction. Arrival commits destination +snapshot, transfer consumption, and registry ownership under the destination +lease/revision in one transaction. Live worlds change only after commit. Lock +order is world, transfer, legacy passage, character registry. A failed validation +keeps the journey recoverable; an uncertain database result freezes its world +owner so stale state cannot keep serving gameplay. Retries return saved outcomes. + +Legacy passage records remain readable for migration/history, but `/api/join` +rejects the old direct passage shortcut. Legacy survivor characters can reconnect +to their winning world and use its portal. Claims are marked during travel to +prevent stale passage copies from reclaiming a character. The legacy title ledger +migration is still a separate pending decision; this milestone preserves titles. + +Do not roll back to writers that do not understand in-transit reservations while +travel records exist. Production still requires PostgreSQL/OIDC; development auth +remains loopback-only. Capacity claims have not changed. + +## Manual test handoff + +1. Grant a living player two escape stones. Note character/item IDs, inventory, + levels, stats, profession XP, titles and daily time. Travel to hub-001: exactly + one stone is spent; the same life and belongings arrive. +2. Reload during travel. Resume from the account page. Retry or choose another + hub if the selected one is unavailable/full; verify no duplication. +3. Switch hub-001 -> hub-002 -> hub-001. Check other connected players keep moving. + Close the Travel menu with Esc and check movement resumes. +4. Craft in the hub: resources decrease and output appears, while all XP stays + unchanged. Attack/gather and destructive hub admin commands must be rejected. +5. Enter a survival world. Verify return fails without a stone, including during + collapse. Test full/closed/destroyed destinations and late admission. +6. Defeat the Harbinger. Walk to the visible portal and travel with no stone cost. + Remote portal use must fail. Reconnect before using the portal and repeat. +7. Confirm dead, sheltered and daily-capped characters cannot initiate travel; + hub switching and world entry never refresh the daily budget. + +Automated coverage includes server lifecycle, authorization/origin checks, source +and destination fencing, concurrent acceptance, interrupted travel, source loss, +destination rejection, repeated hub journeys, progression/items, and hub rules. +The PostgreSQL version runs when `TEST_DATABASE_URL` is configured. Browser +automation expansion remains a later TODO; this milestone uses manual playtesting. + +Local validation passed: `npm run check`, `npm run build`, +`npm run test:contracts`, and `go test ./...` in `server`. PostgreSQL integration +was not run locally because `TEST_DATABASE_URL` was not configured. No Playwright +run was added to this milestone's local validation. diff --git a/planning/SYSTEMS-ROADMAP.md b/planning/SYSTEMS-ROADMAP.md index f183545..63772aa 100644 --- a/planning/SYSTEMS-ROADMAP.md +++ b/planning/SYSTEMS-ROADMAP.md @@ -549,7 +549,7 @@ milestones, not time estimates or new tested-capacity claims. | 3. Terrain, movement, gathering | Hills/valleys/forests, biomes, jumping, closer camera, resources, three gathering professions | Movement/terrain agreement, resource requirements/yields/respawn, profession XP | | 4. Combat and mobs | Melee/ranged combat, navigation across chunks, projectiles/AoE, mob/spawn/loot editors | Targeting, damage, chunk crossings, loot, basic Control spawning | | 4.5. Models and action presentation | Model rigs, equipment attachments, animations, sound hooks | Compatible rigs/slots, locomotion/attack/gather animation, action/outcome sounds | -| 5. Playable hub travel | Hub instances/switching, survival-world entry, escape items, Harbinger victory portal | Admission, escape restrictions, single character/item ownership, hub XP restrictions | +| 5. Playable hub travel | Hub instances/switching, survival-world entry, escape items, Harbinger victory portal | Implemented; [manual handoff](../docs/MILESTONE-5.md): admission, escape restrictions, single character/item ownership, hub XP restrictions | | 6. Crafting and item quality | Recipe discovery, nine professions, failure/refund curves, random stats, crafter provenance, hub crafting | Valid-recipe feedback, resource use, quality/provenance, discoveries without hub XP | | 7. Spells, abilities, resurrection | Spell books/ranks/unlocks, weapon proficiency, corpse revival, full bindings/controller targeting | Use-based progression, effects, resurrection constraints, input usability | | 8. Building and housing | Destructible world structures, house instances, keys, permissions, storage, timed deletion/recovery | Persistence, ownership, navigation changes, guest access, three-second deletion and recovery | diff --git a/schemas/protocol.json b/schemas/protocol.json index 56665a9..4ec412f 100644 --- a/schemas/protocol.json +++ b/schemas/protocol.json @@ -277,11 +277,19 @@ "WorldInfo": { "type": "object", "additionalProperties": false, "properties": { - "id": {"type": "string"}, "seed": {"type": "integer"}, "phase": {"type": "string"}, - "ageSeconds": {"type": "number"}, "bossInSeconds": {"type": "number"}, - "collapseInSeconds": {"type": "number"}, "safeRadius": {"type": "number"}, - "radius": {"type": "number"}, "online": {"type": "integer"}, "capacity": {"type": "integer"}, - "bossHp": {"type": "number"}, "bossMaxHp": {"type": "number"} + "id": {"type": "string"}, + "seed": {"type": "integer"}, + "phase": {"type": "string"}, + "ageSeconds": {"type": "number"}, + "bossInSeconds": {"type": "number"}, + "collapseInSeconds": {"type": "number"}, + "safeRadius": {"type": "number"}, + "radius": {"type": "number"}, + "online": {"type": "integer"}, + "capacity": {"type": "integer"}, + "bossHp": {"type": "number"}, + "bossMaxHp": {"type": "number"}, + "kind": {"type": "string"} }, "required": ["id", "seed", "phase", "ageSeconds", "bossInSeconds", "collapseInSeconds", "safeRadius", "radius", "online", "capacity", "bossHp", "bossMaxHp"] }, diff --git a/server/cmd/world/main.go b/server/cmd/world/main.go index 17a156e..9a3f821 100644 --- a/server/cmd/world/main.go +++ b/server/cmd/world/main.go @@ -96,7 +96,15 @@ func run() error { return err } defer db.Close() + kind := env("WORLD_KIND", "survival") + if kind != "survival" && kind != "hub" { + return errors.New("WORLD_KIND must be survival or hub") + } w := game.New(id, seed, time.Now().UTC(), b) + w.Kind = kind + if kind == "hub" { + w.Phase = "hub" + } lease, raw, err := db.Acquire(ctx, w) if err != nil { return fmt.Errorf("acquire world: %w", err) @@ -109,10 +117,8 @@ func run() error { _ = lease.Release(ctx) } }() - if err = json.Unmarshal(raw, w); err != nil { - return err - } - if err = w.Restore(time.Now().UTC()); err != nil { + w, err = restoreInstance(raw, kind, time.Now().UTC()) + if err != nil { return err } auth, err := transport.NewAuth(ctx, db, dev, base, os.Getenv("OIDC_ISSUER"), os.Getenv("OIDC_CLIENT_ID"), os.Getenv("OIDC_CLIENT_SECRET")) @@ -175,3 +181,22 @@ func main() { os.Exit(1) } } + +func restoreInstance(raw []byte, kind string, now time.Time) (*game.World, error) { + var w game.World + if err := json.Unmarshal(raw, &w); err != nil { + return nil, err + } + // An older image can initialize a new hub ID during image promotion. Only an + // untyped, unused legacy instance may adopt its configured hub kind. + if w.Kind == "" && kind == "hub" && w.Phase == "gathering" && w.EndedAt == nil && len(w.Characters) == 0 && len(w.Corpses) == 0 { + w.Kind = "hub" + } + if err := w.Restore(now); err != nil { + return nil, err + } + if w.Kind != kind { + return nil, errors.New("WORLD_KIND does not match saved world; use a new world ID") + } + return &w, nil +} diff --git a/server/cmd/world/main_test.go b/server/cmd/world/main_test.go new file mode 100644 index 0000000..85739ff --- /dev/null +++ b/server/cmd/world/main_test.go @@ -0,0 +1,44 @@ +package main + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + "encoding/json" + "testing" + "time" +) + +func TestInstanceKindRestore(t *testing.T) { + b, _ := content.Load() + now := time.Now() + w := game.New("legacy", 1, now, b) + w.Kind = "" + raw, _ := json.Marshal(w) + if restored, err := restoreInstance(raw, "survival", now); err != nil || restored.Kind != "survival" { + t.Fatal("legacy survival restore", err) + } + if restored, err := restoreInstance(raw, "hub", now); err != nil || restored.Kind != "hub" || restored.Phase != "hub" { + t.Fatal("empty hub bootstrap", err) + } + c, _ := w.Join("account", "Traveler") + raw, _ = json.Marshal(w) + if _, err := restoreInstance(raw, "hub", now); err == nil { + t.Fatal("converted a populated legacy survival world to hub") + } + c.View.Entity.State = "dead" + raw, _ = json.Marshal(w) + if _, err := restoreInstance(raw, "hub", now); err == nil { + t.Fatal("converted a world with character history") + } + w = game.New("typed", 2, now, b) + raw, _ = json.Marshal(w) + if _, err := restoreInstance(raw, "hub", now); err == nil { + t.Fatal("changed existing typed instance kind") + } + w.Kind = "hub" + w.Phase = "hub" + raw, _ = json.Marshal(w) + if _, err := restoreInstance(raw, "survival", now); err == nil { + t.Fatal("changed hub to survival") + } +} diff --git a/server/content/combat.go b/server/content/combat.go index 4d7ea0e..599d0ef 100644 --- a/server/content/combat.go +++ b/server/content/combat.go @@ -129,7 +129,7 @@ func (c Catalog) validateCombat() error { attacks[a.ID] = true } items := map[string]bool{} - for _, id := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"} { + for _, id := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage", "escape_stone"} { items[id] = true } for _, i := range c.Items { diff --git a/server/internal/game/admin_content.go b/server/internal/game/admin_content.go index 44cefab..f0eca62 100644 --- a/server/internal/game/admin_content.go +++ b/server/internal/game/admin_content.go @@ -42,7 +42,7 @@ func (w *World) AdminItems(c *Character, op, value string) error { } } } - for _, key := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"} { + for _, key := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage", "escape_stone"} { if key == id { known = true } diff --git a/server/internal/game/biomes.go b/server/internal/game/biomes.go index 7230fad..42612f2 100644 --- a/server/internal/game/biomes.go +++ b/server/internal/game/biomes.go @@ -13,6 +13,11 @@ import ( // Read-only arrival preview uses the world's generator and any explored layout. func (w *World) PreviewChunk(x, z int) p.Chunk { c := w.terrain.Chunk(x, z) + if w.IsHub() { + c.Resources = []p.Entity{} + c.Biome = "Survivor haven" + return c + } if layout, ok := w.ResourceLayouts[c.Key]; ok { c.Biome, c.Color, c.Resources = layout.Biome, layout.Color, layout.Resources } diff --git a/server/internal/game/combat.go b/server/internal/game/combat.go index 2e1ce42..5af7fe5 100644 --- a/server/internal/game/combat.go +++ b/server/internal/game/combat.go @@ -101,6 +101,9 @@ func (w *World) terrainHit(a, b p.Vec3) (p.Vec3, bool) { return b, false } func (w *World) attack(c *Character, target string) error { + if !w.AllowsXP() { + return errors.New("combat is unavailable here") + } a := w.playerAttack(c) if w.Age() < c.AttackReadyAt || w.Age()-c.LastAttack < a.Cooldown { return errors.New("attack cooldown") diff --git a/server/internal/game/gathering.go b/server/internal/game/gathering.go index 5adcfc9..07fa078 100644 --- a/server/internal/game/gathering.go +++ b/server/internal/game/gathering.go @@ -160,6 +160,9 @@ func (w *World) gatherRisk(c *Character, r content.ResourceDefinition) p.Gatheri return risk } func (w *World) gather(c *Character, target string) error { + if w.IsHub() { + return errors.New("gathering is unavailable in the hub") + } if until := w.Depleted[target]; until > w.Age() { return errors.New("resource depleted") } diff --git a/server/internal/game/mobs.go b/server/internal/game/mobs.go index 2695ef0..3436c00 100644 --- a/server/internal/game/mobs.go +++ b/server/internal/game/mobs.go @@ -59,6 +59,9 @@ func (w *World) newMob(id string, d content.MobDefinition, pos p.Vec3, respawn f return m } func (w *World) SpawnMobs(definition, value string) error { + if w.IsHub() { + return errors.New("combat is unavailable in the hub") + } if w.Phase == "won" || w.Phase == "lost" { return errors.New("world has ended") } diff --git a/server/internal/game/progression.go b/server/internal/game/progression.go index 582994c..05a84db 100644 --- a/server/internal/game/progression.go +++ b/server/internal/game/progression.go @@ -89,6 +89,9 @@ func (c *Character) nextLevelXP() int64 { } func (w *World) grantXP(c *Character, amount int64) { + if !w.AllowsXP() { + return + } if amount <= 0 || c.View.Entity.State != "alive" || c.View.Level >= c.Progression.MaxLevel { return } diff --git a/server/internal/game/travel.go b/server/internal/game/travel.go new file mode 100644 index 0000000..9827440 --- /dev/null +++ b/server/internal/game/travel.go @@ -0,0 +1,54 @@ +package game + +import ( + p "aeternalis/server/internal/protocol" + "errors" +) + +func (w *World) IsHub() bool { return w.Kind == "hub" } +func (w *World) AllowsXP() bool { + return w.Kind == "survival" && (w.Phase == "gathering" || w.Phase == "cataclysm") +} +func (w *World) PortalPosition() p.Vec3 { return w.terrain.Position(0, 0) } + +// Escape is an explicit one-item action. It grants no victory/survival credit. +func (w *World) Departure(c *Character, route string) error { + if c == nil || !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") { + return errors.New("character cannot travel") + } + if w.IsHub() { + if route != "hub" { + return errors.New("choose hub travel") + } + return nil + } + if w.Phase == "won" && c.View.Entity.State == "eligible" { + if route != "portal" || distance(c.View.Entity.Position, w.PortalPosition()) > w.Balance.GatherRange { + return errors.New("stand next to the victory portal") + } + return nil + } + if w.Phase != "gathering" && w.Phase != "cataclysm" { + return errors.New("world is no longer available") + } + if route != "escape" || c.View.Inventory["escape_stone"] < 1 { + return errors.New("an escape stone is required before victory") + } + return nil +} + +// Transfers arrive as the same life. Import retains progression, inventory and +// daily usage; its resets apply only to instance-local movement/cooldowns. +func (w *World) Arrive(c *Character) error { + if c.View.Entity.HP <= 0 || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") { + return errors.New("only living characters can arrive") + } + if old := w.Characters[c.View.Entity.ID]; old != nil { + if old.View.Entity.State != "eligible" || old.Online { + return errors.New("character already present") + } + delete(w.Characters, c.View.Entity.ID) // Historical legacy passage copy. + } + c.View.Entity.State = "eligible" + return w.Import(c) +} diff --git a/server/internal/game/travel_test.go b/server/internal/game/travel_test.go new file mode 100644 index 0000000..b792280 --- /dev/null +++ b/server/internal/game/travel_test.go @@ -0,0 +1,112 @@ +package game + +import ( + p "aeternalis/server/internal/protocol" + "encoding/json" + "testing" + "time" +) + +func TestHubRulesAndDailyLimit(t *testing.T) { + w, c := fixture(t) + w.Kind = "hub" + w.Phase = "hub" + if _, err := w.Join("new", "New"); err == nil { + t.Fatal("new life began in hub") + } + c.View.Inventory["herb"] = 4 + xp, craft := c.View.Experience, c.View.Skills["crafting"] + if err := w.craft(c, "bandage"); err != nil { + t.Fatal(err) + } + w.grantXP(c, 1000) + if c.View.Inventory["herb"] != 2 || c.View.Inventory["bandage"] < 1 || c.View.Experience != xp || c.View.Skills["crafting"] != craft { + t.Fatal("hub crafting must spend resources without granting XP") + } + if w.attack(c, "boss") == nil || w.gather(c, "tree") == nil || w.TriggerBoss() == nil || w.Control("end-world", "", "", "test") == nil || w.SpawnMobs("", "") == nil { + t.Fatal("hub allowed combat, gathering or destruction") + } + w.Advance(w.CreatedAt.Add(30*24*time.Hour), .05) + if w.Phase != "hub" || len(w.Mobs) != 0 { + t.Fatal("hub decayed or spawned mobs") + } + for _, chunk := range w.Snapshot(c.View.Entity.ID, nil).Chunks { + if len(chunk.Resources) != 0 { + t.Fatal("hub spawned gathering resources") + } + } + w.Balance.DailyPlaySeconds = 1 + w.Advance(w.now.Add(2*time.Second), 2) + if c.Online || c.View.RemainingSeconds != 0 { + t.Fatal("hub bypassed daily time cap") + } + if w.Departure(c, "hub") == nil { + t.Fatal("capped character traveled") + } +} + +func TestVictoryPortalAndTravelEligibility(t *testing.T) { + w, c := fixture(t) + if w.Departure(c, "escape") == nil { + t.Fatal("escaped without item") + } + c.View.Inventory["escape_stone"] = 1 + if e := w.Departure(c, "escape"); e != nil { + t.Fatal(e) + } + c.Online = false + if w.Departure(c, "escape") == nil { + t.Fatal("offline escape") + } + c.Online = true + c.Sheltered = true + if w.Departure(c, "escape") == nil { + t.Fatal("sheltered escape") + } + c.Sheltered = false + c.View.Entity.State = "dead" + if w.Departure(c, "escape") == nil { + t.Fatal("dead character escaped") + } + c.View.Entity.State = "alive" + w.Phase = "cataclysm" + w.damageBoss(c, w.BossHP) + c.View.Entity.Position = w.terrain.Position(100, 100) + if w.Departure(c, "portal") == nil { + t.Fatal("remote portal use") + } + if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 1, X: 1}); err != nil { + t.Fatal("survivor cannot walk to portal", err) + } + if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 2, Target: "boss"}); err == nil { + t.Fatal("combat continued after victory") + } + c.View.Entity.Position = w.PortalPosition() + if e := w.Departure(c, "portal"); e != nil { + t.Fatal(e) + } + found := false + for _, entity := range w.Snapshot(c.View.Entity.ID, nil).Entities { + if entity.Kind == "portal" { + found = true + } + } + if !found { + t.Fatal("victory portal missing from snapshot") + } + raw, _ := json.Marshal(w) + var restored World + if e := json.Unmarshal(raw, &restored); e != nil { + t.Fatal(e) + } + if e := restored.Restore(w.now); e != nil { + t.Fatal(e) + } + rc := restored.Characters[c.View.Entity.ID] + if e := restored.Connect(rc.View.Entity.ID); e != nil { + t.Fatal(e) + } + if e := restored.Departure(rc, "portal"); e != nil { + t.Fatal("portal was not preserved across restart", e) + } +} diff --git a/server/internal/game/world.go b/server/internal/game/world.go index 2d89d1a..de931da 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -70,6 +70,7 @@ type ResourceLayout struct { Resources []p.Entity `json:"resources"` } type World struct { + Kind string `json:"kind,omitempty"` ProjectileVisuals []p.ProjectileVisual `json:"projectileVisuals,omitempty"` Projectiles map[string]*Projectile `json:"projectiles,omitempty"` Areas map[string]*CombatArea `json:"areas,omitempty"` @@ -114,6 +115,15 @@ func New(id string, seed int64, now time.Time, b content.Balance) *World { return w } func (w *World) Restore(now time.Time) error { + if w.Kind == "" { + w.Kind = "survival" + } + if w.Kind != "" && w.Kind != "survival" && w.Kind != "hub" { + return errors.New("unknown instance kind") + } + if w.IsHub() { + w.Phase = "hub" + } if w.Version != 1 && w.Version != GeneratorVersion { return errors.New("unsupported persisted generator version") } @@ -233,6 +243,9 @@ func (w *World) Age() float64 { func (w *World) Dirty() bool { return w.dirty } func (w *World) Saved() { w.dirty = false } func (w *World) SafeRadius() float64 { + if w.IsHub() { + return w.Balance.WorldRadius + } if w.Phase == "gathering" { return w.Balance.WorldRadius } @@ -248,7 +261,7 @@ func (w *World) Info() p.WorldInfo { online++ } } - return p.WorldInfo{ID: w.ID, Seed: w.Seed, Phase: w.Phase, AgeSeconds: w.Age(), BossInSeconds: math.Max(0, w.Balance.SeasonSeconds-w.Age()), CollapseInSeconds: math.Max(0, w.Balance.SeasonSeconds+w.Balance.CollapseSeconds-w.Age()), SafeRadius: w.SafeRadius(), Radius: w.Balance.WorldRadius, Online: online, Capacity: int64(w.Balance.MaxPlayers), BossHP: w.BossHP, BossMaxHP: w.Balance.BossHp} + return p.WorldInfo{Kind: stringPtr(w.Kind), ID: w.ID, Seed: w.Seed, Phase: w.Phase, AgeSeconds: w.Age(), BossInSeconds: math.Max(0, w.Balance.SeasonSeconds-w.Age()), CollapseInSeconds: math.Max(0, w.Balance.SeasonSeconds+w.Balance.CollapseSeconds-w.Age()), SafeRadius: w.SafeRadius(), Radius: w.Balance.WorldRadius, Online: online, Capacity: int64(w.Balance.MaxPlayers), BossHP: w.BossHP, BossMaxHP: w.Balance.BossHp} } func (w *World) ForAccount(account string) *Character { for _, c := range w.Characters { @@ -289,6 +302,9 @@ func (w *World) spawn(exclude string) (p.Vec3, error) { return p.Vec3{}, errors.New("no separated spawn available") } func (w *World) Join(account, name string) (*Character, error) { + if w.IsHub() { + return nil, errors.New("new characters must begin in a survival world") + } if c := w.ForAccount(account); c != nil { return c, nil } @@ -325,7 +341,7 @@ func (w *World) Join(account, name string) (*Character, error) { return c, nil } func (w *World) Import(c *Character) error { - if w.Phase != "gathering" || w.AdmissionsClosed || w.ForAccount(c.Account) != nil || w.Characters[c.View.Entity.ID] != nil || w.LivingCount() >= w.Balance.MaxPlayers { + if (w.Phase != "gathering" && w.Phase != "cataclysm" && !w.IsHub()) || w.AdmissionsClosed || w.ForAccount(c.Account) != nil || w.Characters[c.View.Entity.ID] != nil || w.LivingCount() >= w.Balance.MaxPlayers { return errors.New("destination cannot accept character") } if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 { @@ -414,6 +430,12 @@ func (w *World) chunk(x, z int) p.Chunk { return c } c := w.terrain.Chunk(x, z) + if w.IsHub() { + c.Resources = []p.Entity{} + c.Biome = "Survivor haven" + w.chunks[key] = c + return c + } if layout, ok := w.ResourceLayouts[key]; ok { c.Biome, c.Color, c.Resources = layout.Biome, layout.Color, layout.Resources } else { @@ -435,7 +457,7 @@ func (w *World) neighbors(pos p.Vec3) []p.Chunk { } func (w *World) Intent(id string, i p.Intent) error { c := w.Characters[id] - if c == nil || !c.Online || c.View.Entity.State != "alive" || w.Phase == "won" || w.Phase == "lost" { + if c == nil || !c.Online || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") || w.Phase == "lost" { return errors.New("character cannot act") } if i.Seq <= c.View.ACK || i.Seq > c.View.ACK+10000 { @@ -449,6 +471,12 @@ func (w *World) Intent(id string, i p.Intent) error { c.Sheltered = false w.dirty = true } + if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" { + return errors.New("use the victory portal to continue") + } + if w.IsHub() && (i.Op == "attack" || i.Op == "gather") { + return errors.New("combat and gathering are unavailable in the hub") + } switch i.Op { case "allocate-stat": return w.allocateStat(c, i.Target) @@ -525,7 +553,9 @@ func (w *World) craft(c *Character, name string) error { } c.View.Inventory, c.View.Items = inventory, items w.RefreshStats(c) - c.View.Skills["crafting"] += w.Balance.SkillXpPerAction + if w.AllowsXP() { + c.View.Skills["crafting"] += w.Balance.SkillXpPerAction + } c.Message = "Crafted " + name w.grantXP(c, w.Balance.Progression.CraftXP) w.evaluateTitles(c) @@ -587,6 +617,9 @@ func (w *World) kill(c *Character, reason string) { // Operator changes use the same simulation and persistence path as gameplay. func (w *World) Control(op, target, value, reason string) error { + if w.IsHub() && (op == "end-world" || op == "awaken-boss" || op == "spawn-mobs") { + return errors.New("hubs cannot be destroyed or host combat") + } switch op { case "spawn-mobs": return w.SpawnMobs(target, value) @@ -645,9 +678,13 @@ func (w *World) Advance(now time.Time, dt float64) { } w.ProjectileVisuals = kept dt = math.Max(0, math.Min(dt, 0.25)) - if w.Phase == "won" || w.Phase == "lost" { + if w.Phase == "lost" { return } + if w.Phase == "won" || w.IsHub() { + clear(w.Projectiles) + clear(w.Areas) + } if w.Phase == "gathering" && w.Age() >= w.Balance.SeasonSeconds { w.Phase = "cataclysm" w.dirty = true @@ -655,7 +692,7 @@ func (w *World) Advance(now time.Time, dt float64) { active := map[string]bool{} characters := w.orderedCharacters() for _, c := range characters { - if c.View.Entity.State != "alive" { + if c.View.Entity.State != "alive" && c.View.Entity.State != "eligible" { continue } w.resetDay(c) @@ -707,7 +744,9 @@ func (w *World) Advance(now time.Time, dt float64) { w.moveCharacter(c, dt) for _, ch := range w.neighbors(c.View.Entity.Position) { active[ch.Key] = true - w.ensureMob(ch) + if !w.IsHub() && w.Phase != "won" { + w.ensureMob(ch) + } } } if w.Phase == "cataclysm" && math.Hypot(c.View.Entity.Position.X, c.View.Entity.Position.Z) > w.SafeRadius() { @@ -718,8 +757,10 @@ func (w *World) Advance(now time.Time, dt float64) { w.kill(c, "The encroaching ruin claimed this character.") } } - w.updateMobs(active, dt) - w.updateCombat(dt) + if !w.IsHub() && w.Phase != "won" { + w.updateMobs(active, dt) + w.updateCombat(dt) + } if w.Phase == "cataclysm" { if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown { for _, c := range characters { @@ -818,7 +859,7 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot { } } for _, m := range w.Mobs { - if m.Entity.HP > 0 && visible(m.Entity.Position) { + if !w.IsHub() && w.Phase != "won" && m.Entity.HP > 0 && visible(m.Entity.Position) { s.Entities = append(s.Entities, m.Entity) } } @@ -841,10 +882,16 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot { s.Entities = append(s.Entities, p.Entity{ID: area.ID, Kind: "area", Name: area.Attack.Name, Position: area.Position, State: area.Attack.Effect, Radius: &radius, HP: 1, MaxHP: 1}) } } + if w.Phase == "won" && visible(w.PortalPosition()) { + s.Entities = append(s.Entities, p.Entity{ID: "hub-portal", Kind: "portal", Name: "Portal to the hub", Position: w.PortalPosition(), HP: 1, MaxHP: 1, State: "open"}) + } sort.Slice(s.Entities, func(i, j int) bool { return s.Entities[i].ID < s.Entities[j].ID }) return s } func (w *World) TriggerBoss() error { + if w.IsHub() { + return errors.New("hubs have no Harbinger") + } if w.Phase != "gathering" { return fmt.Errorf("boss event already started") } diff --git a/server/internal/game/world_test.go b/server/internal/game/world_test.go index 21bb82e..030b98e 100644 --- a/server/internal/game/world_test.go +++ b/server/internal/game/world_test.go @@ -247,8 +247,11 @@ func TestBossVictoryAndCollapse(t *testing.T) { if c.View.Entity.State != "eligible" { t.Fatal("victory not terminal") } - if w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 2, X: 1}) == nil { - t.Fatal("survivor mutated frozen world") + if w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 2, X: 1}) != nil { + t.Fatal("survivor cannot walk to the victory portal") + } + if w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 3, Target: "boss"}) == nil { + t.Fatal("combat continued after victory") } }) t.Run("collapse kills offline and capped characters", func(t *testing.T) { diff --git a/server/internal/gitops/worlds.go b/server/internal/gitops/worlds.go index 55ba9bd..91bf6a3 100644 --- a/server/internal/gitops/worlds.go +++ b/server/internal/gitops/worlds.go @@ -107,6 +107,12 @@ func scalar(v string) *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag: // Only the worlds sequence is changed; image pins, comments and runtime settings // stay intact. Gitea's content SHA rejects concurrent image-promotion overwrites. func (c *Client) CreateWorld(ctx context.Context, id, seed string) (string, error) { + return c.CreateInstance(ctx, id, seed, "survival") +} +func (c *Client) CreateInstance(ctx context.Context, id, seed, kind string) (string, error) { + if kind != "hub" && kind != "survival" { + return "", errors.New("invalid world kind") + } if !identifier.MatchString(id) || !seedPattern.MatchString(seed) { return "", errors.New("invalid world ID or seed") } @@ -147,16 +153,20 @@ func (c *Client) CreateWorld(ctx context.Context, id, seed string) (string, erro key := mapping(world, "id") if key != nil && key.Value == id { existing := mapping(world, "seed") - if existing != nil && existing.Value == seed { + existingKind := "survival" + if k := mapping(world, "kind"); k != nil { + existingKind = k.Value + } + if existing != nil && existing.Value == seed && existingKind == kind { return "World definition already committed; waiting for ArgoCD readiness.", nil } - return "", errors.New("world ID already exists with a different seed") + return "", errors.New("world ID already exists with a different seed or kind") } } if len(worlds.Content) >= 50 { return "", errors.New("operator world limit reached (50)") } - worlds.Content = append(worlds.Content, &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{scalar("id"), scalar(id), scalar("seed"), scalar(seed), scalar("host"), scalar(public.Host)}}) + worlds.Content = append(worlds.Content, &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{scalar("id"), scalar(id), scalar("seed"), scalar(seed), scalar("host"), scalar(public.Host), scalar("kind"), scalar(kind)}}) encoded, err := yaml.Marshal(&doc) if err != nil { return "", err diff --git a/server/internal/gitops/worlds_test.go b/server/internal/gitops/worlds_test.go index 9a6df9a..1b7dd78 100644 --- a/server/internal/gitops/worlds_test.go +++ b/server/internal/gitops/worlds_test.go @@ -74,6 +74,15 @@ func TestCreateWorldPreservesValuesAndRetries(t *testing.T) { if _, err = c.CreateWorld(context.Background(), "../bad", "42"); err == nil { t.Fatal("invalid ID accepted") } + if _, err = c.CreateInstance(context.Background(), "hub-001", "50", "hub"); err != nil || !strings.Contains(current, "kind: hub") { + t.Fatal("hub definition missing", err, current) + } + if _, err = c.CreateInstance(context.Background(), "hub-001", "50", "hub"); err != nil || puts != 3 { + t.Fatal("hub retry duplicated instance", err) + } + if _, err = c.CreateWorld(context.Background(), "hub-001", "50"); err == nil { + t.Fatal("existing hub changed to survival world") + } } func TestGitOpsConfigurationValidation(t *testing.T) { for _, repository := range []string{"http://example.test/o/r", "https://token@example.test/o/r", "https://example.test/only-one", "https://example.test/../repo"} { diff --git a/server/internal/protocol/generated.go b/server/internal/protocol/generated.go index e812b6b..3dc6cad 100644 --- a/server/internal/protocol/generated.go +++ b/server/internal/protocol/generated.go @@ -549,6 +549,7 @@ type WorldInfo struct { Capacity int64 `json:"capacity"` CollapseInSeconds float64 `json:"collapseInSeconds"` ID string `json:"id"` + Kind *string `json:"kind,omitempty"` Online int64 `json:"online"` Phase string `json:"phase"` Radius float64 `json:"radius"` diff --git a/server/internal/store/portal.go b/server/internal/store/portal.go index ff571d9..19742d6 100644 --- a/server/internal/store/portal.go +++ b/server/internal/store/portal.go @@ -24,6 +24,7 @@ type CharacterRecord struct { Character *game.Character `json:"character"` } type WorldRecord struct { + Kind string `json:"kind"` ID string `json:"id"` Phase string `json:"phase"` Living int `json:"living"` @@ -69,6 +70,9 @@ func (d *DB) migrate(ctx context.Context) error { `CREATE TABLE IF NOT EXISTS title_revocations(account_id TEXT NOT NULL,title_id TEXT NOT NULL,command_id TEXT NOT NULL,PRIMARY KEY(account_id,title_id))`, `CREATE TABLE IF NOT EXISTS character_records(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, world_id TEXT NOT NULL, name TEXT NOT NULL, state TEXT NOT NULL, character TEXT NOT NULL)`, `CREATE UNIQUE INDEX IF NOT EXISTS one_living_character ON character_records(account_id) WHERE state IN ('alive','eligible')`, + `CREATE UNIQUE INDEX IF NOT EXISTS one_current_character ON character_records(account_id) WHERE state IN ('alive','eligible','transit')`, + `CREATE TABLE IF NOT EXISTS character_transfers(id TEXT PRIMARY KEY,request_id TEXT NOT NULL,account_id TEXT NOT NULL,source_world TEXT NOT NULL,source_kind TEXT NOT NULL,destination TEXT NOT NULL,character_id TEXT NOT NULL,route TEXT NOT NULL,status TEXT NOT NULL,accepted_world TEXT NOT NULL,character TEXT NOT NULL,UNIQUE(account_id,request_id))`, + `CREATE UNIQUE INDEX IF NOT EXISTS one_pending_transfer ON character_transfers(account_id) WHERE status='prepared'`, `CREATE INDEX IF NOT EXISTS characters_world ON character_records(world_id)`, `CREATE TABLE IF NOT EXISTS admin_sessions(token_hash TEXT PRIMARY KEY, expires BIGINT NOT NULL)`, `CREATE TABLE IF NOT EXISTS control_commands(id TEXT PRIMARY KEY, world_id TEXT NOT NULL, actor TEXT NOT NULL, op TEXT NOT NULL, target TEXT NOT NULL, value TEXT NOT NULL, reason TEXT NOT NULL, status TEXT NOT NULL, result TEXT NOT NULL, created_at BIGINT NOT NULL, completed_at BIGINT NOT NULL DEFAULT 0)`, @@ -140,7 +144,7 @@ func (d *DB) writeCharacter(ctx context.Context, tx *sql.Tx, world string, c *ga where = "character_records.account_id=excluded.account_id" } _, err = tx.ExecContext(ctx, d.q(`INSERT INTO character_records(character_id,account_id,world_id,name,state,character) VALUES(?,?,?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET world_id=excluded.world_id,name=excluded.name,state=excluded.state,character=excluded.character WHERE `+where), c.View.Entity.ID, c.Account, world, c.View.Entity.Name, c.View.Entity.State, string(raw)) - if err != nil && (strings.Contains(err.Error(), "one_living_character") || strings.Contains(err.Error(), "character_records.account_id")) { + if err != nil && ((strings.Contains(err.Error(), "one_living_character") || strings.Contains(err.Error(), "one_current_character")) || strings.Contains(err.Error(), "character_records.account_id")) { return ErrLivingCharacter } return err @@ -168,7 +172,7 @@ func (d *DB) syncCharacters(ctx context.Context, tx *sql.Tx, w *game.World, clai func (d *DB) ActiveCharacter(ctx context.Context, account string) (*CharacterRecord, error) { var r CharacterRecord var raw string - err := d.sql.QueryRowContext(ctx, d.q(`SELECT character_id,account_id,world_id,name,state,character FROM character_records WHERE account_id=? AND state IN ('alive','eligible')`), account).Scan(&r.ID, &r.Account, &r.WorldID, &r.Name, &r.State, &raw) + err := d.sql.QueryRowContext(ctx, d.q(`SELECT character_id,account_id,world_id,name,state,character FROM character_records WHERE account_id=? AND state IN ('alive','eligible','transit')`), account).Scan(&r.ID, &r.Account, &r.WorldID, &r.Name, &r.State, &raw) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -230,6 +234,10 @@ func (d *DB) Worlds(ctx context.Context) ([]WorldRecord, error) { return nil, err } r.ID = w.ID + r.Kind = w.Kind + if r.Kind == "" { + r.Kind = "survival" + } r.CatalogVersion = w.CatalogVersion r.Phase = w.Phase r.Living = w.LivingCount() @@ -299,6 +307,6 @@ func (d *DB) FinishProvision(ctx context.Context, id, result string, success boo if success { status = "completed" } - _, err := d.sql.ExecContext(ctx, d.q(`UPDATE control_commands SET status=?,result=?,completed_at=`+d.now()+` WHERE id=? AND status='pending' AND op='create-world'`), status, result, id) + _, err := d.sql.ExecContext(ctx, d.q(`UPDATE control_commands SET status=?,result=?,completed_at=`+d.now()+` WHERE id=? AND status='pending' AND op IN ('create-world','create-hub')`), status, result, id) return err } diff --git a/server/internal/store/travel.go b/server/internal/store/travel.go new file mode 100644 index 0000000..9726294 --- /dev/null +++ b/server/internal/store/travel.go @@ -0,0 +1,218 @@ +package store + +import ( + "aeternalis/server/internal/game" + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "maps" +) + +var ErrTravel = errors.New("travel unavailable") + +func travelError(message string) error { return fmt.Errorf("%w: %s", ErrTravel, message) } + +type Transfer struct { + ID string `json:"id"` + RequestID string `json:"requestId"` + Account string `json:"-"` + Source string `json:"source"` + SourceKind string `json:"sourceKind"` + Destination string `json:"destination"` + CharacterID string `json:"characterId"` + Route string `json:"route"` + Status string `json:"status"` + AcceptedWorld string `json:"acceptedWorld"` + Payload string `json:"-"` +} + +const transferColumns = `id,request_id,account_id,source_world,source_kind,destination,character_id,route,status,accepted_world,character` + +func scanTransfer(row interface{ Scan(...any) error }) (*Transfer, error) { + t := &Transfer{} + err := row.Scan(&t.ID, &t.RequestID, &t.Account, &t.Source, &t.SourceKind, &t.Destination, &t.CharacterID, &t.Route, &t.Status, &t.AcceptedWorld, &t.Payload) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + return t, err +} +func (d *DB) PendingTransfer(ctx context.Context, account string) (*Transfer, error) { + return scanTransfer(d.sql.QueryRowContext(ctx, d.q(`SELECT `+transferColumns+` FROM character_transfers WHERE account_id=? AND status='prepared'`), account)) +} +func (d *DB) Transfer(ctx context.Context, account, id string) (*Transfer, error) { + return scanTransfer(d.sql.QueryRowContext(ctx, d.q(`SELECT `+transferColumns+` FROM character_transfers WHERE account_id=? AND id=?`), account, id)) +} +func (d *DB) RequestedTransfer(ctx context.Context, account, request string) (*Transfer, error) { + return scanTransfer(d.sql.QueryRowContext(ctx, d.q(`SELECT `+transferColumns+` FROM character_transfers WHERE account_id=? AND request_id=?`), account, request)) +} +func (l *Lease) fenceTravel(ctx context.Context, tx *sql.Tx, w *game.World) error { + raw, err := json.Marshal(w) + if err != nil { + return err + } + r, err := tx.ExecContext(ctx, l.DB.q(`UPDATE worlds SET snapshot=?,revision=revision+1,lease_until=`+l.DB.now()+`+30 WHERE id=? AND owner=? AND revision=? AND lease_until>=`+l.DB.now()), string(raw), l.WorldID, l.Owner, l.Revision) + if err != nil { + return err + } + n, _ := r.RowsAffected() + if n != 1 { + return ErrOwnership + } + return nil +} +func (l *Lease) PrepareTravel(ctx context.Context, live *game.World, account, request, destination, route string) (*Transfer, error) { + d := l.DB + previous, err := d.RequestedTransfer(ctx, account, request) + if err != nil { + return nil, err + } + if previous != nil { + if previous.Source != live.ID || previous.Destination != destination || previous.Route != route { + return nil, travelError("request already used") + } + return previous, nil + } + c := live.ForAccount(account) + if err = live.Departure(c, route); err != nil { + return nil, travelError(err.Error()) + } + if destination == live.ID { + return nil, travelError("choose another world") + } + worlds, err := d.Worlds(ctx) + if err != nil { + return nil, err + } + valid := false + for _, w := range worlds { + if w.ID == destination && w.Available && !w.Closed && w.Living < w.Capacity && (w.Phase == "hub" || w.Phase == "gathering" || w.Phase == "cataclysm") && (live.IsHub() || w.Kind == "hub") { + valid = true + } + } + if !valid { + return nil, travelError("destination unavailable or full") + } + // Only the departing copy is changed before commit. Other online players retain + // their connections, inputs and acknowledgement counters. + staged := *live + staged.Characters = maps.Clone(live.Characters) + raw, err := json.Marshal(c) + if err != nil { + return nil, err + } + var departing game.Character + if err = json.Unmarshal(raw, &departing); err != nil { + return nil, err + } + if route == "escape" { + departing.View.Inventory["escape_stone"]-- + if departing.View.Inventory["escape_stone"] == 0 { + delete(departing.View.Inventory, "escape_stone") + } + } + raw, err = json.Marshal(&departing) + if err != nil { + return nil, err + } + t := &Transfer{ID: game.ID(), RequestID: request, Account: account, Source: live.ID, SourceKind: live.Kind, Destination: destination, CharacterID: c.View.Entity.ID, Route: route, Status: "prepared", Payload: string(raw)} + delete(staged.Characters, t.CharacterID) + tx, err := d.sql.BeginTx(ctx, nil) + if err != nil { + return nil, err + } + defer tx.Rollback() + if err = l.fenceTravel(ctx, tx, &staged); err != nil { + return nil, err + } + _, err = tx.ExecContext(ctx, d.q(`INSERT INTO character_transfers(`+transferColumns+`) VALUES(?,?,?,?,?,?,?,?,?,?,?)`), t.ID, t.RequestID, t.Account, t.Source, t.SourceKind, t.Destination, t.CharacterID, t.Route, t.Status, "", t.Payload) + if err != nil { + return nil, err + } + marker := "travel:" + t.ID + if _, err = tx.ExecContext(ctx, d.q(`UPDATE passages SET claimed_world=? WHERE character_id=? AND account_id=? AND source_world=? AND claimed_world IS NULL`), marker, t.CharacterID, account, live.ID); err != nil { + return nil, err + } + r, err := tx.ExecContext(ctx, d.q(`UPDATE character_records SET world_id=?,state='transit',character=? WHERE character_id=? AND account_id=? AND world_id=? AND state IN ('alive','eligible')`), marker, t.Payload, t.CharacterID, account, live.ID) + if err != nil { + return nil, err + } + n, _ := r.RowsAffected() + if n != 1 { + return nil, travelError("character no longer belongs to source") + } + if err = tx.Commit(); err != nil { + return nil, err + } + l.Revision++ + *live = staged + live.Saved() + return t, nil +} +func (l *Lease) AcceptTravel(ctx context.Context, live *game.World, account, id string) (*Transfer, error) { + d := l.DB + t, err := d.Transfer(ctx, account, id) + if err != nil { + return nil, err + } + if t == nil { + return nil, travelError("transfer not found") + } + if t.Status == "accepted" { + return t, nil + } + if t.SourceKind != "hub" && !live.IsHub() { + return nil, travelError("escape and victory lead to a hub") + } + staged := *live + staged.Characters = maps.Clone(live.Characters) + var c game.Character + if err = json.Unmarshal([]byte(t.Payload), &c); err != nil { + return nil, err + } + if err = staged.Arrive(&c); err != nil { + return nil, travelError(err.Error()) + } + raw, err := json.Marshal(&c) + if err != nil { + return nil, err + } + tx, err := d.sql.BeginTx(ctx, nil) + if err != nil { + return nil, err + } + defer tx.Rollback() + if err = l.fenceTravel(ctx, tx, &staged); err != nil { + return nil, err + } + r, err := tx.ExecContext(ctx, d.q(`UPDATE character_transfers SET status='accepted',accepted_world=? WHERE id=? AND account_id=? AND status='prepared'`), live.ID, id, account) + if err != nil { + return nil, err + } + n, _ := r.RowsAffected() + if n != 1 { + return nil, travelError("transfer already accepted; refresh travel status") + } + marker := "travel:" + id + if _, err = tx.ExecContext(ctx, d.q(`UPDATE passages SET claimed_world=? WHERE character_id=? AND account_id=? AND claimed_world=?`), live.ID, t.CharacterID, account, marker); err != nil { + return nil, err + } + r, err = tx.ExecContext(ctx, d.q(`UPDATE character_records SET world_id=?,state='alive',character=? WHERE character_id=? AND account_id=? AND world_id=? AND state='transit'`), live.ID, string(raw), t.CharacterID, account, marker) + if err != nil { + return nil, err + } + n, _ = r.RowsAffected() + if n != 1 { + return nil, travelError("transfer no longer owns character") + } + if err = tx.Commit(); err != nil { + return nil, err + } + l.Revision++ + *live = staged + live.Saved() + t.Status = "accepted" + t.AcceptedWorld = live.ID + return t, nil +} diff --git a/server/internal/store/travel_test.go b/server/internal/store/travel_test.go new file mode 100644 index 0000000..3d6dcbc --- /dev/null +++ b/server/internal/store/travel_test.go @@ -0,0 +1,279 @@ +package store + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "reflect" + "sync" + "testing" + "time" +) + +func TestTravelLifecycle(t *testing.T) { + runTravelTests(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "travel.db"))) +} +func TestPostgresTravelLifecycle(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not configured") + } + runTravelTests(t, dsn) +} +func runTravelTests(t *testing.T, dsn string) { + ctx := context.Background() + db, err := Open(ctx, dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + b, _ := content.Load() + now := time.Now().UTC() + suffix := game.ID() + makeWorld := func(id, kind string) (*game.World, *Lease) { + t.Helper() + w := game.New(id+suffix, 123, now, b) + w.Kind = kind + if kind == "hub" { + w.Phase = "hub" + } + l, _, e := db.Acquire(ctx, w) + if e != nil { + t.Fatal(e) + } + return w, l + } + source, sl := makeWorld("source", "survival") + hub, hl := makeWorld("hub", "hub") + other, ol := makeWorld("other", "hub") + next, nl := makeWorld("next", "survival") + c, e := source.Join("traveler"+suffix, "Traveler") + if e != nil { + t.Fatal(e) + } + id := c.View.Entity.ID + c.View.Inventory["escape_stone"] = 2 + c.View.Inventory["wood"] = 31 + c.View.Skills["combat"] = 29 + c.View.Level = 3 + c.View.PendingVitalChoices = 2 + c.View.Experience = 7 + c.View.StatPoints = 20 + c.DailySeconds = 123 + c.WorldsSurvived = 2 + if e = source.AdminItems(c, "grant-item", "spear:1"); e != nil { + t.Fatal(e) + } + if e = source.Connect(id); e != nil { + t.Fatal(e) + } + if e = sl.Save(ctx, source, ""); e != nil { + t.Fatal(e) + } + if _, e = sl.PrepareTravel(ctx, source, c.Account, game.ID(), next.ID, "escape"); !errors.Is(e, ErrTravel) { + t.Fatal("escape accepted survival destination", e) + } + if c.View.Inventory["escape_stone"] != 2 { + t.Fatal("rejected escape spent item") + } + request := game.ID() + transfer, e := sl.PrepareTravel(ctx, source, c.Account, request, hub.ID, "escape") + if e != nil { + t.Fatal(e) + } + if source.ForAccount(c.Account) != nil { + t.Fatal("source retained the live character") + } + active, e := db.ActiveCharacter(ctx, c.Account) + if e != nil || active == nil || active.State != "transit" { + t.Fatal("missing travel reservation", e) + } + // The account cannot create a replacement while in escrow. + replacement, _ := next.Join(c.Account, "Replacement") + if e = nl.Save(ctx, next, ""); !errors.Is(e, ErrLivingCharacter) { + t.Fatal("replacement bypassed in-transit life", e) + } + delete(next.Characters, replacement.View.Entity.ID) + again, e := sl.PrepareTravel(ctx, source, c.Account, request, hub.ID, "escape") + if e != nil || again.ID != transfer.ID { + t.Fatal("departure retry was not idempotent", e) + } + if _, e = hl.AcceptTravel(ctx, hub, "intruder", transfer.ID); !errors.Is(e, ErrTravel) { + t.Fatal("another account accepted transfer", e) + } + hub.AdmissionsClosed = true + if _, e = hl.AcceptTravel(ctx, hub, c.Account, transfer.ID); !errors.Is(e, ErrTravel) { + t.Fatal("closed hub accepted transfer", e) + } + if hub.ForAccount(c.Account) != nil { + t.Fatal("rejected arrival mutated destination") + } + hub.AdmissionsClosed = false + hub.Balance.MaxPlayers = 0 + if _, e = hl.AcceptTravel(ctx, hub, c.Account, transfer.ID); !errors.Is(e, ErrTravel) { + t.Fatal("full hub accepted transfer", e) + } + hub.Balance.MaxPlayers = b.MaxPlayers + // Departure survives source destruction and a process/database restart. + source.Phase = "lost" + if e = sl.Save(ctx, source, ""); e != nil { + t.Fatal(e) + } + reopened, e := Open(ctx, dsn) + if e != nil { + t.Fatal(e) + } + pending, e := reopened.PendingTransfer(ctx, c.Account) + reopened.Close() + if e != nil || pending == nil || pending.ID != transfer.ID { + t.Fatal("pending transfer was not durable", e) + } + var wg sync.WaitGroup + results := make(chan error, 2) + for i := range 2 { + wg.Add(1) + go func(i int) { + defer wg.Done() + w, l := hub, hl + if i == 1 { + w, l = other, ol + } + _, err := l.AcceptTravel(ctx, w, c.Account, transfer.ID) + results <- err + }(i) + } + wg.Wait() + close(results) + for err := range results { + if err != nil && !errors.Is(err, ErrTravel) { + t.Fatal(err) + } + } + copies := 0 + var arrived *game.Character + var current *game.World + var lease *Lease + for i, w := range []*game.World{hub, other} { + if v := w.ForAccount(c.Account); v != nil { + copies++ + arrived = v + current = w + lease = hl + if i == 1 { + lease = ol + } + } + } + if copies != 1 { + t.Fatalf("arrival copies: %d", copies) + } + if !reflect.DeepEqual(arrived.View.Items, c.View.Items) || !reflect.DeepEqual(arrived.View.Gathering, c.View.Gathering) || !reflect.DeepEqual(arrived.View.AllocatedStats, c.View.AllocatedStats) { + t.Fatal("item identities or character progression changed during travel") + } + if arrived.View.Inventory["escape_stone"] != 1 || arrived.View.Inventory["wood"] != 31 || arrived.View.Level != 3 || arrived.View.Experience != 7 || arrived.View.StatPoints != 20 || arrived.View.Skills["combat"] != 29 || arrived.DailySeconds != 123 || arrived.WorldsSurvived != 2 || arrived.View.Entity.ID != id || !reflect.DeepEqual(arrived.View.Titles, c.View.Titles) { + t.Fatal("travel changed ownership, progression, time, or survival credit") + } + accepted, e := hl.AcceptTravel(ctx, hub, c.Account, transfer.ID) + if e != nil || accepted.AcceptedWorld != current.ID { + t.Fatal("arrival retry changed destination", e) + } + if e = current.Connect(id); e != nil { + t.Fatal(e) + } + if e = lease.Save(ctx, current, ""); e != nil { + t.Fatal(e) + } + switchTo, switchLease := hub, hl + if current == hub { + switchTo, switchLease = other, ol + } + switched, e := lease.PrepareTravel(ctx, current, c.Account, game.ID(), switchTo.ID, "hub") + if e != nil { + t.Fatal(e) + } + if _, e = switchLease.AcceptTravel(ctx, switchTo, c.Account, switched.ID); e != nil { + t.Fatal(e) + } + if e = switchTo.Connect(id); e != nil { + t.Fatal(e) + } + if e = switchLease.Save(ctx, switchTo, ""); e != nil { + t.Fatal(e) + } + onward, e := switchLease.PrepareTravel(ctx, switchTo, c.Account, game.ID(), next.ID, "hub") + if e != nil { + t.Fatal(e) + } + next.Phase = "lost" + if _, e = nl.AcceptTravel(ctx, next, c.Account, onward.ID); !errors.Is(e, ErrTravel) { + t.Fatal("destroyed destination accepted traveler", e) + } + next.Phase = "cataclysm" + if _, e = nl.AcceptTravel(ctx, next, c.Account, onward.ID); e != nil { + t.Fatal("admission to collapsing world failed", e) + } + if next.Characters[id].View.Inventory["escape_stone"] != 1 { + t.Fatal("hub travel consumed escape item") + } + // The persisted destination, not just the in-memory world, owns this life. + var raw string + if e = db.sql.QueryRowContext(ctx, db.q(`SELECT snapshot FROM worlds WHERE id=?`), next.ID).Scan(&raw); e != nil { + t.Fatal(e) + } + var restored game.World + if e = json.Unmarshal([]byte(raw), &restored); e != nil || restored.Characters[id] == nil { + t.Fatal("arrival snapshot missing", e) + } + active, e = db.ActiveCharacter(ctx, c.Account) + if e != nil || active.WorldID != next.ID || active.State != "alive" { + t.Fatal("arrival registry missing", e) + } +} + +func TestTravelLeaseRollback(t *testing.T) { + ctx := context.Background() + db, e := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "fence.db"))) + if e != nil { + t.Fatal(e) + } + defer db.Close() + b, _ := content.Load() + source := game.New("source", 1, time.Now(), b) + hub := game.New("hub", 2, time.Now(), b) + hub.Kind = "hub" + hub.Phase = "hub" + sl, _, _ := db.Acquire(ctx, source) + hl, _, _ := db.Acquire(ctx, hub) + c, _ := source.Join("account", "Traveler") + _ = source.Connect(c.View.Entity.ID) + c.View.Inventory["escape_stone"] = 1 + _ = sl.Save(ctx, source, "") + stale := *sl + stale.Revision-- + if _, e = stale.PrepareTravel(ctx, source, c.Account, game.ID(), hub.ID, "escape"); !errors.Is(e, ErrOwnership) { + t.Fatal("stale source was not fenced", e) + } + if source.ForAccount(c.Account) != c || c.View.Inventory["escape_stone"] != 1 { + t.Fatal("rollback changed live source") + } + tr, e := sl.PrepareTravel(ctx, source, c.Account, game.ID(), hub.ID, "escape") + if e != nil { + t.Fatal(e) + } + stale = *hl + stale.Revision-- + if _, e = stale.AcceptTravel(ctx, hub, c.Account, tr.ID); !errors.Is(e, ErrOwnership) { + t.Fatal("stale destination was not fenced", e) + } + if hub.ForAccount(c.Account) != nil { + t.Fatal("rollback leaked destination character") + } + pending, _ := db.PendingTransfer(ctx, c.Account) + if pending == nil { + t.Fatal("rollback consumed transfer") + } +} diff --git a/server/internal/transport/control.go b/server/internal/transport/control.go index fe59213..3b3c151 100644 --- a/server/internal/transport/control.go +++ b/server/internal/transport/control.go @@ -116,7 +116,7 @@ func (h *HTTP) portalRoutes(mux *http.ServeMux) { fail(w, 400, "choose a title") return } - case "create-world": + case "create-world", "create-hub": if h.Provisioner == nil { fail(w, 503, "GitOps provisioning is not configured") return @@ -145,7 +145,7 @@ func (h *HTTP) portalRoutes(mux *http.ServeMux) { return } } - if req.Op != "create-world" { + if req.Op != "create-world" && req.Op != "create-hub" { worlds, err := h.auth.db.Worlds(r.Context()) if err != nil { fail(w, 503, "world directory unavailable") @@ -163,7 +163,7 @@ func (h *HTTP) portalRoutes(mux *http.ServeMux) { } } command := store.Command{ID: req.ID, WorldID: req.WorldID, Actor: actor, Op: req.Op, Target: req.Target, Value: req.Value, Reason: req.Reason} - if req.Op == "create-world" { + if req.Op == "create-world" || req.Op == "create-hub" { command.Target = req.WorldID command.WorldID = "_provision" } @@ -193,11 +193,15 @@ func (h *HTTP) RunProvisioning(ctx context.Context) { continue } for _, c := range commands { - if c.Op != "create-world" { + if c.Op != "create-world" && c.Op != "create-hub" { continue } request, cancel := context.WithTimeout(ctx, 45*time.Second) - result, err := h.Provisioner.CreateWorld(request, c.Target, c.Value) + kind := "survival" + if c.Op == "create-hub" { + kind = "hub" + } + result, err := h.Provisioner.CreateInstance(request, c.Target, c.Value, kind) cancel() if errors.Is(ctx.Err(), context.Canceled) { return diff --git a/server/internal/transport/http.go b/server/internal/transport/http.go index a10a3f5..5885526 100644 --- a/server/internal/transport/http.go +++ b/server/internal/transport/http.go @@ -97,6 +97,7 @@ func (h *HTTP) allow(r *http.Request) bool { func (h *HTTP) Handler() http.Handler { mux := http.NewServeMux() h.portalRoutes(mux) + h.travelRoutes(mux) h.catalogRoutes(mux) mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { if !h.s.ready.Load() { @@ -148,7 +149,7 @@ func (h *HTTP) Handler() http.Handler { h.s.mu.Lock() defer h.s.mu.Unlock() b := h.s.world.Balance - respond(w, 200, map[string]any{"worldId": h.s.world.ID, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "recipes": b.Recipes, "tickHz": b.TickHz}) + respond(w, 200, map[string]any{"worldId": h.s.world.ID, "kind": h.s.world.Kind, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "recipes": b.Recipes, "tickHz": b.TickHz}) }) mux.HandleFunc("GET /api/preview", func(w http.ResponseWriter, r *http.Request) { h.s.mu.Lock() @@ -367,8 +368,10 @@ func (h *HTTP) socket(w http.ResponseWriter, r *http.Request) { cancel() _ = conn.CloseNow() h.s.mu.Lock() - delete(h.s.peers, id) - h.s.world.Disconnect(id) + if h.s.peers[id] == peer { + delete(h.s.peers, id) + h.s.world.Disconnect(id) + } h.s.mu.Unlock() }() go func() { diff --git a/server/internal/transport/service.go b/server/internal/transport/service.go index 8a9dc3a..02ddcc6 100644 --- a/server/internal/transport/service.go +++ b/server/internal/transport/service.go @@ -135,6 +135,9 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char if err := s.refreshCatalog(ctx); err != nil { return p.Character{}, err } + if claim != "" { + return p.Character{}, errors.New("use the victory portal and travel menu") + } var c *game.Character var err error active, err := s.lease.DB.ActiveCharacter(ctx, account) diff --git a/server/internal/transport/travel.go b/server/internal/transport/travel.go new file mode 100644 index 0000000..a792b12 --- /dev/null +++ b/server/internal/transport/travel.go @@ -0,0 +1,114 @@ +package transport + +import ( + "aeternalis/server/internal/store" + "errors" + "net/http" + "time" +) + +func (h *HTTP) travelRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/travel", func(w http.ResponseWriter, r *http.Request) { + account, err := h.auth.account(r) + if err != nil { + fail(w, 401, "sign in required") + return + } + var t *store.Transfer + if id := r.URL.Query().Get("id"); id != "" { + t, err = h.auth.db.Transfer(r.Context(), account, id) + } else { + t, err = h.auth.db.PendingTransfer(r.Context(), account) + } + if err != nil { + fail(w, 503, "travel status unavailable") + return + } + respond(w, 200, t) + }) + mux.HandleFunc("POST /api/travel/prepare", func(w http.ResponseWriter, r *http.Request) { + account, err := h.auth.account(r) + if err != nil { + fail(w, 401, "sign in required") + return + } + var req struct { + RequestID string `json:"requestId"` + Destination string `json:"destination"` + Route string `json:"route"` + } + if decode(w, r, &req) != nil || !requestIDPattern.MatchString(req.RequestID) || !worldIDPattern.MatchString(req.Destination) || (req.Route != "hub" && req.Route != "portal" && req.Route != "escape") { + fail(w, 400, "invalid travel request") + return + } + h.s.mu.Lock() + defer h.s.mu.Unlock() + if !h.s.ready.Load() { + fail(w, 503, "world unavailable") + return + } + // Flush pending awards and the source's current daily usage before escrow. + if err = h.s.persist(r.Context(), ""); err != nil { + fail(w, 503, "save unavailable") + return + } + t, err := h.s.lease.PrepareTravel(r.Context(), h.s.world, account, req.RequestID, req.Destination, req.Route) + if err != nil { + h.travelFailure(w, err) + return + } + if peer := h.s.peers[t.CharacterID]; peer != nil && t.Status == "prepared" && h.s.world.Characters[t.CharacterID] == nil { + delete(h.s.peers, t.CharacterID) + peer.close() + } + h.s.lastSave = time.Now() + respond(w, 200, t) + }) + mux.HandleFunc("POST /api/travel/accept", func(w http.ResponseWriter, r *http.Request) { + account, err := h.auth.account(r) + if err != nil { + fail(w, 401, "sign in required") + return + } + var req struct { + TransferID string `json:"transferId"` + } + if decode(w, r, &req) != nil || !requestIDPattern.MatchString(req.TransferID) { + fail(w, 400, "invalid transfer ID") + return + } + h.s.mu.Lock() + defer h.s.mu.Unlock() + if !h.s.ready.Load() { + fail(w, 503, "world unavailable") + return + } + if err = h.s.refreshCatalog(r.Context()); err != nil { + h.travelFailure(w, err) + return + } + if err = h.s.persist(r.Context(), ""); err != nil { + fail(w, 503, "save unavailable") + return + } + t, err := h.s.lease.AcceptTravel(r.Context(), h.s.world, account, req.TransferID) + if err != nil { + h.travelFailure(w, err) + return + } + h.s.lastSave = time.Now() + respond(w, 200, t) + }) +} +func (h *HTTP) travelFailure(w http.ResponseWriter, err error) { + if errors.Is(err, store.ErrTravel) { + fail(w, 409, err.Error()) + return + } + // An uncertain transaction result must never leave a process serving a stale life. + h.s.ready.Store(false) + for _, p := range h.s.peers { + p.close() + } + fail(w, 503, "travel save unavailable; check travel status before retrying") +} diff --git a/server/internal/transport/travel_test.go b/server/internal/transport/travel_test.go new file mode 100644 index 0000000..fa30639 --- /dev/null +++ b/server/internal/transport/travel_test.go @@ -0,0 +1,117 @@ +package transport + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + "aeternalis/server/internal/store" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestTravelHTTPAuthorizationAndResume(t *testing.T) { + ctx := context.Background() + db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "travel.db"))) + if err != nil { + t.Fatal(err) + } + defer db.Close() + b, _ := content.Load() + source := game.New("source", 1, time.Now(), b) + hub := game.New("hub", 2, time.Now(), b) + hub.Kind = "hub" + hub.Phase = "hub" + sl, _, _ := db.Acquire(ctx, source) + hl, _, _ := db.Acquire(ctx, hub) + c, _ := source.Join("owner", "Traveler") + c.View.Inventory["escape_stone"] = 1 + _ = source.Connect(c.View.Entity.ID) + if err = sl.Save(ctx, source, ""); err != nil { + t.Fatal(err) + } + auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "") + cookie := func(account string) *http.Cookie { + t.Helper() + out := httptest.NewRecorder() + r := httptest.NewRequest("POST", auth.base+"/auth/dev", nil) + if e := auth.session(out, r, account); e != nil { + t.Fatal(e) + } + return out.Result().Cookies()[0] + } + owner, intruder := cookie("owner"), cookie("intruder") + s := NewService(source, sl) + h := NewHTTP(s, auth, t.TempDir(), nil).Handler() + target := NewHTTP(NewService(hub, hl), auth, t.TempDir(), nil).Handler() + request := func(handler http.Handler, path, origin string, body any, cookie *http.Cookie) *httptest.ResponseRecorder { + t.Helper() + method := "GET" + var raw []byte + if body != nil { + method = "POST" + raw, _ = json.Marshal(body) + } + r := httptest.NewRequest(method, auth.base+path, strings.NewReader(string(raw))) + r.RemoteAddr = "127.0.0.1:4321" + if origin != "" { + r.Header.Set("Origin", origin) + } + if cookie != nil { + r.AddCookie(cookie) + } + out := httptest.NewRecorder() + handler.ServeHTTP(out, r) + return out + } + req := map[string]string{"requestId": game.ID(), "destination": "hub", "route": "escape"} + if r := request(h, "/api/travel/prepare", auth.base, req, nil); r.Code != 401 { + t.Fatal("anonymous travel", r.Code) + } + if r := request(h, "/api/travel/prepare", "https://evil.example", req, owner); r.Code != 403 { + t.Fatal("cross-origin travel", r.Code) + } + if r := request(h, "/api/travel/prepare", auth.base, req, intruder); r.Code != 409 { + t.Fatal("other account traveled", r.Code) + } + if !s.ready.Load() { + t.Fatal("ordinary rejection froze world") + } + r := request(h, "/api/travel/prepare", auth.base, req, owner) + if r.Code != 200 { + t.Fatal(r.Code, r.Body.String()) + } + var tr store.Transfer + if err = json.Unmarshal(r.Body.Bytes(), &tr); err != nil { + t.Fatal(err) + } + if strings.Contains(r.Body.String(), "escape_stone") || strings.Contains(r.Body.String(), "account") { + t.Fatal("private escrow leaked") + } + if r = request(h, "/api/travel", auth.base, nil, owner); r.Code != 200 || !strings.Contains(r.Body.String(), tr.ID) { + t.Fatal("pending recovery failed", r.Body.String()) + } + if r = request(h, "/api/travel?id="+tr.ID, auth.base, nil, intruder); r.Body.String() != "null\n" { + t.Fatal("transfer exposed to another account", r.Body.String()) + } + accept := map[string]string{"transferId": tr.ID} + if r = request(target, "/api/travel/accept", auth.base, accept, intruder); r.Code != 409 { + t.Fatal("other account claimed transfer", r.Code) + } + if r = request(target, "/api/travel/accept", auth.base, accept, owner); r.Code != 200 { + t.Fatal("arrival failed", r.Body.String()) + } + if r = request(target, "/api/travel/accept", auth.base, accept, owner); r.Code != 200 || hub.LivingCount() != 1 { + t.Fatal("arrival retry duplicated character", r.Body.String()) + } + if r = request(h, "/api/join", auth.base, map[string]string{"name": "Replacement", "passage": ""}, owner); r.Code != 409 { + t.Fatal("created replacement after travel", r.Code) + } + if r = request(h, "/api/join", auth.base, map[string]string{"name": "", "passage": c.View.Entity.ID}, owner); r.Code != 409 { + t.Fatal("legacy shortcut bypassed travel", r.Code) + } +}