Add public shard read endpoints + live SSE stream (phase 2)
Curated, same-origin, token-free reads so the browser never sees the sidecar
URL or token:
- public/shard.controller.js:
- GET /public/shard/status — connection state + online count + latest economy
(from the site's ingested data).
- GET /public/shard/feed?kind=&limit= — recent notable events from the log.
- GET /public/shard/economy — gold-supply series (oldest → newest).
- GET /public/shard/idoc — houses currently at IDOC.
- GET /public/shard/char/:serial — live sheet round-trip via uoLinkClient,
briefly cached; 503 (shard restarting) serves a stale cache or a retry
banner rather than an error.
- GET /public/shard/stream — public SSE channel (safe kinds only).
- Wired into public.routes.js with express-validator guards and #swagger
annotations; new "Public · Shard" tag + ShardStatus/ShardEvent/
ShardEconomyPoint/ShardHouse schemas; swagger-output.json regenerated.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011qPmpmVH1xGCiZoz9m9vW3
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
const express = require('express')
|
||||
const { body } = require('express-validator')
|
||||
const { body, param, query } = require('express-validator')
|
||||
|
||||
const ctrl = require('./public.controller')
|
||||
const shard = require('./shard.controller')
|
||||
const siteMode = require('../../../middleware/siteMode')
|
||||
const validate = require('../../../middleware/validate')
|
||||
const { contactLimiter } = require('../../../middleware/rateLimit')
|
||||
@@ -128,4 +129,66 @@ publicRouter.get(
|
||||
ctrl.getPage,
|
||||
)
|
||||
|
||||
// ── Shard live data (uo-link) ──────────────────────────────────────────────
|
||||
// Token-free, same-origin reads. The status/feed/economy/idoc endpoints read
|
||||
// the site's own ingested data; /char round-trips the live shard (cached). Not
|
||||
// site-mode gated — shard status is useful even during site maintenance.
|
||||
publicRouter.get(
|
||||
'/shard/status',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'Shard connection state, online count and latest economy'
|
||||
/* #swagger.responses[200] = { description: 'Shard status', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardStatus" } } } } */
|
||||
shard.getStatus,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/feed',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'Recent notable shard events (from the ingested log)'
|
||||
// #swagger.parameters['kind'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Filter to a single event kind, e.g. vendor.sale.' }
|
||||
// #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max rows (default 100, max 1000).' }
|
||||
/* #swagger.responses[200] = { description: 'Events, newest first', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEvent" } } } } } */
|
||||
query('kind').optional({ values: 'falsy' }).isString().isLength({ max: 48 }),
|
||||
query('limit').optional().isInt({ min: 1, max: 1000 }),
|
||||
validate,
|
||||
shard.getFeed,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/economy',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'Gold-supply time series (oldest → newest)'
|
||||
// #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max samples (default 100, max 1000).' }
|
||||
/* #swagger.responses[200] = { description: 'Economy samples', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEconomyPoint" } } } } } */
|
||||
query('limit').optional().isInt({ min: 1, max: 1000 }),
|
||||
validate,
|
||||
shard.getEconomy,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/idoc',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'Houses currently in danger (IDOC)'
|
||||
/* #swagger.responses[200] = { description: 'IDOC houses', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */
|
||||
shard.getIdoc,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/char/:serial',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'Live character sheet by serial (cached; degrades on shard restart)'
|
||||
// #swagger.parameters['serial'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Mobile serial, e.g. 0x24C.' }
|
||||
/* #swagger.responses[200] = { description: 'Character profile', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
|
||||
/* #swagger.responses[400] = { description: 'Invalid serial', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
|
||||
/* #swagger.responses[404] = { description: 'Character not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
|
||||
/* #swagger.responses[503] = { description: 'Shard restarting — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
|
||||
param('serial').matches(/^0x[0-9a-fA-F]+$/),
|
||||
validate,
|
||||
shard.getChar,
|
||||
)
|
||||
publicRouter.get(
|
||||
'/shard/stream',
|
||||
// #swagger.tags = ['Public · Shard']
|
||||
// #swagger.summary = 'Live shard event stream (Server-Sent Events, public/safe kinds)'
|
||||
// #swagger.description = 'text/event-stream of curated live events. Sensitive kinds (staff audit, cheat detection, login attempts, IPs) are NOT sent on this channel.'
|
||||
/* #swagger.responses[200] = { description: 'An SSE stream (Content-Type: text/event-stream).' } */
|
||||
shard.stream,
|
||||
)
|
||||
|
||||
module.exports = publicRouter
|
||||
|
||||
121
server/src/router/v1/public/shard.controller.js
Normal file
121
server/src/router/v1/public/shard.controller.js
Normal file
@@ -0,0 +1,121 @@
|
||||
// ── Public: shard live data ────────────────────────────────────────────────
|
||||
//
|
||||
// Same-origin, token-free read endpoints backed by the data the WS ingest
|
||||
// pipeline persists (shard_online / shard_events / shard_economy / shard_houses)
|
||||
// plus a live character round-trip to the sidecar. The browser never sees the
|
||||
// sidecar URL or token — every sidecar call is server-side (uoLinkClient).
|
||||
//
|
||||
// The stored-data endpoints are cheap DB reads. The live /char endpoint hits the
|
||||
// running shard, so it is briefly cached and degrades gracefully: a 503 (shard
|
||||
// restarting) surfaces as a retry-able banner rather than an error.
|
||||
|
||||
const shardEvents = require('../../../model/shardEvents/shardEvents.model')
|
||||
const shardState = require('../../../model/shardState/shardState.model')
|
||||
const uoLinkConfig = require('../../../model/uoLinkConfig/uoLinkConfig.model')
|
||||
const uoLinkClient = require('../../../utils/uoLinkClient')
|
||||
const broadcast = require('../../../utils/shardBroadcast')
|
||||
|
||||
const log = require('../../../utils/logger')('public-shard')
|
||||
|
||||
// Serials are opaque hex keys like "0x24C" — validate before hitting the sidecar.
|
||||
const SERIAL_RE = /^0x[0-9a-fA-F]+$/
|
||||
|
||||
// Tiny in-memory cache for live character sheets (the sidecar warns these hit the
|
||||
// live shard, so cache them). Keyed by serial; short TTL.
|
||||
const CHAR_TTL_MS = 20000
|
||||
const charCache = new Map()
|
||||
|
||||
// GET /public/shard/status — connection state + online count + latest economy.
|
||||
async function getStatus(req, res) {
|
||||
try {
|
||||
const config = await uoLinkConfig.getSafe()
|
||||
const [online, economy] = await Promise.all([
|
||||
shardState.onlineCount(),
|
||||
shardState.latestEconomy(),
|
||||
])
|
||||
return res.json({
|
||||
enabled: config.enabled,
|
||||
status: config.status,
|
||||
pluginConnected: config.pluginConnected,
|
||||
lastEventAt: config.lastEventAt,
|
||||
onlineCount: online,
|
||||
economy,
|
||||
})
|
||||
} catch (err) {
|
||||
log.error('shard.getStatus', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// GET /public/shard/feed?kind=&limit= — recent notable events from the log.
|
||||
async function getFeed(req, res) {
|
||||
try {
|
||||
const { kind, limit } = req.query
|
||||
const events = await shardEvents.list({ kind, limit })
|
||||
return res.json(events)
|
||||
} catch (err) {
|
||||
log.error('shard.getFeed', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// GET /public/shard/economy — gold-supply series, oldest → newest.
|
||||
async function getEconomy(req, res) {
|
||||
try {
|
||||
return res.json(await shardState.listEconomy(req.query.limit))
|
||||
} catch (err) {
|
||||
log.error('shard.getEconomy', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// GET /public/shard/idoc — houses currently in danger (stage IDOC).
|
||||
async function getIdoc(req, res) {
|
||||
try {
|
||||
return res.json(await shardState.listIdoc())
|
||||
} catch (err) {
|
||||
log.error('shard.getIdoc', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// GET /public/shard/char/:serial — live character sheet (cached briefly). A 503
|
||||
// from the sidecar means the shard is restarting: report it as such so the UI
|
||||
// can show a retry banner instead of an error.
|
||||
async function getChar(req, res) {
|
||||
const { serial } = req.params
|
||||
if (!SERIAL_RE.test(serial)) {
|
||||
return res.status(400).json({ message: 'Invalid serial.' })
|
||||
}
|
||||
|
||||
const cached = charCache.get(serial)
|
||||
if (cached && Date.now() - cached.at < CHAR_TTL_MS) {
|
||||
return res.json(cached.data)
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await uoLinkClient.getCharBySerial(serial)
|
||||
if (result.ok) {
|
||||
charCache.set(serial, { at: Date.now(), data: result.data })
|
||||
return res.json(result.data)
|
||||
}
|
||||
if (result.status === 404) return res.status(404).json({ message: 'Character not found.' })
|
||||
if (result.status === 503) {
|
||||
// Serve a stale cache if we have one; otherwise the restart banner.
|
||||
if (cached) return res.json(cached.data)
|
||||
return res.status(503).json({ message: 'The game server is restarting — try again shortly.' })
|
||||
}
|
||||
if (result.status === 0) return res.status(503).json({ message: 'Shard data is unavailable right now.' })
|
||||
return res.status(502).json({ message: 'Could not reach the shard.' })
|
||||
} catch (err) {
|
||||
log.error('shard.getChar', 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, getIdoc, getChar, stream }
|
||||
Reference in New Issue
Block a user