Files
FFF_vtt_frozen/client/src/tiles.ts
T
SirStone 52ab50d765 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.
2026-11-21 22:28:18 +01:00

314 lines
12 KiB
TypeScript

// The tile scheduler (#69, spec #63 decision 12; #86 tile-loading). Pure: the loader is injected, so
// the concurrency, cache and retry rules are unit-tested without a browser or a GPU.
//
// Rules encoded here:
// - at most TILE_CONCURRENCY requests in flight (measured knee: a browser decodes and uploads
// 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
// reconnect; this scheduler remembers settled URLs too);
// - a `403` is a permanent `denied` answer: never retried in a loop (the server said no). It is
// 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
// prefetches beyond the margin.
import type { SceneInfo } from './protocol.ts'
import { tileUrl } from './viewport.ts'
/**
* 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 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 {
load(url: string): Promise<TileLoadResult>
onSettled?(url: string, result: TileLoadResult): void
onIdle?(): void
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 {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
return true
}
/**
* The tile urls touched by a set of explored cells (fog slice indices, row-major). v1 has
* `cell == tile_size` (DESIGN 8), but the maths keeps a cell-to-tile mapping general.
*/
export function tilesForCells(
scene: Pick<SceneInfo, 'id' | 'art_version' | 'tile_size'>,
grid: { cols: number; cell: number },
cells: Iterable<number>,
): string[] {
const tileSize = scene.tile_size
if (!(tileSize > 0) || grid.cell <= 0 || grid.cols <= 0) return []
const urls = new Set<string>()
for (const index of cells) {
const cx = index % grid.cols
const cy = (index / grid.cols) | 0
const tx = Math.floor((cx * grid.cell) / tileSize)
const ty = Math.floor((cy * grid.cell) / tileSize)
urls.add(tileUrl(scene, tx, ty))
}
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 {
readonly #load: (url: string) => Promise<TileLoadResult>
readonly #onSettled: ((url: string, result: TileLoadResult) => void) | undefined
readonly #onIdle: (() => void) | undefined
readonly #concurrency: number
readonly #maxAttempts: number
readonly #retryBaseMs: number
readonly #scheduleRetry: RetryScheduler
#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[] = []
#desired = new Set<string>()
#lastDesired: readonly string[] = []
#active = 0
#idle = true
constructor(options: TileSchedulerOptions) {
this.#load = options.load
this.#onSettled = options.onSettled
this.#onIdle = options.onIdle
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 {
return this.#states.get(url)
}
get active(): number {
return this.#active
}
/** What the viewport wants now. `urls` is already in the caller's order (centre-out). */
setDesired(urls: readonly string[]): void {
// 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.
if (sameList(urls, this.#lastDesired)) {
this.#pump()
return
}
this.#lastDesired = [...urls]
this.#desired = new Set(urls)
// Keep queued entries that are still wanted, in the new viewport order; forget the rest so a
// later viewport that asks for the tile again can queue it fresh.
const order = new Map(urls.map((url, index) => [url, index]))
const dropped = this.#queue.filter(url => !this.#desired.has(url))
for (const url of dropped) this.#states.delete(url)
this.#queue = this.#queue
.filter(url => this.#desired.has(url))
.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0))
for (const url of urls) {
const existing = this.#states.get(url)
if (existing === 'error') {
// 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.#queue.push(url)
}
this.#pump()
}
/** A texture already in the cache (e.g. a renderer remount) needs no request. */
markLoaded(url: string): void {
if (!this.#states.has(url)) this.#states.set(url, 'ok')
}
/**
* 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 {
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 = []
}
/**
* 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
* newly explored cells (#70), the tiles those cells touch may have become allowed, so those
* denied urls are forgotten and the next `setDesired` asks for them exactly once more. Nothing
* else is retried: an unexplored 403 stays denied (no retry loop).
*/
retryDenied(urls: Iterable<string>): void {
let changed = false
for (const url of urls) {
if (this.#states.get(url) !== 'denied') continue
this.#states.delete(url)
changed = true
}
// The next setDesired rebuilds the queue, which re-queues the forgotten urls as `queued`.
if (changed) this.#lastDesired = []
}
/**
* True while any wanted tile still has to settle on this pass (queued, loading, or not yet
* asked). A stored `error` is *terminal for this pass*: it is only retried on a new window or
* after `retryFailed()`, so it must not keep a readiness probe waiting forever.
*/
isPending(urls: readonly string[]): boolean {
return urls.some(url => {
const status = this.#states.get(url)
return status === undefined || status === 'queued' || status === 'loading'
})
}
/** True when every wanted tile settled with an `ok` or `denied` answer. */
isComplete(urls: readonly string[]): boolean {
return urls.every(url => {
const status = this.#states.get(url)
return status === 'ok' || status === 'denied'
})
}
#pump(): void {
while (this.#active < this.#concurrency && this.#queue.length > 0) {
const url = this.#queue.shift()
if (url === undefined) break
if (!this.#desired.has(url) || this.#states.get(url) !== 'queued') continue
this.#states.set(url, 'loading')
this.#active += 1
this.#idle = false
const epoch = this.#epoch
void this.#load(url).then(
result => this.#settle(url, result, epoch),
() => this.#settle(url, 'error', epoch),
)
}
if (this.#active === 0 && this.#queue.length === 0 && !this.#idle) {
this.#idle = true
this.#onIdle?.()
}
}
#settle(url: string, result: TileLoadResult, epoch: number): void {
this.#active -= 1
if (result === 'ok' || result === 'denied') {
this.#states.set(url, result)
this.#attempts.delete(url)
this.#cancelRetry(url)
} else {
// Transient: retry with exponential backoff up to `maxAttempts`, then store the failure and
// wait for a new window or `retryFailed()` (reconnect). A 403 is a separate `denied` answer.
// 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.#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)
}
}