Remove performance CLI and demo, fix typos, update proto

Deleted the performance CLI and demo files. Fixed a typo in getFullQQVesion to getFullQQVersion across multiple files. Changed the 'time' field type from UINT32 to UINT64 in Oidb.0x9067_202 proto. Commented out performanceMonitorPlugin in vite.config.ts. Removed an unimplemented log statement in NodeIKernelBuddyListener.
This commit is contained in:
手瓜一十雪 2025-08-06 19:57:36 +08:00
parent 69a19b0e32
commit 0d251a9343
6 changed files with 20 additions and 305 deletions

View File

@ -1,197 +0,0 @@
#!/usr/bin/env node
/**
*
*/
import { performanceMonitor } from '../common/performance-monitor';
function printColoredText(text: string, color: string): void {
const colors: Record<string, string> = {
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m',
reset: '\x1b[0m',
bright: '\x1b[1m'
};
console.log(`${colors[color] || colors['white']}${text}${colors['reset']}`);
}
function printHeader(title: string): void {
const line = '='.repeat(50);
printColoredText(line, 'cyan');
printColoredText(title.toUpperCase().padStart((50 + title.length) / 2), 'bright');
printColoredText(line, 'cyan');
}
function printSubHeader(title: string): void {
const line = '-'.repeat(30);
printColoredText(line, 'yellow');
printColoredText(title, 'yellow');
printColoredText(line, 'yellow');
}
function formatTime(ms: number): string {
if (ms < 1) {
return `${(ms * 1000).toFixed(2)}μs`;
} else if (ms < 1000) {
return `${ms.toFixed(2)}ms`;
} else {
return `${(ms / 1000).toFixed(2)}s`;
}
}
function printStatsTable(stats: any[], title: string): void {
printSubHeader(`${title} (Top 10)`);
if (stats.length === 0) {
printColoredText(' 暂无数据', 'yellow');
return;
}
console.log();
console.log(' 排名 | 函数名称 | 调用次数 | 总耗时 | 平均耗时 | 最小耗时 | 最大耗时');
console.log(' ' + '-'.repeat(100));
stats.slice(0, 10).forEach((stat, index) => {
const rank = (index + 1).toString().padEnd(4);
const name = stat.name.length > 30 ? stat.name.substring(0, 27) + '...' : stat.name.padEnd(30);
const callCount = stat.callCount.toString().padEnd(8);
const totalTime = formatTime(stat.totalTime).padEnd(10);
const avgTime = formatTime(stat.averageTime).padEnd(10);
const minTime = formatTime(stat.minTime).padEnd(10);
const maxTime = formatTime(stat.maxTime).padEnd(10);
const color = index < 3 ? 'green' : 'white';
printColoredText(
` ${rank} | ${name} | ${callCount} | ${totalTime} | ${avgTime} | ${minTime} | ${maxTime}`,
color
);
});
console.log();
}
function printSummary(): void {
const stats = performanceMonitor.getStats();
const totalFunctions = stats.length;
const totalCalls = stats.reduce((sum, stat) => sum + stat.callCount, 0);
const totalTime = stats.reduce((sum, stat) => sum + stat.totalTime, 0);
const avgTimePerCall = totalCalls > 0 ? totalTime / totalCalls : 0;
printSubHeader('📊 统计摘要');
console.log();
printColoredText(` 监控函数数量: ${totalFunctions}`, 'cyan');
printColoredText(` 总调用次数: ${totalCalls}`, 'cyan');
printColoredText(` 总耗时: ${formatTime(totalTime)}`, 'cyan');
printColoredText(` 平均每次调用耗时: ${formatTime(avgTimePerCall)}`, 'cyan');
console.log();
}
function main(): void {
const args = process.argv.slice(2);
const command = args[0] || 'report';
switch (command) {
case 'report':
case 'r':
printHeader('🚀 NapCat 性能监控报告');
console.log();
printSummary();
const totalTimeStats = performanceMonitor.getTopByTotalTime(10);
const callCountStats = performanceMonitor.getTopByCallCount(10);
const avgTimeStats = performanceMonitor.getTopByAverageTime(10);
printStatsTable(totalTimeStats, '🔥 总耗时排行榜');
printStatsTable(callCountStats, '📈 调用次数排行榜');
printStatsTable(avgTimeStats, '⏱️ 平均耗时排行榜');
break;
case 'top':
case 't':
const type = args[1] || 'total';
const limit = parseInt(args[2] || '10') || 10;
switch (type) {
case 'total':
case 'time':
printHeader('🔥 总耗时排行榜');
printStatsTable(performanceMonitor.getTopByTotalTime(limit), '');
break;
case 'count':
case 'calls':
printHeader('📈 调用次数排行榜');
printStatsTable(performanceMonitor.getTopByCallCount(limit), '');
break;
case 'avg':
case 'average':
printHeader('⏱️ 平均耗时排行榜');
printStatsTable(performanceMonitor.getTopByAverageTime(limit), '');
break;
default:
printColoredText('未知的排行榜类型。可用类型: total, count, avg', 'red');
}
break;
case 'clear':
case 'c':
performanceMonitor.clear();
printColoredText('✅ 性能统计数据已清空', 'green');
break;
case 'json':
case 'j':
const jsonStats = performanceMonitor.toJSON();
console.log(JSON.stringify(jsonStats, null, 2));
break;
case 'help':
case 'h':
case '--help':
printHelp();
break;
default:
printColoredText(`未知命令: ${command}`, 'red');
printHelp();
process.exit(1);
}
}
function printHelp(): void {
printHeader('📖 帮助信息');
console.log();
printColoredText('用法: napcat-perf <command> [options]', 'cyan');
console.log();
printColoredText('命令:', 'yellow');
console.log(' report, r 显示完整性能报告 (默认)');
console.log(' top <type> [limit] 显示指定类型的排行榜');
console.log(' - total, time 按总耗时排序');
console.log(' - count, calls 按调用次数排序');
console.log(' - avg, average 按平均耗时排序');
console.log(' clear, c 清空所有统计数据');
console.log(' json, j 以JSON格式输出数据');
console.log(' help, h 显示此帮助信息');
console.log();
printColoredText('示例:', 'yellow');
console.log(' napcat-perf report');
console.log(' napcat-perf top total 20');
console.log(' napcat-perf top count');
console.log(' napcat-perf clear');
console.log();
}
// 如果直接运行此文件
if (require.main === module) {
main();
}
export { main as runPerfMonitor };

View File

@ -1,87 +0,0 @@
/**
*
*/
import { performanceMonitor } from './performance-monitor';
// 模拟一些函数调用来测试性能监控
class ExampleService {
async fetchData(id: string): Promise<string> {
// 模拟网络请求延迟
await new Promise(resolve => setTimeout(resolve, Math.random() * 100));
return `Data for ${id}`;
}
processData(data: string): string {
// 模拟CPU密集型操作
let result = data;
for (let i = 0; i < 1000; i++) {
result = result.split('').reverse().join('');
}
return result;
}
async saveData(data: string): Promise<void> {
// 模拟保存操作
console.log(`保存数据: ${data.length} 字符`);
await new Promise(resolve => setTimeout(resolve, Math.random() * 50));
}
}
// 工具函数
function calculateHash(input: string): string {
let hash = 0;
for (let i = 0; i < input.length; i++) {
const char = input.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // 转换为32位整数
}
return hash.toString(16);
}
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
// 演示函数
export async function runPerformanceDemo(): Promise<void> {
console.log('🚀 开始性能监控演示...\n');
const service = new ExampleService();
// 执行一些操作来生成性能数据
for (let i = 0; i < 10; i++) {
try {
// 获取数据
const data = await service.fetchData(`item-${i}`);
// 处理数据
const processed = service.processData(data);
// 计算哈希
const hash = calculateHash(processed);
// 保存数据
await service.saveData(`${processed}-${hash}`);
console.log(`✅ 处理完成第 ${i + 1}`);
// 随机延迟
await delay(Math.random() * 20);
} catch (error) {
console.error(`❌ 处理第 ${i + 1} 项时出错:`, error);
}
}
// 等待一小段时间确保所有异步操作完成
await delay(100);
console.log('\n📊 性能监控演示完成!');
console.log('性能统计数据:');
// 显示性能统计
performanceMonitor.printReport();
}
// 如果直接运行此文件
if (require.main === module) {
runPerformanceDemo().catch(console.error);
}

View File

@ -40,7 +40,6 @@ export class NodeIKernelBuddyListener {
}
onDelBatchBuddyInfos(_arg: unknown): any {
console.log('onDelBatchBuddyInfos not implemented', ...arguments);
}
onDoubtBuddyReqChange(_arg:

View File

@ -37,7 +37,7 @@ export async function NCoreInitFramework(
const pathWrapper = new NapCatPathWrapper();
const logger = new LogWrapper(pathWrapper.logsPath);
const basicInfoWrapper = new QQBasicInfoWrapper({ logger });
const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVesion());
const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVersion());
if (!process.env['NAPCAT_DISABLE_FFMPEG_DOWNLOAD']) {
downloadFFmpegIfNotExists(logger).then(({ path, reset }) => {
if (reset && path) {

View File

@ -80,7 +80,7 @@ async function initializeEngine(
base_path_prefix: '',
platform_type: systemPlatform,
app_type: 4,
app_version: basicInfoWrapper.getFullQQVesion(),
app_version: basicInfoWrapper.getFullQQVersion(),
os_version: systemVersion,
use_xlog: false,
qua: basicInfoWrapper.QQVersionQua ?? '',
@ -105,7 +105,7 @@ async function initializeLoginService(
appid: basicInfoWrapper.QQVersionAppid ?? '',
platVer: systemVersion,
commonPath: dataPathGlobal,
clientVer: basicInfoWrapper.getFullQQVesion(),
clientVer: basicInfoWrapper.getFullQQVersion(),
hostName: hostname,
});
}
@ -324,7 +324,7 @@ export async function NCoreInitShell() {
});
}
const basicInfoWrapper = new QQBasicInfoWrapper({ logger });
const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVesion());
const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVersion());
const o3Service = wrapper.NodeIO3MiscService.get();
o3Service.addO3MiscListener(new NodeIO3MiscListener());
@ -363,7 +363,7 @@ export async function NCoreInitShell() {
const sessionConfig = await genSessionConfig(
guid,
basicInfoWrapper.QQVersionAppid,
basicInfoWrapper.getFullQQVesion(),
basicInfoWrapper.getFullQQVersion(),
selfInfo.uin,
selfInfo.uid,
dataPath,

View File

@ -22,11 +22,11 @@ if (process.env.NAPCAT_BUILDSYS == 'linux') {
}
const UniversalBaseConfigPlugin: PluginOption[] = [
performanceMonitorPlugin({
enabled: process.env.NODE_ENV !== 'production',
exclude: [/node_modules/, /\.min\./, /performance-monitor/],
include: [/\.ts$/, /\.js$/]
}),
// performanceMonitorPlugin({
// enabled: process.env.NODE_ENV !== 'production',
// exclude: [/node_modules/, /\.min\./, /performance-monitor/],
// include: [/\.ts$/, /\.js$/]
// }),
cp({
targets: [
{ src: './manifest.json', dest: 'dist' },
@ -50,11 +50,11 @@ const UniversalBaseConfigPlugin: PluginOption[] = [
];
const FrameworkBaseConfigPlugin: PluginOption[] = [
performanceMonitorPlugin({
enabled: process.env.NODE_ENV !== 'production',
exclude: [/node_modules/, /\.min\./, /performance-monitor/],
include: [/\.ts$/, /\.js$/]
}),
// performanceMonitorPlugin({
// enabled: process.env.NODE_ENV !== 'production',
// exclude: [/node_modules/, /\.min\./, /performance-monitor/],
// include: [/\.ts$/, /\.js$/]
// }),
cp({
targets: [
{ src: './manifest.json', dest: 'dist' },
@ -75,11 +75,11 @@ const FrameworkBaseConfigPlugin: PluginOption[] = [
];
const ShellBaseConfigPlugin: PluginOption[] = [
performanceMonitorPlugin({
enabled: process.env.NODE_ENV !== 'production',
exclude: [/node_modules/, /\.min\./, /performance-monitor/],
include: [/\.ts$/, /\.js$/]
}),
// performanceMonitorPlugin({
// enabled: process.env.NODE_ENV !== 'production',
// exclude: [/node_modules/, /\.min\./, /performance-monitor/],
// include: [/\.ts$/, /\.js$/]
// }),
cp({
targets: [
{ src: './src/native/packet', dest: 'dist/moehoo', flatten: false },