mc-dashboard/lib/server-status.ts
hurkicorgi 359a12ef9d SSE events bridge, PWA service worker, offline banner, lazy admin tabs
- New /api/events SSE endpoint (authed): pushes status every 5s and chat
  on log-file mtime change (~1.5s poll). Heartbeat every 15s, hard-caps
  each stream at 10min so the browser gets a clean auth refresh on
  reconnect. Auto-aborts on client disconnect.
- Factored shared helpers out of the existing routes:
  - lib/server-status.ts (probeStatus, reused by /api/status + SSE)
  - lib/chat-log.ts (parseLogLine, readChatMessages, logMtime, reused by
    /api/chat + SSE)
- EventsBridge client (mounted in Providers) opens one EventSource per
  authed session and writes live data into the TanStack Query cache for
  ["status"] and ["chat"] — no refactor needed in consuming components,
  they keep reading their usual query keys.
- Now that SSE pushes updates, polling intervals bumped: StatusCard and
  ServerControls 10s -> 60s, ChatBridge 5s -> 30s. SSE handles realtime,
  polling is safety fallback.
- OfflineBanner: sticky amber bar when navigator.onLine flips false.
- PWA: minimal public/sw.js with shell + asset cache (network-first for
  HTML, stale-while-revalidate for static assets, never touches /api/*
  or text/event-stream). ServiceWorkerRegister client registers it in
  production only.
- AdminTabs now uses next/dynamic with skeleton fallbacks for Players /
  Chat / Mods / Backups / Logs, keeping initial /admin bundle smaller.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 05:48:00 -06:00

47 lines
1.3 KiB
TypeScript

import { status } from "minecraft-server-util";
import { execSync } from "child_process";
import { MC_SERVER_IP, MC_SERVER_PORT } from "./constants";
import { sendCommand } from "./rcon";
export type StatusResult = {
online: boolean;
starting?: boolean;
players: { online: number; max: number };
version?: string;
motd?: string;
};
export async function probeStatus(): Promise<StatusResult> {
const ping = status(MC_SERVER_IP, MC_SERVER_PORT, { timeout: 3000 }).then(
(r): StatusResult => ({
online: true,
players: { online: r.players.online, max: r.players.max },
version: r.version.name,
motd: r.motd.clean,
})
);
const rcon = sendCommand("list").then((response): StatusResult => {
const match = response.match(/There are (\d+) of a max of (\d+) players/);
return {
online: true,
players: {
online: match ? parseInt(match[1], 10) : 0,
max: match ? parseInt(match[2], 10) : 20,
},
};
});
try {
return await Promise.any([ping, rcon]);
} catch {
let starting = false;
try {
const out = execSync("systemctl is-active minecraft.service", {
encoding: "utf8",
}).trim();
starting = out === "active" || out === "activating";
} catch {}
return { online: false, starting, players: { online: 0, max: 0 } };
}
}