Files
browser/platform_web/components/ServerLiveOperations.tsx
T

464 lines
23 KiB
TypeScript

import { ListChecks, Pause, Play, RotateCw, Send, Sparkles, Terminal, Trash2, X } from "lucide-react";
import { type FormEvent, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import { platformApiClient } from "../api/client";
import type { LogEntryBody, LogStreamResponse } from "../api/types";
import { sourceRCONRawCommandRequest } from "../schemas/sourceRcon";
import { cx } from "../utils/classes";
import { EmptyState, ErrorState, LoadingState, ResultBadge } from "./StateViews";
type LoadState<T> = { status: "loading" } | { status: "error"; reason: string } | { status: "ready"; data: T };
type LiveLogEntry = LogEntryBody & { source: string; streamId: string; streamKey: string };
type TerminalLine = { id: string; tone: "input" | "info" | "success" | "warn" | "error"; text: string; at: string; sortKey: number; streamKey?: string; level?: string; seq?: number };
type TerminalQuickCommand = { label: string; command: string; hint: string };
const liveLogPollMs = 1000;
const terminalLogPollMs = 1000;
const logStreamPollMs = 5000;
const liveLogHistoryWindow = 100;
const terminalLogQueryLimit = 150;
const terminalHistoryWindow = 150;
const maxLogEntries = 500;
const maxTerminalLines = 600;
const terminalQuickCommandCatalog: Record<string, TerminalQuickCommand[]> = {
"game.scum": [
{ label: "查询玩家", command: "ListPlayers", hint: "SCUM RCON" },
{ label: "服务器信息", command: "ServerInfo", hint: "SCUM RCON" },
{ label: "设为中午", command: "SetTime 12", hint: "SCUM RCON" }
]
};
interface LiveOperationDrawerProps {
open: boolean;
title: string;
description?: string;
onClose: () => void;
children: ReactNode;
backdropClassName?: string;
panelClassName?: string;
bodyClassName?: string;
hideHeader?: boolean;
}
function LiveOperationDrawer({ open, title, description, onClose, children, backdropClassName, panelClassName, bodyClassName, hideHeader }: LiveOperationDrawerProps) {
useEffect(() => {
if (!open) return undefined;
const previous = document.body.style.overflow;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") onClose();
};
document.body.style.overflow = "hidden";
document.addEventListener("keydown", handleKeyDown);
return () => {
document.body.style.overflow = previous;
document.removeEventListener("keydown", handleKeyDown);
};
}, [onClose, open]);
if (!open) return null;
return (
<div className={cx("drawer-backdrop", backdropClassName)} role="presentation" onClick={onClose}>
<aside className={cx("drawer-panel live-operation-drawer", panelClassName)} role="dialog" aria-modal="true" aria-label={title} onClick={(event) => event.stopPropagation()}>
{!hideHeader && (
<div className="panel-header">
<div>
<h2>{title}</h2>
{description && <p className="page-status">{description}</p>}
</div>
<button type="button" className="theme-upload drawer-close" aria-label={`关闭${title}`} onClick={onClose}><X size={14} /><span>关闭</span></button>
</div>
)}
<div className={cx("live-operation-content", bodyClassName)}>{children}</div>
</aside>
</div>
);
}
interface ServerLiveLogDrawerProps {
open: boolean;
serverId: string;
serverName: string;
onClose: () => void;
}
export function ServerLiveLogDrawer({ open, serverId, serverName, onClose }: ServerLiveLogDrawerProps) {
const [streams, setStreams] = useState<LoadState<LogStreamResponse[]>>({ status: "loading" });
const [selectedStreamId, setSelectedStreamId] = useState("");
const [entries, setEntries] = useState<LiveLogEntry[]>([]);
const [cursorByStream, setCursorByStream] = useState<Record<string, number>>({});
const [paused, setPaused] = useState(false);
const [keyword, setKeyword] = useState("");
const [lastRefreshAt, setLastRefreshAt] = useState("");
const loadStreams = useCallback(async (showLoading = true) => {
if (!open) return;
if (showLoading) setStreams({ status: "loading" });
try {
const response = await platformApiClient.listServerLiveLogs(serverId);
setStreams({ status: "ready", data: response.items });
setSelectedStreamId((current) => response.items.some((stream) => stream.id === current) ? current : response.items[0]?.id ?? "");
} catch (error) {
setStreams({ status: "error", reason: error instanceof Error ? error.message : "实时日志源加载失败" });
}
}, [open, serverId]);
useEffect(() => {
if (!open) return;
setEntries([]);
setCursorByStream({});
setPaused(false);
void loadStreams();
}, [loadStreams, open]);
useEffect(() => {
if (!open) return undefined;
const timer = window.setInterval(() => void loadStreams(false).catch(() => undefined), logStreamPollMs);
return () => window.clearInterval(timer);
}, [loadStreams, open]);
const selectedStream = streams.status === "ready" ? streams.data.find((stream) => stream.id === selectedStreamId) : undefined;
const tailSelectedStream = useCallback(async () => {
if (!open || !selectedStream) return;
const afterSeq = cursorByStream[selectedStream.id] ?? initialLogCursor(selectedStream, liveLogHistoryWindow);
const cursor = await platformApiClient.queryLogStream({ logStreamId: selectedStream.id, afterSeq, limit: 100 });
const nextSeq = nextCursorSeq(afterSeq, cursor.entries, cursor.nextSeq);
setCursorByStream((current) => updateCursor(current, selectedStream.id, nextSeq));
setLastRefreshAt(new Date().toLocaleTimeString());
if (cursor.entries.length === 0) return;
setEntries((current) => [
...current,
...cursor.entries.map((entry) => ({ ...entry, source: selectedStream.source || selectedStream.streamKey, streamId: selectedStream.id, streamKey: selectedStream.streamKey }))
].slice(-maxLogEntries));
}, [cursorByStream, open, selectedStream]);
useEffect(() => {
if (!open || paused || !selectedStream) return undefined;
void tailSelectedStream().catch(() => undefined);
const timer = window.setInterval(() => void tailSelectedStream().catch(() => undefined), liveLogPollMs);
return () => window.clearInterval(timer);
}, [open, paused, selectedStream, tailSelectedStream]);
const visibleEntries = useMemo(() => {
const query = keyword.trim().toLowerCase();
return entries.filter((entry) => entry.streamId === selectedStreamId && (!query || entry.line.toLowerCase().includes(query) || (entry.level ?? "info").toLowerCase().includes(query)));
}, [entries, keyword, selectedStreamId]);
function clearVisibleBuffer() {
setEntries((current) => current.filter((entry) => entry.streamId !== selectedStreamId));
if (selectedStream) setCursorByStream((current) => ({ ...current, [selectedStream.id]: selectedStream.latestSeq }));
}
function selectLogStream(nextStreamId: string) {
setSelectedStreamId(nextStreamId);
setEntries([]);
setCursorByStream((current) => {
const next = { ...current };
delete next[nextStreamId];
return next;
});
}
return (
<LiveOperationDrawer open={open} title="实时日志" description={`${serverName} · 每 ${liveLogPollMs / 1000} 秒刷新一次平台日志游标`} onClose={onClose}>
<div className="log-filter-bar live-operation-toolbar">
<select value={selectedStreamId} aria-label="选择日志源" onChange={(event) => selectLogStream(event.target.value)}>
{streams.status === "ready" && streams.data.map((stream) => <option key={stream.id} value={stream.id}>{stream.streamKey || stream.source} · seq {stream.latestSeq}</option>)}
</select>
<input type="search" value={keyword} placeholder="过滤可见日志" aria-label="过滤可见日志" onChange={(event) => setKeyword(event.target.value)} />
<button type="button" className="icon-command" onClick={() => setPaused((current) => !current)}>{paused ? <Play size={14} /> : <Pause size={14} />}<span>{paused ? "继续" : "暂停"}</span></button>
<button type="button" className="icon-command" onClick={() => void tailSelectedStream().catch(() => undefined)}><RotateCw size={14} /><span>刷新</span></button>
<button type="button" className="icon-command" onClick={clearVisibleBuffer}><Trash2 size={14} /><span>清屏</span></button>
</div>
<span className="page-status">状态:{paused ? "已暂停" : "自动刷新"} · 最新刷新 {lastRefreshAt || "等待"} · 游标 {selectedStream ? cursorByStream[selectedStream.id] ?? 0 : "--"}</span>
{streams.status === "loading" && <LoadingState label="正在加载日志源…" compact />}
{streams.status === "error" && <ErrorState title="实时日志不可用" reason={streams.reason} diagnosticId={`live-logs:${serverId}`} onRetry={() => void loadStreams()} compact />}
{streams.status === "ready" && streams.data.length === 0 && <EmptyState title="暂无日志源" description="运行端还没有向平台登记该服务器的日志流。" />}
{streams.status === "ready" && streams.data.length > 0 && visibleEntries.length === 0 && <EmptyState title="等待日志" description="没有新的匹配日志;保持窗口打开会继续按游标刷新。" />}
{visibleEntries.length > 0 && (
<div className="log-list live-log-list" role="log" aria-live={paused ? "off" : "polite"}>
{visibleEntries.map((entry) => (
<div key={`${entry.streamId}-${entry.seq}`} className="log-line live-log-line">
<time>{new Date(entry.timestamp).toLocaleTimeString()}</time>
<span className={cx("log-level", levelClass(entry.level))}>{(entry.level ?? "info").toUpperCase()}</span>
<span>{entry.line}</span>
</div>
))}
</div>
)}
</LiveOperationDrawer>
);
}
interface ServerManagementTerminalDrawerProps {
open: boolean;
serverId: string;
serverName: string;
pluginId: string;
canManage: boolean;
onClose: () => void;
}
export function ServerManagementTerminalDrawer({ open, serverId, serverName, pluginId, canManage, onClose }: ServerManagementTerminalDrawerProps) {
const [command, setCommand] = useState("");
const [pending, setPending] = useState(false);
const [lines, setLines] = useState<TerminalLine[]>([]);
const [streams, setStreams] = useState<LoadState<LogStreamResponse[]>>({ status: "loading" });
const [cursorByStream, setCursorByStream] = useState<Record<string, number>>({});
const [commandHistory, setCommandHistory] = useState<string[]>([]);
const [historyIndex, setHistoryIndex] = useState<number | null>(null);
const [result, setResult] = useState<{ status: "pending" | "succeeded" | "failed"; label: string } | null>(null);
const quickCommands = useMemo(() => terminalQuickCommandsForPlugin(pluginId), [pluginId]);
const supportsCommands = quickCommands.length > 0;
const terminalStreams = useMemo(() => streams.status === "ready" ? terminalRelevantStreams(streams.data) : [], [streams]);
const appendLines = useCallback((incoming: TerminalLine[]) => {
if (incoming.length === 0) return;
setLines((current) => mergeTerminalLines(current, incoming));
}, []);
const loadStreams = useCallback(async (showLoading = true) => {
if (!open) return;
if (showLoading) setStreams({ status: "loading" });
try {
const response = await platformApiClient.listServerLiveLogs(serverId);
setStreams({ status: "ready", data: response.items });
} catch (error) {
setStreams({ status: "error", reason: error instanceof Error ? error.message : "实时日志源加载失败" });
}
}, [open, serverId]);
const tailTerminalLogs = useCallback(async (targetStreams = terminalStreams) => {
if (!open || targetStreams.length === 0) return;
const cursorUpdates: Record<string, number> = {};
const batches = await Promise.all(targetStreams.map(async (stream) => {
const afterSeq = cursorByStream[stream.id] ?? initialLogCursor(stream, terminalHistoryWindow);
const cursor = await platformApiClient.queryLogStream({ logStreamId: stream.id, afterSeq, limit: terminalLogQueryLimit });
cursorUpdates[stream.id] = nextCursorSeq(afterSeq, cursor.entries, cursor.nextSeq);
return cursor.entries.map((entry) => terminalLineFromLog(stream, entry));
}));
setCursorByStream((current) => {
let changed = false;
const next = { ...current };
for (const [streamId, cursor] of Object.entries(cursorUpdates)) {
const nextCursor = Math.max(next[streamId] ?? 0, cursor);
if (nextCursor !== next[streamId]) {
next[streamId] = nextCursor;
changed = true;
}
}
return changed ? next : current;
});
appendLines(batches.flat().sort(compareTerminalLines));
}, [appendLines, cursorByStream, open, terminalStreams]);
useEffect(() => {
if (!open) return;
setCommand("");
setPending(false);
setResult(null);
setCursorByStream({});
setHistoryIndex(null);
setLines([terminalSystemLine("info", supportsCommands ? "读取平台历史日志,后续按游标实时追加。" : "该插件暂未声明可用的管理终端命令通道。", "SYSTEM")]);
void loadStreams();
}, [loadStreams, open, supportsCommands]);
useEffect(() => {
if (!open) return undefined;
const timer = window.setInterval(() => void loadStreams(false).catch(() => undefined), logStreamPollMs);
return () => window.clearInterval(timer);
}, [loadStreams, open]);
useEffect(() => {
if (!open || streams.status !== "ready") return;
void tailTerminalLogs(terminalRelevantStreams(streams.data)).catch((error) => appendLines([terminalSystemLine("error", error instanceof Error ? error.message : "历史日志读取失败", "LOGS")]));
}, [appendLines, open, streams]);
useEffect(() => {
if (!open || terminalStreams.length === 0) return undefined;
const timer = window.setInterval(() => void tailTerminalLogs().catch(() => undefined), terminalLogPollMs);
return () => window.clearInterval(timer);
}, [open, tailTerminalLogs, terminalStreams]);
function selectQuickCommand(item: TerminalQuickCommand) {
setCommand(item.command);
setHistoryIndex(null);
}
function handleCommandKeyDown(event: ReactKeyboardEvent<HTMLInputElement>) {
if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
if (commandHistory.length === 0) return;
event.preventDefault();
const lastIndex = commandHistory.length - 1;
if (event.key === "ArrowUp") {
const nextIndex = historyIndex === null ? lastIndex : Math.max(0, historyIndex - 1);
setHistoryIndex(nextIndex);
setCommand(commandHistory[nextIndex] ?? "");
return;
}
if (historyIndex === null) return;
const nextIndex = historyIndex + 1;
if (nextIndex > lastIndex) {
setHistoryIndex(null);
setCommand("");
return;
}
setHistoryIndex(nextIndex);
setCommand(commandHistory[nextIndex] ?? "");
}
function clearTerminalBuffer() {
setLines([]);
}
async function submitCommand(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!supportsCommands || !canManage || pending || !command.trim()) return;
const submitted = command.trim();
setCommand("");
setHistoryIndex(null);
setCommandHistory((current) => [...current.filter((item) => item !== submitted), submitted].slice(-50));
setPending(true);
setResult({ status: "pending", label: "正在提交命令" });
appendLines([terminalSystemLine("input", `> ${submitted}`, "COMMAND")]);
try {
const response = await platformApiClient.sendSourceRCONCommand(serverId, sourceRCONRawCommandRequest(serverId, submitted));
const label = `已排队 · 任务 ${response.jobId}`;
setResult({ status: "succeeded", label });
appendLines([terminalSystemLine("success", `${label} · ${response.message || response.status}`, "PLATFORM", `ok-${response.jobId}`)]);
void tailTerminalLogs().catch(() => undefined);
} catch (error) {
const label = error instanceof Error ? error.message : "命令提交失败";
setResult({ status: "failed", label });
appendLines([terminalSystemLine("error", label, "ERROR")]);
} finally {
setPending(false);
}
}
return (
<LiveOperationDrawer open={open} title="管理终端" onClose={onClose} backdropClassName="terminal-drawer-backdrop" panelClassName="management-terminal-drawer" bodyClassName="management-terminal-body" hideHeader>
<section className="terminal-output-panel" aria-label="terminal output">
<div className="terminal-output-topbar">
<div>
<strong>{serverName}</strong>
<span>最近历史 + {terminalLogPollMs / 1000}s 实时刷新 · 日志源 {logStreamPollMs / 1000}s 探测 · {streams.status === "ready" ? `${terminalStreams.length} 个日志源` : streams.status === "loading" ? "读取日志源" : "日志源异常"}</span>
</div>
<div>
<button type="button" className="terminal-output-action" onClick={clearTerminalBuffer}><Trash2 size={14} /><span>清屏</span></button>
<button type="button" className="terminal-output-action" aria-label="关闭管理终端" onClick={onClose}><X size={14} /><span>关闭</span></button>
</div>
</div>
<div className="terminal-output" role="log" aria-live="polite">
{streams.status === "error" && <div className="terminal-line terminal-line-error"><time>{new Date().toLocaleTimeString()}</time><span className="terminal-stream">LOGS</span><span className="terminal-text">{streams.reason}</span></div>}
{streams.status === "ready" && streams.data.length === 0 && <div className="terminal-line terminal-line-warn"><time>{new Date().toLocaleTimeString()}</time><span className="terminal-stream">LOGS</span><span className="terminal-text">暂无日志源。需要 Run 上报或历史日志回填后,这里才会持续追加。</span></div>}
{lines.map((line) => <div key={line.id} className={`terminal-line terminal-line-${line.tone}`}><time>{line.at}</time><span className="terminal-stream">{line.streamKey || line.level || "LOG"}</span><span className="terminal-text">{line.text}</span></div>)}
</div>
</section>
<section className="terminal-command-dock" aria-label="terminal command controls">
<div className="terminal-command-dock-header">
<span><ListChecks size={14} />{quickCommands.length > 0 ? "插件快捷指令" : "命令输入"}</span>
{result && <ResultBadge status={result.status} label={result.label} />}
</div>
{quickCommands.length > 0 && <div className="terminal-quick-command-list">
{quickCommands.map((item) => <button key={item.command} type="button" className="terminal-quick-command" disabled={!canManage || pending} onClick={() => selectQuickCommand(item)}><strong>{item.label}</strong><span>{item.command}</span><small>{item.hint}</small></button>)}
</div>}
{!supportsCommands && <EmptyState icon={<Terminal size={24} />} title="终端不可用" description="当前插件没有声明平台可调度的即时命令能力,因此不会开放浏览器直连 shell。" />}
{supportsCommands && (
<form className="terminal-command-form" onSubmit={(event) => void submitCommand(event)}>
<label>
<span>SCUM 管理命令</span>
<small>Enter 发送,↑/ 调出历史;命令结果以 Run 日志追加为准。</small>
<input value={command} disabled={!canManage || pending} placeholder={canManage ? "输入单行命令" : "当前账号没有运行操作权限"} onKeyDown={handleCommandKeyDown} onChange={(event) => { setCommand(event.target.value); setHistoryIndex(null); }} />
</label>
<button type="submit" className="primary-command" disabled={!canManage || pending || !command.trim()}>{pending ? <Sparkles size={15} /> : <Send size={15} />}<span>{pending ? "提交中…" : "发送"}</span></button>
</form>
)}
</section>
</LiveOperationDrawer>
);
}
function levelClass(level?: string): string {
const normalized = (level ?? "info").toLowerCase();
if (normalized === "error" || normalized === "fatal") return "log-level-error";
if (normalized === "warn" || normalized === "warning") return "log-level-warn";
return "log-level-info";
}
function initialLogCursor(stream: LogStreamResponse, historyWindow: number): number {
return Math.max(0, stream.latestSeq - historyWindow);
}
function nextCursorSeq(afterSeq: number, entries: LogEntryBody[], nextSeq: number): number {
if (entries.length === 0) return Math.max(afterSeq, nextSeq);
return Math.max(afterSeq, nextSeq, entries[entries.length - 1]?.seq ?? afterSeq);
}
function updateCursor(current: Record<string, number>, streamId: string, cursor: number): Record<string, number> {
const nextCursor = Math.max(current[streamId] ?? 0, cursor);
if (nextCursor === current[streamId]) return current;
return { ...current, [streamId]: nextCursor };
}
function terminalQuickCommandsForPlugin(pluginId: string): TerminalQuickCommand[] {
return terminalQuickCommandCatalog[pluginId] ?? [];
}
function terminalRelevantStreams(streams: LogStreamResponse[]): LogStreamResponse[] {
return [...streams].sort(compareTerminalStreams).slice(0, 8);
}
function compareTerminalStreams(a: LogStreamResponse, b: LogStreamResponse): number {
return terminalStreamRank(a) - terminalStreamRank(b) || a.streamKey.localeCompare(b.streamKey) || a.id.localeCompare(b.id);
}
function terminalStreamRank(stream: LogStreamResponse): number {
const key = `${stream.source}:${stream.streamKey}`.toLowerCase();
if (key.includes("management-program")) return 0;
if (key.includes("stderr")) return 1;
if (key.includes("stdout")) return 2;
return 3;
}
function terminalLineFromLog(stream: LogStreamResponse, entry: LogEntryBody): TerminalLine {
return {
id: `log-${stream.id}-${entry.seq}`,
tone: terminalTone(entry),
text: entry.line,
at: new Date(entry.timestamp).toLocaleTimeString(),
sortKey: Date.parse(entry.timestamp) || Date.now(),
streamKey: stream.streamKey || stream.source,
level: entry.level,
seq: entry.seq
};
}
function terminalSystemLine(tone: TerminalLine["tone"], text: string, streamKey: string, id = `${streamKey.toLowerCase()}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`): TerminalLine {
const now = Date.now();
return { id, tone, text, at: new Date(now).toLocaleTimeString(), sortKey: now, streamKey };
}
function terminalTone(entry: LogEntryBody): TerminalLine["tone"] {
const value = `${entry.level ?? ""} ${entry.line}`.toLowerCase();
if (/\b(error|fatal|panic|exception|failed|failure)\b/.test(value)) return "error";
if (/\b(warn|warning|timeout|retry)\b/.test(value)) return "warn";
if (/\b(success|succeeded|ready|started|online|listening|accepted)\b/.test(value)) return "success";
return "info";
}
function mergeTerminalLines(current: TerminalLine[], incoming: TerminalLine[]): TerminalLine[] {
const seen = new Set(current.map((line) => line.id));
const merged = [...current];
for (const line of incoming) {
if (seen.has(line.id)) continue;
seen.add(line.id);
merged.push(line);
}
return merged.sort(compareTerminalLines).slice(-maxTerminalLines);
}
function compareTerminalLines(a: TerminalLine, b: TerminalLine): number {
return a.sortKey - b.sortKey || (a.seq ?? 0) - (b.seq ?? 0) || a.id.localeCompare(b.id);
}