Add hot-reloadable transports and log streaming
Enable runtime config reload and dynamic endpoint management across transports, and add server-side log streaming + UI. - Transport hot-reload: HttpTransport, HttpPostTransport and WsTransport now maintain endpoint lists and start/stop individual endpoints (servers/clients) dynamically; servers/clients use keys/Maps to identify instances; added reloadConfig methods and helper key functions. - OneBot control: OneBotInstance.reloadConfig delegating to transports; OneBotManager.reloadConfig(uin) to load and apply new config; added getPids helper. - Logger & streaming: added in-memory recent log buffer, subscriber API (getRecentLogs, subscribeLogs) and LogEntry shape; web UI exposes /api/logs and /api/logs/stream (SSE) and improved token/query handling. - Web UI: added LogsPage, integrated into layout and sidebar, EventSource client to show live logs; config save now attempts hot-reload and returns reloaded status. - Misc: refactors to use Maps for server lists, cleanup on stop, and various small helpers and safety checks.
This commit is contained in:
1 parent
ac1ddee54e
commit
bd40af2517
11 files changed
+391
-60
No files matched your search
@@ -1,13 +1,6 @@
|
||||
import type { JsonObject, OneBotConfig } from './types';
|
||||
import type { JsonObject, OneBotConfig, HttpPostEndpoint } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
export interface HttpPostEndpoint {
|
||||
name?: string;
|
||||
url: string;
|
||||
accessToken?: string;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface HttpPostTransportContext {
|
||||
uin: string;
|
||||
api: import('./api-handler').ApiHandler;
|
||||
@@ -17,29 +10,34 @@ const log = createLogger('OneBot.POST');
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
|
||||
export class HttpPostTransport {
|
||||
private readonly config: OneBotConfig;
|
||||
private readonly context: HttpPostTransportContext;
|
||||
private endpoints: HttpPostEndpoint[] = [];
|
||||
private stopped = false;
|
||||
|
||||
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
|
||||
this.config = config;
|
||||
this.endpoints = [...config.httpPostEndpoints];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.stopped = false;
|
||||
const count = this.config.httpPostEndpoints?.length ?? 0;
|
||||
const count = this.endpoints.length;
|
||||
if (count > 0) {
|
||||
log.info('configured %d HTTP POST endpoint(s)', count);
|
||||
}
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
this.endpoints = [...config.httpPostEndpoints];
|
||||
log.info('reloaded %d HTTP POST endpoint(s)', this.endpoints.length);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
}
|
||||
|
||||
publishEvent(event: JsonObject): void {
|
||||
const endpoints = this.config.httpPostEndpoints;
|
||||
const endpoints = this.endpoints;
|
||||
if (!endpoints || endpoints.length === 0) return;
|
||||
|
||||
const payload = JSON.stringify(event);
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import {
|
||||
createServer,
|
||||
type IncomingHttpHeaders,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse,
|
||||
} from 'http';
|
||||
import type { ApiHandler } from './api-handler';
|
||||
import type { OneBotConfig } from './types';
|
||||
import type { HttpServerEndpoint, OneBotConfig } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
export interface HttpTransportContext {
|
||||
@@ -16,42 +15,65 @@ export interface HttpTransportContext {
|
||||
const log = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpTransport {
|
||||
private readonly config: OneBotConfig;
|
||||
private readonly context: HttpTransportContext;
|
||||
private readonly servers: Server[] = [];
|
||||
private readonly servers = new Map<string, Server>();
|
||||
private endpoints: HttpServerEndpoint[] = [];
|
||||
|
||||
constructor(config: OneBotConfig, context: HttpTransportContext) {
|
||||
this.config = config;
|
||||
this.endpoints = [...config.httpServers];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
for (const endpoint of this.config.httpServers) {
|
||||
const expectedPath = normalizePath(endpoint.path ?? '/');
|
||||
const endpointToken = endpoint.accessToken ?? '';
|
||||
const server = createServer((req, res) => {
|
||||
void this.handleRequest(expectedPath, endpointToken, req, res);
|
||||
});
|
||||
for (const endpoint of this.endpoints) this.startEndpoint(endpoint);
|
||||
}
|
||||
|
||||
server.on('listening', () => {
|
||||
const label = endpoint.name ? `[${endpoint.name}] ` : '';
|
||||
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, expectedPath);
|
||||
});
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
const nextEndpoints = [...config.httpServers];
|
||||
const nextKeys = new Set(nextEndpoints.map(httpServerKey));
|
||||
|
||||
server.on('error', (error) => {
|
||||
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
server.listen(endpoint.port, endpoint.host);
|
||||
this.servers.push(server);
|
||||
for (const [key, server] of this.servers) {
|
||||
if (!nextKeys.has(key)) {
|
||||
server.close();
|
||||
this.servers.delete(key);
|
||||
log.info('stopped %s', key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextEndpoints) {
|
||||
if (!this.servers.has(httpServerKey(endpoint))) {
|
||||
this.startEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
this.endpoints = nextEndpoints;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
for (const server of this.servers) {
|
||||
for (const server of this.servers.values()) {
|
||||
server.close();
|
||||
}
|
||||
this.servers.length = 0;
|
||||
this.servers.clear();
|
||||
}
|
||||
|
||||
private startEndpoint(endpoint: HttpServerEndpoint): void {
|
||||
const expectedPath = normalizePath(endpoint.path ?? '/');
|
||||
const endpointToken = endpoint.accessToken ?? '';
|
||||
const server = createServer((req, res) => {
|
||||
void this.handleRequest(expectedPath, endpointToken, req, res);
|
||||
});
|
||||
|
||||
server.on('listening', () => {
|
||||
const label = endpoint.name ? `[${endpoint.name}] ` : '';
|
||||
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, expectedPath);
|
||||
});
|
||||
|
||||
server.on('error', (error) => {
|
||||
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
server.listen(endpoint.port, endpoint.host);
|
||||
this.servers.set(httpServerKey(endpoint), server);
|
||||
}
|
||||
|
||||
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
@@ -154,6 +176,10 @@ function normalizePath(pathValue: string): string {
|
||||
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
}
|
||||
|
||||
function httpServerKey(endpoint: HttpServerEndpoint): string {
|
||||
return `${endpoint.host}:${endpoint.port}${normalizePath(endpoint.path ?? '/')}#${endpoint.accessToken ?? ''}`;
|
||||
}
|
||||
|
||||
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
if (!token) return true;
|
||||
// 1. Header auth
|
||||
|
||||
@@ -103,6 +103,12 @@ export class OneBotInstance {
|
||||
this.rkeyCache.warmUp(this.bridge, this.uin);
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
this.httpTransport.reloadConfig(config);
|
||||
this.httpPostTransport.reloadConfig(config);
|
||||
this.wsTransport.reloadConfig(config);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.online = false;
|
||||
this.stopHeartbeat();
|
||||
@@ -137,6 +143,10 @@ export class OneBotInstance {
|
||||
return this.pids.has(pid);
|
||||
}
|
||||
|
||||
getPids(): number[] {
|
||||
return [...this.pids];
|
||||
}
|
||||
|
||||
get empty(): boolean {
|
||||
return this.pids.size === 0;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,16 @@ export class OneBotManager {
|
||||
return [...this.instances.values()];
|
||||
}
|
||||
|
||||
reloadConfig(uin: string): boolean {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return false;
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
instance.reloadConfig(config);
|
||||
log.info('configuration reloaded: UIN=%s', uin);
|
||||
return true;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const instance of this.instances.values()) {
|
||||
instance.dispose();
|
||||
|
||||
+83
-15
@@ -1,7 +1,7 @@
|
||||
import WebSocket, { WebSocketServer } from 'ws';
|
||||
import type { IncomingHttpHeaders, IncomingMessage } from 'http';
|
||||
import type { ApiHandler } from './api-handler';
|
||||
import type { JsonObject, OneBotConfig, WsRole } from './types';
|
||||
import type { JsonObject, OneBotConfig, WsClientEndpoint, WsRole, WsServerEndpoint } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
interface ForwardConnection {
|
||||
@@ -14,6 +14,7 @@ interface ReverseConnection {
|
||||
role: WsRole;
|
||||
endpointUrl: string;
|
||||
reconnectIntervalMs: number;
|
||||
key: string;
|
||||
}
|
||||
|
||||
export interface WsTransportContext {
|
||||
@@ -26,17 +27,19 @@ export interface WsTransportContext {
|
||||
const log = createLogger('OneBot.WS');
|
||||
|
||||
export class WsTransport {
|
||||
private readonly config: OneBotConfig;
|
||||
private readonly context: WsTransportContext;
|
||||
|
||||
private readonly servers: WebSocketServer[] = [];
|
||||
private readonly servers = new Map<string, WebSocketServer>();
|
||||
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
|
||||
private readonly reverseConnections = new Set<ReverseConnection>();
|
||||
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
|
||||
private serverEndpoints: WsServerEndpoint[] = [];
|
||||
private clientEndpoints: WsClientEndpoint[] = [];
|
||||
private stopped = false;
|
||||
|
||||
constructor(config: OneBotConfig, context: WsTransportContext) {
|
||||
this.config = config;
|
||||
this.serverEndpoints = [...config.wsServers];
|
||||
this.clientEndpoints = [...config.wsClients];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@@ -46,6 +49,45 @@ export class WsTransport {
|
||||
this.startReverseClients();
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
const nextServers = [...config.wsServers];
|
||||
const nextClients = [...config.wsClients];
|
||||
const nextServerKeys = new Set(nextServers.map(wsServerKey));
|
||||
const nextClientKeys = new Set(nextClients.map(wsClientKey));
|
||||
|
||||
for (const [key, server] of this.servers) {
|
||||
if (!nextServerKeys.has(key)) {
|
||||
server.close();
|
||||
this.servers.delete(key);
|
||||
log.info('stopped forward server %s', key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextServers) {
|
||||
if (!this.servers.has(wsServerKey(endpoint))) {
|
||||
this.startServerEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
for (const conn of [...this.reverseConnections]) {
|
||||
if (!nextClientKeys.has(conn.key)) {
|
||||
safeClose(conn.socket);
|
||||
this.reverseConnections.delete(conn);
|
||||
log.info('stopped reverse client %s', conn.endpointUrl);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextClients) {
|
||||
const key = wsClientKey(endpoint);
|
||||
if (![...this.reverseConnections].some(conn => conn.key === key)) {
|
||||
this.startClientEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
this.serverEndpoints = nextServers;
|
||||
this.clientEndpoints = nextClients;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
this.publishEvent(this.context.buildLifecycleEvent('disable'));
|
||||
@@ -65,10 +107,10 @@ export class WsTransport {
|
||||
}
|
||||
this.reverseConnections.clear();
|
||||
|
||||
for (const server of this.servers) {
|
||||
for (const server of this.servers.values()) {
|
||||
server.close();
|
||||
}
|
||||
this.servers.length = 0;
|
||||
this.servers.clear();
|
||||
}
|
||||
|
||||
publishEvent(event: JsonObject): void {
|
||||
@@ -88,7 +130,12 @@ export class WsTransport {
|
||||
}
|
||||
|
||||
private startServers(): void {
|
||||
for (const endpoint of this.config.wsServers) {
|
||||
for (const endpoint of this.serverEndpoints) {
|
||||
this.startServerEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private startServerEndpoint(endpoint: WsServerEndpoint): void {
|
||||
const wss = new WebSocketServer({
|
||||
host: endpoint.host,
|
||||
port: endpoint.port,
|
||||
@@ -129,16 +176,17 @@ export class WsTransport {
|
||||
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
this.servers.push(wss);
|
||||
}
|
||||
this.servers.set(wsServerKey(endpoint), wss);
|
||||
}
|
||||
|
||||
private startReverseClients(): void {
|
||||
for (const endpoint of this.config.wsClients) {
|
||||
const role = endpoint.role ?? 'universal';
|
||||
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
||||
this.connectReverseClient(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '', endpoint.name);
|
||||
}
|
||||
for (const endpoint of this.clientEndpoints) this.startClientEndpoint(endpoint);
|
||||
}
|
||||
|
||||
private startClientEndpoint(endpoint: WsClientEndpoint): void {
|
||||
const role = endpoint.role ?? 'universal';
|
||||
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
||||
this.connectReverseClient(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '', endpoint.name);
|
||||
}
|
||||
|
||||
private connectReverseClient(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string, name?: string): void {
|
||||
@@ -155,7 +203,7 @@ export class WsTransport {
|
||||
}
|
||||
|
||||
const socket = new WebSocket(endpointUrl, { headers });
|
||||
const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs };
|
||||
const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs, key: wsClientPartsKey(endpointUrl, role, reconnectIntervalMs, accessToken) };
|
||||
this.reverseConnections.add(conn);
|
||||
|
||||
socket.on('open', () => {
|
||||
@@ -223,6 +271,26 @@ function parseRequestPath(urlValue: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeWsPath(pathValue: string | undefined): string {
|
||||
const path = (pathValue ?? '/').trim() || '/';
|
||||
if (path === '/') return '/';
|
||||
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
}
|
||||
|
||||
function wsServerKey(endpoint: WsServerEndpoint): string {
|
||||
return `${endpoint.host}:${endpoint.port}${normalizeWsPath(endpoint.path)}#${endpoint.role ?? 'auto'}#${endpoint.accessToken ?? ''}`;
|
||||
}
|
||||
|
||||
function wsClientPartsKey(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string): string {
|
||||
return `${endpointUrl}#${role}#${reconnectIntervalMs}#${accessToken}`;
|
||||
}
|
||||
|
||||
function wsClientKey(endpoint: WsClientEndpoint): string {
|
||||
const role = endpoint.role ?? 'universal';
|
||||
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
||||
return wsClientPartsKey(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '');
|
||||
}
|
||||
|
||||
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
if (!token) return true;
|
||||
// 1. Header auth
|
||||
|
||||
@@ -2,6 +2,15 @@ import { format } from 'util';
|
||||
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
scope: string;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface LogOptions {
|
||||
scope: string;
|
||||
}
|
||||
@@ -33,6 +42,10 @@ const COLOR_CODE: Record<LogLevel, number> = {
|
||||
const COLOR_SCOPE = 35;
|
||||
const COLOR_DIM = 2;
|
||||
const COLOR_RESET = '\x1b[0m';
|
||||
const MAX_LOG_ENTRIES = 1000;
|
||||
const logEntries: LogEntry[] = [];
|
||||
const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
@@ -82,11 +95,35 @@ function render(level: LogLevel, scope: string, args: unknown[]): string {
|
||||
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
if (!shouldLog(level)) return;
|
||||
const message = format(...args);
|
||||
const line = render(level, options.scope, args);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
message,
|
||||
line,
|
||||
};
|
||||
logEntries.push(entry);
|
||||
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
stream.write(line + '\n');
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
|
||||
return logEntries.slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
logSubscribers.add(callback);
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
|
||||
+49
-5
@@ -1,7 +1,7 @@
|
||||
import { serve } from '@hono/node-server';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import { Hono } from 'hono';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
|
||||
import { randomBytes } from 'crypto';
|
||||
import type { OneBotManager } from '../onebot/manager';
|
||||
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
|
||||
@@ -73,12 +73,14 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
}
|
||||
|
||||
const authHeader = c.req.header('Authorization');
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
|
||||
const queryToken = c.req.query('token') ?? '';
|
||||
const token = bearerToken || queryToken;
|
||||
if (!token) {
|
||||
return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
|
||||
}
|
||||
|
||||
purgeExpiredTokens();
|
||||
const token = authHeader.slice(7);
|
||||
const expiry = sessionTokens.get(token);
|
||||
if (!expiry || Date.now() > expiry) {
|
||||
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
|
||||
@@ -160,6 +162,43 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
return c.json({ list });
|
||||
});
|
||||
|
||||
app.get('/api/logs', (c) => {
|
||||
const limit = Number(c.req.query('limit') ?? 300);
|
||||
return c.json({ list: getRecentLogs(limit) });
|
||||
});
|
||||
|
||||
app.get('/api/logs/stream', (c) => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
const send = (event: unknown) => {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
||||
};
|
||||
send({ type: 'ready' });
|
||||
const unsubscribe = subscribeLogs((entry) => send(entry));
|
||||
const heartbeat = setInterval(() => {
|
||||
controller.enqueue(encoder.encode(': heartbeat\n\n'));
|
||||
}, 15000);
|
||||
c.req.raw.signal.addEventListener('abort', () => {
|
||||
clearInterval(heartbeat);
|
||||
unsubscribe();
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/processes', async (c) => {
|
||||
if (!hookManager) return c.json({ list: [] });
|
||||
try {
|
||||
@@ -208,8 +247,13 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
const uin = c.req.param('uin');
|
||||
const body = await c.req.json() as OneBotConfig;
|
||||
saveOneBotConfig(uin, body);
|
||||
log.info(`Updated OneBot config for UIN: ${uin}`);
|
||||
return c.json({ success: true, message: '配置保存成功,将在下次会话重连时生效。' });
|
||||
const reloaded = oneBotManager.reloadConfig(uin);
|
||||
log.info('Updated OneBot config for UIN: %s%s', uin, reloaded ? ' and reloaded' : '');
|
||||
return c.json({
|
||||
success: true,
|
||||
reloaded,
|
||||
message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。',
|
||||
});
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: String(err) }, 400);
|
||||
}
|
||||
|
||||
+5
-1
@@ -4,6 +4,7 @@ import { MainLayout } from './components/layout/MainLayout';
|
||||
import { LoginPage } from './components/pages/LoginPage';
|
||||
import { OverviewPage } from './components/pages/OverviewPage';
|
||||
import { ConfigPage } from './components/pages/ConfigPage';
|
||||
import { LogsPage } from './components/pages/LogsPage';
|
||||
import type { QQInfo, OneBotConfig, HookProcessInfo } from './types';
|
||||
|
||||
const fetchApi = async (url: string, options: RequestInit = {}) => {
|
||||
@@ -18,7 +19,7 @@ function App() {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(
|
||||
import.meta.env.VITE_SKIP_AUTH === 'true' ? true : null
|
||||
);
|
||||
const [activePage, setActivePage] = useState<'总览' | '配置'>('总览');
|
||||
const [activePage, setActivePage] = useState<'总览' | '配置' | '日志'>('总览');
|
||||
const [qqList, setQqList] = useState<QQInfo[]>([]);
|
||||
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
|
||||
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
|
||||
@@ -219,6 +220,9 @@ function App() {
|
||||
onConfigChange={setConfig}
|
||||
/>
|
||||
)}
|
||||
{activePage === '日志' && (
|
||||
<LogsPage fetchApi={fetchApi} />
|
||||
)}
|
||||
</MainLayout>
|
||||
</ThemeProvider>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { Activity, LayoutDashboard, Settings, Sparkles } from 'lucide-react';
|
||||
import { Activity, LayoutDashboard, Settings, Sparkles, Terminal } from 'lucide-react';
|
||||
import { Sidebar } from './Sidebar';
|
||||
import { useTheme } from '../../contexts/ThemeContext';
|
||||
|
||||
type Page = '总览' | '配置';
|
||||
type Page = '总览' | '配置' | '日志';
|
||||
|
||||
interface MainLayoutProps {
|
||||
activePage: Page;
|
||||
@@ -17,6 +17,7 @@ interface MainLayoutProps {
|
||||
const pageMeta: Record<Page, { title: string; subtitle: string; badge: string; icon: typeof LayoutDashboard }> = {
|
||||
'总览': { title: '总览', subtitle: '查看当前接入的 QQ 账号及服务运行状态', badge: '控制台视图', icon: LayoutDashboard },
|
||||
'配置': { title: '节点配置', subtitle: '管理 OneBot 协议端点与通信参数', badge: '协议编排', icon: Settings },
|
||||
'日志': { title: '日志', subtitle: '查看后端运行日志与实时事件流', badge: 'SSE 实时流', icon: Terminal },
|
||||
};
|
||||
|
||||
export function MainLayout({ activePage, onNavigate, status, onLogout, children }: MainLayoutProps) {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { LayoutDashboard, Settings, LogOut, Sun, Moon, Monitor } from 'lucide-react';
|
||||
import { LayoutDashboard, Settings, LogOut, Sun, Moon, Monitor, Terminal } from 'lucide-react';
|
||||
import { Avatar } from '@heroui/react';
|
||||
import { StatusBadge } from '../ui/StatusBadge';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useTheme, type ThemeMode } from '../../contexts/ThemeContext';
|
||||
|
||||
type Page = '总览' | '配置';
|
||||
type Page = '总览' | '配置' | '日志';
|
||||
|
||||
interface SidebarProps {
|
||||
activePage: Page;
|
||||
@@ -16,6 +16,7 @@ interface SidebarProps {
|
||||
const navItems: { page: Page; label: string; icon: typeof LayoutDashboard }[] = [
|
||||
{ page: '总览', label: '总览', icon: LayoutDashboard },
|
||||
{ page: '配置', label: '配置', icon: Settings },
|
||||
{ page: '日志', label: '日志', icon: Terminal },
|
||||
];
|
||||
|
||||
const THEME_OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { RefreshCw, Terminal } from 'lucide-react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useTheme } from '../../contexts/ThemeContext';
|
||||
|
||||
interface LogEntry {
|
||||
id: number;
|
||||
time: string;
|
||||
level: 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
scope: string;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface LogsPageProps {
|
||||
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
|
||||
}
|
||||
|
||||
const levelColor: Record<LogEntry['level'], string> = {
|
||||
debug: 'var(--text-tertiary)',
|
||||
info: 'var(--accent)',
|
||||
success: 'var(--color-success)',
|
||||
warn: '#f59e0b',
|
||||
error: 'var(--color-danger)',
|
||||
};
|
||||
|
||||
export function LogsPage({ fetchApi }: LogsPageProps) {
|
||||
const { resolved } = useTheme();
|
||||
const dark = resolved === 'dark';
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||
const [streamStatus, setStreamStatus] = useState('连接中');
|
||||
const endRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []);
|
||||
|
||||
async function loadLogs() {
|
||||
const res = await fetchApi('/api/logs?limit=500');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setLogs(data.list || []);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadLogs().catch(console.error);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
const url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
|
||||
const source = new EventSource(url);
|
||||
source.onopen = () => setStreamStatus('实时连接');
|
||||
source.onerror = () => setStreamStatus('重连中');
|
||||
source.onmessage = event => {
|
||||
try {
|
||||
const entry = JSON.parse(event.data) as LogEntry | { type: string };
|
||||
if ('type' in entry) return;
|
||||
setLogs(prev => [...prev.filter(item => item.id !== entry.id), entry].slice(-500));
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
return () => source.close();
|
||||
}, [token]);
|
||||
|
||||
useEffect(() => {
|
||||
endRef.current?.scrollIntoView({ block: 'end' });
|
||||
}, [logs]);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="rounded-xl p-4"
|
||||
style={{
|
||||
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
|
||||
border: '1px solid',
|
||||
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
|
||||
backdropFilter: 'blur(32px) saturate(1.2)',
|
||||
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
|
||||
}}
|
||||
>
|
||||
<div className="mb-4 flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="flex size-9 items-center justify-center rounded-lg"
|
||||
style={{ background: 'var(--accent-subtle)', color: 'var(--accent)' }}
|
||||
>
|
||||
<Terminal size={17} strokeWidth={2} />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold" style={{ color: 'var(--text-primary)' }}>运行日志</h2>
|
||||
<p className="mt-0.5 text-xs" style={{ color: 'var(--text-secondary)' }}>{streamStatus} · 最近 {logs.length} 条</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => loadLogs().catch(console.error)}
|
||||
className="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg px-3 text-xs font-medium"
|
||||
style={{
|
||||
color: 'var(--text-secondary)',
|
||||
border: '1px solid var(--border-subtle)',
|
||||
background: 'transparent',
|
||||
}}
|
||||
>
|
||||
<RefreshCw size={13} />
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="h-[58vh] overflow-auto rounded-xl p-3 text-xs"
|
||||
style={{
|
||||
background: dark ? 'rgba(0,0,0,0.22)' : 'rgba(255,255,255,0.42)',
|
||||
border: '1px solid var(--border-subtle)',
|
||||
fontFamily: 'var(--font-mono)',
|
||||
}}
|
||||
>
|
||||
{logs.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center" style={{ color: 'var(--text-tertiary)' }}>暂无日志</div>
|
||||
) : logs.map(log => (
|
||||
<div key={log.id} className="flex gap-2 whitespace-pre-wrap py-0.5 leading-5">
|
||||
<span className="shrink-0" style={{ color: 'var(--text-tertiary)' }}>{new Date(log.time).toLocaleTimeString()}</span>
|
||||
<span className="w-14 shrink-0 font-semibold" style={{ color: levelColor[log.level] }}>{log.level.toUpperCase()}</span>
|
||||
<span className="w-24 shrink-0 truncate" style={{ color: 'var(--text-secondary)' }}>[{log.scope}]</span>
|
||||
<span style={{ color: 'var(--text-primary)' }}>{log.message}</span>
|
||||
</div>
|
||||
))}
|
||||
<div ref={endRef} />
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user