Merge pull request #48 from SnowLuma/dev
chore: promote dev → main (b94775c)
This commit is contained in:
45 files changed
+2083
-193
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.4",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.4",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { MessageElement } from '../events';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
@@ -16,6 +17,14 @@ import {
|
||||
} from './pipeline';
|
||||
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Image');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
interface ImageData {
|
||||
/** Empty when the caller is forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
@@ -106,7 +115,13 @@ export async function uploadImageMsgInfo(
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const image = await loadImage(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
image.fileSize,
|
||||
image.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
|
||||
@@ -25,6 +25,9 @@ import {
|
||||
NTV2UploadRichMediaRespSchema,
|
||||
} from '../proto/highway';
|
||||
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const moduleLog = createLogger('Highway');
|
||||
|
||||
// ─────────────── public types ───────────────
|
||||
|
||||
@@ -123,6 +126,11 @@ export function hexToBytes(hex: string): Uint8Array {
|
||||
export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
|
||||
const label = params.label ?? 'media';
|
||||
const raw = bridge.identity?.uin;
|
||||
const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
const log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
// Build the full body once. Pulling this in here means each format file
|
||||
// only specifies the seven fields that actually vary.
|
||||
@@ -184,6 +192,7 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
return session;
|
||||
};
|
||||
|
||||
let didPut = false;
|
||||
for (const sub of uploads) {
|
||||
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
|
||||
const uKey = target?.uKey ?? '';
|
||||
@@ -203,7 +212,15 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both
|
||||
sub.subFileIndex ?? 0,
|
||||
);
|
||||
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source));
|
||||
const t0 = Date.now();
|
||||
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
|
||||
log.debug('%s PUT done in %dms', label, Date.now() - t0);
|
||||
didPut = true;
|
||||
}
|
||||
|
||||
if (!didPut) {
|
||||
log.debug('%s fast-upload hit (server already had bytes)', label);
|
||||
}
|
||||
|
||||
return upload;
|
||||
|
||||
@@ -22,7 +22,13 @@ import {
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
|
||||
const log = createLogger('Ptt');
|
||||
const moduleLog = createLogger('Highway.Ptt');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_PTT_CMD_ID = 1007;
|
||||
export const GROUP_PTT_CMD_ID = 1008;
|
||||
@@ -105,7 +111,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
|
||||
const silk = await encodeSilk(inputPath, tempDir);
|
||||
if (silk.converted) {
|
||||
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
|
||||
log.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
||||
moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
||||
}
|
||||
|
||||
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
|
||||
@@ -141,8 +147,15 @@ export async function uploadPttMsgInfo(
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const tempDir = defaultPttTempDir();
|
||||
const ptt = await loadPtt(element, tempDir);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s duration=%ds',
|
||||
ptt.fileSize,
|
||||
ptt.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid),
|
||||
ptt.duration);
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
|
||||
@@ -29,7 +29,13 @@ import {
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
|
||||
const log = createLogger('Video');
|
||||
const moduleLog = createLogger('Highway.Video');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_VIDEO_CMD_ID = 1001;
|
||||
export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
|
||||
@@ -323,7 +329,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
|
||||
try {
|
||||
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
|
||||
} catch (err) {
|
||||
log.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
|
||||
moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -337,7 +343,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
|
||||
thumbBytes = new Uint8Array(info.image);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
|
||||
moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -430,7 +436,13 @@ export async function uploadVideoMsgInfo(
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const video = await loadVideo(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
video.fileSize,
|
||||
video.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [
|
||||
{
|
||||
|
||||
@@ -6,9 +6,9 @@ import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
UserProfileInfo, GroupRequestInfo,
|
||||
} from './qq-info';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('Identity');
|
||||
const moduleLogger = createLogger('Identity');
|
||||
|
||||
/**
|
||||
* Hooks Identity uses when its read methods miss every cache layer. Wired in
|
||||
@@ -112,9 +112,14 @@ export class IdentityService {
|
||||
private readonly db: DatabaseSync | null;
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(uin: string, dbPath: string | null) {
|
||||
this.uin_ = uin;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLogger.child({ uin: uinNum })
|
||||
: moduleLogger;
|
||||
|
||||
if (!dbPath) {
|
||||
this.db = null;
|
||||
@@ -840,7 +845,7 @@ export class IdentityService {
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
this.log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ import { Event0x210SubType } from '../enums';
|
||||
import {
|
||||
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
|
||||
} from '../helpers';
|
||||
import { createLogger } from '../../../utils/logger';
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x210SubType) {
|
||||
@@ -21,6 +24,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx);
|
||||
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
|
||||
}
|
||||
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
|
||||
@@ -16,6 +16,9 @@ import {
|
||||
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
|
||||
unwrapGroupNotifyPayload,
|
||||
} from '../helpers';
|
||||
import { createLogger } from '../../../utils/logger';
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x2DCSubType) {
|
||||
@@ -24,6 +27,7 @@ export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
|
||||
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
|
||||
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
|
||||
}
|
||||
unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { MsgPushContext } from './context';
|
||||
import type { PkgType } from './enums';
|
||||
|
||||
const log = createLogger('MsgPush');
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
|
||||
|
||||
@@ -27,7 +28,13 @@ export class MsgPushRegistry {
|
||||
|
||||
decode(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
|
||||
if (!decoder) return [];
|
||||
if (!decoder) {
|
||||
// Unrecognized PkgType: either we don't care about this notify, or
|
||||
// the QQ NT client added a new variant. Surface at debug so a
|
||||
// protocol change can be spotted without spamming production logs.
|
||||
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
return decoder(ctx);
|
||||
} catch (e) {
|
||||
|
||||
@@ -20,10 +20,23 @@ import type { PacketInfo } from '../protocol/types';
|
||||
import type { QQEventVariant } from './events';
|
||||
import type { IdentityService } from './identity-service';
|
||||
import type { BridgeEventBus } from './event-bus';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { formatEvent } from '../utils/event-format';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const eventLog = createLogger('Event');
|
||||
const moduleLog = createLogger('Bridge');
|
||||
const moduleEventLog = createLogger('Event');
|
||||
|
||||
// Notice kinds that get logged as a warning (operationally important
|
||||
// state changes that an operator probably wants to see at default
|
||||
// info level). Everything else falls through to info.
|
||||
const WARN_EVENT_KINDS = new Set([
|
||||
'group_recall',
|
||||
'friend_recall',
|
||||
'group_member_leave',
|
||||
'group_mute',
|
||||
'friend_request',
|
||||
'group_invite',
|
||||
]);
|
||||
|
||||
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
|
||||
|
||||
@@ -43,8 +56,18 @@ export interface PacketPipelineDeps {
|
||||
export class IncomingPacketPipeline {
|
||||
private cmdHandlers_ = new Map<string, CmdParser[]>();
|
||||
private memberRefreshTasks_ = new Map<number, Promise<void>>();
|
||||
private readonly log: Logger;
|
||||
private readonly eventLog: Logger;
|
||||
|
||||
constructor(private readonly deps: PacketPipelineDeps) {}
|
||||
constructor(private readonly deps: PacketPipelineDeps) {
|
||||
// Tag every line we emit with this Bridge's UIN so per-account file
|
||||
// routing works. Unparseable uin (shouldn't happen) falls back to
|
||||
// the module-level logger so we still log, just without the slot.
|
||||
const uinNum = Number.parseInt(deps.identity.uin, 10);
|
||||
const bind = Number.isFinite(uinNum) && uinNum > 0 ? { uin: uinNum } : null;
|
||||
this.log = bind ? moduleLog.child(bind) : moduleLog;
|
||||
this.eventLog = bind ? moduleEventLog.child(bind) : moduleEventLog;
|
||||
}
|
||||
|
||||
registerCmd(cmd: string, parser: CmdParser): void {
|
||||
const arr = this.cmdHandlers_.get(cmd) ?? [];
|
||||
@@ -65,15 +88,18 @@ export class IncomingPacketPipeline {
|
||||
const events = handler(pkt, this.deps.identity);
|
||||
for (const event of events) {
|
||||
if (this.needsPreDispatchIdentityRefresh(event)) {
|
||||
void this.dispatchAfterIdentityRefresh(event);
|
||||
void this.dispatchAfterIdentityRefresh(event).catch((err) => {
|
||||
this.log.warn('dispatchAfterIdentityRefresh failed: %s',
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
} else {
|
||||
this.handleSideEffects(event);
|
||||
printEvent(event);
|
||||
printEvent(this.eventLog, this.deps.identity, event);
|
||||
this.emit(event);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
this.log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,12 +119,12 @@ export class IncomingPacketPipeline {
|
||||
try {
|
||||
refreshed = await this.prepareGroupMemberJoinIdentity(event);
|
||||
} catch (e) {
|
||||
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
|
||||
this.log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
|
||||
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
this.handleSideEffects(event, refreshed);
|
||||
printEvent(event);
|
||||
printEvent(this.eventLog, this.deps.identity, event);
|
||||
this.emit(event);
|
||||
}
|
||||
|
||||
@@ -166,9 +192,9 @@ export class IncomingPacketPipeline {
|
||||
const task = (async () => {
|
||||
try {
|
||||
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
|
||||
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
|
||||
this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
|
||||
} catch (e) {
|
||||
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
|
||||
this.log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
|
||||
groupId, reason, e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
this.memberRefreshTasks_.delete(groupId);
|
||||
@@ -226,50 +252,16 @@ export class IncomingPacketPipeline {
|
||||
}
|
||||
}
|
||||
|
||||
function formatEventUser(uin: number, uid?: string): string {
|
||||
if (uin > 0) return String(uin);
|
||||
return uid || '未知用户';
|
||||
}
|
||||
|
||||
function printEvent(event: QQEventVariant): void {
|
||||
switch (event.kind) {
|
||||
case 'group_message':
|
||||
case 'friend_message':
|
||||
case 'temp_message':
|
||||
// Message logging is handled by OneBot layer with message ID
|
||||
break;
|
||||
case 'group_recall':
|
||||
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
|
||||
break;
|
||||
case 'friend_recall':
|
||||
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
|
||||
break;
|
||||
case 'group_member_join':
|
||||
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
|
||||
break;
|
||||
case 'group_mute':
|
||||
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
|
||||
break;
|
||||
case 'group_admin':
|
||||
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
|
||||
break;
|
||||
case 'friend_poke':
|
||||
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
|
||||
break;
|
||||
case 'group_poke':
|
||||
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
|
||||
break;
|
||||
case 'friend_request':
|
||||
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
|
||||
break;
|
||||
case 'group_invite':
|
||||
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
|
||||
break;
|
||||
case 'group_essence':
|
||||
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
|
||||
break;
|
||||
function printEvent(log: Logger, identity: IdentityService, event: QQEventVariant): void {
|
||||
// Message-class events (group/friend/temp message) get rendered by the
|
||||
// OneBot layer's logReceivedMessage — its output already includes the
|
||||
// assigned message ID, which the raw packet doesn't have. Returning
|
||||
// null here is the formatter's signal to skip.
|
||||
const message = formatEvent(identity, event);
|
||||
if (!message) return;
|
||||
if (WARN_EVENT_KINDS.has(event.kind)) {
|
||||
log.warn('%s', message);
|
||||
} else {
|
||||
log.info('%s', message);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
// 定义接口返回类型
|
||||
export interface GroupEssenceMsgRet {
|
||||
@@ -39,6 +42,8 @@ export async function getGroupEssenceMsg(
|
||||
);
|
||||
return ret.retcode === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
|
||||
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
export enum WebHonorType {
|
||||
TALKATIVE = 'talkative',
|
||||
@@ -43,7 +46,8 @@ export async function getHonorListWebAPI(cookieObject: Record<string, string>, g
|
||||
description: item?.desc,
|
||||
}));
|
||||
} catch (e) {
|
||||
// console.error(e);
|
||||
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
|
||||
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import https from 'node:https';
|
||||
// import { readFileSync } from 'node:fs';
|
||||
// import * as console from "node:console";
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
export interface SetNoticeRetSuccess {
|
||||
ec?: number;
|
||||
@@ -112,6 +113,7 @@ export async function setGroupNoticeWebAPI(
|
||||
);
|
||||
return ret;
|
||||
} catch (e) {
|
||||
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -158,7 +160,8 @@ export async function getGroupNoticeWebAPI(
|
||||
);
|
||||
// console.log(JSON.stringify(ret, null, 2));
|
||||
return ret?.ec === 0 ? ret : undefined;
|
||||
} catch {
|
||||
} catch (e) {
|
||||
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -215,11 +218,15 @@ export async function uploadGroupNoticeImage(
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', () => resolve(undefined));
|
||||
req.on('error', (err) => {
|
||||
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
|
||||
resolve(undefined);
|
||||
});
|
||||
req.write(body);
|
||||
req.end();
|
||||
});
|
||||
} catch {
|
||||
} catch (e) {
|
||||
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -260,7 +267,8 @@ export async function deleteGroupNotice(
|
||||
false
|
||||
);
|
||||
return ret?.ec === 0;
|
||||
} catch {
|
||||
} catch (e) {
|
||||
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,13 @@ export type HookSessionDeps = {
|
||||
};
|
||||
makeClient: (pid: number) => QqHookClient;
|
||||
/** Sync fast-path check used by load() to skip re-injection when a
|
||||
* prior SnowLuma run left a working pipe behind. */
|
||||
pipeWatcher: { isPipeLive: (pid: number) => boolean };
|
||||
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
|
||||
* fresh poll — used after unload to dodge the up-to-1500ms cache
|
||||
* staleness that would otherwise false-flag a successful unload. */
|
||||
pipeWatcher: {
|
||||
isPipeLive: (pid: number) => boolean;
|
||||
tickNow?: () => Promise<void>;
|
||||
};
|
||||
/** Sink for parsed packets. Called with the BridgeManager-shaped
|
||||
* PacketInfo for every packet received while logged in. If omitted,
|
||||
* packets are dropped (useful in unit tests that don't care). */
|
||||
@@ -254,7 +259,11 @@ export class HookSession extends EventEmitter {
|
||||
this._uin = '0';
|
||||
|
||||
// Verify the unload took: if the pipe is still up the DLL is still
|
||||
// resident. Drop back to 'connecting' and let the watcher reconnect.
|
||||
// resident. The cached snapshot is up to 1500ms stale and we just
|
||||
// changed the world, so force a fresh poll first — otherwise even
|
||||
// a successful unload reads as "pipe still live" until the next
|
||||
// background tick runs and we'd report a spurious failure.
|
||||
await this.pipeWatcher.tickNow?.();
|
||||
if (this.pipeWatcher.isPipeLive(this.pid)) {
|
||||
this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
|
||||
this.setStatus('connecting', this._error);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
import { OneBotManager } from './onebot/manager';
|
||||
import { loadRuntimeConfig } from './common/runtime';
|
||||
import { createLogger } from './utils/logger';
|
||||
import { closeLogger, createLogger } from './utils/logger';
|
||||
import { HookManager } from './hook/hook-manager';
|
||||
|
||||
const runtimeConfig = loadRuntimeConfig();
|
||||
@@ -38,13 +38,17 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Graceful shutdown
|
||||
process.on('SIGINT', () => {
|
||||
log.warn('Shutting down...');
|
||||
// Graceful shutdown: dispose managers, await log flush, then exit.
|
||||
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
|
||||
const shutdown = (signal: string) => async () => {
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
oneBotManager.dispose();
|
||||
hookManager.dispose();
|
||||
await closeLogger();
|
||||
process.exit(0);
|
||||
});
|
||||
};
|
||||
process.on('SIGINT', shutdown('SIGINT'));
|
||||
process.on('SIGTERM', shutdown('SIGTERM'));
|
||||
}
|
||||
|
||||
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
|
||||
@@ -57,7 +61,8 @@ function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
|
||||
return fromConfig === true;
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
main().catch(async (error) => {
|
||||
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
await closeLogger();
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -2,6 +2,10 @@ import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
import type { ForwardPreviewMeta } from './modules/message-actions';
|
||||
import type { BridgeInterface } from '../bridge/bridge-interface';
|
||||
import { RETCODE, failedResponse } from './types';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { summarizeParams } from '../utils/log-summary';
|
||||
|
||||
const moduleLog = createLogger('Bridge.Action');
|
||||
|
||||
import { register as registerInfo } from './actions/info';
|
||||
import { register as registerMessage } from './actions/message';
|
||||
@@ -101,8 +105,10 @@ type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiRespon
|
||||
|
||||
export class ApiHandler {
|
||||
private readonly handlers = new Map<string, ActionHandler>();
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(context: ApiActionContext) {
|
||||
constructor(context: ApiActionContext, uin?: number) {
|
||||
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
registerInfo(this, context);
|
||||
registerMessage(this, context);
|
||||
registerFriend(this, context);
|
||||
@@ -120,12 +126,25 @@ export class ApiHandler {
|
||||
async handle(action: string, params: JsonObject): Promise<import('./types').ApiResponse> {
|
||||
const handler = this.handlers.get(action);
|
||||
if (!handler) {
|
||||
this.log.debug('unknown action %s', action);
|
||||
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
|
||||
}
|
||||
|
||||
// Entry log goes to file always (debug); console only when level is
|
||||
// dialed down to debug. Caller-perspective summary lets the operator
|
||||
// grep "what did the bot get asked to do" without scraping wire logs.
|
||||
this.log.debug('%s params=%s', action, summarizeParams(params));
|
||||
|
||||
try {
|
||||
return await handler(params);
|
||||
} catch (error) {
|
||||
// Action failures are almost always param-shape problems coming
|
||||
// from the OneBot client; warn (not error) is the right level so
|
||||
// the log file stays a useful signal of real internal faults.
|
||||
this.log.warn('%s failed: %s\n%s',
|
||||
action,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
error instanceof Error ? (error.stack ?? '') : '');
|
||||
const message = error instanceof Error ? error.message : 'internal error';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { RKeyCache } from './instance-rkey';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import type { JsonObject, MessageMeta, OneBotConfig, NetworkBase } from './types';
|
||||
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig, NetworkBase } from './types';
|
||||
import {
|
||||
OneBotNetworkManager,
|
||||
WsServerAdapter,
|
||||
@@ -19,9 +19,10 @@ import {
|
||||
HttpPostAdapter,
|
||||
type NetworkAdapterContext,
|
||||
} from './network';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '../utils/event-format';
|
||||
|
||||
const log = createLogger('Event');
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
export class OneBotInstance {
|
||||
readonly uin: string;
|
||||
@@ -40,12 +41,17 @@ export class OneBotInstance {
|
||||
private online = true;
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
private static readonly HEARTBEAT_INTERVAL = 30000;
|
||||
private readonly log: Logger;
|
||||
|
||||
get nickname(): string { return this.bridge.identity.nickname; }
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
this.rkeyCache = new RKeyCache();
|
||||
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
|
||||
@@ -85,10 +91,12 @@ export class OneBotInstance {
|
||||
};
|
||||
this.ctx = ctx;
|
||||
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx));
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
|
||||
this.networkManager = new OneBotNetworkManager();
|
||||
this.installAdaptersFromConfig(config);
|
||||
void this.networkManager.openAll();
|
||||
void this.networkManager.openAll().catch((err) => {
|
||||
this.log.warn('openAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
|
||||
this.startHeartbeat();
|
||||
this.rkeyCache.warmUp(this.bridge, this.uin);
|
||||
@@ -99,7 +107,9 @@ export class OneBotInstance {
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
void this.applyConfigDiff(config);
|
||||
void this.applyConfigDiff(config).catch((err) => {
|
||||
this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
@@ -107,7 +117,9 @@ export class OneBotInstance {
|
||||
this.stopHeartbeat();
|
||||
this.disposeEventPipeline?.();
|
||||
this.disposeEventPipeline = null;
|
||||
void this.networkManager.closeAll();
|
||||
void this.networkManager.closeAll().catch((err) => {
|
||||
this.log.warn('closeAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
this.messageStore.close();
|
||||
this.mediaStore.close();
|
||||
}
|
||||
@@ -136,8 +148,12 @@ export class OneBotInstance {
|
||||
this.cacheMessageEvent(event);
|
||||
this.logReceivedMessage(event);
|
||||
// NetworkManager builds the dispatch payload once and fans out to every
|
||||
// active adapter in parallel via Promise.allSettled.
|
||||
void this.networkManager.emitEvent(event);
|
||||
// active adapter in parallel via Promise.allSettled — per-adapter errors
|
||||
// are already isolated, so the outer promise should never reject. The
|
||||
// .catch is a belt-and-suspenders guard against future refactors.
|
||||
void this.networkManager.emitEvent(event).catch((err) => {
|
||||
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private buildNetworkContext(): NetworkAdapterContext {
|
||||
@@ -206,7 +222,7 @@ export class OneBotInstance {
|
||||
try {
|
||||
await existing.reload(net as never);
|
||||
} catch (err) {
|
||||
log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else if (net.enabled !== false) {
|
||||
const factory = factories.get(name);
|
||||
@@ -224,56 +240,56 @@ export class OneBotInstance {
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
const isGroup = event.message_type === 'group';
|
||||
|
||||
// Build message preview
|
||||
const parts: string[] = [];
|
||||
const idStr = `ID:${messageId}`;
|
||||
const selfTag = isSelf ? '[自身] ' : '';
|
||||
const identity = this.bridge.identity;
|
||||
|
||||
// Walk the segment array once: render via the shared formatter for
|
||||
// non-reply segments, and resolve `reply` segments through the
|
||||
// message store so the chain reference becomes legible
|
||||
// ("[回复 <user>: <body>...]" instead of "[回复:1234567890]").
|
||||
const renderedParts: string[] = [];
|
||||
const message = event.message;
|
||||
|
||||
if (Array.isArray(message)) {
|
||||
for (const seg of message) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const type = String(seg.type ?? '');
|
||||
const data: Record<string, unknown> = (
|
||||
typeof seg.data === 'object' && seg.data !== null && !Array.isArray(seg.data)
|
||||
) ? seg.data : {};
|
||||
|
||||
if (type === 'text' && data.text) {
|
||||
const text = String(data.text);
|
||||
const preview = text.length > 50 ? text.substring(0, 50) + '...' : text;
|
||||
parts.push(preview);
|
||||
} else if (type === 'image') {
|
||||
parts.push('[图片]');
|
||||
} else if (type === 'face') {
|
||||
parts.push('[表情]');
|
||||
} else if (type === 'at') {
|
||||
parts.push(`@${data.qq || ''}`);
|
||||
} else if (type === 'reply') {
|
||||
parts.push(`[回复:${data.id || ''}]`);
|
||||
} else if (type === 'record') {
|
||||
parts.push('[语音]');
|
||||
} else if (type === 'video') {
|
||||
parts.push('[视频]');
|
||||
const type = String((seg as JsonObject).type ?? '');
|
||||
const data = (typeof (seg as JsonObject).data === 'object' && (seg as JsonObject).data !== null && !Array.isArray((seg as JsonObject).data))
|
||||
? (seg as JsonObject).data as Record<string, unknown>
|
||||
: {};
|
||||
if (type === 'reply') {
|
||||
const replyId = toInt(data.id);
|
||||
renderedParts.push(formatReply(this.messageStore, identity, replyId));
|
||||
} else {
|
||||
parts.push(`[${type}]`);
|
||||
renderedParts.push(formatMessageSegments([seg as JsonValue]));
|
||||
}
|
||||
}
|
||||
} else if (typeof message === 'string') {
|
||||
renderedParts.push(formatMessageSegments(message));
|
||||
}
|
||||
|
||||
const content = parts.join(' ').trim() || '[空消息]';
|
||||
const idStr = `ID:${messageId}`;
|
||||
const selfTag = isSelf ? '[自身] ' : '';
|
||||
|
||||
const content = renderedParts.join(' ').trim() || '[空消息]';
|
||||
|
||||
if (isGroup) {
|
||||
const groupId = toInt(event.group_id);
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = event.sender as any;
|
||||
const nickname = sender?.card || sender?.nickname || String(userId);
|
||||
log.success(`${selfTag}群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`);
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const nicknameFromEvent = (sender.card as string) || (sender.nickname as string) || '';
|
||||
const userPart = nicknameFromEvent
|
||||
? `[${nicknameFromEvent}(${userId})]`
|
||||
: formatUser(identity, groupId, userId);
|
||||
this.log.success(`${selfTag}群 ${formatGroup(identity, groupId)} | ${userPart}: ${idStr} ${content}`);
|
||||
} else {
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = event.sender as any;
|
||||
const nickname = sender?.nickname || String(userId);
|
||||
log.success(`${selfTag}私聊 ${nickname}(${userId}): ${idStr} ${content}`);
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const nicknameFromEvent = (sender.nickname as string) || '';
|
||||
const userPart = nicknameFromEvent
|
||||
? `[${nicknameFromEvent}(${userId})]`
|
||||
: formatUser(identity, undefined, userId);
|
||||
this.log.success(`${selfTag}私聊 ${userPart}: ${idStr} ${content}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
import type { MessageElement } from '../bridge/events';
|
||||
import type { JsonValue, JsonObject } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('MsgParser');
|
||||
|
||||
export interface ParseMessageOptions {
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null;
|
||||
@@ -271,7 +274,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
const musicJson = await resp.text();
|
||||
return { type: 'json', text: musicJson };
|
||||
} catch (e) {
|
||||
console.warn(`[MsgParser] music sign failed: ${e}, falling back to local card`);
|
||||
log.warn('music sign failed: %s, falling back to local card', e instanceof Error ? e.message : String(e));
|
||||
// Fallback: build a basic card locally
|
||||
const title = String(data.title ?? 'Music');
|
||||
const jsonData = JSON.stringify({
|
||||
|
||||
@@ -10,21 +10,24 @@ import {
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { executeQuickOperation } from './quick-operation';
|
||||
|
||||
const log = createLogger('OneBot.POST');
|
||||
const moduleLog = createLogger('OneBot.POST');
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
|
||||
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private signature_: string;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.signature_ = bindingSignature(config);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
@@ -74,7 +77,9 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
if (!this.isEnabled) return;
|
||||
const json = pickDispatchJson(payload, this.options);
|
||||
if (json === null) return;
|
||||
void this.postEvent(json, event);
|
||||
void this.postEvent(json, event).catch((err) => {
|
||||
this.log.warn('[%s] postEvent threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private async postEvent(payload: string, event: JsonObject): Promise<void> {
|
||||
@@ -106,11 +111,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.isEnabled) {
|
||||
log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,7 +126,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
if (!operation || typeof operation !== 'object') return;
|
||||
await executeQuickOperation(event, operation, this.ctx.api);
|
||||
} catch (error) {
|
||||
log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
this.log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,14 +12,21 @@ import {
|
||||
} from 'http';
|
||||
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.HTTP');
|
||||
const moduleLog = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
// HTTP server never receives events — `isActive` purely tracks the
|
||||
@@ -81,7 +88,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
this.server = server;
|
||||
|
||||
server.on('listening', () => {
|
||||
log.success(
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
@@ -90,7 +97,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
);
|
||||
});
|
||||
server.on('error', (err) => {
|
||||
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
|
||||
|
||||
@@ -13,11 +13,11 @@ import {
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { rawDataToString, safeClose, safeSend } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.WS-Client');
|
||||
const moduleLog = createLogger('OneBot.WS-Client');
|
||||
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
|
||||
|
||||
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
@@ -26,11 +26,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private role: WsRole;
|
||||
private explicitlyClosed = false;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.role = config.role ?? 'Universal';
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
@@ -111,12 +114,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
this.socket = socket;
|
||||
|
||||
socket.on('open', () => {
|
||||
log.info('[%s] connected %s', this.name, this.config.url);
|
||||
this.log.info('[%s] connected %s', this.name, this.config.url);
|
||||
this.sendBootstrapMetaEvents(socket);
|
||||
});
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, raw);
|
||||
void this.handleApiMessage(socket, raw).catch((err) => {
|
||||
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
@@ -126,7 +131,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
});
|
||||
|
||||
socket.on('error', (err: Error) => {
|
||||
log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -14,11 +14,11 @@ import {
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, parseRequestPath, rawDataToString, safeClose, safeSend, normalizePath } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.WS-Server');
|
||||
const moduleLog = createLogger('OneBot.WS-Server');
|
||||
|
||||
interface ForwardConn {
|
||||
socket: WebSocket;
|
||||
@@ -30,10 +30,13 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private connections = new Map<WebSocket, ForwardConn>();
|
||||
private options: EventReportOptions;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
@@ -114,7 +117,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
this.wss = wss;
|
||||
|
||||
wss.on('listening', () => {
|
||||
log.success(
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
@@ -124,7 +127,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
});
|
||||
|
||||
wss.on('error', (err: Error) => {
|
||||
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
|
||||
@@ -145,7 +148,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
});
|
||||
socket.on('close', () => this.connections.delete(socket));
|
||||
socket.on('error', (err: Error) => {
|
||||
log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
if (role === 'Event' || role === 'Universal') {
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
// Identity-aware, one-line readable rendering for log output.
|
||||
//
|
||||
// Two layers consume this:
|
||||
// - bridge/packet-pipeline.ts → notice events (recall / join / poke / …)
|
||||
// - onebot/instance.ts → received-message log
|
||||
//
|
||||
// All formatters are defensive: any field lookup that throws falls
|
||||
// back to the raw numeric form, so a malformed event or stale
|
||||
// Identity cache never crashes the logger. Cache misses simply
|
||||
// degrade to the previous "just print the uin / groupId" output.
|
||||
|
||||
import type { IdentityService } from '../bridge/identity-service';
|
||||
import type { QQEventVariant } from '../bridge/events';
|
||||
import type { MessageStore } from '../onebot/message-store';
|
||||
import type { JsonObject, JsonValue } from '../onebot/types';
|
||||
|
||||
const MAX_TEXT_PREVIEW = 50;
|
||||
const MAX_REPLY_BODY_PREVIEW = 30;
|
||||
|
||||
/** "[群名(12345)]" if known, else "12345" (or "0" if missing). */
|
||||
export function formatGroup(identity: IdentityService, groupId: number): string {
|
||||
if (!groupId || groupId <= 0) return String(groupId || 0);
|
||||
try {
|
||||
const g = identity.findGroup(groupId);
|
||||
const name = g?.groupName?.trim();
|
||||
return name ? `[${name}(${groupId})]` : String(groupId);
|
||||
} catch {
|
||||
return String(groupId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "[card-or-nick(uin)]" when the uin is in the group-member or friend
|
||||
* roster; falls back to the bare uin string. When only a uid is known
|
||||
* (no uin yet) the uid is returned as-is so the line still references
|
||||
* someone — better than logging "0".
|
||||
*/
|
||||
export function formatUser(
|
||||
identity: IdentityService,
|
||||
groupId: number | undefined,
|
||||
uin: number,
|
||||
uid?: string,
|
||||
): string {
|
||||
try {
|
||||
if (!uin || uin <= 0) return uid ? uid : '0';
|
||||
if (groupId !== undefined && groupId > 0) {
|
||||
const member = identity.findGroupMember(groupId, uin);
|
||||
const name = member?.card?.trim() || member?.nickname?.trim();
|
||||
if (name) return `[${name}(${uin})]`;
|
||||
}
|
||||
const friend = identity.findFriend(uin);
|
||||
const fname = friend?.remark?.trim() || friend?.nickname?.trim();
|
||||
if (fname) return `[${fname}(${uin})]`;
|
||||
return String(uin);
|
||||
} catch {
|
||||
return String(uin);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line preview of an OneBot-shape message (array of segments or
|
||||
* raw string). Element rendering matches the existing logReceivedMessage
|
||||
* vocabulary so this is a drop-in replacement, with a few additions
|
||||
* (json / xml / markdown / forward / poke / file).
|
||||
*/
|
||||
export function formatMessageSegments(message: JsonValue): string {
|
||||
try {
|
||||
if (typeof message === 'string') {
|
||||
return truncate(message, MAX_TEXT_PREVIEW) || '[空消息]';
|
||||
}
|
||||
if (!Array.isArray(message)) return '[空消息]';
|
||||
const parts: string[] = [];
|
||||
for (const seg of message) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const obj = seg as JsonObject;
|
||||
const type = String(obj.type ?? '');
|
||||
const data = (typeof obj.data === 'object' && obj.data !== null && !Array.isArray(obj.data))
|
||||
? obj.data as Record<string, unknown>
|
||||
: {};
|
||||
parts.push(renderSegment(type, data));
|
||||
}
|
||||
return parts.join(' ').trim() || '[空消息]';
|
||||
} catch {
|
||||
return '[消息渲染异常]';
|
||||
}
|
||||
}
|
||||
|
||||
function renderSegment(type: string, data: Record<string, unknown>): string {
|
||||
switch (type) {
|
||||
case 'text': return truncate(String(data.text ?? ''), MAX_TEXT_PREVIEW);
|
||||
case 'image': return '[图片]';
|
||||
case 'face': return '[表情]';
|
||||
case 'mface': return data.text ? `[${String(data.text)}]` : '[表情]';
|
||||
case 'at': return data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`;
|
||||
case 'reply': return `[回复:${data.id ?? ''}]`;
|
||||
case 'record': return '[语音]';
|
||||
case 'video': return '[视频]';
|
||||
case 'file': return data.file ? `[文件:${truncate(String(data.file), 20)}]` : '[文件]';
|
||||
case 'json': return '[JSON]';
|
||||
case 'xml': return '[XML]';
|
||||
case 'markdown': return '[Markdown]';
|
||||
case 'forward': return '[聊天记录]';
|
||||
case 'poke': return '[戳一戳]';
|
||||
default: return `[${type}]`;
|
||||
}
|
||||
}
|
||||
|
||||
function truncate(s: string, max: number): string {
|
||||
return s.length > max ? `${s.slice(0, max)}...` : s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a `reply` segment's referenced message and return a short
|
||||
* "[回复 user: body...]" string. On miss (older than store retention,
|
||||
* never seen, lookup throws) falls back to "[回复:<id>]" so the chain
|
||||
* reference is at least preserved.
|
||||
*
|
||||
* Deliberately one level deep — we don't recurse into the reply's own
|
||||
* reply. Long chains aren't worth the runtime cost in the hot path,
|
||||
* and a 1-level peek catches 90% of real-world "what's this referring
|
||||
* to" questions.
|
||||
*/
|
||||
export function formatReply(
|
||||
messageStore: MessageStore,
|
||||
identity: IdentityService,
|
||||
replyId: number,
|
||||
): string {
|
||||
try {
|
||||
if (!replyId) return '[回复:0]';
|
||||
const event = messageStore.findEvent(replyId);
|
||||
if (!event) return `[回复:${replyId}]`;
|
||||
const isGroup = event.message_type === 'group';
|
||||
const uin = toIntOrZero(event.user_id);
|
||||
const groupId = isGroup ? toIntOrZero(event.group_id) : undefined;
|
||||
|
||||
// Prefer cache; if cache miss, use the sender fields baked into the
|
||||
// stored event itself (those came from the original receive path
|
||||
// when the roster was warm).
|
||||
let userPart = formatUser(identity, groupId, uin);
|
||||
if (userPart === String(uin) && uin > 0) {
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const fallback = ((sender.card as string) || (sender.nickname as string) || '').trim();
|
||||
if (fallback) userPart = `[${fallback}(${uin})]`;
|
||||
}
|
||||
|
||||
const body = truncate(formatMessageSegments(event.message as JsonValue), MAX_REPLY_BODY_PREVIEW);
|
||||
return `[回复 ${userPart}: ${body}]`;
|
||||
} catch {
|
||||
return `[回复:${replyId}]`;
|
||||
}
|
||||
}
|
||||
|
||||
function toIntOrZero(v: unknown): number {
|
||||
if (typeof v === 'number' && Number.isFinite(v)) return v;
|
||||
if (typeof v === 'string') {
|
||||
const n = Number.parseInt(v, 10);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Readable one-line rendering of a notice-class QQEventVariant. Returns
|
||||
* null for kinds the OneBot layer's message log already renders
|
||||
* (group_message / friend_message / temp_message / group_file_upload /
|
||||
* friend_add — those have richer dedicated paths).
|
||||
*/
|
||||
export function formatEvent(identity: IdentityService, event: QQEventVariant): string | null {
|
||||
try {
|
||||
switch (event.kind) {
|
||||
case 'group_message':
|
||||
case 'friend_message':
|
||||
case 'temp_message':
|
||||
case 'group_file_upload':
|
||||
case 'friend_add':
|
||||
return null;
|
||||
case 'group_recall':
|
||||
return `群撤回 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.authorUin)} 被 ${formatUser(identity, event.groupId, event.operatorUin)} 撤回`;
|
||||
case 'friend_recall':
|
||||
return `私聊撤回 ${formatUser(identity, undefined, event.userUin)} 撤回了消息`;
|
||||
case 'group_member_join':
|
||||
return `入群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} 加入 ${formatGroup(identity, event.groupId)}`;
|
||||
case 'group_member_leave':
|
||||
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${event.isKick ? '被踢出' : '退出'} ${formatGroup(identity, event.groupId)}`;
|
||||
case 'group_mute':
|
||||
return `禁言 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.duration}秒`;
|
||||
case 'group_admin':
|
||||
return `管理 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.set ? '+' : '-'}管理员`;
|
||||
case 'friend_poke':
|
||||
return `戳一戳 ${formatUser(identity, undefined, event.userUin)} -> ${formatUser(identity, undefined, event.targetUin)}`;
|
||||
case 'group_poke':
|
||||
return `群戳 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} -> ${formatUser(identity, event.groupId, event.targetUin)}`;
|
||||
case 'friend_request':
|
||||
return `好友请求 ${formatUser(identity, undefined, event.fromUin)}: ${event.message}`;
|
||||
case 'group_invite':
|
||||
return `群邀请 ${formatUser(identity, undefined, event.fromUin)} -> ${formatGroup(identity, event.groupId)}`;
|
||||
case 'group_essence':
|
||||
return `精华 ${formatGroup(identity, event.groupId)} | ${event.set ? '+' : '-'}精华`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
// File transport for the SnowLuma logger.
|
||||
//
|
||||
// Writes plain text (ANSI stripped) to:
|
||||
// <SNOWLUMA_LOG_DIR>/snowluma-YYYY-MM-DD.log (shared, all UINs)
|
||||
// <SNOWLUMA_LOG_DIR>/<uin>/snowluma-YYYY-MM-DD.log (per-account)
|
||||
//
|
||||
// Both pathways use the same daily rotation + per-file size cap. When the
|
||||
// cap is hit the in-flight file is closed and writes continue in
|
||||
// snowluma-YYYY-MM-DD.1.log, .2.log, ...
|
||||
// at the same date. Files older than the retain window are unlinked on
|
||||
// startup and on each day rollover.
|
||||
//
|
||||
// Disabled via SNOWLUMA_LOG_FILE=0. Per-UIN sub-files are additionally
|
||||
// gated by SNOWLUMA_LOG_PER_UIN=0 (still keeps the shared file). Any I/O
|
||||
// failure during init or write degrades silently to console-only — we
|
||||
// deliberately do NOT use the logger from inside this module to avoid
|
||||
// recursion.
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const DEFAULT_DIR = 'logs';
|
||||
const DEFAULT_MAX_MB = 50;
|
||||
const DEFAULT_RETAIN_DAYS = 7;
|
||||
const FILE_PREFIX = 'snowluma-';
|
||||
const FILE_SUFFIX = '.log';
|
||||
const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/;
|
||||
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
|
||||
// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit
|
||||
// multi-line records (stack traces), ESC is stripped through ANSI_RE.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g;
|
||||
|
||||
function parsePositiveInt(v: string | undefined, dflt: number): number {
|
||||
if (!v) return dflt;
|
||||
const n = Number.parseInt(v, 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : dflt;
|
||||
}
|
||||
|
||||
function todayString(d: Date = new Date()): string {
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
function dateOf(s: string): Date {
|
||||
const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10));
|
||||
return new Date(y!, m! - 1, d!);
|
||||
}
|
||||
|
||||
function stripAnsi(line: string): string {
|
||||
return line.replace(ANSI_RE, '').replace(CTRL_RE, '');
|
||||
}
|
||||
|
||||
interface OpenFile {
|
||||
stream: fs.WriteStream;
|
||||
bytes: number;
|
||||
date: string;
|
||||
splitIndex: number;
|
||||
path: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns one output directory: keeps at most one open WriteStream, handles
|
||||
* daily rollover, per-file size cap, and retention cleanup. The shared
|
||||
* top-level dir uses one of these; each per-UIN sub-dir gets its own.
|
||||
*/
|
||||
class FileWriter {
|
||||
private disabled = false;
|
||||
private file: OpenFile | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly dir: string,
|
||||
private readonly maxBytes: number,
|
||||
private readonly retainDays: number,
|
||||
) {
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
} catch (err) {
|
||||
this.disabled = true;
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
get isDisabled(): boolean {
|
||||
return this.disabled;
|
||||
}
|
||||
|
||||
get currentPath(): string | null {
|
||||
return this.file?.path ?? null;
|
||||
}
|
||||
|
||||
write(data: string, bytes: number): void {
|
||||
if (this.disabled) return;
|
||||
const today = todayString();
|
||||
this.ensureForToday(today);
|
||||
if (!this.file) return;
|
||||
|
||||
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
|
||||
this.rotateBySize();
|
||||
if (!this.file) return;
|
||||
}
|
||||
|
||||
this.file.stream.write(data);
|
||||
this.file.bytes += bytes;
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
const f = this.file;
|
||||
this.file = null;
|
||||
if (!f) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
f.stream.end(() => resolve());
|
||||
} catch {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ensureForToday(today: string): void {
|
||||
if (this.file && this.file.date === today) return;
|
||||
|
||||
if (this.file) {
|
||||
try {
|
||||
this.file.stream.end();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
this.file = null;
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
// Resume from the highest existing split index for today (so two
|
||||
// process starts on the same day share files / don't clobber).
|
||||
let idx = 0;
|
||||
while (fs.existsSync(this.pathFor(today, idx + 1))) idx++;
|
||||
this.file = this.openFile(today, idx);
|
||||
}
|
||||
|
||||
private rotateBySize(): void {
|
||||
if (!this.file) return;
|
||||
const date = this.file.date;
|
||||
try {
|
||||
this.file.stream.end();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
let next = this.file.splitIndex + 1;
|
||||
while (fs.existsSync(this.pathFor(date, next))) next++;
|
||||
this.file = this.openFile(date, next);
|
||||
}
|
||||
|
||||
private openFile(date: string, splitIndex: number): OpenFile | null {
|
||||
const p = this.pathFor(date, splitIndex);
|
||||
try {
|
||||
let bytes = 0;
|
||||
try {
|
||||
bytes = fs.statSync(p).size;
|
||||
} catch {
|
||||
/* file doesn't exist yet */
|
||||
}
|
||||
const stream = fs.createWriteStream(p, { flags: 'a' });
|
||||
stream.on('error', (err) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`[logger] file write error on ${p}: ${err.message}`);
|
||||
});
|
||||
return { stream, bytes, date, splitIndex, path: p };
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private pathFor(date: string, splitIndex: number): string {
|
||||
const tail = splitIndex > 0 ? `.${splitIndex}` : '';
|
||||
return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`);
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = fs.readdirSync(this.dir);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const retainMs = this.retainDays * 24 * 60 * 60 * 1000;
|
||||
const cutoff = Date.now() - retainMs;
|
||||
for (const name of entries) {
|
||||
const m = FILE_RE.exec(name);
|
||||
if (!m) continue;
|
||||
const dateStr = m[1]!;
|
||||
if (dateOf(dateStr).getTime() < cutoff) {
|
||||
try {
|
||||
fs.unlinkSync(path.join(this.dir, name));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class FileTransport {
|
||||
private readonly dir: string;
|
||||
private readonly maxBytes: number;
|
||||
private readonly retainDays: number;
|
||||
private readonly enabled: boolean;
|
||||
private readonly perUinEnabled: boolean;
|
||||
private shared: FileWriter | null = null;
|
||||
private perUin = new Map<number, FileWriter>();
|
||||
|
||||
constructor() {
|
||||
this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR;
|
||||
this.maxBytes =
|
||||
parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024;
|
||||
this.retainDays = parsePositiveInt(
|
||||
process.env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
DEFAULT_RETAIN_DAYS,
|
||||
);
|
||||
this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0';
|
||||
this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0';
|
||||
|
||||
if (this.enabled) {
|
||||
const w = new FileWriter(this.dir, this.maxBytes, this.retainDays);
|
||||
this.shared = w.isDisabled ? null : w;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when no file output will happen (env disable or init failure). */
|
||||
get isDisabled(): boolean {
|
||||
return !this.shared;
|
||||
}
|
||||
|
||||
/** Current shared-file path (or null if disabled / not yet opened). */
|
||||
get currentPath(): string | null {
|
||||
return this.shared?.currentPath ?? null;
|
||||
}
|
||||
|
||||
/** Path of the per-UIN file for the given UIN, if open. */
|
||||
perUinPath(uin: number): string | null {
|
||||
return this.perUin.get(uin)?.currentPath ?? null;
|
||||
}
|
||||
|
||||
write(line: string, uin?: number): void {
|
||||
if (!this.shared) return;
|
||||
const data = stripAnsi(line) + '\n';
|
||||
const bytes = Buffer.byteLength(data, 'utf8');
|
||||
|
||||
this.shared.write(data, bytes);
|
||||
|
||||
if (uin !== undefined && this.perUinEnabled) {
|
||||
let w = this.perUin.get(uin);
|
||||
if (!w) {
|
||||
w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays);
|
||||
if (w.isDisabled) return;
|
||||
this.perUin.set(uin, w);
|
||||
}
|
||||
w.write(data, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
const closes: Promise<void>[] = [];
|
||||
if (this.shared) closes.push(this.shared.close());
|
||||
for (const w of this.perUin.values()) closes.push(w.close());
|
||||
this.shared = null;
|
||||
this.perUin.clear();
|
||||
await Promise.all(closes);
|
||||
}
|
||||
}
|
||||
|
||||
let singleton: FileTransport | null = null;
|
||||
|
||||
export function getFileTransport(): FileTransport {
|
||||
if (!singleton) singleton = new FileTransport();
|
||||
return singleton;
|
||||
}
|
||||
|
||||
/** Reset state between tests. Closes all active file handles. */
|
||||
export async function _resetFileTransportForTesting(): Promise<void> {
|
||||
if (singleton) await singleton.close();
|
||||
singleton = null;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Compact one-line param summary for log output.
|
||||
//
|
||||
// OneBot action params can include large message arrays / nested
|
||||
// payloads that would blow the line width to multiple kilobytes if we
|
||||
// JSON.stringify them naively. This helper produces a flat
|
||||
// `k1=v1 k2=v2 ...` rendering with per-field truncation and a hard
|
||||
// total cap, designed to be grep-friendly without flooding the log
|
||||
// file.
|
||||
|
||||
const MAX_FIELD = 40;
|
||||
const MAX_TOTAL = 200;
|
||||
|
||||
function valueRepr(v: unknown): string {
|
||||
if (v === null) return 'null';
|
||||
if (v === undefined) return 'undefined';
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) return `[len=${v.length}]`;
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a params object as a single line for logging. Skips deep
|
||||
* traversal: nested objects collapse to `{...}`, arrays to `[len=N]`.
|
||||
* Strings are quoted; long ones are truncated with an ellipsis.
|
||||
*
|
||||
* Output is capped at MAX_TOTAL chars; on overflow the tail is
|
||||
* replaced with `...` so the next field doesn't get half-rendered.
|
||||
*/
|
||||
export function summarizeParams(params: unknown): string {
|
||||
if (params === null || params === undefined) return '{}';
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
|
||||
}
|
||||
if (Array.isArray(params)) return `[len=${params.length}]`;
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v)}`;
|
||||
// +1 accounts for the separating space we'd insert when joining.
|
||||
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
|
||||
out.push('...');
|
||||
break;
|
||||
}
|
||||
out.push(entry);
|
||||
total += entry.length + (out.length > 1 ? 1 : 0);
|
||||
}
|
||||
return out.join(' ');
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
@@ -7,14 +8,26 @@ export interface LogEntry {
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface LogOptions {
|
||||
scope: string;
|
||||
uin?: number;
|
||||
/** Free-form meta carried across `.child(...)` calls. Currently only
|
||||
* `uin` is rendered, but the bag is preserved for future fields
|
||||
* (requestId / traceId / etc.). */
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// Fixed-width slot for the UIN tag in rendered output so the [Scope]
|
||||
// column stays vertically aligned across lines with and without a UIN.
|
||||
// Width covers `[1234567890]` (12 chars); anything longer just won't pad.
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
debug: 10,
|
||||
info: 20,
|
||||
@@ -55,10 +68,32 @@ function resolveMinLevel(): LogLevel {
|
||||
return 'info';
|
||||
}
|
||||
|
||||
const MIN_LEVEL = resolveMinLevel();
|
||||
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
|
||||
// setLogLevel() lets WebUI / SDK callers flip it without a restart.
|
||||
// Only governs console + ring buffer + subscribers; the file
|
||||
// transport always sees debug-and-up regardless.
|
||||
let currentLevel: LogLevel = resolveMinLevel();
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[MIN_LEVEL];
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the console / subscriber level at runtime. Invalid input is
|
||||
* a no-op (returns false). File transport is unaffected — it always
|
||||
* sees every level so post-mortems remain useful.
|
||||
*/
|
||||
export function setLogLevel(level: string): boolean {
|
||||
const lower = String(level).toLowerCase();
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
}
|
||||
|
||||
function useColor(): boolean {
|
||||
@@ -78,43 +113,72 @@ function currentTime(): string {
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, scope: string, args: unknown[]): string {
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
const message = format(...args);
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} [${scope}] ${message}`;
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
const cLabel = ansi(COLOR_CODE[level], label);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${scope}]`);
|
||||
return `${cTs} ${cLabel} ${cScope} ${message}`;
|
||||
// Pad first, then color only the visible tag so escape codes don't eat
|
||||
// into the alignment width.
|
||||
const cUin = uinTag
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
|
||||
}
|
||||
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
if (!shouldLog(level)) return;
|
||||
// Console / subscriber level filter. File output is debug-and-up always;
|
||||
// see log-file-transport.ts.
|
||||
const passesConsole = shouldLog(level);
|
||||
const message = format(...args);
|
||||
const line = render(level, options.scope, args);
|
||||
const line = render(level, options, args);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
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;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. ESC (0x1B) is preserved so the
|
||||
// ANSI color sequences emitted by render() actually reach the terminal.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
stream.write(line.replace(/[\x00-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
|
||||
if (passesConsole) {
|
||||
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;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// File transport always sees every level (debug-and-up) for post-mortem
|
||||
// value; ANSI stripping happens inside the transport. UIN routes the
|
||||
// line to its per-account sub-file in addition to the shared one.
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush and close the underlying log file. Call from shutdown hooks
|
||||
* (SIGINT / SIGTERM / uncaughtException) so the WriteStream's internal
|
||||
* buffer makes it to disk. Returns a promise that resolves once the OS
|
||||
* has finalized the write.
|
||||
*/
|
||||
export function closeLogger(): Promise<void> {
|
||||
return getFileTransport().close();
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
@@ -135,15 +199,33 @@ export interface Logger {
|
||||
success: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Derive a new logger that inherits this one's scope and carries
|
||||
* additional metadata. Currently `uin` is the only key with rendering
|
||||
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
|
||||
* other keys are preserved on the options bag for forward compat.
|
||||
*/
|
||||
child: (meta: { uin?: number; [k: string]: unknown }) => Logger;
|
||||
}
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
return {
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
warn: (...args: unknown[]) => emit('warn', opts, args),
|
||||
error: (...args: unknown[]) => emit('error', opts, args),
|
||||
child: (meta) => {
|
||||
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
|
||||
return makeLogger({
|
||||
scope: opts.scope,
|
||||
uin: nextUin,
|
||||
meta: { ...(opts.meta ?? {}), ...meta },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createLogger(scope: string): Logger {
|
||||
const options: LogOptions = { scope };
|
||||
return {
|
||||
debug: (...args: unknown[]) => emit('debug', options, args),
|
||||
info: (...args: unknown[]) => emit('info', options, args),
|
||||
success: (...args: unknown[]) => emit('success', options, args),
|
||||
warn: (...args: unknown[]) => emit('warn', options, args),
|
||||
error: (...args: unknown[]) => emit('error', options, args),
|
||||
};
|
||||
return makeLogger({ scope });
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { serve } from '@hono/node-server';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import { Hono, type Context } from 'hono';
|
||||
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
|
||||
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '../utils/logger';
|
||||
import { randomBytes } from 'crypto';
|
||||
import type { OneBotManager } from '../onebot/manager';
|
||||
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
|
||||
@@ -116,6 +116,26 @@ export async function initWebUI(
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
// ─── Anti-indexing ───────────────────────────────────────────────────────
|
||||
// The WebUI is an admin surface that has no business showing up in
|
||||
// search results — even the login page leaks the existence of a
|
||||
// SnowLuma instance to anyone scanning the IP. Three overlapping
|
||||
// signals: a hard X-Robots-Tag on every response, a robots.txt for
|
||||
// crawlers that read it before pages, and a <meta robots> in the
|
||||
// SPA shell for the case where a proxy strips headers.
|
||||
app.use('*', async (c, next) => {
|
||||
await next();
|
||||
c.res.headers.set(
|
||||
'X-Robots-Tag',
|
||||
'noindex, nofollow, noarchive, nosnippet, noimageindex',
|
||||
);
|
||||
});
|
||||
|
||||
app.get('/robots.txt', (c) => {
|
||||
c.res.headers.set('Content-Type', 'text/plain; charset=utf-8');
|
||||
return c.body('User-agent: *\nDisallow: /\n');
|
||||
});
|
||||
|
||||
// ─── Auth middleware ─────────────────────────────────────────────────────
|
||||
app.use('/api/*', async (c, next) => {
|
||||
const reqPath = c.req.path;
|
||||
@@ -340,6 +360,20 @@ export async function initWebUI(
|
||||
return c.json({ list: getRecentLogs(limit) });
|
||||
});
|
||||
|
||||
app.get('/api/logs/level', (c) => {
|
||||
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
|
||||
});
|
||||
|
||||
app.post('/api/logs/level', async (c) => {
|
||||
const body = await c.req.json().catch(() => null) as { level?: unknown } | null;
|
||||
const next = typeof body?.level === 'string' ? body.level : '';
|
||||
if (!setLogLevel(next)) {
|
||||
return c.json({ message: `invalid level: ${next}`, levels: [...LOG_LEVELS] }, 400);
|
||||
}
|
||||
log.info('console log level set to %s via WebUI', getLogLevel());
|
||||
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
|
||||
});
|
||||
|
||||
app.get('/api/logs/stream', (c) => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
// Tests for ApiHandler's central dispatch logging.
|
||||
// Verifies that every action call emits a debug entry line, failures
|
||||
// fold into a warn line with stack, and unknown actions are surfaced.
|
||||
// Also covers the summarizeParams helper used to keep the entry log
|
||||
// from blowing the line width.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { ApiHandler } from '../src/onebot/api-handler';
|
||||
import { subscribeLogs, type LogEntry } from '../src/utils/logger';
|
||||
import { summarizeParams } from '../src/utils/log-summary';
|
||||
|
||||
// Minimal context — we never reach the real action handlers; we
|
||||
// register our own via registerAction.
|
||||
function emptyContext(): any {
|
||||
return {
|
||||
bridge: {},
|
||||
getLoginInfo: () => ({ userId: 0, nickname: '' }),
|
||||
isOnline: () => true,
|
||||
getMessage: () => null,
|
||||
getMessageMeta: () => null,
|
||||
sendPrivateMessage: async () => ({ messageId: 0 }),
|
||||
sendGroupMessage: async () => ({ messageId: 0 }),
|
||||
deleteMessage: async () => {},
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
getFriendList: async () => [],
|
||||
getImageInfo: async () => null,
|
||||
getRecordInfo: async () => null,
|
||||
};
|
||||
}
|
||||
|
||||
let captured: LogEntry[];
|
||||
let unsub: () => void;
|
||||
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.SNOWLUMA_LOG_LEVEL = 'debug';
|
||||
captured = [];
|
||||
unsub = subscribeLogs((e) => captured.push(e));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
unsub();
|
||||
if (savedLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_LEVEL = savedLogLevel;
|
||||
});
|
||||
|
||||
describe('summarizeParams', () => {
|
||||
it('renders flat scalar fields as k=v pairs', () => {
|
||||
const out = summarizeParams({ group_id: 12345, auto_escape: false, foo: 'bar' });
|
||||
expect(out).toBe('group_id=12345 auto_escape=false foo="bar"');
|
||||
});
|
||||
|
||||
it('truncates long string values with an ellipsis', () => {
|
||||
const long = 'x'.repeat(80);
|
||||
const out = summarizeParams({ s: long });
|
||||
expect(out).toMatch(/^s="x{40}\.\.\."$/);
|
||||
});
|
||||
|
||||
it('collapses arrays and nested objects rather than dumping them', () => {
|
||||
const out = summarizeParams({ messages: [1, 2, 3, 4], meta: { a: 1, b: 2 } });
|
||||
expect(out).toBe('messages=[len=4] meta={...}');
|
||||
});
|
||||
|
||||
it('caps the total line and tags the cut with ellipsis', () => {
|
||||
const params: Record<string, number> = {};
|
||||
for (let i = 0; i < 30; i++) params[`field_with_some_padding_${i}`] = i;
|
||||
const out = summarizeParams(params);
|
||||
expect(out.length).toBeLessThan(220);
|
||||
expect(out.endsWith('...')).toBe(true);
|
||||
});
|
||||
|
||||
it('handles null / undefined inputs gracefully', () => {
|
||||
expect(summarizeParams(null)).toBe('{}');
|
||||
expect(summarizeParams(undefined)).toBe('{}');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ApiHandler dispatch logging', () => {
|
||||
it('emits a debug entry under [Bridge.Action] when an action is called', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('echo', async () => ({ status: 'ok', retcode: 0, data: null }));
|
||||
|
||||
await handler.handle('echo', { group_id: 67890, message: [1, 2, 3] });
|
||||
|
||||
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.uin).toBe(12345);
|
||||
expect(entry!.message).toContain('echo');
|
||||
expect(entry!.message).toContain('group_id=67890');
|
||||
expect(entry!.message).toContain('message=[len=3]');
|
||||
});
|
||||
|
||||
it('emits a warn line with the error stack when the handler throws', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('boom', async () => {
|
||||
throw new Error('kapow');
|
||||
});
|
||||
|
||||
const result = await handler.handle('boom', {});
|
||||
expect(result.status).toBe('failed');
|
||||
|
||||
const warn = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'warn');
|
||||
expect(warn).toBeDefined();
|
||||
expect(warn!.message).toContain('boom');
|
||||
expect(warn!.message).toContain('kapow');
|
||||
// stack contains the test file path; just check that something stack-shaped is appended
|
||||
expect(warn!.message).toMatch(/at\s+/);
|
||||
});
|
||||
|
||||
it('logs unknown actions at debug level', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 99);
|
||||
await handler.handle('not_a_real_action', {});
|
||||
|
||||
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.message.includes('unknown action'));
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.level).toBe('debug');
|
||||
});
|
||||
|
||||
it('falls back to the module-level logger (no uin slot) when uin is omitted', async () => {
|
||||
const handler = new ApiHandler(emptyContext());
|
||||
handler.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: null }));
|
||||
|
||||
await handler.handle('ping', {});
|
||||
|
||||
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.uin).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
// Tests for utils/event-format.ts.
|
||||
//
|
||||
// Each formatter is defensive about cache misses / malformed input —
|
||||
// these tests cover both the happy paths (resolves names from
|
||||
// Identity / MessageStore) and the degraded paths (falls back to the
|
||||
// raw uin / groupId without crashing).
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
formatEvent,
|
||||
formatGroup,
|
||||
formatMessageSegments,
|
||||
formatReply,
|
||||
formatUser,
|
||||
} from '../src/utils/event-format';
|
||||
import type { QQEventVariant } from '../src/bridge/events';
|
||||
|
||||
// ─── Test fakes (just the find* surface event-format uses) ───
|
||||
|
||||
function fakeIdentity(opts: {
|
||||
groups?: Record<number, { groupName: string }>;
|
||||
members?: Record<string, { uin: number; card?: string; nickname?: string }>;
|
||||
friends?: Record<number, { uin: number; nickname?: string; remark?: string }>;
|
||||
} = {}): any {
|
||||
return {
|
||||
findGroup: (gid: number) => opts.groups?.[gid] ?? null,
|
||||
findGroupMember: (gid: number, uin: number) => opts.members?.[`${gid}/${uin}`] ?? null,
|
||||
findFriend: (uin: number) => opts.friends?.[uin] ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function fakeMessageStore(events: Record<number, Record<string, unknown>>): any {
|
||||
return {
|
||||
findEvent: (id: number) => events[id] ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
describe('formatGroup', () => {
|
||||
it('renders [groupName(id)] when the group is in cache', () => {
|
||||
const id = fakeIdentity({ groups: { 123: { groupName: 'TestGroup' } } });
|
||||
expect(formatGroup(id, 123)).toBe('[TestGroup(123)]');
|
||||
});
|
||||
|
||||
it('falls back to bare id on cache miss', () => {
|
||||
const id = fakeIdentity();
|
||||
expect(formatGroup(id, 123)).toBe('123');
|
||||
});
|
||||
|
||||
it('handles 0 / missing group id without crashing', () => {
|
||||
const id = fakeIdentity();
|
||||
expect(formatGroup(id, 0)).toBe('0');
|
||||
});
|
||||
|
||||
it('falls back to bare id if findGroup throws', () => {
|
||||
const id = { findGroup: () => { throw new Error('db dead'); } } as any;
|
||||
expect(formatGroup(id, 123)).toBe('123');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatUser', () => {
|
||||
it('prefers group-member card over nickname', () => {
|
||||
const id = fakeIdentity({ members: { '1/100': { uin: 100, card: 'Card', nickname: 'Nick' } } });
|
||||
expect(formatUser(id, 1, 100)).toBe('[Card(100)]');
|
||||
});
|
||||
|
||||
it('falls back to nickname when card is empty', () => {
|
||||
const id = fakeIdentity({ members: { '1/100': { uin: 100, card: '', nickname: 'Nick' } } });
|
||||
expect(formatUser(id, 1, 100)).toBe('[Nick(100)]');
|
||||
});
|
||||
|
||||
it('falls back to friend list when not a group member', () => {
|
||||
const id = fakeIdentity({ friends: { 100: { uin: 100, nickname: 'FriendNick' } } });
|
||||
expect(formatUser(id, undefined, 100)).toBe('[FriendNick(100)]');
|
||||
});
|
||||
|
||||
it('prefers friend remark over nickname', () => {
|
||||
const id = fakeIdentity({ friends: { 100: { uin: 100, nickname: 'A', remark: 'B' } } });
|
||||
expect(formatUser(id, undefined, 100)).toBe('[B(100)]');
|
||||
});
|
||||
|
||||
it('falls back to uin on full cache miss', () => {
|
||||
const id = fakeIdentity();
|
||||
expect(formatUser(id, 1, 100)).toBe('100');
|
||||
});
|
||||
|
||||
it('falls back to uid when only uid is available', () => {
|
||||
const id = fakeIdentity();
|
||||
expect(formatUser(id, undefined, 0, 'u_abc')).toBe('u_abc');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatMessageSegments', () => {
|
||||
it('renders text segments and truncates beyond 50 chars', () => {
|
||||
const long = 'a'.repeat(80);
|
||||
expect(formatMessageSegments([{ type: 'text', data: { text: long } }]))
|
||||
.toBe(`${'a'.repeat(50)}...`);
|
||||
});
|
||||
|
||||
it('handles known media types and at/reply', () => {
|
||||
const out = formatMessageSegments([
|
||||
{ type: 'text', data: { text: 'hi' } },
|
||||
{ type: 'image', data: {} },
|
||||
{ type: 'at', data: { qq: 12345 } },
|
||||
{ type: 'at', data: { qq: 'all' } },
|
||||
{ type: 'reply', data: { id: 999 } },
|
||||
{ type: 'face', data: {} },
|
||||
{ type: 'video', data: {} },
|
||||
{ type: 'record', data: {} },
|
||||
]);
|
||||
expect(out).toBe('hi [图片] @12345 @全体成员 [回复:999] [表情] [视频] [语音]');
|
||||
});
|
||||
|
||||
it('renders unknown segment types as [type]', () => {
|
||||
expect(formatMessageSegments([{ type: 'something_new', data: {} }]))
|
||||
.toBe('[something_new]');
|
||||
});
|
||||
|
||||
it('renders a string message as text (truncated)', () => {
|
||||
expect(formatMessageSegments('hello')).toBe('hello');
|
||||
expect(formatMessageSegments('a'.repeat(60))).toBe(`${'a'.repeat(50)}...`);
|
||||
});
|
||||
|
||||
it('returns [空消息] for empty arrays / non-array / null', () => {
|
||||
expect(formatMessageSegments([])).toBe('[空消息]');
|
||||
expect(formatMessageSegments(null as any)).toBe('[空消息]');
|
||||
expect(formatMessageSegments({} as any)).toBe('[空消息]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatReply', () => {
|
||||
it('renders the resolved sender + body preview when the original is in the store', () => {
|
||||
const store = fakeMessageStore({
|
||||
42: {
|
||||
message_type: 'group',
|
||||
group_id: 1,
|
||||
user_id: 100,
|
||||
sender: { card: 'OrigSender' },
|
||||
message: [{ type: 'text', data: { text: '早安' } }],
|
||||
},
|
||||
});
|
||||
const id = fakeIdentity({ members: { '1/100': { uin: 100, card: 'OrigSender' } } });
|
||||
expect(formatReply(store, id, 42)).toBe('[回复 [OrigSender(100)]: 早安]');
|
||||
});
|
||||
|
||||
it('falls back to [回复:<id>] when the original is missing', () => {
|
||||
const store = fakeMessageStore({});
|
||||
const id = fakeIdentity();
|
||||
expect(formatReply(store, id, 9999)).toBe('[回复:9999]');
|
||||
});
|
||||
|
||||
it('uses the sender baked into the stored event when cache misses', () => {
|
||||
const store = fakeMessageStore({
|
||||
42: {
|
||||
message_type: 'private',
|
||||
user_id: 100,
|
||||
sender: { nickname: 'StoredNick' },
|
||||
message: [{ type: 'text', data: { text: 'hi' } }],
|
||||
},
|
||||
});
|
||||
const id = fakeIdentity(); // no cache
|
||||
expect(formatReply(store, id, 42)).toBe('[回复 [StoredNick(100)]: hi]');
|
||||
});
|
||||
|
||||
it('truncates the body preview to 30 chars', () => {
|
||||
const store = fakeMessageStore({
|
||||
42: {
|
||||
message_type: 'private',
|
||||
user_id: 100,
|
||||
sender: { nickname: 'X' },
|
||||
message: [{ type: 'text', data: { text: 'a'.repeat(80) } }],
|
||||
},
|
||||
});
|
||||
const id = fakeIdentity();
|
||||
const out = formatReply(store, id, 42);
|
||||
// Inner text gets truncated to 50 by formatMessageSegments, then to 30 here
|
||||
expect(out).toContain('...');
|
||||
expect(out.length).toBeLessThan(80);
|
||||
});
|
||||
|
||||
it('returns the fallback when findEvent throws', () => {
|
||||
const store = { findEvent: () => { throw new Error('store dead'); } } as any;
|
||||
const id = fakeIdentity();
|
||||
expect(formatReply(store, id, 42)).toBe('[回复:42]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatEvent', () => {
|
||||
const id = fakeIdentity({
|
||||
groups: { 1: { groupName: 'Grp' } },
|
||||
members: {
|
||||
'1/100': { uin: 100, card: 'Alice' },
|
||||
'1/200': { uin: 200, card: 'Bob' },
|
||||
'1/300': { uin: 300, nickname: 'Carol' },
|
||||
},
|
||||
friends: {
|
||||
500: { uin: 500, nickname: 'FriendA' },
|
||||
600: { uin: 600, nickname: 'FriendB' },
|
||||
},
|
||||
});
|
||||
|
||||
it('returns null for kinds rendered elsewhere', () => {
|
||||
expect(formatEvent(id, { kind: 'group_message' } as QQEventVariant)).toBeNull();
|
||||
expect(formatEvent(id, { kind: 'friend_message' } as QQEventVariant)).toBeNull();
|
||||
expect(formatEvent(id, { kind: 'temp_message' } as QQEventVariant)).toBeNull();
|
||||
});
|
||||
|
||||
it('renders group_recall with all three name slots', () => {
|
||||
expect(formatEvent(id, {
|
||||
kind: 'group_recall',
|
||||
groupId: 1, authorUin: 100, operatorUin: 200,
|
||||
} as QQEventVariant))
|
||||
.toBe('群撤回 [Grp(1)] | [Alice(100)] 被 [Bob(200)] 撤回');
|
||||
});
|
||||
|
||||
it('renders group_member_join with group name and joiner', () => {
|
||||
expect(formatEvent(id, {
|
||||
kind: 'group_member_join',
|
||||
groupId: 1, userUin: 300, userUid: '',
|
||||
} as QQEventVariant))
|
||||
.toBe('入群 [Carol(300)] 加入 [Grp(1)]');
|
||||
});
|
||||
|
||||
it('renders group_poke with both endpoints', () => {
|
||||
expect(formatEvent(id, {
|
||||
kind: 'group_poke',
|
||||
groupId: 1, userUin: 100, targetUin: 200,
|
||||
} as QQEventVariant))
|
||||
.toBe('群戳 [Grp(1)] | [Alice(100)] -> [Bob(200)]');
|
||||
});
|
||||
|
||||
it('renders friend_poke without group context', () => {
|
||||
expect(formatEvent(id, {
|
||||
kind: 'friend_poke',
|
||||
userUin: 500, targetUin: 600,
|
||||
} as QQEventVariant))
|
||||
.toBe('戳一戳 [FriendA(500)] -> [FriendB(600)]');
|
||||
});
|
||||
|
||||
it('degrades to numeric IDs when nothing is cached', () => {
|
||||
const empty = fakeIdentity();
|
||||
expect(formatEvent(empty, {
|
||||
kind: 'group_recall',
|
||||
groupId: 1, authorUin: 100, operatorUin: 200,
|
||||
} as QQEventVariant))
|
||||
.toBe('群撤回 1 | 100 被 200 撤回');
|
||||
});
|
||||
});
|
||||
@@ -254,6 +254,34 @@ describe('HookSession — unload', () => {
|
||||
expect(info.status).toBe('connecting');
|
||||
expect(info.error).toContain('命名管道仍然存在');
|
||||
});
|
||||
|
||||
it('forces a fresh tick before verifying so a stale snapshot does not false-flag a successful unload', async () => {
|
||||
// Reproduces the Windows-WebUI bug: PipeWatcher's cached snapshot is
|
||||
// up to 1500ms stale, so right after a successful native unload the
|
||||
// pre-fix code would read isPipeLive() == true and report failure
|
||||
// even though the DLL is gone. With the fix, tickNow() refreshes
|
||||
// the snapshot first and verification correctly sees the pipe down.
|
||||
const pid = 5555;
|
||||
let pipeLive = true; // initial cached state: pipe is live
|
||||
const tickNow = vi.fn(async () => { pipeLive = false; }); // OS poll says: gone now
|
||||
|
||||
const session = new HookSession(pid, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => new FakeClient() as unknown as QqHookClient,
|
||||
pipeWatcher: { isPipeLive: () => pipeLive, tickNow },
|
||||
});
|
||||
await session.load();
|
||||
pipeLive = true; // ensure the pre-check snapshot says "live"
|
||||
|
||||
const info = await session.unload();
|
||||
|
||||
expect(tickNow).toHaveBeenCalledOnce();
|
||||
expect(info.status).toBe('available');
|
||||
expect(info.error).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — serialization', () => {
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// Tests for the file transport that backs the SnowLuma logger.
|
||||
// Each test gets its own tmp dir and a fresh FileTransport so env / state
|
||||
// from one test never bleeds into another.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { FileTransport } from '../src/utils/log-file-transport';
|
||||
|
||||
let tmpDir: string;
|
||||
const ENV_KEYS = [
|
||||
'SNOWLUMA_LOG_FILE',
|
||||
'SNOWLUMA_LOG_DIR',
|
||||
'SNOWLUMA_LOG_MAX_MB',
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
] as const;
|
||||
const savedEnv: Record<string, string | undefined> = {};
|
||||
|
||||
function setEnv(env: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>): void {
|
||||
for (const [k, v] of Object.entries(env)) {
|
||||
if (v === undefined) delete process.env[k];
|
||||
else process.env[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
function listLogFiles(dir: string): string[] {
|
||||
return fs.readdirSync(dir).filter((f) => f.endsWith('.log')).sort();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const k of ENV_KEYS) savedEnv[k] = process.env[k];
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-log-'));
|
||||
setEnv({
|
||||
SNOWLUMA_LOG_DIR: tmpDir,
|
||||
SNOWLUMA_LOG_FILE: '1',
|
||||
SNOWLUMA_LOG_MAX_MB: '1',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '7',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const k of ENV_KEYS) {
|
||||
if (savedEnv[k] === undefined) delete process.env[k];
|
||||
else process.env[k] = savedEnv[k];
|
||||
}
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('FileTransport', () => {
|
||||
it('creates today\'s file and writes a single line', async () => {
|
||||
const t = new FileTransport();
|
||||
t.write('hello world');
|
||||
await t.close();
|
||||
|
||||
const files = listLogFiles(tmpDir);
|
||||
expect(files).toHaveLength(1);
|
||||
expect(files[0]).toMatch(/^snowluma-\d{4}-\d{2}-\d{2}\.log$/);
|
||||
expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8')).toBe('hello world\n');
|
||||
});
|
||||
|
||||
it('strips ANSI color escapes and ASCII control chars before writing', async () => {
|
||||
const t = new FileTransport();
|
||||
t.write('\x1b[36mINFO\x1b[0m \x07[Bridge] msg');
|
||||
await t.close();
|
||||
|
||||
const [file] = listLogFiles(tmpDir);
|
||||
expect(fs.readFileSync(path.join(tmpDir, file!), 'utf8')).toBe('INFO [Bridge] msg\n');
|
||||
});
|
||||
|
||||
it('rolls into a .1 file when the current file exceeds the size cap', async () => {
|
||||
// 1MB cap from beforeEach. Write ~2 MB to force a single rotation.
|
||||
const t = new FileTransport();
|
||||
const oneKB = 'x'.repeat(1023); // +1 byte newline = 1024
|
||||
for (let i = 0; i < 2048; i++) t.write(oneKB);
|
||||
await t.close();
|
||||
|
||||
const files = listLogFiles(tmpDir);
|
||||
expect(files.length).toBeGreaterThanOrEqual(2);
|
||||
const base = files.find((f) => /snowluma-\d{4}-\d{2}-\d{2}\.log$/.test(f));
|
||||
const split = files.find((f) => /snowluma-\d{4}-\d{2}-\d{2}\.1\.log$/.test(f));
|
||||
expect(base).toBeDefined();
|
||||
expect(split).toBeDefined();
|
||||
});
|
||||
|
||||
it('opens a new file when the day rolls over mid-process', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(2026, 4, 18, 23, 59, 0));
|
||||
const t = new FileTransport();
|
||||
t.write('day-one line');
|
||||
vi.setSystemTime(new Date(2026, 4, 19, 0, 0, 1));
|
||||
t.write('day-two line');
|
||||
await t.close();
|
||||
|
||||
const files = listLogFiles(tmpDir);
|
||||
expect(files).toContain('snowluma-2026-05-18.log');
|
||||
expect(files).toContain('snowluma-2026-05-19.log');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-18.log'), 'utf8'))
|
||||
.toContain('day-one line');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-19.log'), 'utf8'))
|
||||
.toContain('day-two line');
|
||||
});
|
||||
|
||||
it('deletes files older than the retention window on startup', async () => {
|
||||
const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log');
|
||||
fs.writeFileSync(stalePath, 'stale\n');
|
||||
const t = new FileTransport();
|
||||
t.write('fresh');
|
||||
await t.close();
|
||||
|
||||
expect(fs.existsSync(stalePath)).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps files inside the retention window', async () => {
|
||||
const recent = new Date();
|
||||
recent.setDate(recent.getDate() - 2);
|
||||
const recentName = `snowluma-${recent.getFullYear()}-${String(recent.getMonth() + 1).padStart(2, '0')}-${String(recent.getDate()).padStart(2, '0')}.log`;
|
||||
const recentPath = path.join(tmpDir, recentName);
|
||||
fs.writeFileSync(recentPath, 'recent\n');
|
||||
|
||||
const t = new FileTransport();
|
||||
await t.close();
|
||||
|
||||
expect(fs.existsSync(recentPath)).toBe(true);
|
||||
});
|
||||
|
||||
it('SNOWLUMA_LOG_FILE=0 suppresses all file output', async () => {
|
||||
setEnv({ SNOWLUMA_LOG_FILE: '0' });
|
||||
const t = new FileTransport();
|
||||
t.write('should not be written');
|
||||
await t.close();
|
||||
|
||||
expect(t.isDisabled).toBe(true);
|
||||
expect(listLogFiles(tmpDir)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('appends to the existing today file across restarts', async () => {
|
||||
const a = new FileTransport();
|
||||
a.write('before restart');
|
||||
await a.close();
|
||||
|
||||
const b = new FileTransport();
|
||||
b.write('after restart');
|
||||
await b.close();
|
||||
|
||||
const files = listLogFiles(tmpDir);
|
||||
expect(files).toHaveLength(1);
|
||||
expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8'))
|
||||
.toBe('before restart\nafter restart\n');
|
||||
});
|
||||
|
||||
it('exposes the current file path while open', () => {
|
||||
const t = new FileTransport();
|
||||
t.write('x');
|
||||
expect(t.currentPath).not.toBeNull();
|
||||
expect(t.currentPath!).toMatch(/snowluma-\d{4}-\d{2}-\d{2}\.log$/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
// Tests for the core logger API:
|
||||
// - createLogger() output shape (scope rendering)
|
||||
// - .child({ uin }) derivation and the [UIN] slot in the rendered line
|
||||
// - LogEntry.uin propagation to subscribers
|
||||
// - File transport per-UIN fan-out (and the SNOWLUMA_LOG_PER_UIN=0 gate)
|
||||
//
|
||||
// We exercise the file transport via its real fs paths against tmpdirs
|
||||
// so the test catches integration regressions, not just unit shape.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createLogger, getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '../src/utils/logger';
|
||||
import { _resetFileTransportForTesting } from '../src/utils/log-file-transport';
|
||||
|
||||
let tmpDir: string;
|
||||
const ENV_KEYS = [
|
||||
'SNOWLUMA_LOG_FILE',
|
||||
'SNOWLUMA_LOG_PER_UIN',
|
||||
'SNOWLUMA_LOG_DIR',
|
||||
'SNOWLUMA_LOG_MAX_MB',
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
'SNOWLUMA_LOG_LEVEL',
|
||||
'NO_COLOR',
|
||||
] as const;
|
||||
const savedEnv: Record<string, string | undefined> = {};
|
||||
|
||||
function setEnv(env: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>): void {
|
||||
for (const [k, v] of Object.entries(env)) {
|
||||
if (v === undefined) delete process.env[k];
|
||||
else process.env[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
for (const k of ENV_KEYS) savedEnv[k] = process.env[k];
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-logger-'));
|
||||
setEnv({
|
||||
SNOWLUMA_LOG_DIR: tmpDir,
|
||||
SNOWLUMA_LOG_FILE: '1',
|
||||
SNOWLUMA_LOG_PER_UIN: '1',
|
||||
SNOWLUMA_LOG_MAX_MB: '5',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '7',
|
||||
NO_COLOR: '1',
|
||||
});
|
||||
await _resetFileTransportForTesting();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await _resetFileTransportForTesting();
|
||||
for (const k of ENV_KEYS) {
|
||||
if (savedEnv[k] === undefined) delete process.env[k];
|
||||
else process.env[k] = savedEnv[k];
|
||||
}
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('createLogger', () => {
|
||||
it('renders [Scope] with the empty UIN slot when no child binding', async () => {
|
||||
const log = createLogger('Bridge');
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
log.info('hello');
|
||||
unsub();
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
const entry = captured[0]!;
|
||||
expect(entry.scope).toBe('Bridge');
|
||||
expect(entry.uin).toBeUndefined();
|
||||
// Plain-text line shape (NO_COLOR=1):
|
||||
// HH:MM:SS · INFO_ · _<12 blank uin slot>_ · [Bridge] · msg
|
||||
// where · = single separator space inside the template literal.
|
||||
const tail = entry.line.slice(9); // drop "HH:MM:SS "
|
||||
expect(tail).toBe(`INFO ${' '.repeat(12)} [Bridge] hello`);
|
||||
});
|
||||
|
||||
it('child({ uin }) derives a logger that stamps the [UIN] slot', async () => {
|
||||
const log = createLogger('Bridge').child({ uin: 12345 });
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
log.info('via child');
|
||||
unsub();
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
const entry = captured[0]!;
|
||||
expect(entry.uin).toBe(12345);
|
||||
expect(entry.scope).toBe('Bridge');
|
||||
// "[12345]" is 7 chars; padEnd to 12 leaves 5 trailing spaces inside
|
||||
// the slot, then 1 separator space before "[Bridge]".
|
||||
const tail = entry.line.slice(9);
|
||||
expect(tail).toBe(`INFO [12345] [Bridge] via child`);
|
||||
});
|
||||
|
||||
it('child() does not mutate the parent logger', async () => {
|
||||
const parent = createLogger('Bridge');
|
||||
const childA = parent.child({ uin: 100 });
|
||||
const childB = parent.child({ uin: 200 });
|
||||
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
parent.info('parent');
|
||||
childA.info('a');
|
||||
childB.info('b');
|
||||
unsub();
|
||||
|
||||
expect(captured.map((e) => e.uin)).toEqual([undefined, 100, 200]);
|
||||
});
|
||||
|
||||
it('child() can be chained; later uin wins, earlier meta is preserved', async () => {
|
||||
const log = createLogger('Bridge').child({ uin: 100, foo: 'first' }).child({ bar: 'second' });
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
log.info('chained');
|
||||
unsub();
|
||||
|
||||
// uin from first child survives through the second (which only sets bar)
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(captured[0]!.uin).toBe(100);
|
||||
});
|
||||
|
||||
it('writes the per-UIN sub-file in addition to the shared file', async () => {
|
||||
const log = createLogger('Bridge').child({ uin: 67890 });
|
||||
log.info('to file');
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
const sharedFiles = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log'));
|
||||
expect(sharedFiles).toHaveLength(1);
|
||||
const sharedPath = path.join(tmpDir, sharedFiles[0]!);
|
||||
expect(fs.readFileSync(sharedPath, 'utf8')).toContain('[67890]');
|
||||
|
||||
const uinSubDir = path.join(tmpDir, '67890');
|
||||
expect(fs.existsSync(uinSubDir)).toBe(true);
|
||||
const uinFiles = fs.readdirSync(uinSubDir).filter((f) => f.endsWith('.log'));
|
||||
expect(uinFiles).toHaveLength(1);
|
||||
expect(fs.readFileSync(path.join(uinSubDir, uinFiles[0]!), 'utf8'))
|
||||
.toContain('to file');
|
||||
});
|
||||
|
||||
it('lines without uin go only to the shared file', async () => {
|
||||
const log = createLogger('App');
|
||||
log.info('no uin here');
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
const shared = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log'));
|
||||
expect(shared).toHaveLength(1);
|
||||
// No numeric sub-dirs should have been created.
|
||||
const subDirs = fs.readdirSync(tmpDir, { withFileTypes: true })
|
||||
.filter((d) => d.isDirectory())
|
||||
.map((d) => d.name);
|
||||
expect(subDirs).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('SNOWLUMA_LOG_PER_UIN=0 suppresses the per-UIN sub-file but keeps the shared one', async () => {
|
||||
setEnv({ SNOWLUMA_LOG_PER_UIN: '0' });
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
const log = createLogger('Bridge').child({ uin: 9999 });
|
||||
log.info('one line');
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
expect(fs.existsSync(path.join(tmpDir, '9999'))).toBe(false);
|
||||
const shared = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log'));
|
||||
expect(shared).toHaveLength(1);
|
||||
expect(fs.readFileSync(path.join(tmpDir, shared[0]!), 'utf8'))
|
||||
.toContain('one line');
|
||||
});
|
||||
|
||||
it('SNOWLUMA_LOG_FILE=0 also suppresses per-UIN files', async () => {
|
||||
setEnv({ SNOWLUMA_LOG_FILE: '0' });
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
const log = createLogger('Bridge').child({ uin: 1 });
|
||||
log.info('hi');
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
const entries = fs.readdirSync(tmpDir);
|
||||
expect(entries).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setLogLevel / getLogLevel — runtime level toggle', () => {
|
||||
// Each test restores whatever level was active going in so the suite
|
||||
// ordering can't bleed state between specs.
|
||||
let saved: ReturnType<typeof getLogLevel>;
|
||||
beforeEach(() => { saved = getLogLevel(); });
|
||||
afterEach(() => { setLogLevel(saved); });
|
||||
|
||||
it('setLogLevel updates getLogLevel for valid input', () => {
|
||||
expect(setLogLevel('warn')).toBe(true);
|
||||
expect(getLogLevel()).toBe('warn');
|
||||
expect(setLogLevel('debug')).toBe(true);
|
||||
expect(getLogLevel()).toBe('debug');
|
||||
});
|
||||
|
||||
it('setLogLevel rejects unknown values without mutating state', () => {
|
||||
setLogLevel('info');
|
||||
expect(setLogLevel('nonsense')).toBe(false);
|
||||
expect(getLogLevel()).toBe('info');
|
||||
expect(setLogLevel('')).toBe(false);
|
||||
expect(setLogLevel('Verbose')).toBe(false);
|
||||
});
|
||||
|
||||
it('setLogLevel is case-insensitive', () => {
|
||||
expect(setLogLevel('WARN')).toBe(true);
|
||||
expect(getLogLevel()).toBe('warn');
|
||||
});
|
||||
|
||||
it('changes which entries reach the ring buffer / subscribers', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
const log = createLogger('LevelTest');
|
||||
|
||||
setLogLevel('warn');
|
||||
log.debug('hidden-debug');
|
||||
log.info('hidden-info');
|
||||
log.warn('visible-warn');
|
||||
log.error('visible-error');
|
||||
|
||||
unsub();
|
||||
|
||||
const messages = captured
|
||||
.filter((e) => e.scope === 'LevelTest')
|
||||
.map((e) => e.message);
|
||||
expect(messages).toEqual(['visible-warn', 'visible-error']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
// Tests for the new PR5 observability log lines:
|
||||
// - [Highway.Image] entry log on uploadImageMsgInfo
|
||||
// - [Highway] fast-upload hit when OIDB returns no uKey
|
||||
// - [Highway] OIDB-requires-bytes + PUT-done with elapsed ms
|
||||
// - [MsgPush.Unknown] unrecognized PkgType
|
||||
// - [MsgPush.Unknown] wrapper decoder unknown subType
|
||||
//
|
||||
// Highway transport is mocked the same way pipeline.test.ts does it so
|
||||
// runNtv2Upload exercises real OIDB encode/decode but skips actual
|
||||
// network I/O.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { subscribeLogs, type LogEntry } from '../src/utils/logger';
|
||||
|
||||
vi.mock('../src/bridge/highway/highway-client', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
|
||||
uploadHighwayHttp: vi.fn(async () => undefined),
|
||||
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
|
||||
PRIVATE_IMAGE_CMD_ID: 1003,
|
||||
GROUP_IMAGE_CMD_ID: 1004,
|
||||
}));
|
||||
|
||||
import {
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from '../src/bridge/highway/pipeline';
|
||||
import { protoEncode } from '../src/protobuf/decode';
|
||||
import { makeOidbBaseSchema } from '../src/bridge/proto/oidb';
|
||||
import {
|
||||
NTV2UploadRichMediaRespSchema,
|
||||
} from '../src/bridge/proto/highway';
|
||||
import { MsgPushRegistry } from '../src/bridge/msg-push/registry';
|
||||
import type { MsgPushContext } from '../src/bridge/msg-push/context';
|
||||
import { decodeEvent0x2DC } from '../src/bridge/msg-push/decoders/event-0x2dc';
|
||||
|
||||
function encodeOidbResponse(body: unknown): Buffer {
|
||||
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
|
||||
return Buffer.from(protoEncode({
|
||||
command: 0x11C4, subCommand: 100, errorCode: 0,
|
||||
body: body as Record<string, unknown>,
|
||||
errorMsg: '', reserved: 1,
|
||||
}, baseSchema));
|
||||
}
|
||||
|
||||
function fakeBridge(responseData: Buffer, uin = '12345'): any {
|
||||
return {
|
||||
identity: { uin },
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
let captured: LogEntry[];
|
||||
let unsub: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
captured = [];
|
||||
unsub = subscribeLogs((e) => captured.push(e));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
unsub();
|
||||
});
|
||||
|
||||
describe('PR5 — highway pipeline logging', () => {
|
||||
it('logs fast-upload hit when the server returns no uKey', async () => {
|
||||
// upload.uKey absent → no PUT performed.
|
||||
const bridge = fakeBridge(encodeOidbResponse({
|
||||
upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } },
|
||||
}));
|
||||
|
||||
const params = {
|
||||
bridge,
|
||||
isGroup: true,
|
||||
targetIdOrUid: 67890,
|
||||
oidbCmd: 0x11C4,
|
||||
serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100',
|
||||
requestId: 1,
|
||||
businessType: 1,
|
||||
uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }],
|
||||
compatQmsgSceneType: 2,
|
||||
extBizInfo: { pic: {} },
|
||||
uploads: [{
|
||||
source: 'top',
|
||||
cmdId: 1004,
|
||||
bytes: new Uint8Array([1, 2, 3]),
|
||||
md5: new Uint8Array(16),
|
||||
sha1: new Uint8Array(20),
|
||||
}] as MediaSubFileUpload[],
|
||||
label: 'image',
|
||||
};
|
||||
|
||||
await runNtv2Upload(params);
|
||||
|
||||
const hit = captured.find((e) =>
|
||||
e.scope === 'Highway' && e.message.includes('fast-upload hit'));
|
||||
expect(hit).toBeDefined();
|
||||
expect(hit!.uin).toBe(12345);
|
||||
});
|
||||
|
||||
it('logs OIDB-requires-bytes and PUT-done with elapsed ms when uKey is present', async () => {
|
||||
const bridge = fakeBridge(encodeOidbResponse({
|
||||
upload: {
|
||||
uKey: 'server-needs-bytes-please',
|
||||
ipv4s: [{ ipv4: '1.2.3.4', port: 80 }],
|
||||
msgInfo: { msgInfoBody: [], extBizInfo: {} },
|
||||
},
|
||||
}));
|
||||
|
||||
const params = {
|
||||
bridge,
|
||||
isGroup: true,
|
||||
targetIdOrUid: 67890,
|
||||
oidbCmd: 0x11C4,
|
||||
serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100',
|
||||
requestId: 1,
|
||||
businessType: 1,
|
||||
uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }],
|
||||
compatQmsgSceneType: 2,
|
||||
extBizInfo: { pic: {} },
|
||||
uploads: [{
|
||||
source: 'top',
|
||||
cmdId: 1004,
|
||||
bytes: new Uint8Array(1024),
|
||||
md5: new Uint8Array(16),
|
||||
sha1: new Uint8Array(20),
|
||||
}] as MediaSubFileUpload[],
|
||||
label: 'image',
|
||||
};
|
||||
|
||||
await runNtv2Upload(params);
|
||||
|
||||
const requiresBytes = captured.find((e) =>
|
||||
e.scope === 'Highway' && e.message.includes('OIDB requires bytes'));
|
||||
const putDone = captured.find((e) =>
|
||||
e.scope === 'Highway' && /PUT done in \d+ms/.test(e.message));
|
||||
|
||||
expect(requiresBytes).toBeDefined();
|
||||
expect(putDone).toBeDefined();
|
||||
|
||||
const fastHit = captured.find((e) =>
|
||||
e.scope === 'Highway' && e.message.includes('fast-upload hit'));
|
||||
expect(fastHit).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PR5 — MsgPush unknown dispatch logging', () => {
|
||||
it('logs an unknown PkgType under [MsgPush.Unknown]', () => {
|
||||
const reg = new MsgPushRegistry();
|
||||
// No decoders registered → any pkgType is unknown.
|
||||
const ctx = {
|
||||
head: { msgType: 9999, subType: 0, timestamp: 0 },
|
||||
content: new Uint8Array(0),
|
||||
identity: {} as any,
|
||||
fromUin: 0,
|
||||
selfUin: 0,
|
||||
} as unknown as MsgPushContext;
|
||||
|
||||
reg.decode(ctx);
|
||||
|
||||
const entry = captured.find((e) =>
|
||||
e.scope === 'MsgPush.Unknown' && e.message.includes('PkgType=9999'));
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.level).toBe('debug');
|
||||
});
|
||||
|
||||
it('logs an unknown wrapper subType under [MsgPush.Unknown] (Event0x2DC)', () => {
|
||||
const ctx = {
|
||||
head: { msgType: 732, subType: 999, timestamp: 0 },
|
||||
content: new Uint8Array(0),
|
||||
identity: {} as any,
|
||||
fromUin: 0,
|
||||
selfUin: 0,
|
||||
} as unknown as MsgPushContext;
|
||||
|
||||
decodeEvent0x2DC(ctx);
|
||||
|
||||
const entry = captured.find((e) =>
|
||||
e.scope === 'MsgPush.Unknown' && /Event0x2DC unknown subType=999/.test(e.message));
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.level).toBe('debug');
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,18 @@ export default defineConfig({
|
||||
},
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node'
|
||||
environment: 'node',
|
||||
// Suppress the logger's file transport during tests so the suite
|
||||
// doesn't litter cwd with logs/snowluma-*.log files. Tests that
|
||||
// explicitly cover file output set their own SNOWLUMA_LOG_FILE='1'
|
||||
// + SNOWLUMA_LOG_DIR=<tmp>.
|
||||
//
|
||||
// Run at debug level so tests asserting on debug-level log entries
|
||||
// (e.g. action dispatch entry lines) actually see them via the
|
||||
// ring buffer / subscribers, which sit behind the console-level gate.
|
||||
env: {
|
||||
SNOWLUMA_LOG_FILE: '0',
|
||||
SNOWLUMA_LOG_LEVEL: 'debug'
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/runtime",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.4",
|
||||
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.4",
|
||||
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/websocket",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
<link rel="icon" type="image/png" href="/logo.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#0ea5e9" />
|
||||
<!-- WebUI is an admin surface; tell every compliant crawler to skip it. -->
|
||||
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet" />
|
||||
<meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet" />
|
||||
<meta name="bingbot" content="noindex, nofollow, noarchive, nosnippet" />
|
||||
<title>SnowLuma 控制台</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "webui",
|
||||
"private": true,
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.4",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -8,10 +8,10 @@ import { Input } from '@/components/ui/input';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { LogEntry } from '@/types';
|
||||
import type { LogEntry, LogLevel } from '@/types';
|
||||
import { useApi } from '@/lib/api';
|
||||
|
||||
const levelClass: Record<LogEntry['level'], string> = {
|
||||
const levelClass: Record<LogLevel, string> = {
|
||||
debug: 'text-muted-foreground',
|
||||
info: 'text-primary',
|
||||
success: 'text-success',
|
||||
@@ -19,7 +19,7 @@ const levelClass: Record<LogEntry['level'], string> = {
|
||||
error: 'text-destructive',
|
||||
};
|
||||
|
||||
const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
const LEVELS: LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function LogsPage() {
|
||||
const api = useApi();
|
||||
@@ -27,8 +27,10 @@ export function LogsPage() {
|
||||
const [streamStatus, setStreamStatus] = useState('连接中');
|
||||
const [paused, setPaused] = useState(false);
|
||||
const [filter, setFilter] = useState('');
|
||||
const [enabledLevels, setEnabledLevels] = useState<Set<LogEntry['level']>>(new Set(LEVELS));
|
||||
const [enabledLevels, setEnabledLevels] = useState<Set<LogLevel>>(new Set(LEVELS));
|
||||
const [confirmClear, setConfirmClear] = useState(false);
|
||||
const [serverLevel, setServerLevel] = useState<LogLevel | null>(null);
|
||||
const [levelBusy, setLevelBusy] = useState(false);
|
||||
const endRef = useRef<HTMLDivElement | null>(null);
|
||||
const viewportRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
@@ -44,6 +46,25 @@ export function LogsPage() {
|
||||
void loadLogs();
|
||||
}, [loadLogs]);
|
||||
|
||||
useEffect(() => {
|
||||
api.logs.getLevel().then(({ level }) => setServerLevel(level)).catch((err) => {
|
||||
console.error('getLevel', err);
|
||||
});
|
||||
}, [api]);
|
||||
|
||||
const changeServerLevel = useCallback(async (lv: LogLevel) => {
|
||||
if (lv === serverLevel || levelBusy) return;
|
||||
setLevelBusy(true);
|
||||
try {
|
||||
const { level } = await api.logs.setLevel(lv);
|
||||
setServerLevel(level);
|
||||
} catch (err) {
|
||||
console.error('setLevel', err);
|
||||
} finally {
|
||||
setLevelBusy(false);
|
||||
}
|
||||
}, [api, serverLevel, levelBusy]);
|
||||
|
||||
useEffect(() => {
|
||||
return api.logs.stream({
|
||||
onLine: (entry) => {
|
||||
@@ -75,7 +96,7 @@ export function LogsPage() {
|
||||
});
|
||||
}, [logs, filter, enabledLevels]);
|
||||
|
||||
const toggleLevel = (lv: LogEntry['level']) => {
|
||||
const toggleLevel = (lv: LogLevel) => {
|
||||
setEnabledLevels((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(lv)) next.delete(lv);
|
||||
@@ -121,7 +142,8 @@ export function LogsPage() {
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-1 px-5 pb-3">
|
||||
<div className="flex flex-wrap items-center gap-1 px-5 pb-2">
|
||||
<span className="mr-2 text-[11px] text-muted-foreground/80">视图过滤</span>
|
||||
{LEVELS.map((lv) => {
|
||||
const active = enabledLevels.has(lv);
|
||||
return (
|
||||
@@ -142,6 +164,31 @@ export function LogsPage() {
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-1 px-5 pb-3">
|
||||
<span className="mr-2 text-[11px] text-muted-foreground/80" title="文件落盘始终为 debug,此处仅控制控制台 / 实时流的级别">
|
||||
服务端级别
|
||||
</span>
|
||||
{LEVELS.map((lv) => {
|
||||
const active = serverLevel === lv;
|
||||
return (
|
||||
<button
|
||||
key={lv}
|
||||
type="button"
|
||||
onClick={() => void changeServerLevel(lv)}
|
||||
disabled={levelBusy || serverLevel === null}
|
||||
className={cn(
|
||||
'rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50',
|
||||
active
|
||||
? cn('border-primary', levelClass[lv], 'bg-primary/10')
|
||||
: 'border-border text-muted-foreground/70 hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
{lv.toUpperCase()}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<CardContent className="flex min-h-0 flex-1 flex-col pt-0">
|
||||
<div className="flex min-h-0 flex-1 flex-col rounded-lg border bg-muted/30">
|
||||
<ScrollArea
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { HookProcessInfo, LogEntry, QQInfo, SystemInfo } from '@/types';
|
||||
import type { HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types';
|
||||
import type { PasswordRule } from '@/components/pages/change-password-page';
|
||||
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
||||
import {
|
||||
@@ -84,6 +84,9 @@ class HttpApiClient implements ApiClient {
|
||||
return data.list ?? [];
|
||||
},
|
||||
stream: (options) => this.openLogStream(options),
|
||||
getLevel: () => this.getJson<{ level: LogLevel; levels: LogLevel[] }>(`/api/logs/level`),
|
||||
setLevel: (level) =>
|
||||
this.postJson<{ level: LogLevel; levels: LogLevel[] }>(`/api/logs/level`, { level }),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
HookProcessInfo,
|
||||
LogEntry,
|
||||
LogLevel,
|
||||
OneBotConfig,
|
||||
QQInfo,
|
||||
SystemInfo,
|
||||
@@ -69,6 +70,10 @@ export interface ApiClient {
|
||||
list(limit?: number): Promise<LogEntry[]>;
|
||||
/** Subscribe to the SSE log stream. Returns a disposer. */
|
||||
stream(options: LogsStreamOptions): () => void;
|
||||
/** Current console / subscriber level. File output is always debug. */
|
||||
getLevel(): Promise<{ level: LogLevel; levels: LogLevel[] }>;
|
||||
/** Change the console / subscriber level at runtime. No restart needed. */
|
||||
setLevel(level: LogLevel): Promise<{ level: LogLevel; levels: LogLevel[] }>;
|
||||
};
|
||||
|
||||
/** Escape hatch for endpoints not yet wrapped above. */
|
||||
|
||||
@@ -101,10 +101,14 @@ export interface SystemInfo {
|
||||
};
|
||||
}
|
||||
|
||||
export type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
time: string;
|
||||
level: 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
level: LogLevel;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
scope: string;
|
||||
message: string;
|
||||
line: string;
|
||||
|
||||
Reference in new issue
Block a user