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:
+20
-16
@@ -129,22 +129,26 @@ change them only if a slice needs a new *core* event, and say so in the PR.
|
|||||||
and `data-view` (viewport px).
|
and `data-view` (viewport px).
|
||||||
- **Tiles** (`src/tiles.ts` scheduler + `src/render/modules/tiles.ts` layer): the wanted set is
|
- **Tiles** (`src/tiles.ts` scheduler + `src/render/modules/tiles.ts` layer): the wanted set is
|
||||||
`visibleTiles()` — every tile intersecting the viewport plus exactly one tile of margin, clamped
|
`visibleTiles()` — every tile intersecting the viewport plus exactly one tile of margin, clamped
|
||||||
to the scene, in viewport order (row-major). The scheduler keeps at most `TILE_CONCURRENCY` (8)
|
to the scene — ordered centre-out (`orderTilesCentreOut`), so a survey fill grows from what the
|
||||||
loads in flight, drops queued tiles that leave the window, never asks twice for a tile, and
|
eye is on instead of the top-left corner. The scheduler keeps at most `TILE_CONCURRENCY` (32,
|
||||||
remembers a `403`/`404` as `denied` forever: the gate has said "not yours", so it is never retried
|
the measured knee on a Full HD scene) loads in flight, drops queued tiles that leave the window,
|
||||||
in a loop. A transient failure is retried only on a new window or after a reconnect (`hello`).
|
never asks twice for a tile, and remembers a `403` as `denied`: the gate has said "not yours", so
|
||||||
The decoded-texture cache is module-level and keyed by URL, so a reconnect keeps every tile and
|
it is not retried in a loop (it is asked once more when `fog.fresh` says its cells were explored).
|
||||||
the page makes no new tile request. `data-tiles` is `ready` once the current pass is complete:
|
A `404`/`5xx`/network failure is transient: up to 3 loads with 250/500 ms backoff, and a
|
||||||
every wanted tile has a terminal answer (`ok`, `denied`, or a stored transient `error` that waits
|
reconnect (`hello`) or a scene/`art_version` change resets the budget and re-asks. The settle path
|
||||||
for a new window or a reconnect). A transient `error` is deliberately not pending, otherwise one
|
is incremental (one settle = one tile), so filling tens of thousands of tiles is not quadratic.
|
||||||
host hiccup would hold the flag at `loading` and hang every e2e readiness wait; the hole it leaves
|
The decoded-texture cache is module-level and keyed by URL, so a reconnect keeps every tile; a new
|
||||||
fills on the next window or reconnect. `data-tile-requests` counts image attempts (plus the single
|
`art_version` changes every URL, so it drops the cache and refetches. `data-tiles` is `ready` once
|
||||||
status fetch used to classify an image error); `data-tile-distinct` counts the distinct tile URLs
|
the current pass is complete: every wanted tile has a terminal answer (`ok`, `denied`, or a
|
||||||
fetched, so the #70 re-ask of a tile whose 403 became allowed shows in the former, not the latter.
|
stored transient `error` that waits for a retry, a new window or a reconnect). A transient
|
||||||
- **Why `<img>` and not `fetch` + `createImageBitmap`:** the browser's image loader does the
|
`error` is deliberately not pending, otherwise one host hiccup would hold the flag at `loading`
|
||||||
fetch/decode off the JS hot path; one `onload` per tile is the cheapest way to put the ~480 tiles
|
and hang every e2e readiness wait. `data-tile-requests` counts fetches; `data-tile-distinct`
|
||||||
of a phone viewport on the GPU. A failed image is classified once with `fetch`, which is where the
|
counts the distinct tile URLs fetched, so the #70 re-ask of a tile whose 403 became allowed shows
|
||||||
`403` distinction comes from.
|
in the former, not the latter.
|
||||||
|
- **One request per tile:** `fetch` then `createImageBitmap` (decode off the main thread). An
|
||||||
|
`<img>` error carries no status, so classifying it cost a second `fetch` for *every* failure; the
|
||||||
|
fetch-first path gets 403 vs 404/5xx from the same response and lets the scheduler retry a
|
||||||
|
missing tile instead of leaving a permanent hole.
|
||||||
- **Grid** (`src/render/modules/grid.ts`): one `TilingSprite` over a `grid_size` cell texture, drawn
|
- **Grid** (`src/render/modules/grid.ts`): one `TilingSprite` over a `grid_size` cell texture, drawn
|
||||||
once, toggled by `#grid-toggle` (story 18). No per-frame redraw.
|
once, toggled by `#grid-toggle` (story 18). No per-frame redraw.
|
||||||
- **Tile-size gate (a)** (`client/e2e/map.test.mjs`): mobile emulation 412×869 CSS px, DPR 2.625,
|
- **Tile-size gate (a)** (`client/e2e/map.test.mjs`): mobile emulation 412×869 CSS px, DPR 2.625,
|
||||||
|
|||||||
+174
-5
@@ -6,10 +6,13 @@
|
|||||||
// the ~480 image callbacks; see client/README.md, gate (a)).
|
// the ~480 image callbacks; see client/README.md, gate (a)).
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
import assert from 'node:assert/strict'
|
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 { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
|
||||||
import { openAs } from '../../tools/withserver.mjs'
|
import { openAs, startServer, stopServer } from '../../tools/withserver.mjs'
|
||||||
import { writeTileGrid } from '../../tools/tilefixture.mjs'
|
import { writeTileGrid, writeTiles } from '../../tools/tilefixture.mjs'
|
||||||
import { launchBrowser, signIn, waitForVisible, withStack } from './stack.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 MOBILE = { viewport: { width: 412, height: 869 }, deviceScaleFactor: 2.625, isMobile: true, hasTouch: true }
|
||||||
const SMALL = { viewport: { width: 160, height: 160 }, deviceScaleFactor: 1 }
|
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 })
|
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) {
|
async function mobileContext(browser) {
|
||||||
const context = await browser.newContext({ ignoreHTTPSErrors: true, ...MOBILE })
|
const context = await browser.newContext({ ignoreHTTPSErrors: true, ...MOBILE })
|
||||||
const page = await context.newPage()
|
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 page.click('#grid-toggle')
|
||||||
await sleep(2000)
|
await sleep(2000)
|
||||||
assert.equal(await requestsOf(page), first, 'no retry after a viewport re-sync')
|
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.
|
// A denied tile costs exactly one request: the status comes from the fetch itself (#86).
|
||||||
assert.ok([...perUrl.values()].every(count => count <= 2),
|
assert.ok([...perUrl.values()].every(count => count === 1),
|
||||||
`a denied tile was retried: ${JSON.stringify([...perUrl].filter(([, count]) => count > 2))}`)
|
`a denied tile was requested more than once: ${JSON.stringify([...perUrl].filter(([, count]) => count !== 1))}`)
|
||||||
await context.close()
|
await context.close()
|
||||||
} finally {
|
} finally {
|
||||||
await browser.close()
|
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 })
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,11 +1,19 @@
|
|||||||
// The tile layer (story 13/14/19, DESIGN 7.1 layer 1, spec #63 decision 12).
|
// The tile layer (story 13/14/19, DESIGN 7.1 layer 1, spec #63 decision 12; #86 tile loading).
|
||||||
|
//
|
||||||
|
// Only the viewport plus one tile of margin is requested, nearest the viewport centre first,
|
||||||
|
// through the TileScheduler's queue. The decoded textures live in a module-level cache keyed by
|
||||||
|
// URL, so a reconnect (which keeps the stage and only resets the reducer slices) never refetches a
|
||||||
|
// tile; a new `art_version` changes every URL, so its textures are dropped and refetched.
|
||||||
//
|
//
|
||||||
// Only the viewport plus one tile of margin is requested, in viewport order, through the
|
|
||||||
// TileScheduler's 8-wide queue. The decoded textures live in a module-level cache keyed by URL, so
|
|
||||||
// a reconnect (which keeps the stage and only resets the reducer slices) never refetches a tile.
|
|
||||||
// A `403` from the server is the gate saying "not yours": it is remembered as denied and never
|
// A `403` from the server is the gate saying "not yours": it is remembered as denied and never
|
||||||
// retried *while its cells stay unexplored*. When the fog slice reports newly explored cells (#70)
|
// retried *while its cells stay unexplored*. When the fog slice reports newly explored cells (#70)
|
||||||
// the gate's answer for those tiles changed, so exactly those denied tiles are asked once more.
|
// the gate's answer for those tiles changed, so exactly those denied tiles are asked once more.
|
||||||
|
// A `404`/`5xx`/network failure is transient: the scheduler retries it a bounded number of times
|
||||||
|
// with backoff, and a reconnect retries every stored failure once more.
|
||||||
|
//
|
||||||
|
// The settle path is incremental: a tile that arrives only creates its sprite (or nothing, if the
|
||||||
|
// window moved on) and updates the readiness flag. Rebuilding the whole wanted list on every
|
||||||
|
// settle was O(window) per tile — tens of thousands squared while a GM survey view fills.
|
||||||
//
|
//
|
||||||
// The e2e contract on the canvas: `data-tiles` (`loading`/`ready`/`idle`) and
|
// The e2e contract on the canvas: `data-tiles` (`loading`/`ready`/`idle`) and
|
||||||
// `data-tile-requests` (how many fetches this page ever made) and `data-tile-distinct` (how many
|
// `data-tile-requests` (how many fetches this page ever made) and `data-tile-distinct` (how many
|
||||||
@@ -17,8 +25,9 @@
|
|||||||
|
|
||||||
import { Sprite, Texture } from 'pixi.js'
|
import { Sprite, Texture } from 'pixi.js'
|
||||||
import type { RenderModule } from '../stage.ts'
|
import type { RenderModule } from '../stage.ts'
|
||||||
import { viewport, visibleTiles } from '../../viewport.ts'
|
import { viewport, visibleTiles, orderTilesCentreOut } from '../../viewport.ts'
|
||||||
import { TileScheduler, tilesForCells } from '../../tiles.ts'
|
import type { VisibleTile } from '../../viewport.ts'
|
||||||
|
import { TileScheduler, tilesForCells, tilesInvalidated } from '../../tiles.ts'
|
||||||
import type { TileLoadResult } from '../../tiles.ts'
|
import type { TileLoadResult } from '../../tiles.ts'
|
||||||
import { fogOf } from '../../slices/fog.ts'
|
import { fogOf } from '../../slices/fog.ts'
|
||||||
|
|
||||||
@@ -30,44 +39,46 @@ let requests = 0
|
|||||||
* `requests` may exceed this; a duplicate *tile* would not. */
|
* `requests` may exceed this; a duplicate *tile* would not. */
|
||||||
const requestedUrls = new Set<string>()
|
const requestedUrls = new Set<string>()
|
||||||
|
|
||||||
function loadImage(src: string): Promise<HTMLImageElement> {
|
/**
|
||||||
return new Promise((resolve, reject) => {
|
* One request per tile. `fetch` is used instead of an `<img>` because an image error carries no
|
||||||
const image = new Image()
|
* status: asking again with `fetch` to tell 403 from 404 doubled the cost of *every* failure. The
|
||||||
image.onload = () => resolve(image)
|
* response is decoded off the main thread by `createImageBitmap`, so the JS path never holds the
|
||||||
image.onerror = () => reject(new Error(`tile image failed: ${src}`))
|
* image bytes.
|
||||||
image.src = src
|
*/
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchTile(url: string): Promise<TileLoadResult> {
|
async function fetchTile(url: string): Promise<TileLoadResult> {
|
||||||
requests += 1
|
requests += 1
|
||||||
requestedUrls.add(url)
|
requestedUrls.add(url)
|
||||||
|
let response: Response
|
||||||
try {
|
try {
|
||||||
// The browser's own image loader fetches and decodes off the JS path; one `onload` per tile is
|
response = await fetch(url, { credentials: 'same-origin' })
|
||||||
// the cheapest way to get 480 phone-viewport tiles onto the GPU. The response body is not
|
} catch {
|
||||||
// needed here, so no `fetch`, no blob and no `createImageBitmap` in the hot path.
|
return 'error'
|
||||||
const image = await loadImage(url)
|
}
|
||||||
textureCache.set(url, Texture.from(image))
|
if (response.status === 403) return 'denied'
|
||||||
|
if (!response.ok) return 'error'
|
||||||
|
try {
|
||||||
|
const bitmap = await createImageBitmap(await response.blob())
|
||||||
|
textureCache.set(url, Texture.from(bitmap))
|
||||||
return 'ok'
|
return 'ok'
|
||||||
} catch {
|
} catch {
|
||||||
// An <img> error has no status. Ask the gate once: 403/404 is a permanent "not yours" and is
|
return 'error'
|
||||||
// never retried; everything else is transient and may be retried after a reconnect.
|
|
||||||
try {
|
|
||||||
requests += 1
|
|
||||||
const response = await fetch(url, { credentials: 'same-origin' })
|
|
||||||
if (response.status === 403 || response.status === 404) return 'denied'
|
|
||||||
return 'error'
|
|
||||||
} catch {
|
|
||||||
return 'error'
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function clearTextureCache(): void {
|
||||||
|
for (const texture of textureCache.values()) texture.destroy(true)
|
||||||
|
textureCache.clear()
|
||||||
|
}
|
||||||
|
|
||||||
export const renderModule: RenderModule = {
|
export const renderModule: RenderModule = {
|
||||||
name: 'tiles',
|
name: 'tiles',
|
||||||
mount({ app, layers, store }) {
|
mount({ app, layers, store }) {
|
||||||
const canvas = app.canvas
|
const canvas = app.canvas
|
||||||
const sprites = new Map<string, Sprite>()
|
const sprites = new Map<string, Sprite>()
|
||||||
|
/** The current window: url -> tile, so a settle can place its sprite without a rebuild. */
|
||||||
|
let wanted = new Map<string, VisibleTile>()
|
||||||
|
/** Wanted urls that have not settled yet this pass; `ready` is `pending.size === 0`. */
|
||||||
|
let pending = new Set<string>()
|
||||||
let frame = 0
|
let frame = 0
|
||||||
|
|
||||||
canvas.dataset['tileRequests'] = String(requests)
|
canvas.dataset['tileRequests'] = String(requests)
|
||||||
@@ -75,7 +86,7 @@ export const renderModule: RenderModule = {
|
|||||||
|
|
||||||
const scheduler = new TileScheduler({
|
const scheduler = new TileScheduler({
|
||||||
load: fetchTile,
|
load: fetchTile,
|
||||||
onSettled: () => scheduleSync(),
|
onSettled: settle,
|
||||||
})
|
})
|
||||||
|
|
||||||
function scheduleSync(): void {
|
function scheduleSync(): void {
|
||||||
@@ -86,48 +97,76 @@ export const renderModule: RenderModule = {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function setTilesFlag(): void {
|
||||||
|
canvas.dataset['tiles'] = wanted.size === 0 ? 'idle' : pending.size > 0 ? 'loading' : 'ready'
|
||||||
|
canvas.dataset['tileRequests'] = String(requests)
|
||||||
|
canvas.dataset['tileDistinct'] = String(requestedUrls.size)
|
||||||
|
canvas.dataset['visibleTiles'] = String(wanted.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
function addSprite(tile: VisibleTile, texture: Texture, tileSize: number): void {
|
||||||
|
const sprite = new Sprite(texture)
|
||||||
|
sprite.position.set(tile.x * tileSize, tile.y * tileSize)
|
||||||
|
sprite.width = tileSize
|
||||||
|
sprite.height = tileSize
|
||||||
|
layers.tiles.addChild(sprite)
|
||||||
|
sprites.set(tile.url, sprite)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A tile settled: touch only that tile. Runs once per request, not once per window. */
|
||||||
|
function settle(url: string, result: TileLoadResult): void {
|
||||||
|
if (result === 'ok') {
|
||||||
|
const tile = wanted.get(url)
|
||||||
|
const texture = textureCache.get(url)
|
||||||
|
const scene = viewport.state.scene
|
||||||
|
if (tile && texture && scene && !sprites.has(url)) addSprite(tile, texture, scene.tile_size)
|
||||||
|
}
|
||||||
|
pending.delete(url)
|
||||||
|
setTilesFlag()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The viewport changed (pan/zoom/resize/reconnect): rebuild the window and diff it. */
|
||||||
function sync(): void {
|
function sync(): void {
|
||||||
const { scene, camera, size } = viewport.state
|
const { scene, camera, size } = viewport.state
|
||||||
if (!scene) {
|
if (!scene) {
|
||||||
|
for (const sprite of sprites.values()) sprite.destroy()
|
||||||
|
sprites.clear()
|
||||||
|
wanted = new Map()
|
||||||
|
pending = new Set()
|
||||||
canvas.dataset['tiles'] = 'idle'
|
canvas.dataset['tiles'] = 'idle'
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const wanted = visibleTiles(scene, camera, size)
|
const visible = orderTilesCentreOut(visibleTiles(scene, camera, size), scene, camera, size)
|
||||||
const wantedUrls = new Set(wanted.map(tile => tile.url))
|
const next = new Map(visible.map(tile => [tile.url, tile]))
|
||||||
|
|
||||||
for (const [url, sprite] of sprites) {
|
for (const [url, sprite] of sprites) {
|
||||||
if (wantedUrls.has(url)) continue
|
if (next.has(url)) continue
|
||||||
|
// Left the window (possibly before its bytes arrived): drop it, and let the scheduler
|
||||||
|
// cancel it if it was only queued.
|
||||||
sprite.destroy()
|
sprite.destroy()
|
||||||
sprites.delete(url)
|
sprites.delete(url)
|
||||||
}
|
}
|
||||||
|
|
||||||
const tileSize = scene.tile_size
|
for (const tile of visible) {
|
||||||
for (const tile of wanted) {
|
|
||||||
const texture = textureCache.get(tile.url)
|
const texture = textureCache.get(tile.url)
|
||||||
if (texture) scheduler.markLoaded(tile.url)
|
if (!texture) continue
|
||||||
if (sprites.has(tile.url) || !texture) continue
|
scheduler.markLoaded(tile.url)
|
||||||
const sprite = new Sprite(texture)
|
if (!sprites.has(tile.url)) addSprite(tile, texture, scene.tile_size)
|
||||||
sprite.position.set(tile.x * tileSize, tile.y * tileSize)
|
|
||||||
sprite.width = tileSize
|
|
||||||
sprite.height = tileSize
|
|
||||||
layers.tiles.addChild(sprite)
|
|
||||||
sprites.set(tile.url, sprite)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
scheduler.setDesired(wanted.map(tile => tile.url))
|
wanted = next
|
||||||
canvas.dataset['tileRequests'] = String(requests)
|
scheduler.setDesired(visible.map(tile => tile.url))
|
||||||
canvas.dataset['tileDistinct'] = String(requestedUrls.size)
|
pending = new Set()
|
||||||
canvas.dataset['visibleTiles'] = String(wanted.length)
|
for (const tile of visible) {
|
||||||
|
const status = scheduler.status(tile.url)
|
||||||
// `ready` means this pass is done, not that every tile painted: a transient `error` is
|
if (status === undefined || status === 'queued' || status === 'loading') pending.add(tile.url)
|
||||||
// retried only on a new window or a reconnect (README), so it must not hold the flag at
|
}
|
||||||
// `loading` for the rest of the session (a host hiccup would hang every e2e readiness wait).
|
setTilesFlag()
|
||||||
canvas.dataset['tiles'] =
|
|
||||||
wanted.length === 0 ? 'idle' : scheduler.isPending(wanted.map(tile => tile.url)) ? 'loading' : 'ready'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const unsubscribe = viewport.subscribe(scheduleSync)
|
const unsubscribe = viewport.subscribe(scheduleSync)
|
||||||
let lastExplored = -1
|
let lastExplored = -1
|
||||||
|
let lastScene: { id: number; art_version: number } | null = null
|
||||||
const unsubscribeStore = store.subscribe((state, event) => {
|
const unsubscribeStore = store.subscribe((state, event) => {
|
||||||
// Newly explored cells can flip a tile's `403` to an allowed tile (#70): retry exactly the
|
// Newly explored cells can flip a tile's `403` to an allowed tile (#70): retry exactly the
|
||||||
// denied tiles the new cells touch, once. An unexplored 403 stays denied (no retry loop).
|
// denied tiles the new cells touch, once. An unexplored 403 stays denied (no retry loop).
|
||||||
@@ -140,6 +179,23 @@ export const renderModule: RenderModule = {
|
|||||||
scheduleSync()
|
scheduleSync()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// New art is new URLs (`v<art_version>`), so every cached texture and scheduling decision is
|
||||||
|
// stale. Drop them and refetch the window. A same-version hello (reconnect) keeps the cache.
|
||||||
|
const scene = state.session.scene
|
||||||
|
if (scene) {
|
||||||
|
if (tilesInvalidated(lastScene, scene)) {
|
||||||
|
for (const sprite of sprites.values()) sprite.destroy()
|
||||||
|
sprites.clear()
|
||||||
|
clearTextureCache()
|
||||||
|
scheduler.reset()
|
||||||
|
}
|
||||||
|
lastScene = { id: scene.id, art_version: scene.art_version }
|
||||||
|
}
|
||||||
|
// (No branch for `scene === null`: a reconnect's `connecting` reset clears the session, and
|
||||||
|
// keeping the last known scene lets a re-import that happened during the reconnect still drop
|
||||||
|
// the old textures when the new `hello` lands.)
|
||||||
|
|
||||||
// A reconnect is the moment to give transient failures another chance; a 403 stays denied.
|
// A reconnect is the moment to give transient failures another chance; a 403 stays denied.
|
||||||
if (event.type === 'frame' && event.frame.t === 'hello') {
|
if (event.type === 'frame' && event.frame.t === 'hello') {
|
||||||
scheduler.retryFailed()
|
scheduler.retryFailed()
|
||||||
@@ -151,6 +207,7 @@ export const renderModule: RenderModule = {
|
|||||||
return () => {
|
return () => {
|
||||||
unsubscribe()
|
unsubscribe()
|
||||||
unsubscribeStore()
|
unsubscribeStore()
|
||||||
|
scheduler.dispose()
|
||||||
if (frame !== 0) cancelAnimationFrame(frame)
|
if (frame !== 0) cancelAnimationFrame(frame)
|
||||||
for (const sprite of sprites.values()) sprite.destroy()
|
for (const sprite of sprites.values()) sprite.destroy()
|
||||||
sprites.clear()
|
sprites.clear()
|
||||||
|
|||||||
+140
-21
@@ -1,31 +1,57 @@
|
|||||||
// The tile scheduler (#69, spec #63 decision 12). Pure: the loader is injected, so the concurrency,
|
// The tile scheduler (#69, spec #63 decision 12; #86 tile-loading). Pure: the loader is injected, so
|
||||||
// cache and denial rules are unit-tested without a browser or a GPU.
|
// the concurrency, cache and retry rules are unit-tested without a browser or a GPU.
|
||||||
//
|
//
|
||||||
// Rules encoded here:
|
// Rules encoded here:
|
||||||
// - at most TILE_CONCURRENCY (8) requests in flight;
|
// - at most TILE_CONCURRENCY requests in flight (measured knee: a browser decodes and uploads
|
||||||
// - the wanted list is the viewport plus one tile of margin, in viewport order;
|
// faster than one 8-wide queue can keep the server busy on a 16k map, see the issue);
|
||||||
|
// - the wanted list is the viewport plus one tile of margin, ordered by the caller (the renderer
|
||||||
|
// asks nearest the viewport centre first);
|
||||||
// - a tile is never fetched twice (a decoded texture is cached by the tile module across a
|
// - a tile is never fetched twice (a decoded texture is cached by the tile module across a
|
||||||
// reconnect; this scheduler remembers settled URLs too);
|
// reconnect; this scheduler remembers settled URLs too);
|
||||||
// - a `403`/`404` is a permanent `denied` answer: never retried in a loop (the server said no);
|
// - a `403` is a permanent `denied` answer: never retried in a loop (the server said no). It is
|
||||||
// - a transient `error` is retried only when a later viewport sync asks for the tile again;
|
// asked once more only when the fog says its cells just became explored (#70);
|
||||||
|
// - a `404`/`5xx`/network failure is transient: up to TILE_MAX_ATTEMPTS loads with exponential
|
||||||
|
// backoff, then a stored `error` that waits for a new window or a reconnect (`retryFailed`) —
|
||||||
|
// this fixes the black void a missing tile used to leave until a page reload;
|
||||||
// - queued tiles that leave the viewport before they start are dropped, so a fast pan never
|
// - queued tiles that leave the viewport before they start are dropped, so a fast pan never
|
||||||
// prefetches beyond the margin;
|
// prefetches beyond the margin.
|
||||||
// - a denied tile is asked again only when the fog says its cells just became explored (#70):
|
|
||||||
// the gate's answer changed, so the old "no" is stale.
|
|
||||||
|
|
||||||
import type { SceneInfo } from './protocol.ts'
|
import type { SceneInfo } from './protocol.ts'
|
||||||
import { tileUrl } from './viewport.ts'
|
import { tileUrl } from './viewport.ts'
|
||||||
|
|
||||||
export const TILE_CONCURRENCY = 8
|
/**
|
||||||
|
* Torrent of small tiles is bounded here, not by the server: the gate + nginx sustain ~2.5k
|
||||||
|
* requests/s, so a narrow client queue is the bottleneck on a survey view. Measured knee on a
|
||||||
|
* Full HD scene at GM fit / player 0.5 (min-of-3, headless SwiftShader): 8 -> 32 cuts the fill
|
||||||
|
* 11-29%; 64 is inside the noise and doubles browser decode pressure, so 32 is the cap.
|
||||||
|
*/
|
||||||
|
export const TILE_CONCURRENCY = 32
|
||||||
|
/** Total loads per URL (first try included) before a transient failure is stored as `error`. */
|
||||||
|
export const TILE_MAX_ATTEMPTS = 3
|
||||||
|
/** First retry delay; each following retry doubles it (250 ms, 500 ms). */
|
||||||
|
export const TILE_RETRY_BASE_MS = 250
|
||||||
|
|
||||||
export type TileLoadResult = 'ok' | 'denied' | 'error'
|
export type TileLoadResult = 'ok' | 'denied' | 'error'
|
||||||
export type TileStatus = 'queued' | 'loading' | 'ok' | 'denied' | 'error'
|
export type TileStatus = 'queued' | 'loading' | 'ok' | 'denied' | 'error'
|
||||||
|
|
||||||
|
export type RetryScheduler = (run: () => void, ms: number) => () => void
|
||||||
|
|
||||||
|
const setTimeoutRetry: RetryScheduler = (run, ms) => {
|
||||||
|
const timer = setTimeout(run, ms)
|
||||||
|
return () => clearTimeout(timer)
|
||||||
|
}
|
||||||
|
|
||||||
export interface TileSchedulerOptions {
|
export interface TileSchedulerOptions {
|
||||||
load(url: string): Promise<TileLoadResult>
|
load(url: string): Promise<TileLoadResult>
|
||||||
onSettled?(url: string, result: TileLoadResult): void
|
onSettled?(url: string, result: TileLoadResult): void
|
||||||
onIdle?(): void
|
onIdle?(): void
|
||||||
concurrency?: number
|
concurrency?: number
|
||||||
|
/** Bounded transient-failure retries (default TILE_MAX_ATTEMPTS, 3). */
|
||||||
|
maxAttempts?: number
|
||||||
|
/** First backoff in ms; doubles per attempt (default TILE_RETRY_BASE_MS). */
|
||||||
|
retryBaseMs?: number
|
||||||
|
/** Injectable timer, so tests drive backoff without wall-clock waits. */
|
||||||
|
scheduleRetry?: RetryScheduler
|
||||||
}
|
}
|
||||||
|
|
||||||
function sameList(a: readonly string[], b: readonly string[]): boolean {
|
function sameList(a: readonly string[], b: readonly string[]): boolean {
|
||||||
@@ -56,12 +82,32 @@ export function tilesForCells(
|
|||||||
return [...urls]
|
return [...urls]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when a new scene invalidates every cached tile URL: a different scene, or the same scene
|
||||||
|
* after a re-import (`art_version`). A first scene (no previous) has nothing to invalidate, and a
|
||||||
|
* reconnect to the same version must keep the decoded cache.
|
||||||
|
*/
|
||||||
|
export function tilesInvalidated(
|
||||||
|
previous: Pick<SceneInfo, 'id' | 'art_version'> | null,
|
||||||
|
next: Pick<SceneInfo, 'id' | 'art_version'> | null,
|
||||||
|
): boolean {
|
||||||
|
if (previous === null || next === null) return false
|
||||||
|
return previous.id !== next.id || previous.art_version !== next.art_version
|
||||||
|
}
|
||||||
|
|
||||||
export class TileScheduler {
|
export class TileScheduler {
|
||||||
readonly #load: (url: string) => Promise<TileLoadResult>
|
readonly #load: (url: string) => Promise<TileLoadResult>
|
||||||
readonly #onSettled: ((url: string, result: TileLoadResult) => void) | undefined
|
readonly #onSettled: ((url: string, result: TileLoadResult) => void) | undefined
|
||||||
readonly #onIdle: (() => void) | undefined
|
readonly #onIdle: (() => void) | undefined
|
||||||
readonly #concurrency: number
|
readonly #concurrency: number
|
||||||
|
readonly #maxAttempts: number
|
||||||
|
readonly #retryBaseMs: number
|
||||||
|
readonly #scheduleRetry: RetryScheduler
|
||||||
#states = new Map<string, TileStatus>()
|
#states = new Map<string, TileStatus>()
|
||||||
|
#attempts = new Map<string, number>()
|
||||||
|
#timers = new Map<string, () => void>()
|
||||||
|
/** Bumped by `retryFailed`/`reset`: a load that settles after it gets a fresh budget. */
|
||||||
|
#epoch = 0
|
||||||
#queue: string[] = []
|
#queue: string[] = []
|
||||||
#desired = new Set<string>()
|
#desired = new Set<string>()
|
||||||
#lastDesired: readonly string[] = []
|
#lastDesired: readonly string[] = []
|
||||||
@@ -73,6 +119,9 @@ export class TileScheduler {
|
|||||||
this.#onSettled = options.onSettled
|
this.#onSettled = options.onSettled
|
||||||
this.#onIdle = options.onIdle
|
this.#onIdle = options.onIdle
|
||||||
this.#concurrency = Math.max(1, options.concurrency ?? TILE_CONCURRENCY)
|
this.#concurrency = Math.max(1, options.concurrency ?? TILE_CONCURRENCY)
|
||||||
|
this.#maxAttempts = Math.max(1, options.maxAttempts ?? TILE_MAX_ATTEMPTS)
|
||||||
|
this.#retryBaseMs = Math.max(0, options.retryBaseMs ?? TILE_RETRY_BASE_MS)
|
||||||
|
this.#scheduleRetry = options.scheduleRetry ?? setTimeoutRetry
|
||||||
}
|
}
|
||||||
|
|
||||||
status(url: string): TileStatus | undefined {
|
status(url: string): TileStatus | undefined {
|
||||||
@@ -83,7 +132,7 @@ export class TileScheduler {
|
|||||||
return this.#active
|
return this.#active
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What the viewport wants now. `urls` is already in viewport order. */
|
/** What the viewport wants now. `urls` is already in the caller's order (centre-out). */
|
||||||
setDesired(urls: readonly string[]): void {
|
setDesired(urls: readonly string[]): void {
|
||||||
// A settle calls back into the renderer, which syncs again with the same window; skip the
|
// A settle calls back into the renderer, which syncs again with the same window; skip the
|
||||||
// O(n) rebuild in that common case. It still pumps, which is what opens the next slot.
|
// O(n) rebuild in that common case. It still pumps, which is what opens the next slot.
|
||||||
@@ -104,8 +153,13 @@ export class TileScheduler {
|
|||||||
.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0))
|
.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0))
|
||||||
for (const url of urls) {
|
for (const url of urls) {
|
||||||
const existing = this.#states.get(url)
|
const existing = this.#states.get(url)
|
||||||
if (existing === 'error') this.#states.delete(url)
|
if (existing === 'error') {
|
||||||
else if (existing !== undefined) continue
|
// A bounded retry that already used its attempts stays failed until `retryFailed()`; a
|
||||||
|
// fresh window must not hammer a tile the server keeps 404ing.
|
||||||
|
if ((this.#attempts.get(url) ?? 0) >= this.#maxAttempts) continue
|
||||||
|
this.#cancelRetry(url)
|
||||||
|
this.#states.delete(url)
|
||||||
|
} else if (existing !== undefined) continue
|
||||||
this.#states.set(url, 'queued')
|
this.#states.set(url, 'queued')
|
||||||
this.#queue.push(url)
|
this.#queue.push(url)
|
||||||
}
|
}
|
||||||
@@ -117,12 +171,43 @@ export class TileScheduler {
|
|||||||
if (!this.#states.has(url)) this.#states.set(url, 'ok')
|
if (!this.#states.has(url)) this.#states.set(url, 'ok')
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Forget transient failures: the next sync (e.g. after a reconnect) may ask again. */
|
/**
|
||||||
|
* Forget transient failures: the next sync (e.g. after a reconnect) may ask again. The attempt
|
||||||
|
* budget is reset too, so a reconnect gets the full bounded-retry allowance.
|
||||||
|
*/
|
||||||
retryFailed(): void {
|
retryFailed(): void {
|
||||||
for (const [url, status] of this.#states) if (status === 'error') this.#states.delete(url)
|
for (const cancel of this.#timers.values()) cancel()
|
||||||
|
this.#timers.clear()
|
||||||
|
this.#epoch += 1
|
||||||
|
for (const [url, status] of this.#states) {
|
||||||
|
if (status !== 'error') continue
|
||||||
|
this.#states.delete(url)
|
||||||
|
this.#attempts.delete(url)
|
||||||
|
}
|
||||||
this.#lastDesired = []
|
this.#lastDesired = []
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drop every cached decision and pending retry (a new `art_version`: the URLs all changed).
|
||||||
|
* Loads already in flight settle harmlessly and their results are ignored by the caller.
|
||||||
|
*/
|
||||||
|
reset(): void {
|
||||||
|
for (const cancel of this.#timers.values()) cancel()
|
||||||
|
this.#timers.clear()
|
||||||
|
this.#epoch += 1
|
||||||
|
this.#states.clear()
|
||||||
|
this.#attempts.clear()
|
||||||
|
this.#queue = []
|
||||||
|
this.#desired.clear()
|
||||||
|
this.#lastDesired = []
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cancel pending retry timers on teardown; no callback runs after this. */
|
||||||
|
dispose(): void {
|
||||||
|
for (const cancel of this.#timers.values()) cancel()
|
||||||
|
this.#timers.clear()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A `403` is permanent *for the explored set the server had then*. When the fog slice reports
|
* A `403` is permanent *for the explored set the server had then*. When the fog slice reports
|
||||||
* newly explored cells (#70), the tiles those cells touch may have become allowed, so those
|
* newly explored cells (#70), the tiles those cells touch may have become allowed, so those
|
||||||
@@ -168,9 +253,10 @@ export class TileScheduler {
|
|||||||
this.#states.set(url, 'loading')
|
this.#states.set(url, 'loading')
|
||||||
this.#active += 1
|
this.#active += 1
|
||||||
this.#idle = false
|
this.#idle = false
|
||||||
|
const epoch = this.#epoch
|
||||||
void this.#load(url).then(
|
void this.#load(url).then(
|
||||||
result => this.#settle(url, result),
|
result => this.#settle(url, result, epoch),
|
||||||
() => this.#settle(url, 'error'),
|
() => this.#settle(url, 'error', epoch),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (this.#active === 0 && this.#queue.length === 0 && !this.#idle) {
|
if (this.#active === 0 && this.#queue.length === 0 && !this.#idle) {
|
||||||
@@ -179,16 +265,49 @@ export class TileScheduler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#settle(url: string, result: TileLoadResult): void {
|
#settle(url: string, result: TileLoadResult, epoch: number): void {
|
||||||
this.#active -= 1
|
this.#active -= 1
|
||||||
if (result === 'ok' || result === 'denied') {
|
if (result === 'ok' || result === 'denied') {
|
||||||
this.#states.set(url, result)
|
this.#states.set(url, result)
|
||||||
|
this.#attempts.delete(url)
|
||||||
|
this.#cancelRetry(url)
|
||||||
} else {
|
} else {
|
||||||
// Transient: remember the failure, but never retry it on the same viewport; only a new
|
// Transient: retry with exponential backoff up to `maxAttempts`, then store the failure and
|
||||||
// window or `retryFailed()` (reconnect) asks again. A denied 403 is never retried at all.
|
// wait for a new window or `retryFailed()` (reconnect). A 403 is a separate `denied` answer.
|
||||||
this.#states.set(url, 'error')
|
// A reconnect (`retryFailed`) during the load resets the budget: a failure that lands after
|
||||||
|
// it is a fresh first attempt, not the tail of the old one. A tile that left the window
|
||||||
|
// while loading does not spend the budget: a later window can still try it.
|
||||||
|
if (!this.#desired.has(url)) {
|
||||||
|
this.#states.set(url, 'error')
|
||||||
|
} else {
|
||||||
|
const attempt = epoch === this.#epoch ? (this.#attempts.get(url) ?? 0) + 1 : 1
|
||||||
|
this.#attempts.set(url, attempt)
|
||||||
|
this.#states.set(url, 'error')
|
||||||
|
if (attempt < this.#maxAttempts) this.#scheduleRetryFor(url, attempt)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
this.#onSettled?.(url, result)
|
this.#onSettled?.(url, result)
|
||||||
this.#pump()
|
this.#pump()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#scheduleRetryFor(url: string, attempt: number): void {
|
||||||
|
this.#cancelRetry(url)
|
||||||
|
const delay = this.#retryBaseMs * 2 ** (attempt - 1)
|
||||||
|
const cancel = this.#scheduleRetry(() => {
|
||||||
|
this.#timers.delete(url)
|
||||||
|
// The window may have moved on, or the tile may have been answered meanwhile.
|
||||||
|
if (this.#states.get(url) !== 'error' || !this.#desired.has(url)) return
|
||||||
|
this.#states.set(url, 'queued')
|
||||||
|
this.#queue.push(url)
|
||||||
|
this.#pump()
|
||||||
|
}, delay)
|
||||||
|
this.#timers.set(url, cancel)
|
||||||
|
}
|
||||||
|
|
||||||
|
#cancelRetry(url: string): void {
|
||||||
|
const cancel = this.#timers.get(url)
|
||||||
|
if (cancel === undefined) return
|
||||||
|
cancel()
|
||||||
|
this.#timers.delete(url)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-1
@@ -151,6 +151,28 @@ export function visibleTiles(
|
|||||||
return tiles
|
return tiles
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Order tiles nearest the viewport centre first (the tile layer's request order). At a GM survey
|
||||||
|
* zoom a 16k scene is tens of thousands of tiles, and the fill should grow out of what the eye is
|
||||||
|
* on, not from the top-left corner. Ties keep the incoming (row-major) order, so it is stable.
|
||||||
|
*/
|
||||||
|
export function orderTilesCentreOut(
|
||||||
|
tiles: readonly VisibleTile[],
|
||||||
|
scene: Pick<SceneInfo, 'tile_size'>,
|
||||||
|
camera: Camera,
|
||||||
|
size: ViewportSize,
|
||||||
|
): VisibleTile[] {
|
||||||
|
const tileSize = scene.tile_size
|
||||||
|
if (!(tileSize > 0)) return [...tiles]
|
||||||
|
const [cx, cy] = screenToWorld(camera, size.width / 2, size.height / 2)
|
||||||
|
const distance = (tile: VisibleTile): number => {
|
||||||
|
const dx = (tile.x + 0.5) * tileSize - cx
|
||||||
|
const dy = (tile.y + 0.5) * tileSize - cy
|
||||||
|
return dx * dx + dy * dy
|
||||||
|
}
|
||||||
|
return [...tiles].sort((a, b) => distance(a) - distance(b))
|
||||||
|
}
|
||||||
|
|
||||||
/** The canonical tile URL of DESIGN 3.3: digits only, no leading zeros, `v` + art_version. */
|
/** The canonical tile URL of DESIGN 3.3: digits only, no leading zeros, `v` + art_version. */
|
||||||
export function tileUrl(scene: Pick<SceneInfo, 'id' | 'art_version'>, x: number, y: number): string {
|
export function tileUrl(scene: Pick<SceneInfo, 'id' | 'art_version'>, x: number, y: number): string {
|
||||||
return `/tiles/${scene.id}/v${scene.art_version}/${x}_${y}.png`
|
return `/tiles/${scene.id}/v${scene.art_version}/${x}_${y}.png`
|
||||||
@@ -224,7 +246,11 @@ export class ViewportModel {
|
|||||||
|
|
||||||
setScene(scene: SceneInfo | null): void {
|
setScene(scene: SceneInfo | null): void {
|
||||||
if (scene?.id === this.#state.scene?.id) {
|
if (scene?.id === this.#state.scene?.id) {
|
||||||
if (scene && scene !== this.#state.scene) this.#state = { ...this.#state, scene }
|
if (scene === this.#state.scene) return
|
||||||
|
// Same scene, new object (a reconnect `hello`, or a re-import with a new art_version). Keep
|
||||||
|
// the camera, but notify: the tile layer must rebuild its window and drop stale textures.
|
||||||
|
this.#state = { ...this.#state, scene }
|
||||||
|
this.#emit()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
this.reset(scene, this.#state.role, this.#state.size)
|
this.reset(scene, this.#state.role, this.#state.size)
|
||||||
|
|||||||
+144
-21
@@ -1,8 +1,9 @@
|
|||||||
// The tile scheduler (#69, spec #63 decision 12): viewport-order requests, a bounded concurrency of
|
// The tile scheduler (#69, spec #63 decision 12; #86 tile loading): viewport-order requests, a
|
||||||
// 8, a decoded-texture cache the tile module keeps across reconnect, no duplicate in-flight fetch,
|
// bounded concurrency of 32, a decoded-texture cache the tile module keeps across reconnect, no
|
||||||
// and a denied tile (403/404) is remembered so the client never retries it in a loop.
|
// duplicate in-flight fetch, a denied 403 remembered (no loop) and transient failures retried with
|
||||||
|
// bounded backoff.
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { TILE_CONCURRENCY, TileScheduler, tilesForCells } from '../src/tiles.ts'
|
import { TILE_CONCURRENCY, TileScheduler, tilesForCells, tilesInvalidated } from '../src/tiles.ts'
|
||||||
import type { TileLoadResult } from '../src/tiles.ts'
|
import type { TileLoadResult } from '../src/tiles.ts'
|
||||||
|
|
||||||
interface Harness {
|
interface Harness {
|
||||||
@@ -11,12 +12,22 @@ interface Harness {
|
|||||||
maxActive: number
|
maxActive: number
|
||||||
settle(url: string, result: TileLoadResult): void
|
settle(url: string, result: TileLoadResult): void
|
||||||
settleAll(result: TileLoadResult): void
|
settleAll(result: TileLoadResult): void
|
||||||
|
/** Delays of the retry timers currently scheduled, in schedule order. */
|
||||||
|
retryDelays(): number[]
|
||||||
|
/** Fire every live retry timer (the hidden/vitest-free fake of `setTimeout`). */
|
||||||
|
fireRetries(): void
|
||||||
idle: number
|
idle: number
|
||||||
}
|
}
|
||||||
|
|
||||||
function harness(concurrency = TILE_CONCURRENCY): Harness {
|
function harness(concurrency = TILE_CONCURRENCY): Harness {
|
||||||
const calls: string[] = []
|
const calls: string[] = []
|
||||||
const pending = new Map<string, (result: TileLoadResult) => void>()
|
const pending = new Map<string, (result: TileLoadResult) => void>()
|
||||||
|
interface Retry {
|
||||||
|
run: () => void
|
||||||
|
delay: number
|
||||||
|
cancelled: boolean
|
||||||
|
}
|
||||||
|
const retries: Retry[] = []
|
||||||
let active = 0
|
let active = 0
|
||||||
let maxActive = 0
|
let maxActive = 0
|
||||||
const state = { idle: 0 }
|
const state = { idle: 0 }
|
||||||
@@ -34,6 +45,13 @@ function harness(concurrency = TILE_CONCURRENCY): Harness {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
scheduleRetry: (run, delay) => {
|
||||||
|
const retry: Retry = { run, delay, cancelled: false }
|
||||||
|
retries.push(retry)
|
||||||
|
return () => {
|
||||||
|
retry.cancelled = true
|
||||||
|
}
|
||||||
|
},
|
||||||
onIdle: () => {
|
onIdle: () => {
|
||||||
state.idle += 1
|
state.idle += 1
|
||||||
},
|
},
|
||||||
@@ -55,6 +73,12 @@ function harness(concurrency = TILE_CONCURRENCY): Harness {
|
|||||||
pending.delete(url)
|
pending.delete(url)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
retryDelays() {
|
||||||
|
return retries.filter(retry => !retry.cancelled).map(retry => retry.delay)
|
||||||
|
},
|
||||||
|
fireRetries() {
|
||||||
|
for (const retry of retries.splice(0)) if (!retry.cancelled) retry.run()
|
||||||
|
},
|
||||||
get idle() {
|
get idle() {
|
||||||
return state.idle
|
return state.idle
|
||||||
},
|
},
|
||||||
@@ -71,24 +95,24 @@ async function flush(): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('TileScheduler', () => {
|
describe('TileScheduler', () => {
|
||||||
it('starts at most 8 loads at once, in the order asked', async () => {
|
it('starts at most TILE_CONCURRENCY loads at once, in the order asked', async () => {
|
||||||
expect(TILE_CONCURRENCY).toBe(8)
|
expect(TILE_CONCURRENCY).toBe(32)
|
||||||
const h = harness()
|
const h = harness()
|
||||||
const list = urls(20)
|
const list = urls(80)
|
||||||
h.scheduler.setDesired(list)
|
h.scheduler.setDesired(list)
|
||||||
expect(h.calls).toEqual(list.slice(0, 8))
|
expect(h.calls).toEqual(list.slice(0, 32))
|
||||||
expect(h.maxActive).toBe(8)
|
expect(h.maxActive).toBe(32)
|
||||||
h.settle(list[0] as string, 'ok')
|
h.settle(list[0] as string, 'ok')
|
||||||
await flush()
|
await flush()
|
||||||
expect(h.calls[8]).toBe(list[8])
|
expect(h.calls[32]).toBe(list[32])
|
||||||
expect(h.maxActive).toBe(8)
|
expect(h.maxActive).toBe(32)
|
||||||
// Each settle opens a slot for the next queued tile; drain every round.
|
// Each settle opens a slot for the next queued tile; drain every round.
|
||||||
for (let round = 0; round < 4 && h.calls.length < 20; round++) {
|
for (let round = 0; round < 4 && h.calls.length < 80; round++) {
|
||||||
h.settleAll('ok')
|
h.settleAll('ok')
|
||||||
await flush()
|
await flush()
|
||||||
}
|
}
|
||||||
expect(h.calls.length).toBe(20)
|
expect(h.calls.length).toBe(80)
|
||||||
expect(h.maxActive).toBe(8)
|
expect(h.maxActive).toBe(32)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('never asks twice for the same tile', () => {
|
it('never asks twice for the same tile', () => {
|
||||||
@@ -123,15 +147,15 @@ describe('TileScheduler', () => {
|
|||||||
|
|
||||||
it('drops queued work that left the viewport (no prefetch beyond the margin)', async () => {
|
it('drops queued work that left the viewport (no prefetch beyond the margin)', async () => {
|
||||||
const h = harness()
|
const h = harness()
|
||||||
const list = urls(20)
|
const list = urls(80)
|
||||||
h.scheduler.setDesired(list)
|
h.scheduler.setDesired(list)
|
||||||
expect(h.calls.length).toBe(8)
|
expect(h.calls.length).toBe(32)
|
||||||
h.scheduler.setDesired([list[0] as string])
|
h.scheduler.setDesired([list[0] as string])
|
||||||
h.settleAll('ok')
|
h.settleAll('ok')
|
||||||
await flush()
|
await flush()
|
||||||
// Only the first 8 were ever started; the 12 queued tiles were cancelled.
|
// Only the first TILE_CONCURRENCY were ever started; the rest were cancelled.
|
||||||
expect(h.calls.length).toBe(8)
|
expect(h.calls.length).toBe(32)
|
||||||
expect(h.scheduler.status(list[19] as string)).toBeUndefined()
|
expect(h.scheduler.status(list[79] as string)).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('does not retry a failed tile on the same window, only on a new one', async () => {
|
it('does not retry a failed tile on the same window, only on a new one', async () => {
|
||||||
@@ -142,14 +166,103 @@ describe('TileScheduler', () => {
|
|||||||
await flush()
|
await flush()
|
||||||
expect(h.scheduler.isComplete([list[0] as string])).toBe(false)
|
expect(h.scheduler.isComplete([list[0] as string])).toBe(false)
|
||||||
expect(h.calls).toEqual([list[0]])
|
expect(h.calls).toEqual([list[0]])
|
||||||
// Same window: the rAF sync after the failure must not hammer the server.
|
// Same window: the rAF sync after the failure must not hammer the server (only the scheduled
|
||||||
|
// backoff does, which is not a window sync).
|
||||||
h.scheduler.setDesired([list[0] as string])
|
h.scheduler.setDesired([list[0] as string])
|
||||||
expect(h.calls).toEqual([list[0]])
|
expect(h.calls).toEqual([list[0]])
|
||||||
// A new window that still wants the tile asks once more.
|
// A new window that still wants the tile asks once more, and cancels the pending backoff.
|
||||||
h.scheduler.setDesired(list)
|
h.scheduler.setDesired(list)
|
||||||
|
expect(h.retryDelays()).toEqual([])
|
||||||
expect(h.calls).toEqual([list[0], list[0], list[1]])
|
expect(h.calls).toEqual([list[0], list[0], list[1]])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('retries a transient failure with exponential backoff, up to the budget', async () => {
|
||||||
|
const h = harness()
|
||||||
|
const [url] = urls(1) as [string]
|
||||||
|
h.scheduler.setDesired([url])
|
||||||
|
h.settle(url, 'error')
|
||||||
|
await flush()
|
||||||
|
expect(h.retryDelays()).toEqual([250])
|
||||||
|
h.fireRetries()
|
||||||
|
expect(h.calls).toEqual([url, url])
|
||||||
|
h.settle(url, 'error')
|
||||||
|
await flush()
|
||||||
|
expect(h.retryDelays()).toEqual([500])
|
||||||
|
h.fireRetries()
|
||||||
|
expect(h.calls).toEqual([url, url, url])
|
||||||
|
// Third (last) attempt fails: stored error, no more timers until a reconnect.
|
||||||
|
h.settle(url, 'error')
|
||||||
|
await flush()
|
||||||
|
expect(h.retryDelays()).toEqual([])
|
||||||
|
expect(h.scheduler.isPending([url])).toBe(false)
|
||||||
|
expect(h.scheduler.isComplete([url])).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a failure after the tile left the window does not spend the retry budget', async () => {
|
||||||
|
const h = harness()
|
||||||
|
const [url] = urls(1) as [string]
|
||||||
|
h.scheduler.setDesired([url])
|
||||||
|
h.scheduler.setDesired([])
|
||||||
|
h.settle(url, 'error')
|
||||||
|
await flush()
|
||||||
|
expect(h.retryDelays()).toEqual([])
|
||||||
|
h.scheduler.setDesired([url])
|
||||||
|
expect(h.calls).toEqual([url, url])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a retry that fires after the window moved on does not request the tile', async () => {
|
||||||
|
const h = harness()
|
||||||
|
const [url] = urls(1) as [string]
|
||||||
|
h.scheduler.setDesired([url])
|
||||||
|
h.settle(url, 'error')
|
||||||
|
await flush()
|
||||||
|
h.scheduler.setDesired([])
|
||||||
|
h.fireRetries()
|
||||||
|
expect(h.calls).toEqual([url])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a failure that settles after retryFailed gets a fresh budget', async () => {
|
||||||
|
const h = harness()
|
||||||
|
const [url] = urls(1) as [string]
|
||||||
|
h.scheduler.setDesired([url])
|
||||||
|
// The reconnect happens while the load is in flight: its failure must not exhaust the old run.
|
||||||
|
h.scheduler.retryFailed()
|
||||||
|
h.settle(url, 'error')
|
||||||
|
await flush()
|
||||||
|
expect(h.retryDelays()).toEqual([250])
|
||||||
|
expect(h.calls).toEqual([url])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('retryFailed resets the budget so a reconnect can recover a 404', async () => {
|
||||||
|
const h = harness()
|
||||||
|
const [url] = urls(1) as [string]
|
||||||
|
h.scheduler.setDesired([url])
|
||||||
|
for (let attempt = 0; attempt < 3; attempt++) {
|
||||||
|
h.settle(url, 'error')
|
||||||
|
await flush()
|
||||||
|
h.fireRetries()
|
||||||
|
}
|
||||||
|
expect(h.calls).toHaveLength(3)
|
||||||
|
h.scheduler.retryFailed()
|
||||||
|
h.scheduler.setDesired([url])
|
||||||
|
expect(h.calls).toHaveLength(4)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reset forgets every decision (a new art_version)', async () => {
|
||||||
|
const h = harness()
|
||||||
|
const list = urls(2)
|
||||||
|
h.scheduler.setDesired(list)
|
||||||
|
expect(h.calls).toEqual(list)
|
||||||
|
h.settle(list[0] as string, 'error')
|
||||||
|
await flush()
|
||||||
|
h.scheduler.reset()
|
||||||
|
expect(h.retryDelays()).toEqual([])
|
||||||
|
expect(h.scheduler.status(list[0] as string)).toBeUndefined()
|
||||||
|
h.scheduler.setDesired(list)
|
||||||
|
// Both urls are queued again: the new art_version's URLs are different ones in production.
|
||||||
|
expect(h.calls).toEqual([...list, ...list])
|
||||||
|
})
|
||||||
|
|
||||||
it('is not pending once a transient failure has settled this pass', async () => {
|
it('is not pending once a transient failure has settled this pass', async () => {
|
||||||
const h = harness()
|
const h = harness()
|
||||||
const list = urls(2)
|
const list = urls(2)
|
||||||
@@ -184,6 +297,16 @@ describe('TileScheduler', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('art_version invalidation', () => {
|
||||||
|
it('drops the cache on a new art_version or scene, never on a reconnect', () => {
|
||||||
|
expect(tilesInvalidated(null, { id: 1, art_version: 1 })).toBe(false)
|
||||||
|
expect(tilesInvalidated({ id: 1, art_version: 1 }, { id: 1, art_version: 1 })).toBe(false)
|
||||||
|
expect(tilesInvalidated({ id: 1, art_version: 1 }, { id: 1, art_version: 2 })).toBe(true)
|
||||||
|
expect(tilesInvalidated({ id: 1, art_version: 2 }, { id: 2, art_version: 2 })).toBe(true)
|
||||||
|
expect(tilesInvalidated({ id: 1, art_version: 1 }, null)).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('fog-driven denied retry (#70)', () => {
|
describe('fog-driven denied retry (#70)', () => {
|
||||||
it('re-asks a denied tile exactly once after its cells became explored', async () => {
|
it('re-asks a denied tile exactly once after its cells became explored', async () => {
|
||||||
const h = harness()
|
const h = harness()
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
ViewportModel,
|
ViewportModel,
|
||||||
clampZoom,
|
clampZoom,
|
||||||
centredCamera,
|
centredCamera,
|
||||||
|
orderTilesCentreOut,
|
||||||
pinchCamera,
|
pinchCamera,
|
||||||
screenToWorld,
|
screenToWorld,
|
||||||
tileUrl,
|
tileUrl,
|
||||||
@@ -137,6 +138,40 @@ describe('ViewportModel (the render layer\'s UI state)', () => {
|
|||||||
model.setScene({ ...scene, id: 2 })
|
model.setScene({ ...scene, id: 2 })
|
||||||
expect(model.state.camera).toEqual(centredCamera({ ...scene, id: 2 }, size))
|
expect(model.state.camera).toEqual(centredCamera({ ...scene, id: 2 }, size))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('emits on a same-scene resync so a new art_version is not swallowed (#86)', () => {
|
||||||
|
const model = new ViewportModel()
|
||||||
|
let seen = 0
|
||||||
|
model.reset(scene, 'player', size)
|
||||||
|
model.subscribe(() => {
|
||||||
|
seen += 1
|
||||||
|
})
|
||||||
|
const panned = model.state.camera
|
||||||
|
model.setScene({ ...scene, art_version: 2 })
|
||||||
|
expect(seen).toBe(1)
|
||||||
|
expect(model.state.scene?.art_version).toBe(2)
|
||||||
|
expect(model.state.camera).toBe(panned)
|
||||||
|
// The same object again is not a change: no extra notification.
|
||||||
|
model.setScene(model.state.scene)
|
||||||
|
expect(seen).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('centre-out tile order (#86)', () => {
|
||||||
|
it('asks for the tile under the viewport centre first, growing outwards', () => {
|
||||||
|
const camera = centredCamera(scene, size)
|
||||||
|
const tiles = orderTilesCentreOut(visibleTiles(scene, camera, size), scene, camera, size)
|
||||||
|
// 320x320 viewport at zoom 1 centred on world (2048,2048): the four middle tiles tie.
|
||||||
|
expect(tiles.length).toBe(12 * 12)
|
||||||
|
const distance = (tile: { x: number; y: number }) =>
|
||||||
|
Math.hypot((tile.x + 0.5) * scene.tile_size - 2048, (tile.y + 0.5) * scene.tile_size - 2048)
|
||||||
|
const distances = tiles.map(distance)
|
||||||
|
expect(distances).toEqual([...distances].sort((a, b) => a - b))
|
||||||
|
expect(Math.abs((tiles[0]?.x ?? -1) - 63)).toBeLessThanOrEqual(1)
|
||||||
|
expect(Math.abs((tiles[0]?.y ?? -1) - 63)).toBeLessThanOrEqual(1)
|
||||||
|
// It is a permutation of the row-major window, not a different window.
|
||||||
|
expect(new Set(tiles.map(tile => tile.url)).size).toBe(12 * 12)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('visible tiles', () => {
|
describe('visible tiles', () => {
|
||||||
|
|||||||
+13
-10
@@ -307,8 +307,11 @@ Notes:
|
|||||||
- Tile URLs include the scene's `art_version` so that re-imported art does not hit stale caches
|
- Tile URLs include the scene's `art_version` so that re-imported art does not hit stale caches
|
||||||
[FIXED, owner decision 2026-11-14, #7]: from M3 on, always `1` in M3. The gate reads
|
[FIXED, owner decision 2026-11-14, #7]: from M3 on, always `1` in M3. The gate reads
|
||||||
`<state>/tiles/<scene>/v<art_version>/` (layout fixed in M3; writing versions is the import CLI of
|
`<state>/tiles/<scene>/v<art_version>/` (layout fixed in M3; writing versions is the import CLI of
|
||||||
11.1, pulled forward to M4 by #79; cleanup remains M6). Response `Cache-Control: private` [FIXED,
|
11.1, pulled forward to M4 by #79; cleanup remains M6). Response `Cache-Control: private,
|
||||||
owner decision 2026-11-14, #7], not the prototype's `no-store`.
|
max-age=31536000, immutable` [FIXED, owner decision 2026-11-14, #7; immutable cache, #86,
|
||||||
|
2026-11-21]: the URL carries the version, so a tile never changes under its URL, and a reload may
|
||||||
|
reuse every tile from the browser cache instead of revalidating tens of thousands of requests;
|
||||||
|
`private` keeps gated bytes out of shared caches.
|
||||||
- **URL grammar and status split [FIXED (owner-delegated), 2026-11-15, #24].** Every numeric
|
- **URL grammar and status split [FIXED (owner-delegated), 2026-11-15, #24].** Every numeric
|
||||||
component is canonical decimal: digits only, no sign, no space, **no leading zero** (`0` alone is
|
component is canonical decimal: digits only, no sign, no space, **no leading zero** (`0` alone is
|
||||||
the only zero), bounded at 9 digits for `<scene>` and `<art_version>` (`v` + digits) and 5 digits
|
the only zero), bounded at 9 digits for `<scene>` and `<art_version>` (`v` + digits) and 5 digits
|
||||||
@@ -323,9 +326,9 @@ Notes:
|
|||||||
explored set under the global lock; a player with no sight state has explored nothing.
|
explored set under the global lock; a player with no sight state has explored nothing.
|
||||||
`X-Accel-Redirect` is built only from the parsed integers
|
`X-Accel-Redirect` is built only from the parsed integers
|
||||||
(`/_tiles/<scene>/v<art_version>/<x>_<y>.png`), never from request text, so no path shape can
|
(`/_tiles/<scene>/v<art_version>/<x>_<y>.png`), never from request text, so no path shape can
|
||||||
steer it. `Cache-Control: private` is set by the Nim gate and rides through nginx's internal
|
steer it. `Cache-Control: private, max-age=31536000, immutable` is set by the Nim gate and rides
|
||||||
redirect unchanged; nginx adds nothing of its own there (the test vhost records this, TESTING
|
through nginx's internal redirect unchanged; nginx adds nothing of its own there (the test vhost
|
||||||
§11.1). Nim sends no body and no `Content-Type`.
|
records this, TESTING §11.1). Nim sends no body and no `Content-Type`.
|
||||||
|
|
||||||
### 3.4 Threat list
|
### 3.4 Threat list
|
||||||
|
|
||||||
@@ -2251,11 +2254,11 @@ See TESTING §10.4 (Node 26 black-box harnesses, built-ins only, `devbox run tes
|
|||||||
off`. The map must be declared at `http{}` level.
|
off`. The map must be declared at `http{}` level.
|
||||||
- `location = /join` -> proxy, **`access_log off`**, `add_header Referrer-Policy no-referrer`.
|
- `location = /join` -> proxy, **`access_log off`**, `add_header Referrer-Policy no-referrer`.
|
||||||
- `location /tiles/` -> proxy (Nim decides, returns `X-Accel-Redirect`).
|
- `location /tiles/` -> proxy (Nim decides, returns `X-Accel-Redirect`).
|
||||||
- `location /_tiles/` -> `internal; alias <state dir>/tiles/;` `Cache-Control private`. Must be
|
- `location /_tiles/` -> `internal; alias <state dir>/tiles/;` `Cache-Control: private,
|
||||||
readable by the nginx user (group read on the tiles dir) [INFERRED NixOS gotcha]; do not expose
|
max-age=31536000, immutable`. Must be readable by the nginx user (group read on the tiles dir)
|
||||||
the state dir otherwise. [FIXED (owner-delegated), #24] The `Cache-Control: private` on a served
|
[INFERRED NixOS gotcha]; do not expose the state dir otherwise. [FIXED (owner-delegated), #24]
|
||||||
tile comes from the Nim gate (3.3) and nginx passes it through the internal redirect; the
|
The `Cache-Control` on a served tile comes from the Nim gate (3.3) and nginx passes it through
|
||||||
location adds no header of its own, so the header is not duplicated.
|
the internal redirect; the location adds no header of its own, so the header is not duplicated.
|
||||||
- Test nginx [FIXED (owner-delegated), #24]: a devbox `nginx` in front of the harness mirrors this
|
- Test nginx [FIXED (owner-delegated), #24]: a devbox `nginx` in front of the harness mirrors this
|
||||||
vhost shape; details in TESTING §11.1.
|
vhost shape; details in TESTING §11.1.
|
||||||
- Response headers: HSTS, CSP (no inline scripts, `connect-src 'self'` wss),
|
- Response headers: HSTS, CSP (no inline scripts, `connect-src 'self'` wss),
|
||||||
|
|||||||
+6
-3
@@ -798,8 +798,8 @@ proc tileGate(request: Request) {.gcsafe.} =
|
|||||||
## parse the URL (malformed, out of range, another scene, stale art version -> 404 whatever the
|
## parse the URL (malformed, out of range, another scene, stale art version -> 404 whatever the
|
||||||
## session), then the session (missing or unknown -> 403), then the explored bitmap (unexplored ->
|
## session), then the session (missing or unknown -> 403), then the explored bitmap (unexplored ->
|
||||||
## 403). The GM is always allowed. Nim never opens a tile file: a `200` carries
|
## 403). The GM is always allowed. Nim never opens a tile file: a `200` carries
|
||||||
## `X-Accel-Redirect` to the internal `/_tiles/` location and `Cache-Control: private` (Q4), and
|
## `X-Accel-Redirect` to the internal `/_tiles/` location and
|
||||||
## nginx serves the bytes.
|
## `Cache-Control: private, max-age=31536000, immutable` (#86), and nginx serves the bytes.
|
||||||
##
|
##
|
||||||
## No `dbLock` (issue #65): the whole decision is one read of the gate's published snapshot, which
|
## No `dbLock` (issue #65): the whole decision is one read of the gate's published snapshot, which
|
||||||
## holds the scalar scene record, the session table and the explored bitmap. A mutation holding
|
## holds the scalar scene record, the session table and the explored bitmap. A mutation holding
|
||||||
@@ -820,7 +820,10 @@ proc tileGate(request: Request) {.gcsafe.} =
|
|||||||
|
|
||||||
var headers: HttpHeaders
|
var headers: HttpHeaders
|
||||||
headers["X-Accel-Redirect"] = decision.redirect
|
headers["X-Accel-Redirect"] = decision.redirect
|
||||||
headers["Cache-Control"] = "private"
|
# Versioned and immutable: `v<art_version>` changes on a re-import (#86), so a reload may reuse
|
||||||
|
# every tile from the HTTP cache instead of revalidating thousands of URLs. `private` because the
|
||||||
|
# bytes are gated per session and must never land in a shared cache.
|
||||||
|
headers["Cache-Control"] = "private, max-age=31536000, immutable"
|
||||||
request.respond(200, headers)
|
request.respond(200, headers)
|
||||||
|
|
||||||
proc wsUpgrade(request: Request) {.gcsafe.} =
|
proc wsUpgrade(request: Request) {.gcsafe.} =
|
||||||
|
|||||||
+2
-1
@@ -101,7 +101,8 @@ http {
|
|||||||
|
|
||||||
# Unreachable from outside: the internal directive rejects a direct request with 404. The alias
|
# Unreachable from outside: the internal directive rejects a direct request with 404. The alias
|
||||||
# is <state>/tiles/<scene>/v<art_version>/, the tree the X-Accel-Redirect names (3.3, 11.1).
|
# is <state>/tiles/<scene>/v<art_version>/, the tree the X-Accel-Redirect names (3.3, 11.1).
|
||||||
# Cache-Control: private rides from the Nim gate through the internal redirect (nginx passes it).
|
# Cache-Control: private, max-age, immutable rides from the Nim gate through the internal
|
||||||
|
# redirect (nginx passes it); no add_header here, so the header is not duplicated (#86).
|
||||||
location /_tiles/ {
|
location /_tiles/ {
|
||||||
internal;
|
internal;
|
||||||
alias ${tilesRoot}/;
|
alias ${tilesRoot}/;
|
||||||
|
|||||||
@@ -210,7 +210,9 @@ test('tile gate: leak check (d) matches the independent explored oracle', async
|
|||||||
const want = fs.readFileSync(path.join(tileDir(stateDir, scene.id, ctx.artVersion), `${x}_${y}.png`))
|
const want = fs.readFileSync(path.join(tileDir(stateDir, scene.id, ctx.artVersion), `${x}_${y}.png`))
|
||||||
if (!body.equals(want)) fail('served bytes are not the requested tile')
|
if (!body.equals(want)) fail('served bytes are not the requested tile')
|
||||||
if (r.headers.get('x-accel-redirect') !== null) fail('X-Accel-Redirect leaked to the client')
|
if (r.headers.get('x-accel-redirect') !== null) fail('X-Accel-Redirect leaked to the client')
|
||||||
if ((r.headers.get('cache-control') ?? '') !== 'private') fail('Cache-Control is not private')
|
if ((r.headers.get('cache-control') ?? '') !== 'private, max-age=31536000, immutable') {
|
||||||
|
fail('Cache-Control is not private + immutable')
|
||||||
|
}
|
||||||
} else if (r.status === 403) {
|
} else if (r.status === 403) {
|
||||||
if (vis.sure) fail('refused although the oracle is sure the cell is visible')
|
if (vis.sure) fail('refused although the oracle is sure the cell is visible')
|
||||||
if (vis.maybe) maybeRefused++
|
if (vis.maybe) maybeRefused++
|
||||||
@@ -340,7 +342,7 @@ test('tile gate: refusals, direct /_tiles, malformed and out-of-range paths', as
|
|||||||
const gate = await getTile(s.origin, ok, ctx.seenCtx.cookie)
|
const gate = await getTile(s.origin, ok, ctx.seenCtx.cookie)
|
||||||
assert.equal(gate.status, 200)
|
assert.equal(gate.status, 200)
|
||||||
assert.equal(gate.headers.get('x-accel-redirect'), `/_tiles/${scene.id}/v${ctx.artVersion}/9_9.png`)
|
assert.equal(gate.headers.get('x-accel-redirect'), `/_tiles/${scene.id}/v${ctx.artVersion}/9_9.png`)
|
||||||
assert.equal(gate.headers.get('cache-control'), 'private')
|
assert.equal(gate.headers.get('cache-control'), 'private, max-age=31536000, immutable')
|
||||||
assert.equal((await gate.text()), '', 'Nim sends the decision, not the bytes')
|
assert.equal((await gate.text()), '', 'Nim sends the decision, not the bytes')
|
||||||
const refused = await getTile(s.origin, unseen, ctx.seenCtx.cookie)
|
const refused = await getTile(s.origin, unseen, ctx.seenCtx.cookie)
|
||||||
assert.equal(refused.status, 403)
|
assert.equal(refused.status, 403)
|
||||||
|
|||||||
Reference in New Issue
Block a user