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
352 lines
12 KiB
TypeScript
352 lines
12 KiB
TypeScript
import { describe, expect, it } from 'vitest'
|
|
import {
|
|
RECONNECT_BASE_DELAYS_MS,
|
|
RECONNECT_JITTER,
|
|
ProtocolClient,
|
|
backoffDelay,
|
|
reconnectBaseMs,
|
|
} from '../src/ws.ts'
|
|
import type { ClientEvent, SocketLike, Timers } from '../src/ws.ts'
|
|
|
|
class FakeSocket implements SocketLike {
|
|
onopen: (() => void) | null = null
|
|
onmessage: ((event: { data: unknown }) => void) | null = null
|
|
onclose: ((event: { code: number; reason: string }) => void) | null = null
|
|
onerror: ((event: unknown) => void) | null = null
|
|
sent: string[] = []
|
|
closed = false
|
|
|
|
send(data: string): void {
|
|
if (this.closed) throw new Error('socket is closed')
|
|
this.sent.push(data)
|
|
}
|
|
|
|
close(): void {
|
|
this.closed = true
|
|
}
|
|
|
|
open(): void {
|
|
this.onopen?.()
|
|
}
|
|
|
|
receive(body: unknown): void {
|
|
this.onmessage?.({ data: typeof body === 'string' ? body : JSON.stringify(body) })
|
|
}
|
|
|
|
serverClose(code = 1005, reason = ''): void {
|
|
this.closed = true
|
|
this.onclose?.({ code, reason })
|
|
}
|
|
}
|
|
|
|
function connect(): {
|
|
client: ProtocolClient
|
|
socket: FakeSocket
|
|
events: ClientEvent[]
|
|
} {
|
|
const socket = new FakeSocket()
|
|
const events: ClientEvent[] = []
|
|
const client = new ProtocolClient({
|
|
url: 'wss://test/ws?proto=2',
|
|
createSocket: () => socket,
|
|
onEvent: event => events.push(event),
|
|
})
|
|
client.connect()
|
|
socket.open()
|
|
return { client, socket, events }
|
|
}
|
|
|
|
describe('protocol client', () => {
|
|
it('parses text frames and ignores binary or unreadable ones', () => {
|
|
const { socket, events } = connect()
|
|
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: null } })
|
|
socket.receive('not json')
|
|
socket.onmessage?.({ data: new Uint8Array([1, 2]) })
|
|
expect(events.filter(event => event.type === 'frame')).toHaveLength(1)
|
|
})
|
|
|
|
it('correlates one ack per reqId and ignores an unknown ack', async () => {
|
|
const { client, socket } = connect()
|
|
const first = client.send('conn.ping', { ts: 11 })
|
|
const second = client.send('conn.ping', { ts: 12 })
|
|
expect(client.pendingCount).toBe(2)
|
|
const sent = socket.sent.map(raw => JSON.parse(raw) as { t: string; reqId: number; ts: number })
|
|
expect(sent.map(intent => intent.t)).toEqual(['conn.ping', 'conn.ping'])
|
|
expect(sent[0]?.reqId).toBe(1)
|
|
expect(sent[1]?.reqId).toBe(2)
|
|
|
|
socket.receive({ t: 'ack', n: 1, reqId: 2, ok: true, ts: 12 })
|
|
socket.receive({ t: 'ack', n: 2, reqId: 99, ok: true })
|
|
expect(client.pendingCount).toBe(1)
|
|
await expect(second).resolves.toMatchObject({ reqId: 2, ok: true })
|
|
|
|
socket.receive({ t: 'ack', n: 3, reqId: 1, ok: false, code: 'invalid' })
|
|
await expect(first).resolves.toMatchObject({ reqId: 1, ok: false, code: 'invalid' })
|
|
expect(client.pendingCount).toBe(0)
|
|
})
|
|
|
|
it('keeps pending requests across a hello on a live connection (6.3)', async () => {
|
|
const { client, socket } = connect()
|
|
const pending = client.send('player.setname', { name: 'Ann' })
|
|
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: 'Ann' } })
|
|
expect(client.pendingCount).toBe(1)
|
|
socket.receive({ t: 'ack', n: 2, reqId: 1, ok: true })
|
|
await expect(pending).resolves.toMatchObject({ ok: true })
|
|
})
|
|
|
|
it('drops pending requests with the connection (6.3)', async () => {
|
|
const { client, socket } = connect()
|
|
const pending = client.send('conn.ping', { ts: 1 })
|
|
socket.serverClose(1006)
|
|
expect(client.pendingCount).toBe(0)
|
|
await expect(pending).rejects.toThrow(/closed/)
|
|
})
|
|
|
|
it('reads a server close reason from the last closing frame (6.5, FIXED #18)', () => {
|
|
const { socket, events } = connect()
|
|
socket.receive({ t: 'closing', n: 2, reason: 'revoked', code: 4001 })
|
|
socket.serverClose(1005)
|
|
expect(events.at(-1)).toEqual({ type: 'close', reason: 'revoked', code: 4001 })
|
|
})
|
|
|
|
it('treats a close without a closing frame as a transport failure', () => {
|
|
const { client, sockets, events, timers } = reconnectingClient()
|
|
client.connect()
|
|
sockets[0]!.open()
|
|
sockets[0]!.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: null } })
|
|
sockets[0]!.serverClose(1006)
|
|
expect(events.find(event => event.type === 'close')).toEqual({
|
|
type: 'close',
|
|
reason: null,
|
|
code: 1006,
|
|
})
|
|
// It is a transport failure, so the client also schedules a retry (T5, #68).
|
|
expect(events.some(event => event.type === 'reconnecting')).toBe(true)
|
|
expect(timers.size).toBe(1)
|
|
client.close()
|
|
})
|
|
|
|
it('does not reconnect to a terminal outcome (single connect)', () => {
|
|
const socket = new FakeSocket()
|
|
const sockets: FakeSocket[] = [socket]
|
|
const client = new ProtocolClient({
|
|
url: 'wss://test/ws?proto=2',
|
|
createSocket: () => socket,
|
|
onEvent: () => {},
|
|
})
|
|
client.connect()
|
|
socket.open()
|
|
socket.receive({ t: 'closing', n: 1, reason: 'proto-mismatch', code: 4003 })
|
|
socket.serverClose(1005)
|
|
client.connect() // a no-op once closed
|
|
expect(sockets).toHaveLength(1)
|
|
expect(client.state).toBe('closed')
|
|
})
|
|
|
|
it('ignores a frame that arrives after the client closed the socket', () => {
|
|
const { client, socket, events } = connect()
|
|
client.close()
|
|
const before = events.length
|
|
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: null } })
|
|
expect(events).toHaveLength(before)
|
|
})
|
|
|
|
it('refuses to send before the socket opens', async () => {
|
|
const socket = new FakeSocket()
|
|
const client = new ProtocolClient({
|
|
url: 'wss://test/ws?proto=2',
|
|
createSocket: () => socket,
|
|
onEvent: () => {},
|
|
})
|
|
client.connect()
|
|
await expect(client.send('conn.ping', { ts: 1 })).rejects.toThrow(/not connected/)
|
|
})
|
|
})
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// T5 (#68): reconnect with a growing, jittered delay.
|
|
|
|
/** A clock the test advances by hand: no real timers, so the schedule is exact. */
|
|
class ManualTimers implements Timers {
|
|
#next = 1
|
|
pending = new Map<number, { fn: () => void; ms: number }>()
|
|
|
|
setTimeout(fn: () => void, ms: number): number {
|
|
const id = this.#next++
|
|
this.pending.set(id, { fn, ms })
|
|
return id
|
|
}
|
|
|
|
clearTimeout(handle: number): void {
|
|
this.pending.delete(handle)
|
|
}
|
|
|
|
get size(): number {
|
|
return this.pending.size
|
|
}
|
|
|
|
nextDelay(): number | null {
|
|
const first = this.pending.values().next()
|
|
return first.done ? null : first.value.ms
|
|
}
|
|
|
|
runNext(): void {
|
|
const first = this.pending.entries().next()
|
|
if (first.done) throw new Error('no scheduled timer')
|
|
this.pending.delete(first.value[0])
|
|
first.value[1].fn()
|
|
}
|
|
}
|
|
|
|
function reconnectingClient(options: { autoReconnect?: boolean; random?: () => number } = {}): {
|
|
client: ProtocolClient
|
|
sockets: FakeSocket[]
|
|
events: ClientEvent[]
|
|
timers: ManualTimers
|
|
} {
|
|
const sockets: FakeSocket[] = []
|
|
const events: ClientEvent[] = []
|
|
const timers = new ManualTimers()
|
|
const client = new ProtocolClient({
|
|
url: 'wss://test/ws?proto=2',
|
|
createSocket: () => {
|
|
const socket = new FakeSocket()
|
|
sockets.push(socket)
|
|
return socket
|
|
},
|
|
onEvent: event => events.push(event),
|
|
timers,
|
|
random: options.random ?? (() => 0.5),
|
|
...(options.autoReconnect === undefined ? {} : { autoReconnect: options.autoReconnect }),
|
|
})
|
|
return { client, sockets, events, timers }
|
|
}
|
|
|
|
const helloFrame = { t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: 'Ann' } }
|
|
|
|
describe('reconnect backoff (6.3, story 8)', () => {
|
|
it('uses the 1/2/4/8/10 s base schedule with bounded jitter', () => {
|
|
expect(RECONNECT_BASE_DELAYS_MS).toEqual([1000, 2000, 4000, 8000, 10000])
|
|
expect([1, 2, 3, 4, 5, 6, 99].map(reconnectBaseMs)).toEqual([
|
|
1000, 2000, 4000, 8000, 10000, 10000, 10000,
|
|
])
|
|
for (let attempt = 1; attempt <= 6; attempt += 1) {
|
|
const base = reconnectBaseMs(attempt)
|
|
expect(backoffDelay(attempt, () => 0.5)).toBe(base)
|
|
expect(backoffDelay(attempt, () => 0)).toBe(base - base * RECONNECT_JITTER)
|
|
expect(backoffDelay(attempt, () => 0.999999)).toBeLessThanOrEqual(
|
|
Math.round(base * (1 + RECONNECT_JITTER)),
|
|
)
|
|
}
|
|
// Jitter is real, not cosmetic: two random draws give different delays, and the cap still holds.
|
|
expect(backoffDelay(1, () => 0)).not.toBe(backoffDelay(1, () => 0.9))
|
|
expect(backoffDelay(99, () => 0.999999)).toBeLessThanOrEqual(
|
|
Math.round(10000 * (1 + RECONNECT_JITTER)),
|
|
)
|
|
})
|
|
|
|
it('reconnects after a transport close and drops the pending reqIds with it', async () => {
|
|
const { client, sockets, events, timers } = reconnectingClient({ random: () => 0.5 })
|
|
client.connect()
|
|
sockets[0]!.open()
|
|
sockets[0]!.receive(helloFrame)
|
|
const pending = client.send('conn.ping', { ts: 1 })
|
|
expect(client.pendingCount).toBe(1)
|
|
|
|
sockets[0]!.serverClose(1006)
|
|
|
|
expect(client.pendingCount).toBe(0)
|
|
await expect(pending).rejects.toThrow(/closed/)
|
|
expect(events.filter(event => event.type === 'close')).toEqual([
|
|
{ type: 'close', reason: null, code: 1006 },
|
|
])
|
|
const reconnecting = events.filter(event => event.type === 'reconnecting')
|
|
expect(reconnecting).toEqual([{ type: 'reconnecting', attempt: 1, delay: 1000 }])
|
|
expect(timers.size).toBe(1)
|
|
|
|
timers.runNext()
|
|
expect(sockets).toHaveLength(2)
|
|
sockets[1]!.open()
|
|
sockets[1]!.receive(helloFrame)
|
|
expect(events.filter(event => event.type === 'open')).toHaveLength(2)
|
|
|
|
// The backoff resets after a successful reconnect: the next drop starts again at 1 s.
|
|
sockets[1]!.serverClose(1006)
|
|
expect(events.filter(event => event.type === 'reconnecting').at(-1)).toEqual({
|
|
type: 'reconnecting',
|
|
attempt: 1,
|
|
delay: 1000,
|
|
})
|
|
})
|
|
|
|
it('grows the delay while attempts keep failing', () => {
|
|
const { client, sockets, events, timers } = reconnectingClient({ random: () => 0.5 })
|
|
client.connect()
|
|
sockets[0]!.open()
|
|
sockets[0]!.receive(helloFrame)
|
|
sockets[0]!.serverClose(1006)
|
|
for (const attempt of [1, 2, 3, 4, 5]) {
|
|
expect(events.filter(event => event.type === 'reconnecting').at(-1)).toMatchObject({
|
|
attempt,
|
|
delay: reconnectBaseMs(attempt),
|
|
})
|
|
timers.runNext()
|
|
sockets.at(-1)!.serverClose(1006) // the retry never got a hello
|
|
}
|
|
expect(events.filter(event => event.type === 'reconnecting').at(-1)).toMatchObject({
|
|
attempt: 6,
|
|
delay: 10000,
|
|
})
|
|
})
|
|
|
|
it('does not reconnect after a terminal server outcome', () => {
|
|
for (const reason of ['revoked', 'proto-mismatch', 'evicted', 'malformed-flood'] as const) {
|
|
const { client, sockets, events, timers } = reconnectingClient()
|
|
client.connect()
|
|
sockets[0]!.open()
|
|
sockets[0]!.receive(helloFrame)
|
|
sockets[0]!.receive({ t: 'closing', n: 2, reason, code: 4000 })
|
|
sockets[0]!.serverClose(1005)
|
|
expect(events.some(event => event.type === 'reconnecting')).toBe(false)
|
|
expect(timers.size).toBe(0)
|
|
expect(client.state).toBe('closed')
|
|
}
|
|
})
|
|
|
|
it('does not reconnect before the first open (a refused upgrade)', () => {
|
|
const { client, sockets, events, timers } = reconnectingClient()
|
|
client.connect()
|
|
sockets[0]!.serverClose(1006)
|
|
expect(events.some(event => event.type === 'reconnecting')).toBe(false)
|
|
expect(timers.size).toBe(0)
|
|
})
|
|
|
|
it('does not reconnect when autoReconnect is off', () => {
|
|
const { client, sockets, events, timers } = reconnectingClient({ autoReconnect: false })
|
|
client.connect()
|
|
sockets[0]!.open()
|
|
sockets[0]!.receive(helloFrame)
|
|
sockets[0]!.serverClose(1006)
|
|
expect(events.some(event => event.type === 'reconnecting')).toBe(false)
|
|
expect(timers.size).toBe(0)
|
|
})
|
|
|
|
it('retryNow skips the wait and a manual close cancels the retry', () => {
|
|
const { client, sockets, timers } = reconnectingClient()
|
|
client.connect()
|
|
sockets[0]!.open()
|
|
sockets[0]!.receive(helloFrame)
|
|
sockets[0]!.serverClose(1006)
|
|
expect(timers.size).toBe(1)
|
|
client.retryNow()
|
|
expect(timers.size).toBe(0)
|
|
expect(sockets).toHaveLength(2)
|
|
|
|
sockets[1]!.serverClose(1006)
|
|
expect(timers.size).toBe(1)
|
|
client.close()
|
|
expect(timers.size).toBe(0)
|
|
expect(client.state).toBe('closed')
|
|
})
|
|
})
|