Phase 4. `/rust` is the server list and the module's landing page (D12);
`/rust/servers/:id` is one server with four tabs — feed, leaderboard, who is
on, wipes (D13). Everything selectable lives in the URL, so any view of the
page is a link. The feed and the presence list poll every twenty seconds while
the tab is visible and not at all when it is not (D14); the leaderboard and the
wipe list load once. `site.footer.status` is filled with a live server and
player count (D15).
Nothing on these pages calls a game server. Every field comes from this
module's own tables, which is what the phase criterion is about: the site
renders the last thing each server said while every server is off.
Walking that criterion in a browser against a live rig found four defects, two
of them already shipped in phase 3:
* An unreachable refresh called `putState` — the whole-row write — with two
fields, so a host that rebooted lost its hostname, map, size, seed and wipe
id. The list then read "Offline" with nothing beside it, which is not "here
is what we know" but "we have never heard of it". `markUnreachable` now
moves three columns and mentions no others.
* "Last reported" read `updated_at`, which a FAILED poll writes too — so an
offline server claimed it had reported just now, every thirty seconds, for
as long as it stayed down. `last_seen_at` is the new column, moved only by a
frame that arrived.
* Feed rows showed a bare time of day, so three events from six weeks ago all
read as this afternoon once the feed was filtered to a past wipe.
* `/rust/servers/typo` rendered core's ErrorState under its own heading and
read "No such server / Something went wrong", sending a reader who mistyped
a URL looking for an outage.
Also: a detail route (`GET …/servers/:id`), because it is the only route under
that path that can say a server does not exist — the other four answer an empty
list for an id nobody configured, and each of those is a good answer to its own
question.
`useAsync` cannot poll: it blanks its data on every dependency change, so a
twenty-second refresh built on it would clear the killfeed and re-fill it four
times a minute. `hooks/usePolled.js` is the module's own, invisible when it
succeeds and keeping the rows when it fails.
The client test fake was *nearly* core — it prefixed routes without stripping
the trailing separator, so the first module to register an index route failed
the nav check for a link that works in a browser. It now copies core's line
character for character.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016wDDVXWMDz82WqE1i969r4
117 lines
5.0 KiB
JavaScript
117 lines
5.0 KiB
JavaScript
// ── A poll that keeps what it already had ─────────────────────────────────
|
|
//
|
|
// **Why this is not `useAsync`.** Core's hook (MODULE_API.md §3.4, and
|
|
// `client/src/lib/useAsync.js` in core) is `useState({loading:true,error:null,data:null})`
|
|
// re-run on a dependency change — and the first thing it does on every run is
|
|
// blank `data` and set `loading`. That is right for a page load and wrong for a
|
|
// poll: bumping a dependency every twenty seconds would clear the killfeed,
|
|
// render `<Loading />` in its place and re-fill it, four times a minute, for ever.
|
|
//
|
|
// So a poll needs a hook whose refresh is INVISIBLE when it succeeds. It keeps
|
|
// the previous rows on screen, replaces them when the new ones arrive, and keeps
|
|
// them *and* reports the error when the fetch fails — because a site whose whole
|
|
// premise is "it renders while the game is off" must not blank the page the
|
|
// first time a request does.
|
|
//
|
|
// `useAsync` is still the right hook for everything that loads once, and the
|
|
// pages here use it for exactly that. Bundling this beside it is the kit working
|
|
// as intended: the nine shared members are the chrome every module must share,
|
|
// not a ceiling on what a module may write.
|
|
//
|
|
// ── Two behaviours worth knowing ──────────────────────────────────────────
|
|
//
|
|
// 1. **A backgrounded tab does not poll.** Page Visibility, plus an immediate
|
|
// refresh when the viewer comes back — which is also the moment stale rows
|
|
// are most visible. A tab left open overnight is otherwise a request every
|
|
// twenty seconds until the laptop dies.
|
|
// 2. **`key` resets, dependencies do not.** Switching server or wipe SHOULD
|
|
// blank the rows: what is on screen belongs to a different question. That is
|
|
// what `key` is for, and it is separate from the interval.
|
|
|
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
|
|
/**
|
|
* @param {() => Promise<any>} fetcher called with no arguments; must not throw synchronously
|
|
* @param {object} options
|
|
* @param {string} options.key changes when the QUESTION changes, blanking the answer
|
|
* @param {number} options.intervalMs 0 disables polling — the hook then loads once
|
|
* @param {boolean} options.enabled false while the page has nothing to ask about yet
|
|
*/
|
|
export function usePolled(fetcher, { key = '', intervalMs = 20000, enabled = true } = {}) {
|
|
const [state, setState] = useState({ data: null, error: null, loading: enabled, at: null })
|
|
|
|
// The fetcher is rebuilt on every render — it closes over props — and a hook
|
|
// that listed it as a dependency would restart its interval every render. The
|
|
// ref is how the timer keeps calling the CURRENT one without depending on it.
|
|
const latest = useRef(fetcher)
|
|
latest.current = fetcher
|
|
|
|
// Guards a reply from a question nobody is asking any more: a slow request
|
|
// whose page has moved on, or one still in flight at unmount.
|
|
const generation = useRef(0)
|
|
|
|
const run = useCallback(
|
|
async (mine) => {
|
|
try {
|
|
const data = await latest.current()
|
|
if (mine !== generation.current) return
|
|
setState({ data, error: null, loading: false, at: Date.now() })
|
|
} catch (error) {
|
|
if (mine !== generation.current) return
|
|
// `data` is carried forward deliberately. A failed refresh is a page that
|
|
// says "this is what we last knew, and it did not refresh", which is the
|
|
// same promise the server list makes about a game server being down.
|
|
setState((prev) => ({ data: prev.data, error, loading: false, at: prev.at }))
|
|
}
|
|
},
|
|
[],
|
|
)
|
|
|
|
const refresh = useCallback(() => run(generation.current), [run])
|
|
|
|
useEffect(() => {
|
|
generation.current += 1
|
|
const mine = generation.current
|
|
|
|
if (!enabled) {
|
|
setState({ data: null, error: null, loading: false, at: null })
|
|
return undefined
|
|
}
|
|
|
|
setState({ data: null, error: null, loading: true, at: null })
|
|
run(mine)
|
|
|
|
if (!intervalMs) return () => { generation.current += 1 }
|
|
|
|
let timer = null
|
|
|
|
const visible = () => typeof document === 'undefined' || document.visibilityState === 'visible'
|
|
|
|
const start = () => {
|
|
if (timer === null) timer = setInterval(() => run(mine), intervalMs)
|
|
}
|
|
const stop = () => {
|
|
if (timer !== null) { clearInterval(timer); timer = null }
|
|
}
|
|
|
|
const onVisibility = () => {
|
|
if (visible()) { run(mine); start() } else stop()
|
|
}
|
|
|
|
if (visible()) start()
|
|
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisibility)
|
|
|
|
return () => {
|
|
// Bumping the generation on teardown is what makes an in-flight reply from
|
|
// the old question land nowhere. Clearing the timer alone would not.
|
|
generation.current += 1
|
|
stop()
|
|
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisibility)
|
|
}
|
|
}, [key, intervalMs, enabled, run])
|
|
|
|
return { ...state, refresh }
|
|
}
|
|
|
|
export default usePolled
|