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.
348 lines
12 KiB
TypeScript
348 lines
12 KiB
TypeScript
// The tile scheduler (#69, spec #63 decision 12; #86 tile loading): viewport-order requests, a
|
|
// bounded concurrency of 32, a decoded-texture cache the tile module keeps across reconnect, no
|
|
// duplicate in-flight fetch, a denied 403 remembered (no loop) and transient failures retried with
|
|
// bounded backoff.
|
|
import { describe, expect, it } from 'vitest'
|
|
import { TILE_CONCURRENCY, TileScheduler, tilesForCells, tilesInvalidated } from '../src/tiles.ts'
|
|
import type { TileLoadResult } from '../src/tiles.ts'
|
|
|
|
interface Harness {
|
|
scheduler: TileScheduler
|
|
calls: string[]
|
|
maxActive: number
|
|
settle(url: string, 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
|
|
}
|
|
|
|
function harness(concurrency = TILE_CONCURRENCY): Harness {
|
|
const calls: string[] = []
|
|
const pending = new Map<string, (result: TileLoadResult) => void>()
|
|
interface Retry {
|
|
run: () => void
|
|
delay: number
|
|
cancelled: boolean
|
|
}
|
|
const retries: Retry[] = []
|
|
let active = 0
|
|
let maxActive = 0
|
|
const state = { idle: 0 }
|
|
const scheduler = new TileScheduler({
|
|
concurrency,
|
|
load: url => {
|
|
calls.push(url)
|
|
active += 1
|
|
maxActive = Math.max(maxActive, active)
|
|
return new Promise<TileLoadResult>(resolve => {
|
|
pending.set(url, result => {
|
|
active -= 1
|
|
pending.delete(url)
|
|
resolve(result)
|
|
})
|
|
})
|
|
},
|
|
scheduleRetry: (run, delay) => {
|
|
const retry: Retry = { run, delay, cancelled: false }
|
|
retries.push(retry)
|
|
return () => {
|
|
retry.cancelled = true
|
|
}
|
|
},
|
|
onIdle: () => {
|
|
state.idle += 1
|
|
},
|
|
})
|
|
return {
|
|
scheduler,
|
|
calls,
|
|
get maxActive() {
|
|
return maxActive
|
|
},
|
|
settle(url, result) {
|
|
const resolve = pending.get(url)
|
|
if (!resolve) throw new Error(`no pending load for ${url}`)
|
|
resolve(result)
|
|
},
|
|
settleAll(result) {
|
|
for (const url of [...pending.keys()]) {
|
|
pending.get(url)?.(result)
|
|
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() {
|
|
return state.idle
|
|
},
|
|
}
|
|
}
|
|
|
|
function urls(count: number): string[] {
|
|
return Array.from({ length: count }, (_, index) => `/tiles/1/v1/${index}_0.png`)
|
|
}
|
|
|
|
/** Let every queued promise callback and the next pump round run. */
|
|
async function flush(): Promise<void> {
|
|
for (let i = 0; i < 20; i++) await Promise.resolve()
|
|
}
|
|
|
|
describe('TileScheduler', () => {
|
|
it('starts at most TILE_CONCURRENCY loads at once, in the order asked', async () => {
|
|
expect(TILE_CONCURRENCY).toBe(32)
|
|
const h = harness()
|
|
const list = urls(80)
|
|
h.scheduler.setDesired(list)
|
|
expect(h.calls).toEqual(list.slice(0, 32))
|
|
expect(h.maxActive).toBe(32)
|
|
h.settle(list[0] as string, 'ok')
|
|
await flush()
|
|
expect(h.calls[32]).toBe(list[32])
|
|
expect(h.maxActive).toBe(32)
|
|
// Each settle opens a slot for the next queued tile; drain every round.
|
|
for (let round = 0; round < 4 && h.calls.length < 80; round++) {
|
|
h.settleAll('ok')
|
|
await flush()
|
|
}
|
|
expect(h.calls.length).toBe(80)
|
|
expect(h.maxActive).toBe(32)
|
|
})
|
|
|
|
it('never asks twice for the same tile', () => {
|
|
const h = harness()
|
|
const list = urls(4)
|
|
h.scheduler.setDesired(list)
|
|
h.scheduler.setDesired(list)
|
|
expect(h.calls).toEqual(list)
|
|
})
|
|
|
|
it('remembers a denied tile and never retries it', async () => {
|
|
const h = harness()
|
|
const list = urls(1)
|
|
h.scheduler.setDesired(list)
|
|
h.settle(list[0] as string, 'denied')
|
|
await flush()
|
|
expect(h.scheduler.status(list[0] as string)).toBe('denied')
|
|
h.scheduler.setDesired(list)
|
|
h.scheduler.setDesired(list)
|
|
expect(h.calls).toEqual(list)
|
|
})
|
|
|
|
it('reports idle once when every wanted tile is settled', async () => {
|
|
const h = harness()
|
|
const list = urls(3)
|
|
h.scheduler.setDesired(list)
|
|
h.settleAll('ok')
|
|
await flush()
|
|
expect(h.scheduler.isComplete(list)).toBe(true)
|
|
expect(h.idle).toBe(1)
|
|
})
|
|
|
|
it('drops queued work that left the viewport (no prefetch beyond the margin)', async () => {
|
|
const h = harness()
|
|
const list = urls(80)
|
|
h.scheduler.setDesired(list)
|
|
expect(h.calls.length).toBe(32)
|
|
h.scheduler.setDesired([list[0] as string])
|
|
h.settleAll('ok')
|
|
await flush()
|
|
// Only the first TILE_CONCURRENCY were ever started; the rest were cancelled.
|
|
expect(h.calls.length).toBe(32)
|
|
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 () => {
|
|
const h = harness()
|
|
const list = urls(2)
|
|
h.scheduler.setDesired([list[0] as string])
|
|
h.settle(list[0] as string, 'error')
|
|
await flush()
|
|
expect(h.scheduler.isComplete([list[0] as string])).toBe(false)
|
|
expect(h.calls).toEqual([list[0]])
|
|
// 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])
|
|
expect(h.calls).toEqual([list[0]])
|
|
// A new window that still wants the tile asks once more, and cancels the pending backoff.
|
|
h.scheduler.setDesired(list)
|
|
expect(h.retryDelays()).toEqual([])
|
|
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 () => {
|
|
const h = harness()
|
|
const list = urls(2)
|
|
h.scheduler.setDesired(list)
|
|
expect(h.scheduler.isPending(list)).toBe(true) // both in flight
|
|
h.settle(list[0] as string, 'error')
|
|
h.settle(list[1] as string, 'ok')
|
|
await flush()
|
|
// The stored error is terminal until a new window or a reconnect: readiness must not wait on it.
|
|
expect(h.scheduler.isPending(list)).toBe(false)
|
|
expect(h.scheduler.isComplete(list)).toBe(false)
|
|
})
|
|
|
|
it('markLoaded satisfies a tile from the texture cache without a request', () => {
|
|
const h = harness()
|
|
const list = urls(1)
|
|
h.scheduler.markLoaded(list[0] as string)
|
|
h.scheduler.setDesired(list)
|
|
expect(h.calls).toEqual([])
|
|
expect(h.scheduler.isComplete(list)).toBe(true)
|
|
})
|
|
|
|
it('retryFailed makes a transient failure askable again after a reconnect', async () => {
|
|
const h = harness()
|
|
const list = urls(1)
|
|
h.scheduler.setDesired(list)
|
|
h.settle(list[0] as string, 'error')
|
|
await flush()
|
|
h.scheduler.retryFailed()
|
|
h.scheduler.setDesired(list)
|
|
expect(h.calls).toEqual([list[0], list[0]])
|
|
})
|
|
})
|
|
|
|
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)', () => {
|
|
it('re-asks a denied tile exactly once after its cells became explored', async () => {
|
|
const h = harness()
|
|
const list = urls(2)
|
|
h.scheduler.setDesired(list)
|
|
h.settle(list[0] as string, 'denied')
|
|
h.settle(list[1] as string, 'ok')
|
|
await flush()
|
|
expect(h.calls).toEqual(list)
|
|
|
|
// The fog says cells under the first tile became explored: only that denied tile is stale.
|
|
h.scheduler.retryDenied([list[0] as string])
|
|
h.scheduler.setDesired(list)
|
|
expect(h.calls).toEqual([...list, list[0]])
|
|
h.settleAll('ok')
|
|
await flush()
|
|
|
|
// A plain re-sync (no new cells) must not ask again: the denial is still remembered.
|
|
h.scheduler.setDesired(list)
|
|
h.scheduler.retryDenied([])
|
|
h.scheduler.setDesired(list)
|
|
expect(h.calls).toEqual([...list, list[0]])
|
|
})
|
|
|
|
it('maps explored cells to the tiles they touch', () => {
|
|
const scene = { id: 3, art_version: 7, tile_size: 32 }
|
|
const grid = { cols: 4, cell: 32 }
|
|
// Cells (1,0) -> tile (1,0), (1,1) -> tile (1,1), (3,1) -> tile (3,1).
|
|
expect(tilesForCells(scene, grid, [1, 5, 7])).toEqual([
|
|
'/tiles/3/v7/1_0.png',
|
|
'/tiles/3/v7/1_1.png',
|
|
'/tiles/3/v7/3_1.png',
|
|
])
|
|
// Two cells in one tile are one url; a smaller cell than a tile still maps correctly.
|
|
expect(tilesForCells(scene, { cols: 16, cell: 8 }, [0, 1, 2])).toEqual(['/tiles/3/v7/0_0.png'])
|
|
expect(tilesForCells(scene, { cols: 0, cell: 0 }, [1])).toEqual([])
|
|
})
|
|
})
|