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:
+209
-5
@@ -1,6 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ProtocolClient } from '../src/ws.ts'
|
||||
import type { ClientEvent, SocketLike } from '../src/ws.ts'
|
||||
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
|
||||
@@ -104,9 +110,20 @@ describe('protocol client', () => {
|
||||
})
|
||||
|
||||
it('treats a close without a closing frame as a transport failure', () => {
|
||||
const { socket, events } = connect()
|
||||
socket.serverClose(1006)
|
||||
expect(events.at(-1)).toEqual({ type: 'close', reason: null, code: 1006 })
|
||||
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)', () => {
|
||||
@@ -145,3 +162,190 @@ describe('protocol client', () => {
|
||||
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')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user