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:
+140
-21
@@ -1,31 +1,57 @@
|
||||
// The tile scheduler (#69, spec #63 decision 12). Pure: the loader is injected, so the concurrency,
|
||||
// cache and denial rules are unit-tested without a browser or a GPU.
|
||||
// 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 (8) requests in flight;
|
||||
// - the wanted list is the viewport plus one tile of margin, in viewport order;
|
||||
// - 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`/`404` is a permanent `denied` answer: never retried in a loop (the server said no);
|
||||
// - a transient `error` is retried only when a later viewport sync asks for the tile again;
|
||||
// - 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;
|
||||
// - 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.
|
||||
// prefetches beyond the margin.
|
||||
|
||||
import type { SceneInfo } from './protocol.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 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 {
|
||||
@@ -56,12 +82,32 @@ export function tilesForCells(
|
||||
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[] = []
|
||||
@@ -73,6 +119,9 @@ export class TileScheduler {
|
||||
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 {
|
||||
@@ -83,7 +132,7 @@ export class TileScheduler {
|
||||
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 {
|
||||
// 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.
|
||||
@@ -104,8 +153,13 @@ export class TileScheduler {
|
||||
.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') this.#states.delete(url)
|
||||
else if (existing !== undefined) continue
|
||||
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)
|
||||
}
|
||||
@@ -117,12 +171,43 @@ export class TileScheduler {
|
||||
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 {
|
||||
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 = []
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -168,9 +253,10 @@ export class TileScheduler {
|
||||
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),
|
||||
() => this.#settle(url, 'error'),
|
||||
result => this.#settle(url, result, epoch),
|
||||
() => this.#settle(url, 'error', epoch),
|
||||
)
|
||||
}
|
||||
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
|
||||
if (result === 'ok' || result === 'denied') {
|
||||
this.#states.set(url, result)
|
||||
this.#attempts.delete(url)
|
||||
this.#cancelRetry(url)
|
||||
} else {
|
||||
// Transient: remember the failure, but never retry it on the same viewport; only a new
|
||||
// window or `retryFailed()` (reconnect) asks again. A denied 403 is never retried at all.
|
||||
this.#states.set(url, 'error')
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user