aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit d4bc084f622f0ae465060e0255d393f914a8b975
parent b890ca2764c0bb45b84e8ac03a5d147a37c94a50
Author: anon <anon@example.com>
Date:   Fri,  6 Nov 2026 23:22:39 +0000

Open Options immediately and decouple account reads from simulation

Diffstat:
MTODO.md | 14++++++++++++++
Mclient/browser/index.html | 23++++++++++++++---------
Mclient/tests/browser_accounts.mjs | 39++++++++++++++++++++++++++++++++-------
Mclient/tests/browser_controls.mjs | 1+
Mclient/tests/browser_loading.mjs | 4++++
Mdocs/browser-accounts.md | 20+++++++++++++++++++-
Mserver/browser_account.go | 23+++++++++++++----------
Aserver/browser_account_info_test.go | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtests/e2e/mobile-creation.test.mjs | 4++++
Atests/e2e/options.test.mjs | 49+++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 224 insertions(+), 27 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -35,6 +35,20 @@ research separately. More screenshots and test cases do not count as new gamepla ## P0: first experience +- [x] **Open Options without an account lookup delay.** Account state loads with + the session and refreshes after native creation. Browser coverage holds the + lookup open while using Create/Log in; reopening sends no new request. The + account endpoint reads committed SQLite state without the simulation mutex. + Authenticated HTTP requests measured 1.1-3.3 ms with the native client running, + and a regression confirms the response completes while the simulation is locked. + +- [ ] **Isolate long simulation critical sections during phone play.** November 6: + local unauthenticated account requests waited 1.1-5.6 seconds on the simulation + mutex while static HTTPS responses took 2-8 ms; the server used about one CPU + core. Restart removed the long stalls, and a 20-second CPU/mutex profile of the + idle server did not isolate the previous long holder. Reopen profiling when an + active-play stall reproduces; preserve gameplay and persistence cadence. + - [x] **Use the original native character creation flow.** Login credentials are collected in a compact modal with password confirmation at native naming, with native controls blocked until OK diff --git a/client/browser/index.html b/client/browser/index.html @@ -113,7 +113,7 @@ </div> <section id="account-panel" hidden> <p id="account-current"></p> - <fieldset id="account-choices" disabled> + <fieldset id="account-choices"> <button id="create-button" type="button">Create character from scratch</button> <button id="claim-button" type="button" hidden>Save this character</button> <button id="password-button" type="button" hidden>Change password</button> @@ -430,6 +430,7 @@ show(); if (!response.ok) { status.textContent = await response.text(); return; } Module.arguments = (await response.text()).trim().split(' ').slice(1); Module.worldPort = Number(response.headers.get('X-AO-World-Port')) || Number(Module.arguments.at(-3)); + Module.loadAccount(); // The render worker owns the backing canvas after startup. [canvas.width, canvas.height] = renderSize(); // Keep the script available when later pthreads start during a server outage. @@ -453,7 +454,10 @@ show(); let creationSubmitted = false; Module.onCreationState = state => { creatorSeen ||= state.active; - if (creatorSeen) setCreatorActive(state.active); + if (creatorSeen) { + if (creatorActive && !state.active) Module.loadAccount(); + setCreatorActive(state.active); + } if (creationSubmitted && (!state.name || !state.active) && creationDialog.open) { creationDialog.close(); canvas.focus(); @@ -1030,7 +1034,6 @@ show(); }); window.visualViewport?.addEventListener('resize', updateChatViewport); window.visualViewport?.addEventListener('scroll', updateChatViewport); - startGame().catch(error => Module.onAbort(error.message)); </script> <script id="account-controls"> const accountForm = document.querySelector('#account-form'); @@ -1079,17 +1082,19 @@ show(); document.querySelector('#' + accountAction + '-button').focus(); accountAction = ''; }; - Module.onOptionsOpen = async () => { + Module.onOptionsOpen = () => { if (accountRequest) return; document.querySelector('#account-panel').hidden = false; accountForm.hidden = true; accountChoices.hidden = false; - accountChoices.disabled = true; accountAction = ''; document.querySelector('#account-name').value = document.querySelector('#account-password').value = ''; - accountError.textContent = ''; - claimButton.hidden = passwordButton.hidden = true; + if (currentName) accountError.textContent = ''; accountError.classList.remove('success'); + }; + + // Fetch identity during loading and after native creation, never on menu opening. + Module.loadAccount = async () => { try { const response = await fetch('browser-account'); if (!response.ok) { accountError.textContent = await response.text(); return; } @@ -1099,9 +1104,8 @@ show(); (player.visitor ? ' Save this character to enable name-and-password login.' : ''); claimButton.hidden = !player.visitor; passwordButton.hidden = !player.adopted; - accountChoices.disabled = false; } catch (error) { - accountError.textContent = 'Could not load player details. Open Options again to retry.'; + accountError.textContent = 'Could not load player details. Reload to retry.'; } }; accountForm.onsubmit = async event => { @@ -1137,5 +1141,6 @@ show(); Module.onGameClosed(replaced); } }; + startGame().catch(error => Module.onAbort(error.message)); </script> </html> diff --git a/client/tests/browser_accounts.mjs b/client/tests/browser_accounts.mjs @@ -25,7 +25,7 @@ function accountPage() { }; const window = new EventTarget(); const context = vm.createContext({ - document, window, navigator: {userAgent: 'Desktop'}, console, URLSearchParams, + document, window, navigator: {userAgent: 'Desktop'}, console, URLSearchParams, crossOriginIsolated: false, Option: class { constructor(text, value) { this.text = text; this.value = String(value); } }, localStorage: {getItem() { return null; }}, location: {reload: () => reloads.push(true), assign: url => reloads.push(url)}, @@ -43,6 +43,7 @@ function accountPage() { vm.runInContext(html.match(/<script id="account-controls">([\s\S]*?)<\/script>/)[1], context); return {context, requests, replies, reloads, timers, element: document.querySelector, open: () => context.Module.onOptionsOpen(), + load: () => context.Module.loadAccount(), choose: action => document.querySelector('#' + action + '-button').onclick(), submit: () => document.querySelector('#account-form').onsubmit({preventDefault() {}})}; } @@ -55,7 +56,8 @@ test('Options offers visitor account flows with credentials hidden until a choic const page = accountPage(); page.replies.push(response(200, {name: 'Lupeza', visitor: true})); - await page.open(); + await page.load(); + page.open(); assert.equal(page.element('#claim-button').hidden, false); assert.equal(page.element('#password-button').hidden, true); @@ -72,7 +74,8 @@ test('an adopted player can change password with adoption hidden', async () => { const page = accountPage(); page.replies.push(response(200, {name: 'Alice', visitor: false, adopted: true})); - await page.open(); + await page.load(); + page.open(); assert.equal(page.element('#claim-button').hidden, true); assert.equal(page.element('#password-button').hidden, false); @@ -169,25 +172,47 @@ test('network failure reports a retryable error and preserves a pending takeover }); for (const reply of [response(401, 'Reconnect to continue.'), new Error('Offline')]) { - test('an unavailable account lookup leaves its error visible and controls disabled', async () => { + test('an unavailable account lookup leaves Create and Log in usable', async () => { const page = accountPage(); page.element('#account-form').hidden = true; page.replies.push(reply); - await page.open(); + await page.load(); + page.open(); assert.equal(page.element('#account-panel').hidden, false); assert.equal(page.element('#account-form').hidden, true); - assert.equal(page.element('#account-choices').disabled, true); + assert.equal(page.element('#account-choices').disabled, false); assert(page.element('#account-error').textContent.length > 0); assert.deepEqual(page.reloads, []); }); } +test('Options opens immediately during loading and reuses identity on every opening', async () => { + const page = accountPage(); + let finish; + page.replies.push(new Promise(resolve => { finish = resolve; })); + const loading = page.load(); + + page.open(); + assert.equal(page.element('#account-choices').disabled, false); + page.choose('login'); + assert.equal(page.element('#account-form').hidden, false); + finish(response(200, {name: 'Alice', visitor: false, adopted: true})); + await loading; + page.open(); + page.open(); + + assert.equal(page.requests.length, 1); + assert.equal(page.element('#password-button').hidden, false); + assert.equal(page.element('#account-choices').disabled, false); +}); + test('Create launches the native creator without submitting account fields', async () => { const page = accountPage(); page.replies.push(response(200, {name: 'Lupeza', visitor: true})); - await page.open(); + await page.load(); + page.open(); page.choose('create'); diff --git a/client/tests/browser_controls.mjs b/client/tests/browser_controls.mjs @@ -81,6 +81,7 @@ function page({navigator = {userAgent: 'Mozilla/5.0 (Android) Gecko Firefox/149. }; context.Module._browser_input_character = character => characters.push(character); context.Module.finishCreation = name => creationNames.push(name); + context.Module.loadAccount = () => {}; context.Module._browser_input_motion = (x, y) => mouse.push(['mousemove', x, y, 0]); context.Module._browser_input_button = (button, down, x, y) => mouse.push([down ? 'mousedown' : 'mouseup', x, y, button === 3 ? 2 : 0]); context.Module._browser_input_wheel = (x, y, vertical) => wheels.push([x, y, vertical]); diff --git a/client/tests/browser_loading.mjs b/client/tests/browser_loading.mjs @@ -32,6 +32,7 @@ function fixture(response) { const script = html.match(/<script>([\s\S]*?)<\/script>/)[1] .replace('__WASM_DOWNLOAD_MB__', '11.57').replace('__WASM_DECODED_BYTES__', '65549'); vm.runInContext(script, context); + context.Module.loadAccount = () => {}; return {context, progress, loading, downloadProgress, percentages, widths}; } @@ -126,6 +127,8 @@ async function reportsUnavailableWebGLOnBothThreadsBeforeDownloading() { async function startsWithMainThreadGraphicsWithoutOffscreenCanvas(creating) { const test = fixture(); + let accountLoads = 0; + test.context.Module.loadAccount = () => { ++accountLoads; }; test.context.location.href = 'http://localhost/?profile=1' + (creating ? '&create=1' : ''); let restoredURL; test.context.history.replaceState = (state, title, url) => { restoredURL = String(url); }; @@ -157,6 +160,7 @@ async function startsWithMainThreadGraphicsWithoutOffscreenCanvas(creating) { await test.context.startGame(); assert.deepEqual(scripts, ['blob:client']); + assert.equal(accountLoads, 1); assert.equal(await clientScript.text(), 'client code'); assert.equal(clientScript.type, 'text/javascript'); assert.equal(canvas.transferControlToOffscreen, undefined); diff --git a/docs/browser-accounts.md b/docs/browser-accounts.md @@ -21,10 +21,28 @@ connections and does not reload the page. Visitors cannot change passwords. Credentials appear only after choosing a flow; Back clears them. Creation opens the original in-game breed, appearance, profession and naming scenes, followed by faction selection in Arrival Hall. Native creation initially uses -the browser cookie; Save this character enables name/password login. +the browser cookie and collects confirmed name/password credentials at its naming +step. Completing creation enables name/password login immediately. A successful login loads that character; a failed submission leaves the current player usable. +Account information loads once after browser launch and again when the native +creator finishes. Opening Options uses those values without making a request or +disabling Create and Log in. The account endpoint reads committed identity and +password status directly from SQLite without acquiring the simulation mutex. +Credential changes remain atomic, and revoked browser cookies cannot read the +previous account's information. + +`tests/e2e/options.test.mjs` holds the initial lookup pending while opening Options +and using Log in, then verifies that reopening makes no new request. A server +regression holds the simulation mutex while requesting authenticated account +information. Local measurements for this fix found 1.1-3.3 ms authenticated HTTP +responses with the native client running; the SQLite lookup on the live database +was below 0.02 ms. Earlier unauthenticated requests waited up to 5.6 seconds on +the simulation mutex before reaching any query. The separate long simulation +critical section was not reproduced after restarting for CPU/mutex profiling +and remains an open TODO. + ## Source and publication Maintain the account UI in `client/browser/index.html`. The page target in diff --git a/server/browser_account.go b/server/browser_account.go @@ -20,29 +20,32 @@ func (server *server) setBrowserCookie(w http.ResponseWriter, r *http.Request, t func (server *server) browserAccountInfo(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") - server.mutex.Lock() - player := server.browserCharacter_locked(r) - if player == nil { - server.mutex.Unlock() + cookie, err := r.Cookie("ao_client") + if err != nil { http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized) return } db, err := server.database() if err != nil { - server.mutex.Unlock() http.Error(w, err.Error(), http.StatusInternalServerError) return } + + // Account identity and credentials commit atomically; reading them needs no simulation lock. + credential := fmt.Sprintf("%x", sha256.Sum256([]byte(cookie.Value))) + var name string var claimed bool - if err := db.QueryRow("SELECT length(password_hash)>0 FROM characters WHERE id=?", player.id).Scan(&claimed); err != nil { - server.mutex.Unlock() + err = db.QueryRow("SELECT name, length(password_hash)>0 FROM characters WHERE id<1000000 AND browser_token_hash=?", credential).Scan(&name, &claimed) + if err == sql.ErrNoRows { + http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized) + return + } + if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } - name, visitor := player.name, !claimed - server.mutex.Unlock() w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{"name": name, "visitor": visitor, "adopted": claimed}) + json.NewEncoder(w).Encode(map[string]any{"name": name, "visitor": !claimed, "adopted": claimed}) } func (server *server) browserPassword(password string, salt []byte) []byte { diff --git a/server/browser_account_info_test.go b/server/browser_account_info_test.go @@ -0,0 +1,74 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestBrowserAccountInfoDoesNotWaitForSimulation(t *testing.T) { + world := newTestServer(t) + cookie := accountVisitor(t, world) + name := world.characters[1].name + request := httptest.NewRequest("GET", "/browser-account", nil) + request.AddCookie(cookie) + response := httptest.NewRecorder() + done := make(chan struct{}) + + // A busy simulation must not block a read of committed account information. + world.mutex.Lock() + go func() { + world.httpHandler().ServeHTTP(response, request) + close(done) + }() + completed := false + select { + case <-done: + completed = true + case <-time.After(time.Second): + } + world.mutex.Unlock() + <-done + + if !completed { + t.Fatal("account information waited for the simulation lock") + } + var account map[string]any + if err := json.Unmarshal(response.Body.Bytes(), &account); err != nil { + t.Fatal(err) + } + if response.Code != http.StatusOK || account["name"] != name || account["visitor"] != true || account["adopted"] != false { + t.Fatal("incorrect committed account information", response.Code, account) + } +} + +func TestBrowserAccountInfoRejectsRevokedCookie(t *testing.T) { + world := newTestServer(t) + cookie := accountVisitor(t, world) + claimed := accountRequest(world, cookie, "claim", "Alice", "secret") + if claimed.Code != http.StatusNoContent { + t.Fatal(claimed.Body.String()) + } + request := httptest.NewRequest("GET", "/browser-account", nil) + request.AddCookie(cookie) + response := httptest.NewRecorder() + + world.httpHandler().ServeHTTP(response, request) + + if response.Code != http.StatusUnauthorized { + t.Fatal("revoked cookie could read account details", response.Code) + } + request = httptest.NewRequest("GET", "/browser-account", nil) + request.AddCookie(claimed.Result().Cookies()[0]) + response = httptest.NewRecorder() + world.httpHandler().ServeHTTP(response, request) + var account map[string]any + if err := json.Unmarshal(response.Body.Bytes(), &account); err != nil { + t.Fatal(err) + } + if response.Code != http.StatusOK || account["name"] != "Alice" || account["adopted"] != true || account["visitor"] != false { + t.Fatal("new credential did not return committed account state", response.Code, account) + } +} diff --git a/tests/e2e/mobile-creation.test.mjs b/tests/e2e/mobile-creation.test.mjs @@ -128,6 +128,10 @@ test('mobile naming modal blocks native controls, survives refresh and preserves assert.equal(created.items.length, 4); const account = await context.request.get(fixture.url + '/browser-account'); assert.equal((await account.json()).adopted, true); + await page.locator('#menu-button').tap(); + await page.locator('#password-button').waitFor({state: 'visible'}); + assert.equal(await page.locator('#claim-button').isVisible(), false); + await page.keyboard.press('Escape'); await page.reload(); await game.ready(); assert.equal((await fixture.state(context)).id, created.id); diff --git a/tests/e2e/options.test.mjs b/tests/e2e/options.test.mjs @@ -0,0 +1,49 @@ +import assert from 'node:assert/strict'; +import {before, test} from 'node:test'; +import {buildServer, withFixture} from './fixture.mjs'; + +before(buildServer); + +test('Options opens without waiting for account information or fetching it again', +{timeout: 240_000}, async () => withFixture('options', async fixture => { + const context = await fixture.visitor(); + let release, requests = 0; + const held = new Promise(resolve => { release = resolve; }); + await context.route('**/browser-account', async route => { + ++requests; + await held; + await route.continue(); + }); + try { + const game = await fixture.game(context); + const page = game.page; + + // Keep the lookup pending while real browser input opens and uses Options. + await page.keyboard.press('Control+Alt+M'); + assert.equal(await page.locator('#create-button').isEnabled(), true); + assert.equal(await page.locator('#login-button').isEnabled(), true); + await page.locator('#login-button').click(); + assert.equal(await page.locator('#account-form').isVisible(), true); + await page.locator('#account-back').click(); + release(); + await page.locator('#claim-button').waitFor({state: 'visible'}); + await page.keyboard.press('Control+Alt+M'); + await page.keyboard.press('Control+Alt+M'); + assert.equal(await page.locator('#claim-button').isEnabled(), true); + assert.equal(requests, 1); + await game.save(fixture.output + '/instant-options'); + + // Measure the authenticated endpoint with the full native client running. + const milliseconds = []; + for (let index = 0; index < 10; ++index) { + const start = performance.now(); + const response = await context.request.get(fixture.url + '/browser-account'); + assert.equal(response.status(), 200); + milliseconds.push(performance.now() - start); + } + console.log('Authenticated account HTTP timings (ms): ' + milliseconds.map(value => value.toFixed(1)).join(', ')); + assert.deepEqual(game.errors, []); + } finally { + release(); + } +}));