mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-07-16 16:52:34 +00:00
Add live game stats endpoint to the admin bot API (#4399)
## Summary The game simulation runs **client-side**, so the server can't directly see what's happening in a running game. This adds a way for the admin bot to observe a live game: clients report a live stats snapshot every ~10s, the server reaches consensus on it (reusing the winner's vote mechanism), and a new admin-bot endpoint serves it. ## How it works 1. **`LiveStatsController`** (client) emits a snapshot every **100 turns** (~10s at 100ms/turn) — only deterministic sim values, with players sorted by clientID, so in-sync clients produce an identical payload. 2. The snapshot is sent as a new **`live_stats`** wire message wrapping a `LiveStats` object (`turn` + per-human-player `tilesOwned`/`troops`/`gold`/`isAlive`/`team`). 3. **`GameServer.handleLiveStats`** tallies a per-turn **IP-weighted majority vote** — the same consensus the winner uses — and keeps the latest agreed snapshot. 4. **`GET /api/adminbot/game/:id/stats`** returns it, enriched with usernames the server already holds. `liveStats` is `null` until the first consensus. The winner's vote tally was extracted into a small reusable **`VoteRound`** (`src/server/VoteTally.ts`) and is now used for both winner and live-stats consensus. Names are deliberately **excluded** from the voted payload (they vary per client under name anonymization, which would break exact-match consensus); the server joins `clientID → username` instead. ## Changes - `src/server/VoteTally.ts` *(new)* — reusable IP-weighted `VoteRound` - `src/core/Schemas.ts` — `PlayerLiveStatsSchema`, `LiveStatsSchema`, `ClientSendLiveStatsSchema` + unions - `src/client/controllers/LiveStatsController.ts` *(new)* — per-100-turn snapshot reporter - `src/client/Transport.ts` — `SendLiveStatsEvent` + sender - `src/client/hud/GameRenderer.ts` — register the controller - `src/server/GameServer.ts` — refactor winner onto `VoteRound`; add live-stats consensus + `liveStats()` accessor - `src/server/AdminBotRoutes.ts` — `GET …/stats` endpoint ## Testing - **Unit:** `tests/server/VoteTally.test.ts` (majority/dedup/ties), `tests/server/LiveStats.test.ts` (consensus, disagreement, per-client dedup, stale-turn rejection, turn advance, out-of-sync exclusion, + endpoint 200/404/400). Full suite green (`npm test`), typecheck + lint clean. - **Manual e2e** against the dev server: created an admin-bot game, joined it in a browser, force-started via `toggle_game_start_timer`, and confirmed `GET …/stats` returned the consensus snapshot with username enrichment and an advancing `turn`. Also verified wrong-worker → 400 and missing-key → 401. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
committed by
evanpelle
co-authored by
Claude Opus 4.8
parent
3f0592f84e
commit
8049ebcc7a
@@ -102,6 +102,24 @@ export function registerAdminBotRoutes(opts: {
|
||||
});
|
||||
});
|
||||
|
||||
// Read what's happening in a running game. The sim runs on the clients, so
|
||||
// this returns the latest live stats snapshot a majority of them agreed on
|
||||
// (liveStats is null until the first consensus is reached).
|
||||
app.get("/api/adminbot/game/:id/stats", requireAdminBotKey, (req, res) => {
|
||||
const id = req.params.id as string;
|
||||
if (!ownsGame(id, res)) return;
|
||||
|
||||
const game = gm.game(id);
|
||||
if (game === null) {
|
||||
return res.status(404).json({ error: "Game not found" });
|
||||
}
|
||||
|
||||
res.json({
|
||||
gameID: id,
|
||||
liveStats: game.liveStats(),
|
||||
});
|
||||
});
|
||||
|
||||
// Send an intent. Honors the lobby-management intents; everything else 400.
|
||||
app.post("/api/adminbot/game/:id/intent", requireAdminBotKey, (req, res) => {
|
||||
const id = req.params.id as string;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ClientID } from "../core/Schemas";
|
||||
const INTENTS_PER_SECOND = 10;
|
||||
const INTENTS_PER_MINUTE = 150;
|
||||
const MAX_INTENT_SIZE = 2000;
|
||||
const TOTAL_BYTES = 2 * 1024 * 1024; // 2MB per client
|
||||
const TOTAL_BYTES = 5 * 1024 * 1024; // 5MB per client
|
||||
export type RateLimitResult = "ok" | "limit" | "kick";
|
||||
|
||||
interface ClientBucket {
|
||||
|
||||
+111
-16
@@ -8,12 +8,15 @@ import { GameType } from "../core/game/Game";
|
||||
import {
|
||||
ClientID,
|
||||
ClientMessageSchema,
|
||||
ClientSendLiveStatsMessage,
|
||||
ClientSendWinnerMessage,
|
||||
GameConfig,
|
||||
GameInfo,
|
||||
GameStartInfo,
|
||||
GameStartInfoSchema,
|
||||
Intent,
|
||||
LiveStats,
|
||||
PlayerLiveStats,
|
||||
PlayerRecord,
|
||||
PublicGameType,
|
||||
ServerDesyncSchema,
|
||||
@@ -30,6 +33,7 @@ import { archive, finalizeGameRecord } from "./Archive";
|
||||
import { Client } from "./Client";
|
||||
import { ClientMsgRateLimiter } from "./ClientMsgRateLimiter";
|
||||
import { ServerEnv } from "./ServerEnv";
|
||||
import { VoteRound } from "./VoteTally";
|
||||
export enum GamePhase {
|
||||
Lobby = "LOBBY",
|
||||
Active = "ACTIVE",
|
||||
@@ -104,10 +108,17 @@ export class GameServer {
|
||||
|
||||
private websockets: Set<WebSocket> = new Set();
|
||||
|
||||
private winnerVotes: Map<
|
||||
string,
|
||||
{ winner: ClientSendWinnerMessage; ips: Set<string> }
|
||||
private winnerVotes = new VoteRound<ClientSendWinnerMessage>();
|
||||
|
||||
// Per-turn consensus on the live stats snapshot (see handleLiveStats).
|
||||
// Tallies are keyed by turn number; an entry is removed once consensus is
|
||||
// reached for that turn (or a later one) so the map stays small.
|
||||
private liveStatsVotes: Map<
|
||||
number,
|
||||
{ round: VoteRound<LiveStats>; voters: Set<ClientID> }
|
||||
> = new Map();
|
||||
private latestLiveStats: LiveStats | null = null;
|
||||
private static readonly MAX_PENDING_LIVE_STATS_ROUNDS = 20;
|
||||
|
||||
private _hasEnded = false;
|
||||
|
||||
@@ -615,6 +626,10 @@ export class GameServer {
|
||||
this.handleWinner(client, clientMsg);
|
||||
break;
|
||||
}
|
||||
case "live_stats": {
|
||||
this.handleLiveStats(client, clientMsg);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
this.log.warn(`Unknown message type: ${(clientMsg as any).type}`, {
|
||||
clientID: client.clientID,
|
||||
@@ -1309,34 +1324,114 @@ export class GameServer {
|
||||
|
||||
// Add client vote
|
||||
const winnerKey = JSON.stringify(clientMsg.winner);
|
||||
if (!this.winnerVotes.has(winnerKey)) {
|
||||
this.winnerVotes.set(winnerKey, { ips: new Set(), winner: clientMsg });
|
||||
}
|
||||
const potentialWinner = this.winnerVotes.get(winnerKey)!;
|
||||
potentialWinner.ips.add(client.ip);
|
||||
const activeUniqueIPs = new Set(this.activeClients.map((c) => c.ip)).size;
|
||||
const votes = this.winnerVotes.add(winnerKey, clientMsg, client.ip);
|
||||
|
||||
const activeUniqueIPs = new Set(this.activeClients.map((c) => c.ip));
|
||||
|
||||
const ratio = `${potentialWinner.ips.size}/${activeUniqueIPs.size}`;
|
||||
this.log.info(
|
||||
`received winner vote ${clientMsg.winner}, ${ratio} votes for this winner`,
|
||||
`received winner vote ${clientMsg.winner}, ${votes}/${activeUniqueIPs} votes for this winner`,
|
||||
{
|
||||
clientID: client.clientID,
|
||||
},
|
||||
);
|
||||
|
||||
if (potentialWinner.ips.size * 2 < activeUniqueIPs.size) {
|
||||
const result = this.winnerVotes.result(activeUniqueIPs);
|
||||
if (result === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Vote succeeded
|
||||
this.winner = potentialWinner.winner;
|
||||
this.winner = result.value;
|
||||
this.log.info(
|
||||
`Winner determined by ${potentialWinner.ips.size}/${activeUniqueIPs.size} active IPs`,
|
||||
`Winner determined by ${result.votes}/${activeUniqueIPs} active IPs`,
|
||||
{
|
||||
winnerKey: winnerKey,
|
||||
winnerKey,
|
||||
},
|
||||
);
|
||||
this.archiveGame();
|
||||
}
|
||||
|
||||
// Clients each send a live stats snapshot every ~10s tagged with the turn it
|
||||
// was taken at. In-sync clients produce an identical snapshot for a given
|
||||
// turn, so we reach majority consensus (same IP-weighted vote as the winner)
|
||||
// and keep the latest agreed snapshot for the admin bot to read.
|
||||
private handleLiveStats(
|
||||
client: Client,
|
||||
clientMsg: ClientSendLiveStatsMessage,
|
||||
) {
|
||||
if (
|
||||
this.outOfSyncClients.has(client.clientID) ||
|
||||
this.isKicked(client.clientID)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const stats = clientMsg.stats;
|
||||
const turn = stats.turn;
|
||||
// Ignore turns we've already reached consensus on (or older ones).
|
||||
if (this.latestLiveStats !== null && turn <= this.latestLiveStats.turn) {
|
||||
return;
|
||||
}
|
||||
|
||||
let entry = this.liveStatsVotes.get(turn);
|
||||
if (entry === undefined) {
|
||||
entry = { round: new VoteRound<LiveStats>(), voters: new Set() };
|
||||
this.liveStatsVotes.set(turn, entry);
|
||||
this.pruneLiveStatsVotes();
|
||||
}
|
||||
// One vote per client per turn.
|
||||
if (entry.voters.has(client.clientID)) {
|
||||
return;
|
||||
}
|
||||
entry.voters.add(client.clientID);
|
||||
|
||||
const activeUniqueIPs = new Set(this.activeClients.map((c) => c.ip)).size;
|
||||
entry.round.add(JSON.stringify(stats), stats, client.ip);
|
||||
const result = entry.round.result(activeUniqueIPs);
|
||||
if (result === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.latestLiveStats = result.value;
|
||||
// This turn (and any older still-pending ones) are now settled.
|
||||
for (const t of this.liveStatsVotes.keys()) {
|
||||
if (t <= turn) {
|
||||
this.liveStatsVotes.delete(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bound the pending-vote map in case consensus is never reached for some
|
||||
// turns (e.g. a persistent desync). Maps iterate in insertion order and turns
|
||||
// arrive ascending, so this drops the oldest pending rounds.
|
||||
private pruneLiveStatsVotes() {
|
||||
while (
|
||||
this.liveStatsVotes.size > GameServer.MAX_PENDING_LIVE_STATS_ROUNDS
|
||||
) {
|
||||
const oldest = this.liveStatsVotes.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
this.liveStatsVotes.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
// Latest majority-agreed live stats snapshot, with players enriched with
|
||||
// server-authoritative info the clients don't vote on: the username and
|
||||
// current connection status. null until the first consensus.
|
||||
public liveStats(): {
|
||||
turn: number;
|
||||
players: (PlayerLiveStats & {
|
||||
username: string | null;
|
||||
connected: boolean;
|
||||
})[];
|
||||
} | null {
|
||||
if (this.latestLiveStats === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
turn: this.latestLiveStats.turn,
|
||||
players: this.latestLiveStats.players.map((p) => ({
|
||||
...p,
|
||||
username: this.allClients.get(p.clientID)?.username ?? null,
|
||||
connected: !this.isClientDisconnected(p.clientID),
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// IP-weighted single-round vote used to reach consensus on a value that the
|
||||
// authoritative simulation only exists for on the clients (which run the game),
|
||||
// not the server. Clients each vote for a candidate value; a candidate wins once
|
||||
// a strict majority of the electorate's unique IPs back it.
|
||||
//
|
||||
// Used both for end-of-game winner consensus and for periodic running-stats
|
||||
// consensus (see GameServer).
|
||||
export class VoteRound<T> {
|
||||
private candidates = new Map<string, { value: T; ips: Set<string> }>();
|
||||
|
||||
// Records a vote for `value` (identified by the stable string `key`) from
|
||||
// `ip`. Repeat votes from the same IP for the same candidate are idempotent.
|
||||
// Returns the candidate's unique-IP vote count after the vote.
|
||||
add(key: string, value: T, ip: string): number {
|
||||
let candidate = this.candidates.get(key);
|
||||
if (candidate === undefined) {
|
||||
candidate = { value, ips: new Set() };
|
||||
this.candidates.set(key, candidate);
|
||||
}
|
||||
candidate.ips.add(ip);
|
||||
return candidate.ips.size;
|
||||
}
|
||||
|
||||
// Returns the winning value once some candidate holds a strict majority of
|
||||
// `totalUniqueIPs` (votes * 2 >= total), else null.
|
||||
result(totalUniqueIPs: number): { value: T; votes: number } | null {
|
||||
for (const candidate of this.candidates.values()) {
|
||||
if (candidate.ips.size * 2 >= totalUniqueIPs) {
|
||||
return { value: candidate.value, votes: candidate.ips.size };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user