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';
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
export interface HttpPostEndpoint {
|
|
||||||
name?: string;
|
|
||||||
url: string;
|
|
||||||
accessToken?: string;
|
|
||||||
timeoutMs?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HttpPostTransportContext {
|
export interface HttpPostTransportContext {
|
||||||
uin: string;
|
uin: string;
|
||||||
api: import('./api-handler').ApiHandler;
|
api: import('./api-handler').ApiHandler;
|
||||||
@@ -17,29 +10,34 @@ const log = createLogger('OneBot.POST');
|
|||||||
const DEFAULT_TIMEOUT_MS = 5000;
|
const DEFAULT_TIMEOUT_MS = 5000;
|
||||||
|
|
||||||
export class HttpPostTransport {
|
export class HttpPostTransport {
|
||||||
private readonly config: OneBotConfig;
|
|
||||||
private readonly context: HttpPostTransportContext;
|
private readonly context: HttpPostTransportContext;
|
||||||
|
private endpoints: HttpPostEndpoint[] = [];
|
||||||
private stopped = false;
|
private stopped = false;
|
||||||
|
|
||||||
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
|
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
|
||||||
this.config = config;
|
this.endpoints = [...config.httpPostEndpoints];
|
||||||
this.context = context;
|
this.context = context;
|
||||||
}
|
}
|
||||||
|
|
||||||
start(): void {
|
start(): void {
|
||||||
this.stopped = false;
|
this.stopped = false;
|
||||||
const count = this.config.httpPostEndpoints?.length ?? 0;
|
const count = this.endpoints.length;
|
||||||
if (count > 0) {
|
if (count > 0) {
|
||||||
log.info('configured %d HTTP POST endpoint(s)', count);
|
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 {
|
stop(): void {
|
||||||
this.stopped = true;
|
this.stopped = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
publishEvent(event: JsonObject): void {
|
publishEvent(event: JsonObject): void {
|
||||||
const endpoints = this.config.httpPostEndpoints;
|
const endpoints = this.endpoints;
|
||||||
if (!endpoints || endpoints.length === 0) return;
|
if (!endpoints || endpoints.length === 0) return;
|
||||||
|
|
||||||
const payload = JSON.stringify(event);
|
const payload = JSON.stringify(event);
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import {
|
import {
|
||||||
createServer,
|
createServer,
|
||||||
type IncomingHttpHeaders,
|
|
||||||
type IncomingMessage,
|
type IncomingMessage,
|
||||||
type Server,
|
type Server,
|
||||||
type ServerResponse,
|
type ServerResponse,
|
||||||
} from 'http';
|
} from 'http';
|
||||||
import type { ApiHandler } from './api-handler';
|
import type { ApiHandler } from './api-handler';
|
||||||
import type { OneBotConfig } from './types';
|
import type { HttpServerEndpoint, OneBotConfig } from './types';
|
||||||
import { createLogger } from '../utils/logger';
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
export interface HttpTransportContext {
|
export interface HttpTransportContext {
|
||||||
@@ -16,42 +15,65 @@ export interface HttpTransportContext {
|
|||||||
const log = createLogger('OneBot.HTTP');
|
const log = createLogger('OneBot.HTTP');
|
||||||
|
|
||||||
export class HttpTransport {
|
export class HttpTransport {
|
||||||
private readonly config: OneBotConfig;
|
|
||||||
private readonly context: HttpTransportContext;
|
private readonly context: HttpTransportContext;
|
||||||
private readonly servers: Server[] = [];
|
private readonly servers = new Map<string, Server>();
|
||||||
|
private endpoints: HttpServerEndpoint[] = [];
|
||||||
|
|
||||||
constructor(config: OneBotConfig, context: HttpTransportContext) {
|
constructor(config: OneBotConfig, context: HttpTransportContext) {
|
||||||
this.config = config;
|
this.endpoints = [...config.httpServers];
|
||||||
this.context = context;
|
this.context = context;
|
||||||
}
|
}
|
||||||
|
|
||||||
start(): void {
|
start(): void {
|
||||||
for (const endpoint of this.config.httpServers) {
|
for (const endpoint of this.endpoints) this.startEndpoint(endpoint);
|
||||||
const expectedPath = normalizePath(endpoint.path ?? '/');
|
}
|
||||||
const endpointToken = endpoint.accessToken ?? '';
|
|
||||||
const server = createServer((req, res) => {
|
|
||||||
void this.handleRequest(expectedPath, endpointToken, req, res);
|
|
||||||
});
|
|
||||||
|
|
||||||
server.on('listening', () => {
|
reloadConfig(config: OneBotConfig): void {
|
||||||
const label = endpoint.name ? `[${endpoint.name}] ` : '';
|
const nextEndpoints = [...config.httpServers];
|
||||||
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, expectedPath);
|
const nextKeys = new Set(nextEndpoints.map(httpServerKey));
|
||||||
});
|
|
||||||
|
|
||||||
server.on('error', (error) => {
|
for (const [key, server] of this.servers) {
|
||||||
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
if (!nextKeys.has(key)) {
|
||||||
});
|
server.close();
|
||||||
|
this.servers.delete(key);
|
||||||
server.listen(endpoint.port, endpoint.host);
|
log.info('stopped %s', key);
|
||||||
this.servers.push(server);
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const endpoint of nextEndpoints) {
|
||||||
|
if (!this.servers.has(httpServerKey(endpoint))) {
|
||||||
|
this.startEndpoint(endpoint);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.endpoints = nextEndpoints;
|
||||||
}
|
}
|
||||||
|
|
||||||
stop(): void {
|
stop(): void {
|
||||||
for (const server of this.servers) {
|
for (const server of this.servers.values()) {
|
||||||
server.close();
|
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> {
|
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;
|
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 {
|
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||||
if (!token) return true;
|
if (!token) return true;
|
||||||
// 1. Header auth
|
// 1. Header auth
|
||||||
|
|||||||
@@ -103,6 +103,12 @@ export class OneBotInstance {
|
|||||||
this.rkeyCache.warmUp(this.bridge, this.uin);
|
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 {
|
dispose(): void {
|
||||||
this.online = false;
|
this.online = false;
|
||||||
this.stopHeartbeat();
|
this.stopHeartbeat();
|
||||||
@@ -137,6 +143,10 @@ export class OneBotInstance {
|
|||||||
return this.pids.has(pid);
|
return this.pids.has(pid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getPids(): number[] {
|
||||||
|
return [...this.pids];
|
||||||
|
}
|
||||||
|
|
||||||
get empty(): boolean {
|
get empty(): boolean {
|
||||||
return this.pids.size === 0;
|
return this.pids.size === 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,16 @@ export class OneBotManager {
|
|||||||
return [...this.instances.values()];
|
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 {
|
dispose(): void {
|
||||||
for (const instance of this.instances.values()) {
|
for (const instance of this.instances.values()) {
|
||||||
instance.dispose();
|
instance.dispose();
|
||||||
|
|||||||
+83
-15
@@ -1,7 +1,7 @@
|
|||||||
import WebSocket, { WebSocketServer } from 'ws';
|
import WebSocket, { WebSocketServer } from 'ws';
|
||||||
import type { IncomingHttpHeaders, IncomingMessage } from 'http';
|
import type { IncomingHttpHeaders, IncomingMessage } from 'http';
|
||||||
import type { ApiHandler } from './api-handler';
|
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';
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
interface ForwardConnection {
|
interface ForwardConnection {
|
||||||
@@ -14,6 +14,7 @@ interface ReverseConnection {
|
|||||||
role: WsRole;
|
role: WsRole;
|
||||||
endpointUrl: string;
|
endpointUrl: string;
|
||||||
reconnectIntervalMs: number;
|
reconnectIntervalMs: number;
|
||||||
|
key: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WsTransportContext {
|
export interface WsTransportContext {
|
||||||
@@ -26,17 +27,19 @@ export interface WsTransportContext {
|
|||||||
const log = createLogger('OneBot.WS');
|
const log = createLogger('OneBot.WS');
|
||||||
|
|
||||||
export class WsTransport {
|
export class WsTransport {
|
||||||
private readonly config: OneBotConfig;
|
|
||||||
private readonly context: WsTransportContext;
|
private readonly context: WsTransportContext;
|
||||||
|
|
||||||
private readonly servers: WebSocketServer[] = [];
|
private readonly servers = new Map<string, WebSocketServer>();
|
||||||
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
|
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
|
||||||
private readonly reverseConnections = new Set<ReverseConnection>();
|
private readonly reverseConnections = new Set<ReverseConnection>();
|
||||||
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
|
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
|
||||||
|
private serverEndpoints: WsServerEndpoint[] = [];
|
||||||
|
private clientEndpoints: WsClientEndpoint[] = [];
|
||||||
private stopped = false;
|
private stopped = false;
|
||||||
|
|
||||||
constructor(config: OneBotConfig, context: WsTransportContext) {
|
constructor(config: OneBotConfig, context: WsTransportContext) {
|
||||||
this.config = config;
|
this.serverEndpoints = [...config.wsServers];
|
||||||
|
this.clientEndpoints = [...config.wsClients];
|
||||||
this.context = context;
|
this.context = context;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,6 +49,45 @@ export class WsTransport {
|
|||||||
this.startReverseClients();
|
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 {
|
stop(): void {
|
||||||
this.stopped = true;
|
this.stopped = true;
|
||||||
this.publishEvent(this.context.buildLifecycleEvent('disable'));
|
this.publishEvent(this.context.buildLifecycleEvent('disable'));
|
||||||
@@ -65,10 +107,10 @@ export class WsTransport {
|
|||||||
}
|
}
|
||||||
this.reverseConnections.clear();
|
this.reverseConnections.clear();
|
||||||
|
|
||||||
for (const server of this.servers) {
|
for (const server of this.servers.values()) {
|
||||||
server.close();
|
server.close();
|
||||||
}
|
}
|
||||||
this.servers.length = 0;
|
this.servers.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
publishEvent(event: JsonObject): void {
|
publishEvent(event: JsonObject): void {
|
||||||
@@ -88,7 +130,12 @@ export class WsTransport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private startServers(): void {
|
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({
|
const wss = new WebSocketServer({
|
||||||
host: endpoint.host,
|
host: endpoint.host,
|
||||||
port: endpoint.port,
|
port: endpoint.port,
|
||||||
@@ -129,16 +176,17 @@ export class WsTransport {
|
|||||||
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
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 {
|
private startReverseClients(): void {
|
||||||
for (const endpoint of this.config.wsClients) {
|
for (const endpoint of this.clientEndpoints) this.startClientEndpoint(endpoint);
|
||||||
const role = endpoint.role ?? 'universal';
|
}
|
||||||
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
|
||||||
this.connectReverseClient(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '', endpoint.name);
|
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 {
|
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 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);
|
this.reverseConnections.add(conn);
|
||||||
|
|
||||||
socket.on('open', () => {
|
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 {
|
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||||
if (!token) return true;
|
if (!token) return true;
|
||||||
// 1. Header auth
|
// 1. Header auth
|
||||||
|
|||||||
@@ -2,6 +2,15 @@ import { format } from 'util';
|
|||||||
|
|
||||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||||
|
|
||||||
|
export interface LogEntry {
|
||||||
|
id: number;
|
||||||
|
time: string;
|
||||||
|
level: LogLevel;
|
||||||
|
scope: string;
|
||||||
|
message: string;
|
||||||
|
line: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface LogOptions {
|
interface LogOptions {
|
||||||
scope: string;
|
scope: string;
|
||||||
}
|
}
|
||||||
@@ -33,6 +42,10 @@ const COLOR_CODE: Record<LogLevel, number> = {
|
|||||||
const COLOR_SCOPE = 35;
|
const COLOR_SCOPE = 35;
|
||||||
const COLOR_DIM = 2;
|
const COLOR_DIM = 2;
|
||||||
const COLOR_RESET = '\x1b[0m';
|
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 {
|
function resolveMinLevel(): LogLevel {
|
||||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
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 {
|
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||||
if (!shouldLog(level)) return;
|
if (!shouldLog(level)) return;
|
||||||
|
const message = format(...args);
|
||||||
const line = render(level, options.scope, 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;
|
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||||
stream.write(line + '\n');
|
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 {
|
export interface Logger {
|
||||||
debug: (...args: unknown[]) => void;
|
debug: (...args: unknown[]) => void;
|
||||||
info: (...args: unknown[]) => void;
|
info: (...args: unknown[]) => void;
|
||||||
|
|||||||
+49
-5
@@ -1,7 +1,7 @@
|
|||||||
import { serve } from '@hono/node-server';
|
import { serve } from '@hono/node-server';
|
||||||
import { serveStatic } from '@hono/node-server/serve-static';
|
import { serveStatic } from '@hono/node-server/serve-static';
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import { createLogger } from '../utils/logger';
|
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
|
||||||
import { randomBytes } from 'crypto';
|
import { randomBytes } from 'crypto';
|
||||||
import type { OneBotManager } from '../onebot/manager';
|
import type { OneBotManager } from '../onebot/manager';
|
||||||
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
|
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');
|
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);
|
return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
purgeExpiredTokens();
|
purgeExpiredTokens();
|
||||||
const token = authHeader.slice(7);
|
|
||||||
const expiry = sessionTokens.get(token);
|
const expiry = sessionTokens.get(token);
|
||||||
if (!expiry || Date.now() > expiry) {
|
if (!expiry || Date.now() > expiry) {
|
||||||
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
|
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 });
|
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) => {
|
app.get('/api/processes', async (c) => {
|
||||||
if (!hookManager) return c.json({ list: [] });
|
if (!hookManager) return c.json({ list: [] });
|
||||||
try {
|
try {
|
||||||
@@ -208,8 +247,13 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
|||||||
const uin = c.req.param('uin');
|
const uin = c.req.param('uin');
|
||||||
const body = await c.req.json() as OneBotConfig;
|
const body = await c.req.json() as OneBotConfig;
|
||||||
saveOneBotConfig(uin, body);
|
saveOneBotConfig(uin, body);
|
||||||
log.info(`Updated OneBot config for UIN: ${uin}`);
|
const reloaded = oneBotManager.reloadConfig(uin);
|
||||||
return c.json({ success: true, message: '配置保存成功,将在下次会话重连时生效。' });
|
log.info('Updated OneBot config for UIN: %s%s', uin, reloaded ? ' and reloaded' : '');
|
||||||
|
return c.json({
|
||||||
|
success: true,
|
||||||
|
reloaded,
|
||||||
|
message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。',
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return c.json({ success: false, message: String(err) }, 400);
|
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 { LoginPage } from './components/pages/LoginPage';
|
||||||
import { OverviewPage } from './components/pages/OverviewPage';
|
import { OverviewPage } from './components/pages/OverviewPage';
|
||||||
import { ConfigPage } from './components/pages/ConfigPage';
|
import { ConfigPage } from './components/pages/ConfigPage';
|
||||||
|
import { LogsPage } from './components/pages/LogsPage';
|
||||||
import type { QQInfo, OneBotConfig, HookProcessInfo } from './types';
|
import type { QQInfo, OneBotConfig, HookProcessInfo } from './types';
|
||||||
|
|
||||||
const fetchApi = async (url: string, options: RequestInit = {}) => {
|
const fetchApi = async (url: string, options: RequestInit = {}) => {
|
||||||
@@ -18,7 +19,7 @@ function App() {
|
|||||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(
|
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(
|
||||||
import.meta.env.VITE_SKIP_AUTH === 'true' ? true : null
|
import.meta.env.VITE_SKIP_AUTH === 'true' ? true : null
|
||||||
);
|
);
|
||||||
const [activePage, setActivePage] = useState<'总览' | '配置'>('总览');
|
const [activePage, setActivePage] = useState<'总览' | '配置' | '日志'>('总览');
|
||||||
const [qqList, setQqList] = useState<QQInfo[]>([]);
|
const [qqList, setQqList] = useState<QQInfo[]>([]);
|
||||||
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
|
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
|
||||||
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
|
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
|
||||||
@@ -219,6 +220,9 @@ function App() {
|
|||||||
onConfigChange={setConfig}
|
onConfigChange={setConfig}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{activePage === '日志' && (
|
||||||
|
<LogsPage fetchApi={fetchApi} />
|
||||||
|
)}
|
||||||
</MainLayout>
|
</MainLayout>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
import { motion, AnimatePresence } from 'framer-motion';
|
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 { Sidebar } from './Sidebar';
|
||||||
import { useTheme } from '../../contexts/ThemeContext';
|
import { useTheme } from '../../contexts/ThemeContext';
|
||||||
|
|
||||||
type Page = '总览' | '配置';
|
type Page = '总览' | '配置' | '日志';
|
||||||
|
|
||||||
interface MainLayoutProps {
|
interface MainLayoutProps {
|
||||||
activePage: Page;
|
activePage: Page;
|
||||||
@@ -17,6 +17,7 @@ interface MainLayoutProps {
|
|||||||
const pageMeta: Record<Page, { title: string; subtitle: string; badge: string; icon: typeof LayoutDashboard }> = {
|
const pageMeta: Record<Page, { title: string; subtitle: string; badge: string; icon: typeof LayoutDashboard }> = {
|
||||||
'总览': { title: '总览', subtitle: '查看当前接入的 QQ 账号及服务运行状态', badge: '控制台视图', icon: LayoutDashboard },
|
'总览': { title: '总览', subtitle: '查看当前接入的 QQ 账号及服务运行状态', badge: '控制台视图', icon: LayoutDashboard },
|
||||||
'配置': { title: '节点配置', subtitle: '管理 OneBot 协议端点与通信参数', badge: '协议编排', icon: Settings },
|
'配置': { title: '节点配置', subtitle: '管理 OneBot 协议端点与通信参数', badge: '协议编排', icon: Settings },
|
||||||
|
'日志': { title: '日志', subtitle: '查看后端运行日志与实时事件流', badge: 'SSE 实时流', icon: Terminal },
|
||||||
};
|
};
|
||||||
|
|
||||||
export function MainLayout({ activePage, onNavigate, status, onLogout, children }: MainLayoutProps) {
|
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 { Avatar } from '@heroui/react';
|
||||||
import { StatusBadge } from '../ui/StatusBadge';
|
import { StatusBadge } from '../ui/StatusBadge';
|
||||||
import { motion } from 'framer-motion';
|
import { motion } from 'framer-motion';
|
||||||
import { useTheme, type ThemeMode } from '../../contexts/ThemeContext';
|
import { useTheme, type ThemeMode } from '../../contexts/ThemeContext';
|
||||||
|
|
||||||
type Page = '总览' | '配置';
|
type Page = '总览' | '配置' | '日志';
|
||||||
|
|
||||||
interface SidebarProps {
|
interface SidebarProps {
|
||||||
activePage: Page;
|
activePage: Page;
|
||||||
@@ -16,6 +16,7 @@ interface SidebarProps {
|
|||||||
const navItems: { page: Page; label: string; icon: typeof LayoutDashboard }[] = [
|
const navItems: { page: Page; label: string; icon: typeof LayoutDashboard }[] = [
|
||||||
{ page: '总览', label: '总览', icon: LayoutDashboard },
|
{ page: '总览', label: '总览', icon: LayoutDashboard },
|
||||||
{ page: '配置', label: '配置', icon: Settings },
|
{ page: '配置', label: '配置', icon: Settings },
|
||||||
|
{ page: '日志', label: '日志', icon: Terminal },
|
||||||
];
|
];
|
||||||
|
|
||||||
const THEME_OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [
|
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