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:
+28
-1
@@ -28,7 +28,7 @@ is wiring:
|
|||||||
| `src/protocol.ts` | Wire types, envelope/ack/closing guards, intent encoding, `/ws?proto=2` URL. Pure. |
|
| `src/protocol.ts` | Wire types, envelope/ack/closing guards, intent encoding, `/ws?proto=2` URL. Pure. |
|
||||||
| `src/reducer.ts` | `RootState`, phase machine (`boot/connecting/signin/live/reload/offline`), `hello` reset, slice registry. Pure. |
|
| `src/reducer.ts` | `RootState`, phase machine (`boot/connecting/signin/live/reload/offline`), `hello` reset, slice registry. Pure. |
|
||||||
| `src/slices/*.ts` | Append-only domain state (roster today; fog, tokens, walls, panels later). |
|
| `src/slices/*.ts` | Append-only domain state (roster today; fog, tokens, walls, panels later). |
|
||||||
| `src/ws.ts` | Socket, `reqId` counter, pending map, close-code mapping. No DOM. |
|
| `src/ws.ts` | Socket, `reqId` counter, pending map, close-code mapping, backoff and retry. No DOM. |
|
||||||
| `src/shell.ts` | Sign-in, HUD/roster, fatal screens. Plain DOM, `textContent` only. |
|
| `src/shell.ts` | Sign-in, HUD/roster, fatal screens. Plain DOM, `textContent` only. |
|
||||||
| `src/render/stage.ts` | One Pixi `Application`, one world container, fixed layers. Pixi lives here and in modules only. |
|
| `src/render/stage.ts` | One Pixi `Application`, one world container, fixed layers. Pixi lives here and in modules only. |
|
||||||
| `src/render/modules/*.ts` | Append-only render modules. |
|
| `src/render/modules/*.ts` | Append-only render modules. |
|
||||||
@@ -72,3 +72,30 @@ change them only if a slice needs a new *core* event, and say so in the PR.
|
|||||||
unknown key is shown as the same "Key not recognised." (DESIGN §3.2, story 3).
|
unknown key is shown as the same "Key not recognised." (DESIGN §3.2, story 3).
|
||||||
- No game data (and no Pixi `Application`) exists before a live `hello`; a visitor without a session
|
- No game data (and no Pixi `Application`) exists before a live `hello`; a visitor without a session
|
||||||
only sees the sign-in page.
|
only sees the sign-in page.
|
||||||
|
|
||||||
|
## Name, badge and reconnect (T5, #68)
|
||||||
|
|
||||||
|
- **First sign-in name prompt.** A live player with `me.name === null` gets the `#name` section
|
||||||
|
instead of the HUD, and no Pixi stage (the server sends no scene, no state, until named). Submitting
|
||||||
|
sends `player.setname`; the server acks *before* the second `hello` (FIXED #33), so a refusal's
|
||||||
|
code becomes visible text on the prompt (`name-taken` → "That name is taken. Choose another.",
|
||||||
|
`invalid` and `not-allowed` have their own copy) and an acceptance is followed by the `hello` that
|
||||||
|
resets every slice plus the 6.3 resync. The prompt is keyed on state, so it cannot come back and
|
||||||
|
survives a reload with the same session.
|
||||||
|
- **Badge** (`#badge[data-state]`): `connected` while live; `reconnecting` while the socket backs
|
||||||
|
off, with the stale map staying on screen; `offline` when the browser reports no network
|
||||||
|
(`navigator.onLine`/`online`/`offline` events) or after a terminal outcome (`evicted`,
|
||||||
|
`malformed-flood`, `server-shutdown`). Hidden on boot, sign-in and reload.
|
||||||
|
- **Reconnect** (DESIGN 6.3): a transport close (no `closing` frame) after a connection has been
|
||||||
|
live retries with `backoffDelay`: base 1/2/4/8/10 s then the cap, ±20 % jitter
|
||||||
|
(`RECONNECT_BASE_DELAYS_MS`, `RECONNECT_JITTER`). Terminal reasons never retry: `revoked` →
|
||||||
|
sign-in, `proto-mismatch` → reload. Pending `reqId`s die with the socket; a browser `online` event
|
||||||
|
calls `retryNow()` to skip the rest of the wait. The view is **not** cleared on a drop: `hello` is
|
||||||
|
the reset point, and the resync that follows rebuilds tokens, fog, explored, markers and lists.
|
||||||
|
- **Two devices** of one player both stay live and receive the same frame stream (each connection
|
||||||
|
has its own `known` table, DESIGN 6.3).
|
||||||
|
- **Proof**: `test/ws.test.ts` (schedule, retry state machine, pending drop) and
|
||||||
|
`test/reducer.test.ts` (badge transitions, reconnect reset, name errors) are the unit seam;
|
||||||
|
`e2e/session.test.mjs` kills and restarts the real server under a live page, drops the browser
|
||||||
|
network with `context.setOffline`, asserts the badge transitions and the full resync frames, and
|
||||||
|
runs two pages on one key.
|
||||||
|
|||||||
@@ -0,0 +1,284 @@
|
|||||||
|
// T5 (#68, TESTING 10.3): the name prompt, the connection badge, reconnect + full resync and two
|
||||||
|
// devices on one player key. Everything runs against the real server through the TLS/HTTP2 test
|
||||||
|
// nginx; the browser's own WebSocket is wrapped only to *record* frames (the app is untouched), so
|
||||||
|
// the resync assertions read the real wire.
|
||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { createPlayer, namePlayer } from '../../tools/lib.mjs'
|
||||||
|
import { openAs, startServer, stopServer } from '../../tools/withserver.mjs'
|
||||||
|
import {
|
||||||
|
launchBrowser,
|
||||||
|
newPage,
|
||||||
|
signIn,
|
||||||
|
waitForHidden,
|
||||||
|
waitForText,
|
||||||
|
waitForVisible,
|
||||||
|
withStack,
|
||||||
|
} from './stack.mjs'
|
||||||
|
|
||||||
|
/** Record every WS frame/close on `window.__wsLog` without changing what the app sees. */
|
||||||
|
async function recordSockets(page) {
|
||||||
|
await page.addInitScript(() => {
|
||||||
|
window.__wsLog = { sockets: 0, frames: [], closes: [] }
|
||||||
|
const Native = window.WebSocket
|
||||||
|
class RecordingSocket extends Native {
|
||||||
|
constructor(url, protocols) {
|
||||||
|
super(url, protocols)
|
||||||
|
window.__wsLog.sockets += 1
|
||||||
|
this.addEventListener('message', event => {
|
||||||
|
try {
|
||||||
|
window.__wsLog.frames.push(JSON.parse(event.data))
|
||||||
|
} catch {
|
||||||
|
// a non-JSON frame is not state; the client ignores it too
|
||||||
|
}
|
||||||
|
})
|
||||||
|
this.addEventListener('close', event => {
|
||||||
|
window.__wsLog.closes.push({ code: event.code, reason: event.reason })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.WebSocket = RecordingSocket
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const frames = page => page.evaluate(() => window.__wsLog.frames)
|
||||||
|
const frameCount = async page => (await frames(page)).length
|
||||||
|
|
||||||
|
async function waitForFrame(page, predicate, timeout = 20000) {
|
||||||
|
await page.waitForFunction(predicate, null, { timeout })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForBadge(page, state, timeout = 30000) {
|
||||||
|
await page.locator(`#badge[data-state="${state}"]`).waitFor({ state: 'visible', timeout })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function gmWorld(origin, gmKey) {
|
||||||
|
const gm = await openAs(origin, gmKey)
|
||||||
|
const hello = await gm.ws.waitText('hello')
|
||||||
|
const walls = await gm.ws.waitText('walls')
|
||||||
|
return { ...gm, hello, scene: walls.scene }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('first sign-in asks once for a name and shows a taken name', { timeout: 120000 }, async () => {
|
||||||
|
await withStack(async ({ origin, gmKey }) => {
|
||||||
|
const gm = await openAs(origin, gmKey)
|
||||||
|
await gm.ws.waitText('hello')
|
||||||
|
const alice = await createPlayer(gm.ws)
|
||||||
|
await namePlayer(origin, alice.key, 'Alice')
|
||||||
|
const unnamed = await createPlayer(gm.ws)
|
||||||
|
gm.ws.close()
|
||||||
|
|
||||||
|
const browser = await launchBrowser()
|
||||||
|
try {
|
||||||
|
const { page } = await newPage(browser)
|
||||||
|
await page.goto(`${origin}/`)
|
||||||
|
await waitForVisible(page, '#signin')
|
||||||
|
await signIn(page, unnamed.key)
|
||||||
|
|
||||||
|
// Stories 5: the prompt, and no game data (canvas/HUD) before the name is accepted.
|
||||||
|
await waitForVisible(page, '#name')
|
||||||
|
assert.equal(await page.locator('#stage canvas').count(), 0)
|
||||||
|
assert.equal(await page.locator('#hud').isVisible(), false)
|
||||||
|
assert.equal(await page.locator('#name-error').isVisible(), false)
|
||||||
|
|
||||||
|
// Story 6: a taken name is refused with a visible reason, and the prompt stays.
|
||||||
|
await page.fill('#name-input', 'alice')
|
||||||
|
await page.click('#name-submit')
|
||||||
|
await waitForText(page, '#name-error', /taken/i)
|
||||||
|
assert.equal(await page.locator('#name').isVisible(), true)
|
||||||
|
|
||||||
|
// A free name lands on the map; `hello` (name set) + the resync rebuild the view.
|
||||||
|
await page.fill('#name-input', 'Bob')
|
||||||
|
await page.click('#name-submit')
|
||||||
|
await waitForVisible(page, '#hud')
|
||||||
|
await waitForVisible(page, '#stage canvas')
|
||||||
|
await waitForText(page, '#me', /^Bob$/)
|
||||||
|
await waitForText(page, '#roster', /Bob/)
|
||||||
|
await waitForBadge(page, 'connected')
|
||||||
|
await waitForHidden(page, '#name')
|
||||||
|
|
||||||
|
// Asked once: a reload with the same session comes straight back to the table.
|
||||||
|
await page.reload()
|
||||||
|
await waitForVisible(page, '#hud')
|
||||||
|
await waitForText(page, '#me', /^Bob$/)
|
||||||
|
await waitForHidden(page, '#name')
|
||||||
|
await waitForBadge(page, 'connected')
|
||||||
|
} finally {
|
||||||
|
await browser.close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a killed server under a live player: badge reconnecting, then a full resync', { timeout: 180000 }, async () => {
|
||||||
|
await withStack(async ({ origin, gmKey, server }) => {
|
||||||
|
const gm = await gmWorld(origin, gmKey)
|
||||||
|
const player = await createPlayer(gm.ws)
|
||||||
|
await namePlayer(origin, player.key, 'Ann')
|
||||||
|
// The view the resync must rebuild: a controlled token (vision + explored), another token in
|
||||||
|
// sight (encountered + token) and a player-marked window (marker).
|
||||||
|
const own = await gm.ws.request({
|
||||||
|
t: 'token.create', scene: gm.scene, kind: 'pc', pos: [400, 400],
|
||||||
|
descriptive_name: 'Ann', actual_name: 'Ann', controller: player.id,
|
||||||
|
})
|
||||||
|
assert.equal(own.ok, true)
|
||||||
|
const npc = await gm.ws.request({
|
||||||
|
t: 'token.create', scene: gm.scene, kind: 'npc', pos: [460, 400],
|
||||||
|
descriptive_name: 'Rat', actual_name: 'Rat',
|
||||||
|
})
|
||||||
|
assert.equal(npc.ok, true)
|
||||||
|
const windowAck = await gm.ws.request({
|
||||||
|
t: 'wall.add', scene: gm.scene, a: [430, 360], b: [430, 440], preset: 'window',
|
||||||
|
})
|
||||||
|
assert.equal(windowAck.ok, true)
|
||||||
|
gm.ws.close()
|
||||||
|
|
||||||
|
const browser = await launchBrowser()
|
||||||
|
let restarted = null
|
||||||
|
try {
|
||||||
|
const { page } = await newPage(browser)
|
||||||
|
await recordSockets(page)
|
||||||
|
await page.goto(`${origin}/`)
|
||||||
|
await waitForVisible(page, '#signin')
|
||||||
|
await signIn(page, player.key)
|
||||||
|
await waitForVisible(page, '#hud')
|
||||||
|
await waitForBadge(page, 'connected')
|
||||||
|
|
||||||
|
// The first connect already carries the full view; wait for all of it before the drop.
|
||||||
|
await waitForFrame(page, () => {
|
||||||
|
const seen = new Set((window.__wsLog?.frames ?? []).map(frame => frame.t))
|
||||||
|
return ['hello', 'roster', 'encountered', 'vision', 'explored', 'marker', 'token']
|
||||||
|
.every(type => seen.has(type))
|
||||||
|
})
|
||||||
|
const before = await frameCount(page)
|
||||||
|
|
||||||
|
await stopServer(server)
|
||||||
|
// Story 7/8: the map stays up (stale) and the badge says reconnecting, with no reload.
|
||||||
|
await waitForBadge(page, 'reconnecting')
|
||||||
|
assert.equal(await page.locator('#stage canvas').count(), 1)
|
||||||
|
assert.equal(await page.locator('#signin').isVisible(), false)
|
||||||
|
|
||||||
|
// Restart the real server on the same port and state (sessions are durable, DESIGN 4.4).
|
||||||
|
restarted = await startServer({
|
||||||
|
stateDir: server.stateDir,
|
||||||
|
port: server.port,
|
||||||
|
publicOrigin: server.publicOrigin,
|
||||||
|
})
|
||||||
|
await waitForBadge(page, 'connected', 60000)
|
||||||
|
|
||||||
|
// Story 11: the reconnect's `hello` is followed by the whole 6.3 resync, not a stale diff.
|
||||||
|
await page.waitForFunction(
|
||||||
|
beforeIndex => {
|
||||||
|
const log = window.__wsLog.frames
|
||||||
|
const helloAt = log.findIndex((frame, index) => index >= beforeIndex && frame.t === 'hello')
|
||||||
|
if (helloAt < 0) return false
|
||||||
|
const after = log.slice(helloAt)
|
||||||
|
const seen = new Set(after.map(frame => frame.t))
|
||||||
|
return ['roster', 'encountered', 'vision', 'explored', 'marker', 'token']
|
||||||
|
.every(type => seen.has(type))
|
||||||
|
},
|
||||||
|
before,
|
||||||
|
{ timeout: 30000 },
|
||||||
|
)
|
||||||
|
const log = await frames(page)
|
||||||
|
const helloAt = log.findLastIndex(frame => frame.t === 'hello')
|
||||||
|
const after = log.slice(helloAt)
|
||||||
|
const full = type => after.find(frame => frame.t === type)
|
||||||
|
assert.equal(full('explored')?.full, true, 'explored comes back as a full snapshot')
|
||||||
|
assert.equal(full('marker')?.full, true, 'markers come back as a full snapshot')
|
||||||
|
assert.equal(full('encountered')?.full, true, 'the encountered list comes back full')
|
||||||
|
assert.ok(after.some(frame => frame.t === 'token'), 'tokens come back')
|
||||||
|
assert.ok(after.some(frame => frame.t === 'vision'), 'fog/vision comes back')
|
||||||
|
assert.match(await page.textContent('#roster'), /Ann/)
|
||||||
|
assert.equal(await page.locator('#hud').isVisible(), true)
|
||||||
|
} finally {
|
||||||
|
if (restarted) await stopServer(restarted)
|
||||||
|
await browser.close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a dropped network is offline, and coming back reconnects to the same view', { timeout: 120000 }, async () => {
|
||||||
|
await withStack(async ({ origin, gmKey }) => {
|
||||||
|
const gm = await openAs(origin, gmKey)
|
||||||
|
await gm.ws.waitText('hello')
|
||||||
|
const player = await createPlayer(gm.ws)
|
||||||
|
await namePlayer(origin, player.key, 'Cara')
|
||||||
|
gm.ws.close()
|
||||||
|
|
||||||
|
const browser = await launchBrowser()
|
||||||
|
try {
|
||||||
|
const { context, page } = await newPage(browser)
|
||||||
|
await page.goto(`${origin}/`)
|
||||||
|
await waitForVisible(page, '#signin')
|
||||||
|
await signIn(page, player.key)
|
||||||
|
await waitForVisible(page, '#hud')
|
||||||
|
await waitForBadge(page, 'connected')
|
||||||
|
|
||||||
|
await context.setOffline(true)
|
||||||
|
// Story 7: no network at all is the `offline` badge, distinct from a socket retrying.
|
||||||
|
await waitForBadge(page, 'offline', 15000)
|
||||||
|
|
||||||
|
await context.setOffline(false)
|
||||||
|
// The `online` event skips the rest of the backoff; the session is still valid.
|
||||||
|
await waitForBadge(page, 'connected', 30000)
|
||||||
|
await waitForText(page, '#me', /^Cara$/)
|
||||||
|
assert.equal(await page.locator('#stage canvas').count(), 1)
|
||||||
|
} finally {
|
||||||
|
await browser.close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('two connections of one player are both live and stay in sync', { timeout: 120000 }, async () => {
|
||||||
|
await withStack(async ({ origin, gmKey }) => {
|
||||||
|
const gm = await gmWorld(origin, gmKey)
|
||||||
|
const scene = gm.scene
|
||||||
|
const player = await createPlayer(gm.ws)
|
||||||
|
await namePlayer(origin, player.key, 'Dee')
|
||||||
|
gm.ws.close()
|
||||||
|
|
||||||
|
const browser = await launchBrowser()
|
||||||
|
try {
|
||||||
|
const first = await newPage(browser)
|
||||||
|
const second = await newPage(browser)
|
||||||
|
for (const view of [first, second]) {
|
||||||
|
await recordSockets(view.page)
|
||||||
|
await view.page.goto(`${origin}/`)
|
||||||
|
await waitForVisible(view.page, '#signin')
|
||||||
|
await signIn(view.page, player.key)
|
||||||
|
await waitForVisible(view.page, '#hud')
|
||||||
|
await waitForBadge(view.page, 'connected')
|
||||||
|
}
|
||||||
|
assert.equal(await first.page.textContent('#me'), 'Dee')
|
||||||
|
assert.equal(await second.page.textContent('#me'), 'Dee')
|
||||||
|
|
||||||
|
// A state change after both are connected reaches both connections: the GM places the
|
||||||
|
// player's own token, and each device's `token` frame carries it with `mine:true`.
|
||||||
|
const gm = await openAs(origin, gmKey)
|
||||||
|
await gm.ws.waitText('hello')
|
||||||
|
const created = await gm.ws.request({
|
||||||
|
t: 'token.create', scene, kind: 'pc', pos: [400, 400],
|
||||||
|
descriptive_name: 'Dee', actual_name: 'Dee', controller: player.id,
|
||||||
|
})
|
||||||
|
assert.equal(created.ok, true)
|
||||||
|
for (const view of [first, second]) {
|
||||||
|
await view.page.waitForFunction(
|
||||||
|
id => (window.__wsLog?.frames ?? []).some(frame => frame.t === 'token' && frame.id === id && frame.mine === true),
|
||||||
|
created.id,
|
||||||
|
{ timeout: 20000 },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A later roster change is broadcast to every connection of the named player too.
|
||||||
|
const renamed = await gm.ws.request({ t: 'player.rename', id: player.id, name: 'Dee Two' })
|
||||||
|
assert.equal(renamed.ok, true)
|
||||||
|
gm.ws.close()
|
||||||
|
for (const view of [first, second]) {
|
||||||
|
await waitForText(view.page, '#roster', /Dee Two/)
|
||||||
|
await waitForBadge(view.page, 'connected')
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await browser.close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
+54
-4
@@ -11,6 +11,13 @@ import type { RootState } from './reducer.ts'
|
|||||||
|
|
||||||
const KEY_REFUSED = 'Key not recognised.'
|
const KEY_REFUSED = 'Key not recognised.'
|
||||||
|
|
||||||
|
/** Story 6: a refused name is shown with a reason, next to the prompt. */
|
||||||
|
const NAME_REFUSALS: Record<string, string> = {
|
||||||
|
'name-taken': 'That name is taken. Choose another.',
|
||||||
|
invalid: 'Enter a name of 1–32 characters, with no control characters.',
|
||||||
|
'not-allowed': 'You cannot change your name.',
|
||||||
|
}
|
||||||
|
|
||||||
const host = document.querySelector<HTMLElement>('#app')
|
const host = document.querySelector<HTMLElement>('#app')
|
||||||
if (!host) throw new Error('#app is missing')
|
if (!host) throw new Error('#app is missing')
|
||||||
|
|
||||||
@@ -23,6 +30,9 @@ const shell = mountShell(host, {
|
|||||||
onSubmitKey: key => {
|
onSubmitKey: key => {
|
||||||
void signIn(key)
|
void signIn(key)
|
||||||
},
|
},
|
||||||
|
onSubmitName: name => {
|
||||||
|
void submitName(name)
|
||||||
|
},
|
||||||
onReload: () => location.reload(),
|
onReload: () => location.reload(),
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -58,6 +68,31 @@ async function signIn(key: string): Promise<void> {
|
|||||||
connect()
|
connect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stories 5/6: send `player.setname` once. The server acks before the `hello` + resync (FIXED #33),
|
||||||
|
* so a refusal is shown on the prompt and an acceptance is followed by the second `hello` the
|
||||||
|
* reducer already turns into a full reset+resync.
|
||||||
|
*/
|
||||||
|
async function submitName(name: string): Promise<void> {
|
||||||
|
if (!client || store.state.connection.phase !== 'live') return
|
||||||
|
shell.setNameBusy(true)
|
||||||
|
let accepted = false
|
||||||
|
try {
|
||||||
|
const ack = await client.send('player.setname', { name })
|
||||||
|
accepted = ack.ok
|
||||||
|
if (!ack.ok) {
|
||||||
|
store.dispatch({
|
||||||
|
type: 'name-failed',
|
||||||
|
message: NAME_REFUSALS[ack.code ?? ''] ?? 'That name is not available.',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
store.dispatch({ type: 'name-failed', message: 'Could not reach the server. Try again.' })
|
||||||
|
} finally {
|
||||||
|
if (!accepted) shell.setNameBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function connect(): void {
|
function connect(): void {
|
||||||
client = new ProtocolClient({
|
client = new ProtocolClient({
|
||||||
onEvent: event => {
|
onEvent: event => {
|
||||||
@@ -67,17 +102,21 @@ function connect(): void {
|
|||||||
client.connect()
|
client.connect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A stage exists only for a named live session; a reconnect keeps the last map on screen. */
|
||||||
function syncStage(state: RootState): void {
|
function syncStage(state: RootState): void {
|
||||||
const live = state.connection.phase === 'live'
|
const named = state.session.me !== null && state.session.me.name !== null
|
||||||
if (!live) {
|
const live = state.connection.phase === 'live' && named
|
||||||
|
const keep = state.connection.phase === 'reconnecting' && stage !== null
|
||||||
|
if (!live && !keep) {
|
||||||
stage?.destroy()
|
stage?.destroy()
|
||||||
stage = null
|
stage = null
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (stage || startingStage) return
|
if (!live || stage || startingStage) return
|
||||||
startingStage = createStage(stageRoot, store)
|
startingStage = createStage(stageRoot, store)
|
||||||
.then(created => {
|
.then(created => {
|
||||||
if (store.state.connection.phase !== 'live') {
|
const phase = store.state.connection.phase
|
||||||
|
if (phase !== 'live' && phase !== 'reconnecting') {
|
||||||
created.destroy()
|
created.destroy()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -96,8 +135,19 @@ store.subscribe(state => {
|
|||||||
syncStage(state)
|
syncStage(state)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Story 7: the badge distinguishes "no network at all" from "socket is reconnecting". The socket
|
||||||
|
// retries by itself, but a browser `online` event is the moment to skip the rest of the backoff.
|
||||||
|
window.addEventListener('offline', () => {
|
||||||
|
store.dispatch({ type: 'network', online: false })
|
||||||
|
})
|
||||||
|
window.addEventListener('online', () => {
|
||||||
|
store.dispatch({ type: 'network', online: true })
|
||||||
|
client?.retryNow()
|
||||||
|
})
|
||||||
|
|
||||||
// Boot: show the neutral connecting screen and probe for a session. A visitor without a session
|
// Boot: show the neutral connecting screen and probe for a session. A visitor without a session
|
||||||
// gets a refused `/ws` upgrade and lands on the sign-in page; no map data is ever created.
|
// gets a refused `/ws` upgrade and lands on the sign-in page; no map data is ever created.
|
||||||
|
store.dispatch({ type: 'network', online: navigator.onLine })
|
||||||
store.dispatch({ type: 'connecting' })
|
store.dispatch({ type: 'connecting' })
|
||||||
shell.render(store.state)
|
shell.render(store.state)
|
||||||
connect()
|
connect()
|
||||||
|
|||||||
+74
-3
@@ -16,7 +16,9 @@ import type {
|
|||||||
} from './protocol.ts'
|
} from './protocol.ts'
|
||||||
import { closeOutcome, isClosing, isHello } from './protocol.ts'
|
import { closeOutcome, isClosing, isHello } from './protocol.ts'
|
||||||
|
|
||||||
export type Phase = 'boot' | 'connecting' | 'signin' | 'live' | 'reload' | 'offline'
|
export type Phase = 'boot' | 'connecting' | 'signin' | 'live' | 'reconnecting' | 'reload' | 'offline'
|
||||||
|
|
||||||
|
export type ConnectionBadge = 'connected' | 'reconnecting' | 'offline'
|
||||||
|
|
||||||
export interface ConnectionState {
|
export interface ConnectionState {
|
||||||
phase: Phase
|
phase: Phase
|
||||||
@@ -27,6 +29,14 @@ export interface ConnectionState {
|
|||||||
notice: string | null
|
notice: string | null
|
||||||
/** Sign-in failure text ("Key not recognised.") or a transport message. */
|
/** Sign-in failure text ("Key not recognised.") or a transport message. */
|
||||||
error: string | null
|
error: string | null
|
||||||
|
/** The name the player tried was refused; shown only on the first-sign-in name prompt. */
|
||||||
|
nameError: string | null
|
||||||
|
/** Consecutive reconnect attempts since the last live connection (0 when connected). */
|
||||||
|
attempt: number
|
||||||
|
/** The delay the socket scheduled for the next attempt, for the badge/notification text. */
|
||||||
|
retryDelayMs: number | null
|
||||||
|
/** The browser's own connectivity (story 7: offline when there is no network at all). */
|
||||||
|
network: 'online' | 'offline'
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SessionState {
|
export interface SessionState {
|
||||||
@@ -51,7 +61,10 @@ export type ReducerEvent =
|
|||||||
| { type: 'open' }
|
| { type: 'open' }
|
||||||
| { type: 'frame'; frame: ServerFrame }
|
| { type: 'frame'; frame: ServerFrame }
|
||||||
| { type: 'close'; reason: CloseReason | null; code: number | null }
|
| { type: 'close'; reason: CloseReason | null; code: number | null }
|
||||||
|
| { type: 'reconnecting'; attempt: number; delay: number }
|
||||||
|
| { type: 'network'; online: boolean }
|
||||||
| { type: 'signin-failed'; message: string }
|
| { type: 'signin-failed'; message: string }
|
||||||
|
| { type: 'name-failed'; message: string }
|
||||||
| { type: 'signed-out' }
|
| { type: 'signed-out' }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -87,7 +100,32 @@ export function sliceOf<S>(state: RootState, name: string): S {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function initialConnection(): ConnectionState {
|
function initialConnection(): ConnectionState {
|
||||||
return { phase: 'boot', frames: 0, lastN: 0, notice: null, error: null }
|
return {
|
||||||
|
phase: 'boot',
|
||||||
|
frames: 0,
|
||||||
|
lastN: 0,
|
||||||
|
notice: null,
|
||||||
|
error: null,
|
||||||
|
nameError: null,
|
||||||
|
attempt: 0,
|
||||||
|
retryDelayMs: null,
|
||||||
|
network: 'online',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Story 7's three badge states. The badge is hidden outside the game (boot, sign-in, reload), is
|
||||||
|
* `offline` whenever the browser has no network even if the socket has not noticed yet, and is
|
||||||
|
* `reconnecting` while the socket backs off. Pure, so the transition table is unit-tested.
|
||||||
|
*/
|
||||||
|
export function connectionBadge(state: RootState): ConnectionBadge | null {
|
||||||
|
const { phase, network } = state.connection
|
||||||
|
if (phase === 'boot' || phase === 'connecting' || phase === 'signin' || phase === 'reload') {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
if (phase === 'offline' || network === 'offline') return 'offline'
|
||||||
|
if (phase === 'live') return 'connected'
|
||||||
|
return 'reconnecting'
|
||||||
}
|
}
|
||||||
|
|
||||||
function initialSession(): SessionState {
|
function initialSession(): SessionState {
|
||||||
@@ -123,6 +161,9 @@ function onFrame(state: RootState, frame: ServerFrame): void {
|
|||||||
state.connection.phase = 'live'
|
state.connection.phase = 'live'
|
||||||
state.connection.notice = null
|
state.connection.notice = null
|
||||||
state.connection.error = null
|
state.connection.error = null
|
||||||
|
state.connection.nameError = null
|
||||||
|
state.connection.attempt = 0
|
||||||
|
state.connection.retryDelayMs = null
|
||||||
} else if (isClosing(frame)) {
|
} else if (isClosing(frame)) {
|
||||||
// DESIGN 6.5: the closing frame is the reason a browser cannot read from the close code.
|
// DESIGN 6.5: the closing frame is the reason a browser cannot read from the close code.
|
||||||
const outcome = closeOutcome(frame.reason)
|
const outcome = closeOutcome(frame.reason)
|
||||||
@@ -160,17 +201,34 @@ export function reduce(previous: RootState, event: ReducerEvent): RootState {
|
|||||||
state.connection.lastN = 0
|
state.connection.lastN = 0
|
||||||
state.connection.notice = null
|
state.connection.notice = null
|
||||||
state.connection.error = null
|
state.connection.error = null
|
||||||
|
state.connection.nameError = null
|
||||||
|
state.connection.attempt = 0
|
||||||
|
state.connection.retryDelayMs = null
|
||||||
break
|
break
|
||||||
case 'open':
|
case 'open':
|
||||||
// An open socket is not a view: stay on the boot/connecting screen until `hello` (6.3).
|
// An open socket is not a view: stay on the boot/connecting screen until `hello` (6.3).
|
||||||
|
// A new socket also restarts the per-connection frame counter (`n` starts at 1).
|
||||||
|
state.connection.frames = 0
|
||||||
|
state.connection.lastN = 0
|
||||||
break
|
break
|
||||||
case 'frame':
|
case 'frame':
|
||||||
onFrame(state, event.frame)
|
onFrame(state, event.frame)
|
||||||
break
|
break
|
||||||
|
case 'reconnecting':
|
||||||
|
// The map stays on screen (stale) with a badge until the resync replaces it; nothing here
|
||||||
|
// clears state, because `hello` is the reset point (6.3).
|
||||||
|
state.connection.phase = 'reconnecting'
|
||||||
|
state.connection.attempt = event.attempt
|
||||||
|
state.connection.retryDelayMs = event.delay
|
||||||
|
state.connection.notice = 'Connection lost. Reconnecting…'
|
||||||
|
break
|
||||||
|
case 'network':
|
||||||
|
state.connection.network = event.online ? 'online' : 'offline'
|
||||||
|
break
|
||||||
case 'close': {
|
case 'close': {
|
||||||
// A `closing` frame already decided the outcome (6.5); a close without one is a transport
|
// A `closing` frame already decided the outcome (6.5); a close without one is a transport
|
||||||
// failure. Before the first `hello` that means "no session" (the `/ws` upgrade was refused).
|
// failure. Before the first `hello` that means "no session" (the `/ws` upgrade was refused).
|
||||||
if (state.connection.phase === 'live') {
|
if (state.connection.phase === 'live' || state.connection.phase === 'reconnecting') {
|
||||||
const outcome = closeOutcome(event.reason)
|
const outcome = closeOutcome(event.reason)
|
||||||
if (outcome === 'signin') {
|
if (outcome === 'signin') {
|
||||||
resetDomain(state)
|
resetDomain(state)
|
||||||
@@ -179,6 +237,10 @@ export function reduce(previous: RootState, event: ReducerEvent): RootState {
|
|||||||
} else if (outcome === 'reload') {
|
} else if (outcome === 'reload') {
|
||||||
state.connection.phase = 'reload'
|
state.connection.phase = 'reload'
|
||||||
state.connection.notice = 'This client is out of date.'
|
state.connection.notice = 'This client is out of date.'
|
||||||
|
} else if (event.reason === null) {
|
||||||
|
// Transport failure: the socket retries by itself; the view stays until the resync.
|
||||||
|
state.connection.phase = 'reconnecting'
|
||||||
|
state.connection.notice = 'Connection lost. Reconnecting…'
|
||||||
} else {
|
} else {
|
||||||
state.connection.phase = 'offline'
|
state.connection.phase = 'offline'
|
||||||
state.connection.notice = 'Connection lost.'
|
state.connection.notice = 'Connection lost.'
|
||||||
@@ -193,12 +255,21 @@ export function reduce(previous: RootState, event: ReducerEvent): RootState {
|
|||||||
resetDomain(state)
|
resetDomain(state)
|
||||||
state.connection.phase = 'signin'
|
state.connection.phase = 'signin'
|
||||||
state.connection.error = event.message
|
state.connection.error = event.message
|
||||||
|
state.connection.nameError = null
|
||||||
|
state.connection.attempt = 0
|
||||||
|
state.connection.retryDelayMs = null
|
||||||
|
break
|
||||||
|
case 'name-failed':
|
||||||
|
state.connection.nameError = event.message
|
||||||
break
|
break
|
||||||
case 'signed-out':
|
case 'signed-out':
|
||||||
resetDomain(state)
|
resetDomain(state)
|
||||||
state.connection.phase = 'signin'
|
state.connection.phase = 'signin'
|
||||||
state.connection.notice = null
|
state.connection.notice = null
|
||||||
state.connection.error = null
|
state.connection.error = null
|
||||||
|
state.connection.nameError = null
|
||||||
|
state.connection.attempt = 0
|
||||||
|
state.connection.retryDelayMs = null
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+110
-13
@@ -4,19 +4,25 @@
|
|||||||
// The shell is the only module that owns page structure; later panels (roster/keys/tokens T11,
|
// The shell is the only module that owns page structure; later panels (roster/keys/tokens T11,
|
||||||
// characters/reveals T12) add their DOM under `#panels` or as their own file next to this one,
|
// characters/reveals T12) add their DOM under `#panels` or as their own file next to this one,
|
||||||
// never by rewriting the sign-in flow.
|
// never by rewriting the sign-in flow.
|
||||||
|
//
|
||||||
|
// T5 (#68) adds three things here: the first-sign-in name prompt (stories 5, 6), the connection
|
||||||
|
// badge (story 7) and the `reconnecting` screen state, which keeps the map (stale) on screen while
|
||||||
|
// the socket backs off instead of dropping the player to a fatal page.
|
||||||
|
|
||||||
import type { RootState } from './reducer.ts'
|
import type { RootState } from './reducer.ts'
|
||||||
import { rosterOf } from './reducer.ts'
|
import { connectionBadge, rosterOf } from './reducer.ts'
|
||||||
import type { RosterEntry } from './protocol.ts'
|
import type { RosterEntry } from './protocol.ts'
|
||||||
|
|
||||||
export interface ShellHandlers {
|
export interface ShellHandlers {
|
||||||
onSubmitKey(key: string): void
|
onSubmitKey(key: string): void
|
||||||
|
onSubmitName(name: string): void
|
||||||
onReload(): void
|
onReload(): void
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Shell {
|
export interface Shell {
|
||||||
render(state: RootState): void
|
render(state: RootState): void
|
||||||
setBusy(busy: boolean): void
|
setBusy(busy: boolean): void
|
||||||
|
setNameBusy(busy: boolean): void
|
||||||
}
|
}
|
||||||
|
|
||||||
function element<K extends keyof HTMLElementTagNameMap>(
|
function element<K extends keyof HTMLElementTagNameMap>(
|
||||||
@@ -34,6 +40,12 @@ function rosterName(entry: RosterEntry): string {
|
|||||||
return entry.name ?? '(unnamed)'
|
return entry.name ?? '(unnamed)'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const BADGE_TEXT = {
|
||||||
|
connected: 'Connected',
|
||||||
|
reconnecting: 'Reconnecting…',
|
||||||
|
offline: 'Offline',
|
||||||
|
} as const
|
||||||
|
|
||||||
export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
|
export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
|
||||||
const stage = element('div', 'stage')
|
const stage = element('div', 'stage')
|
||||||
stage.hidden = true
|
stage.hidden = true
|
||||||
@@ -65,13 +77,40 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
|
|||||||
error.setAttribute('role', 'alert')
|
error.setAttribute('role', 'alert')
|
||||||
signin.append(title, notice, form, error)
|
signin.append(title, notice, form, error)
|
||||||
|
|
||||||
|
// First-sign-in name prompt (stories 5, 6). Shown while a live session has `me.name === null`;
|
||||||
|
// the server sends no scene and no game data until the name is accepted (DESIGN 6.1/6.3).
|
||||||
|
const namePanel = element('section', 'name')
|
||||||
|
namePanel.hidden = true
|
||||||
|
const nameTitle = element('h1', 'name-title', 'Choose a display name')
|
||||||
|
const nameHint = element('p', 'name-hint', 'The rest of the table will see this name.')
|
||||||
|
const nameForm = element('form', 'name-form')
|
||||||
|
const nameLabel = element('label', 'name-label', 'Display name')
|
||||||
|
nameLabel.htmlFor = 'name-input'
|
||||||
|
const nameInput = element('input', 'name-input')
|
||||||
|
nameInput.name = 'name'
|
||||||
|
nameInput.type = 'text'
|
||||||
|
nameInput.autocomplete = 'off'
|
||||||
|
nameInput.autocapitalize = 'words'
|
||||||
|
nameInput.maxLength = 32
|
||||||
|
nameInput.spellcheck = false
|
||||||
|
nameInput.required = true
|
||||||
|
const nameSubmit = element('button', 'name-submit', 'Join the table')
|
||||||
|
nameSubmit.type = 'submit'
|
||||||
|
nameForm.append(nameLabel, nameInput, nameSubmit)
|
||||||
|
const nameError = element('p', 'name-error')
|
||||||
|
nameError.hidden = true
|
||||||
|
nameError.setAttribute('role', 'alert')
|
||||||
|
namePanel.append(nameTitle, nameHint, nameForm, nameError)
|
||||||
|
|
||||||
const hud = element('header', 'hud')
|
const hud = element('header', 'hud')
|
||||||
hud.hidden = true
|
hud.hidden = true
|
||||||
const role = element('span', 'role')
|
const role = element('span', 'role')
|
||||||
const scene = element('span', 'scene')
|
const scene = element('span', 'scene')
|
||||||
const me = element('span', 'me')
|
const me = element('span', 'me')
|
||||||
|
const badge = element('span', 'badge', BADGE_TEXT.connected)
|
||||||
|
badge.dataset['state'] = 'connected'
|
||||||
const roster = element('ul', 'roster')
|
const roster = element('ul', 'roster')
|
||||||
hud.append(role, scene, me, roster)
|
hud.append(role, scene, me, badge, roster)
|
||||||
|
|
||||||
const fatal = element('section', 'fatal')
|
const fatal = element('section', 'fatal')
|
||||||
fatal.hidden = true
|
fatal.hidden = true
|
||||||
@@ -82,7 +121,7 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
|
|||||||
fatal.append(fatalText, reload)
|
fatal.append(fatalText, reload)
|
||||||
|
|
||||||
const panels = element('div', 'panels')
|
const panels = element('div', 'panels')
|
||||||
root.replaceChildren(stage, hud, signin, boot, fatal, panels)
|
root.replaceChildren(stage, hud, signin, boot, namePanel, fatal, panels)
|
||||||
|
|
||||||
form.addEventListener('submit', event => {
|
form.addEventListener('submit', event => {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
@@ -91,7 +130,16 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
|
|||||||
handlers.onSubmitKey(key)
|
handlers.onSubmitKey(key)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
nameForm.addEventListener('submit', event => {
|
||||||
|
event.preventDefault()
|
||||||
|
const name = nameInput.value.trim()
|
||||||
|
if (name.length === 0) return
|
||||||
|
handlers.onSubmitName(name)
|
||||||
|
})
|
||||||
|
|
||||||
let busy = false
|
let busy = false
|
||||||
|
let nameBusy = false
|
||||||
|
let prevPhase: string | null = null
|
||||||
|
|
||||||
function setBusy(next: boolean): void {
|
function setBusy(next: boolean): void {
|
||||||
busy = next
|
busy = next
|
||||||
@@ -101,8 +149,15 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
|
|||||||
if (next) showOnly(boot)
|
if (next) showOnly(boot)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function setNameBusy(next: boolean): void {
|
||||||
|
nameBusy = next
|
||||||
|
nameInput.disabled = next
|
||||||
|
nameSubmit.disabled = next
|
||||||
|
nameSubmit.textContent = next ? 'Saving…' : 'Join the table'
|
||||||
|
}
|
||||||
|
|
||||||
function showOnly(active: HTMLElement): void {
|
function showOnly(active: HTMLElement): void {
|
||||||
for (const node of [boot, signin, hud, fatal]) node.hidden = node !== active
|
for (const node of [boot, signin, hud, namePanel, fatal]) node.hidden = node !== active
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderRoster(players: RosterEntry[]): void {
|
function renderRoster(players: RosterEntry[]): void {
|
||||||
@@ -118,23 +173,47 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function renderBadge(state: RootState): void {
|
||||||
|
const current = connectionBadge(state)
|
||||||
|
badge.hidden = current === null
|
||||||
|
if (current === null) return
|
||||||
|
badge.dataset['state'] = current
|
||||||
|
badge.textContent = BADGE_TEXT[current]
|
||||||
|
const retry = state.connection.retryDelayMs
|
||||||
|
badge.title =
|
||||||
|
current === 'reconnecting' && retry !== null
|
||||||
|
? `Attempt ${state.connection.attempt}, retrying in ${(retry / 1000).toFixed(1)} s`
|
||||||
|
: current === 'offline'
|
||||||
|
? 'No connection. The map is not live.'
|
||||||
|
: 'The map is live.'
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearHud(): void {
|
||||||
|
role.textContent = ''
|
||||||
|
scene.textContent = ''
|
||||||
|
me.textContent = ''
|
||||||
|
roster.replaceChildren()
|
||||||
|
}
|
||||||
|
|
||||||
function render(state: RootState): void {
|
function render(state: RootState): void {
|
||||||
const phase = state.connection.phase
|
const phase = state.connection.phase
|
||||||
|
const phaseChanged = phase !== prevPhase
|
||||||
|
prevPhase = phase
|
||||||
|
|
||||||
notice.textContent = state.connection.notice ?? ''
|
notice.textContent = state.connection.notice ?? ''
|
||||||
notice.hidden = state.connection.notice === null
|
notice.hidden = state.connection.notice === null
|
||||||
error.textContent = state.connection.error ?? ''
|
error.textContent = state.connection.error ?? ''
|
||||||
error.hidden = state.connection.error === null
|
error.hidden = state.connection.error === null
|
||||||
|
|
||||||
stage.hidden = phase !== 'live'
|
stage.hidden = phase !== 'live' && phase !== 'reconnecting'
|
||||||
|
renderBadge(state)
|
||||||
|
|
||||||
// Leaving the live phase clears every server-derived DOM text, so a revoked session cannot
|
// Leaving the game clears every server-derived DOM text, so a revoked session cannot leave a
|
||||||
// leave a roster (or names) behind the sign-in page.
|
// roster (or names) behind the sign-in page. A reconnect keeps the view: the badge says it is
|
||||||
if (phase !== 'live') {
|
// stale, and the resync after the next `hello` replaces it.
|
||||||
role.textContent = ''
|
if (phase === 'signin' || phase === 'offline' || phase === 'reload' || phase === 'boot') {
|
||||||
scene.textContent = ''
|
clearHud()
|
||||||
me.textContent = ''
|
setNameBusy(false)
|
||||||
roster.replaceChildren()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (phase) {
|
switch (phase) {
|
||||||
@@ -152,6 +231,24 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
|
|||||||
break
|
break
|
||||||
case 'live':
|
case 'live':
|
||||||
busy = false
|
busy = false
|
||||||
|
if (state.session.role === 'player' && state.session.me !== null && state.session.me.name === null) {
|
||||||
|
// Stories 5/6: ask once, before any game data (the server sends no scene to a nameless
|
||||||
|
// player). `nameError` is the server's refusal text.
|
||||||
|
showOnly(namePanel)
|
||||||
|
nameError.textContent = state.connection.nameError ?? ''
|
||||||
|
nameError.hidden = state.connection.nameError === null
|
||||||
|
if (phaseChanged) nameInput.focus()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
setNameBusy(false)
|
||||||
|
showOnly(hud)
|
||||||
|
role.textContent = state.session.role === 'gm' ? 'GM' : 'Player'
|
||||||
|
scene.textContent = state.session.scene?.name ?? ''
|
||||||
|
me.textContent = state.session.me?.name ?? ''
|
||||||
|
renderRoster(rosterOf(state))
|
||||||
|
break
|
||||||
|
case 'reconnecting':
|
||||||
|
// Keep the HUD (and the stale map) visible; only the badge changes.
|
||||||
showOnly(hud)
|
showOnly(hud)
|
||||||
role.textContent = state.session.role === 'gm' ? 'GM' : 'Player'
|
role.textContent = state.session.role === 'gm' ? 'GM' : 'Player'
|
||||||
scene.textContent = state.session.scene?.name ?? ''
|
scene.textContent = state.session.scene?.name ?? ''
|
||||||
@@ -169,5 +266,5 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { render, setBusy }
|
return { render, setBusy, setNameBusy }
|
||||||
}
|
}
|
||||||
|
|||||||
+42
-3
@@ -28,6 +28,7 @@ body {
|
|||||||
|
|
||||||
#boot,
|
#boot,
|
||||||
#signin,
|
#signin,
|
||||||
|
#name,
|
||||||
#fatal {
|
#fatal {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
@@ -40,14 +41,16 @@ body {
|
|||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
#signin form {
|
#signin form,
|
||||||
|
#name form {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
width: min(360px, 90vw);
|
width: min(360px, 90vw);
|
||||||
}
|
}
|
||||||
|
|
||||||
#key {
|
#key,
|
||||||
|
#name-input {
|
||||||
font: inherit;
|
font: inherit;
|
||||||
padding: 10px 12px;
|
padding: 10px 12px;
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
@@ -58,7 +61,13 @@ body {
|
|||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#name-input {
|
||||||
|
letter-spacing: normal;
|
||||||
|
text-transform: none;
|
||||||
|
}
|
||||||
|
|
||||||
#signin button,
|
#signin button,
|
||||||
|
#name button,
|
||||||
#fatal button {
|
#fatal button {
|
||||||
font: inherit;
|
font: inherit;
|
||||||
padding: 10px 12px;
|
padding: 10px 12px;
|
||||||
@@ -68,7 +77,8 @@ body {
|
|||||||
color: inherit;
|
color: inherit;
|
||||||
}
|
}
|
||||||
|
|
||||||
#signin-error {
|
#signin-error,
|
||||||
|
#name-error {
|
||||||
color: #ff8a8a;
|
color: #ff8a8a;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,3 +112,32 @@ body {
|
|||||||
#roster-state {
|
#roster-state {
|
||||||
opacity: 0.6;
|
opacity: 0.6;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Story 7: connected / reconnecting / offline. The dot carries the state at a glance; the text is
|
||||||
|
the accessible label. */
|
||||||
|
#badge {
|
||||||
|
margin-left: auto;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#badge::before {
|
||||||
|
content: '';
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: currentColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
#badge[data-state='connected'] {
|
||||||
|
color: #7ee787;
|
||||||
|
}
|
||||||
|
|
||||||
|
#badge[data-state='reconnecting'] {
|
||||||
|
color: #e3b341;
|
||||||
|
}
|
||||||
|
|
||||||
|
#badge[data-state='offline'] {
|
||||||
|
color: #ff7b72;
|
||||||
|
}
|
||||||
|
|||||||
+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`
|
// 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
|
// counter, the pending-request map and the reconnect schedule; it emits reducer events and never
|
||||||
// socket factory and clock-free design make it unit-testable without a browser.
|
// 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 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.
|
// 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
|
// `revoked` and `proto-mismatch` are terminal (the reducer goes to the sign-in page / reload and
|
||||||
// with backoff is T5 (#68); T4 only proves the outcome mapping.
|
// 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 type { AckFrame, CloseReason, ServerFrame } from './protocol.ts'
|
||||||
import { encodeIntent, isAck, isClosing, parseServerFrame, wsUrl } from './protocol.ts'
|
import { encodeIntent, isAck, isClosing, parseServerFrame, wsUrl } from './protocol.ts'
|
||||||
@@ -23,11 +27,53 @@ export type ClientEvent =
|
|||||||
| { type: 'open' }
|
| { type: 'open' }
|
||||||
| { type: 'frame'; frame: ServerFrame }
|
| { type: 'frame'; frame: ServerFrame }
|
||||||
| { type: 'close'; reason: CloseReason | null; code: number | null }
|
| { 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 {
|
export interface ProtocolClientOptions {
|
||||||
url?: string
|
url?: string
|
||||||
createSocket?: (url: string) => SocketLike
|
createSocket?: (url: string) => SocketLike
|
||||||
onEvent: (event: ClientEvent) => void
|
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 = {
|
type Pending = {
|
||||||
@@ -43,16 +89,26 @@ export class ProtocolClient {
|
|||||||
#url: string
|
#url: string
|
||||||
#createSocket: (url: string) => SocketLike
|
#createSocket: (url: string) => SocketLike
|
||||||
#onEvent: (event: ClientEvent) => void
|
#onEvent: (event: ClientEvent) => void
|
||||||
|
#autoReconnect: boolean
|
||||||
|
#random: () => number
|
||||||
|
#timers: Timers
|
||||||
#socket: SocketLike | null = null
|
#socket: SocketLike | null = null
|
||||||
#nextReqId = 1
|
#nextReqId = 1
|
||||||
#pending = new Map<number, Pending>()
|
#pending = new Map<number, Pending>()
|
||||||
#lastClosing: { reason: CloseReason; code: number } | null = null
|
#lastClosing: { reason: CloseReason; code: number } | null = null
|
||||||
#state: 'idle' | 'connecting' | 'open' | 'closed' = 'idle'
|
#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) {
|
constructor(options: ProtocolClientOptions) {
|
||||||
this.#url = options.url ?? wsUrl()
|
this.#url = options.url ?? wsUrl()
|
||||||
this.#createSocket = options.createSocket ?? defaultSocket
|
this.#createSocket = options.createSocket ?? defaultSocket
|
||||||
this.#onEvent = options.onEvent
|
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' {
|
get state(): 'idle' | 'connecting' | 'open' | 'closed' {
|
||||||
@@ -63,15 +119,33 @@ export class ProtocolClient {
|
|||||||
return this.#pending.size
|
return this.#pending.size
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The number of consecutive retries scheduled/failed since the last successful open. */
|
||||||
|
get attempt(): number {
|
||||||
|
return this.#attempt
|
||||||
|
}
|
||||||
|
|
||||||
connect(): void {
|
connect(): void {
|
||||||
if (this.#state !== 'idle') return
|
if (this.#state !== 'idle') return
|
||||||
this.#state = 'connecting'
|
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
|
this.#socket = socket
|
||||||
|
|
||||||
socket.onopen = () => {
|
socket.onopen = () => {
|
||||||
if (this.#state !== 'connecting') return
|
if (this.#state !== 'connecting') return
|
||||||
this.#state = 'open'
|
this.#state = 'open'
|
||||||
|
this.#everOpened = true
|
||||||
|
this.#attempt = 0
|
||||||
this.#onEvent({ type: 'open' })
|
this.#onEvent({ type: 'open' })
|
||||||
}
|
}
|
||||||
socket.onmessage = event => {
|
socket.onmessage = event => {
|
||||||
@@ -93,10 +167,18 @@ export class ProtocolClient {
|
|||||||
}
|
}
|
||||||
socket.onclose = event => {
|
socket.onclose = event => {
|
||||||
if (this.#state === 'closed') return
|
if (this.#state === 'closed') return
|
||||||
this.#state = 'closed'
|
|
||||||
const reason = this.#lastClosing?.reason ?? null
|
const reason = this.#lastClosing?.reason ?? null
|
||||||
const code = this.#lastClosing?.code ?? event.code ?? null
|
const code = this.#lastClosing?.code ?? event.code ?? null
|
||||||
this.#failPending(new Error(`connection closed (${reason ?? code ?? 'no code'})`))
|
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 })
|
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 {
|
close(): void {
|
||||||
|
this.#cancelRetry()
|
||||||
if (this.#state === 'closed') return
|
if (this.#state === 'closed') return
|
||||||
this.#state = 'closed'
|
this.#state = 'closed'
|
||||||
try {
|
try {
|
||||||
@@ -135,6 +226,24 @@ export class ProtocolClient {
|
|||||||
this.#failPending(new Error('connection closed by the client'))
|
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 {
|
#failPending(error: Error): void {
|
||||||
const pending = [...this.#pending.values()]
|
const pending = [...this.#pending.values()]
|
||||||
this.#pending.clear()
|
this.#pending.clear()
|
||||||
|
|||||||
+124
-3
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { SLICES, initialState, reduce, rosterOf } from '../src/reducer.ts'
|
import { SLICES, connectionBadge, initialState, reduce, rosterOf } from '../src/reducer.ts'
|
||||||
import type { ReducerEvent, RootState } from '../src/reducer.ts'
|
import type { ReducerEvent, RootState } from '../src/reducer.ts'
|
||||||
import { parseServerFrame } from '../src/protocol.ts'
|
import { parseServerFrame } from '../src/protocol.ts'
|
||||||
import type { RosterEntry } from '../src/protocol.ts'
|
import type { RosterEntry } from '../src/protocol.ts'
|
||||||
@@ -140,9 +140,10 @@ describe('connection outcomes (6.5)', () => {
|
|||||||
expect(state.connection.phase).toBe('offline')
|
expect(state.connection.phase).toBe('offline')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('a transport close while live is offline, not a silent sign-out', () => {
|
it('a transport close while live is reconnecting, not a silent sign-out', () => {
|
||||||
const state = run({ type: 'connecting' }, hello(1), { type: 'close', reason: null, code: 1006 })
|
const state = run({ type: 'connecting' }, hello(1), { type: 'close', reason: null, code: 1006 })
|
||||||
expect(state.connection.phase).toBe('offline')
|
expect(state.connection.phase).toBe('reconnecting')
|
||||||
|
expect(connectionBadge(state)).toBe('reconnecting')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -182,3 +183,123 @@ describe('registry', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// T5 (#68): the connection slice — badge, backoff display, name prompt errors, reconnect reset.
|
||||||
|
|
||||||
|
const named = (): RootState =>
|
||||||
|
run(
|
||||||
|
{ type: 'connecting' },
|
||||||
|
hello(1),
|
||||||
|
roster(2, [{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }]),
|
||||||
|
)
|
||||||
|
|
||||||
|
describe('connection badge (story 7)', () => {
|
||||||
|
it('is connected while live, hidden at the sign-in door and on boot', () => {
|
||||||
|
expect(connectionBadge(named())).toBe('connected')
|
||||||
|
expect(connectionBadge(initialState())).toBeNull()
|
||||||
|
expect(connectionBadge(run({ type: 'connecting' }))).toBeNull()
|
||||||
|
expect(
|
||||||
|
connectionBadge(run({ type: 'connecting' }, { type: 'signin-failed', message: 'Key not recognised.' })),
|
||||||
|
).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is reconnecting after a transport close and keeps showing the last view', () => {
|
||||||
|
const state = reduce(named(), { type: 'close', reason: null, code: 1006 })
|
||||||
|
expect(state.connection.phase).toBe('reconnecting')
|
||||||
|
expect(connectionBadge(state)).toBe('reconnecting')
|
||||||
|
expect(state.connection.notice).toMatch(/reconnect/i)
|
||||||
|
// The map is stale but stays on screen until the resync replaces it (no blank flash).
|
||||||
|
expect(state.session.me).toEqual({ id: 2, name: 'Ann' })
|
||||||
|
expect(rosterOf(state)).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('records the attempt and delay the socket scheduled', () => {
|
||||||
|
const state = reduce(named(), { type: 'reconnecting', attempt: 3, delay: 4400 })
|
||||||
|
expect(state.connection.phase).toBe('reconnecting')
|
||||||
|
expect(state.connection.attempt).toBe(3)
|
||||||
|
expect(state.connection.retryDelayMs).toBe(4400)
|
||||||
|
expect(state.connection.notice).toMatch(/reconnect/i)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is offline when the browser reports no network, and connected again when it returns', () => {
|
||||||
|
const offline = reduce(named(), { type: 'network', online: false })
|
||||||
|
expect(connectionBadge(offline)).toBe('offline')
|
||||||
|
expect(offline.session.me).toEqual({ id: 2, name: 'Ann' })
|
||||||
|
const online = reduce(offline, { type: 'network', online: true })
|
||||||
|
expect(connectionBadge(online)).toBe('connected')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is offline for a terminal outcome (evicted) even while a retry was in flight', () => {
|
||||||
|
const reconnecting = reduce(named(), { type: 'close', reason: null, code: 1006 })
|
||||||
|
const state = reduce(reconnecting, { type: 'close', reason: 'evicted', code: 4002 })
|
||||||
|
expect(state.connection.phase).toBe('offline')
|
||||||
|
expect(connectionBadge(state)).toBe('offline')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a reconnect keeps the view until hello, then reset+resync rebuilds it', () => {
|
||||||
|
const reconnecting = run(
|
||||||
|
{ type: 'connecting' },
|
||||||
|
hello(1),
|
||||||
|
roster(2, [{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }]),
|
||||||
|
{ type: 'close', reason: null, code: 1006 },
|
||||||
|
{ type: 'reconnecting', attempt: 2, delay: 2200 },
|
||||||
|
)
|
||||||
|
expect(connectionBadge(reconnecting)).toBe('reconnecting')
|
||||||
|
expect(rosterOf(reconnecting)).toHaveLength(1)
|
||||||
|
|
||||||
|
const back = reduce(reconnecting, { type: 'open' })
|
||||||
|
expect(back.connection.frames).toBe(0)
|
||||||
|
expect(rosterOf(back)).toHaveLength(1)
|
||||||
|
|
||||||
|
const resynced = reduce(back, hello(1))
|
||||||
|
expect(resynced.connection.phase).toBe('live')
|
||||||
|
expect(resynced.connection.attempt).toBe(0)
|
||||||
|
expect(resynced.connection.retryDelayMs).toBeNull()
|
||||||
|
expect(connectionBadge(resynced)).toBe('connected')
|
||||||
|
// `hello` cleared the old view; the resync frames after it refill it.
|
||||||
|
expect(rosterOf(resynced)).toEqual([])
|
||||||
|
const filled = reduce(
|
||||||
|
resynced,
|
||||||
|
roster(2, [
|
||||||
|
{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true },
|
||||||
|
{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true },
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
expect(rosterOf(filled)).toHaveLength(2)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('name prompt (stories 5, 6)', () => {
|
||||||
|
const unnamed = (): RootState =>
|
||||||
|
run({ type: 'connecting' }, frame({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 5, name: null } }))
|
||||||
|
|
||||||
|
it('an unnamed player is live with a null name and no scene', () => {
|
||||||
|
const state = unnamed()
|
||||||
|
expect(state.connection.phase).toBe('live')
|
||||||
|
expect(state.session.me).toEqual({ id: 5, name: null })
|
||||||
|
expect(state.session.scene).toBeNull()
|
||||||
|
expect(state.connection.nameError).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a taken name keeps the connection live and carries the visible reason', () => {
|
||||||
|
const state = reduce(unnamed(), { type: 'name-failed', message: 'That name is taken.' })
|
||||||
|
expect(state.connection.phase).toBe('live')
|
||||||
|
expect(state.connection.nameError).toBe('That name is taken.')
|
||||||
|
expect(state.session.me?.name).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('the second hello (me.name set) clears the name error and starts the resync', () => {
|
||||||
|
const failed = reduce(unnamed(), { type: 'name-failed', message: 'That name is taken.' })
|
||||||
|
const state = reduce(failed, hello(2, { me: { id: 5, name: 'Bob' }, scene: scene('Cellar') }))
|
||||||
|
expect(state.connection.nameError).toBeNull()
|
||||||
|
expect(state.session.me).toEqual({ id: 5, name: 'Bob' })
|
||||||
|
expect(state.session.scene?.name).toBe('Cellar')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('signing out or reconnecting clears a stale name error', () => {
|
||||||
|
const failed = reduce(unnamed(), { type: 'name-failed', message: 'Enter a name.' })
|
||||||
|
expect(reduce(failed, { type: 'connecting' }).connection.nameError).toBeNull()
|
||||||
|
expect(reduce(failed, { type: 'signed-out' }).connection.nameError).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
+209
-5
@@ -1,6 +1,12 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { ProtocolClient } from '../src/ws.ts'
|
import {
|
||||||
import type { ClientEvent, SocketLike } from '../src/ws.ts'
|
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 {
|
class FakeSocket implements SocketLike {
|
||||||
onopen: (() => void) | null = null
|
onopen: (() => void) | null = null
|
||||||
@@ -104,9 +110,20 @@ describe('protocol client', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('treats a close without a closing frame as a transport failure', () => {
|
it('treats a close without a closing frame as a transport failure', () => {
|
||||||
const { socket, events } = connect()
|
const { client, sockets, events, timers } = reconnectingClient()
|
||||||
socket.serverClose(1006)
|
client.connect()
|
||||||
expect(events.at(-1)).toEqual({ type: 'close', reason: null, code: 1006 })
|
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)', () => {
|
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/)
|
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