feat(shard): ingest Protocol 2.0 boards — guilds, governors, presence, houses
Phase 1 of the Protocol 2.0/2.1 integration: the read/ingest backend for the four
new uo-link boards, following the established champs/pages pattern (ingest → our
MariaDB + snapshot-on-reconnect + public SSE + token-free public endpoint).
- Schema: shard_guilds, shard_governors, shard_governor_terms, shard_presence;
extend shard_houses with the house.update registry columns (owner_name,
co_owners, friends, price, decay, in_registry) so the decay-transition and
registry feeds share one house row without clobbering each other.
- Ingest: route guild.update/remove, city.update, presence.online,
house.update/remove; log guild.join (real-time joins feed); region.enter is
broadcast-only. All new public kinds added to the SSE allowlist.
- Governor term history captured from day one: on every observed governor CHANGE
the open term is closed and a new one opened, idempotent so backfill/duplicate
city.update never spawn spurious terms. votes stays NULL (the feed carries only
candidate count, not tallies) — we never fabricate vote numbers.
- Client + backfill: getGuilds/getGovernors/getHouses/getPresence; snapshot each
board on every WS (re)connect, independently guarded so an empty/failed board
(e.g. no City Loyalty) never wipes another.
- Public endpoints: /shard/{guilds,governors,governors/:city/history,presence,houses}.
- Tests: ingest routing for all new kinds + governor term-capture idempotency
(15 new; full suite 179/179). Swagger regenerated.
Refs .plans/protocol2-integration.md (Phase 1).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -107,12 +107,23 @@ const listHousesByAccounts = (accounts) =>
|
||||
accounts.length === 0
|
||||
? Promise.resolve([])
|
||||
: query(
|
||||
`SELECT ${HOUSE_COLS} FROM shard_houses
|
||||
`SELECT ${HOUSE_REG_COLS} FROM shard_houses
|
||||
WHERE owner_acct IN (${accounts.map(() => '?').join(', ')})
|
||||
ORDER BY is_idoc DESC, updated_at DESC`,
|
||||
accounts,
|
||||
)
|
||||
|
||||
// ── House registry (Protocol 2.0 house.update / house.remove) ──────────────
|
||||
// The registry columns extend HOUSE_COLS; a registry row is one we've seen via
|
||||
// house.update (in_registry = 1), as opposed to a decay-only transition row.
|
||||
const HOUSE_REG_COLS = `${HOUSE_COLS}, owner_name, co_owners, friends, price, decay, in_registry`
|
||||
|
||||
const removeHouse = (serial) => query('DELETE FROM shard_houses WHERE serial = ?', [serial])
|
||||
|
||||
// The full registered-house browser: every row we've seen via house.update.
|
||||
const listRegistryHouses = () =>
|
||||
query(`SELECT ${HOUSE_REG_COLS} FROM shard_houses WHERE in_registry = 1 ORDER BY name ASC`)
|
||||
|
||||
// ── Champion spawns ────────────────────────────────────────────────────────
|
||||
const CHAMP_COLS =
|
||||
'serial, category, type, name, status, active, map, x, y, z, boss_up, payload, t, updated_at'
|
||||
@@ -157,6 +168,104 @@ const clearPages = () => query('DELETE FROM shard_pages')
|
||||
// Oldest-open first so the queue reads like a work list.
|
||||
const listPages = () => query(`SELECT ${PAGE_COLS} FROM shard_pages ORDER BY sent_ms ASC`)
|
||||
|
||||
// ── Guild board (Protocol 2.0) ─────────────────────────────────────────────
|
||||
const GUILD_COLS =
|
||||
'id, name, abbr, members, online, alliance, leader_serial, leader_name, leader_acct, leader_web_id, payload, t, updated_at'
|
||||
|
||||
async function upsertGuild(id, fields) {
|
||||
const cols = Object.keys(fields)
|
||||
const allCols = ['id', ...cols]
|
||||
const insertCols = allCols.map((c) => `\`${c}\``).join(', ')
|
||||
const placeholders = allCols.map(() => '?').join(', ')
|
||||
const updates = cols.map((c) => `\`${c}\` = VALUES(\`${c}\`)`).join(', ')
|
||||
await query(
|
||||
`INSERT INTO shard_guilds (${insertCols}) VALUES (${placeholders})
|
||||
ON DUPLICATE KEY UPDATE ${updates}`,
|
||||
[id, ...cols.map((c) => fields[c])],
|
||||
)
|
||||
}
|
||||
|
||||
const removeGuild = (id) => query('DELETE FROM shard_guilds WHERE id = ?', [id])
|
||||
const clearGuilds = () => query('DELETE FROM shard_guilds')
|
||||
const listGuilds = () => query(`SELECT ${GUILD_COLS} FROM shard_guilds ORDER BY name ASC`)
|
||||
|
||||
// ── Governor board + term history (Protocol 2.0) ───────────────────────────
|
||||
const GOV_COLS =
|
||||
'city, governor_serial, governor_name, governor_acct, governor_web_id, elect_serial, elect_name, elect_acct, election_phase, candidates, auto_pick_at, payload, t, updated_at'
|
||||
|
||||
async function upsertGovernor(city, fields) {
|
||||
const cols = Object.keys(fields)
|
||||
const allCols = ['city', ...cols]
|
||||
const insertCols = allCols.map((c) => `\`${c}\``).join(', ')
|
||||
const placeholders = allCols.map(() => '?').join(', ')
|
||||
const updates = cols.map((c) => `\`${c}\` = VALUES(\`${c}\`)`).join(', ')
|
||||
await query(
|
||||
`INSERT INTO shard_governors (${insertCols}) VALUES (${placeholders})
|
||||
ON DUPLICATE KEY UPDATE ${updates}`,
|
||||
[city, ...cols.map((c) => fields[c])],
|
||||
)
|
||||
}
|
||||
|
||||
const listGovernors = () => query(`SELECT ${GOV_COLS} FROM shard_governors ORDER BY city ASC`)
|
||||
|
||||
// Cities whose current governor is one of the given game accounts (cross-link:
|
||||
// does this user hold a governorship?). Empty list short-circuits.
|
||||
const listGovernorshipsByAccounts = (accounts) =>
|
||||
accounts.length === 0
|
||||
? Promise.resolve([])
|
||||
: query(
|
||||
`SELECT ${GOV_COLS} FROM shard_governors
|
||||
WHERE governor_acct IN (${accounts.map(() => '?').join(', ')})
|
||||
ORDER BY city ASC`,
|
||||
accounts,
|
||||
)
|
||||
|
||||
// The single open term (ended_at IS NULL) for a city, if any.
|
||||
async function currentGovernorTerm(city) {
|
||||
const rows = await query(
|
||||
'SELECT id, city, governor_serial, governor_name, governor_acct, governor_web_id, started_at, ended_at, votes FROM shard_governor_terms WHERE city = ? AND ended_at IS NULL ORDER BY started_at DESC LIMIT 1',
|
||||
[city],
|
||||
)
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
const closeGovernorTerm = (id, endedAt) =>
|
||||
query('UPDATE shard_governor_terms SET ended_at = ? WHERE id = ?', [endedAt, id])
|
||||
|
||||
const openGovernorTerm = ({ city, serial, name, acct, webId, startedAt }) =>
|
||||
query(
|
||||
`INSERT INTO shard_governor_terms
|
||||
(city, governor_serial, governor_name, governor_acct, governor_web_id, started_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
[city, serial ?? null, name ?? null, acct ?? null, webId ?? null, startedAt],
|
||||
)
|
||||
|
||||
const listGovernorTerms = (city, limit) =>
|
||||
query(
|
||||
'SELECT id, city, governor_serial, governor_name, governor_acct, governor_web_id, started_at, ended_at, votes FROM shard_governor_terms WHERE city = ? ORDER BY started_at DESC LIMIT ?',
|
||||
[city, limit],
|
||||
)
|
||||
|
||||
// ── Online-population snapshot (Protocol 2.0 presence.online) ───────────────
|
||||
async function setPresence({ count, byFacet, byRegion, t }) {
|
||||
await query(
|
||||
`INSERT INTO shard_presence (id, count, by_facet, by_region, t) VALUES (1, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE count = VALUES(count), by_facet = VALUES(by_facet),
|
||||
by_region = VALUES(by_region), t = VALUES(t)`,
|
||||
[
|
||||
Number.isFinite(count) ? count : 0,
|
||||
byFacet ? JSON.stringify(byFacet) : null,
|
||||
byRegion ? JSON.stringify(byRegion) : null,
|
||||
Number.isFinite(t) ? t : null,
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
async function latestPresence() {
|
||||
const rows = await query('SELECT count, by_facet, by_region, t FROM shard_presence WHERE id = 1')
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
upsertOnline,
|
||||
removeOnline,
|
||||
@@ -171,6 +280,21 @@ module.exports = {
|
||||
upsertHouse,
|
||||
listIdocHouses,
|
||||
listHousesByAccounts,
|
||||
removeHouse,
|
||||
listRegistryHouses,
|
||||
upsertGuild,
|
||||
removeGuild,
|
||||
clearGuilds,
|
||||
listGuilds,
|
||||
upsertGovernor,
|
||||
listGovernors,
|
||||
listGovernorshipsByAccounts,
|
||||
currentGovernorTerm,
|
||||
closeGovernorTerm,
|
||||
openGovernorTerm,
|
||||
listGovernorTerms,
|
||||
setPresence,
|
||||
latestPresence,
|
||||
upsertChamp,
|
||||
removeChamp,
|
||||
clearChamps,
|
||||
|
||||
@@ -148,6 +148,13 @@ function shapeHouse(r) {
|
||||
name: r.name,
|
||||
ownerSerial: r.owner_serial,
|
||||
ownerAcct: r.owner_acct,
|
||||
// Registry fields (Protocol 2.0 house.update); undefined on decay-only rows.
|
||||
ownerName: r.owner_name,
|
||||
coOwners: r.co_owners,
|
||||
friends: r.friends,
|
||||
price: r.price == null ? null : Number(r.price),
|
||||
decay: r.decay,
|
||||
inRegistry: r.in_registry == null ? undefined : Boolean(r.in_registry),
|
||||
builtOn: r.built_on,
|
||||
lastRefreshed: r.last_refreshed,
|
||||
isIdoc: Boolean(r.is_idoc),
|
||||
@@ -166,6 +173,42 @@ async function listHousesForAccounts(accounts) {
|
||||
return rows.map(shapeHouse)
|
||||
}
|
||||
|
||||
// ── House registry (Protocol 2.0 house.update / house.remove) ──────────────
|
||||
// Richer per-house snapshot than the decay-transition feed. Writes only the
|
||||
// registry columns (+ shared location/owner fields); is_idoc/stage stay owned by
|
||||
// the house.decay path, so the two feeds never clobber each other. owner is an
|
||||
// actor object (or null for an abandoned house).
|
||||
async function upsertHouseRegistry(data) {
|
||||
if (!data || !data.serial) return
|
||||
const owner = data.owner || null
|
||||
const fields = {
|
||||
name: data.name ?? null,
|
||||
owner_serial: owner ? owner.serial ?? null : null,
|
||||
owner_acct: owner ? owner.acct ?? null : null,
|
||||
owner_name: owner ? owner.name ?? null : null,
|
||||
co_owners: data.coOwners ?? null,
|
||||
friends: data.friends ?? null,
|
||||
price: data.price ?? null,
|
||||
decay: data.decay ?? null,
|
||||
region: data.region ?? null,
|
||||
map: data.map ?? null,
|
||||
x: data.x ?? null,
|
||||
y: data.y ?? null,
|
||||
z: data.z ?? null,
|
||||
built_on: data.builtOn ? new Date(data.builtOn) : null,
|
||||
last_refreshed: data.lastRefreshed ? new Date(data.lastRefreshed) : null,
|
||||
in_registry: 1,
|
||||
}
|
||||
await db.upsertHouse(data.serial, fields)
|
||||
}
|
||||
|
||||
const removeHouse = (serial) => (serial ? db.removeHouse(serial) : Promise.resolve())
|
||||
|
||||
async function listHouses() {
|
||||
const rows = await db.listRegistryHouses()
|
||||
return rows.map(shapeHouse)
|
||||
}
|
||||
|
||||
// Online players on the given game accounts (admin: a user's linked accounts).
|
||||
async function listOnlineForAccounts(accounts) {
|
||||
const rows = await db.listOnlineByAccounts(accounts)
|
||||
@@ -287,6 +330,179 @@ async function replacePages(pages) {
|
||||
for (const ev of pages || []) await upsertPage(ev)
|
||||
}
|
||||
|
||||
// ── Guild board (Protocol 2.0) ─────────────────────────────────────────────
|
||||
// Upsert a guild's roster snapshot (guild.update). The leader is an actor object
|
||||
// flattened into leader_* columns; the full event lives in `payload`.
|
||||
async function upsertGuild(ev) {
|
||||
if (!ev || ev.id == null) return
|
||||
const leader = ev.leader || {}
|
||||
await db.upsertGuild(ev.id, {
|
||||
name: ev.name ?? null,
|
||||
abbr: ev.abbr ?? null,
|
||||
members: ev.members ?? null,
|
||||
online: ev.online ?? null,
|
||||
alliance: ev.alliance ?? null,
|
||||
leader_serial: leader.serial ?? null,
|
||||
leader_name: leader.name ?? null,
|
||||
leader_acct: leader.acct ?? null,
|
||||
leader_web_id: leader.webId ?? null,
|
||||
payload: JSON.stringify(ev),
|
||||
t: Number.isFinite(ev.t) ? ev.t : null,
|
||||
})
|
||||
}
|
||||
|
||||
const removeGuild = (id) => (id == null ? Promise.resolve() : db.removeGuild(id))
|
||||
const clearGuilds = () => db.clearGuilds()
|
||||
|
||||
function shapeGuild(r) {
|
||||
const payload = typeof r.payload === 'string' ? safeJson(r.payload) : r.payload
|
||||
return payload || {
|
||||
kind: 'guild.update',
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
abbr: r.abbr,
|
||||
members: r.members,
|
||||
online: r.online,
|
||||
alliance: r.alliance,
|
||||
leader: r.leader_serial
|
||||
? { serial: r.leader_serial, name: r.leader_name, acct: r.leader_acct, webId: r.leader_web_id }
|
||||
: null,
|
||||
t: r.t,
|
||||
}
|
||||
}
|
||||
|
||||
async function listGuilds() {
|
||||
const rows = await db.listGuilds()
|
||||
return rows.map(shapeGuild)
|
||||
}
|
||||
|
||||
// Replace the board with a fresh snapshot (sidecar GET /guilds on connect).
|
||||
async function replaceGuilds(guilds) {
|
||||
await db.clearGuilds()
|
||||
for (const ev of guilds || []) await upsertGuild(ev)
|
||||
}
|
||||
|
||||
// ── Town governors (Protocol 2.0) ──────────────────────────────────────────
|
||||
// Upsert a city's governance snapshot (city.update) AND capture term history.
|
||||
// Term capture runs first (it reads the CURRENT open term to decide whether the
|
||||
// governor changed) and is idempotent: a repeat/backfill of the same governor is a
|
||||
// no-op, so it's safe to call on the live feed and on reconnect snapshots alike.
|
||||
async function upsertGovernor(ev) {
|
||||
if (!ev || !ev.city) return
|
||||
await recordGovernorTransition(ev)
|
||||
const gov = ev.governor || null
|
||||
const elect = ev.governorElect || null
|
||||
await db.upsertGovernor(ev.city, {
|
||||
governor_serial: gov ? gov.serial ?? null : null,
|
||||
governor_name: gov ? gov.name ?? null : null,
|
||||
governor_acct: gov ? gov.acct ?? null : null,
|
||||
governor_web_id: gov ? gov.webId ?? null : null,
|
||||
elect_serial: elect ? elect.serial ?? null : null,
|
||||
elect_name: elect ? elect.name ?? null : null,
|
||||
elect_acct: elect ? elect.acct ?? null : null,
|
||||
election_phase: ev.electionPhase ?? null,
|
||||
candidates: ev.candidates ?? null,
|
||||
auto_pick_at: ev.autoPickAt ? new Date(ev.autoPickAt) : null,
|
||||
payload: JSON.stringify(ev),
|
||||
t: Number.isFinite(ev.t) ? ev.t : null,
|
||||
})
|
||||
}
|
||||
|
||||
// Close the open term and open a new one when the governor CHANGES. Idempotent:
|
||||
// same governor as the open term ⇒ nothing happens (so backfill/duplicate
|
||||
// city.update events never spawn spurious terms).
|
||||
async function recordGovernorTransition(ev) {
|
||||
const gov = ev.governor || null
|
||||
const newSerial = gov ? gov.serial ?? null : null
|
||||
const t = Number.isFinite(ev.t) ? ev.t : Date.now()
|
||||
const open = await db.currentGovernorTerm(ev.city)
|
||||
const openSerial = open ? open.governor_serial : null
|
||||
if (open && openSerial === newSerial) return // unchanged — nothing to record
|
||||
if (open) await db.closeGovernorTerm(open.id, t) // governor changed or seat vacated
|
||||
if (newSerial) {
|
||||
await db.openGovernorTerm({
|
||||
city: ev.city,
|
||||
serial: newSerial,
|
||||
name: gov.name ?? null,
|
||||
acct: gov.acct ?? null,
|
||||
webId: gov.webId ?? null,
|
||||
startedAt: t,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function shapeGovernor(r) {
|
||||
const payload = typeof r.payload === 'string' ? safeJson(r.payload) : r.payload
|
||||
return payload || {
|
||||
kind: 'city.update',
|
||||
city: r.city,
|
||||
governor: r.governor_serial
|
||||
? { serial: r.governor_serial, name: r.governor_name, acct: r.governor_acct, webId: r.governor_web_id }
|
||||
: null,
|
||||
governorElect: r.elect_serial
|
||||
? { serial: r.elect_serial, name: r.elect_name, acct: r.elect_acct }
|
||||
: null,
|
||||
electionPhase: r.election_phase,
|
||||
candidates: r.candidates,
|
||||
t: r.t,
|
||||
}
|
||||
}
|
||||
|
||||
async function listGovernors() {
|
||||
const rows = await db.listGovernors()
|
||||
return rows.map(shapeGovernor)
|
||||
}
|
||||
|
||||
// Cities the given game accounts currently govern (cross-link badge).
|
||||
async function listGovernorshipsForAccounts(accounts) {
|
||||
const rows = await db.listGovernorshipsByAccounts(accounts)
|
||||
return rows.map(shapeGovernor)
|
||||
}
|
||||
|
||||
// Term history for a city (look-back), newest first.
|
||||
async function listGovernorHistory(city, limit = 100) {
|
||||
const n = Math.min(Math.max(Number(limit) || 100, 1), 500)
|
||||
const rows = await db.listGovernorTerms(city, n)
|
||||
return rows.map((r) => ({
|
||||
city: r.city,
|
||||
governor: r.governor_serial
|
||||
? { serial: r.governor_serial, name: r.governor_name, acct: r.governor_acct, webId: r.governor_web_id }
|
||||
: null,
|
||||
startedAt: r.started_at == null ? null : Number(r.started_at),
|
||||
endedAt: r.ended_at == null ? null : Number(r.ended_at),
|
||||
votes: r.votes,
|
||||
}))
|
||||
}
|
||||
|
||||
// Upsert governors without clearing (cities are fixed, no remove event); term
|
||||
// capture inside upsertGovernor stays idempotent across reconnect snapshots.
|
||||
async function replaceGovernors(cities) {
|
||||
for (const ev of cities || []) await upsertGovernor(ev)
|
||||
}
|
||||
|
||||
// ── Online-population snapshot (Protocol 2.0 presence.online) ───────────────
|
||||
async function setPresence(ev) {
|
||||
if (!ev) return
|
||||
await db.setPresence({
|
||||
count: ev.count,
|
||||
byFacet: ev.byFacet || null,
|
||||
byRegion: ev.byRegion || null,
|
||||
t: ev.t,
|
||||
})
|
||||
}
|
||||
|
||||
async function latestPresence() {
|
||||
const r = await db.latestPresence()
|
||||
if (!r) return { count: 0, byFacet: {}, byRegion: {}, t: null }
|
||||
const parse = (v) => (typeof v === 'string' ? safeJson(v) || {} : v || {})
|
||||
return {
|
||||
count: Number(r.count) || 0,
|
||||
byFacet: parse(r.by_facet),
|
||||
byRegion: parse(r.by_region),
|
||||
t: r.t == null ? null : Number(r.t),
|
||||
}
|
||||
}
|
||||
|
||||
function safeJson(s) {
|
||||
try {
|
||||
return JSON.parse(s)
|
||||
@@ -309,6 +525,9 @@ module.exports = {
|
||||
upsertHouse,
|
||||
listIdoc,
|
||||
listHousesForAccounts,
|
||||
upsertHouseRegistry,
|
||||
removeHouse,
|
||||
listHouses,
|
||||
upsertChamp,
|
||||
removeChamp,
|
||||
clearChamps,
|
||||
@@ -319,4 +538,16 @@ module.exports = {
|
||||
clearPages,
|
||||
listPages,
|
||||
replacePages,
|
||||
upsertGuild,
|
||||
removeGuild,
|
||||
clearGuilds,
|
||||
listGuilds,
|
||||
replaceGuilds,
|
||||
upsertGovernor,
|
||||
listGovernors,
|
||||
listGovernorshipsForAccounts,
|
||||
listGovernorHistory,
|
||||
replaceGovernors,
|
||||
setPresence,
|
||||
latestPresence,
|
||||
}
|
||||
|
||||
@@ -184,6 +184,50 @@ publicRouter.get(
|
||||
/* #swagger.responses[200] = { description: 'Champion spawns, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */
|
||||
shard.getChamps,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/guilds',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'Current guild board (rosters, alliances, leaders)'
|
||||
// #swagger.description = 'The live board of every guild. Update in place via the guild.update / guild.remove / guild.join frames on /shard/stream.'
|
||||
/* #swagger.responses[200] = { description: 'Guilds, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */
|
||||
shard.getGuilds,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/governors',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'Current town-governor board (City Loyalty)'
|
||||
// #swagger.description = 'One entry per city with its governor and election phase. Empty if the shard does not run the City Loyalty system. Live via city.update on /shard/stream.'
|
||||
/* #swagger.responses[200] = { description: 'Cities, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */
|
||||
shard.getGovernors,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/governors/:city/history',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'Governor term history for a city'
|
||||
// #swagger.parameters['city'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'City name, e.g. Britain.' }
|
||||
// #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max terms (default 100, max 500).' }
|
||||
/* #swagger.responses[200] = { description: 'Terms, newest first', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */
|
||||
param('city').isString().isLength({ min: 1, max: 40 }),
|
||||
query('limit').optional().isInt({ min: 1, max: 500 }),
|
||||
validate,
|
||||
shard.getGovernorHistory,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/presence',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'Online population aggregate (count + per-facet + per-region)'
|
||||
// #swagger.description = 'The latest presence.online snapshot powering the "Players Online" widget. Live via presence.online on /shard/stream.'
|
||||
/* #swagger.responses[200] = { description: 'Population snapshot', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
|
||||
shard.getPresence,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/houses',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'House registry (owner, co-owners, price, decay)'
|
||||
// #swagger.description = 'Every house seen via the house.update registry feed. `price` is the placement value, not a for-sale flag. Live via house.update / house.remove on /shard/stream.'
|
||||
/* #swagger.responses[200] = { description: 'Houses, ordered by name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */
|
||||
shard.getHouses,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/stream',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
|
||||
@@ -104,9 +104,77 @@ async function getChamps(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
// GET /public/shard/guilds — the current guild board. Served from our store;
|
||||
// live via guild.update / guild.remove / guild.join on the public SSE stream.
|
||||
async function getGuilds(req, res) {
|
||||
try {
|
||||
return res.json(await shardState.listGuilds())
|
||||
} catch (err) {
|
||||
log.error('shard.getGuilds', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// GET /public/shard/governors — the current town-governor board (empty on shards
|
||||
// without City Loyalty). Live via city.update on the public SSE stream.
|
||||
async function getGovernors(req, res) {
|
||||
try {
|
||||
return res.json(await shardState.listGovernors())
|
||||
} catch (err) {
|
||||
log.error('shard.getGovernors', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// GET /public/shard/governors/:city/history — the term ledger for one city
|
||||
// (look-back: "who were all the governors of Britain?"), newest first.
|
||||
async function getGovernorHistory(req, res) {
|
||||
try {
|
||||
return res.json(await shardState.listGovernorHistory(req.params.city, req.query.limit))
|
||||
} catch (err) {
|
||||
log.error('shard.getGovernorHistory', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// GET /public/shard/presence — the online-population aggregate (count + per-facet
|
||||
// + per-region). Live via presence.online on the public SSE stream.
|
||||
async function getPresence(req, res) {
|
||||
try {
|
||||
return res.json(await shardState.latestPresence())
|
||||
} catch (err) {
|
||||
log.error('shard.getPresence', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// GET /public/shard/houses — the house registry (every house we've seen via
|
||||
// house.update). Live via house.update / house.remove on the public SSE stream.
|
||||
async function getHouses(req, res) {
|
||||
try {
|
||||
return res.json(await shardState.listHouses())
|
||||
} catch (err) {
|
||||
log.error('shard.getHouses', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// GET /public/shard/stream — public live-event SSE channel (safe kinds only).
|
||||
function stream(req, res) {
|
||||
broadcast.subscribe(req, res, 'public')
|
||||
}
|
||||
|
||||
module.exports = { getStatus, getFeed, getEconomy, getOnline, getIdoc, getChamps, stream }
|
||||
module.exports = {
|
||||
getStatus,
|
||||
getFeed,
|
||||
getEconomy,
|
||||
getOnline,
|
||||
getIdoc,
|
||||
getChamps,
|
||||
getGuilds,
|
||||
getGovernors,
|
||||
getGovernorHistory,
|
||||
getPresence,
|
||||
getHouses,
|
||||
stream,
|
||||
}
|
||||
|
||||
@@ -36,6 +36,15 @@ const PUBLIC_KINDS = new Set([
|
||||
// Champion-spawn board deltas — the public Champions page renders these live.
|
||||
'champ.update',
|
||||
'champ.remove',
|
||||
// Protocol 2.0 boards — all public, rendered live on their respective pages.
|
||||
'guild.update',
|
||||
'guild.remove',
|
||||
'guild.join',
|
||||
'city.update',
|
||||
'presence.online',
|
||||
'region.enter',
|
||||
'house.update',
|
||||
'house.remove',
|
||||
])
|
||||
|
||||
// Open response streams per channel.
|
||||
|
||||
@@ -39,6 +39,8 @@ const LOGGED_KINDS = new Set([
|
||||
'server.hello',
|
||||
'server.shutdown',
|
||||
'server.crashed',
|
||||
// Protocol 2.0: a real-time guild join (the board itself is state, not logged).
|
||||
'guild.join',
|
||||
])
|
||||
|
||||
// Tracks the current shard boot id so a restart (changed bootId on server.hello)
|
||||
@@ -146,6 +148,27 @@ async function applyStateChange(event, deps) {
|
||||
case 'page.closed':
|
||||
await shardState.removePage(event.pageId)
|
||||
return
|
||||
// ── Protocol 2.0 boards ──────────────────────────────────────────────
|
||||
case 'guild.update':
|
||||
await shardState.upsertGuild(event)
|
||||
return
|
||||
case 'guild.remove':
|
||||
await shardState.removeGuild(event.id)
|
||||
return
|
||||
case 'city.update':
|
||||
// Upserts the board AND captures term history (idempotent).
|
||||
await shardState.upsertGovernor(event)
|
||||
return
|
||||
case 'presence.online':
|
||||
await shardState.setPresence(event)
|
||||
return
|
||||
case 'house.update':
|
||||
await shardState.upsertHouseRegistry(event)
|
||||
return
|
||||
case 'house.remove':
|
||||
await shardState.removeHouse(event.serial)
|
||||
return
|
||||
// guild.join → logged (real-time feed); region.enter → broadcast-only.
|
||||
default:
|
||||
// No state side effect (e.g. vendor.sale, audit.*, cheat.*) — logging and
|
||||
// broadcasting still happen in ingest().
|
||||
|
||||
@@ -104,6 +104,11 @@ const getEconomy = (limit = 100) => call(`/economy?limit=${encodeURIComponent(li
|
||||
// our own store thereafter.
|
||||
const getChamps = () => call('/champs')
|
||||
const getPages = () => call('/pages')
|
||||
// Protocol 2.0 board projections — same snapshot-on-connect pattern.
|
||||
const getGuilds = () => call('/guilds')
|
||||
const getGovernors = () => call('/governors')
|
||||
const getHouses = () => call('/houses')
|
||||
const getPresence = () => call('/online') // aggregate population (count + byFacet/byRegion)
|
||||
|
||||
// ── Commands ──────────────────────────────────────────────────────────────
|
||||
const confirmLink = (code, websiteUserId) =>
|
||||
@@ -142,6 +147,10 @@ module.exports = {
|
||||
getEconomy,
|
||||
getChamps,
|
||||
getPages,
|
||||
getGuilds,
|
||||
getGovernors,
|
||||
getHouses,
|
||||
getPresence,
|
||||
confirmLink,
|
||||
linkLookup,
|
||||
postTownCrier,
|
||||
|
||||
@@ -75,6 +75,33 @@ async function backfill() {
|
||||
await shardState.replacePages(pages.data.pages)
|
||||
log.info('snapshotted help-page queue from /pages', { count: pages.data.pages.length })
|
||||
}
|
||||
|
||||
// ── Protocol 2.0 boards ──────────────────────────────────────────────
|
||||
// Same as champs/pages: snapshot the authoritative current state and
|
||||
// reconcile our tables to it. Each call is independently guarded so a
|
||||
// failed/absent board (e.g. no City Loyalty → empty /governors) never wipes
|
||||
// another. Governors are NOT cleared before upsert (cities are fixed and the
|
||||
// term-capture is idempotent, so a reconnect can't spawn spurious terms).
|
||||
const guilds = await uoLinkClient.getGuilds()
|
||||
if (guilds.ok && guilds.data && Array.isArray(guilds.data.guilds)) {
|
||||
await shardState.replaceGuilds(guilds.data.guilds)
|
||||
log.info('snapshotted guild board from /guilds', { count: guilds.data.guilds.length })
|
||||
}
|
||||
const governors = await uoLinkClient.getGovernors()
|
||||
if (governors.ok && governors.data && Array.isArray(governors.data.cities)) {
|
||||
await shardState.replaceGovernors(governors.data.cities)
|
||||
log.info('snapshotted governor board from /governors', { count: governors.data.cities.length })
|
||||
}
|
||||
const houses = await uoLinkClient.getHouses()
|
||||
if (houses.ok && houses.data && Array.isArray(houses.data.houses)) {
|
||||
for (const ev of houses.data.houses) await shardIngest.ingest(ev, { fromBackfill: true })
|
||||
log.info('snapshotted house registry from /houses', { count: houses.data.houses.length })
|
||||
}
|
||||
const presence = await uoLinkClient.getPresence()
|
||||
if (presence.ok && presence.data && typeof presence.data.count === 'number') {
|
||||
await shardState.setPresence(presence.data)
|
||||
log.info('snapshotted online population from /online', { count: presence.data.count })
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('backfill failed (continuing on live feed)', { message: err.message })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user