Drag a controlled token (GM: any token) at <=20 Hz plus a final send on release; the sprite follows the pointer while authoritative frames are ignored for drawing. Uniform move nacks roll back with a short tween (on release if still dragging), rate-limited acks drop quietly, and pending reqIds die with the connection. - slices/move.ts: pure drag/pending/ack state machine at the reducer seam - render/modules/drag.ts: canvas pointer input, capture-phase so token drag wins over pan/pinch (#69); sends via the new intents bridge - tokens renderer draws the optimistic/confirmed position and tweens the rollback - intents.ts + ws.send onReqId: one reqId-keyed sender for render modules - e2e: drag persists after reload, wall refusal tween, GM move mid-drag, reconnect mid-drag dropping the pending map
261 lines
9.5 KiB
TypeScript
261 lines
9.5 KiB
TypeScript
// The protocol client (DESIGN 6.2, 6.3, 6.5; spec #63 decision 14). It owns the socket, the `reqId`
|
|
// 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 (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'
|
|
|
|
export interface SocketLike {
|
|
send(data: string): void
|
|
close(code?: number, reason?: string): void
|
|
onopen: (() => void) | null
|
|
onmessage: ((event: { data: unknown }) => void) | null
|
|
onclose: ((event: { code: number; reason: string }) => void) | null
|
|
onerror: ((event: unknown) => void) | null
|
|
}
|
|
|
|
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 = {
|
|
resolve: (ack: AckFrame) => void
|
|
reject: (error: Error) => void
|
|
}
|
|
|
|
function defaultSocket(url: string): SocketLike {
|
|
return new WebSocket(url) as unknown as SocketLike
|
|
}
|
|
|
|
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' {
|
|
return this.#state
|
|
}
|
|
|
|
get pendingCount(): number {
|
|
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'
|
|
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 => {
|
|
if (this.#state === 'closed') return // a frame in flight after the client closed
|
|
const frame = parseServerFrame(event.data)
|
|
if (!frame) return // binary or unreadable: 6.2 says ignore what cannot be read
|
|
if (isClosing(frame)) this.#lastClosing = { reason: frame.reason, code: frame.code }
|
|
if (isAck(frame)) {
|
|
const pending = this.#pending.get(frame.reqId)
|
|
if (pending) {
|
|
this.#pending.delete(frame.reqId)
|
|
pending.resolve(frame)
|
|
}
|
|
}
|
|
this.#onEvent({ type: 'frame', frame })
|
|
}
|
|
socket.onerror = () => {
|
|
// The browser follows an error with a close; mapping the outcome there keeps it single.
|
|
}
|
|
socket.onclose = event => {
|
|
if (this.#state === 'closed') return
|
|
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 })
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Send one intent and resolve with its single `ack` (DESIGN 6 Conventions: exactly one ack per
|
|
* readable intent, whatever the outcome). Pending reqIds die with the connection (6.3), and a
|
|
* `hello` on a live connection does not drop them.
|
|
*
|
|
* `onReqId` is told the request id once the frame has left the socket, so a caller that must
|
|
* match the ack itself (the drag's `token.move`, #72) can record it before the reply can arrive.
|
|
*/
|
|
send(
|
|
t: string,
|
|
fields: Record<string, unknown> = {},
|
|
onReqId?: (reqId: number) => void,
|
|
): Promise<AckFrame> {
|
|
const socket = this.#socket
|
|
if (this.#state !== 'open' || !socket) {
|
|
return Promise.reject(new Error('not connected'))
|
|
}
|
|
const reqId = this.#nextReqId++
|
|
const frame = encodeIntent(t, reqId, fields)
|
|
return new Promise<AckFrame>((resolve, reject) => {
|
|
this.#pending.set(reqId, { resolve, reject })
|
|
try {
|
|
socket.send(frame)
|
|
onReqId?.(reqId)
|
|
} catch (error) {
|
|
this.#pending.delete(reqId)
|
|
reject(error instanceof Error ? error : new Error(String(error)))
|
|
}
|
|
})
|
|
}
|
|
|
|
/** 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 {
|
|
this.#socket?.close()
|
|
} catch {
|
|
// A socket that is already gone is the outcome we wanted.
|
|
}
|
|
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()
|
|
for (const entry of pending) entry.reject(error)
|
|
}
|
|
}
|