fix(client): tile loading: centre-out, one request per tile, 404 recovery (#86)
The GM survey view asked row-major, at most 8 at a time, rebuilt the whole wanted window on every settle, and paid two requests for every failed tile (image error, then a fetch to learn the status). A 404/5xx was stored as permanent `denied`, so a tile imported after page load stayed black until a page reload, and `viewport.setScene` swallowed a same-id art_version change so the old textures were never dropped. - TILE_CONCURRENCY 8 -> 32, the measured knee on a Full HD scene (min-of-3 headless: GM fit + player 0.5, tile 32/64; 64 is inside the noise). - orderTilesCentreOut: nearest the viewport centre first. - Settle path is incremental (one settle = one tile sprite/flag update); the window is rebuilt only on camera/scene changes. - fetch + createImageBitmap: status from the same response, decode off the main thread, so a failure costs one request. - 403 stays permanent (retried only on fog.fresh); 404/5xx/network retry with 250/500 ms backoff up to 3 loads, and `hello`/reconnect or a scene/art_version change resets the budget. A failure that lands after a reconnect is a fresh first attempt; a failure that leaves the window does not spend the budget. - setScene emits for a same-id scene; a new art_version drops the texture cache and reschedules. Tiles are `Cache-Control: private, max-age=1y, immutable` (still gated), so a reload reuses them; DESIGN 3.3/11.1 and client/README updated. Tests: vitest for ordering, incremental invariants, retry budget/backoff, reconnect epoch and art_version invalidation; e2e for a GM survey fill (one request per succeeded tile) and a 404 tile recovering after the file appears and a real reconnect. Before -> after (min-of-3, saturated host, Full HD): GM fit 32px 910->843 ms, player 0.5 32px 972->862 ms, GM fit 64px 320->249 ms, player 0.5 64px 332->368 ms (noise). Part of #63. Blocks #77.
This commit is contained in:
+174
-5
@@ -6,10 +6,13 @@
|
||||
// the ~480 image callbacks; see client/README.md, gate (a)).
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import path from 'node:path'
|
||||
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
|
||||
import { openAs } from '../../tools/withserver.mjs'
|
||||
import { writeTileGrid } from '../../tools/tilefixture.mjs'
|
||||
import { openAs, startServer, stopServer } from '../../tools/withserver.mjs'
|
||||
import { writeTileGrid, writeTiles } from '../../tools/tilefixture.mjs'
|
||||
import { launchBrowser, signIn, waitForVisible, withStack } from './stack.mjs'
|
||||
import { probe } from './pixels.mjs'
|
||||
|
||||
const MOBILE = { viewport: { width: 412, height: 869 }, deviceScaleFactor: 2.625, isMobile: true, hasTouch: true }
|
||||
const SMALL = { viewport: { width: 160, height: 160 }, deviceScaleFactor: 1 }
|
||||
@@ -49,6 +52,23 @@ async function tileMap(stateDir, scene) {
|
||||
writeTileGrid(stateDir, { scene: scene.id, artVersion: scene.art_version, size: tile, x0: 40, x1: last - 40, y0: 40, y1: last - 40 })
|
||||
}
|
||||
|
||||
/** The importer owns w/h/tile_size (DESIGN 6.1); a harness writes the row before the server boots. */
|
||||
function setScene(stateDir, { w, h, tile }) {
|
||||
const db = path.join(stateDir, 'state.db')
|
||||
const sql = `UPDATE scene SET w=${w}, h=${h}, tile_size=${tile}, cell=${tile} WHERE id=1`
|
||||
const r = spawnSync('sqlite3', [db, sql], { encoding: 'utf8' })
|
||||
assert.equal(r.status, 0, `set scene: ${r.stderr}`)
|
||||
}
|
||||
|
||||
/** The fixture tile colour (tools/tilefixture.mjs `colourOf`), for a pixel probe. */
|
||||
function tileColour(x, y) {
|
||||
return { r: (x * 37 + y * 11) & 0xff, g: (x * 17 + y * 53) & 0xff, b: (x * 97 + y * 5) & 0xff }
|
||||
}
|
||||
|
||||
function nearColour(a, b, tolerance = 40) {
|
||||
return Math.abs(a.r - b.r) <= tolerance && Math.abs(a.g - b.g) <= tolerance && Math.abs(a.b - b.b) <= tolerance
|
||||
}
|
||||
|
||||
async function mobileContext(browser) {
|
||||
const context = await browser.newContext({ ignoreHTTPSErrors: true, ...MOBILE })
|
||||
const page = await context.newPage()
|
||||
@@ -298,12 +318,161 @@ test('a 403 is remembered: no retry loop, even when the viewport re-syncs', { ti
|
||||
await page.click('#grid-toggle')
|
||||
await sleep(2000)
|
||||
assert.equal(await requestsOf(page), first, 'no retry after a viewport re-sync')
|
||||
// One <img> attempt + one status fetch classify each denied tile; never more.
|
||||
assert.ok([...perUrl.values()].every(count => count <= 2),
|
||||
`a denied tile was retried: ${JSON.stringify([...perUrl].filter(([, count]) => count > 2))}`)
|
||||
// A denied tile costs exactly one request: the status comes from the fetch itself (#86).
|
||||
assert.ok([...perUrl.values()].every(count => count === 1),
|
||||
`a denied tile was requested more than once: ${JSON.stringify([...perUrl].filter(([, count]) => count !== 1))}`)
|
||||
await context.close()
|
||||
} finally {
|
||||
await browser.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// #86: a GM survey zoom asks for the whole map. The fill must be one request per tile (no
|
||||
// duplicate classification fetches), centre-out, and it must reach `ready`. Headless SwiftShader,
|
||||
// so the time is a host floor, not the phone budget; recorded, never gated tightly.
|
||||
test('GM survey zoom on a Full HD map fills one request per tile', { timeout: 120000 }, async () => {
|
||||
const W = 1920
|
||||
const H = 1080
|
||||
const TILE = 32
|
||||
await withStack(
|
||||
async ({ origin, gmKey }) => {
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1000, height: 700 } })
|
||||
const page = await context.newPage()
|
||||
const perUrl = new Map()
|
||||
const transient = new Set()
|
||||
page.on('request', request => {
|
||||
const p = new URL(request.url()).pathname
|
||||
if (p.startsWith('/tiles/')) perUrl.set(p, (perUrl.get(p) ?? 0) + 1)
|
||||
})
|
||||
page.on('response', response => {
|
||||
const p = new URL(response.url()).pathname
|
||||
if (p.startsWith('/tiles/') && response.status() !== 200 && response.status() !== 403) transient.add(p)
|
||||
})
|
||||
await page.goto(`${origin}/`)
|
||||
await waitForVisible(page, '#signin')
|
||||
await signIn(page, gmKey)
|
||||
await waitForVisible(page, canvas)
|
||||
await waitTilesReady(page)
|
||||
const before = await requestsOf(page)
|
||||
|
||||
// Fit: zoom = min(1000/1920, 700/1080); one wheel is enough (delta -> exp factor).
|
||||
const fit = Math.min(1000 / W, 700 / H)
|
||||
await page.mouse.move(500, 350)
|
||||
const startedAt = Date.now()
|
||||
await page.mouse.wheel(0, Math.log(1 / fit) / 0.0015)
|
||||
await page.waitForFunction(
|
||||
() => {
|
||||
const data = document.querySelector('#stage canvas')?.dataset ?? {}
|
||||
return Number(data.zoom ?? 1) < 0.53 && Number(data.visibleTiles ?? 0) > 1900 && data.tiles === 'ready'
|
||||
},
|
||||
null,
|
||||
{ timeout: 60000, polling: 50 },
|
||||
)
|
||||
const fillMs = Date.now() - startedAt
|
||||
const visible = await page.evaluate(() =>
|
||||
Number(document.querySelector('#stage canvas')?.dataset.visibleTiles ?? 0))
|
||||
const requests = await requestsOf(page)
|
||||
console.log(`#86 GM survey fill: ${fillMs} ms, ${visible} tiles, ${requests} requests (before ${before})`)
|
||||
assert.equal(visible, (W / TILE) * Math.ceil(H / TILE), 'the whole Full HD map at this zoom')
|
||||
assert.ok(perUrl.size >= visible, `every wanted tile was asked for: ${perUrl.size} of ${visible}`)
|
||||
// No tile that answered 200 cost a second request (the old path re-asked on every image
|
||||
// error to learn its status). A genuinely failed tile may retry.
|
||||
const duplicated = [...perUrl].filter(([url, count]) => count > 1 && !transient.has(url))
|
||||
assert.deepEqual(duplicated, [], 'one request per tile that succeeded')
|
||||
assert.ok(fillMs < 30000, `the survey fill reached ready in ${fillMs} ms`)
|
||||
await context.close()
|
||||
} finally {
|
||||
await browser.close()
|
||||
}
|
||||
},
|
||||
{
|
||||
prepare: stateDir => {
|
||||
setScene(stateDir, { w: W, h: H, tile: TILE })
|
||||
writeTileGrid(stateDir, {
|
||||
scene: 1, artVersion: 1, size: TILE, x0: 0, x1: W / TILE - 1, y0: 0, y1: Math.ceil(H / TILE) - 1,
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
// #86: a tile that 404s (art imported after the page loaded) is retried a bounded number of times,
|
||||
// and a reconnect retries it after the file appears. Before, the void was permanent until reload.
|
||||
test('a 404 tile is retried with a budget and recovers on reconnect', { timeout: 120000 }, async () => {
|
||||
const W = 1920
|
||||
const H = 1080
|
||||
const TILE = 32
|
||||
const MISSING = [Math.floor(W / 2 / TILE), Math.floor(H / 2 / TILE)]
|
||||
const missingUrl = `/tiles/1/v1/${MISSING[0]}_${MISSING[1]}.png`
|
||||
await withStack(
|
||||
async ({ origin, gmKey, stateDir, server }) => {
|
||||
const browser = await launchBrowser()
|
||||
let restarted = null
|
||||
try {
|
||||
const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1000, height: 700 } })
|
||||
const page = await context.newPage()
|
||||
let missingRequests = 0
|
||||
page.on('request', request => {
|
||||
if (new URL(request.url()).pathname === missingUrl) missingRequests += 1
|
||||
})
|
||||
await page.goto(`${origin}/`)
|
||||
await waitForVisible(page, '#signin')
|
||||
await signIn(page, gmKey)
|
||||
await waitForVisible(page, canvas)
|
||||
await waitTilesReady(page)
|
||||
|
||||
// The first pass spends its whole budget (3 loads), not 2 requests per load.
|
||||
for (let i = 0; i < 100 && missingRequests < 3; i++) await sleep(100)
|
||||
assert.equal(missingRequests, 3, 'three bounded loads, one request each')
|
||||
|
||||
const camera = await page.evaluate(() =>
|
||||
(document.querySelector('#stage canvas')?.dataset.camera ?? '0,0').split(',').map(Number))
|
||||
const zoom = Number(await zoomOf(page))
|
||||
const at = [(MISSING[0] + 0.5) * TILE * zoom + camera[0], (MISSING[1] + 0.5) * TILE * zoom + camera[1]]
|
||||
const blank = await probe(page, at[0], at[1])
|
||||
assert.ok(!nearColour(blank, tileColour(MISSING[0], MISSING[1])),
|
||||
`the missing tile is not painted yet: ${JSON.stringify(blank)}`)
|
||||
|
||||
// The art arrives, then a reconnect (a real socket close and a fresh `hello`) gives the
|
||||
// stored failure another chance. A server restart on the same port is the honest trigger:
|
||||
// CDP "offline" does not necessarily close an established WebSocket.
|
||||
writeTiles(stateDir, { scene: 1, artVersion: 1, size: TILE, tiles: [MISSING] })
|
||||
await stopServer(server)
|
||||
restarted = await startServer({ stateDir, port: server.port, publicOrigin: origin })
|
||||
// The badge may flip through `reconnecting` faster than a poll sees it; `connected` after a
|
||||
// real socket close is the hello that matters.
|
||||
await page.locator('#badge[data-state="reconnecting"]').waitFor({ state: 'visible', timeout: 20000 })
|
||||
.catch(() => {})
|
||||
await page.locator('#badge[data-state="connected"]').waitFor({ state: 'visible', timeout: 30000 })
|
||||
|
||||
let painted = null
|
||||
for (let i = 0; i < 100; i++) {
|
||||
painted = await probe(page, at[0], at[1])
|
||||
if (nearColour(painted, tileColour(MISSING[0], MISSING[1]))) break
|
||||
await sleep(100)
|
||||
}
|
||||
assert.ok(missingRequests >= 4, `the reconnect re-asked for the failed tile: ${missingRequests}`)
|
||||
assert.ok(nearColour(painted, tileColour(MISSING[0], MISSING[1])),
|
||||
`the recovered tile is painted: ${JSON.stringify(painted)}`)
|
||||
await context.close()
|
||||
} finally {
|
||||
if (restarted) await stopServer(restarted)
|
||||
await browser.close()
|
||||
}
|
||||
},
|
||||
{
|
||||
prepare: stateDir => {
|
||||
setScene(stateDir, { w: W, h: H, tile: TILE })
|
||||
const tiles = []
|
||||
for (let y = 0; y <= Math.ceil(H / TILE) - 1; y++) for (let x = 10; x <= 50; x++) {
|
||||
if (x === MISSING[0] && y === MISSING[1]) continue
|
||||
tiles.push([x, y])
|
||||
}
|
||||
writeTiles(stateDir, { scene: 1, artVersion: 1, size: TILE, tiles })
|
||||
},
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user