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:
2026-11-21 00:18:17 +01:00
parent 2727617db9
commit 465259c853
9 changed files with 1040 additions and 38 deletions
+54 -4
View File
@@ -11,6 +11,13 @@ import type { RootState } from './reducer.ts'
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')
if (!host) throw new Error('#app is missing')
@@ -23,6 +30,9 @@ const shell = mountShell(host, {
onSubmitKey: key => {
void signIn(key)
},
onSubmitName: name => {
void submitName(name)
},
onReload: () => location.reload(),
})
@@ -58,6 +68,31 @@ async function signIn(key: string): Promise<void> {
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 {
client = new ProtocolClient({
onEvent: event => {
@@ -67,17 +102,21 @@ function connect(): void {
client.connect()
}
/** A stage exists only for a named live session; a reconnect keeps the last map on screen. */
function syncStage(state: RootState): void {
const live = state.connection.phase === 'live'
if (!live) {
const named = state.session.me !== null && state.session.me.name !== null
const live = state.connection.phase === 'live' && named
const keep = state.connection.phase === 'reconnecting' && stage !== null
if (!live && !keep) {
stage?.destroy()
stage = null
return
}
if (stage || startingStage) return
if (!live || stage || startingStage) return
startingStage = createStage(stageRoot, store)
.then(created => {
if (store.state.connection.phase !== 'live') {
const phase = store.state.connection.phase
if (phase !== 'live' && phase !== 'reconnecting') {
created.destroy()
return
}
@@ -96,8 +135,19 @@ store.subscribe(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
// 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' })
shell.render(store.state)
connect()
+74 -3
View File
@@ -16,7 +16,9 @@ import type {
} 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 {
phase: Phase
@@ -27,6 +29,14 @@ export interface ConnectionState {
notice: string | null
/** Sign-in failure text ("Key not recognised.") or a transport message. */
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 {
@@ -51,7 +61,10 @@ export type ReducerEvent =
| { type: 'open' }
| { type: 'frame'; frame: ServerFrame }
| { type: 'close'; reason: CloseReason | null; code: number | null }
| { type: 'reconnecting'; attempt: number; delay: number }
| { type: 'network'; online: boolean }
| { type: 'signin-failed'; message: string }
| { type: 'name-failed'; message: string }
| { type: 'signed-out' }
/**
@@ -87,7 +100,32 @@ export function sliceOf<S>(state: RootState, name: string): S {
}
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 {
@@ -123,6 +161,9 @@ function onFrame(state: RootState, frame: ServerFrame): void {
state.connection.phase = 'live'
state.connection.notice = null
state.connection.error = null
state.connection.nameError = null
state.connection.attempt = 0
state.connection.retryDelayMs = null
} else if (isClosing(frame)) {
// DESIGN 6.5: the closing frame is the reason a browser cannot read from the close code.
const outcome = closeOutcome(frame.reason)
@@ -160,17 +201,34 @@ export function reduce(previous: RootState, event: ReducerEvent): RootState {
state.connection.lastN = 0
state.connection.notice = null
state.connection.error = null
state.connection.nameError = null
state.connection.attempt = 0
state.connection.retryDelayMs = null
break
case 'open':
// 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
case 'frame':
onFrame(state, event.frame)
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': {
// 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).
if (state.connection.phase === 'live') {
if (state.connection.phase === 'live' || state.connection.phase === 'reconnecting') {
const outcome = closeOutcome(event.reason)
if (outcome === 'signin') {
resetDomain(state)
@@ -179,6 +237,10 @@ export function reduce(previous: RootState, event: ReducerEvent): RootState {
} else if (outcome === 'reload') {
state.connection.phase = 'reload'
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 {
state.connection.phase = 'offline'
state.connection.notice = 'Connection lost.'
@@ -193,12 +255,21 @@ export function reduce(previous: RootState, event: ReducerEvent): RootState {
resetDomain(state)
state.connection.phase = 'signin'
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
case 'signed-out':
resetDomain(state)
state.connection.phase = 'signin'
state.connection.notice = null
state.connection.error = null
state.connection.nameError = null
state.connection.attempt = 0
state.connection.retryDelayMs = null
break
}
+110 -13
View File
@@ -4,19 +4,25 @@
// 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,
// 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 { rosterOf } from './reducer.ts'
import { connectionBadge, rosterOf } from './reducer.ts'
import type { RosterEntry } from './protocol.ts'
export interface ShellHandlers {
onSubmitKey(key: string): void
onSubmitName(name: string): void
onReload(): void
}
export interface Shell {
render(state: RootState): void
setBusy(busy: boolean): void
setNameBusy(busy: boolean): void
}
function element<K extends keyof HTMLElementTagNameMap>(
@@ -34,6 +40,12 @@ function rosterName(entry: RosterEntry): string {
return entry.name ?? '(unnamed)'
}
const BADGE_TEXT = {
connected: 'Connected',
reconnecting: 'Reconnecting…',
offline: 'Offline',
} as const
export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
const stage = element('div', 'stage')
stage.hidden = true
@@ -65,13 +77,40 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
error.setAttribute('role', 'alert')
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')
hud.hidden = true
const role = element('span', 'role')
const scene = element('span', 'scene')
const me = element('span', 'me')
const badge = element('span', 'badge', BADGE_TEXT.connected)
badge.dataset['state'] = 'connected'
const roster = element('ul', 'roster')
hud.append(role, scene, me, roster)
hud.append(role, scene, me, badge, roster)
const fatal = element('section', 'fatal')
fatal.hidden = true
@@ -82,7 +121,7 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
fatal.append(fatalText, reload)
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 => {
event.preventDefault()
@@ -91,7 +130,16 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
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 nameBusy = false
let prevPhase: string | null = null
function setBusy(next: boolean): void {
busy = next
@@ -101,8 +149,15 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
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 {
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 {
@@ -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 {
const phase = state.connection.phase
const phaseChanged = phase !== prevPhase
prevPhase = phase
notice.textContent = state.connection.notice ?? ''
notice.hidden = state.connection.notice === null
error.textContent = state.connection.error ?? ''
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
// leave a roster (or names) behind the sign-in page.
if (phase !== 'live') {
role.textContent = ''
scene.textContent = ''
me.textContent = ''
roster.replaceChildren()
// Leaving the game clears every server-derived DOM text, so a revoked session cannot leave a
// roster (or names) behind the sign-in page. A reconnect keeps the view: the badge says it is
// stale, and the resync after the next `hello` replaces it.
if (phase === 'signin' || phase === 'offline' || phase === 'reload' || phase === 'boot') {
clearHud()
setNameBusy(false)
}
switch (phase) {
@@ -152,6 +231,24 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
break
case 'live':
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)
role.textContent = state.session.role === 'gm' ? 'GM' : 'Player'
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
View File
@@ -28,6 +28,7 @@ body {
#boot,
#signin,
#name,
#fatal {
position: absolute;
inset: 0;
@@ -40,14 +41,16 @@ body {
text-align: center;
}
#signin form {
#signin form,
#name form {
display: flex;
flex-direction: column;
gap: 8px;
width: min(360px, 90vw);
}
#key {
#key,
#name-input {
font: inherit;
padding: 10px 12px;
border-radius: 6px;
@@ -58,7 +61,13 @@ body {
text-transform: uppercase;
}
#name-input {
letter-spacing: normal;
text-transform: none;
}
#signin button,
#name button,
#fatal button {
font: inherit;
padding: 10px 12px;
@@ -68,7 +77,8 @@ body {
color: inherit;
}
#signin-error {
#signin-error,
#name-error {
color: #ff8a8a;
}
@@ -102,3 +112,32 @@ body {
#roster-state {
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
View File
@@ -1,11 +1,15 @@
// The protocol client (DESIGN 6.2, 6.3, 6.5; spec #63 decision 14). It owns the socket, the `reqId`
// counter and the pending-request map; it emits reducer events and never touches the DOM. The
// socket factory and clock-free design make it unit-testable without a browser.
// counter, the pending-request map and the reconnect schedule; it emits reducer events and never
// touches the DOM. The socket factory, the clock and the random source are injectable, so the
// backoff and the retry state machine are unit-testable without a browser and without waiting.
//
// Close mapping (6.5, FIXED #18): a server-initiated close is `closing {reason, code}` and then a
// close frame the browser reports as 1005, so the reason always comes from the last `closing` frame.
// `revoked` and `proto-mismatch` are terminal: this client does not reconnect to them. Reconnect
// with backoff is T5 (#68); T4 only proves the outcome mapping.
// `revoked` and `proto-mismatch` are terminal (the reducer goes to the sign-in page / reload and
// this client stops). A close with no `closing` frame is a transport failure: the socket retries
// with exponential backoff and jitter, because a flaky phone network must recover without a reload
// (stories 7, 8). Pending reqIds are dropped with every connection (6.3); a `hello` on a live
// connection does not drop them.
import type { AckFrame, CloseReason, ServerFrame } from './protocol.ts'
import { encodeIntent, isAck, isClosing, parseServerFrame, wsUrl } from './protocol.ts'
@@ -23,11 +27,53 @@ export type ClientEvent =
| { type: 'open' }
| { type: 'frame'; frame: ServerFrame }
| { type: 'close'; reason: CloseReason | null; code: number | null }
| { type: 'reconnecting'; attempt: number; delay: number }
/** The reconnect delays of DESIGN 6.3: 1/2/4/8/10 s, then the cap. Attempts are 1-based. */
export const RECONNECT_BASE_DELAYS_MS = [1000, 2000, 4000, 8000, 10000] as const
/** Jitter is +/- this fraction of the base delay (story 8: "growing, jittered delays"). */
export const RECONNECT_JITTER = 0.2
/** The un-jittered delay for a 1-based attempt number; past the last entry the cap holds. */
export function reconnectBaseMs(attempt: number): number {
const index = Math.min(Math.max(Math.floor(attempt), 1), RECONNECT_BASE_DELAYS_MS.length) - 1
return RECONNECT_BASE_DELAYS_MS[index] ?? RECONNECT_BASE_DELAYS_MS[RECONNECT_BASE_DELAYS_MS.length - 1]!
}
/** The next retry delay: the base schedule times a random factor in [1-jitter, 1+jitter). */
export function backoffDelay(attempt: number, random: () => number = Math.random): number {
const base = reconnectBaseMs(attempt)
const factor = 1 - RECONNECT_JITTER + clamp(random()) * 2 * RECONNECT_JITTER
return Math.round(base * factor)
}
function clamp(value: number): number {
if (!Number.isFinite(value)) return 0.5
return Math.min(Math.max(value, 0), 1)
}
/** `setTimeout`'s handle in the browser; tests substitute their own clock behind this type. */
export type TimerHandle = number
export interface Timers {
setTimeout(fn: () => void, ms: number): TimerHandle
clearTimeout(handle: TimerHandle): void
}
const defaultTimers: Timers = {
setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms) as unknown as TimerHandle,
clearTimeout: handle => globalThis.clearTimeout(handle),
}
export interface ProtocolClientOptions {
url?: string
createSocket?: (url: string) => SocketLike
onEvent: (event: ClientEvent) => void
/** Transport failures retry by default (DESIGN 6.3); a terminal server outcome never does. */
autoReconnect?: boolean
random?: () => number
timers?: Timers
}
type Pending = {
@@ -43,16 +89,26 @@ export class ProtocolClient {
#url: string
#createSocket: (url: string) => SocketLike
#onEvent: (event: ClientEvent) => void
#autoReconnect: boolean
#random: () => number
#timers: Timers
#socket: SocketLike | null = null
#nextReqId = 1
#pending = new Map<number, Pending>()
#lastClosing: { reason: CloseReason; code: number } | null = null
#state: 'idle' | 'connecting' | 'open' | 'closed' = 'idle'
/** A socket has opened at least once: only then can a transport close be a lost session. */
#everOpened = false
#attempt = 0
#retryTimer: TimerHandle | null = null
constructor(options: ProtocolClientOptions) {
this.#url = options.url ?? wsUrl()
this.#createSocket = options.createSocket ?? defaultSocket
this.#onEvent = options.onEvent
this.#autoReconnect = options.autoReconnect ?? true
this.#random = options.random ?? Math.random
this.#timers = options.timers ?? defaultTimers
}
get state(): 'idle' | 'connecting' | 'open' | 'closed' {
@@ -63,15 +119,33 @@ export class ProtocolClient {
return this.#pending.size
}
/** The number of consecutive retries scheduled/failed since the last successful open. */
get attempt(): number {
return this.#attempt
}
connect(): void {
if (this.#state !== 'idle') return
this.#state = 'connecting'
const socket = this.#createSocket(this.#url)
this.#lastClosing = null
let socket: SocketLike
try {
socket = this.#createSocket(this.#url)
} catch {
// A socket that cannot even be constructed is a failed upgrade, not a lost session: the
// reducer sends a visitor with no session to the sign-in page (6.5 row 2).
this.#state = 'closed'
this.#onEvent({ type: 'close', reason: null, code: null })
return
}
this.#socket = socket
socket.onopen = () => {
if (this.#state !== 'connecting') return
this.#state = 'open'
this.#everOpened = true
this.#attempt = 0
this.#onEvent({ type: 'open' })
}
socket.onmessage = event => {
@@ -93,10 +167,18 @@ export class ProtocolClient {
}
socket.onclose = event => {
if (this.#state === 'closed') return
this.#state = 'closed'
const reason = this.#lastClosing?.reason ?? null
const code = this.#lastClosing?.code ?? event.code ?? null
this.#failPending(new Error(`connection closed (${reason ?? code ?? 'no code'})`))
// A named reason always came from a `closing` frame: it is an application outcome, and
// 6.5 says the client must stop for revoked/proto-mismatch/evicted/flood. Only a bare
// transport close (reason null) is retried, and only after this client was live once.
if (reason === null && this.#autoReconnect && this.#everOpened) {
this.#onEvent({ type: 'close', reason, code })
this.#scheduleRetry()
return
}
this.#state = 'closed'
this.#onEvent({ type: 'close', reason, code })
}
}
@@ -124,7 +206,16 @@ export class ProtocolClient {
})
}
/** Retry at once instead of waiting out the backoff (used when the browser goes online). */
retryNow(): void {
if (this.#retryTimer === null) return
this.#timers.clearTimeout(this.#retryTimer)
this.#retryTimer = null
this.connect()
}
close(): void {
this.#cancelRetry()
if (this.#state === 'closed') return
this.#state = 'closed'
try {
@@ -135,6 +226,24 @@ export class ProtocolClient {
this.#failPending(new Error('connection closed by the client'))
}
#scheduleRetry(): void {
this.#attempt += 1
const delay = backoffDelay(this.#attempt, this.#random)
this.#state = 'idle' // connect() may run again; the view stays in the reducer meanwhile
this.#socket = null
this.#onEvent({ type: 'reconnecting', attempt: this.#attempt, delay })
this.#retryTimer = this.#timers.setTimeout(() => {
this.#retryTimer = null
this.connect()
}, delay)
}
#cancelRetry(): void {
if (this.#retryTimer === null) return
this.#timers.clearTimeout(this.#retryTimer)
this.#retryTimer = null
}
#failPending(error: Error): void {
const pending = [...this.#pending.values()]
this.#pending.clear()