The website's half of protocol 6. Every event-driven write now carries the step's idempotency key, and `uo.broadcast` stops being un-retryable. Phase 9 shipped it answering `retry: false` to everything including a 503 from a shard that was merely restarting, with a comment naming the line that would change when the wire could refuse a repeat. This is that line: it defers to `sidecarFailure`, the same helper its two siblings already used, so the hand-rolled variant that forced every outcome terminal is gone rather than re-tuned. One verb was less idempotent than its own id made it look. Both keyed verbs post under a run-scoped id and a repeat replaces — but `news.add` with `announce: true` makes the criers proclaim the title on every post, so a retry replaced the article silently and proclaimed it again. The key stops the second proclamation. `champ.boss.killed` is mapped to the `champs` feature (rule 2 would otherwise fail it closed to admin), with `damagers` a nested `staff` field rule: the kill is public because a champion falling is what the board is for, the ranked roll of who was strong enough to fell it is not. `uo.champ.boss_killed` is declared as a trigger — which is what makes it usable as an event PHASE CONDITION, since a condition is written over a trigger firing — and it carries `damagerCount`, never a damager name, because a trigger variable reaches mail an operator may address to every subscriber. Its seeded rule is its own group, `champ-boss-killed-v1`: `triggers-v1` is stamped once under a settings guard, so appending a 27th entry would have reached fresh installs and nothing else. It also ships email+inapp and NOT push, and the comment says why — no trigger in this module is also a registered stream, so no engagement rule here can push. That is pre-existing in twenty rules and flagged rather than fixed; this one declines to be the twenty-first. Co-Authored-By: Claude <noreply@anthropic.com>
266 lines
13 KiB
JavaScript
266 lines
13 KiB
JavaScript
// ── uo-link sidecar REST client ────────────────────────────────────────────
|
|
//
|
|
// Server-side HTTP client for the uo-link sidecar (the bridge to the ServUO
|
|
// shard). Same shape as botInternalClient: never throws — every call returns
|
|
// { ok, data, status, error } so an admin poll or a public page never 500s just
|
|
// because the sidecar/shard is down or restarting.
|
|
//
|
|
// The base URL + shared-secret token come from the DB-backed uoLinkConfig
|
|
// (admin-managed, encrypted at rest) — NOT env vars, and the token is NEVER sent
|
|
// to the browser. Every request carries `Authorization: Bearer <token>` and
|
|
// `X-UOLink-Version: <protocol>` so a protocol mismatch is caught (409) rather
|
|
// than mis-parsed. Config is cached for a few seconds to avoid decrypting the
|
|
// token on every call.
|
|
//
|
|
// ── Protocol 6: `idempotencyKey` on a write ────────────────────────────────
|
|
//
|
|
// The three write helpers the event engine drives take an optional
|
|
// `idempotencyKey`, which the sidecar passes to the shard verbatim. The shard
|
|
// executes a key at most once and answers a repeat with the ORIGINAL reply, which
|
|
// is what makes retrying a world write safe — before it, a lost acknowledgement
|
|
// and a command that never applied were the same event seen from here.
|
|
//
|
|
// **A key is a function of the caller's unit of work, never of the attempt.** The
|
|
// event runner derives it from `sha256(runId|stepId)`, so every retry of one step
|
|
// carries the same key and a different step never collides with it. Passing a
|
|
// fresh value per call would satisfy the type and defeat the entire mechanism.
|
|
//
|
|
// **The DELETEs deliberately take no key.** Their idempotency is inherent — the
|
|
// second removal of a town-crier entry or a news article is a no-op the shard is
|
|
// already happy to perform — and the sidecar builds those commands from the path
|
|
// rather than from a body, so carrying one would be a protocol change bought for
|
|
// a guarantee that already holds.
|
|
//
|
|
// A caller that sends no key gets exactly the pre-protocol-6 behaviour, which is
|
|
// what leaves the admin screens (which send none, being driven by a human who can
|
|
// see whether the thing happened) unchanged.
|
|
//
|
|
// One new status can now come back from a keyed write: **425**, the sidecar's
|
|
// mapping of `bridge.busy` — a command under this key is still in flight on the
|
|
// shard. It is transient and retryable, and `shardAnnounce.classify` already
|
|
// treats it so by falling through to its retry case.
|
|
|
|
const uoLinkConfig = require('../model/uoLinkConfig/uoLinkConfig.model')
|
|
const log = require('../core').logger('uo-link-client')
|
|
|
|
// The sidecar waits up to 10s on the shard before answering 504, so this sits
|
|
// just above it — every call answers rather than being abandoned mid-flight.
|
|
//
|
|
// **Exported because the event actions are declared against it** (EVENTS_PLAN.md
|
|
// Phase 9). An action's `budgetMs` must exceed this or core's dispatch deadline
|
|
// fires first and classifies the step `retry` without asking the module, which
|
|
// for a broadcast means announcing twice. `config/uoEventActions.js` states that
|
|
// relationship and its test asserts it, and both need the number to come from
|
|
// here rather than from a copy that can drift.
|
|
const TIMEOUT_MS = 12000
|
|
const CONFIG_TTL_MS = 5000
|
|
|
|
let cachedConfig = null
|
|
let cachedAt = 0
|
|
|
|
// Read (and briefly cache) the connection config incl. decrypted token.
|
|
async function resolveConfig() {
|
|
const now = Date.now()
|
|
if (cachedConfig && now - cachedAt < CONFIG_TTL_MS) return cachedConfig
|
|
cachedConfig = await uoLinkConfig.getWithToken()
|
|
cachedAt = now
|
|
return cachedConfig
|
|
}
|
|
|
|
// Drop the cache after a save so the next call picks up new URL/token immediately.
|
|
function invalidateConfig() {
|
|
cachedConfig = null
|
|
cachedAt = 0
|
|
}
|
|
|
|
// Core request. Returns { ok, data, status, error }. `ok` is true only on a 2xx
|
|
// with a parseable JSON body. Non-2xx responses still return their status + body
|
|
// so callers can distinguish 503 (shard restarting — transient) from 404.
|
|
async function call(path, { method = 'GET', body } = {}) {
|
|
const controller = new AbortController()
|
|
const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS)
|
|
// resolveConfig() decrypts the stored auth token, and decryption THROWS when the
|
|
// ciphertext can't be authenticated — SECRET_ENC_KEY was rotated, or a DB dump was
|
|
// restored into an environment keyed differently. It must stay INSIDE the try: out
|
|
// here it escaped `call()` entirely and 500'd every live-shard route (admin and
|
|
// player character/roster/vendor lookups, GET /admin/uo-link/config) instead of
|
|
// degrading to "shard unavailable". This module never throws — see the header.
|
|
let configResolved = false
|
|
try {
|
|
const config = await resolveConfig()
|
|
configResolved = true
|
|
if (!config || !config.baseUrl) {
|
|
return { ok: false, status: 0, error: 'uo-link is not configured' }
|
|
}
|
|
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
'X-UOLink-Version': String(config.protocol || 3),
|
|
}
|
|
if (config.token) headers.Authorization = `Bearer ${config.token}`
|
|
|
|
const res = await fetch(`${config.baseUrl}${path}`, {
|
|
method,
|
|
headers,
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
signal: controller.signal,
|
|
})
|
|
|
|
let data = null
|
|
try {
|
|
data = await res.json()
|
|
} catch {
|
|
// Non-JSON (or empty) body — leave data null; status still reported.
|
|
}
|
|
|
|
if (!res.ok) {
|
|
if (res.status === 401) log.warn('uo-link rejected auth token (401)', { path })
|
|
if (res.status === 409) log.error('uo-link protocol mismatch (409)', { path, body: data })
|
|
return { ok: false, status: res.status, data, error: `sidecar responded ${res.status}` }
|
|
}
|
|
return { ok: true, status: res.status, data }
|
|
} catch (err) {
|
|
// A failure before the config resolved is a misconfiguration, not a flaky
|
|
// sidecar: log it loudly (and distinctly) so "the shard looks offline" doesn't
|
|
// silently mean "the token can no longer be decrypted".
|
|
if (!configResolved) {
|
|
log.error('uo-link config unreadable — is SECRET_ENC_KEY the key the stored token was encrypted with?', {
|
|
path,
|
|
message: err.message,
|
|
})
|
|
return { ok: false, status: 0, error: 'uo-link config unreadable' }
|
|
}
|
|
log.warn('uo-link call failed', { path, message: err.message })
|
|
return { ok: false, status: 0, error: err.message }
|
|
} finally {
|
|
clearTimeout(timeout)
|
|
}
|
|
}
|
|
|
|
// ── Read queries ───────────────────────────────────────────────────────────
|
|
// Liveness (no auth required by the sidecar, but we send it anyway).
|
|
const health = () => call('/health')
|
|
const getCharBySerial = (serial) => call(`/char/serial/${encodeURIComponent(serial)}`)
|
|
const getCharBySlot = (account, slot) =>
|
|
call(`/char/${encodeURIComponent(account)}/${encodeURIComponent(slot)}`)
|
|
const getRoster = (account) => call(`/roster/${encodeURIComponent(account)}`)
|
|
const getVendors = (account) => call(`/vendors/${encodeURIComponent(account)}`)
|
|
|
|
// History / economy series — used for WS-reconnect backfill and public feeds.
|
|
function getHistory({ kind, limit = 100 } = {}) {
|
|
const params = new URLSearchParams()
|
|
if (kind) params.set('kind', kind)
|
|
if (limit) params.set('limit', String(limit))
|
|
const qs = params.toString()
|
|
const suffix = qs ? `?${qs}` : ''
|
|
return call(`/history${suffix}`)
|
|
}
|
|
const getEconomy = (limit = 100) => call(`/economy?limit=${encodeURIComponent(limit)}`)
|
|
// Live board / queue projections — snapshotted on WS (re)connect and served from
|
|
// 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)
|
|
// Protocol 3.0: the shard's published ruleset. Object-shaped, not a board — the
|
|
// sidecar answers `{ ruleset: null }` until the shard has published one.
|
|
const getRuleset = () => call('/ruleset')
|
|
// Protocol 3.0: points/loyalty leaderboards. `/points` is board-shaped (an array
|
|
// under `boards`); the per-system read 404s for a system the shard never published.
|
|
const getPoints = () => call('/points')
|
|
const getPointsBoard = (system) => call(`/points/${encodeURIComponent(system)}`)
|
|
// Protocol 3.0: the player-vendor market index. The one PAGED sidecar read — a
|
|
// whole-world market does not fit in a response — so it answers with
|
|
// `{ vendors, total, limit, offset }` and the caller walks it (see uoLinkSocket).
|
|
const getMarket = ({ limit = 200, offset = 0 } = {}) =>
|
|
call(`/market?limit=${encodeURIComponent(limit)}&offset=${encodeURIComponent(offset)}`)
|
|
|
|
// ── Commands ──────────────────────────────────────────────────────────────
|
|
const confirmLink = (code, websiteUserId) =>
|
|
call('/link/confirm', { method: 'POST', body: { code, websiteUserId: String(websiteUserId) } })
|
|
const linkLookup = (account) => call(`/link/${encodeURIComponent(account)}`)
|
|
|
|
// Account provisioning (Protocol 2.0). createAccount provisions a game account and
|
|
// auto-links it to the website user in one step; `ip` is the END USER's browser IP
|
|
// (read from the request), which the shard needs for its per-IP account cap — the
|
|
// sidecar only sees our server. The password is hashed on the shard and never
|
|
// appears in any reply/event/log. unlinkAccount severs a game account's tie from
|
|
// the site side. `actor` is the staff/website id, recorded in the shard audit.
|
|
const createAccount = ({ actor, account, password, websiteUserId, ip }) =>
|
|
call('/accounts/create', {
|
|
method: 'POST',
|
|
body: { actor, account, password, websiteUserId: websiteUserId == null ? undefined : String(websiteUserId), ip },
|
|
})
|
|
const unlinkAccount = ({ actor, account }) =>
|
|
call(`/link/${encodeURIComponent(account)}`, { method: 'DELETE', body: { actor } })
|
|
const postTownCrier = ({ id, lines, durationSec, idempotencyKey }) =>
|
|
call('/towncrier', { method: 'POST', body: { id, lines, durationSec, idempotencyKey } })
|
|
const deleteTownCrier = (id) => call(`/towncrier/${encodeURIComponent(id)}`, { method: 'DELETE' })
|
|
|
|
// Town Cryer News gump (Protocol 2.1). A full article (title/HTML body/image/URL)
|
|
// in the in-game News window; re-posting the same id REPLACES it. `announce`
|
|
// (default true on the sidecar) controls whether the criers proclaim the title.
|
|
const postNews = ({ id, title, body, image, url, announce, idempotencyKey }) =>
|
|
call('/news', {
|
|
method: 'POST',
|
|
body: { id: String(id), title, body, image, url, announce, idempotencyKey },
|
|
})
|
|
const deleteNews = (id) => call(`/news/${encodeURIComponent(id)}`, { method: 'DELETE' })
|
|
|
|
// ── Staff write plane (§6) ─────────────────────────────────────────────────
|
|
// Every call carries `actor` — the website username of the staff member — set by
|
|
// the controller from the session, NEVER from the browser. The shard records it
|
|
// for attribution and echoes an admin.audit event back over the WS feed.
|
|
const adminKick = ({ actor, account, serial }) =>
|
|
call('/admin/kick', { method: 'POST', body: { actor, account, serial } })
|
|
const adminBan = ({ actor, account, serial, durationSec, reason }) =>
|
|
call('/admin/ban', { method: 'POST', body: { actor, account, serial, durationSec, reason } })
|
|
const adminUnban = ({ actor, account }) =>
|
|
call('/admin/unban', { method: 'POST', body: { actor, account } })
|
|
const adminBroadcast = ({ actor, text, hue, idempotencyKey }) =>
|
|
call('/admin/broadcast', { method: 'POST', body: { actor, text, hue, idempotencyKey } })
|
|
|
|
// ── Help-page (support) queue commands (§6) ────────────────────────────────
|
|
const respondPage = (pageId, { message, close }) =>
|
|
call(`/pages/${encodeURIComponent(pageId)}/respond`, { method: 'POST', body: { message, close } })
|
|
const closePage = (pageId) => call(`/pages/${encodeURIComponent(pageId)}/close`, { method: 'POST' })
|
|
|
|
module.exports = {
|
|
TIMEOUT_MS,
|
|
invalidateConfig,
|
|
health,
|
|
getCharBySerial,
|
|
getCharBySlot,
|
|
getRoster,
|
|
getVendors,
|
|
getHistory,
|
|
getEconomy,
|
|
getChamps,
|
|
getPages,
|
|
getGuilds,
|
|
getGovernors,
|
|
getHouses,
|
|
getPresence,
|
|
getRuleset,
|
|
getPoints,
|
|
getPointsBoard,
|
|
getMarket,
|
|
confirmLink,
|
|
linkLookup,
|
|
createAccount,
|
|
unlinkAccount,
|
|
postTownCrier,
|
|
deleteTownCrier,
|
|
postNews,
|
|
deleteNews,
|
|
adminKick,
|
|
adminBan,
|
|
adminUnban,
|
|
adminBroadcast,
|
|
respondPage,
|
|
closePage,
|
|
}
|