feat(client): name prompt, connection badge, reconnect and resync (#68)
T5 of the M4 client (spec #63). All of it at the existing seams: the pure reducer slice, the WS client and the browser e2e. - First sign-in: a live player with `me.name === null` gets a name prompt instead of the HUD and no Pixi stage (the server sends no scene until named). `player.setname` is acked before the second `hello` (#33); `name-taken`, `invalid` and `not-allowed` become visible text and the prompt stays put. Acceptance is followed by `hello` + the 6.3 resync, so the prompt is keyed on state and is asked once. - Badge (`#badge[data-state]`): connected / reconnecting / offline. Offline is driven by `navigator.onLine` (a phone with no network) and by terminal close outcomes; reconnecting keeps the stale map on screen. - Reconnect: a transport close after a live connection retries with 1/2/4/8/10 s base delays +/-20% jitter, then the cap. `revoked` and `proto-mismatch` stay terminal; pending `reqId`s die with the socket; the browser `online` event skips the rest of the wait. A drop does not clear the view: `hello` resets every slice and the resync rebuilds tokens, fog, explored, markers and lists. - Two devices on one player key both stay live and receive the same frames. Proof: new unit tests for the schedule/retry machine (`test/ws.test.ts`) and the badge/reconnect/name transitions (`test/reducer.test.ts`); new `client/e2e/session.test.mjs` runs the real server and TLS/HTTP2 vhost, kills and restarts the server under a live page, drops the browser network with `context.setOffline`, and asserts the full resync frames (roster, encountered, vision, explored, marker, token) plus two pages on one key. Refs #68
This commit is contained in:
+115
-6
@@ -1,11 +1,15 @@
|
||||
// The protocol client (DESIGN 6.2, 6.3, 6.5; spec #63 decision 14). It owns the socket, the `reqId`
|
||||
// counter and the pending-request map; it emits reducer events and never touches the DOM. The
|
||||
// socket factory and clock-free design make it unit-testable without a browser.
|
||||
// counter, the pending-request map and the reconnect schedule; it emits reducer events and never
|
||||
// touches the DOM. The socket factory, the clock and the random source are injectable, so the
|
||||
// backoff and the retry state machine are unit-testable without a browser and without waiting.
|
||||
//
|
||||
// Close mapping (6.5, FIXED #18): a server-initiated close is `closing {reason, code}` and then a
|
||||
// close frame the browser reports as 1005, so the reason always comes from the last `closing` frame.
|
||||
// `revoked` and `proto-mismatch` are terminal: this client does not reconnect to them. Reconnect
|
||||
// with backoff is T5 (#68); T4 only proves the outcome mapping.
|
||||
// `revoked` and `proto-mismatch` are terminal (the reducer goes to the sign-in page / reload and
|
||||
// this client stops). A close with no `closing` frame is a transport failure: the socket retries
|
||||
// with exponential backoff and jitter, because a flaky phone network must recover without a reload
|
||||
// (stories 7, 8). Pending reqIds are dropped with every connection (6.3); a `hello` on a live
|
||||
// connection does not drop them.
|
||||
|
||||
import type { AckFrame, CloseReason, ServerFrame } from './protocol.ts'
|
||||
import { encodeIntent, isAck, isClosing, parseServerFrame, wsUrl } from './protocol.ts'
|
||||
@@ -23,11 +27,53 @@ export type ClientEvent =
|
||||
| { type: 'open' }
|
||||
| { type: 'frame'; frame: ServerFrame }
|
||||
| { type: 'close'; reason: CloseReason | null; code: number | null }
|
||||
| { type: 'reconnecting'; attempt: number; delay: number }
|
||||
|
||||
/** The reconnect delays of DESIGN 6.3: 1/2/4/8/10 s, then the cap. Attempts are 1-based. */
|
||||
export const RECONNECT_BASE_DELAYS_MS = [1000, 2000, 4000, 8000, 10000] as const
|
||||
|
||||
/** Jitter is +/- this fraction of the base delay (story 8: "growing, jittered delays"). */
|
||||
export const RECONNECT_JITTER = 0.2
|
||||
|
||||
/** The un-jittered delay for a 1-based attempt number; past the last entry the cap holds. */
|
||||
export function reconnectBaseMs(attempt: number): number {
|
||||
const index = Math.min(Math.max(Math.floor(attempt), 1), RECONNECT_BASE_DELAYS_MS.length) - 1
|
||||
return RECONNECT_BASE_DELAYS_MS[index] ?? RECONNECT_BASE_DELAYS_MS[RECONNECT_BASE_DELAYS_MS.length - 1]!
|
||||
}
|
||||
|
||||
/** The next retry delay: the base schedule times a random factor in [1-jitter, 1+jitter). */
|
||||
export function backoffDelay(attempt: number, random: () => number = Math.random): number {
|
||||
const base = reconnectBaseMs(attempt)
|
||||
const factor = 1 - RECONNECT_JITTER + clamp(random()) * 2 * RECONNECT_JITTER
|
||||
return Math.round(base * factor)
|
||||
}
|
||||
|
||||
function clamp(value: number): number {
|
||||
if (!Number.isFinite(value)) return 0.5
|
||||
return Math.min(Math.max(value, 0), 1)
|
||||
}
|
||||
|
||||
/** `setTimeout`'s handle in the browser; tests substitute their own clock behind this type. */
|
||||
export type TimerHandle = number
|
||||
|
||||
export interface Timers {
|
||||
setTimeout(fn: () => void, ms: number): TimerHandle
|
||||
clearTimeout(handle: TimerHandle): void
|
||||
}
|
||||
|
||||
const defaultTimers: Timers = {
|
||||
setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms) as unknown as TimerHandle,
|
||||
clearTimeout: handle => globalThis.clearTimeout(handle),
|
||||
}
|
||||
|
||||
export interface ProtocolClientOptions {
|
||||
url?: string
|
||||
createSocket?: (url: string) => SocketLike
|
||||
onEvent: (event: ClientEvent) => void
|
||||
/** Transport failures retry by default (DESIGN 6.3); a terminal server outcome never does. */
|
||||
autoReconnect?: boolean
|
||||
random?: () => number
|
||||
timers?: Timers
|
||||
}
|
||||
|
||||
type Pending = {
|
||||
@@ -43,16 +89,26 @@ export class ProtocolClient {
|
||||
#url: string
|
||||
#createSocket: (url: string) => SocketLike
|
||||
#onEvent: (event: ClientEvent) => void
|
||||
#autoReconnect: boolean
|
||||
#random: () => number
|
||||
#timers: Timers
|
||||
#socket: SocketLike | null = null
|
||||
#nextReqId = 1
|
||||
#pending = new Map<number, Pending>()
|
||||
#lastClosing: { reason: CloseReason; code: number } | null = null
|
||||
#state: 'idle' | 'connecting' | 'open' | 'closed' = 'idle'
|
||||
/** A socket has opened at least once: only then can a transport close be a lost session. */
|
||||
#everOpened = false
|
||||
#attempt = 0
|
||||
#retryTimer: TimerHandle | null = null
|
||||
|
||||
constructor(options: ProtocolClientOptions) {
|
||||
this.#url = options.url ?? wsUrl()
|
||||
this.#createSocket = options.createSocket ?? defaultSocket
|
||||
this.#onEvent = options.onEvent
|
||||
this.#autoReconnect = options.autoReconnect ?? true
|
||||
this.#random = options.random ?? Math.random
|
||||
this.#timers = options.timers ?? defaultTimers
|
||||
}
|
||||
|
||||
get state(): 'idle' | 'connecting' | 'open' | 'closed' {
|
||||
@@ -63,15 +119,33 @@ export class ProtocolClient {
|
||||
return this.#pending.size
|
||||
}
|
||||
|
||||
/** The number of consecutive retries scheduled/failed since the last successful open. */
|
||||
get attempt(): number {
|
||||
return this.#attempt
|
||||
}
|
||||
|
||||
connect(): void {
|
||||
if (this.#state !== 'idle') return
|
||||
this.#state = 'connecting'
|
||||
const socket = this.#createSocket(this.#url)
|
||||
this.#lastClosing = null
|
||||
|
||||
let socket: SocketLike
|
||||
try {
|
||||
socket = this.#createSocket(this.#url)
|
||||
} catch {
|
||||
// A socket that cannot even be constructed is a failed upgrade, not a lost session: the
|
||||
// reducer sends a visitor with no session to the sign-in page (6.5 row 2).
|
||||
this.#state = 'closed'
|
||||
this.#onEvent({ type: 'close', reason: null, code: null })
|
||||
return
|
||||
}
|
||||
this.#socket = socket
|
||||
|
||||
socket.onopen = () => {
|
||||
if (this.#state !== 'connecting') return
|
||||
this.#state = 'open'
|
||||
this.#everOpened = true
|
||||
this.#attempt = 0
|
||||
this.#onEvent({ type: 'open' })
|
||||
}
|
||||
socket.onmessage = event => {
|
||||
@@ -93,10 +167,18 @@ export class ProtocolClient {
|
||||
}
|
||||
socket.onclose = event => {
|
||||
if (this.#state === 'closed') return
|
||||
this.#state = 'closed'
|
||||
const reason = this.#lastClosing?.reason ?? null
|
||||
const code = this.#lastClosing?.code ?? event.code ?? null
|
||||
this.#failPending(new Error(`connection closed (${reason ?? code ?? 'no code'})`))
|
||||
// A named reason always came from a `closing` frame: it is an application outcome, and
|
||||
// 6.5 says the client must stop for revoked/proto-mismatch/evicted/flood. Only a bare
|
||||
// transport close (reason null) is retried, and only after this client was live once.
|
||||
if (reason === null && this.#autoReconnect && this.#everOpened) {
|
||||
this.#onEvent({ type: 'close', reason, code })
|
||||
this.#scheduleRetry()
|
||||
return
|
||||
}
|
||||
this.#state = 'closed'
|
||||
this.#onEvent({ type: 'close', reason, code })
|
||||
}
|
||||
}
|
||||
@@ -124,7 +206,16 @@ export class ProtocolClient {
|
||||
})
|
||||
}
|
||||
|
||||
/** Retry at once instead of waiting out the backoff (used when the browser goes online). */
|
||||
retryNow(): void {
|
||||
if (this.#retryTimer === null) return
|
||||
this.#timers.clearTimeout(this.#retryTimer)
|
||||
this.#retryTimer = null
|
||||
this.connect()
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.#cancelRetry()
|
||||
if (this.#state === 'closed') return
|
||||
this.#state = 'closed'
|
||||
try {
|
||||
@@ -135,6 +226,24 @@ export class ProtocolClient {
|
||||
this.#failPending(new Error('connection closed by the client'))
|
||||
}
|
||||
|
||||
#scheduleRetry(): void {
|
||||
this.#attempt += 1
|
||||
const delay = backoffDelay(this.#attempt, this.#random)
|
||||
this.#state = 'idle' // connect() may run again; the view stays in the reducer meanwhile
|
||||
this.#socket = null
|
||||
this.#onEvent({ type: 'reconnecting', attempt: this.#attempt, delay })
|
||||
this.#retryTimer = this.#timers.setTimeout(() => {
|
||||
this.#retryTimer = null
|
||||
this.connect()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
#cancelRetry(): void {
|
||||
if (this.#retryTimer === null) return
|
||||
this.#timers.clearTimeout(this.#retryTimer)
|
||||
this.#retryTimer = null
|
||||
}
|
||||
|
||||
#failPending(error: Error): void {
|
||||
const pending = [...this.#pending.values()]
|
||||
this.#pending.clear()
|
||||
|
||||
Reference in New Issue
Block a user